File: dimension.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 (4633 lines) | stat: -rw-r--r-- 162,933 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
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
#
# 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
#
#
# generic dimension classes
#

import math
import sys
import types
import warnings

from PythonCAD.Generic import text
from PythonCAD.Generic import point
from PythonCAD.Generic import circle
from PythonCAD.Generic import arc
from PythonCAD.Generic import color
from PythonCAD.Generic import units
from PythonCAD.Generic import util
from PythonCAD.Generic import tolerance
from PythonCAD.Generic import baseobject
from PythonCAD.Generic import entity

_dtr = math.pi/180.0
_rtd = 180.0/math.pi

class DimString(text.TextBlock):
    """A class for the visual presentation of the dimensional value.

The DimString class is used to present the numerical display for
the dimension. A DimString object is derived from the text.TextBlock
class, so it shares all of that classes methods and attributes.

The DimString class has the following additional properties:

prefix: A prefix prepended to the dimension text
suffix: A suffix appended to the dimension text
units: The units the dimension text will display
precision: The displayed dimension precision
print_zero: Displayed dimensions will have a leading 0 if needed
print_decimal: Displayed dimensions will have a trailing decimal point

The DimString class has the following additional methods:

{get/set}Prefix(): Get/Set the text preceding the dimension value.
{get/set}Suffix(): Get/Set the text following the dimension value.
{get/set}Units(): Define what units the dimension will be in.
{get/set}Precision(): Get/Set how many fractional digits are displayed.
{get/set}PrintZero(): Get/Set whether or not a dimension less than one
                      unit long should have a leading 0 printed
{get/set}PrintDecimal(): Get/Set whether or not a dimension with 0
                         fractional digits prints out the decimal point.
{get/set}Dimension(): Get/Set the dimension using the DimString
    """

    __defcolor = color.Color(0xffffff)
    __defstyle = text.TextStyle(u'Default Dimension Text Style',
                                color=__defcolor,
                                align=text.TextStyle.ALIGN_CENTER)

    messages = {
        'prefix_changed' : True,
        'suffix_changed' : True,
        'units_changed' : True,
        'precision_changed' : True,
        'print_zero_changed' : True,
        'print_decimal_changed' : True,
        'dimension_changed' : True,
        }

    def __init__(self, x, y, **kw):
        """Initialize a DimString object

ds = DimString(x, y, **kw)

Arguments 'x' and 'y' should be floats. Various keyword arguments can
also be used:

text: Displayed text
textstyle: The default textstyle
family: Font family
style: Font style
weight: Font weight
color: Text color
size: Text size
angle: Text angle
align: Text alignment
prefix: Default prefix
suffix: Default suffix
units: Displayed units
precision: Displayed precision of units
print_zero: Boolean to print a leading '0'
print_decimal: Boolean to print a leading '.'

By default, a DimString object has the following values ...

prefix: Empty string
suffix: Empty string
unit: Millimeters
precision: 3 decimal places
print zero: True
print decimal: True
        """
        _text = u''
        if 'text' in kw:
            _text = kw['text']
        _tstyle = DimString.__defstyle
        if 'textstyle' in kw:
            _tstyle = kw['textstyle']
            del kw['textstyle']
        _prefix = u''
        if 'prefix' in kw:
            _prefix = kw['prefix']
            if not isinstance(_prefix, types.StringTypes):
                raise TypeError, "Invalid prefix type: " + `type(_prefix)`
        _suffix = u''
        if 'suffix' in kw:
            _suffix = kw['suffix']
            if not isinstance(_suffix, types.StringTypes):
                raise TypeError, "Invalid suffix type: " + `type(_suffix)`
        _unit = units.MILLIMETERS
        if 'units' in kw:
            _unit = kw['units']
        _prec = 3
        if 'precision' in kw:
            _prec = kw['precision']
            if not isinstance(_prec, int):
                raise TypeError, "Invalid precision type: " + `type(_prec)`
            if _prec < 0 or _prec > 15:
                raise ValueError, "Invalid precision: %d" % _prec
        _pz = True
        if 'print_zero' in kw:
            _pz = kw['print_zero']
            util.test_boolean(_pz)
        _pd = True
        if 'print_decimal' in kw:
            _pd = kw['print_decimal']
            util.test_boolean(_pd)
        super(DimString, self).__init__(x, y, _text, textstyle=_tstyle, **kw)
        self.__prefix = _prefix
        self.__suffix = _suffix
        self.__unit = units.Unit(_unit)
        self.__precision = _prec
        self.__print_zero = _pz
        self.__print_decimal = _pd
        self.__dim = None

    def finish(self):
        """Finalization for  DimString instances.

finish()
        """
        if self.__dim is not None:
            self.__dim = None
        super(DimString, self).finish()

    def getValues(self):
        """Return values comprising the DimString.

getValues()

This method extends the TextBlock::getValues() method.
        """
        _data = super(DimString, self).getValues()
        _data.setValue('type', 'dimstring')
        if self.getTextStyle() is DimString.__defstyle:
            _data.setValue('textstyle', None)
        _data.setValue('prefix', self.__prefix)
        _data.setValue('suffix', self.__suffix)
        _data.setValue('units', self.__unit.getStringUnit())
        _data.setValue('precision', self.__precision)
        _data.setValue('print_zero', self.__print_zero)
        _data.setValue('print_decimal', self.__print_decimal)
        return _data

    def setLocation(self, x, y):
        """Set the location of the DimString.

setLocation(x, y)

Arguments 'x' and 'y' should be floats. This method extends
the TextBlock::setLocation() method.
        """
        #
        # the DimString location is defined in relation to
        # the position defined by the Dimension::setLocation()
        # call, so don't bother sending out 'moved' or 'modified'
        # messages
        #
        self.mute()
        super(DimString, self).setLocation(x, y)
        self.unmute()

    def getPrefix(self):
        """Return the prefix for the DimString object.

getPrefix()
        """
        return self.__prefix

    def setPrefix(self, prefix=None):
        """Set the prefix for the DimString object.

setPrefix([prefix])

Invoking this method without arguments sets the prefix
to an empty string, or to the DimStyle value in the associated
Dimension if one is set for the DimString. When an argument
is passed, the argument should be a Unicode string.
        """
        if self.isLocked():
            raise RuntimeError, "Setting prefix not allowed - object locked."
        _p = prefix
        if _p is None:
            _p = u''
            if self.__dim is not None:
                _p = self.__dim.getStyleValue(self, 'prefix')
        if not isinstance(_p, unicode):
            _p = unicode(prefix)
        _op = self.__prefix
        if _op != _p:
            self.__prefix = _p
            self.setBounds()
            self.sendMessage('prefix_changed', _op)
            self.modified()

    prefix = property(getPrefix, setPrefix, None, 'Dimension string prefix')

    def getSuffix(self):
        """Return the suffix for the DimString object.

getSuffix()
        """
        return self.__suffix

    def setSuffix(self, suffix=None):
        """Set the suffix for the DimString object.

setSuffix([suffix])

Invoking this method without arguments sets the suffix
to an empty string, or to the DimStyle value in the associated
Dimension if one is set for the DimString.. When an argument
is passed, the argument should be a Unicode string.
        """
        if self.isLocked():
            raise RuntimeError, "Setting suffix not allowed - object locked."
        _s = suffix
        if _s is None:
            _s = u''
            if self.__dim is not None:
                _s = self.__dim.getStyleValue(self, 'suffix')
        if not isinstance(_s, unicode):
            _s = unicode(suffix)
        _os = self.__suffix
        if _os != _s:
            self.__suffix = _s
            self.setBounds()
            self.sendMessage('suffix_changed', _os)
            self.modified()

    suffix = property(getSuffix, setSuffix, None, 'Dimension string suffix')

    def getPrecision(self):
        """Return the number of decimal points used for the DimString.

getPrecision()
        """
        return self.__precision

    def setPrecision(self, precision=None):
        """Set the number of decimal points used for the DimString.

setPrecision([p])

The valid range of p is 0 <= p <= 15. Invoking this method without
arguments sets the precision to 3, or to the DimStyle value in the
associated Dimension if one is set for the DimString..
        """
        if self.isLocked():
            raise RuntimeError, "Setting precision not allowed - object locked."
        _p = precision
        if _p is None:
            _p = 3
            if self.__dim is not None:
                _p = self.__dim.getStyleValue(self, 'precision')
        if not isinstance(_p, int):
            raise TypeError, "Invalid precision type: " + `type(_p)`
        if _p < 0 or _p > 15:
            raise ValueError, "Invalid precision: %d" % _p
        _op = self.__precision
        if _op != _p:
            self.__precision = _p
            self.setBounds()
            self.sendMessage('precision_changed', _op)
            self.modified()

    precision = property(getPrecision, setPrecision, None,
                         'Dimension precision')

    def getUnits(self):
        """Return the current units used in the DimString().

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

    def setUnits(self, unit=None):
        """The the units for the DimString.

setUnits([unit])

The value units are given in the units module. Invoking this
method without arguments sets the units to millimeters, or
to the DimStyle value of the associated Dimension if one
is set for the DimString.
        """
        _u = unit
        if _u is None:
            _u = units.MILLIMETERS
            if self.__dim is not None:
                _u = self.__dim.getStyleValue(self, 'units')
        _ou = self.__unit.getUnit()
        self.__unit.setUnit(_u)
        if _ou != _u:
            self.setBounds()
            self.sendMessage('units_changed', _ou)
            self.modified()

    units = property(getUnits, setUnits, None, 'Dimensional units.')

    def getPrintZero(self):
        """Return whether or not a leading 0 is printed for the DimString.

getPrintZero()
        """
        return self.__print_zero

    def setPrintZero(self, print_zero=None):
        """Set whether or not a leading 0 is printed for the DimString.

setPrintZero([pz])

Invoking this method without arguments sets the value to True,
or to the DimStyle value of the associated Dimension if one is
set for the DimString. If called with an argument, the argument
should be either True or False.
        """
        _pz = print_zero
        if _pz is None:
            _pz = True
            if self.__dim is not None:
                _pz = self.__dim.getStyleValue(self, 'print_zero')
        util.test_boolean(_pz)
        _flag = self.__print_zero
        if _flag is not _pz:
            self.__print_zero = _pz
            self.setBounds()
            self.sendMessage('print_zero_changed', _flag)
            self.modified()

    print_zero = property(getPrintZero, setPrintZero, None,
                          'Print a leading 0 for decimal dimensions')

    def getPrintDecimal(self):
        """Return whether or not the DimString will print a trailing decimal.

getPrintDecimal()
        """
        return self.__print_decimal

    def setPrintDecimal(self, print_decimal=None):
        """Set whether or not the DimString will print a trailing decimal.

setPrintDecimal([pd])

Invoking this method without arguments sets the value to True, or
to the DimStyle value of the associated Dimension if one is set
for the DimString. If called with an argument, the argument should
be either True or False.
        """
        _pd = print_decimal
        if _pd is None:
            _pd = True
            if self.__dim is not None:
                _pd = self.__dim.getStyleValue(self, 'print_decimal')
        util.test_boolean(_pd)
        _flag = self.__print_decimal
        if _flag is not _pd:
            self.__print_decimal = _pd
            self.setBounds()
            self.sendMessage('print_decimal_changed', _flag)
            self.modified()

    print_decimal = property(getPrintDecimal, setPrintDecimal, None,
                             'Print a decimal point after the dimension value')

    def getDimension(self):
        """Return the dimension using the Dimstring.

getDimension()

This method can return None if there is not Dimension association set
for the DimString.
        """
        return self.__dim

    def setDimension(self, dim, adjust):
        """Set the dimension using this DimString.

setDimension(dim, adjust)

Argument 'dim' must be a Dimension or None, and argument
'adjust' must be a Boolean. Argument 'adjust' is only used
if a Dimension is passed for the first argument.
        """
        _dim = dim
        if _dim is not None and not isinstance(_dim, Dimension):
            raise TypeError, "Invalid dimension: " + `type(_dim)`
        util.test_boolean(adjust)
        _d = self.__dim
        if _d is not _dim:
            self.__dim = _dim
            if _dim is not None and adjust:
                self.setPrefix()
                self.setSuffix()
                self.setPrecision()
                self.setUnits()
                self.setPrintZero()
                self.setPrintDecimal()
                self.setFamily()
                self.setStyle()
                self.setWeight()
                self.setColor()
                self.setSize()
                self.setAngle()
                self.setAlignment()
            self.sendMessage('dimension_changed', _d)
            self.modified()
        if self.__dim is not None:
            self.setParent(self.__dim.getParent())

#
# extend the TextBlock set methods to use the values
# found in a DimStyle if one is available
#

    def setFamily(self, family=None):
        """Set the font family for the DimString.

setFamily([family])

Calling this method without an argument will set the
family to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _family = family
        if _family is None and self.__dim is not None:
            _family = self.__dim.getStyleValue(self, 'font_family')
        super(DimString, self).setFamily(_family)

    def setStyle(self, style=None):
        """Set the font style for the DimString.

setStyle([style])

Calling this method without an argument will set the
font style to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _style = style
        if _style is None and self.__dim is not None:
            _style = self.__dim.getStyleValue(self, 'font_style')
        super(DimString, self).setStyle(_style)

    def setWeight(self, weight=None):
        """Set the font weight for the DimString.

setWeight([weight])

Calling this method without an argument will set the
font weight to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _weight = weight
        if _weight is None and self.__dim is not None:
            _weight = self.__dim.getStyleValue(self, 'font_weight')
        super(DimString, self).setWeight(_weight)

    def setColor(self, color=None):
        """Set the font color for the DimString.

setColor([color])

Calling this method without an argument will set the
font color to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _color = color
        if _color is None and self.__dim is not None:
            _color = self.__dim.getStyleValue(self, 'color')
        super(DimString, self).setColor(_color)

    def setSize(self, size=None):
        """Set the text size for the DimString.

setSize([size])

Calling this method without an argument will set the
text size to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _size = size
        if _size is None and self.__dim is not None:
            _size = self.__dim.getStyleValue(self, 'size')
        super(DimString, self).setSize(_size)

    def setAngle(self, angle=None):
        """Set the text angle for the DimString.

setAngle([angle])

Calling this method without an argument will set the
text angle to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _angle = angle
        if _angle is None and self.__dim is not None:
            _angle = self.__dim.getStyleValue(self, 'angle')
        super(DimString, self).setAngle(_angle)

    def setAlignment(self, align=None):
        """Set the text alignment for the DimString.

setAlignment([align])

Calling this method without an argument will set the
text alignment to that given in the DimStyle of the associated
Dimension if one is set for this DimString.
        """
        _align = align
        if _align is None and self.__dim is not None:
            _align = self.__dim.getStyleValue(self, 'alignment')
        super(DimString, self).setAlignment(_align)

    def setText(self, text):
        """Set the text in the DimString.

This method overrides the setText method in the TextBlock.
        """
        pass

    def formatDimension(self, dist):
        """Return a formatted numerical value for a dimension.

formatDimension(dist)

The argument 'dist' should be a float value representing the
distance in millimeters. The returned value will have the
prefix prepended and suffix appended to the numerical value
that has been formatted with the precision.
        """
        _d = abs(util.get_float(dist))
        _fmtstr = u"%%#.%df" % self.__precision
        _dstr = _fmtstr % self.__unit.fromMillimeters(_d)
        if _d < 1.0 and self.__print_zero is False:
            _dstr = _dstr[1:]
        if _dstr.endswith('.') and self.__print_decimal is False:
            _dstr = _dstr[:-1]
        _text = self.__prefix + _dstr + self.__suffix
        #
        # don't send out 'text_changed' or 'modified' messages
        #
        self.mute()
        try:
            super(DimString, self).setText(_text)
        finally:
            self.unmute()
        return _text

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

class DimBar(entity.Entity):
    """The class for the dimension bar.

A dimension bar leads from the point the dimension references
out to, and possibly beyond, the point where the dimension
text bar the DimBar to another DimBar. Linear,
horizontal, vertical, and angular dimension will have two
dimension bars; radial dimensions have none.

The DimBar class has the following methods:

getEndpoints(): Get the x/y position of the DimBar start and end
{get/set}FirstEndpoint(): Get/Set the starting x/y position of the DimBar.
{get/set}SecondEndpoint(): Get/Set the ending x/y position of the DimBar.
getAngle(): Get the angle at which the DimBar slopes
getSinCosValues(): Get trig values used for transformation calculations.
    """

    messages = {
        'attribute_changed' : True,
        }
    def __init__(self, x1=0.0, y1=0.0, x2=0.0, y2=0.0, **kw):
        """Initialize a DimBar.

db = DimBar([x1, y1, x2, y2])

By default all the arguments are 0.0. Any arguments passed to this
method should be float values.
        """
        _x1 = util.get_float(x1)
        _y1 = util.get_float(y1)
        _x2 = util.get_float(x2)
        _y2 = util.get_float(y2)
        super(DimBar, self).__init__(**kw)
        self.__ex1 = _x1
        self.__ey1 = _y1
        self.__ex2 = _x2
        self.__ey2 = _y2

    def getEndpoints(self):
        """Return the coordinates of the DimBar endpoints.

getEndpoints()

This method returns two tuples, each containing two float values.
The first tuple gives the x/y coordinates of the DimBar start,
the second gives the coordinates of the DimBar end.
        """
        _ep1 = (self.__ex1, self.__ey1)
        _ep2 = (self.__ex2, self.__ey2)
        return _ep1, _ep2

    def setFirstEndpoint(self, x, y):
        """Set the starting coordinates for the DimBar

setFirstEndpoint(x, y)

Arguments x and y should be float values.
        """
        if self.isLocked():
            raise RuntimeError, "Setting endpoint not allowed - object locked."
        _x = util.get_float(x)
        _y = util.get_float(y)
        _sx = self.__ex1
        _sy = self.__ey1
        if abs(_sx - _x) > 1e-10 or abs(_sy - _y) > 1e-10:
            self.__ex1 = _x
            self.__ey1 = _y
            self.sendMessage('attribute_changed', 'endpoint', _sx, _sy,
                             self.__ex2, self.__ey2)
            self.modified()

    def getFirstEndpoint(self):
        """Return the starting coordinates of the DimBar.

getFirstEndpoint()

This method returns a tuple giving the x/y coordinates.
        """
        return self.__ex1, self.__ey1

    def setSecondEndpoint(self, x, y):
        """Set the ending coordinates for the DimBar

setSecondEndpoint(x, y)

Arguments x and y should be float values.
        """
        if self.isLocked():
            raise RuntimeError, "Setting endpoint not allowed - object locked."
        _x = util.get_float(x)
        _y = util.get_float(y)
        _sx = self.__ex2
        _sy = self.__ey2
        if abs(_sx - _x) > 1e-10 or abs(_sy - _y) > 1e-10:
            self.__ex2 = _x
            self.__ey2 = _y
            self.sendMessage('attribute_changed', 'endpoint',
                             self.__ex1, self.__ey1, _sx, _sy)
            self.modified()

    def getSecondEndpoint(self):
        """Return the ending coordinates of the DimBar.

getSecondEndpoint()

This method returns a tuple giving the x/y coordinates.
        """
        return self.__ex2, self.__ey2

    def getAngle(self):
        """Return the angle at which the DimBar lies.

getAngle()

This method returns a float value giving the angle of inclination
of the DimBar.

The value returned will be a positive value less than 360.0.
        """
        _x1 = self.__ex1
        _y1 = self.__ey1
        _x2 = self.__ex2
        _y2 = self.__ey2
        if abs(_x2 - _x1) < 1e-10 and abs(_y2 - _y1) < 1e-10:
            raise ValueError, "Endpoints are equal"
        if abs(_x2 - _x1) < 1e-10: # vertical
            if _y2 > _y1:
                _angle = 90.0
            else:
                _angle = 270.0
        elif abs(_y2 - _y1) < 1e-10: # horizontal
            if _x2 > _x1:
                _angle = 0.0
            else:
                _angle = 180.0
        else:
            _angle = _rtd * math.atan2((_y2 - _y1), (_x2 - _x1))
            if _angle < 0.0:
                _angle = _angle + 360.0
        return _angle

    def getSinCosValues(self):
        """Return sin()/cos() values based on the DimBar slope

getSinCosValues()

This method returns a tuple of two floats. The first value is
the sin() value, the second is the cos() value.
        """
        _x1 = self.__ex1
        _y1 = self.__ey1
        _x2 = self.__ex2
        _y2 = self.__ey2
        if abs(_x2 - _x1) < 1e-10: # vertical
            _cosine = 0.0
            if _y2 > _y1:
                _sine = 1.0
            else:
                _sine = -1.0
        elif abs(_y2 - _y1) < 1e-10: # horizontal
            _sine = 0.0
            if _x2 > _x1:
                _cosine = 1.0
            else:
                _cosine = -1.0
        else:
            _angle = math.atan2((_y2 - _y1), (_x2 - _x1))
            _sine = math.sin(_angle)
            _cosine = math.cos(_angle)
        return _sine, _cosine

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

class DimCrossbar(DimBar):
    """The class for the Dimension crossbar.

The DimCrossbar class is drawn between two DimBar objects for
horizontal, vertical, and generic linear dimensions. The dimension
text is place over the DimCrossbar object. Arrow heads, circles, or
slashes can be drawn at the intersection of the DimCrossbar and
the DimBar if desired. These objects are called markers.

The DimCrossbar class is derived from the DimBar class so it shares
all the methods of that class. In addition the DimCrossbar class has
the following methods:

{set/get}FirstCrossbarPoint(): Set/Get the initial location of the crossbar.
{set/get}SecondCrossbarPoint(): Set/Get the ending location of the crossbar.
getCrossbarPoints(): Get the location of the crossbar endpoints.
clearMarkerPoints(): Delete the stored coordintes of the dimension markers.
storeMarkerPoint(): Save a coordinate pair of the dimension marker.
getMarkerPoints(): Return the coordinates of the dimension marker.
    """
    messages = {}
    def __init__(self, **kw):
        """Initialize a DimCrossbar object.

dcb = DimCrossbar()

This method takes no arguments.
        """
        super(DimCrossbar, self).__init__(**kw)
        self.__mx1 = 0.0
        self.__my1 = 0.0
        self.__mx2 = 0.0
        self.__my2 = 0.0
        self.__mpts = []

    def setFirstCrossbarPoint(self, x, y):
        """Store the initial endpoint of the DimCrossbar.

setFirstCrossbarPoint(x, y)

Arguments x and y should be floats.
        """
        if self.isLocked():
            raise RuntimeError, "Setting crossbar point not allowed - object locked."
        _x = util.get_float(x)
        _y = util.get_float(y)
        _sx = self.__mx1
        _sy = self.__my1
        if abs(_sx - _x) > 1e-10 or abs(_sy - _y) > 1e-10:
            self.__mx1 = _x
            self.__my1 = _y
            self.sendMessage('attribute_changed', 'barpoint', _sx, _sy,
                             self.__mx2, self.__my2)
            self.modified()

    def getFirstCrossbarPoint(self):
        """Return the initial coordinates of the DimCrossbar.

getFirstCrossbarPoint()

This method returns a tuple of two floats giving the x/y coordinates.
        """
        return self.__mx1, self.__my1

    def setSecondCrossbarPoint(self, x, y):
        """Store the terminal endpoint of the DimCrossbar.

setSecondCrossbarPoint(x, y)

Arguments 'x' and 'y' should be floats.
        """
        if self.isLocked():
            raise RuntimeError, "Setting crossbar point not allowed - object locked"
        _x = util.get_float(x)
        _y = util.get_float(y)
        _sx = self.__mx2
        _sy = self.__my2
        if abs(_sx - _x) > 1e-10 or abs(_sy - _y) > 1e-10:
            self.__mx2 = _x
            self.__my2 = _y
            self.sendMessage('attribute_changed', 'barpoint',
                             self.__mx1, self.__my1, _sx, _sy)
            self.modified()

    def getSecondCrossbarPoint(self):
        """Return the terminal coordinates of the DimCrossbar.

getSecondCrossbarPoint()

This method returns a tuple of two floats giving the x/y coordinates.
        """
        return self.__mx2, self.__my2

    def getCrossbarPoints(self):
        """Return the endpoints of the DimCrossbar.

getCrossbarPoints()

This method returns two tuples, each tuple containing two float
values giving the x/y coordinates.
        """
        _mp1 = (self.__mx1, self.__my1)
        _mp2 = (self.__mx2, self.__my2)
        return _mp1, _mp2

    def clearMarkerPoints(self):
        """Delete the stored location of any dimension markers.

clearMarkerPoints()
        """
        del self.__mpts[:]

    def storeMarkerPoint(self, x, y):
        """Save a coordinate pair of the current dimension marker.

storeMarkerPoint(x, y)

Arguments 'x' and 'y' should be floats. Each time this method is invoked
the list of stored coordinates is appended with the values given as
arguments.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        self.__mpts.append((_x, _y))

    def getMarkerPoints(self):
        """Return the stored marker coordinates.

getMarkerPoints()

This method returns a list of coordinates stored with storeMarkerPoint().
Each item in the list is a tuple holding two float values - the x/y
coordinate of the point.
        """
        return self.__mpts[:]

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

class DimCrossarc(DimCrossbar):
    """The class for specialized crossbars for angular dimensions.

The DimCrossarc class is meant to be used only with angular dimensions.
As an angular dimension has two DimBar objects that are connected
with an arc. The DimCrossarc class is derived from the DimCrossbar
class so it shares all the methods of that class. The DimCrossarc
class has the following additional methods:

{get/set}Radius(): Get/Set the radius of the arc.
{get/set}StartAngle(): Get/Set the arc starting angle.
{get/set}EndAngle(): Get/Set the arc finishing angle.
    """

    messages = {
        'arcpoint_changed' : True,
        'radius_changed' : True,
        'start_angle_changed' : True,
        'end_angle_changed' : True,
    }
    def __init__(self, radius=0.0, start=0.0, end=0.0, **kw):
        """Initialize a DimCrossarc object.

dca = DimCrossarc([radius, start, end])

By default the arguments are all 0.0. Any arguments passed to
this method should be floats.
        """
        super(DimCrossarc, self).__init__(**kw)
        _r = util.get_float(radius)
        if _r < 0.0:
            raise ValueError, "Invalid radius: %g" % _r
        _start = util.make_c_angle(start)
        _end = util.make_c_angle(end)
        self.__radius = _r
        self.__start = _start
        self.__end = _end

    def getRadius(self):
        """Return the radius of the arc.

getRadius()

This method returns a float value.
        """
        return self.__radius

    def setRadius(self, radius):
        """Set the radius of the arc.

setRadius(radius)

Argument 'radius' should be a float value greater than 0.0.
        """
        if self.isLocked():
            raise RuntimeError, "Setting radius not allowed - object locked."
        _r = util.get_float(radius)
        if _r < 0.0:
            raise ValueError, "Invalid radius: %g" % _r
        _sr = self.__radius
        if abs(_sr - _r) > 1e-10:
            self.__radius = _r
            self.sendMessage('radius_changed', _sr)
            self.modified()

    def getStartAngle(self):
        """Return the arc starting angle.

getStartAngle()

This method returns a float.
        """
        return self.__start

    def setStartAngle(self, angle):
        """Set the starting angle of the arc.

setStartAngle(angle)

Argument angle should be a float value.
        """
        if self.isLocked():
            raise RuntimeError, "Setting start angle not allowed - object locked."
        _sa = self.__start
        _angle = util.make_c_angle(angle)
        if abs(_sa - _angle) > 1e-10:
            self.__start = _angle
            self.sendMessage('start_angle_changed', _sa)
            self.modified()

    def getEndAngle(self):
        """Return the arc ending angle.

getEndAngle()

This method returns a float.
        """
        return self.__end

    def setEndAngle(self, angle):
        """Set the ending angle of the arc.

setEndAngle(angle)

Argument angle should be a float value.
        """
        if self.isLocked():
            raise RuntimeError, "Setting end angle not allowed - object locked."
        _ea = self.__end
        _angle = util.make_c_angle(angle)
        if abs(_ea - _angle) > 1e-10:
            self.__end = _angle
            self.sendMessage('end_angle_changed', _ea)
            self.modified()

    def getAngle(self):
        pass # override the DimBar::getAngle() method

    def getSinCosValues(self):
        pass # override the DimBar::getSinCosValues() method

_deftextcolor = color.Color('#ffffff')
_defcolor = color.Color(255, 165, 0)

dimstyle_defaults = {
    'DIM_PRIMARY_FONT_FAMILY' : 'Sans',
    'DIM_PRIMARY_FONT_SIZE' : 1.0,
    'DIM_PRIMARY_TEXT_SIZE' : 1.0,
    'DIM_PRIMARY_FONT_WEIGHT' : text.TextStyle.FONT_NORMAL,
    'DIM_PRIMARY_FONT_STYLE' : text.TextStyle.FONT_NORMAL,
    'DIM_PRIMARY_FONT_COLOR' : _deftextcolor,
    'DIM_PRIMARY_TEXT_ANGLE' : 0.0,
    'DIM_PRIMARY_TEXT_ALIGNMENT' : text.TextStyle.ALIGN_CENTER,
    'DIM_PRIMARY_PREFIX' : u'',
    'DIM_PRIMARY_SUFFIX' : u'',
    'DIM_PRIMARY_PRECISION' : 3,
    'DIM_PRIMARY_UNITS' : units.MILLIMETERS,
    'DIM_PRIMARY_LEADING_ZERO' : True,
    'DIM_PRIMARY_TRAILING_DECIMAL': True,
    'DIM_SECONDARY_FONT_FAMILY' : 'Sans',
    'DIM_SECONDARY_FONT_SIZE' : 1.0,
    'DIM_SECONDARY_TEXT_SIZE' : 1.0,
    'DIM_SECONDARY_FONT_WEIGHT' : text.TextStyle.FONT_NORMAL,
    'Dim_secondary_font_style' : text.TextStyle.FONT_NORMAL,
    'DIM_SECONDARY_FONT_COLOR' : _deftextcolor,
    'DIM_SECONDARY_TEXT_ANGLE' : 0.0,
    'DIM_SECONDARY_TEXT_ALIGNMENT' : text.TextStyle.ALIGN_CENTER,
    'DIM_SECONDARY_PREFIX' : u'',
    'DIM_SECONDARY_SUFFIX' : u'',
    'DIM_SECONDARY_PRECISION' : 3,
    'DIM_SECONDARY_UNITS' : units.MILLIMETERS,
    'DIM_SECONDARY_LEADING_ZERO' : True,
    'DIM_SECONDARY_TRAILING_DECIMAL': True,
    'DIM_OFFSET' : 1.0,
    'DIM_EXTENSION': 1.0,
    'DIM_COLOR' : _defcolor,
    'DIM_POSITION': 0, # Dimension.DIM_TEXT_POS_SPLIT,
    'DIM_ENDPOINT': 0, # Dimension.DIM_ENDPT_NONE
    'DIM_ENDPOINT_SIZE' : 1.0,
    'DIM_DUAL_MODE' : False,
    'DIM_POSITION_OFFSET' : 0.0,
    'DIM_DUAL_MODE_OFFSET' : 1.0,
    'RADIAL_DIM_PRIMARY_PREFIX' : u'',
    'RADIAL_DIM_PRIMARY_SUFFIX' : u'',
    'RADIAL_DIM_SECONDARY_PREFIX' : u'',
    'RADIAL_DIM_SECONDARY_SUFFIX' : u'',
    'RADIAL_DIM_DIA_MODE' : False,
    'ANGULAR_DIM_PRIMARY_PREFIX' : u'',
    'ANGULAR_DIM_PRIMARY_SUFFIX' : u'',
    'ANGULAR_DIM_SECONDARY_PREFIX' : u'',
    'ANGULAR_DIM_SECONDARY_SUFFIX' : u'',
    }

class Dimension(entity.Entity):
    """The base class for Dimensions

A Dimension object is meant to be a base class for specialized
dimensions.

Every Dimension object holds two DimString objects, so any
dimension can be displayed with two separate formatting options
and units.

A Dimension has the following methods

{get/set}DimStyle(): Get/Set the DimStyle used for this Dimension.
getPrimaryDimstring(): Return the DimString used for formatting the
                       Primary dimension.
getSecondaryDimstring(): Return the DimString used for formatting the
                         Secondary dimension.
{get/set}EndpointType(): Get/Set the type of endpoints used in the Dimension
{get/set}EndpointSize(): Get/Set the size of the dimension endpoints
{get/set}DualDimMode(): Get/Set whether or not to display both the Primary
                        and Secondary DimString objects
{get/set}Offset(): Get/Set how far from the dimension endpoints to draw
                   dimension lines at the edges of the dimension.
{get/set}Extension(): Get/Set how far past the dimension crossbar line
                      to draw.
{get/set}Position(): Get/Set where the dimensional values are placed on the
                     dimension cross bar.
{get/set}Color(): Get/Set the color used to draw the dimension lines.
{get/set}Location(): Get/Set where to draw the dimensional values.
{get/set}PositionOffset(): Get/Set the dimension text offset when the text is
                           above or below the crossbar/crossarc
{get/set}DualModeOffset(): Get/Set the text offset for spaceing the two
                           dimension strings above and below the bar
                           separating the two dimensions
getStyleValue(): Return the DimStyle value for some option
getDimensions(): Return the formatted dimensional values in this Dimension.
inRegion(): Return if the dimension is visible within some are.
calcDimValues(): Calculate the dimension lines endpoints.
mapCoords(): Return the coordinates on the dimension within some point.
onDimension(): Test if an x/y coordinate pair hit the dimension lines.
getBounds(): Return the minma and maximum locations of the dimension.
    """
    #
    # Endpoint
    #
    DIM_ENDPT_NONE= 0
    DIM_ENDPT_ARROW = 1
    DIM_ENDPT_FILLED_ARROW = 2
    DIM_ENDPT_SLASH = 3
    DIM_ENDPT_CIRCLE = 4

    #
    # Dimension position on dimline
    #
    DIM_TEXT_POS_SPLIT = 0
    DIM_TEXT_POS_ABOVE = 1
    DIM_TEXT_POS_BELOW = 2

    __defdimcolor = color.Color(255,165,0)
    #
    # hack alert
    #
    __defdimstyle = None # DimStyle(u'Default DimStyle')

    messages = {
        'dimstyle_changed' : True,
        'endpoint_type_changed' : True,
        'endpoint_size_changed' : True,
        'dual_mode_changed' : True,
        'offset_changed' : True,
        'extension_changed' : True,
        'position_changed' : True,
        'position_offset_changed' : True,
        'dual_mode_offset_changed' : True,
        'color_changed' :  True,
        'thickness_changed' : True,
        'moved' : True,
    }
    def __init__(self, x, y, dimstyle=None, **kw):
        """Initialize a Dimension object

dim = Dimension(x, y[, ds])

Arguments 'x' and 'y' should be float values. Optional argument
'ds' should be a DimStyle instance. A default DimStyle is used
of the optional argument is not used.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _ds = dimstyle
        if _ds is None:
            if Dimension.__defdimstyle is None:
                Dimension.__defdimstyle = DimStyle(u'Default DimStyle')
            _ds = Dimension.__defdimstyle
        if not isinstance(_ds, DimStyle):
            raise TypeError, "Invalid DimStyle type: " + `type(_ds)`
        _ddm = _ds.getValue('DIM_DUAL_MODE')
        if 'dual-mode' in kw:
            _ddm = kw['dual-mode']
            util.test_boolean(_ddm)
        _offset = _ds.getValue('DIM_OFFSET')
        if 'offset' in kw:
            _offset = util.get_float(kw['offset'])
            if _offset < 0.0:
                raise ValueError, "Invalid dimension offset: %g" % _offset
        _extlen = _ds.getValue('DIM_EXTENSION')
        if 'extlen' in kw:
            _extlen = util.get_float(kw['extlen'])
            if _extlen < 0.0:
                raise ValueError, "Invalid dimension extension: %g" % _extlen
        _textpos = _ds.getValue('DIM_POSITION')
        if 'textpos' in kw:
            _textpos = kw['textpos']
            if (_textpos != Dimension.DIM_TEXT_POS_SPLIT and
                _textpos != Dimension.DIM_TEXT_POS_ABOVE and
                _textpos != Dimension.DIM_TEXT_POS_BELOW):
                raise ValueError, "Invalid dimension text position: '%s'" % str(_textpos)
        _poffset = _ds.getValue('DIM_POSITION_OFFSET')
        if 'poffset' in kw:
            _poffset = util.get_float(kw['poffset'])
            if _poffset < 0.0:
                raise ValueError, "Invalid text offset length %g" % _poffset
        _dmoffset = _ds.getValue('DIM_DUAL_MODE_OFFSET')
        if 'dmoffset' in kw:
            _dmoffset = util.get_float(kw['dmoffset'])
            if _dmoffset < 0.0:
                raise ValueError, "Invalid dual mode offset length %g" % _dmoffset
        _eptype = _ds.getValue('DIM_ENDPOINT')
        if 'eptype' in kw:
            _eptype = kw['eptype']
            if (_eptype != Dimension.DIM_ENDPT_NONE and
                _eptype != Dimension.DIM_ENDPT_ARROW and
                _eptype != Dimension.DIM_ENDPT_FILLED_ARROW and
                _eptype != Dimension.DIM_ENDPT_SLASH and
                _eptype != Dimension.DIM_ENDPT_CIRCLE):
                raise ValueError, "Invalid endpoint type: '%s'" % str(_eptype)
        _epsize = _ds.getValue('DIM_ENDPOINT_SIZE')
        if 'epsize' in kw:
            _epsize = util.get_float(kw['epsize'])
            if _epsize < 0.0:
                raise ValueError, "Invalid endpoint size %g" % _epsize
        _color = _ds.getValue('DIM_COLOR')
        if 'color' in kw:
            _color = kw['color']
            if not isinstance(_color, color.Color):
                raise TypeError, "Invalid color type: " + `type(_color)`
        _thickness = _ds.getValue('DIM_THICKNESS')
        if 'thickness' in kw:
            _thickness = util.get_float(kw['thickness'])
            if _thickness < 0.0:
                raise ValueError, "Invalid thickness: %g" % _thickness
        #
        # dimstrings
        #
        # the setDimension() call will adjust the values in the
        # new DimString instances if they get created
        #
        _ds1 = _ds2 = None
        _ds1adj = _ds2adj = True
        if 'ds1' in kw:
            _ds1 = kw['ds1']
            if not isinstance(_ds1, DimString):
                raise TypeError, "Invalid DimString type: " + `type(_ds1)`
            _ds1adj = False
        if _ds1 is None:
            _ds1 = DimString(_x, _y)
        #
        if 'ds2' in kw:
            _ds2 = kw['ds2']
            if not isinstance(_ds2, DimString):
                raise TypeError, "Invalid DimString type: " + `type(_ds2)`
            _ds2adj = False
        if _ds2 is None:
            _ds2 = DimString(_x, _y)
        #
        # finally ...
        #
        super(Dimension, self).__init__(**kw)
        self.__dimstyle = _ds
        self.__ddm = _ddm
        self.__offset = _offset
        self.__extlen = _extlen
        self.__textpos = _textpos
        self.__poffset = _poffset
        self.__dmoffset = _dmoffset
        self.__eptype = _eptype
        self.__epsize = _epsize
        self.__color = _color
        self.__thickness = _thickness
        self.__dimloc = (_x, _y)
        self.__ds1 = _ds1
        self.__ds2 = _ds2
        self.__ds1.setDimension(self, _ds1adj)
        self.__ds2.setDimension(self, _ds2adj)

    def finish(self):
        self.__ds1.finish()
        self.__ds2.finish()
        self.__ds1 = self.__ds2 = None
        super(Dimension, self).finish()

    def getValues(self):
        """Return values comprising the Dimension.

getValues()

This method extends the Entity::getValues() method.
        """
        _ds = self.__dimstyle
        _data = super(Dimension, self).getValues()
        _data.setValue('location', self.__dimloc)
        if abs(self.__offset - _ds.getValue('DIM_OFFSET')) > 1e-10:
            _data.setValue('offset', self.__offset)
        if abs(self.__extlen - _ds.getValue('DIM_EXTENSION')) > 1e-10:
            _data.setValue('extension', self.__extlen)
        if self.__textpos != _ds.getValue('DIM_POSITION'):
            _data.setValue('position', self.__textpos)
        if self.__eptype != _ds.getValue('DIM_ENDPOINT'):
            _data.setValue('eptype', self.__eptype)
        if abs(self.__epsize - _ds.getValue('DIM_ENDPOINT_SIZE')) > 1e-10:
            _data.setValue('epsize', self.__epsize)
        if self.__color != _ds.getValue('DIM_COLOR'):
            _data.setValue('color', self.__color.getColors())
        if self.__ddm != _ds.getValue('DIM_DUAL_MODE'):
            _data.setValue('dualmode', self.__ddm)
        if abs(self.__poffset - _ds.getValue('DIM_POSITION_OFFSET')) > 1e-10:
            _data.setValue('poffset', self.__poffset)
        if abs(self.__dmoffset - _ds.getValue('DIM_DUAL_MODE_OFFSET')) > 1e-10:
            _data.setValue('dmoffset', self.__dmoffset)
        if abs(self.__thickness - _ds.getValue('DIM_THICKNESS')) > 1e-10:
            _data.setValue('thickness', self.__thickness)
        _data.setValue('ds1', self.__ds1.getValues())
        _data.setValue('ds2', self.__ds2.getValues())
        if _ds is Dimension.__defdimstyle:
            _data.setValue('dimstyle', None)
        else:
            _data.setValue('dimstyle', _ds.getValues())
        return _data

    def getDimStyle(self):
        """Return the DimStyle used in this Dimension.

getDimStyle()
        """
        return self.__dimstyle

    def setDimStyle(self, ds):
        """Set the DimStyle used for this Dimension.

setDimStyle(ds)

After setting the DimStyle, the values stored in it
are applied to the DimensionObject.
        """
        if self.isLocked():
            raise RuntimeError, "Changing dimstyle not allowed - object locked."
        if not isinstance(ds, DimStyle):
            raise TypeError, "Invalid DimStyle type: " + `type(ds)`
        _sds = self.__dimstyle
        if ds is not _sds:
            self.__dimstyle = ds
            #
            # call the various methods without arguments
            # so the values given in the new DimStyle are used
            #
            self.setOffset()
            self.setExtension()
            self.setPosition()
            self.setEndpointType()
            self.setEndpointSize()
            self.setColor()
            self.setThickness()
            self.setDualDimMode()
            self.setPositionOffset()
            self.setDualModeOffset()
            #
            # set the values in the two DimString instances
            #
            _d = self.__ds1
            _d.setPrefix(ds.getValue('DIM_PRIMARY_PREFIX'))
            _d.setSuffix(ds.getValue('DIM_PRIMARY_SUFFIX'))
            _d.setPrecision(ds.getValue('DIM_PRIMARY_PRECISION'))
            _d.setUnits(ds.getValue('DIM_PRIMARY_UNITS'))
            _d.setPrintZero(ds.getValue('DIM_PRIMARY_LEADING_ZERO'))
            _d.setPrintDecimal(ds.getValue('DIM_PRIMARY_TRAILING_DECIMAL'))
            _d.setFamily(ds.getValue('DIM_PRIMARY_FONT_FAMILY'))
            _d.setWeight(ds.getValue('DIM_PRIMARY_FONT_WEIGHT'))
            _d.setStyle(ds.getValue('DIM_PRIMARY_FONT_STYLE'))
            _d.setColor(ds.getValue('DIM_PRIMARY_FONT_COLOR'))
            _d.setSize(ds.getValue('DIM_PRIMARY_TEXT_SIZE'))
            _d.setAngle(ds.getValue('DIM_PRIMARY_TEXT_ANGLE'))
            _d.setAlignment(ds.getVaue('DIM_PRIMARY_TEXT_ALIGNMENT'))
            _d = self.__ds2
            _d.setPrefix(ds.getValue('DIM_SECONDARY_PREFIX'))
            _d.setSuffix(ds.getValue('DIM_SECONDARY_SUFFIX'))
            _d.setPrecision(ds.getValue('DIM_SECONDARY_PRECISION'))
            _d.setUnits(ds.getValue('DIM_SECONDARY_UNITS'))
            _d.setPrintZero(ds.getValue('DIM_SECONDARY_LEADING_ZERO'))
            _d.setPrintDecimal(ds.getValue('DIM_SECONDARY_TRAILING_DECIMAL'))
            _d.setFamily(ds.getValue('DIM_SECONDARY_FONT_FAMILY'))
            _d.setWeight(ds.getValue('DIM_SECONDARY_FONT_WEIGHT'))
            _d.setStyle(ds.getValue('DIM_SECONDARY_FONT_STYLE'))
            _d.setColor(ds.getValue('DIM_SECONDARY_FONT_COLOR'))
            _d.setSize(ds.getValue('DIM_SECONDARY_TEXT_SIZE'))
            _d.setAngle(ds.getValue('DIM_SECONDARY_TEXT_ANGLE'))
            _d.setAlignment(ds.getVaue('DIM_SECONDARY_TEXT_ALIGNMENT'))
            self.sendMessage('dimstyle_changed', _sds)
            self.modified()

    dimstyle = property(getDimStyle, setDimStyle, None,
                        "Dimension DimStyle object.")

    def applyDimStyle(self):
        """Apply the values in the DimStyle to the Dimension.

applyDimStyle()
        """
        warnings.warn("applyDimStyle() called",
                      DeprecationWarning, stacklevel=2)
        return

    def getEndpointType(self):
        """Return what type of endpoints the Dimension uses.

getEndpointType()
        """
        return self.__eptype

    def setEndpointType(self, eptype=None):
        """Set what type of endpoints the Dimension will use.

setEndpointType([e])

The argument 'e' should be one of the following

dimension.NO_ENDPOINT => no special marking at the dimension crossbar ends
dimension.ARROW => an arrowhead at the dimension crossbar ends
dimension.FILLED_ARROW => a filled arrohead at the dimension crossbar ends
dimension.SLASH => a slash mark at the dimension crossbar ends
dimension.CIRCLE => a filled circle at the dimension crossbar ends

If this method is called without an argument, the endpoint type is set
to that given in the DimStyle.
        """
        if self.isLocked():
            raise RuntimeError, "Changing endpoint type allowed - object locked."
        _ep = eptype
        if _ep is None:
            _ep = self.__dimstyle.getValue('DIM_ENDPOINT')
        if (_ep != Dimension.DIM_ENDPT_NONE and
            _ep != Dimension.DIM_ENDPT_ARROW and
            _ep != Dimension.DIM_ENDPT_FILLED_ARROW and
            _ep != Dimension.DIM_ENDPT_SLASH and
            _ep != Dimension.DIM_ENDPT_CIRCLE):
            raise ValueError, "Invalid endpoint value: '%s'" % str(_ep)
        _et = self.__eptype
        if _et != _ep:
            self.__eptype = _ep
            self.sendMessage('endpoint_type_changed', _et)
            self.modified()

    endpoint = property(getEndpointType, setEndpointType,
                        None, "Dimension endpoint type.")

    def getEndpointSize(self):
        """Return the size of the Dimension endpoints.

getEndpointSize()
        """
        return self.__epsize

    def setEndpointSize(self, size=None):
        """Set the size of the Dimension endpoints.

setEndpointSize([size])

Optional argument 'size' should be a float greater than or equal to 0.0.
Calling this method without an argument sets the endpoint size to that
given in the DimStle.
        """
        if self.isLocked():
            raise RuntimeError, "Changing endpoint type allowed - object locked."
        _size = size
        if _size is None:
            _size = self.__dimstyle.getValue('DIM_ENDPOINT_SIZE')
        _size = util.get_float(_size)
        if _size < 0.0:
            raise ValueError, "Invalid endpoint size: %g" % _size
        _es = self.__epsize
        if abs(_es - _size) > 1e-10:
            self.__epsize = _size
            self.sendMessage('endpoint_size_changed', _es)
            self.modified()

    def getDimstrings(self):
        """Return both primary and secondry dimstrings.

getDimstrings()
        """
        return self.__ds1, self.__ds2

    def getPrimaryDimstring(self):
        """ Return the DimString used for formatting the primary dimension.

getPrimaryDimstring()
        """
        return self.__ds1

    def getSecondaryDimstring(self):
        """Return the DimString used for formatting the secondary dimension.

getSecondaryDimstring()
        """
        return self.__ds2

    def getDualDimMode(self):
        """Return if the Dimension is displaying primary and secondary values.

getDualDimMode(self)
        """
        return self.__ddm

    def setDualDimMode(self, mode=None):
        """Set the Dimension to display both primary and secondary values.

setDualDimMode([mode])

Optional argument 'mode' should be either True or False.
Invoking this method without arguments will set the dual dimension
value display mode to that given from the DimStyle
        """
        if self.isLocked():
            raise RuntimeError, "Changing dual mode not allowed - object locked."
        _mode = mode
        if _mode is None:
            _mode = self.__dimstyle.getValue('DIM_DUAL_MODE')
        util.test_boolean(_mode)
        _ddm = self.__ddm
        if _ddm is not _mode:
            self.__ddm = _mode
            self.__ds1.setBounds()
            self.__ds2.setBounds()
            self.sendMessage('dual_mode_changed', _ddm)
            self.modified()

    dual_mode = property(getDualDimMode, setDualDimMode, None,
                         "Display both primary and secondary dimensions")

    def getOffset(self):
        """Return the current offset value for the Dimension.

getOffset()
        """
        return self.__offset

    def setOffset(self, offset=None):
        """Set the offset value for the Dimension.

setOffset([offset])

Optional argument 'offset' should be a positive float.
Calling this method without arguments sets the value to that
given in the DimStyle.
        """
        if self.isLocked():
            raise RuntimeError, "Setting offset not allowed - object locked."
        _o = offset
        if _o is None:
            _o = self.__dimstyle.getValue('DIM_OFFSET')
        _o = util.get_float(_o)
        if _o < 0.0:
            raise ValueError, "Invalid dimension offset length: %g" % _o
        _off = self.__offset
        if abs(_off - _o) > 1e-10:
            _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
            self.__offset = _o
            self.calcDimValues()
            self.sendMessage('offset_changed', _off)
            self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    offset = property(getOffset, setOffset, None, "Dimension offset.")

    def getExtension(self):
        """Get the extension length of the Dimension.

getExtension()
        """
        return self.__extlen

    def setExtension(self, ext=None):
        """Set the extension length of the Dimension.

setExtension([ext])

Optional argument 'ext' should be a positive float value.
Calling this method without arguments set the extension length
to that given in the DimStyle.
        """
        if self.isLocked():
            raise RuntimeError, "Setting extension not allowed - object locked."
        _e = ext
        if _e is None:
            _e = self.__dimstyle.getValue('DIM_EXTENSION')
        _e = util.get_float(_e)
        if _e < 0.0:
            raise ValueError, "Invalid dimension extension length: %g" % _e
        _ext = self.__extlen
        if abs(_ext - _e) > 1e-10:
            _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
            self.__extlen = _e
            self.calcDimValues()
            self.sendMessage('extension_changed', _ext)
            self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    extension = property(getExtension, setExtension, None,
                         "Dimension extension length.")

    def getPosition(self):
        """Return how the dimension text intersects the crossbar.

getPosition()
        """
        return self.__textpos

    def setPosition(self, pos=None):
        """Set where the dimension text should be placed at the crossbar.

setPosition([pos])

Choices for optional argument 'pos' are:

dimension.SPLIT => In the middle of the crossbar.
dimension.ABOVE => Beyond the crossbar from the dimensioned objects.
dimension.BELOW => Between the crossbar and the dimensioned objects.

Calling this method without arguments sets the position to that given
in the DimStyle.
        """
        if self.isLocked():
            raise RuntimeError, "Setting position not allowed - object locked."
        _pos = pos
        if _pos is None:
            _pos = self.__dimstyle.getValue('DIM_POSITION')
        if (_pos != Dimension.DIM_TEXT_POS_SPLIT and
            _pos != Dimension.DIM_TEXT_POS_ABOVE and
            _pos != Dimension.DIM_TEXT_POS_BELOW):
            raise ValueError, "Invalid dimension text position: '%s'" % str(_pos)
        _dp = self.__textpos
        if _dp != _pos:
            self.__textpos = _pos
            self.__ds1.setBounds()
            self.__ds2.setBounds()
            self.sendMessage('position_changed', _dp)
            self.modified()

    position = property(getPosition, setPosition, None,
                        "Dimension text position")

    def getPositionOffset(self):
        """Get the offset for the dimension text and the crossbar/crossarc.

getPositionOffset()
        """
        return self.__poffset

    def setPositionOffset(self, offset=None):
        """Set the separation between the dimension text and the crossbar.

setPositionOffset([offset])

If this method is called without arguments, the text offset
length is set to the value given in the DimStyle.
If the argument 'offset' is supplied, it should be a positive float value.
        """
        if self.isLocked():
            raise RuntimeError, "Setting text offset length not allowed - object locked."
        _o = offset
        if _o is None:
            _o = self.__dimstyle.getValue('DIM_POSITION_OFFSET')
        _o = util.get_float(_o)
        if _o < 0.0:
            raise ValueError, "Invalid text offset length: %g" % _o
        _to = self.__poffset
        if abs(_to - _o) > 1e-10:
            _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
            self.__poffset = _o
            self.__ds1.setBounds()
            self.__ds2.setBounds()
            self.calcDimValues()
            self.sendMessage('position_offset_changed', _to)
            self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    position_offset = property(getPositionOffset, setPositionOffset, None,
                               "Text offset from crossbar/crossarc distance.")

    def getDualModeOffset(self):
        """Get the offset for the dimension text when displaying two dimensions.

getDualModeOffset()
        """
        return self.__dmoffset

    def setDualModeOffset(self, offset=None):
        """Set the separation between the dimensions and the dual mode dimension divider.

setDualModeOffset([offset])

If this method is called without arguments, the dual mode offset
length is set to the value given in the DimStyle.
If the argument 'offset' is supplied, it should be a positive float value.
        """
        if self.isLocked():
            raise RuntimeError, "Setting dual mode offset length not allowed - object locked."
        _o = offset
        if _o is None:
            _o = self.__dimstyle.getValue('DIM_DUAL_MODE_OFFSET')
        _o = util.get_float(_o)
        if _o < 0.0:
            raise ValueError, "Invalid dual mode offset length: %g" % _o
        _dmo = self.__dmoffset
        if abs(_dmo - _o) > 1e-10:
            _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
            self.__dmoffset = _o
            self.__ds1.setBounds()
            self.__ds2.setBounds()
            self.calcDimValues()
            self.sendMessage('dual_mode_offset_changed', _dmo)
            self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    dual_mode_offset = property(getDualModeOffset, setDualModeOffset, None,
                                "Text offset from dimension splitting bar when displaying two dimensions.")

    def getColor(self):
        """Return the color of the dimension lines.

getColor()
        """
        return self.__color

    def setColor(self, c=None):
        """Set the color of the dimension lines.

setColor([c])

Optional argument 'c' should be a Color instance. Calling this
method without an argument sets the color to the value given
in the DimStyle.
        """
        if self.isLocked():
            raise RuntimeError, "Setting object color not allowed - object locked."
        _c = c
        if _c is None:
            _c = self.__dimstyle.getValue('DIM_COLOR')
        if not isinstance(_c, color.Color):
            raise TypeError, "Invalid color type: " + `type(_c)`
        _oc = self.__color
        if _oc != _c:
            self.__color = _c
            self.sendMessage('color_changed', _oc)
            self.modified()

    color = property(getColor, setColor, None, "Dimension Color")

    def getThickness(self):
        """Return the thickness of the dimension bars.

getThickness()

This method returns a float.
        """
        return self.__thickness

    def setThickness(self, thickness=None):
        """Set the thickness of the dimension bars.

setThickness([thickness])

Optional argument 'thickness' should be a float value. Setting the
thickness to 0 will display and print the lines with the thinnest
value possible. Calling this method without arguments resets the
thickness to the value defined in the DimStyle.
        """
        if self.isLocked():
            raise RuntimeError, "Setting thickness not allowed - object locked."
        _t = thickness
        if _t is None:
            _t = self.__dimstyle.getValue('DIM_THICKNESS')
        _t = util.get_float(_t)
        if _t < 0.0:
            raise ValueError, "Invalid thickness: %g" % _t
        _ot = self.__thickness
        if abs(_ot - _t) > 1e-10:
            self.__thickness = _t
            self.sendMessage('thickness_changed', _ot)
            self.modified()

    thickness = property(getThickness, setThickness, None,
                         "Dimension bar thickness.")

    def getLocation(self):
        """Return the location of the dimensional text values.

getLocation()
        """
        return self.__dimloc

    def setLocation(self, x, y):
        """Set the location of the dimensional text values.

setLocation(x, y)

The 'x' and 'y' arguments should be float values. The text is
centered around that point.
        """
        if self.isLocked():
            raise RuntimeError, "Setting location not allowed - object locked."
        _x = util.get_float(x)
        _y = util.get_float(y)
        _ox, _oy = self.__dimloc
        if abs(_ox - _x) > 1e-10 or abs(_oy - _y) > 1e-10:
            _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
            self.__dimloc = (_x, _y)
            self.__ds1.setBounds()
            self.__ds2.setBounds()
            self.calcDimValues()
            self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    location = property(getLocation, setLocation, None,
                        "Dimension location")

    def getStyleValue(self, ds, opt):
        """Get the value in the DimStyle for some option

getStyleValue(ds, opt)

Argument 'ds' should be one of the DimString objects in
the Dimension, and argument 'opt' should be a string.
Valid choices for 'opt' are 'prefix', 'suffix', 'precision',
'units', 'print_zero', 'print_decimal', 'font_family',
'font_style', 'font_weight', 'size', 'color', 'angle',
and 'alignment'.
        """
        if not isinstance(ds, DimString):
            raise TypeError, "Invalid DimString type: " + `type(ds)`
        if not isinstance(opt, str):
            raise TypeError, "Invalid DimStyle option type: " + `type(opt)`
        _key = None
        if ds is self.__ds1:
            if opt == 'prefix':
                _key = 'DIM_PRIMARY_PREFIX'
            elif opt == 'suffix':
                _key = 'DIM_PRIMARY_SUFFIX'
            elif opt == 'precision':
                _key = 'DIM_PRIMARY_PRECISION'
            elif opt == 'units':
                _key = 'DIM_PRIMARY_UNITS'
            elif opt == 'print_zero':
                _key = 'DIM_PRIMARY_LEADING_ZERO'
            elif opt == 'print_decimal':
                _key = 'DIM_PRIMARY_TRAILING_DECIMAL'
            elif opt == 'font_family':
                _key = 'DIM_PRIMARY_FONT_FAMILY'
            elif opt == 'font_weight':
                _key = 'DIM_PRIMARY_FONT_WEIGHT'
            elif opt == 'font_style':
                _key = 'DIM_PRIMARY_FONT_STYLE'
            elif opt == 'size':
                _key = 'DIM_PRIMARY_TEXT_SIZE'
            elif opt == 'color':
                _key = 'DIM_PRIMARY_FONT_COLOR'
            elif opt == 'angle':
                _key = 'DIM_PRIMARY_TEXT_ANGLE'
            elif opt == 'alignment':
                _key = 'DIM_PRIMARY_TEXT_ALIGNMENT'
            else:
                raise ValueError, "Unexpected option: %s" % opt
        elif ds is self.__ds2:
            if opt == 'prefix':
                _key = 'DIM_SECONDARY_PREFIX'
            elif opt == 'suffix':
                _key = 'DIM_SECONDARY_SUFFIX'
            elif opt == 'precision':
                _key = 'DIM_SECONDARY_PRECISION'
            elif opt == 'units':
                _key = 'DIM_SECONDARY_UNITS'
            elif opt == 'print_zero':
                _key = 'DIM_SECONDARY_LEADING_ZERO'
            elif opt == 'print_decimal':
                _key = 'DIM_SECONDARY_TRAILING_DECIMAL'
            elif opt == 'font_family':
                _key = 'DIM_SECONDARY_FONT_FAMILY'
            elif opt == 'font_weight':
                _key = 'DIM_SECONDARY_FONT_WEIGHT'
            elif opt == 'font_style':
                _key = 'DIM_SECONDARY_FONT_STYLE'
            elif opt == 'size':
                _key = 'DIM_SECONDARY_TEXT_SIZE'
            elif opt == 'color':
                _key = 'DIM_SECONDARY_FONT_COLOR'
            elif opt == 'angle':
                _key = 'DIM_SECONDARY_TEXT_ANGLE'
            elif opt == 'alignment':
                _key = 'DIM_SECONDARY_TEXT_ALIGNMENT'
            else:
                raise ValueError, "Unexpected option: %s" % opt
        else:
            raise ValueError, "DimString not used in this Dimension: " + `ds`
        if _key is None:
            raise ValueError, "Unexpected option: %s" % opt
        return self.__dimstyle.getValue(_key)

    def getDimensions(self, dimlen):
        """Return the formatted dimensional values.

getDimensions(dimlen)

The argument 'dimlen' should be the length in millimeters.

This method returns a list of the primary and secondary
dimensional values.
        """
        _dl = util.get_float(dimlen)
        dims = []
        dims.append(self.__ds1.formatDimension(_dl))
        dims.append(self.__ds2.formatDimension(_dl))
        return dims

    def calcDimValues(self, allpts=True):
        """Recalculate the values for dimensional display

calcDimValues([allpts])

This method is meant to be overriden by subclasses.
        """
        pass

    def inRegion(self, xmin, ymin, xmax, ymax, fully=False):
        """Return whether or not a Dimension exists with a region.

isRegion(xmin, ymin, xmax, ymax[, fully])

The first four arguments define the boundary. The optional
fifth argument 'fully' indicates whether or not the Dimension
must be completely contained within the region or just pass
through it.

This method should be overriden in classes derived from Dimension.
        """
        return False

    def getBounds(self):
        """Return the minimal and maximal locations of the dimension

getBounds()

This method returns a tuple of four values - xmin, ymin, xmax, ymax.
These values give the mimimum and maximum coordinates of the dimension
object.

This method should be overriden in classes derived from Dimension.
        """
        _xmin = _ymin = -float(sys.maxint)
        _xmax = _ymax = float(sys.maxint)
        return _xmin, _ymin, _xmax, _ymax

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

#
# class stuff for dimension styles
#

class DimStyle(object):
    """A class storing preferences for Dimensions

The DimStyle class stores a set of dimension parameters
that will be used when creating dimensions when the
particular style is active.

A DimStyle object has the following methods:

getName(): Return the name of the DimStyle.
getOption(): Return a single value in the DimStyle.
getOptions(): Return all the options in the DimStyle.
getValue(): Return the value of one of the DimStyle options.

getOption() and getValue() are synonymous.
    """

    #
    # the default values for the DimStyle class
    #
    __deftextcolor = color.Color('#ffffff')
    __defdimcolor = color.Color(255,165,0)
    __defaults = {
        'DIM_PRIMARY_FONT_FAMILY' : 'Sans',
        'DIM_PRIMARY_FONT_SIZE' : 1.0,
        'DIM_PRIMARY_TEXT_SIZE' : 1.0,
        'DIM_PRIMARY_FONT_WEIGHT' : text.TextStyle.FONT_NORMAL,
        'DIM_PRIMARY_FONT_STYLE' : text.TextStyle.FONT_NORMAL,
        'DIM_PRIMARY_FONT_COLOR' : __deftextcolor,
        'DIM_PRIMARY_TEXT_ANGLE' : 0.0,
        'DIM_PRIMARY_TEXT_ALIGNMENT' : text.TextStyle.ALIGN_CENTER,
        'DIM_PRIMARY_PREFIX' : u'',
        'DIM_PRIMARY_SUFFIX' : u'',
        'DIM_PRIMARY_PRECISION' : 3,
        'DIM_PRIMARY_UNITS' : units.MILLIMETERS,
        'DIM_PRIMARY_LEADING_ZERO' : True,
        'DIM_PRIMARY_TRAILING_DECIMAL' : True,
        'DIM_SECONDARY_FONT_FAMILY' : 'Sans',
        'DIM_SECONDARY_FONT_SIZE' : 1.0,
        'DIM_SECONDARY_TEXT_SIZE' : 1.0,
        'DIM_SECONDARY_FONT_WEIGHT' : text.TextStyle.FONT_NORMAL,
        'DIM_SECONDARY_FONT_STYLE' : text.TextStyle.FONT_NORMAL,
        'DIM_SECONDARY_FONT_COLOR' : __deftextcolor,
        'DIM_SECONDARY_TEXT_ANGLE' : 0.0,
        'DIM_SECONDARY_TEXT_ALIGNMENT' : text.TextStyle.ALIGN_CENTER,
        'DIM_SECONDARY_PREFIX' : u'',
        'DIM_SECONDARY_SUFFIX' : u'',
        'DIM_SECONDARY_PRECISION' : 3,
        'DIM_SECONDARY_UNITS' : units.MILLIMETERS,
        'DIM_SECONDARY_LEADING_ZERO' : True,
        'DIM_SECONDARY_TRAILING_DECIMAL' : True,
        'DIM_OFFSET' : 1.0,
        'DIM_EXTENSION' : 1.0,
        'DIM_COLOR' : __defdimcolor,
        'DIM_THICKNESS' : 0.0,
        'DIM_POSITION' : Dimension.DIM_TEXT_POS_SPLIT,
        'DIM_ENDPOINT' : Dimension.DIM_ENDPT_NONE,
        'DIM_ENDPOINT_SIZE' : 1.0,
        'DIM_DUAL_MODE' : False,
        'DIM_POSITION_OFFSET' : 0.0,
        'DIM_DUAL_MODE_OFFSET' : 1.0,
        'RADIAL_DIM_PRIMARY_PREFIX' : u'',
        'RADIAL_DIM_PRIMARY_SUFFIX' : u'',
        'RADIAL_DIM_SECONDARY_PREFIX' : u'',
        'RADIAL_DIM_SECONDARY_SUFFIX' : u'',
        'RADIAL_DIM_DIA_MODE' : False,
        'ANGULAR_DIM_PRIMARY_PREFIX' : u'',
        'ANGULAR_DIM_PRIMARY_SUFFIX' : u'',
        'ANGULAR_DIM_SECONDARY_PREFIX' : u'',
        'ANGULAR_DIM_SECONDARY_SUFFIX' : u'',
        }

    def __init__(self, name, keywords={}):
        """Instantiate a DimStyle object.

ds = DimStyle(name, keywords)

The argument 'name' should be a unicode name, and the
'keyword' argument should be a dict. The keys should
be the same keywords used to set option values, such
as DIM_OFFSET, DIM_EXTENSION, etc, and the value corresponding
to each key should be set appropriately.
        """
        super(DimStyle, self).__init__()
        _n = name
        if not isinstance(_n, types.StringTypes):
            raise TypeError, "Invalid DimStyle name type: "+ `type(_n)`
        if isinstance(_n, str):
            _n = unicode(_n)
        if not isinstance(keywords, dict):
            raise TypeError, "Invalid keywords argument type: " + `type(keywords)`
        from PythonCAD.Generic.options import test_option
        self.__opts = baseobject.ConstDict(str)
        self.__name = _n
        for _kw in keywords:
            _val = keywords[_kw]
            if _kw not in DimStyle.__defaults:
                raise KeyError, "Unknown DimStyle keyword: " + _kw
            _valid = test_option(_kw, _val)
            self.__opts[_kw] = _val

    def __eq__(self, obj):
        """Test a DimStyle object for equality with another DimStyle.
        """
        if not isinstance(obj, DimStyle):
            return False
        # FIXME: Change obj.__opts
        return self.__name == obj.getName() and self.__opts == obj.__opts

    def __ne__(self, obj):
        """Test a DimStyle object for inequality with another DimStyle.
        """
        if not isinstance(obj, DimStyle):
            return True
        # FIXME: Change obj.__opts
        return self.__name != obj.getName() or self.__opts != obj.__opts

    def getName(self):
        """Return the name of the DimStyle.

getName()
        """
        return self.__name

    name = property(getName, None, None, "DimStyle name.")

    def getKeys(self):
        """Return the non-default options within the DimStyle.

getKeys()
        """
        return self.__opts.keys()

    def getOptions(self):
        """Return all the options stored within the DimStyle.

getOptions()
        """
        _keys = self.__opts.keys()
        for _key in DimStyle.__defaults:
            if _key not in self.__opts:
                _keys.append(_key)
        return _keys

    def getOption(self, key):
        """Return the value of a particular option in the DimStyle.

getOption(key)

The key should be one of the strings returned from getOptions. If
there is no value found in the DimStyle for the key, the value None
is returned.
        """
        if key in self.__opts:
            _val = self.__opts[key]
        elif key in DimStyle.__defaults:
            _val = DimStyle.__defaults[key]
        else:
            raise KeyError, "Unexpected DimStyle keyword: " + key
        return _val

    def getValue(self, key):
        """Return the value of a particular option in the DimStyle.

getValue(key)

The key should be one of the strings returned from getOptions. This
method raises a KeyError exception if the key is not found.

        """
        if key in self.__opts:
            _val = self.__opts[key]
        elif key in DimStyle.__defaults:
            _val = DimStyle.__defaults[key]
        else:
            raise KeyError, "Unexpected DimStyle keyword: " + key
        return _val

    def getValues(self):
        """Return values comprising the DimStyle.

getValues()
        """
        _vals = {}
        _vals['name'] = self.__name
        for _opt in self.__opts:
            _val = self.__opts[_opt]
            if ((_opt == 'DIM_PRIMARY_FONT_COLOR') or
                (_opt == 'DIM_SECONDARY_FONT_COLOR') or
                (_opt == 'DIM_COLOR')):
                _vals[_opt] = _val.getColors()
            else:
                _vals[_opt] = _val
        return _vals

class LinearDimension(Dimension):
    """A class for Linear dimensions.

The LinearDimension class is derived from the Dimension
class, so it shares all of those methods and attributes.
A LinearDimension should be used to display the absolute
distance between two Point objects.

A LinearDimension object has the following methods:

{get/set}P1(): Get/Set the first Point for the LinearDimension.
{get/set}P2(): Get/Set the second Point for the LinearDimension.
getDimPoints(): Return the two Points used in this dimension.
getDimLayers(): Return the two Layers holding the Points.
getDimXPoints(): Get the x-coordinates of the dimension bar positions.
getDimYPoints(): Get the y-coordinates of the dimension bar positions.
getDimMarkerPoints(): Get the locaiton of the dimension endpoint markers.
calcMarkerPoints(): Calculate the coordinates of any dimension marker objects.
    """

    messages = {
        'point_changed' : True,
    }

    def __init__(self, l1, p1, l2, p2, x, y, ds=None, **kw):
        """Instantiate a LinearDimension object.

ldim = LinearDimension(l1, p1, l2, p2, x, y, ds)

l1: A Layer holding Point p1
p1: A Point contained in Layer l1
l2: A Layer holding Point p2
p2: A Point contained in Layer l2
x: The x-coordinate of the dimensional text
y: The y-coordinate of the dimensional text
ds: The DimStyle used for this Dimension.
        """
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l1, Layer):
            raise TypeError, "Invalid layer type: " + `type(l1)`
        if not isinstance(p1, point.Point):
            raise TypeError, "Invalid point type: " + `type(p1)`
        _lp = l1.findObject(p1)
        if _lp is not p1:
            raise ValueError, "Point p1 not found in layer!"
        if not isinstance(l2, Layer):
            raise TypeError, "Invalid layer type: " + `type(l2)`
        if not isinstance(p2, point.Point):
            raise TypeError, "Invalid point type: " + `type(p2)`
        _lp = l2.findObject(p2)
        if _lp is not p2:
            raise ValueError, "Point p2 not found in layer!"
        super(LinearDimension, self).__init__(x, y, ds, **kw)
        self.__l1 = l1
        self.__p1 = p1
        self.__l2 = l2
        self.__p2 = p2
        self.__bar1 = DimBar()
        self.__bar2 = DimBar()
        self.__crossbar = DimCrossbar()
        p1.storeUser(self)
        p1.connect('moved', self._movePoint)
        p2.storeUser(self)
        p2.connect('moved', self._movePoint)
        self.calcDimValues()

    def __eq__(self, ldim):
        """Test two LinearDimension objects for equality.
        """
        if not isinstance(ldim, LinearDimension):
            return False
        _l1, _l2 = ldim.getDimLayers()
        _p1, _p2 = ldim.getDimPoints()
        if (self.__l1 is _l1 and
            self.__l2 is _l2 and
            self.__p1 == _p1 and
            self.__p2 == _p2):
            return True
        if (self.__l1 is _l2 and
            self.__l2 is _l1 and
            self.__p1 == _p2 and
            self.__p2 == _p1):
            return True
        return False

    def __ne__(self, ldim):
        """Test two LinearDimension objects for equality.
        """
        if not isinstance(ldim, LinearDimension):
            return True
        _l1, _l2 = ldim.getDimLayers()
        _p1, _p2 = ldim.getDimPoints()
        if (self.__l1 is _l1 and
            self.__l2 is _l2 and
            self.__p1 == _p1 and
            self.__p2 == _p2):
            return False
        if (self.__l1 is _l2 and
            self.__l2 is _l1 and
            self.__p1 == _p2 and
            self.__p2 == _p1):
            return False
        return True

    def finish(self):
        self.__p1.disconnect(self)
        self.__p1.freeUser(self)
        self.__p2.disconnect(self)
        self.__p2.freeUser(self)
        self.__bar1 = self.__bar2 = self.__crossbar = None
        self.__p1 = self.__p2 = self.__l1 = self.__l2 = None
        super(LinearDimension, self).finish()

    def getValues(self):
        """Return values comprising the LinearDimension.

getValues()

This method extends the Dimension::getValues() method.
        """
        _data = super(LinearDimension, self).getValues()
        _data.setValue('type', 'ldim')
        _data.setValue('l1', self.__l1.getID())
        _data.setValue('p1', self.__p1.getID())
        _data.setValue('l2', self.__l2.getID())
        _data.setValue('p2', self.__p2.getID())
        return _data

    def getP1(self):
        """Return the first Point of a LinearDimension.

getP1()
        """
        return self.__p1

    def setP1(self, l, p):
        """Set the first Point of a LinearDimension.

setP1(l, p)

There are two required arguments for this method

l: The layer holding the Point p
p: A point in Layer l
        """
        if self.isLocked():
            raise RuntimeError, "Setting point not allowed - object locked."
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l, Layer):
            raise TypeError, "Invalid layer type: " + `type(l)`
        if not isinstance(p, point.Point):
            raise TypeError, "Invalid point type: " + `type(p)`
        _lp = l.findObject(p)
        if _lp is not p:
            raise ValueError, "Point not found in layer!"
        _pt = self.__p1
        if _pt is not p:
            _pt.disconnect(self)
            _pt.freeUser(self)
            self.__l1 = l
            self.__p1 = p
            self.sendMessage('point_changed', _pt, p)
            p.storeUser(self)
            p.connect('moved', self._movePoint)
            if abs(_pt.x - p.x) > 1e-10 or abs(_pt.y - p.y) > 1e-10:
                _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
                self.calcDimValues()
                self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    p1 = property(getP1, None, None, "Dimension first point.")

    def getP2(self):
        """Return the second point of a LinearDimension.

getP2()
        """
        return self.__p2

    def setP2(self, l, p):
        """Set the second Point of a LinearDimension.

setP2(l, p)

There are two required arguments for this method

l: The layer holding the Point p
p: A point in Layer l
        """
        if self.isLocked():
            raise RuntimeError, "Setting point not allowed - object locked."
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l, Layer):
            raise TypeError, "Invalid layer type: " + `type(l)`
        if not isinstance(p, point.Point):
            raise TypeError, "Invalid point type: " + `type(p)`
        _lp = l.findObject(p)
        if _lp is not p:
            raise ValueError, "Point not found in layer!"
        _pt = self.__p2
        if _pt is not p:
            _pt.disconnect(self)
            _pt.freeUser(self)
            self.__l2 = l
            self.__p2 = p
            self.sendMessage('point_changed', _pt, p)
            p.storeUser(self)
            p.connect('moved', self._movePoint)
            if abs(_pt.x - p.x) > 1e-10 or abs(_pt.y - p.y) > 1e-10:
                _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
                self.calcDimValues()
                self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)
            self.modified()

    p2 = property(getP2, None, None, "Dimension second point.")

    def getDimPoints(self):
        """Return both points used in the LinearDimension.

getDimPoints()

The two points are returned in a tuple.
        """
        return self.__p1, self.__p2

    def getDimBars(self):
        """Return the dimension boundary bars.

getDimBars()
        """
        return self.__bar1, self.__bar2

    def getDimCrossbar(self):
        """Return the dimension crossbar.

getDimCrossbar()
        """
        return self.__crossbar

    def getDimLayers(self):
        """Return both layers used in the LinearDimension.

getDimLayers()

The two layers are returned in a tuple.
        """
        return self.__l1, self.__l2

    def calculate(self):
        """Determine the length of this LinearDimension.

calculate()
        """
        return self.__p1 - self.__p2

    def inRegion(self, xmin, ymin, xmax, ymax, fully=False):
        """Return whether or not a LinearDimension exists within a region.

isRegion(xmin, ymin, xmax, ymax[, fully])

The four arguments define the boundary of an area, and the
function returns True if the LinearDimension lies within that
area. If the optional argument fully is used and is True,
then the dimension points and the location of the dimension
text must lie within the boundary. Otherwise, the function
returns False.
        """
        _xmin = util.get_float(xmin)
        _ymin = util.get_float(ymin)
        _xmax = util.get_float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = util.get_float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        util.test_boolean(fully)
        _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
        if ((_dxmin > _xmax) or
            (_dymin > _ymax) or
            (_dxmax < _xmin) or
            (_dymax < _ymin)):
            return False
        if fully:
            if ((_dxmin > _xmin) and
                (_dymin > _ymin) and
                (_dxmax < _xmax) and
                (_dymax < _ymax)):
                return True
            return False
        _dx, _dy = self.getLocation()
        if _xmin < _dx < _xmax and _ymin < _dy < _ymax: # dim text
            return True
        #
        # bar at p1
        #
        _ep1, _ep2 = self.__bar1.getEndpoints()
        _x1, _y1 = _ep1
        _x2, _y2 = _ep2
        if util.in_region(_x1, _y1, _x2, _y2, _xmin, _ymin, _xmax, _ymax):
            return True
        #
        # bar at p2
        #
        _ep1, _ep2 = self.__bar2.getEndpoints()
        _x1, _y1 = _ep1
        _x2, _y2 = _ep2
        if util.in_region(_x1, _y1, _x2, _y2, _xmin, _ymin, _xmax, _ymax):
            return True
        #
        # crossbar
        #
        _ep1, _ep2 = self.__crossbar.getEndpoints()
        _x1, _y1 = _ep1
        _x2, _y2 = _ep2
        return util.in_region(_x1, _y1, _x2, _y2, _xmin, _ymin, _xmax, _ymax)

    def calcDimValues(self, allpts=True):
        """Recalculate the values for dimensional display.

calcDimValues([allpts])

This method calculates where the points for the dimension
bars and crossbar are located. The argument 'allpts' is
optional. By default it is True. If the argument is set to
False, then the coordinates of the dimension marker points
will not be calculated.
        """
        _allpts = allpts
        util.test_boolean(_allpts)
        _p1, _p2 = self.getDimPoints()
        _bar1 = self.__bar1
        _bar2 = self.__bar2
        _crossbar = self.__crossbar
        _p1x, _p1y = _p1.getCoords()
        _p2x, _p2y = _p2.getCoords()
        _dx, _dy = self.getLocation()
        _offset = self.getOffset()
        _ext = self.getExtension()
        #
        # see comp.graphics.algorithms.faq section on calcuating
        # the distance between a point and line for info about
        # the following equations ...
        #
        _dpx = _p2x - _p1x
        _dpy = _p2y - _p1y
        _rnum = ((_dx - _p1x) * _dpx) + ((_dy - _p1y) * _dpy)
        _snum = ((_p1y - _dy) * _dpx) - ((_p1x - _dx) * _dpy)
        _den = pow(_dpx, 2) + pow(_dpy, 2)
        _r = _rnum/_den
        _s = _snum/_den
        _sep = abs(_s) * math.sqrt(_den)
        if abs(_dpx) < 1e-10: # vertical
            if _p2y > _p1y:
                _slope = math.pi/2.0
            else:
                _slope = -math.pi/2.0
        elif abs(_dpy) < 1e-10: # horizontal
            if _p2x > _p1x:
                _slope = 0.0
            else:
                _slope = -math.pi
        else:
            _slope = math.atan2(_dpy, _dpx)
        if _s < 0.0: # dim point left of p1-p2 line
            _angle = _slope + (math.pi/2.0)
        else: # dim point right of p1-p2 line (or on it)
            _angle = _slope - (math.pi/2.0)
        _sin_angle = math.sin(_angle)
        _cos_angle = math.cos(_angle)
        _x = _p1x + (_offset * _cos_angle)
        _y = _p1y + (_offset * _sin_angle)
        _bar1.setFirstEndpoint(_x, _y)
        if _r < 0.0:
            _px = _p1x + (_r * _dpx)
            _py = _p1y + (_r * _dpy)
            _x = _px + (_sep * _cos_angle)
            _y = _py + (_sep * _sin_angle)
        else:
            _x = _p1x + (_sep * _cos_angle)
            _y = _p1y + (_sep * _sin_angle)
        _crossbar.setFirstEndpoint(_x, _y)
        _x = _p1x + (_sep * _cos_angle)
        _y = _p1y + (_sep * _sin_angle)
        _crossbar.setFirstCrossbarPoint(_x, _y)
        _x = _p1x + ((_sep + _ext) * _cos_angle)
        _y = _p1y + ((_sep + _ext) * _sin_angle)
        _bar1.setSecondEndpoint(_x, _y)
        _x = _p2x + (_offset * _cos_angle)
        _y = _p2y + (_offset * _sin_angle)
        _bar2.setFirstEndpoint(_x, _y)
        if _r > 1.0:
            _px = _p1x + (_r * _dpx)
            _py = _p1y + (_r * _dpy)
            _x = _px + (_sep * _cos_angle)
            _y = _py + (_sep * _sin_angle)
        else:
            _x = _p2x + (_sep * _cos_angle)
            _y = _p2y + (_sep * _sin_angle)
        _crossbar.setSecondEndpoint(_x, _y)
        _x = _p2x + (_sep * _cos_angle)
        _y = _p2y + (_sep * _sin_angle)
        _crossbar.setSecondCrossbarPoint(_x, _y)
        _x = _p2x + ((_sep + _ext) * _cos_angle)
        _y = _p2y + ((_sep + _ext) * _sin_angle)
        _bar2.setSecondEndpoint(_x, _y)
        if _allpts:
            self.calcMarkerPoints()

    def calcMarkerPoints(self):
        """Calculate and store the dimension endpoint markers coordinates.

calcMarkerPoints()
        """
        _type = self.getEndpointType()
        _crossbar = self.__crossbar
        _crossbar.clearMarkerPoints()
        if _type == Dimension.DIM_ENDPT_NONE or _type == Dimension.DIM_ENDPT_CIRCLE:
            return
        _size = self.getEndpointSize()
        _p1, _p2 = _crossbar.getCrossbarPoints()
        _x1, _y1 = _p1
        _x2, _y2 = _p2
        # print "x1: %g" % _x1
        # print "y1: %g" % _y1
        # print "x2: %g" % _x2
        # print "y2: %g" % _y2
        _sine, _cosine = _crossbar.getSinCosValues()
        if _type == Dimension.DIM_ENDPT_ARROW or _type == Dimension.DIM_ENDPT_FILLED_ARROW:
            _height = _size/5.0
            # p1 -> (x,y) = (size, _height)
            _mx = (_cosine * _size - _sine * _height) + _x1
            _my = (_sine * _size + _cosine * _height) + _y1
            _crossbar.storeMarkerPoint(_mx, _my)
            # p2 -> (x,y) = (size, -_height)
            _mx = (_cosine * _size - _sine *(-_height)) + _x1
            _my = (_sine * _size + _cosine *(-_height)) + _y1
            _crossbar.storeMarkerPoint(_mx, _my)
            # p3 -> (x,y) = (-size, _height)
            _mx = (_cosine * (-_size) - _sine * _height) + _x2
            _my = (_sine * (-_size) + _cosine * _height) + _y2
            _crossbar.storeMarkerPoint(_mx, _my)
            # p4 -> (x,y) = (-size, -_height)
            _mx = (_cosine * (-_size) - _sine *(-_height)) + _x2
            _my = (_sine * (-_size) + _cosine *(-_height)) + _y2
            _crossbar.storeMarkerPoint(_mx, _my)
        elif _type == Dimension.DIM_ENDPT_SLASH:
            _angle = 30.0 * _dtr # slope of slash
            _height = 0.5 * _size * math.sin(_angle)
            _length = 0.5 * _size * math.cos(_angle)
            # p1 -> (x,y) = (-_length, -_height)
            _sx1 = (_cosine * (-_length) - _sine * (-_height))
            _sy1 = (_sine * (-_length) + _cosine * (-_height))
            # p2 -> (x,y) = (_length, _height)
            _sx2 = (_cosine * _length - _sine * _height)
            _sy2 = (_sine * _length + _cosine * _height)
            #
            # shift the calculate based on the location of the
            # marker point
            #
            _mx = _sx1 + _x2
            _my = _sy1 + _y2
            _crossbar.storeMarkerPoint(_mx, _my)
            _mx = _sx2 + _x2
            _my = _sy2 + _y2
            _crossbar.storeMarkerPoint(_mx, _my)
            _mx = _sx1 + _x1
            _my = _sy1 + _y1
            _crossbar.storeMarkerPoint(_mx, _my)
            _mx = _sx2 + _x1
            _my = _sy2 + _y1
            _crossbar.storeMarkerPoint(_mx, _my)
        else:
            raise ValueError, "Unexpected endpoint type: '%s'" % str(_type)

    def mapCoords(self, x, y, tol=tolerance.TOL):
        """Test an x/y coordinate pair if it could lay on the dimension.

mapCoords(x, y[, tol])

This method has two required parameters:

x: The x-coordinate
y: The y-coordinate

These should both be float values.

There is an optional third parameter tol giving the maximum distance
from the dimension bars that the x/y coordinates may lie.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _t = tolerance.toltest(tol)
        _ep1, _ep2 = self.__bar1.getEndpoints()
        #
        # test p1 bar
        #
        _mp = util.map_coords(_x, _y, _ep1[0], _ep1[1], _ep2[0], _ep2[1], _t)
        if _mp is not None:
            return _mp
        #
        # test p2 bar
        #
        _ep1, _ep2 = self.__bar2.getEndpoints()
        _mp = util.map_coords(_x, _y, _ep1[0], _ep1[1], _ep2[0], _ep2[1], _t)
        if _mp is not None:
            return _mp
        #
        # test crossbar
        #
        _ep1, _ep2 = self.__crossbar.getEndpoints()
        return util.map_coords(_x, _y, _ep1[0], _ep1[1], _ep2[0], _ep2[1], _t)

    def onDimension(self, x, y, tol=tolerance.TOL):
        return self.mapCoords(x, y, tol) is not None

    def getBounds(self):
        """Return the minimal and maximal locations of the dimension

getBounds()

This method overrides the Dimension::getBounds() method
        """
        _dx, _dy = self.getLocation()
        _dxpts = []
        _dypts = []
        _ep1, _ep2 = self.__bar1.getEndpoints()
        _dxpts.append(_ep1[0])
        _dypts.append(_ep1[1])
        _dxpts.append(_ep2[0])
        _dypts.append(_ep2[1])
        _ep1, _ep2 = self.__bar2.getEndpoints()
        _dxpts.append(_ep1[0])
        _dypts.append(_ep1[1])
        _dxpts.append(_ep2[0])
        _dypts.append(_ep2[1])
        _ep1, _ep2 = self.__crossbar.getEndpoints()
        _dxpts.append(_ep1[0])
        _dypts.append(_ep1[1])
        _dxpts.append(_ep2[0])
        _dypts.append(_ep2[1])
        _xmin = min(_dx, min(_dxpts))
        _ymin = min(_dy, min(_dypts))
        _xmax = max(_dx, max(_dxpts))
        _ymax = max(_dy, max(_dypts))
        return _xmin, _ymin, _xmax, _ymax

    def _movePoint(self, p, *args):
        _alen = len(args)
        if _alen < 2:
            raise ValueError, "Invalid argument count: %d" % _alen
        if p is not self.__p1 and p is not self.__p2:
            raise ValueError, "Unexpected dimension point: " + `p`
        _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
        self.calcDimValues(True)
        self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)

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

class HorizontalDimension(LinearDimension):
    """A class representing Horizontal dimensions.

This class is derived from the LinearDimension class, so
it shares all those attributes and methods of its parent.
    """
    def __init__(self, l1, p1, l2, p2, x, y, ds=None, **kw):
        """Initialize a Horizontal Dimension.

hdim = HorizontalDimension(l1, p1, l2, p2, x, y, ds)

l1: A Layer holding Point p1
p1: A Point contained in Layer l1
l2: A Layer holding Point p2
p2: A Point contained in Layer l2
x: The x-coordinate of the dimensional text
y: The y-coordinate of the dimensional text
ds: The DimStyle used for this Dimension.
        """
        super(HorizontalDimension, self).__init__(l1, p1, l2, p2, x, y, ds, **kw)

    def getValues(self):
        """Return values comprising the HorizontalDimension.

getValues()

This method extends the LinearDimension::getValues() method.
        """
        _data = super(HorizontalDimension, self).getValues()
        _data.setValue('type', 'hdim')
        return _data

    def calculate(self):
        """Determine the length of this HorizontalDimension.

calculate()
        """
        _p1, _p2 = self.getDimPoints()
        return abs(_p1.x - _p2.x)

    def calcDimValues(self, allpts=True):
        """Recalculate the values for dimensional display.

calcDimValues([allpts])

This method overrides the LinearDimension::calcDimValues() method.
        """
        _allpts = allpts
        util.test_boolean(_allpts)
        _p1, _p2 = self.getDimPoints()
        _bar1, _bar2 = self.getDimBars()
        _crossbar = self.getDimCrossbar()
        _p1x, _p1y = _p1.getCoords()
        _p2x, _p2y = _p2.getCoords()
        _dx, _dy = self.getLocation()
        _offset = self.getOffset()
        _ext = self.getExtension()
        _crossbar.setFirstEndpoint(_p1x, _dy)
        _crossbar.setSecondEndpoint(_p2x, _dy)
        if _dx < min(_p1x, _p2x) or _dx > max(_p1x, _p2x):
            if _p1x < _p2x:
                if _dx < _p1x:
                    _crossbar.setFirstEndpoint(_dx, _dy)
                if _dx > _p2x:
                    _crossbar.setSecondEndpoint(_dx, _dy)
            else:
                if _dx < _p2x:
                    _crossbar.setSecondEndpoint(_dx, _dy)
                if _dx > _p1x:
                    _crossbar.setFirstEndpoint(_dx, _dy)
        _crossbar.setFirstCrossbarPoint(_p1x, _dy)
        _crossbar.setSecondCrossbarPoint(_p2x, _dy)
        if _dy < min(_p1y, _p2y):
            _bar1.setFirstEndpoint(_p1x, (_p1y - _offset))
            _bar1.setSecondEndpoint(_p1x, (_dy - _ext))
            _bar2.setFirstEndpoint(_p2x, (_p2y - _offset))
            _bar2.setSecondEndpoint(_p2x, (_dy - _ext))
        elif _dy > max(_p1y, _p2y):
            _bar1.setFirstEndpoint(_p1x, (_p1y + _offset))
            _bar1.setSecondEndpoint(_p1x, (_dy + _ext))
            _bar2.setFirstEndpoint(_p2x, (_p2y + _offset))
            _bar2.setSecondEndpoint(_p2x, (_dy + _ext))
        else:
            if _dy > _p1y:
                _bar1.setFirstEndpoint(_p1x, (_p1y + _offset))
                _bar1.setSecondEndpoint(_p1x, (_dy + _ext))
            else:
                _bar1.setFirstEndpoint(_p1x, (_p1y - _offset))
                _bar1.setSecondEndpoint(_p1x, (_dy - _ext))
            if _dy > _p2y:
                _bar2.setFirstEndpoint(_p2x, (_p2y + _offset))
                _bar2.setSecondEndpoint(_p2x, (_dy + _ext))
            else:
                _bar2.setFirstEndpoint(_p2x, (_p2y - _offset))
                _bar2.setSecondEndpoint(_p2x, (_dy - _ext))
        if _allpts:
            self.calcMarkerPoints()

class VerticalDimension(LinearDimension):
    """A class representing Vertical dimensions.

This class is derived from the LinearDimension class, so
it shares all those attributes and methods of its parent.
    """

    def __init__(self, l1, p1, l2, p2, x, y, ds=None, **kw):
        """Initialize a Vertical Dimension.

vdim = VerticalDimension(l1, p1, l2, p2, x, y, ds)

l1: A Layer holding Point p1
p1: A Point contained in Layer l1
l2: A Layer holding Point p2
p2: A Point contained in Layer l2
x: The x-coordinate of the dimensional text
y: The y-coordinate of the dimensional text
ds: The DimStyle used for this Dimension.
        """
        super(VerticalDimension, self).__init__(l1, p1, l2, p2, x, y, ds, **kw)

    def getValues(self):
        """Return values comprising the VerticalDimension.

getValues()

This method extends the LinearDimension::getValues() method.
        """
        _data = super(VerticalDimension, self).getValues()
        _data.setValue('type', 'vdim')
        return _data

    def calculate(self):
        """Determine the length of this VerticalDimension.

calculate()
        """
        _p1, _p2 = self.getDimPoints()
        return abs(_p1.y - _p2.y)

    def calcDimValues(self, allpts=True):
        """Recalculate the values for dimensional display.

calcDimValues([allpts])

This method overrides the LinearDimension::calcDimValues() method.
        """
        _allpts = allpts
        util.test_boolean(_allpts)
        _p1, _p2 = self.getDimPoints()
        _bar1, _bar2 = self.getDimBars()
        _crossbar = self.getDimCrossbar()
        _p1x, _p1y = _p1.getCoords()
        _p2x, _p2y = _p2.getCoords()
        _dx, _dy = self.getLocation()
        _offset = self.getOffset()
        _ext = self.getExtension()
        _crossbar.setFirstEndpoint(_dx, _p1y)
        _crossbar.setSecondEndpoint(_dx, _p2y)
        if _dy < min(_p1y, _p2y) or _dy > max(_p1y, _p2y):
            if _p1y < _p2y:
                if _dy < _p1y:
                    _crossbar.setFirstEndpoint(_dx, _dy)
                if _dy > _p2y:
                    _crossbar.setSecondEndpoint(_dx, _dy)
            if _p2y < _p1y:
                if _dy < _p2y:
                    _crossbar.setSecondEndpoint(_dx, _dy)
                if _dy > _p1y:
                    _crossbar.setFirstEndpoint(_dx, _dy)
        _crossbar.setFirstCrossbarPoint(_dx, _p1y)
        _crossbar.setSecondCrossbarPoint(_dx, _p2y)
        if _dx < min(_p1x, _p2x):
            _bar1.setFirstEndpoint((_p1x - _offset), _p1y)
            _bar1.setSecondEndpoint((_dx - _ext), _p1y)
            _bar2.setFirstEndpoint((_p2x - _offset), _p2y)
            _bar2.setSecondEndpoint((_dx - _ext), _p2y)
        elif _dx > max(_p1x, _p2x):
            _bar1.setFirstEndpoint((_p1x + _offset), _p1y)
            _bar1.setSecondEndpoint((_dx + _ext), _p1y)
            _bar2.setFirstEndpoint((_p2x + _offset), _p2y)
            _bar2.setSecondEndpoint((_dx + _ext), _p2y)
        else:
            if _dx > _p1x:
                _bar1.setFirstEndpoint((_p1x + _offset), _p1y)
                _bar1.setSecondEndpoint((_dx + _ext), _p1y)
            else:
                _bar1.setFirstEndpoint((_p1x - _offset), _p1y)
                _bar1.setSecondEndpoint((_dx - _ext), _p1y)
            if _dx > _p2x:
                _bar2.setFirstEndpoint((_p2x + _offset), _p2y)
                _bar2.setSecondEndpoint((_dx + _ext), _p2y)
            else:
                _bar2.setFirstEndpoint((_p2x - _offset), _p2y)
                _bar2.setSecondEndpoint((_dx - _ext), _p2y)
        if _allpts:
            self.calcMarkerPoints()

class RadialDimension(Dimension):
    """A class for Radial dimensions.

The RadialDimension class is derived from the Dimension
class, so it shares all of those methods and attributes.
A RadialDimension should be used to display either the
radius or diamter of a Circle object.

A RadialDimension object has the following methods:

{get/set}DimCircle(): Get/Set the measured circle object.
getDimLayer(): Return the layer containing the measured circle.
{get/set}DiaMode(): Get/Set if the RadialDimension should return diameters.
getDimXPoints(): Get the x-coordinates of the dimension bar positions.
getDimYPoints(): Get the y-coordinates of the dimension bar positions.
getDimMarkerPoints(): Get the locaiton of the dimension endpoint markers.
getDimCrossbar(): Get the DimCrossbar object of the RadialDimension.
calcDimValues(): Calculate the endpoint of the dimension line.
mapCoords(): Return coordinates on the dimension near some point.
onDimension(): Test if an x/y coordinate pair fall on the dimension line.
    """
    messages = {
        'dimobj_changed' : True,
        'dia_mode_changed' : True,
    }
    def __init__(self, lyr, cir, x, y, ds=None, **kw):
        """Initialize a RadialDimension object.

rdim = RadialDimension(cl, cir, x, y, ds)

lyr: A Layer object
cir: A Circle or Arc object
x: The x-coordinate of the dimensional text
y: The y-coordinate of the dimensional text
ds: The DimStyle used for this Dimension.
        """
        super(RadialDimension, self).__init__(x, y, ds, **kw)
        from PythonCAD.Generic.layer import Layer
        if not isinstance(lyr, Layer):
            raise TypeError, "Invalid layer type: " + `type(lyr)`
        if not isinstance(cir, (circle.Circle, arc.Arc)):
            raise TypeError, "Invalid circle/arc type: " + `type(cir)`
        _lc = lyr.findObject(cir)
        if _lc is not cir:
            raise ValueError, "Circle not found in layer!"
        self.__layer = lyr
        self.__circle = cir
        self.__crossbar = DimCrossbar()
        self.__dia_mode = False
        cir.storeUser(self)
        _pds, _sds = self.getDimstrings()
        _pds.mute()
        try:
            _pds.setPrefix(ds.getValue('RADIAL_DIM_PRIMARY_PREFIX'))
            _pds.setSuffix(ds.getValue('RADIAL_DIM_PRIMARY_SUFFIX'))
        finally:
            _pds.unmute()
        _sds.mute()
        try:
            _sds.setPrefix(ds.getValue('RADIAL_DIM_SECONDARY_PREFIX'))
            _sds.setSuffix(ds.getValue('RADIAL_DIM_SECONDARY_SUFFIX'))
        finally:
            _sds.unmute()
        self.setDiaMode(ds.getValue('RADIAL_DIM_DIA_MODE'))
        cir.connect('moved', self._moveCircle)
        cir.connect('radius_changed', self._radiusChanged)
        self.calcDimValues()

    def __eq__(self, rdim):
        """Compare two RadialDimensions for equality.
        """
        if not isinstance(rdim, RadialDimension):
            return False
        _val = False
        _rc = rdim.getDimCircle()
        _rl = rdim.getDimLayer()
        if self.__layer is _rl and self.__circle == _rc:
            _val = True
        return _val

    def __ne__(self, rdim):
        """Compare two RadialDimensions for inequality.
        """
        if not isinstance(rdim, RadialDimension):
            return True
        _val = True
        _rc = rdim.getDimCircle()
        _rl = rdim.getDimLayer()
        if self.__layer is _rl and self.__circle == _rc:
            _val = False
        return _val

    def finish(self):
        self.__circle.disconnect(self)
        self.__circle.freeUser(self)
        self.__circle = self.__layer = self.__crossbar = None
        super(RadialDimension, self).finish()

    def getValues(self):
        """Return values comprising the RadialDimension.

getValues()

This method extends the Dimension::getValues() method.
        """
        _data = super(RadialDimension, self).getValues()
        _data.setValue('type', 'rdim')
        _data.setValue('layer', self.__layer.getID())
        _data.setValue('circle', self.__circle.getID())
        return _data

    def getDiaMode(self):
        """Return if the RadialDimension will return diametrical values.

getDiaMode()

This method returns True if the diameter value is returned,
and False otherwise.
        """
        return self.__dia_mode

    def setDiaMode(self, mode=False):
        """Set the RadialDimension to return diametrical values.

setDiaMode([mode])

Calling this method without an argument sets the RadialDimension
to return radial measurements. If the argument "mode" is supplied,
it should be either True or False.

If the RadialDimension is measuring an arc, the returned value
will always be set to return a radius.
        """
        if mode is True or mode is False:
            if not isinstance(self.__circle, arc.Arc):
                _m = self.__dia_mode
                if _m is not mode:
                    self.__dia_mode = mode
                    self.sendMessage('dia_mode_changed', _m)
                    self.calcDimValues()
                    self.modified()
        else:
            raise ValueError, "Invalid diameter mode: " + str(mode)

    dia_mode = property(getDiaMode, setDiaMode, None,
                        "Draw the Dimension as a diameter")

    def getDimLayer(self):
        """Return the Layer object holding the Circle for this RadialDimension.

getDimLayer()
        """
        return self.__layer

    def getDimCircle(self):
        """Return the Circle object this RadialDimension is measuring.

getDimCircle()
        """
        return self.__circle

    def setDimCircle(self, l, c):
        """Set the Circle object measured by this RadialDimension.

setDimCircle(l, c)

The arguments for this method are:

l: A Layer containing circle c
c: A circle contained in layer l
        """
        if self.isLocked():
            raise RuntimeError, "Setting circle/arc not allowed - object locked."
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l, Layer):
            raise TypeError, "Invalid layer type: " + `type(l)`
        if not isinstance(c, (circle.Circle, arc.Arc)):
            raise TypeError, "Invalid circle/arc type: " + `type(c)`
        _lc = l.findObject(c)
        if _lc is not c:
            raise ValueError, "Circle not found in layer!"
        _circ = self.__circle
        if _circ is not c:
            _circ.disconnect(self)
            _circ.freeUser(self)
            self.__layer = l
            self.__circle = c
            c.storeUser(self)
            self.sendMessage('dimobj_changed', _circ, c)
            c.connect('moved', self._moveCircle)
            c.connect('radius_changed', self._radiusChanged)
            self.calcDimValues()
            self.modified()

    circle = property(getDimCircle, None, None,
                      "Radial dimension circle object.")

    def getDimCrossbar(self):
        """Get the DimCrossbar object used by the RadialDimension.

getDimCrossbar()
        """
        return self.__crossbar

    def calcDimValues(self, allpts=True):
        """Recalculate the values for dimensional display.

calcDimValues([allpts])

The optional argument 'allpts' is by default True. Calling
this method with the argument set to False will skip the
calculation of any dimension endpoint marker points.
        """
        _allpts = allpts
        util.test_boolean(_allpts)
        _c = self.__circle
        _dimbar = self.__crossbar
        _cx, _cy = _c.getCenter().getCoords()
        _rad = _c.getRadius()
        _dx, _dy = self.getLocation()
        _dia_mode = self.__dia_mode
        _sep = math.hypot((_dx - _cx), (_dy - _cy))
        _angle = math.atan2((_dy - _cy), (_dx - _cx))
        _sx = _rad * math.cos(_angle)
        _sy = _rad * math.sin(_angle)
        if isinstance(_c, arc.Arc):
            assert _dia_mode is False, "dia_mode for arc radial dimension"
            _sa = _c.getStartAngle()
            _ea = _c.getEndAngle()
            _angle = _rtd * _angle
            if _angle < 0.0:
                _angle = _angle + 360.0
            if not _c.throughAngle(_angle):
                _ep1, _ep2 = _c.getEndpoints()
                if _angle < _sa:
                    _sa = _dtr * _sa
                    _sx = _rad * math.cos(_sa)
                    _sy = _rad * math.sin(_sa)
                    if _sep > _rad:
                        _dx = _cx + (_sep * math.cos(_sa))
                        _dy = _cy + (_sep * math.sin(_sa))
                if _angle > _ea:
                    _ea = _dtr * _ea
                    _sx = _rad * math.cos(_ea)
                    _sy = _rad * math.sin(_ea)
                    if _sep > _rad:
                        _dx = _cx + (_sep * math.cos(_ea))
                        _dy = _cy + (_sep * math.sin(_ea))
        if _dia_mode:
            _dimbar.setFirstEndpoint((_cx - _sx), (_cy - _sy))
            _dimbar.setFirstCrossbarPoint((_cx - _sx), (_cy - _sy))
        else:
            _dimbar.setFirstEndpoint(_cx, _cy)
            _dimbar.setFirstCrossbarPoint(_cx, _cy)
        if _sep > _rad:
            _dimbar.setSecondEndpoint(_dx, _dy)
        else:
            _dimbar.setSecondEndpoint((_cx + _sx), (_cy + _sy))
        _dimbar.setSecondCrossbarPoint((_cx + _sx), (_cy + _sy))
        if not _allpts:
            return
        #
        # calculate dimension endpoint marker coordinates
        #
        _type = self.getEndpointType()
        _dimbar.clearMarkerPoints()
        if _type == Dimension.DIM_ENDPT_NONE or _type == Dimension.DIM_ENDPT_CIRCLE:
            return
        _size = self.getEndpointSize()
        _x1, _y1 = _dimbar.getFirstCrossbarPoint()
        _x2, _y2 = _dimbar.getSecondCrossbarPoint()
        _sine, _cosine = _dimbar.getSinCosValues()
        if _type == Dimension.DIM_ENDPT_ARROW or _type == Dimension.DIM_ENDPT_FILLED_ARROW:
            _height = _size/5.0
            # p1 -> (x,y) = (size, _height)
            _mx = (_cosine * _size - _sine * _height) + _x1
            _my = (_sine * _size + _cosine * _height) + _y1
            _dimbar.storeMarkerPoint(_mx, _my)
            # p2 -> (x,y) = (size, -_height)
            _mx = (_cosine * _size - _sine *(-_height)) + _x1
            _my = (_sine * _size + _cosine *(-_height)) + _y1
            _dimbar.storeMarkerPoint(_mx, _my)
            # p3 -> (x,y) = (-size, _height)
            _mx = (_cosine * (-_size) - _sine * _height) + _x2
            _my = (_sine * (-_size) + _cosine * _height) + _y2
            _dimbar.storeMarkerPoint(_mx, _my)
            # p4 -> (x,y) = (-size, -_height)
            _mx = (_cosine * (-_size) - _sine *(-_height)) + _x2
            _my = (_sine * (-_size) + _cosine *(-_height)) + _y2
            _dimbar.storeMarkerPoint(_mx, _my)
        elif _type == Dimension.DIM_ENDPT_SLASH:
            _angle = 30.0 * _dtr # slope of slash
            _height = 0.5 * _size * math.sin(_angle)
            _length = 0.5 * _size * math.cos(_angle)
            # p1 -> (x,y) = (-_length, -_height)
            _sx1 = (_cosine * (-_length) - _sine * (-_height))
            _sy1 = (_sine * (-_length) + _cosine * (-_height))
            # p2 -> (x,y) = (_length, _height)
            _sx2 = (_cosine * _length - _sine * _height)
            _sy2 = (_sine * _length + _cosine * _height)
            #
            # shift the calculate based on the location of the
            # marker point
            #
            _mx = _sx1 + _x1
            _my = _sy1 + _y1
            _dimbar.storeMarkerPoint(_mx, _my)
            _mx = _sx2 + _x1
            _my = _sy2 + _y1
            _dimbar.storeMarkerPoint(_mx, _my)
            _mx = _sx1 + _x2
            _my = _sy1 + _y2
            _dimbar.storeMarkerPoint(_mx, _my)
            _mx = _sx2 + _x2
            _my = _sy2 + _y2
            _dimbar.storeMarkerPoint(_mx, _my)
        else:
            raise ValueError, "Unexpected endpoint type: '%s'" % str(_type)

    def calculate(self):
        """Return the radius or diamter of this RadialDimension.

calculate()

By default, a RadialDimension will return the radius of the
circle. The setDiaMode() method can be called to set the
returned value to corresponed to a diameter.
        """
        _val = self.__circle.getRadius()
        if self.__dia_mode is True:
            _val = _val * 2.0
        return _val

    def inRegion(self, xmin, ymin, xmax, ymax, fully=False):
        """Return whether or not a RadialDimension exists within a region.

isRegion(xmin, ymin, xmax, ymax[, fully])

The four arguments define the boundary of an area, and the
function returns True if the RadialDimension lies within that
area. If the optional argument 'fully' is used and is True,
then the dimensioned circle and the location of the dimension
text must lie within the boundary. Otherwise, the function
returns False.
        """
        _xmin = util.get_float(xmin)
        _ymin = util.get_float(ymin)
        _xmax = util.get_float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = util.get_float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        util.test_boolean(fully)
        _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
        if ((_dxmin > _xmax) or
            (_dymin > _ymax) or
            (_dxmax < _xmin) or
            (_dymax < _ymin)):
            return False
        if fully:
            if ((_dxmin > _xmin) and
                (_dymin > _ymin) and
                (_dxmax < _xmax) and
                (_dymax < _ymax)):
                return True
            return False
        _dx, _dy = self.getLocation()
        if _xmin < _dx < _xmax and _ymin < _dy < _ymax: # dim text
            return True
        _p1, _p2 = self.__crossbar.getEndpoints()
        _x1, _y1 = _p1
        _x2, _y2 = _p2
        return util.in_region(_x1, _y1, _x2, _y2, _xmin, _ymin, _xmax, _ymax)

    def mapCoords(self, x, y, tol=tolerance.TOL):
        """Test an x/y coordinate pair if it could lay on the dimension.

mapCoords(x, y[, tol])

This method has two required parameters:

x: The x-coordinate
y: The y-coordinate

These should both be float values.

There is an optional third parameter, 'tol', giving
the maximum distance from the dimension bars that the
x/y coordinates may sit.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _t = tolerance.toltest(tol)
        _p1, _p2 = self.__crossbar.getEndpoints()
        _x1, _y1 = _p1
        _x2, _y2 = _p2
        return util.map_coords(_x, _y, _x1, _y1, _x2, _y2, _t)

    def onDimension(self, x, y, tol=tolerance.TOL):
        return self.mapCoords(x, y, tol) is not None

    def getBounds(self):
        """Return the minimal and maximal locations of the dimension

getBounds()

This method overrides the Dimension::getBounds() method
        """
        _p1, _p2 = self.__crossbar.getEndpoints()
        _x1, _y1 = _p1
        _x2, _y2 = _p2
        _xmin = min(_x1, _x2)
        _ymin = min(_y1, _y2)
        _xmax = max(_x1, _x2)
        _ymax = max(_y1, _y2)
        return _xmin, _ymin, _xmax, _ymax

    def _moveCircle(self, circ, *args):
        _alen = len(args)
        if _alen < 3:
            raise ValueError, "Invalid argument count: %d" % _alen
        if circ is not self.__circle:
            raise ValueError, "Unexpected sender: " + `circ`
        _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
        self.calcDimValues()
        self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)

    def _radiusChanged(self, circ, *args):
        self.calcDimValues()
        
    def sendsMessage(self, m):
        if m in RadialDimension.messages:
            return True
        return super(RadialDimension, self).sendsMessage(m)

class AngularDimension(Dimension):
    """A class for Angular dimensions.

The AngularDimension class is derived from the Dimension
class, so it shares all of those methods and attributes.

AngularDimension objects have the following methods:

{get/set}VertexPoint(): Get/Set the vertex point for the AngularDimension.
{get/set}P1(): Get/Set the first Point for the AngularDimension.
{get/set}P2(): Get/Set the second Point for the AngularDimension.
getDimPoints(): Return the two Points used in this dimension.
getDimLayers(): Return the two Layers holding the Points.
getDimXPoints(): Get the x-coordinates of the dimension bar positions.
getDimYPoints(): Get the y-coordinates of the dimension bar positions.
getDimAngles(): Get the angles at which the dimension bars should be drawn.
getDimMarkerPoints(): Get the locaiton of the dimension endpoint markers.
calcDimValues(): Calculate the endpoint of the dimension line.
mapCoords(): Return coordinates on the dimension near some point.
onDimension(): Test if an x/y coordinate pair fall on the dimension line.
invert(): Switch the endpoints used to measure the dimension
    """

    messages = {
        'point_changed' : True,
        'inverted' : True,
    }
    def __init__(self, vl, vp, l1, p1, l2, p2, x, y, ds=None, **kw):
        """Initialize an AngularDimension object.

adim = AngularDimension(vl, vp, l1, p1, l2, p2, x, y, ds)

vl: A Layer holding Point vp
vp: A Point contained in layer vl
l1: A Layer holding Point p1
p1: A Point contained in Layer l1
l2: A Layer holding Point p2
p2: A Point contained in Layer l2
x: The x-coordinate of the dimensional text
y: The y-coordinate of the dimensional text
ds: The DimStyle used for this Dimension.
        """
        super(AngularDimension, self).__init__(x, y, ds, **kw)
        from PythonCAD.Generic.layer import Layer
        if not isinstance(vl, Layer):
            raise TypeError, "Invalid layer type: " + `type(vl)`
        if not isinstance(vp, point.Point):
            raise TypeError, "Invalid point type: " + `type(vp)`
        _lp = vl.findObject(vp)
        if _lp is not vp:
            raise ValueError, "Vertex Point not found in layer!"
        if not isinstance(l1, Layer):
            raise TypeError, "Invalid layer type: " + `type(l1)`
        if not isinstance(p1, point.Point):
            raise TypeError, "Invalid point type: " + `type(p1)`
        _lp = l1.findObject(p1)
        if _lp is not p1:
            raise ValueError, "Point p1 not found in layer!"
        if not isinstance(l2, Layer):
            raise TypeError, "Invalid layer type: " + `type(l2)`
        if not isinstance(p2, point.Point):
            raise TypeError, "Invalid point type: " + `type(p2)`
        _lp = l2.findObject(p2)
        if _lp is not p2:
            raise ValueError, "Point p2 not found in layer!"
        self.__vl = vl
        self.__vp = vp
        self.__l1 = l1
        self.__p1 = p1
        self.__l2 = l2
        self.__p2 = p2
        self.__bar1 = DimBar()
        self.__bar2 = DimBar()
        self.__crossarc = DimCrossarc()
        _pds, _sds = self.getDimstrings()
        _pds.mute()
        try:
            _pds.setPrefix(ds.getValue('ANGULAR_DIM_PRIMARY_PREFIX'))
            _pds.setSuffix(ds.getValue('ANGULAR_DIM_PRIMARY_SUFFIX'))
        finally:
            _pds.unmute()
        _sds.mute()
        try:
            _sds.setPrefix(ds.getValue('ANGULAR_DIM_SECONDARY_PREFIX'))
            _sds.setSuffix(ds.getValue('ANGULAR_DIM_SECONDARY_SUFFIX'))
        finally:
            _sds.unmute()
        vp.storeUser(self)
        vp.connect('moved', self._movePoint)
        p1.storeUser(self)
        p1.connect('moved', self._movePoint)
        p2.storeUser(self)
        p2.connect('moved', self._movePoint)
        self.calcDimValues()

    def __eq__(self, adim):
        """Compare two AngularDimensions for equality.
        """
        if not isinstance(adim, AngularDimension):
            return False
        _val = False
        _vl, _l1, _l2 = adim.getDimLayers()
        _vp, _p1, _p2 = adim.getDimPoints()
        if (self.__vl is _vl and
            self.__vp == _vp and
            self.__l1 is _l1 and
            self.__p1 == _p1 and
            self.__l2 is _l2 and
            self.__p2 == _p2):
            _val = True
        return _val

    def __ne__(self, adim):
        """Compare two AngularDimensions for inequality.
        """
        if not isinstance(adim, AngularDimension):
            return True
        _val = True
        _vl, _l1, _l2 = adim.getDimLayers()
        _vp, _p1, _p2 = adim.getDimPoints()
        if (self.__vl is _vl and
            self.__vp == _vp and
            self.__l1 is _l1 and
            self.__p1 == _p1 and
            self.__l2 is _l2 and
            self.__p2 == _p2):
            _val = False
        return _val

    def finish(self):
        self.__vp.disconnect(self)
        self.__vp.freeUser(self)
        self.__p1.disconnect(self)
        self.__p1.freeUser(self)
        self.__p2.disconnect(self)
        self.__p2.freeUser(self)
        self.__bar1 = self.__bar2 = self.__crossarc = None
        self.__vp = self.__p1 = self.__p2 = None
        self.__vl = self.__l1 = self.__l2 = None
        super(AngularDimension, self).finish()

    def getValues(self):
        """Return values comprising the AngularDimension.

getValues()

This method extends the Dimension::getValues() method.
        """
        _data = super(AngularDimension, self).getValues()
        _data.setValue('type', 'adim')
        _data.setValue('vl', self.__vl.getID())
        _data.setValue('vp', self.__vp.getID())
        _data.setValue('l1', self.__l1.getID())
        _data.setValue('p1', self.__p1.getID())
        _data.setValue('l2', self.__l2.getID())
        _data.setValue('p2', self.__p2.getID())
        return _data

    def getDimLayers(self):
        """Return the layers used in an AngularDimension.

getDimLayers()
        """
        return self.__vl, self.__l1, self.__l2

    def getDimPoints(self):
        """Return the points used in an AngularDimension.

getDimPoints()
        """
        return self.__vp, self.__p1, self.__p2

    def getVertexPoint(self):
        """Return the vertex point used in an AngularDimension.

getVertexPoint()
        """
        return self.__vp

    def setVertexPoint(self, l, p):
        """Set the vertex point for an AngularDimension.

setVertexPoint(l, p)

There are two required arguments for this method

l: The layer holding the Point p
p: A point in Layer l
        """
        if self.isLocked():
            raise RuntimeError, "Setting vertex point allowed - object locked."
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l, Layer):
            raise TypeError, "Invalid layer type: " + `type(l)`
        if not isinstance(p, point.Point):
            raise TypeError, "Invalid point type: " + `type(p)`
        _lp = l.findObject(p)
        if _lp is not p:
            raise ValueError, "Point not found in layer!"
        _vp = self.__vp
        if _vp is not p:
            _vp.disconnect(self)
            _vp.freeUser(self)
            self.__vl = l
            self.__vp = p
            p.storeUser(self)
            p.connect('moved', self._movePoint)
            self.sendMessage('point_changed', _vp, p)
            self.calcDimValues()
            if abs(_vp.x - p.x) > 1e-10 or abs(_vp.y - p.y) > 1e-10:
                _x1, _y1 = self.__p1.getCoords()
                _x2, _y2 = self.__p2.getCoords()
                _dx, _dy = self.getLocation()
                self.sendMessage('moved', _vp.x, _vp.y, _x1, _y1,
                                 _x2, _y2, _dx, _dy)
            self.modified()

    vp = property(getVertexPoint, None, None,
                  "Angular Dimension vertex point.")

    def getP1(self):
        """Return the first angle point used in an AngularDimension.

getP1()
        """
        return self.__p1

    def setP1(self, l, p):
        """Set the first Point for an AngularDimension.

setP1(l, p)

There are two required arguments for this method

l: The layer holding the Point p
p: A point in Layer l
        """
        if self.isLocked():
            raise RuntimeError, "Setting vertex point allowed - object locked."
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l, Layer):
            raise TypeError, "Invalid layer type: " + `type(l)`
        if not isinstance(p, point.Point):
            raise TypeError, "Invalid point type: " + `type(p)`
        _lp = l.findObject(p)
        if _lp is not p:
            raise ValueError, "Point not found in layer!"
        _p1 = self.__p1
        if _p1 is not p:
            _p1.disconnect(self)
            _p1.freeUser(self)
            self.__l1 = l
            self.__p1 = p
            p.storeUser(self)
            p.connect('moved', self._movePoint)
            self.sendMessage('point_changed', _p1, p)
            self.calcDimValues()
            if abs(_p1.x - p.x) > 1e-10 or abs(_p1.y - p.y) > 1e-10:
                _vx, _vy = self.__vp.getCoords()
                _x2, _y2 = self.__p2.getCoords()
                _dx, _dy = self.getLocation()
                self.sendMessage('moved', _vx, _vy, _p1.x, _p1.y,
                                 _x2, _y2, _dx, _dy)
            self.modified()

    p1 = property(getP1, None, None, "Dimension first point.")

    def getP2(self):
        """Return the second angle point used in an AngularDimension.

getP2()
        """
        return self.__p2

    def setP2(self, l, p):
        """Set the second Point for an AngularDimension.

setP2(l, p)

There are two required arguments for this method

l: The layer holding the Point p
p: A point in Layer l
        """
        if self.isLocked():
            raise RuntimeError, "Setting vertex point allowed - object locked."
        from PythonCAD.Generic.layer import Layer
        if not isinstance(l, Layer):
            raise TypeError, "Invalid layer type: " + `type(l)`
        if not isinstance(p, point.Point):
            raise TypeError, "Invalid point type: " + `type(p)`
        _lp = l.findObject(p)
        if _lp is not p:
            raise ValueError, "Point not found in layer!"
        _p2 = self.__p2
        if _p2 is not p:
            _p2.disconnect(self)
            _p2.freeUser(self)
            self.__l2 = l
            self.__p2 = p
            p.storeUser(self)
            p.connect('moved', self._movePoint)
            self.sendMessage('point_changed', _p2, p)
            self.calcDimValues()
            if abs(_p2.x - p.x) > 1e-10 or abs(_p2.y - p.y) > 1e-10:
                _vx, _vy = self.__vp.getCoords()
                _x1, _y1 = self.__p1.getCoords()
                _dx, _dy = self.getLocation()
                self.sendMessage('moved', _vx, _vy, _x1, _y1,
                                 _p2.x, _p2.y, _dx, _dy)
            self.modified()


    p2 = property(getP2, None, None, "Dimension second point.")

    def getDimAngles(self):
        """Get the array of dimension bar angles.

geDimAngles()
        """
        _angle1 = self.__bar1.getAngle()
        _angle2 = self.__bar2.getAngle()
        return _angle1, _angle2

    def getDimRadius(self):
        """Get the radius of the dimension crossarc.

getDimRadius()
        """
        return self.__crossarc.getRadius()

    def getDimBars(self):
        """Return the dimension boundary bars.

getDimBars()
        """
        return self.__bar1, self.__bar2

    def getDimCrossarc(self):
        """Get the DimCrossarc object used by the AngularDimension.

getDimCrossarc()
        """
        return self.__crossarc

    def invert(self):
        """Switch the endpoints used in this object.

invert()

Invoking this method on an AngularDimension will result in
it measuring the opposite angle than what it currently measures.
        """
        _ltemp = self.__l1
        _ptemp = self.__p1
        self.__l1 = self.__l2
        self.__p1 = self.__p2
        self.__l2 = _ltemp
        self.__p2 = _ptemp
        self.sendMessage('inverted')
        self.modified()

    def calculate(self):
        """Find the value of the angle measured by this AngularDimension.

calculate()
        """
        _vx, _vy = self.__vp.getCoords()
        _p1x, _p1y = self.__p1.getCoords()
        _p2x, _p2y = self.__p2.getCoords()
        _a1 = _rtd * math.atan2((_p1y - _vy), (_p1x - _vx))
        if _a1 < 0.0:
            _a1 = _a1 + 360.0
        _a2 = _rtd * math.atan2((_p2y - _vy), (_p2x - _vx))
        if _a2 < 0.0:
            _a2 = _a2 + 360.0
        _val = _a2 - _a1
        if _a1 > _a2:
            _val = _val + 360.0
        return _val

    def inRegion(self, xmin, ymin, xmax, ymax, fully=False):
        """Return whether or not an AngularDimension exists within a region.

isRegion(xmin, ymin, xmax, ymax[, fully])

The four arguments define the boundary of an area, and the
function returns True if the RadialDimension lies within that
area. If the optional argument 'fully' is used and is True,
then the dimensioned circle and the location of the dimension
text must lie within the boundary. Otherwise, the function
returns False.
        """
        _xmin = util.get_float(xmin)
        _ymin = util.get_float(ymin)
        _xmax = util.get_float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = util.get_float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        util.test_boolean(fully)
        _vx, _vy = self.__vp.getCoords()
        _dx, _dy = self.getLocation()
        _pxmin, _pymin, _pxmax, _pymax = self.getBounds()
        _val = False
        if ((_pxmin > _xmax) or
            (_pymin > _ymax) or
            (_pxmax < _xmin) or
            (_pymax < _ymin)):
            return False
        if _xmin < _dx < _xmax and _ymin < _dy < _ymax:
            return True
        #
        # bar on vp-p1 line
        #
        _ep1, _ep2 = self.__bar1.getEndpoints()
        _ex1, _ey1 = _ep1
        _ex2, _ey2 = _ep2
        if util.in_region(_ex1, _ey1, _ex2, _ey2, _xmin, _ymin, _xmax, _ymax):
            return True
        #
        # bar at vp-p2 line
        #
        _ep1, _ep2 = self.__bar2.getEndpoints()
        _ex1, _ey1 = _ep1
        _ex2, _ey2 = _ep2
        if util.in_region(_ex1, _ey1, _ex2, _ey2, _xmin, _ymin, _xmax, _ymax):
            return True
        #
        # dimension crossarc
        #
        _val = False
        _r = self.__crossarc.getRadius()
        _d1 = math.hypot((_xmin - _vx), (_ymin - _vy))
        _d2 = math.hypot((_xmin - _vx), (_ymax - _vy))
        _d3 = math.hypot((_xmax - _vx), (_ymax - _vy))
        _d4 = math.hypot((_xmax - _vx), (_ymin - _vy))
        _dmin = min(_d1, _d2, _d3, _d4)
        _dmax = max(_d1, _d2, _d3, _d4)
        if _xmin < _vx < _xmax and _ymin < _vy < _ymax:
            _dmin = -1e-10
        else:
            if _vx > _xmax and _ymin < _vy < _ymax:
                _dmin = _vx - _xmax
            elif _vx < _xmin and _ymin < _vy < _ymax:
                _dmin = _xmin - _vx
            elif _vy > _ymax and _xmin < _vx < _xmax:
                _dmin = _vy - _ymax
            elif _vy < _ymin and _xmin < _vx < _xmax:
                _dmin = _ymin - _vy
        if _dmin < _r < _dmax:
            _da = _rtd * math.atan2((_ymin - _vy), (_xmin - _vx))
            if _da < 0.0:
                _da = _da + 360.0
            _val = self._throughAngle(_da)
            if _val:
                return _val
            _da = _rtd * math.atan2((_ymin - _vy), (_xmax - _vx))
            if _da < 0.0:
                _da = _da + 360.0
            _val = self._throughAngle(_da)
            if _val:
                return _val
            _da = _rtd * math.atan2((_ymax - _vy), (_xmax - _vx))
            if _da < 0.0:
                _da = _da + 360.0
            _val = self._throughAngle(_da)
            if _val:
                return _val
            _da = _rtd * math.atan2((_ymax - _vy), (_xmin - _vx))
            if _da < 0.0:
                _da = _da + 360.0
            _val = self._throughAngle(_da)
        return _val

    def _throughAngle(self, angle):
        """Test if the angular crossarc exists at a certain angle.

_throughAngle()

This method is private to the AngularDimension class.
        """
        _crossarc = self.__crossarc
        _sa = _crossarc.getStartAngle()
        _ea = _crossarc.getEndAngle()
        _val = True
        if abs(_sa - _ea) > 1e-10:
            if _sa > _ea:
                if angle > _ea and angle < _sa:
                    _val = False
            else:
                if angle > _ea or angle < _sa:
                    _val = False
        return _val

    def calcDimValues(self, allpts=True):
        """Recalculate the values for dimensional display.

calcDimValues([allpts])

The optional argument 'allpts' is by default True. Calling
this method with the argument set to False will skip the
calculation of any dimension endpoint marker points.
        """
        _allpts = allpts
        util.test_boolean(_allpts)
        _vx, _vy = self.__vp.getCoords()
        _p1x, _p1y = self.__p1.getCoords()
        _p2x, _p2y = self.__p2.getCoords()
        _dx, _dy = self.getLocation()
        _offset = self.getOffset()
        _ext = self.getExtension()
        _bar1 = self.__bar1
        _bar2 = self.__bar2
        _crossarc = self.__crossarc
        _dv1 = math.hypot((_p1x - _vx), (_p1y - _vy))
        _dv2 = math.hypot((_p2x - _vx), (_p2y - _vy))
        _ddp = math.hypot((_dx - _vx), (_dy - _vy))
        _crossarc.setRadius(_ddp)
        #
        # first dimension bar
        #
        _angle = math.atan2((_p1y - _vy), (_p1x - _vx))
        _sine = math.sin(_angle)
        _cosine = math.cos(_angle)
        _deg = _angle * _rtd
        if _deg < 0.0:
            _deg = _deg + 360.0
        _crossarc.setStartAngle(_deg)
        _ex = _vx + (_ddp * _cosine)
        _ey = _vy + (_ddp * _sine)
        _crossarc.setFirstCrossbarPoint(_ex, _ey)
        _crossarc.setFirstEndpoint(_ex, _ey)
        if _ddp > _dv1: # dim point is radially further to vp than p1
            _x1 = _p1x + (_offset * _cosine)
            _y1 = _p1y + (_offset * _sine)
            _x2 = _vx + ((_ddp + _ext) * _cosine)
            _y2 = _vy + ((_ddp + _ext) * _sine)
        else: # dim point is radially closer to vp than p1
            _x1 = _p1x - (_offset * _cosine)
            _y1 = _p1y - (_offset * _sine)
            _x2 = _vx + ((_ddp - _ext) * _cosine)
            _y2 = _vy + ((_ddp - _ext) * _sine)
        _bar1.setFirstEndpoint(_x1, _y1)
        _bar1.setSecondEndpoint(_x2, _y2)
        #
        # second dimension bar
        #
        _angle = math.atan2((_p2y - _vy), (_p2x - _vx))
        _sine = math.sin(_angle)
        _cosine = math.cos(_angle)
        _deg = _angle * _rtd
        if _deg < 0.0:
            _deg = _deg + 360.0
        _crossarc.setEndAngle(_deg)
        _ex = _vx + (_ddp * _cosine)
        _ey = _vy + (_ddp * _sine)
        _crossarc.setSecondCrossbarPoint(_ex, _ey)
        _crossarc.setSecondEndpoint(_ex, _ey)
        if _ddp > _dv2: # dim point is radially further to vp than p2
            _x1 = _p2x + (_offset * _cosine)
            _y1 = _p2y + (_offset * _sine)
            _x2 = _vx + ((_ddp + _ext) * _cosine)
            _y2 = _vy + ((_ddp + _ext) * _sine)
        else: # dim point is radially closers to vp than p2
            _x1 = _p2x - (_offset * _cosine)
            _y1 = _p2y - (_offset * _sine)
            _x2 = _vx + ((_ddp - _ext) * _cosine)
            _y2 = _vy + ((_ddp - _ext) * _sine)
        _bar2.setFirstEndpoint(_x1, _y1)
        _bar2.setSecondEndpoint(_x2, _y2)
        if not _allpts:
            return
        #
        # calculate dimension endpoint marker coordinates
        #
        _type = self.getEndpointType()
        _crossarc.clearMarkerPoints()
        if _type == Dimension.DIM_ENDPT_NONE or _type == Dimension.DIM_ENDPT_CIRCLE:
            return
        _size = self.getEndpointSize()
        _a1 = _bar1.getAngle() - 90.0
        _a2 = _bar2.getAngle() - 90.0
        # print "a1: %g" % _a1
        # print "a2: %g" % _a2
        _mp1, _mp2 = _crossarc.getCrossbarPoints()
        _x1, _y1 = _mp1
        _x2, _y2 = _mp2
        # print "x1: %g" % _x1
        # print "y1: %g" % _y1
        # print "x2: %g" % _x2
        # print "y2: %g" % _y2
        _sin1 = math.sin(_dtr * _a1)
        _cos1 = math.cos(_dtr * _a1)
        _sin2 = math.sin(_dtr * _a2)
        _cos2 = math.cos(_dtr * _a2)
        if _type == Dimension.DIM_ENDPT_ARROW or _type == Dimension.DIM_ENDPT_FILLED_ARROW:
            _height = _size/5.0
            # p1 -> (x,y) = (size, _height)
            _mx = (_cos1 * (-_size) - _sin1 * _height) + _x1
            _my = (_sin1 * (-_size) + _cos1 * _height) + _y1
            _crossarc.storeMarkerPoint(_mx, _my)
            # p2 -> (x,y) = (size, -_height)
            _mx = (_cos1 * (-_size) - _sin1 *(-_height)) + _x1
            _my = (_sin1 * (-_size) + _cos1 *(-_height)) + _y1
            _crossarc.storeMarkerPoint(_mx, _my)
            # p3 -> (x,y) = (size, _height)
            _mx = (_cos2 * _size - _sin2 * _height) + _x2
            _my = (_sin2 * _size + _cos2 * _height) + _y2
            _crossarc.storeMarkerPoint(_mx, _my)
            # p4 -> (x,y) = (size, -_height)
            _mx = (_cos2 * _size - _sin2 *(-_height)) + _x2
            _my = (_sin2 * _size + _cos2 *(-_height)) + _y2
            _crossarc.storeMarkerPoint(_mx, _my)
        elif _type == Dimension.DIM_ENDPT_SLASH:
            _angle = 30.0 * _dtr # slope of slash
            _height = 0.5 * _size * math.sin(_angle)
            _length = 0.5 * _size * math.cos(_angle)
            # p1 -> (x,y) = (-_length, -_height)
            _mx = (_cos1 * (-_length) - _sin1 * (-_height)) + _x1
            _my = (_sin1 * (-_length) + _cos1 * (-_height)) + _y1
            _crossarc.storeMarkerPoint(_mx, _my)
            # p2 -> (x,y) = (_length, _height)
            _mx = (_cos1 * _length - _sin1 * _height) + _x1
            _my = (_sin1 * _length + _cos1 * _height) + _y1
            _crossarc.storeMarkerPoint(_mx, _my)
            # p3 -> (x,y) = (-_length, -_height)
            _mx = (_cos2 * (-_length) - _sin2 * (-_height)) + _x2
            _my = (_sin2 * (-_length) + _cos2 * (-_height)) + _y2
            _crossarc.storeMarkerPoint(_mx, _my)
            # p4 -> (x,y) = (_length, _height)
            _mx = (_cos2 * _length - _sin2 * _height) + _x2
            _my = (_sin2 * _length + _cos2 * _height) + _y2
            _crossarc.storeMarkerPoint(_mx, _my)
        else:
            raise ValueError, "Unexpected endpoint type: '%s'" % str(_type)

    def mapCoords(self, x, y, tol=tolerance.TOL):
        """Test an x/y coordinate pair hit the dimension lines and arc.

mapCoords(x, y[, tol])

This method has two required parameters:

x: The x-coordinate
y: The y-coordinate

These should both be float values.

There is an optional third parameter, 'tol', giving
the maximum distance from the dimension bars that the
x/y coordinates may sit.
        """
        _x = util.get_float(x)
        _y = util.get_float(y)
        _t = tolerance.toltest(tol)
        #
        # test vp-p1 bar
        #
        _ep1, _ep2 = self.__bar1.getEndpoints()
        _ex1, _ey1 = _ep1
        _ex2, _ey2 = _ep2
        _mp = util.map_coords(_x, _y, _ex1, _ey1, _ex2, _ey2, _t)
        if _mp is not None:
            return _mp
        #
        # test vp-p2 bar
        #
        _ep1, _ep2 = self.__bar2.getEndpoints()
        _mp = util.map_coords(_x, _y, _ex1, _ey1, _ex2, _ey2, _t)
        if _mp is not None:
            return _mp
        #
        # test the arc
        #
        _vx, _vy = self.__vp.getCoords()
        _psep = math.hypot((_vx - _x), (_vy - y))
        _dx, _dy = self.getLocation()
        _dsep = math.hypot((_vx - _dx), (_vy - _dy))
        if abs(_psep - _dsep) < _t:
            _crossarc = self.__crossarc
            _sa = _crossarc.getStartAngle()
            _ea = _crossarc.getEndAngle()
            _angle = _rtd * math.atan2((_y - _vy), (_x - _vx))
            _val = True
            if abs(_sa - _ea) > 1e-10:
                if _sa < _ea:
                    if _angle < _sa or  _angle > _ea:
                        _val = False
                else:
                    if _angle > _ea or _angle < _sa:
                        _val = False
            if _val:
                _xoff = _dsep * math.cos(_angle)
                _yoff = _dsep * math.sin(_angle)
                return (_vx + _xoff), (_vy + _yoff)
        return None

    def onDimension(self, x, y, tol=tolerance.TOL):
        return self.mapCoords(x, y, tol) is not None

    def getBounds(self):
        """Return the minimal and maximal locations of the dimension

getBounds()

This method overrides the Dimension::getBounds() method
        """
        _vx, _vy = self.__vp.getCoords()
        _dx, _dy = self.getLocation()
        _dxpts = []
        _dypts = []
        _ep1, _ep2 = self.__bar1.getEndpoints()
        _dxpts.append(_ep1[0])
        _dypts.append(_ep1[1])
        _dxpts.append(_ep2[0])
        _dypts.append(_ep2[1])
        _ep1, _ep2 = self.__bar2.getEndpoints()
        _dxpts.append(_ep1[0])
        _dypts.append(_ep1[1])
        _dxpts.append(_ep2[0])
        _dypts.append(_ep2[1])
        _rad = self.__crossarc.getRadius()
        if self._throughAngle(0.0):
            _dxpts.append((_vx + _rad))
        if self._throughAngle(90.0):
            _dypts.append((_vy + _rad))
        if self._throughAngle(180.0):
            _dxpts.append((_vx - _rad))
        if self._throughAngle(270.0):
            _dypts.append((_vy - _rad))
        _xmin = min(_dx, min(_dxpts))
        _ymin = min(_dy, min(_dypts))
        _xmax = max(_dx, max(_dxpts))
        _ymax = max(_dy, max(_dypts))
        return _xmin, _ymin, _xmax, _ymax

    def _movePoint(self, p, *args):
        _alen = len(args)
        if _alen < 2:
            raise ValueError, "Invalid argument count: %d" % _alen
        if ((p is not self.__vp) and
            (p is not self.__p1) and
            (p is not self.__p2)):
            raise ValueError, "Unexpected dimension point: " + `p`
        _dxmin, _dymin, _dxmax, _dymax = self.getBounds()
        self.calcDimValues()
        self.sendMessage('moved', _dxmin, _dymin, _dxmax, _dymax)

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

#
# class stuff for dimension styles
#

dimstyle_defaults = {
    'DIM_PRIMARY_FONT_FAMILY' : 'Sans',
    'DIM_PRIMARY_FONT_SIZE' : 1.0,
    'DIM_PRIMARY_TEXT_SIZE' : 1.0,
    'DIM_PRIMARY_FONT_WEIGHT' : text.TextStyle.FONT_NORMAL,
    'DIM_PRIMARY_FONT_STYLE' : text.TextStyle.FONT_NORMAL,
    'DIM_PRIMARY_FONT_COLOR' : color.Color(255,255,255),
    'DIM_PRIMARY_TEXT_ANGLE' : 0.0,
    'DIM_PRIMARY_TEXT_ALIGNMENT' : text.TextStyle.ALIGN_CENTER,
    'DIM_PRIMARY_PREFIX' : u'',
    'DIM_PRIMARY_SUFFIX' : u'',
    'DIM_PRIMARY_PRECISION' : 3,
    'DIM_PRIMARY_UNITS' : units.MILLIMETERS,
    'DIM_PRIMARY_LEADING_ZERO' : True,
    'DIM_PRIMARY_TRAILING_DECIMAL': True,
    'DIM_SECONDARY_FONT_FAMILY' : 'Sans',
    'DIM_SECONDARY_FONT_SIZE' : 1.0,
    'DIM_SECONDARY_TEXT_SIZE' : 1.0,
    'DIM_SECONDARY_FONT_WEIGHT' : text.TextStyle.FONT_NORMAL,
    'DIM_SECONDARY_FONT_STYLE' : text.TextStyle.FONT_NORMAL,
    'DIM_SECONDARY_FONT_COLOR' : color.Color(255,255,255),
    'DIM_SECONDARY_TEXT_ANGLE' : 0.0,
    'DIM_SECONDARY_TEXT_ALIGNMENT' : text.TextStyle.ALIGN_CENTER,
    'DIM_SECONDARY_PREFIX' : u'',
    'DIM_SECONDARY_SUFFIX' : u'',
    'DIM_SECONDARY_PRECISION' : 3,
    'DIM_SECONDARY_UNITS' : units.MILLIMETERS,
    'DIM_SECONDARY_LEADING_ZERO' : True,
    'DIM_SECONDARY_TRAILING_DECIMAL': True,
    'DIM_OFFSET' : 1.0,
    'DIM_EXTENSION': 1.0,
    'DIM_COLOR' : color.Color(255,165,0),
    'DIM_THICKNESS' : 0.0,
    'DIM_POSITION': Dimension.DIM_TEXT_POS_SPLIT,
    'DIM_ENDPOINT': Dimension.DIM_ENDPT_NONE,
    'DIM_ENDPOINT_SIZE' : 1.0,
    'DIM_DUAL_MODE' : False,
    'DIM_POSITION_OFFSET' : 0.0,
    'DIM_DUAL_MODE_OFFSET' : 1.0,
    'RADIAL_DIM_PRIMARY_PREFIX' : u'',
    'RADIAL_DIM_PRIMARY_SUFFIX' : u'',
    'RADIAL_DIM_SECONDARY_PREFIX' : u'',
    'RADIAL_DIM_SECONDARY_SUFFIX' : u'',
    'RADIAL_DIM_DIA_MODE' : False,
    'ANGULAR_DIM_PRIMARY_PREFIX' : u'',
    'ANGULAR_DIM_PRIMARY_SUFFIX' : u'',
    'ANGULAR_DIM_SECONDARY_PREFIX' : u'',
    'ANGULAR_DIM_SECONDARY_SUFFIX' : u'',
    }

#
# DimString history class
#

class DimStringLog(text.TextBlockLog):
    __setops = {
        'prefix_changed' : DimString.setPrefix,
        'suffix_changed' : DimString.setSuffix,
        'units_changed' : DimString.setUnits,
        'precision_changed' : DimString.setPrecision,
        'print_zero_changed' : DimString.setPrintZero,
        'print_decimal_changed' : DimString.setPrintDecimal,
        'dimension_changed' : DimString.setDimension,
        }

    __getops = {
        'prefix_changed' : DimString.getPrefix,
        'suffix_changed' : DimString.getSuffix,
        'units_changed' : DimString.getUnits,
        'precision_changed' : DimString.getPrecision,
        'print_zero_changed' : DimString.getPrintZero,
        'print_decimal_changed' : DimString.getPrintDecimal,
        'dimension_changed' : DimString.getDimension,
        }

    def __init__(self, obj):
        if not isinstance(obj, DimString):
            raise TypeError, "Invalid DimString type: " + `type(obj)`
        super(DimStringLog, self).__init__(obj)
        _ds = self.getObject()
        _ds.connect('prefix_changed', self._prefixChanged)
        _ds.connect('suffix_changed', self._suffixChanged)
        _ds.connect('units_changed', self._unitsChanged)
        _ds.connect('precision_changed', self._precisionChanged)
        _ds.connect('print_zero_changed', self._printZeroChanged)
        _ds.connect('print_decimal_changed', self._printDecimalChanged)
        _ds.connect('dimension_changed', self._dimensionChanged)

    def _prefixChanged(self, ds, *args):
        # print "prefixChanged() ..."
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _prefix = args[0]
        if not isinstance(_prefix, types.StringTypes):
            raise TypeError, "Invalid prefix type: " + `type(_prefix)`
        # print "old prefix: %s" % _prefix
        self.saveUndoData('prefix_changed', _prefix)

    def _suffixChanged(self, ds, *args):
        # print "suffixChanged() ..."
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _suffix = args[0]
        if not isinstance(_suffix, types.StringTypes):
            raise TypeError, "Invalid suffix type " + `type(_suffix)`
        # print "old suffix: %s" % _suffix
        self.saveUndoData('suffix_changed', _suffix)

    def _unitsChanged(self, ds, *args):
        # print "unitsChanged() ..."
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _units = args[0]
        if not isinstance(_units, int):
            raise TypeError, "Invalid unit type: " + `type(_units)`
        # print "old units: %d" % _units
        self.saveUndoData('units_changed', _units)

    def _precisionChanged(self, ds, *args):
        # print "precisionChanged() ..."
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _prec = args[0]
        if not isinstance(_prec, int):
            raise TypeError, "Invalid precision type: " + `type(_prec)`
        # print "old precision: %d" % _prec
        self.saveUndoData('precision_changed', _prec)

    def _printZeroChanged(self, ds, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _flag = args[0]
        util.test_boolean(_flag)
        self.saveUndoData('print_zero_changed', _flag)

    def _printDecimalChanged(self, ds, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _flag = args[0]
        util.test_boolean(_flag)
        self.saveUndoData('print_decimal_changed', _flag)

    def _dimensionChanged(self, ds, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _dim = args[0]
        if not isinstance(_dim, Dimension):
            raise TypeError, "Invalid dimension type: " + `type(_dim)`
        self.saveUndoData('dimension_changed', _dim.getID())

    def execute(self, undo, *args):
        util.test_boolean(undo)
        _alen = len(args)
        if len(args) == 0:
            raise ValueError, "No arguments to execute()"
        _obj = self.getObject()
        _op = args[0]
        if (_op == 'prefix_changed' or
            _op == 'suffix_changed' or
            _op == 'units_changed' or
            _op == 'precision_changed' or
            _op == 'print_zero_changed' or
            _op == 'print_decimal_changed'):
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _val = args[1]
            _get = DimStringLog.__getops[_op]
            _sdata = _get(_obj)
            self.ignore(_op)
            try:
                _set = DimStringLog.__setops[_op]
                if undo:
                    _obj.startUndo()
                    try:
                        _set(_obj, _val)
                    finally:
                        _obj.endUndo()
                else:
                    _obj.startRedo()
                    try:
                        _set(_obj, _val)
                    finally:
                        _obj.endRedo()
            finally:
                self.receive(_op)
            self.saveData(undo, _op, _sdata)
        elif _op == 'dimension_changed':
            pass # fixme
        else:
            super(DimStringLog, self).execute(undo, *args)

#
# Dimension history class
#

class DimLog(entity.EntityLog):
    __setops = {
        'offset_changed' : Dimension.setOffset,
        'extension_changed' : Dimension.setExtension,
        'endpoint_type_changed' : Dimension.setEndpointType,
        'endpoint_size_changed' : Dimension.setEndpointSize,
        'dual_mode_changed' : Dimension.setDualDimMode,
        'dual_mode_offset_changed' : Dimension.setDualModeOffset,
        'position_changed' : Dimension.setPosition,
        'position_offset_changed' : Dimension.setPositionOffset,
        'thickness_changed' : Dimension.setThickness,
        'dia_mode_changed' : RadialDimension.setDiaMode,
        }

    __getops = {
        'offset_changed' : Dimension.getOffset,
        'extension_changed' : Dimension.getExtension,
        'endpoint_type_changed' : Dimension.getEndpointType,
        'endpoint_size_changed' : Dimension.getEndpointSize,
        'dual_mode_changed' : Dimension.getDualDimMode,
        'dual_mode_offset_changed' : Dimension.getDualModeOffset,
        'position_changed' : Dimension.getPosition,
        'position_offset_changed' : Dimension.getPositionOffset,
        'thickness_changed' : Dimension.getThickness,
        'dia_mode_changed' : RadialDimension.getDiaMode,
        }

    def __init__(self, dim):
        if not isinstance(dim, Dimension):
            raise TypeError, "Invalid dimension type: " + `type(dim)`
        super(DimLog, self).__init__(dim)
        _ds1, _ds2 = dim.getDimstrings()
        _ds1.connect('modified', self._dimstringChanged)
        _ds2.connect('modified', self._dimstringChanged)
        dim.connect('offset_changed', self._offsetChanged)
        dim.connect('extension_changed', self._extensionChanged)
        # 'dimstyle_changed' : True,
        dim.connect('endpoint_type_changed', self._endpointTypeChanged)
        dim.connect('endpoint_size_changed', self._endpointSizeChanged)
        dim.connect('dual_mode_changed', self._dualModeChanged)
        dim.connect('dual_mode_offset_changed', self._dualModeOffsetChanged)
        dim.connect('position_changed', self._positionChanged)
        dim.connect('position_offset_changed', self._positionOffsetChanged)
        dim.connect('color_changed', self._colorChanged)
        dim.connect('thickness_changed', self._thicknessChanged)
        if isinstance(dim, RadialDimension):
            dim.connect('dia_mode_changed', self._diaModeChanged)
        if isinstance(dim, AngularDimension):
            dim.connect('inverted', self._dimInverted)
        # dim.connect('moved', self._moveDim)

    def detatch(self):
        _dim = self.getObject()
        super(DimLog, self).detatch()
        _ds1, _ds2 = _dim.getDimstrings()
        _ds1.disconnect(self)
        _log = _ds1.getLog()
        if _log is not None:
            _log.detatch()
        _ds2.disconnect(self)
        _log = _ds2.getLog()
        if _log is not None:
            _log.detatch()

    def _moveDim(self, dim, *args):
        _alen = len(args)
        if _alen < 4:
            raise ValueError, "Invalid argument count: %d" % _alen
        _xmin = util.get_float(args[0])
        _ymin = util.get_float(args[1])
        _xmax = util.get_float(args[2])
        _ymax = util.get_float(args[3])
        self.saveUndoData('moved', _xmin, _ymin, _xmax, _ymax)

    def _dimstringChanged(self, dstr, *args):
        _dim = self.getObject()
        _ds1, _ds2 = _dim.getDimstrings()
        if dstr is _ds1:
            _dstr = 'ds1'
        elif dstr is _ds2:
            _dstr = 'ds2'
        else:
            raise ValueError, "Unexpected Dimstring: " + `dstr`
        self.saveUndoData('dimstring_changed', _dstr)
        _dim.modified()

    def _endpointTypeChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _ep = args[0]
        if (_ep != Dimension.DIM_ENDPT_NONE and
            _ep != Dimension.DIM_ENDPT_ARROW and
            _ep != Dimension.DIM_ENDPT_FILLED_ARROW and
            _ep != Dimension.DIM_ENDPT_SLASH and
            _ep != Dimension.DIM_ENDPT_CIRCLE):
            raise ValueError, "Invalid endpoint value: '%s'" % str(_ep)
        self.saveUndoData('endpoint_type_changed', _ep)

    def _endpointSizeChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _size = args[0]
        if not isinstance(_size, float):
            raise TypeError, "Unexpected type for size: " + `type(_size)`
        if _size < 0.0:
            raise ValueError, "Invalid endpoint size: %g" % _size
        self.saveUndoData('endpoint_size_changed', _size)

    def _dualModeChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _flag = args[0]
        util.test_boolean(_flag)
        self.saveUndoData('dual_mode_changed', _flag)

    def _dualModeOffsetChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _offset = args[0]
        if not isinstance(_offset, float):
            raise TypeError, "Unexpected type for flag: " + `type(_offset)`
        if _offset < 0.0:
            raise ValueError, "Invalid dual mode offset: %g" % _offset
        self.saveUndoData('dual_mode_offset_changed', _offset)

    def _positionChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _pos = args[0]
        if (_pos != Dimension.DIM_TEXT_POS_SPLIT and
            _pos != Dimension.DIM_TEXT_POS_ABOVE and
            _pos != Dimension.DIM_TEXT_POS_BELOW):
            raise ValueError, "Invalid position: '%s'" % str(_pos)
        self.saveUndoData('position_changed', _pos)

    def _positionOffsetChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _offset = args[0]
        if not isinstance(_offset, float):
            raise TypeError, "Unexpected type for offset: " + `type(_offset)`
        if _offset < 0.0:
            raise ValueError, "Invalid position offset: %g" % _offset
        self.saveUndoData('position_offset_changed', _offset)

    def _thicknessChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _t = args[0]
        if not isinstance(_t, float):
            raise TypeError, "Unexpected type for thickness" + `type(_t)`
        if _t < 0.0:
            raise ValueError, "Invalid thickness: %g" % _t
        self.saveUndoData('thickness_changed', _t)

    def _colorChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _color = args[0]
        if not isinstance(_color, color.Color):
            raise TypeError, "Invalid color: " + str(_color)
        self.saveUndoData('color_changed', _color.getColors())

    def _offsetChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _offset = args[0]
        if not isinstance(_offset, float):
            raise TypeError, "Unexpected type for offset: " + `type(_offset)`
        if _offset < 0.0:
            raise ValueError, "Invalid offset: %g" % _offset
        self.saveUndoData('offset_changed', _offset)

    def _extensionChanged(self, dim, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _extlen = args[0]
        if not isinstance(_extlen, float):
            raise TypeError, "Unexpected type for length: " + `type(_extlen)`
        if _extlen < 0.0:
            raise ValueError, "Invalid extension length: %g" % _extlen
        self.saveUndoData('extension_changed', _extlen)

    def _diaModeChanged(self, dim, *args): # RadialDimensions
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _flag = args[0]
        util.test_boolean(_flag)
        self.saveUndoData('dia_mode_changed', _flag)

    def _dimInverted(self, dim, *args): # AngularDimensions
        self.saveUndoData('inverted')

    def execute(self, undo, *args):
        util.test_boolean(undo)
        _alen = len(args)
        if len(args) == 0:
            raise ValueError, "No arguments to execute()"
        _dim = self.getObject()
        _op = args[0]
        if (_op == 'offset_changed' or
            _op == 'extension_changed' or
            _op == 'endpoint_type_changed' or
            _op == 'endpoint_size_changed' or
            _op == 'dual_mode_changed' or
            _op == 'dual_mode_offset_changed' or
            _op == 'dia_mode_changed' or
            _op == 'thickness_changed' or
            _op == 'position_changed' or
            _op == 'position_offset_changed'):
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _val = args[1]
            _get = DimLog.__getops[_op]
            _sdata = _get(_dim)
            self.ignore(_op)
            try:
                _set = DimLog.__setops[_op]
                if undo:
                    _dim.startUndo()
                    try:
                        _set(_dim, _val)
                    finally:
                        _dim.endUndo()
                else:
                    _dim.startRedo()
                    try:
                        _set(_dim, _val)
                    finally:
                        _dim.endRedo()
            finally:
                self.receive(_op)
            self.saveData(undo, _op, _sdata)
        elif _op == 'color_changed':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _val = args[1]
            _sdata = _dim.getColor().getColors()
            self.ignore(_op)
            try:
                _r, _g, _b = _val
                _color = color.get_color(_r, _g, _b)
                if undo:
                    _dim.startUndo()
                    try:
                        _dim.setColor(_color)
                    finally:
                        _dim.endUndo()
                else:
                    _dim.startRedo()
                    try:
                        _dim.setColor(_color)
                    finally:
                        _dim.endRedo()
            finally:
                self.receive(_op)
            self.saveData(undo, _op, _sdata)
        elif _op == 'dimstring_changed':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _dstr = args[1]
            _ds1, _ds2 = _dim.getDimstrings()
            self.ignore('modified')
            try:
                if _dstr == 'ds1':
                    if undo:
                        _ds1.undo()
                    else:
                        _ds1.redo()
                elif _dstr == 'ds2':
                    if undo:
                        _ds2.undo()
                    else:
                        _ds2.redo()
                else:
                    raise ValueError, "Unexpected dimstring key: " + str(_dstr)
            finally:
                self.receive('modified')
            self.saveData(undo, _op, _dstr)                
            if not undo:
                _dim.modified()
        elif _op == 'inverted': # AngularDimensions only
            self.ignore(_op)
            try:
                if undo:
                    _dim.startUndo()
                    try:
                        _dim.invert()
                    finally:
                        _dim.endUndo()
                else:
                    _dim.startRedo()
                    try:
                        _dim.invert()
                    finally:
                        _dim.endRedo()
            finally:
                self.receive(_op)
            self.saveData(undo, _op)
        else:
            super(DimLog, self).execute(undo, *args)