Skip to content

Core API

build123d_techdraw.core.sheet

ISO 5457 drawing sheets, standard sizes, borders, and coordinate grids.

DrawingSheet

Represents a single ISO 5457 technical drawing sheet with views and annotations.

Source code in src/build123d_techdraw/core/sheet.py
 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
class DrawingSheet:
    """Represents a single ISO 5457 technical drawing sheet with views and annotations."""

    def __init__(
        self,
        sheet_size: SheetSize | str | tuple[float, float] | None = None,
        custom_size: tuple[float, float] | None = None,
        title_info: TitleBlockInfo | None = None,
        left_margin: float = 15.0,
        margin: float = 8.0,
        style: str = "iso",
        show_border: bool = True,
        show_title_block: bool = True,
        show_grid: bool = True,
        show_notes: bool = True,
        borderless: bool = False,
        template: SheetTemplate | str | os.PathLike[str] | None = None,
    ):
        resolved_template: SheetTemplate | None
        if template is None:
            resolved_template = None
        elif isinstance(template, SheetTemplate):
            resolved_template = template
        else:
            resolved_template = SheetTemplate.from_file(template)

        if sheet_size is None:
            if (
                custom_size is None
                and resolved_template is not None
                and resolved_template.mode is TemplateMode.SHEET
            ):
                custom_size = (resolved_template.width_mm, resolved_template.height_mm)
            resolved_size = SheetSize.A3_LANDSCAPE
        elif (
            custom_size is None
            and isinstance(sheet_size, (tuple, list))
            and not isinstance(sheet_size, SheetSize)
            and len(sheet_size) == 2
        ):
            custom_size = (float(sheet_size[0]), float(sheet_size[1]))
            resolved_size = SheetSize.A3_LANDSCAPE
        else:
            resolved_size = SheetSize.coerce(sheet_size)  # type: ignore[arg-type]

        if custom_size is not None:
            self.width_mm, self.height_mm = float(custom_size[0]), float(custom_size[1])
            self.sheet_size = resolved_size
        else:
            self.width_mm, self.height_mm = resolved_size.value
            self.sheet_size = resolved_size

        self.style = style.lower()
        if borderless or self.style in ("frameless", "manual", "clean"):
            self.show_border = False
            self.show_title_block = False
            self.show_grid = False
            self.show_notes = False
            self.left_margin = margin
        else:
            self.show_border = show_border
            self.show_title_block = show_title_block
            self.show_grid = show_grid
            self.show_notes = show_notes
            self.left_margin = left_margin

        self.right_margin = margin
        self.top_margin = margin
        self.bottom_margin = margin

        self.template: SheetTemplate | None = None
        if resolved_template is not None:
            self.set_template(resolved_template, adopt_size=False)

        self.title_info: TitleBlockInfo = title_info or TitleBlockInfo(
            drawing_title="COMPONENT DRAWING",
            drawing_no="DWG-001",
        )

        self.views: list[SheetView] = []
        self.bom_items: list[BOMItem] = []
        self.bom_position: str = "above_title_block"
        self.revision_rows: list[RevisionEntry] = [
            RevisionEntry(
                rev="A",
                description="INITIAL ENGINEERING RELEASE",
                date=self.title_info.date,
                approved_by="APPROVED",
            )
        ]
        # The seeded row above is a placeholder; the first add_revision() call drops it.
        self._revision_placeholder: bool = True
        self.notes: list[str] = [
            "1. ALL DIMENSIONS IN MILLIMETERS (mm) UNLESS NOTED.",
            "2. GENERAL TOLERANCES ACCORDING TO ISO 2768-mK.",
            "3. DEBURR AND BREAK ALL SHARP EDGES 0.2mm x 45°.",
            "4. 100% CAD MODEL CONFORMANCE; DO NOT SCALE DRAWING.",
        ]

        self.custom_svg_elements: list[str] = []
        self.annotations: list[Annotation] = []
        self._ctx_token: Any = None

    @classmethod
    def from_template(
        cls,
        template: SheetTemplate | str | os.PathLike[str],
        **kwargs: Any,
    ) -> Self:
        """Create a ``DrawingSheet`` initialized with a custom SVG or DXF template."""
        tpl = template if isinstance(template, SheetTemplate) else SheetTemplate.from_file(template)
        return cls(template=tpl, **kwargs)

    def set_template(
        self,
        template: SheetTemplate | str | os.PathLike[str] | None,
        *,
        adopt_size: bool = False,
    ) -> Self:
        """Attach or clear a custom corporate ``SheetTemplate`` on this sheet."""
        if template is None:
            self.template = None
            return self
        tpl = template if isinstance(template, SheetTemplate) else SheetTemplate.from_file(template)
        self.template = tpl
        if tpl.mode is TemplateMode.SHEET:
            if adopt_size:
                self.width_mm = tpl.width_mm
                self.height_mm = tpl.height_mm
            if tpl.margins is not None:
                self.left_margin, self.right_margin, self.top_margin, self.bottom_margin = (
                    tpl.margins
                )
        return self

    def __enter__(self) -> Self:
        self._ctx_token = CURRENT_SHEET.set(self)
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: Any,
    ) -> None:
        if self._ctx_token is not None:
            CURRENT_SHEET.reset(self._ctx_token)
            self._ctx_token = None

    def __iadd__(self, item: SheetItem | Iterable[SheetItem]) -> Self:
        return self.add(item)

    def __add__(self, item: SheetItem | Iterable[SheetItem]) -> Self:
        return self.add(item)

    def add(self, item: SheetItem | Iterable[SheetItem]) -> Self:
        """Add a view, layout, annotation, title block, or notes to the drawing sheet."""
        if isinstance(item, SheetDirective):
            item._apply_to_sheet(self)
        elif isinstance(item, SheetView):
            self.add_view(item)
        elif isinstance(item, TitleBlockInfo):
            self.title_info = item
        elif isinstance(item, Annotation):
            if item not in self.annotations:
                self.annotations.append(item)
            item._attach_to_sheet(self)
        elif isinstance(item, Iterable) and not isinstance(item, str):
            for sub_item in item:
                self.add(sub_item)
        else:
            raise TypeError(f"Cannot add {type(item).__name__} to a DrawingSheet.")
        return self

    add_annotation = add

    def set_title_block(
        self,
        title: str | None = None,
        drawing_number: str | None = None,
        drawing_title: str | None = None,
        drawing_no: str | None = None,
        subtitle: str | None = None,
        sheet_no: str | None = None,
        sheet_num: int | None = None,
        num_sheets: int | None = None,
        total_sheets: str | int | None = None,
        scale: str | None = None,
        rev: str | None = None,
        date: str | None = None,
        material: str | None = None,
        finish: str | None = None,
        author: str | None = None,
        project: str | None = None,
        status: str | None = None,
        units: str | None = None,
        third_angle: bool | None = None,
        fields: dict[str, str] | None = None,
    ) -> None:
        """Update metadata fields in the ISO 7200 title block."""
        if title is not None:
            self.title_info.drawing_title = title
        if drawing_title is not None:
            self.title_info.drawing_title = drawing_title
        if subtitle is not None:
            self.title_info.subtitle = subtitle
        if drawing_number is not None:
            self.title_info.drawing_no = drawing_number
        if drawing_no is not None:
            self.title_info.drawing_no = drawing_no
        if total_sheets is not None:
            self.title_info.total_sheets = str(total_sheets)
        if sheet_no is not None:
            self.title_info.sheet_no = sheet_no
        elif sheet_num is not None:
            total = num_sheets if num_sheets is not None else sheet_num
            self.title_info.sheet_no = f"{sheet_num} OF {total}"
        if scale is not None:
            self.title_info.scale = scale
        if rev is not None:
            self.title_info.rev = rev
        if date is not None:
            self.title_info.date = date
        if material is not None:
            self.title_info.material = material
        if finish is not None:
            self.title_info.finish = finish
        if author is not None:
            self.title_info.author = author
        if project is not None:
            self.title_info.project = project
        if status is not None:
            self.title_info.status = status
        if units is not None:
            self.title_info.units = units
        if third_angle is not None:
            self.title_info.third_angle = third_angle
        if fields is not None:
            self.title_info.apply_custom_fields(fields)

    def set_notes(self, notes: list[str]) -> None:
        """Set drawing general notes block."""
        self.notes = list(notes)

    def add_bom_item(
        self, item_no: int, qty: int, part_no: str, description: str, material: str
    ) -> None:
        """Add a row to the Bill of Materials table."""
        self.bom_items.append(
            BOMItem(
                item_no=item_no,
                qty=qty,
                part_no=part_no,
                description=description,
                material=material,
            )
        )

    def add_revision(self, rev: str, description: str, date: str, approved_by: str) -> None:
        """Add a row to the Revision History table.

        A new sheet shows a placeholder row (``A / INITIAL ENGINEERING RELEASE``) so an
        un-revised drawing still has a revision table. That placeholder is removed by the
        first explicit call to this method, whatever its ``rev``. After that, every call
        appends a row, so the table holds exactly the revisions the caller added, in order.
        Rows written straight into ``revision_rows`` do not affect the placeholder.

        Args:
            rev: Revision letter or number, e.g. ``"A"``.
            description: Short description of the change.
            date: Date of the revision as it should be printed.
            approved_by: Approver's name or initials.
        """
        if self._revision_placeholder:
            self.revision_rows.clear()
            self._revision_placeholder = False
        self.revision_rows.append(
            RevisionEntry(
                rev=rev,
                description=description,
                date=date,
                approved_by=approved_by,
            )
        )

    def add_view(
        self,
        shape_or_view: SheetView | bd.Solid | bd.Compound | Any,
        view_type: ViewType = ViewType.FRONT,
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        show_hidden: bool = True,
        view_label: str | None = None,
        rotation_angle_deg: float = 0.0,
        view_label_y: float | None = None,
        model_origin: tuple[float, float] | None = None,
        align_to: AlignSpec | None = None,
        style: ViewStyle | str = ViewStyle.WIREFRAME,
        shading_dpi: int = 300,
        color_by_part: bool = False,
        part_colors: PartColors | None = None,
        ssao: bool = True,
        gpu: bool | None = None,
        shading_theme: Theme | str | None = None,
        *,
        hlr: HLRMode = "exact",
        hlr_resolution: int = 2048,
        hlr_gpu_face_threshold: int = 250,
    ) -> SheetView:
        """Add a projected orthographic/isometric view to the sheet."""
        if isinstance(shape_or_view, SheetView):
            view = shape_or_view
        else:
            view = project_shape_to_view(
                shape=shape_or_view,
                view_type=view_type,
                center_x=center[0],
                center_y=center[1],
                scale=scale,
                show_hidden=show_hidden,
                view_label=view_label,
                rotation_angle_deg=rotation_angle_deg,
                view_label_y=view_label_y,
                model_origin=model_origin,
                style=style,
                shading_dpi=shading_dpi,
                color_by_part=color_by_part,
                part_colors=part_colors,
                ssao=ssao,
                gpu=gpu,
                shading_theme=shading_theme,
                hlr=hlr,
                hlr_resolution=hlr_resolution,
                hlr_gpu_face_threshold=hlr_gpu_face_threshold,
            )
        if align_to is not None:
            _apply_align_to(view, align_to)
        view.sheet = self
        if view not in self.views:
            self.views.append(view)
        for ann in view.annotations:
            if ann not in self.annotations:
                self.annotations.append(ann)
        return view

    def _register_view(self, view: SheetView, align_to: AlignSpec | None) -> SheetView:
        if align_to is not None:
            _apply_align_to(view, align_to)
        view.sheet = self
        if view not in self.views:
            self.views.append(view)
        for ann in view.annotations:
            if ann not in self.annotations:
                self.annotations.append(ann)
        return view

    def update_shape(self, new_shape: Any) -> Self:
        """Update the 3D model across all views on the sheet and re-bind anchored annotations.

        Every view is checked before any is changed, so a view that cannot be regenerated
        raises ``ValueError`` without leaving the sheet half-updated. Detail views are
        updated last so they re-cut their already-updated parent view.
        """
        stale = [v for v in self.views if not v.can_regenerate()]
        if stale:
            names = ", ".join(f"{v.view_type.value} {v.view_label or ''!r}" for v in stale)
            raise ValueError(
                f"Cannot update shape: these views have no recorded build parameters: {names}"
            )
        ordered = [v for v in self.views if v.view_type != ViewType.DETAIL] + [
            v for v in self.views if v.view_type == ViewType.DETAIL
        ]
        for view in ordered:
            view.update_shape(new_shape)
        return self

    def add_section_view(
        self,
        shape: bd.Solid | bd.Compound | Any,
        cutting_plane: bd.Plane,
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        view_label: str = "SECTION A-A",
        view_label_y: float | None = None,
        model_origin: tuple[float, float] | None = None,
        align_to: AlignSpec | None = None,
        show_background: bool = True,
        hatch: str = "steel",
        hatch_pitch: float = 4.0,
        hatch_angle: float = 45.0,
    ) -> SheetView:
        """Add a 2D section slice view with material hatching to the sheet."""
        view = project_section_to_view(
            shape=shape,
            cutting_plane=cutting_plane,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            view_label=view_label,
            view_label_y=view_label_y,
            model_origin=model_origin,
            show_background=show_background,
            hatch=hatch,
            hatch_pitch=hatch_pitch,
            hatch_angle=hatch_angle,
        )
        return self._register_view(view, align_to)

    def add_half_section_view(
        self,
        shape: bd.Solid | bd.Compound | Any,
        cutting_plane: bd.Plane,
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        section_half: str = "top",
        view_label: str | None = "HALF SECTION",
        view_label_y: float | None = None,
        model_origin: tuple[float, float] | None = None,
        align_to: AlignSpec | None = None,
        show_background: bool = True,
        hatch: str = "steel",
        hatch_pitch: float = 4.0,
        hatch_angle: float = 45.0,
    ) -> SheetView:
        """Add an ISO 128-3 half-section view (one half sectioned, opposite half external)."""
        view = project_half_section_to_view(
            shape=shape,
            cutting_plane=cutting_plane,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            section_half=section_half,
            view_label=view_label,
            view_label_y=view_label_y,
            model_origin=model_origin,
            show_background=show_background,
            hatch=hatch,
            hatch_pitch=hatch_pitch,
            hatch_angle=hatch_angle,
        )
        return self._register_view(view, align_to)

    def add_offset_section_view(
        self,
        shape: bd.Solid | bd.Compound | Any,
        base_plane: bd.Plane,
        points: Sequence[Any],
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        view_label: str = "SECTION A-A",
        view_label_y: float | None = None,
        model_origin: tuple[float, float] | None = None,
        align_to: AlignSpec | None = None,
        show_background: bool = True,
        show_jog_lines: bool = False,
        hatch: str = "steel",
        hatch_pitch: float = 4.0,
        hatch_angle: float = 45.0,
    ) -> SheetView:
        """Add a stepped/offset section view along a multi-jog cutting path."""
        view = project_offset_section_to_view(
            shape=shape,
            base_plane=base_plane,
            points=points,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            view_label=view_label,
            view_label_y=view_label_y,
            model_origin=model_origin,
            show_background=show_background,
            show_jog_lines=show_jog_lines,
            hatch=hatch,
            hatch_pitch=hatch_pitch,
            hatch_angle=hatch_angle,
        )
        return self._register_view(view, align_to)

    def add_aligned_section_view(
        self,
        shape: bd.Solid | bd.Compound | Any,
        base_plane: bd.Plane,
        points: Sequence[Any],
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        view_label: str = "SECTION A-A",
        view_label_y: float | None = None,
        model_origin: tuple[float, float] | None = None,
        align_to: AlignSpec | None = None,
        show_background: bool = True,
        show_jog_lines: bool = False,
        hatch: str = "steel",
        hatch_pitch: float = 4.0,
        hatch_angle: float = 45.0,
    ) -> SheetView:
        """Add an aligned/revolved section view unfolding angled legs onto base_plane."""
        view = project_aligned_section_to_view(
            shape=shape,
            base_plane=base_plane,
            points=points,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            view_label=view_label,
            view_label_y=view_label_y,
            model_origin=model_origin,
            show_background=show_background,
            show_jog_lines=show_jog_lines,
            hatch=hatch,
            hatch_pitch=hatch_pitch,
            hatch_angle=hatch_angle,
        )
        return self._register_view(view, align_to)

    def add_detail_view(
        self,
        parent_view: SheetView,
        focus_target: Any = None,
        radius: float = 12.0,
        scale: float = 2.0,
        center: tuple[float, float] = (150.0, 150.0),
        view_label: str | None = None,
        label_letter: str = "A",
        view_label_y: float | None = None,
        align_to: AlignSpec | None = None,
        shape: str = "circle",
        region_center: Any = None,
        label: str | None = None,
    ) -> SheetView:
        """Add a magnified circular or rectangular detail view to the sheet."""
        view = project_detail_to_view(
            parent_view=parent_view,
            focus_target=focus_target,
            radius=radius,
            scale=scale,
            center_x=center[0],
            center_y=center[1],
            view_label=view_label,
            label_letter=label_letter,
            view_label_y=view_label_y,
            shape=shape,
            region_center=region_center,
            label=label,
        )
        if align_to is not None:
            _apply_align_to(view, align_to)
        view.sheet = self
        if view not in self.views:
            self.views.append(view)
        return view

    def add_auxiliary_view(
        self,
        shape: bd.Solid | bd.Compound | Any,
        face: Any,
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        show_hidden: bool = True,
        view_label: str = "AUXILIARY VIEW",
        view_label_y: float | None = None,
        align_to: AlignSpec | None = None,
    ) -> SheetView:
        """Add an auxiliary view normal to an inclined face."""
        view = project_auxiliary_view(
            shape=shape,
            face=face,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            show_hidden=show_hidden,
            view_label=view_label,
            view_label_y=view_label_y,
        )
        if align_to is not None:
            _apply_align_to(view, align_to)
        view.sheet = self
        if view not in self.views:
            self.views.append(view)
        return view

    def add_flat_pattern(
        self,
        shape: Any,
        center: tuple[float, float] = (150.0, 150.0),
        scale: float = 1.0,
        *,
        k_factor: float | str = "din6935",
        thickness: float | None = None,
        base_face: bd.Face | None = None,
        recognize_punches: bool = True,
        align_longest_horizontal: bool = True,
        annotate_bends: bool = True,
        annotate_punches: bool = True,
        show_bend_extents: bool = False,
        view_label: str = "FLAT PATTERN",
        view_label_y: float | None = None,
        align_to: AlignSpec | None = None,
    ) -> SheetView:
        """Unfold a 3D sheet metal part (or wrap a ``FlatPattern``) and add its flat pattern view."""
        from build123d_techdraw.core.view import project_flat_pattern_to_view

        view = project_flat_pattern_to_view(
            shape=shape,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            k_factor=k_factor,
            thickness=thickness,
            base_face=base_face,
            recognize_punches=recognize_punches,
            align_longest_horizontal=align_longest_horizontal,
            view_label=view_label,
            view_label_y=view_label_y,
        )
        self._register_view(view, align_to)
        if annotate_punches:
            view.add_punch_markers()
        if annotate_bends:
            view.add_bend_annotations(show_bend_extents=show_bend_extents)
        return view

    def add_sheet_metal_views(
        self,
        shape: Any,
        **kwargs: Any,
    ) -> SheetMetalLayout:
        """Create a complete sheet metal drawing layout (flat pattern, 3D iso, bend & punch schedules)."""
        from build123d_techdraw.layout.sheet_metal import add_sheet_metal_views

        return add_sheet_metal_views(self, shape, **kwargs)

    def add_dimension(
        self,
        start: tuple[float, float],
        end: tuple[float, float],
        offset: float = 8.0,
        dim_type: DimensionType = DimensionType.ALIGNED,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        prefix: str = "",
        suffix: str = "",
        nominal: float | None = None,
        view: SheetView | None = None,
    ) -> LinearDimension:
        """Add a linear dimension directly in sheet paper coordinates."""
        dim = LinearDimension(
            start=start,
            end=end,
            offset=offset,
            dim_type=dim_type,
            text=text,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            nominal=nominal,
            view=view,
        )
        if dim not in self.annotations:
            self.annotations.append(dim)
        if view is not None and dim not in view.annotations:
            view.annotations.append(dim)
        return dim

    def add_radial_dimension(
        self,
        center: tuple[float, float],
        radius: float,
        angle_deg: float = 45.0,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
    ) -> RadialDimension:
        """Add a radial dimension in sheet paper coordinates."""
        dim = RadialDimension(
            center=center,
            radius=radius,
            angle_deg=angle_deg,
            text=text,
            tolerance=tolerance,
        )
        if dim not in self.annotations:
            self.annotations.append(dim)
        return dim

    def add_diameter_dimension(
        self,
        center: tuple[float, float],
        diameter: float,
        angle_deg: float = 45.0,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
    ) -> DiameterDimension:
        """Add a diameter dimension in sheet paper coordinates."""
        dim = DiameterDimension(
            center=center,
            diameter=diameter,
            angle_deg=angle_deg,
            text=text,
            tolerance=tolerance,
        )
        if dim not in self.annotations:
            self.annotations.append(dim)
        return dim

    def add_angular_dimension(
        self,
        target1: Any,
        target2: Any,
        radius: float = 20.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "°",
        apex: tuple[float, float] | None = None,
        view: SheetView | None = None,
    ) -> AngularDimension:
        """Add an angular dimension to the sheet."""
        dim = AngularDimension(
            target1=target1,
            target2=target2,
            radius=radius,
            text=text,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            apex=apex,
            view=view,
        )
        if dim not in self.annotations:
            self.annotations.append(dim)
        if view is not None and dim not in view.annotations:
            view.annotations.append(dim)
        return dim

    def add_ordinate(
        self,
        target: Any,
        datum_coord: float = 0.0,
        direction: str = "horizontal",
        jog: float = 0.0,
        extension_length: float = 12.0,
        prefix: str = "",
        suffix: str = "",
        view: SheetView | None = None,
    ) -> OrdinateDimension:
        """Add an ordinate dimension point to the sheet."""
        dim = OrdinateDimension(
            target=target,
            datum_coord=datum_coord,
            direction=direction,
            jog=jog,
            extension_length=extension_length,
            prefix=prefix,
            suffix=suffix,
            view=view,
        )
        if dim not in self.annotations:
            self.annotations.append(dim)
        if view is not None and dim not in view.annotations:
            view.annotations.append(dim)
        return dim

    def add_chamfer_callout(
        self,
        target: Any,
        width: float | None = None,
        angle_deg: float = 45.0,
        style: str = "iso",
        quantity: int | None = None,
        elbow_offset: tuple[float, float] = (15.0, -12.0),
        view: SheetView | None = None,
    ) -> ChamferCallout:
        """Add an ISO/ASME chamfer callout note to the sheet."""
        cc = ChamferCallout(
            target_or_edge=target,
            width=width,
            angle_deg=angle_deg,
            style=style,
            quantity=quantity,
            elbow_offset=elbow_offset,
            view=view,
        )
        if cc not in self.annotations:
            self.annotations.append(cc)
        if view is not None and cc not in view.annotations:
            view.annotations.append(cc)
        return cc

    def add_half_diameter_dimension(
        self,
        feature_point: tuple[float, float],
        centerline_coord: float,
        diameter: float | None = None,
        orientation: str = "vertical",
        offset: float = 0.0,
        past_centerline: float = 5.0,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        view: SheetView | None = None,
    ) -> HalfDiameterDimension:
        """Add an ISO 129-1 §5.2.3 diametral centerline half-dimension in sheet space."""
        dim = HalfDiameterDimension(
            feature_point=feature_point,
            centerline_coord=centerline_coord,
            diameter=diameter,
            orientation=orientation,
            offset=offset,
            past_centerline=past_centerline,
            text=text,
            tolerance=tolerance,
            view=view,
        )
        if dim not in self.annotations:
            self.annotations.append(dim)
        if view is not None and dim not in view.annotations:
            view.annotations.append(dim)
        return dim

    def add_undercut_callout(
        self,
        target: Any,
        spec: Any = "E 0.8x0.3",
        roughness: str | None = None,
        quantity: int | None = None,
        include_standard: bool = True,
        elbow_offset: tuple[float, float] = (15.0, -12.0),
        view: SheetView | None = None,
    ) -> UndercutCallout:
        """Add a DIN 509 relief undercut callout note to the sheet."""
        uc = UndercutCallout(
            target=target,
            spec=spec,
            roughness=roughness,
            quantity=quantity,
            include_standard=include_standard,
            elbow_offset=elbow_offset,
            view=view,
        )
        if uc not in self.annotations:
            self.annotations.append(uc)
        if view is not None and uc not in view.annotations:
            view.annotations.append(uc)
        return uc

    def add_welding_symbol(
        self,
        target: Any,
        weld_type: WeldType | str = WeldType.FILLET,
        size: str | float | None = "a5",
        length: str | float | None = None,
        pitch: str | float | None = None,
        all_around: bool = False,
        field_weld: bool = False,
        tail_text: str | None = None,
        arrow_side: bool = True,
        elbow_offset: tuple[float, float] = (16.0, -12.0),
        view: SheetView | None = None,
    ) -> WeldingSymbol:
        """Add an ISO 2553 welding annotation to the sheet."""
        ws = WeldingSymbol(
            target=target,
            weld_type=weld_type,
            size=size,
            length=length,
            pitch=pitch,
            all_around=all_around,
            field_weld=field_weld,
            tail_text=tail_text,
            arrow_side=arrow_side,
            elbow_offset=elbow_offset,
            view=view,
        )
        if ws not in self.annotations:
            self.annotations.append(ws)
        if view is not None and ws not in view.annotations:
            view.annotations.append(ws)
        return ws

    def lint(self) -> list[LintIssue]:
        """Inspect sheet layout, annotations, and margins for drawing defects."""
        return run_sheet_lint(self)

    def inspect_layout(self) -> dict[str, Any]:
        """Return a structured layout dictionary of canvas, views, title blocks, and annotations for AI and CI inspection."""
        drawable = [
            round(self.left_margin, 2),
            round(self.top_margin, 2),
            round(self.width_mm - self.right_margin, 2),
            round(self.height_mm - self.bottom_margin, 2),
        ]
        if self.template is not None:
            tb_bb = self.template.title_block_bbox(self)
            tb_bounds = (
                [round(tb_bb[0], 2), round(tb_bb[1], 2), round(tb_bb[2], 2), round(tb_bb[3], 2)]
                if (self.show_title_block or self.template.mode is TemplateMode.SHEET)
                else [0.0, 0.0, 0.0, 0.0]
            )
        else:
            tb_w = 180.0
            tb_h = 36.0
            tb_bounds = (
                [
                    round(self.width_mm - self.right_margin - tb_w, 2),
                    round(self.height_mm - self.bottom_margin - tb_h, 2),
                    round(self.width_mm - self.right_margin, 2),
                    round(self.height_mm - self.bottom_margin, 2),
                ]
                if self.show_title_block
                else [0.0, 0.0, 0.0, 0.0]
            )

        views_info = []
        for v in self.views:
            v_bounds = [
                round(v.min_x, 2),
                round(v.min_y, 2),
                round(v.max_x, 2),
                round(v.max_y, 2),
            ]
            vis_bounds = [round(x, 2) for x in v.get_visual_bounds()]
            views_info.append(
                {
                    "label": v.view_label or v.view_type.value.upper(),
                    "view_type": v.view_type.value,
                    "bounds": v_bounds,
                    "visual_bounds": vis_bounds,
                    "scale": round(v.scale, 4),
                    "center": (round(v.center_x, 2), round(v.center_y, 2)),
                    "annotations_count": len(v.annotations),
                }
            )

        mid_x = (drawable[0] + drawable[2]) / 2.0
        mid_y = (drawable[1] + drawable[3]) / 2.0
        quadrants = {
            "top-left": (drawable[0], drawable[1], mid_x, mid_y),
            "top-right": (mid_x, drawable[1], drawable[2], mid_y),
            "bottom-left": (drawable[0], mid_y, mid_x, drawable[3]),
            "bottom-right": (mid_x, mid_y, drawable[2], drawable[3]),
        }

        free_quads = []
        for q_name, (qx1, qy1, qx2, qy2) in quadrants.items():
            occupied = False
            if self.show_title_block and not (
                tb_bounds[2] <= qx1
                or tb_bounds[0] >= qx2
                or tb_bounds[3] <= qy1
                or tb_bounds[1] >= qy2
            ):
                occupied = True
            if not occupied:
                for v in self.views:
                    vb = v.get_visual_bounds()
                    if not (vb[2] <= qx1 or vb[0] >= qx2 or vb[3] <= qy1 or vb[1] >= qy2):
                        occupied = True
                        break
            if not occupied:
                free_quads.append(q_name)

        lint_res = self.lint()
        return {
            "sheet_size": (round(self.width_mm, 2), round(self.height_mm, 2)),
            "drawable_bounds": drawable,
            "title_block_bounds": tb_bounds,
            "views": views_info,
            "annotations_count": len(self.annotations),
            "free_quadrants": free_quads,
            "lint_issues_count": len(lint_res),
            "lint_issues": [
                {"code": i.code, "severity": i.severity, "message": i.message} for i in lint_res
            ],
        }

    def add_gdt_frame(
        self,
        position: tuple[float, float],
        characteristic: GDTCharacteristic,
        tolerance_value: str,
        datum_a: str | None = None,
        datum_b: str | None = None,
        datum_c: str | None = None,
    ) -> FeatureControlFrame:
        """Add a GD&T Feature Control Frame in sheet paper coordinates."""
        fcf = FeatureControlFrame(
            position=position,
            characteristic=characteristic,
            tolerance_value=tolerance_value,
            datum_a=datum_a,
            datum_b=datum_b,
            datum_c=datum_c,
        )
        if fcf not in self.annotations:
            self.annotations.append(fcf)
        return fcf

    def add_datum_symbol(
        self,
        target: tuple[float, float],
        label: str = "A",
        direction: str = "up",
    ) -> DatumFeatureSymbol:
        """Add an ISO datum feature identifier symbol."""
        sym = DatumFeatureSymbol(target=target, label=label, direction=direction)
        if sym not in self.annotations:
            self.annotations.append(sym)
        return sym

    def add_surface_finish(
        self,
        position: tuple[float, float],
        ra_value: str = "Ra 3.2",
        material_removal: MaterialRemoval = MaterialRemoval.REQUIRED,
        process: str | None = None,
    ) -> SurfaceFinishSymbol:
        """Add an ISO 1302 surface roughness / finish symbol."""
        sym = SurfaceFinishSymbol(
            position=position,
            ra_value=ra_value,
            material_removal=material_removal,
            process=process,
        )
        if sym not in self.annotations:
            self.annotations.append(sym)
        return sym

    def add_centerline(
        self,
        start: tuple[float, float],
        end: tuple[float, float],
        stroke_width: float = 0.25,
    ) -> Centerline:
        """Add an ISO dash-dot centerline between two sheet points."""
        cl = Centerline(start=start, end=end, stroke_width=stroke_width)
        if cl not in self.annotations:
            self.annotations.append(cl)
        return cl

    def add_centermark(
        self,
        center: tuple[float, float],
        size: float = 6.0,
    ) -> CenterMark:
        """Add an ISO center crosshair."""
        cm = CenterMark(center=center, size=size)
        if cm not in self.annotations:
            self.annotations.append(cm)
        return cm

    def add_bolt_circle(
        self,
        center: tuple[float, float],
        diameter: float,
        num_holes: int = 4,
        start_angle_deg: float = 0.0,
    ) -> BoltCircle:
        """Add a bolt pitch circle diameter (PCD) annotation."""
        bc = BoltCircle(
            center=center,
            diameter=diameter,
            num_holes=num_holes,
            start_angle_deg=start_angle_deg,
        )
        if bc not in self.annotations:
            self.annotations.append(bc)
        return bc

    def add_leader_note(
        self,
        target: tuple[float, float],
        lines: list[str] | str,
        elbow_offset: tuple[float, float] = (15.0, -12.0),
        shelf_length: float = 20.0,
        align_right: bool | None = None,
        terminator: str = "dot",
    ) -> LeaderNote:
        """Add a leader note with pointer dot/arrow, elbow, and horizontal text shelf."""
        line_list = [lines] if isinstance(lines, str) else list(lines)
        note = LeaderNote(
            target=target,
            lines=line_list,
            elbow_offset=elbow_offset,
            shelf_length=shelf_length,
            align_right=align_right,
            terminator=terminator,
        )
        if note not in self.annotations:
            self.annotations.append(note)
        return note

    add_leader = add_leader_note

    def add_hole_callout(
        self,
        center: tuple[float, float],
        diameter: float | None = None,
        depth: float | str | None = None,
        countersink_dia: float | None = None,
        countersink_angle: float = 90.0,
        counterbore_dia: float | None = None,
        counterbore_depth: float | None = None,
        quantity: int | None = None,
        tolerance: str | None = None,
        clearance_for: str | None = None,
        fit: str = "medium",
        elbow_offset: tuple[float, float] = (15.0, -12.0),
    ) -> HoleCallout:
        """Add a standard engineering hole callout in sheet paper coordinates."""
        hc = HoleCallout(
            center=center,
            diameter=diameter,
            depth=depth,
            countersink_dia=countersink_dia,
            countersink_angle=countersink_angle,
            counterbore_dia=counterbore_dia,
            counterbore_depth=counterbore_depth,
            quantity=quantity,
            tolerance=tolerance,
            clearance_for=clearance_for,
            fit=fit,
            elbow_offset=elbow_offset,
        )
        if hc not in self.annotations:
            self.annotations.append(hc)
        return hc

    def add_thread_callout(
        self,
        center: tuple[float, float],
        thread: str = "M5x0.8",
        depth: float | str | None = "THRU",
        class_fit: str | None = None,
        quantity: int | None = None,
        show_tap_drill: bool = False,
        elbow_offset: tuple[float, float] = (15.0, -12.0),
    ) -> ThreadCallout:
        """Add a standard engineering thread callout in sheet paper coordinates."""
        tc = ThreadCallout(
            center=center,
            thread=thread,
            depth=depth,
            class_fit=class_fit,
            quantity=quantity,
            show_tap_drill=show_tap_drill,
            elbow_offset=elbow_offset,
        )
        if tc not in self.annotations:
            self.annotations.append(tc)
        return tc

    def add_cosmetic_thread(
        self,
        center: tuple[float, float] | None = None,
        thread: str | Any | None = None,
        nominal_diameter: float | None = None,
        minor_diameter: float | None = None,
        thread_type: str = "internal",
        depth: float | None = None,
        start: tuple[float, float] | None = None,
        end: tuple[float, float] | None = None,
        view_mode: str | None = None,
    ) -> CosmeticThread:
        """Add an ISO 6410-1 cosmetic thread in sheet paper coordinates."""
        ct = CosmeticThread(
            thread=thread,
            nominal_diameter=nominal_diameter,
            minor_diameter=minor_diameter,
            thread_type=thread_type,
            depth=depth,
            center=center,
            start=start,
            end=end,
            view_mode=view_mode,
        )
        if ct not in self.annotations:
            self.annotations.append(ct)
        return ct

    def add_table(
        self,
        headers: list[str] | None = None,
        rows: list[list[Any]] | None = None,
        position: tuple[float, float] = (0.0, 0.0),
        col_widths: list[float] | None = None,
        title: str | None = None,
        **kwargs: Any,
    ) -> Table:
        """Add a tabular schedule to the sheet."""
        tbl = Table(
            headers=headers,
            rows=rows,
            position=position,
            col_widths=col_widths,
            title=title,
            sheet=self,
            **kwargs,
        )
        if tbl not in self.annotations:
            self.annotations.append(tbl)
        return tbl

    def add_raw_svg(
        self,
        content: str,
        position: tuple[float, float] = (0.0, 0.0),
        **kwargs: Any,
    ) -> RawSVG:
        """Add a raw SVG vector element to the sheet."""
        raw = RawSVG(content=content, position=position, sheet=self, **kwargs)
        if raw not in self.annotations:
            self.annotations.append(raw)
        return raw

    def add_balloon(
        self,
        item_no: int,
        target: tuple[float, float],
        balloon_center: tuple[float, float],
        radius: float = 4.5,
        terminator: str = "dot",
    ) -> BOMBalloon:
        """Add an ISO BOM balloon callout circle connected to component via leader."""
        balloon = BOMBalloon(
            item_no=item_no,
            target=target,
            balloon_center=balloon_center,
            radius=radius,
            terminator=terminator,
        )
        if balloon not in self.annotations:
            self.annotations.append(balloon)
        return balloon

    def add_section_cutting_line(
        self,
        points: Sequence[Any],
        label: str = "A",
        arrow_dir: str | tuple[float, float] = "up",
    ) -> SectionCuttingLine:
        """Add an ISO section cutting plane line."""
        cut = SectionCuttingLine(
            points=points,
            label=label,
            arrow_dir=arrow_dir,
        )
        if cut not in self.annotations:
            self.annotations.append(cut)
        return cut

    add_section_cut = add_section_cutting_line

    def render_border_and_grid(self) -> str:
        """Render ISO 5457 borders, centering marks, and alphanumeric grid zones."""
        if not self.show_border and not self.show_grid:
            return ""
        w = self.width_mm
        h = self.height_mm
        bx = self.left_margin
        by = self.top_margin
        bw = w - self.left_margin - self.right_margin
        bh = h - self.top_margin - self.bottom_margin

        num_cols = 8 if w > 350 else 6
        num_rows = 6 if h > 250 else 4
        col_w = bw / num_cols
        row_h = bh / num_rows

        grid_lines: list[str] = []
        labels: list[str] = []

        # Vertical grid ticks and column numbers
        for i in range(num_cols + 1):
            gx = bx + i * col_w
            grid_lines.append(
                f'<line x1="{gx:.2f}" y1="{by - 3.0:.2f}" x2="{gx:.2f}" y2="{by:.2f}" class="border-sub"/>'
            )
            grid_lines.append(
                f'<line x1="{gx:.2f}" y1="{by + bh:.2f}" x2="{gx:.2f}" y2="{by + bh + 3.0:.2f}" class="border-sub"/>'
            )
            if i < num_cols:
                zone_num = str(num_cols - i)
                labels.append(
                    f'<text x="{gx + col_w / 2:.2f}" y="{by - 1.0:.2f}" class="zone-text">{zone_num}</text>'
                )
                labels.append(
                    f'<text x="{gx + col_w / 2:.2f}" y="{by + bh + 4.5:.2f}" class="zone-text">{zone_num}</text>'
                )

        # Horizontal grid ticks and row letters
        row_letters = ["A", "B", "C", "D", "E", "F", "G", "H"]
        for j in range(num_rows + 1):
            gy = by + j * row_h
            grid_lines.append(
                f'<line x1="{bx - 3.0:.2f}" y1="{gy:.2f}" x2="{bx:.2f}" y2="{gy:.2f}" class="border-sub"/>'
            )
            grid_lines.append(
                f'<line x1="{bx + bw:.2f}" y1="{gy:.2f}" x2="{bx + bw + 3.0:.2f}" y2="{gy:.2f}" class="border-sub"/>'
            )
            if j < num_rows:
                zone_let = row_letters[j % len(row_letters)]
                labels.append(
                    f'<text x="{bx - 1.8:.2f}" y="{gy + row_h / 2 + 1.2:.2f}" class="zone-text">{zone_let}</text>'
                )
                labels.append(
                    f'<text x="{bx + bw + 1.8:.2f}" y="{gy + row_h / 2 + 1.2:.2f}" class="zone-text">{zone_let}</text>'
                )

        # Centering marks (ISO 5457 section 4.3)
        mid_x = bx + bw / 2.0
        mid_y = by + bh / 2.0
        cm_len = 5.0
        centering_marks = f"""
        <line x1="{mid_x:.2f}" y1="0" x2="{mid_x:.2f}" y2="{cm_len}" class="border-main" stroke-width="0.7"/>
        <line x1="{mid_x:.2f}" y1="{h - cm_len:.2f}" x2="{mid_x:.2f}" y2="{h:.2f}" class="border-main" stroke-width="0.7"/>
        <line x1="0" y1="{mid_y:.2f}" x2="{cm_len}" y2="{mid_y:.2f}" class="border-main" stroke-width="0.7"/>
        <line x1="{w - cm_len:.2f}" y1="{mid_y:.2f}" x2="{w:.2f}" y2="{mid_y:.2f}" class="border-main" stroke-width="0.7"/>
        """

        return f"""
        <rect x="0" y="0" width="{w}" height="{h}" class="sheet-bg"/>
        <rect x="0" y="0" width="{w}" height="{h}" class="blueprint-grid" fill="url(#techGrid)"/>
        <rect x="2" y="2" width="{w - 4}" height="{h - 4}" class="border-sub" stroke-width="0.25" fill="none"/>
        <rect x="{bx:.2f}" y="{by:.2f}" width="{bw:.2f}" height="{bh:.2f}" class="border-main" stroke-width="0.7" fill="none"/>
        {centering_marks}
        <g class="grid-ticks">{"".join(grid_lines)}</g>
        <g class="zone-labels">{"".join(labels)}</g>
        """

    def render_notes(self) -> str:
        """Render general notes block in bottom-left."""
        if not self.notes:
            return ""
        bx = self.left_margin + 5.0
        by = self.height_mm - self.bottom_margin - 30.0

        notes_svg: list[str] = [
            '<text x="0" y="0" class="tb-field-label" font-weight="bold">GENERAL NOTES:</text>'
        ]
        for i, note in enumerate(self.notes):
            notes_svg.append(
                f'<text x="0" y="{4.5 + i * 4.2:.2f}" class="notes-text">{note}</text>'
            )

        return f"""
        <g class="sheet-notes" transform="translate({bx:.2f}, {by:.2f})">
            {"".join(notes_svg)}
        </g>
        """

    def render_view_labels(self) -> str:
        """Render view titles and scale notes positioned cleanly below annotations."""
        out: list[str] = []
        for v in self.views:
            if v.view_label and v.scale_label:
                vx = v.center_x
                # Position label dynamically below any bottom annotations with clearance
                vy = max(
                    v.bottom_annotation_y + 8.0,
                    v.view_label_pos[1] if v.view_label_pos else v.max_y + 8.0,
                )
                line_w = max(len(v.view_label) * 2.8, 20.0)
                out.append(f"""
                <text x="{vx:.2f}" y="{vy:.2f}" class="view-title" text-anchor="middle" font-size="4.2" font-weight="bold">{v.view_label}</text>
                <text x="{vx:.2f}" y="{vy + 3.8:.2f}" class="view-scale" text-anchor="middle" font-size="2.8">{v.scale_label}</text>
                <line x1="{vx - line_w / 2:.2f}" y1="{vy + 1.0:.2f}" x2="{vx + line_w / 2:.2f}" y2="{vy + 1.0:.2f}" class="border-sub" stroke-width="0.3"/>
                """)
        return f'<g class="view-labels">{"".join(out)}</g>'

    def render_hatch_defs(self) -> str:
        """Render standard ISO 128 / ANSI hatch patterns in SVG defs."""
        patterns = [
            """<pattern id="sectionHatch" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>""",
            """<pattern id="hatch_steel" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>""",
            """<pattern id="hatch_aluminum" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
      <line x1="1.2" y1="0" x2="1.2" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>""",
            """<pattern id="hatch_brass" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
      <line x1="2" y1="0" x2="2" y2="4" stroke="var(--hatch-color)" stroke-width="0.35" stroke-dasharray="1.5,1.5"/>
    </pattern>""",
            """<pattern id="hatch_plastic" width="4" height="4" patternTransform="rotate(60 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
      <line x1="0" y1="0" x2="4" y2="0" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>""",
            """<pattern id="hatch_rubber" width="4" height="4" patternUnits="userSpaceOnUse">
      <circle cx="2" cy="2" r="0.45" fill="var(--hatch-color)"/>
      <circle cx="0" cy="0" r="0.45" fill="var(--hatch-color)"/>
      <circle cx="4" cy="0" r="0.45" fill="var(--hatch-color)"/>
      <circle cx="0" cy="4" r="0.45" fill="var(--hatch-color)"/>
      <circle cx="4" cy="4" r="0.45" fill="var(--hatch-color)"/>
    </pattern>""",
        ]
        for v in self.views:
            h_id = v.hatch_id
            if h_id and not any(f'id="{h_id}"' in p for p in patterns):
                mat = v.hatch or "steel"
                pitch = v.hatch_pitch if v.hatch_pitch is not None else 4.0
                angle = v.hatch_angle if v.hatch_angle is not None else 45.0
                if mat in ("aluminum", "ansi38"):
                    p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
      <line x1="{pitch * 0.3:.2f}" y1="0" x2="{pitch * 0.3:.2f}" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>"""
                elif mat in ("brass", "ansi32"):
                    p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
      <line x1="{pitch * 0.5:.2f}" y1="0" x2="{pitch * 0.5:.2f}" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35" stroke-dasharray="1.5,1.5"/>
    </pattern>"""
                elif mat in ("plastic", "rubber"):
                    p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
      <line x1="0" y1="0" x2="{pitch:.2f}" y2="0" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>"""
                else:
                    p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
      <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
    </pattern>"""
                patterns.append(p_svg)
        return "\n    ".join(patterns)

    def to_svg(self, theme: Theme | str = Theme.DARK_BLUEPRINT) -> str:
        """Render the complete drawing sheet to an SVG vector string."""
        if isinstance(theme, str):
            theme = (
                Theme.ISO_WHITE
                if theme.lower() in ("print", "white", "iso_white")
                else Theme.DARK_BLUEPRINT
            )
        w, h = self.width_mm, self.height_mm
        theme_class = "theme-iso-white" if theme == Theme.ISO_WHITE else "theme-dark-blueprint"

        view_elements = "".join([v.svg_content for v in self.views])

        # Annotation SVG rendering (dimensions, leaders, GD&T, tables, raw SVG, etc.)
        annotation_svgs = "".join([a.to_svg() for a in self.annotations])

        # Position BOM table (bottom-up above title block or top-right below revisions)
        if self.bom_position == "top_right":
            rev_h = 10.0 if self.revision_rows else 0.0
            bom_top_y = self.top_margin + rev_h + 2.0
        elif self.template is not None:
            tb_y = self.template.title_block_bbox(self)[1]
            bom_h = 5.5 + len(self.bom_items) * 5.2
            bom_top_y = tb_y - bom_h - 1.0
        else:
            extra_fields = self.title_info.extra_fields
            extra_rows = (
                (len(extra_fields) + min(3, len(extra_fields)) - 1) // min(3, len(extra_fields))
                if extra_fields
                else 0
            )
            tb_y = h - self.bottom_margin - 36.0 - extra_rows * 7.0
            bom_h = 5.5 + len(self.bom_items) * 5.2
            bom_top_y = tb_y - bom_h - 1.0

        template_defs = ""
        if self.template is None:
            border_svg = (
                self.render_border_and_grid() if (self.show_border or self.show_grid) else ""
            )
            tb_svg = (
                render_title_block_svg(self.title_info, w, h, self.right_margin, self.bottom_margin)
                if self.show_title_block and self.title_info
                else ""
            )
            rev_svg = (
                render_revision_table_svg(self.revision_rows, w, self.right_margin, self.top_margin)
                if self.show_title_block and self.revision_rows
                else ""
            )
        else:
            should_render_tpl = self.template.mode is TemplateMode.SHEET or self.show_title_block
            template_defs, template_body = (
                self.template.render_parts(self) if should_render_tpl else ("", "")
            )
            if self.template.mode is TemplateMode.SHEET:
                bg_rect = f'<rect x="0" y="0" width="{w}" height="{h}" class="sheet-bg"/>'
                grid_rect = (
                    f'\n        <rect x="0" y="0" width="{w}" height="{h}" class="blueprint-grid" fill="url(#techGrid)"/>'
                    if self.show_grid
                    else ""
                )
                border_svg = f"{bg_rect}{grid_rect}\n        {template_body}"
                tb_svg = ""
                show_rev = self.template.show_revision_table
                include_rev = bool(self.revision_rows) and (
                    (show_rev is True) or (show_rev is None and not self._revision_placeholder)
                )
                rev_svg = (
                    render_revision_table_svg(
                        self.revision_rows, w, self.right_margin, self.top_margin
                    )
                    if include_rev
                    else ""
                )
            else:
                border_svg = (
                    self.render_border_and_grid() if (self.show_border or self.show_grid) else ""
                )
                tb_svg = template_body if self.show_title_block else ""
                rev_svg = (
                    render_revision_table_svg(
                        self.revision_rows, w, self.right_margin, self.top_margin
                    )
                    if self.show_title_block and self.revision_rows
                    else ""
                )
        bom_svg = (
            render_bom_table_svg(self.bom_items, w, self.right_margin, bom_top_y)
            if self.bom_items
            else ""
        )
        notes_svg = self.render_notes() if self.show_notes else ""
        extra_defs = f"\n    {template_defs}" if template_defs else ""

        has_shaded = any(v.style is not ViewStyle.WIREFRAME for v in self.views)
        has_sheet_metal = any(
            v.view_type == ViewType.FLAT_PATTERN or v.flat_pattern is not None for v in self.views
        ) or any(
            isinstance(a, (BendLineAnnotation, PunchMarker, BendTable, PunchTable))
            for a in self.annotations
        )
        return f"""<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 {w} {h}"
     width="{w}mm"
     height="{h}mm"
     class="{theme_class}"
     id="sheet_{self.title_info.drawing_no}">
  <defs>
    <style type="text/css">
      {generate_theme_css(theme, include_shaded=has_shaded, include_sheet_metal=has_sheet_metal)}
    </style>
    <pattern id="techGrid" width="10" height="10" patternUnits="userSpaceOnUse">
      <path d="M 10 0 L 0 0 0 10" fill="none" stroke="var(--grid-color)" stroke-width="0.15"/>
      <circle cx="0" cy="0" r="0.3" fill="var(--grid-color)"/>
    </pattern>
    {self.render_hatch_defs()}{extra_defs}
  </defs>

  {border_svg}
  {tb_svg}
  {rev_svg}
  {bom_svg}
  {notes_svg}

  <g class="drawing-views">
    {view_elements}
  </g>

  {self.render_view_labels()}

  <g class="annotations">
    {annotation_svgs}
  </g>
</svg>
"""

    def export_svg(self, path: str, theme: Theme | str = Theme.DARK_BLUEPRINT) -> None:
        """Export sheet to an SVG file."""
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
        svg = self.to_svg(theme=theme)
        with open(path, "w", encoding="utf-8") as f:
            f.write(svg)

    def export_pdf(self, path: str, theme: Theme | str = Theme.DARK_BLUEPRINT) -> None:
        """Export sheet to a vector PDF file."""
        from build123d_techdraw.renderers.pdf import PDFRenderer

        resolved_theme = (
            Theme.ISO_WHITE
            if (isinstance(theme, str) and theme.lower() in ("print", "white", "iso_white"))
            or theme == Theme.ISO_WHITE
            else Theme.DARK_BLUEPRINT
        )
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
        PDFRenderer.render_sheets_to_pdf(
            [(self.width_mm, self.height_mm, self.to_svg(resolved_theme))], path, resolved_theme
        )

    def export_dxf(self, path: str, flat_pattern: bool = False, dxfversion: str = "R2010") -> None:
        """Export sheet to a multi-layer DXF CAD drawing. If flat_pattern=True, exports 1:1 unannotated CNC geometry."""
        from build123d_techdraw.renderers.dxf import DXFRenderer

        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
        if flat_pattern:
            for v in self.views:
                if v.flat_pattern is not None:
                    DXFRenderer.export_flat_pattern_to_dxf(
                        v.flat_pattern, path, dxfversion=dxfversion
                    )
                    return

            unique_shapes: list[Any] = []
            for v in self.views:
                if v.shape is not None and v.shape not in unique_shapes:
                    unique_shapes.append(v.shape)

            if unique_shapes:
                shape_to_export = (
                    unique_shapes[0]
                    if len(unique_shapes) == 1
                    else bd.Compound(children=unique_shapes)
                )
                DXFRenderer.export_shape_to_dxf(shape_to_export, path, dxfversion=dxfversion)
            else:
                from ezdxf.filemanagement import new as ezdxf_new

                doc = ezdxf_new(dxfversion=dxfversion)
                doc.saveas(path)
        else:
            DXFRenderer.export_sheet_to_dxf(self, path, dxfversion=dxfversion)

    def export_html(
        self,
        filepath: str | os.PathLike[str],
        theme: Theme | str = Theme.DARK_BLUEPRINT,
        *,
        shape: Any | None = None,
        linear_deflection: float = 0.08,
        angular_deflection: float = 0.25,
        crease_angle_deg: float = 20.0,
        title: str | None = None,
        initial_layout: str = "split",
    ) -> None:
        """Export sheet to a self-contained interactive 3D-in-2D HTML5 blueprint."""
        from build123d_techdraw.renderers.html import export_interactive_html

        export_interactive_html(
            self,
            filepath,
            theme=theme,
            shape=shape,
            linear_deflection=linear_deflection,
            angular_deflection=angular_deflection,
            crease_angle_deg=crease_angle_deg,
            title=title,
            initial_layout=initial_layout,
        )

from_template(template, **kwargs) classmethod

Create a DrawingSheet initialized with a custom SVG or DXF template.

Source code in src/build123d_techdraw/core/sheet.py
@classmethod
def from_template(
    cls,
    template: SheetTemplate | str | os.PathLike[str],
    **kwargs: Any,
) -> Self:
    """Create a ``DrawingSheet`` initialized with a custom SVG or DXF template."""
    tpl = template if isinstance(template, SheetTemplate) else SheetTemplate.from_file(template)
    return cls(template=tpl, **kwargs)

set_template(template, *, adopt_size=False)

Attach or clear a custom corporate SheetTemplate on this sheet.

Source code in src/build123d_techdraw/core/sheet.py
def set_template(
    self,
    template: SheetTemplate | str | os.PathLike[str] | None,
    *,
    adopt_size: bool = False,
) -> Self:
    """Attach or clear a custom corporate ``SheetTemplate`` on this sheet."""
    if template is None:
        self.template = None
        return self
    tpl = template if isinstance(template, SheetTemplate) else SheetTemplate.from_file(template)
    self.template = tpl
    if tpl.mode is TemplateMode.SHEET:
        if adopt_size:
            self.width_mm = tpl.width_mm
            self.height_mm = tpl.height_mm
        if tpl.margins is not None:
            self.left_margin, self.right_margin, self.top_margin, self.bottom_margin = (
                tpl.margins
            )
    return self

add(item)

Add a view, layout, annotation, title block, or notes to the drawing sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add(self, item: SheetItem | Iterable[SheetItem]) -> Self:
    """Add a view, layout, annotation, title block, or notes to the drawing sheet."""
    if isinstance(item, SheetDirective):
        item._apply_to_sheet(self)
    elif isinstance(item, SheetView):
        self.add_view(item)
    elif isinstance(item, TitleBlockInfo):
        self.title_info = item
    elif isinstance(item, Annotation):
        if item not in self.annotations:
            self.annotations.append(item)
        item._attach_to_sheet(self)
    elif isinstance(item, Iterable) and not isinstance(item, str):
        for sub_item in item:
            self.add(sub_item)
    else:
        raise TypeError(f"Cannot add {type(item).__name__} to a DrawingSheet.")
    return self

set_title_block(title=None, drawing_number=None, drawing_title=None, drawing_no=None, subtitle=None, sheet_no=None, sheet_num=None, num_sheets=None, total_sheets=None, scale=None, rev=None, date=None, material=None, finish=None, author=None, project=None, status=None, units=None, third_angle=None, fields=None)

Update metadata fields in the ISO 7200 title block.

Source code in src/build123d_techdraw/core/sheet.py
def set_title_block(
    self,
    title: str | None = None,
    drawing_number: str | None = None,
    drawing_title: str | None = None,
    drawing_no: str | None = None,
    subtitle: str | None = None,
    sheet_no: str | None = None,
    sheet_num: int | None = None,
    num_sheets: int | None = None,
    total_sheets: str | int | None = None,
    scale: str | None = None,
    rev: str | None = None,
    date: str | None = None,
    material: str | None = None,
    finish: str | None = None,
    author: str | None = None,
    project: str | None = None,
    status: str | None = None,
    units: str | None = None,
    third_angle: bool | None = None,
    fields: dict[str, str] | None = None,
) -> None:
    """Update metadata fields in the ISO 7200 title block."""
    if title is not None:
        self.title_info.drawing_title = title
    if drawing_title is not None:
        self.title_info.drawing_title = drawing_title
    if subtitle is not None:
        self.title_info.subtitle = subtitle
    if drawing_number is not None:
        self.title_info.drawing_no = drawing_number
    if drawing_no is not None:
        self.title_info.drawing_no = drawing_no
    if total_sheets is not None:
        self.title_info.total_sheets = str(total_sheets)
    if sheet_no is not None:
        self.title_info.sheet_no = sheet_no
    elif sheet_num is not None:
        total = num_sheets if num_sheets is not None else sheet_num
        self.title_info.sheet_no = f"{sheet_num} OF {total}"
    if scale is not None:
        self.title_info.scale = scale
    if rev is not None:
        self.title_info.rev = rev
    if date is not None:
        self.title_info.date = date
    if material is not None:
        self.title_info.material = material
    if finish is not None:
        self.title_info.finish = finish
    if author is not None:
        self.title_info.author = author
    if project is not None:
        self.title_info.project = project
    if status is not None:
        self.title_info.status = status
    if units is not None:
        self.title_info.units = units
    if third_angle is not None:
        self.title_info.third_angle = third_angle
    if fields is not None:
        self.title_info.apply_custom_fields(fields)

set_notes(notes)

Set drawing general notes block.

Source code in src/build123d_techdraw/core/sheet.py
def set_notes(self, notes: list[str]) -> None:
    """Set drawing general notes block."""
    self.notes = list(notes)

add_bom_item(item_no, qty, part_no, description, material)

Add a row to the Bill of Materials table.

Source code in src/build123d_techdraw/core/sheet.py
def add_bom_item(
    self, item_no: int, qty: int, part_no: str, description: str, material: str
) -> None:
    """Add a row to the Bill of Materials table."""
    self.bom_items.append(
        BOMItem(
            item_no=item_no,
            qty=qty,
            part_no=part_no,
            description=description,
            material=material,
        )
    )

add_revision(rev, description, date, approved_by)

Add a row to the Revision History table.

A new sheet shows a placeholder row (A / INITIAL ENGINEERING RELEASE) so an un-revised drawing still has a revision table. That placeholder is removed by the first explicit call to this method, whatever its rev. After that, every call appends a row, so the table holds exactly the revisions the caller added, in order. Rows written straight into revision_rows do not affect the placeholder.

Parameters:

Name Type Description Default
rev str

Revision letter or number, e.g. "A".

required
description str

Short description of the change.

required
date str

Date of the revision as it should be printed.

required
approved_by str

Approver's name or initials.

required
Source code in src/build123d_techdraw/core/sheet.py
def add_revision(self, rev: str, description: str, date: str, approved_by: str) -> None:
    """Add a row to the Revision History table.

    A new sheet shows a placeholder row (``A / INITIAL ENGINEERING RELEASE``) so an
    un-revised drawing still has a revision table. That placeholder is removed by the
    first explicit call to this method, whatever its ``rev``. After that, every call
    appends a row, so the table holds exactly the revisions the caller added, in order.
    Rows written straight into ``revision_rows`` do not affect the placeholder.

    Args:
        rev: Revision letter or number, e.g. ``"A"``.
        description: Short description of the change.
        date: Date of the revision as it should be printed.
        approved_by: Approver's name or initials.
    """
    if self._revision_placeholder:
        self.revision_rows.clear()
        self._revision_placeholder = False
    self.revision_rows.append(
        RevisionEntry(
            rev=rev,
            description=description,
            date=date,
            approved_by=approved_by,
        )
    )

add_view(shape_or_view, view_type=ViewType.FRONT, center=(150.0, 150.0), scale=1.0, show_hidden=True, view_label=None, rotation_angle_deg=0.0, view_label_y=None, model_origin=None, align_to=None, style=ViewStyle.WIREFRAME, shading_dpi=300, color_by_part=False, part_colors=None, ssao=True, gpu=None, shading_theme=None, *, hlr='exact', hlr_resolution=2048, hlr_gpu_face_threshold=250)

Add a projected orthographic/isometric view to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_view(
    self,
    shape_or_view: SheetView | bd.Solid | bd.Compound | Any,
    view_type: ViewType = ViewType.FRONT,
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    show_hidden: bool = True,
    view_label: str | None = None,
    rotation_angle_deg: float = 0.0,
    view_label_y: float | None = None,
    model_origin: tuple[float, float] | None = None,
    align_to: AlignSpec | None = None,
    style: ViewStyle | str = ViewStyle.WIREFRAME,
    shading_dpi: int = 300,
    color_by_part: bool = False,
    part_colors: PartColors | None = None,
    ssao: bool = True,
    gpu: bool | None = None,
    shading_theme: Theme | str | None = None,
    *,
    hlr: HLRMode = "exact",
    hlr_resolution: int = 2048,
    hlr_gpu_face_threshold: int = 250,
) -> SheetView:
    """Add a projected orthographic/isometric view to the sheet."""
    if isinstance(shape_or_view, SheetView):
        view = shape_or_view
    else:
        view = project_shape_to_view(
            shape=shape_or_view,
            view_type=view_type,
            center_x=center[0],
            center_y=center[1],
            scale=scale,
            show_hidden=show_hidden,
            view_label=view_label,
            rotation_angle_deg=rotation_angle_deg,
            view_label_y=view_label_y,
            model_origin=model_origin,
            style=style,
            shading_dpi=shading_dpi,
            color_by_part=color_by_part,
            part_colors=part_colors,
            ssao=ssao,
            gpu=gpu,
            shading_theme=shading_theme,
            hlr=hlr,
            hlr_resolution=hlr_resolution,
            hlr_gpu_face_threshold=hlr_gpu_face_threshold,
        )
    if align_to is not None:
        _apply_align_to(view, align_to)
    view.sheet = self
    if view not in self.views:
        self.views.append(view)
    for ann in view.annotations:
        if ann not in self.annotations:
            self.annotations.append(ann)
    return view

update_shape(new_shape)

Update the 3D model across all views on the sheet and re-bind anchored annotations.

Every view is checked before any is changed, so a view that cannot be regenerated raises ValueError without leaving the sheet half-updated. Detail views are updated last so they re-cut their already-updated parent view.

Source code in src/build123d_techdraw/core/sheet.py
def update_shape(self, new_shape: Any) -> Self:
    """Update the 3D model across all views on the sheet and re-bind anchored annotations.

    Every view is checked before any is changed, so a view that cannot be regenerated
    raises ``ValueError`` without leaving the sheet half-updated. Detail views are
    updated last so they re-cut their already-updated parent view.
    """
    stale = [v for v in self.views if not v.can_regenerate()]
    if stale:
        names = ", ".join(f"{v.view_type.value} {v.view_label or ''!r}" for v in stale)
        raise ValueError(
            f"Cannot update shape: these views have no recorded build parameters: {names}"
        )
    ordered = [v for v in self.views if v.view_type != ViewType.DETAIL] + [
        v for v in self.views if v.view_type == ViewType.DETAIL
    ]
    for view in ordered:
        view.update_shape(new_shape)
    return self

add_section_view(shape, cutting_plane, center=(150.0, 150.0), scale=1.0, view_label='SECTION A-A', view_label_y=None, model_origin=None, align_to=None, show_background=True, hatch='steel', hatch_pitch=4.0, hatch_angle=45.0)

Add a 2D section slice view with material hatching to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_section_view(
    self,
    shape: bd.Solid | bd.Compound | Any,
    cutting_plane: bd.Plane,
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    view_label: str = "SECTION A-A",
    view_label_y: float | None = None,
    model_origin: tuple[float, float] | None = None,
    align_to: AlignSpec | None = None,
    show_background: bool = True,
    hatch: str = "steel",
    hatch_pitch: float = 4.0,
    hatch_angle: float = 45.0,
) -> SheetView:
    """Add a 2D section slice view with material hatching to the sheet."""
    view = project_section_to_view(
        shape=shape,
        cutting_plane=cutting_plane,
        center_x=center[0],
        center_y=center[1],
        scale=scale,
        view_label=view_label,
        view_label_y=view_label_y,
        model_origin=model_origin,
        show_background=show_background,
        hatch=hatch,
        hatch_pitch=hatch_pitch,
        hatch_angle=hatch_angle,
    )
    return self._register_view(view, align_to)

add_half_section_view(shape, cutting_plane, center=(150.0, 150.0), scale=1.0, section_half='top', view_label='HALF SECTION', view_label_y=None, model_origin=None, align_to=None, show_background=True, hatch='steel', hatch_pitch=4.0, hatch_angle=45.0)

Add an ISO 128-3 half-section view (one half sectioned, opposite half external).

Source code in src/build123d_techdraw/core/sheet.py
def add_half_section_view(
    self,
    shape: bd.Solid | bd.Compound | Any,
    cutting_plane: bd.Plane,
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    section_half: str = "top",
    view_label: str | None = "HALF SECTION",
    view_label_y: float | None = None,
    model_origin: tuple[float, float] | None = None,
    align_to: AlignSpec | None = None,
    show_background: bool = True,
    hatch: str = "steel",
    hatch_pitch: float = 4.0,
    hatch_angle: float = 45.0,
) -> SheetView:
    """Add an ISO 128-3 half-section view (one half sectioned, opposite half external)."""
    view = project_half_section_to_view(
        shape=shape,
        cutting_plane=cutting_plane,
        center_x=center[0],
        center_y=center[1],
        scale=scale,
        section_half=section_half,
        view_label=view_label,
        view_label_y=view_label_y,
        model_origin=model_origin,
        show_background=show_background,
        hatch=hatch,
        hatch_pitch=hatch_pitch,
        hatch_angle=hatch_angle,
    )
    return self._register_view(view, align_to)

add_offset_section_view(shape, base_plane, points, center=(150.0, 150.0), scale=1.0, view_label='SECTION A-A', view_label_y=None, model_origin=None, align_to=None, show_background=True, show_jog_lines=False, hatch='steel', hatch_pitch=4.0, hatch_angle=45.0)

Add a stepped/offset section view along a multi-jog cutting path.

Source code in src/build123d_techdraw/core/sheet.py
def add_offset_section_view(
    self,
    shape: bd.Solid | bd.Compound | Any,
    base_plane: bd.Plane,
    points: Sequence[Any],
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    view_label: str = "SECTION A-A",
    view_label_y: float | None = None,
    model_origin: tuple[float, float] | None = None,
    align_to: AlignSpec | None = None,
    show_background: bool = True,
    show_jog_lines: bool = False,
    hatch: str = "steel",
    hatch_pitch: float = 4.0,
    hatch_angle: float = 45.0,
) -> SheetView:
    """Add a stepped/offset section view along a multi-jog cutting path."""
    view = project_offset_section_to_view(
        shape=shape,
        base_plane=base_plane,
        points=points,
        center_x=center[0],
        center_y=center[1],
        scale=scale,
        view_label=view_label,
        view_label_y=view_label_y,
        model_origin=model_origin,
        show_background=show_background,
        show_jog_lines=show_jog_lines,
        hatch=hatch,
        hatch_pitch=hatch_pitch,
        hatch_angle=hatch_angle,
    )
    return self._register_view(view, align_to)

add_aligned_section_view(shape, base_plane, points, center=(150.0, 150.0), scale=1.0, view_label='SECTION A-A', view_label_y=None, model_origin=None, align_to=None, show_background=True, show_jog_lines=False, hatch='steel', hatch_pitch=4.0, hatch_angle=45.0)

Add an aligned/revolved section view unfolding angled legs onto base_plane.

Source code in src/build123d_techdraw/core/sheet.py
def add_aligned_section_view(
    self,
    shape: bd.Solid | bd.Compound | Any,
    base_plane: bd.Plane,
    points: Sequence[Any],
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    view_label: str = "SECTION A-A",
    view_label_y: float | None = None,
    model_origin: tuple[float, float] | None = None,
    align_to: AlignSpec | None = None,
    show_background: bool = True,
    show_jog_lines: bool = False,
    hatch: str = "steel",
    hatch_pitch: float = 4.0,
    hatch_angle: float = 45.0,
) -> SheetView:
    """Add an aligned/revolved section view unfolding angled legs onto base_plane."""
    view = project_aligned_section_to_view(
        shape=shape,
        base_plane=base_plane,
        points=points,
        center_x=center[0],
        center_y=center[1],
        scale=scale,
        view_label=view_label,
        view_label_y=view_label_y,
        model_origin=model_origin,
        show_background=show_background,
        show_jog_lines=show_jog_lines,
        hatch=hatch,
        hatch_pitch=hatch_pitch,
        hatch_angle=hatch_angle,
    )
    return self._register_view(view, align_to)

add_detail_view(parent_view, focus_target=None, radius=12.0, scale=2.0, center=(150.0, 150.0), view_label=None, label_letter='A', view_label_y=None, align_to=None, shape='circle', region_center=None, label=None)

Add a magnified circular or rectangular detail view to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_detail_view(
    self,
    parent_view: SheetView,
    focus_target: Any = None,
    radius: float = 12.0,
    scale: float = 2.0,
    center: tuple[float, float] = (150.0, 150.0),
    view_label: str | None = None,
    label_letter: str = "A",
    view_label_y: float | None = None,
    align_to: AlignSpec | None = None,
    shape: str = "circle",
    region_center: Any = None,
    label: str | None = None,
) -> SheetView:
    """Add a magnified circular or rectangular detail view to the sheet."""
    view = project_detail_to_view(
        parent_view=parent_view,
        focus_target=focus_target,
        radius=radius,
        scale=scale,
        center_x=center[0],
        center_y=center[1],
        view_label=view_label,
        label_letter=label_letter,
        view_label_y=view_label_y,
        shape=shape,
        region_center=region_center,
        label=label,
    )
    if align_to is not None:
        _apply_align_to(view, align_to)
    view.sheet = self
    if view not in self.views:
        self.views.append(view)
    return view

add_auxiliary_view(shape, face, center=(150.0, 150.0), scale=1.0, show_hidden=True, view_label='AUXILIARY VIEW', view_label_y=None, align_to=None)

Add an auxiliary view normal to an inclined face.

Source code in src/build123d_techdraw/core/sheet.py
def add_auxiliary_view(
    self,
    shape: bd.Solid | bd.Compound | Any,
    face: Any,
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    show_hidden: bool = True,
    view_label: str = "AUXILIARY VIEW",
    view_label_y: float | None = None,
    align_to: AlignSpec | None = None,
) -> SheetView:
    """Add an auxiliary view normal to an inclined face."""
    view = project_auxiliary_view(
        shape=shape,
        face=face,
        center_x=center[0],
        center_y=center[1],
        scale=scale,
        show_hidden=show_hidden,
        view_label=view_label,
        view_label_y=view_label_y,
    )
    if align_to is not None:
        _apply_align_to(view, align_to)
    view.sheet = self
    if view not in self.views:
        self.views.append(view)
    return view

add_flat_pattern(shape, center=(150.0, 150.0), scale=1.0, *, k_factor='din6935', thickness=None, base_face=None, recognize_punches=True, align_longest_horizontal=True, annotate_bends=True, annotate_punches=True, show_bend_extents=False, view_label='FLAT PATTERN', view_label_y=None, align_to=None)

Unfold a 3D sheet metal part (or wrap a FlatPattern) and add its flat pattern view.

Source code in src/build123d_techdraw/core/sheet.py
def add_flat_pattern(
    self,
    shape: Any,
    center: tuple[float, float] = (150.0, 150.0),
    scale: float = 1.0,
    *,
    k_factor: float | str = "din6935",
    thickness: float | None = None,
    base_face: bd.Face | None = None,
    recognize_punches: bool = True,
    align_longest_horizontal: bool = True,
    annotate_bends: bool = True,
    annotate_punches: bool = True,
    show_bend_extents: bool = False,
    view_label: str = "FLAT PATTERN",
    view_label_y: float | None = None,
    align_to: AlignSpec | None = None,
) -> SheetView:
    """Unfold a 3D sheet metal part (or wrap a ``FlatPattern``) and add its flat pattern view."""
    from build123d_techdraw.core.view import project_flat_pattern_to_view

    view = project_flat_pattern_to_view(
        shape=shape,
        center_x=center[0],
        center_y=center[1],
        scale=scale,
        k_factor=k_factor,
        thickness=thickness,
        base_face=base_face,
        recognize_punches=recognize_punches,
        align_longest_horizontal=align_longest_horizontal,
        view_label=view_label,
        view_label_y=view_label_y,
    )
    self._register_view(view, align_to)
    if annotate_punches:
        view.add_punch_markers()
    if annotate_bends:
        view.add_bend_annotations(show_bend_extents=show_bend_extents)
    return view

add_sheet_metal_views(shape, **kwargs)

Create a complete sheet metal drawing layout (flat pattern, 3D iso, bend & punch schedules).

Source code in src/build123d_techdraw/core/sheet.py
def add_sheet_metal_views(
    self,
    shape: Any,
    **kwargs: Any,
) -> SheetMetalLayout:
    """Create a complete sheet metal drawing layout (flat pattern, 3D iso, bend & punch schedules)."""
    from build123d_techdraw.layout.sheet_metal import add_sheet_metal_views

    return add_sheet_metal_views(self, shape, **kwargs)

add_dimension(start, end, offset=8.0, dim_type=DimensionType.ALIGNED, text=None, tolerance=None, prefix='', suffix='', nominal=None, view=None)

Add a linear dimension directly in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_dimension(
    self,
    start: tuple[float, float],
    end: tuple[float, float],
    offset: float = 8.0,
    dim_type: DimensionType = DimensionType.ALIGNED,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
    prefix: str = "",
    suffix: str = "",
    nominal: float | None = None,
    view: SheetView | None = None,
) -> LinearDimension:
    """Add a linear dimension directly in sheet paper coordinates."""
    dim = LinearDimension(
        start=start,
        end=end,
        offset=offset,
        dim_type=dim_type,
        text=text,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        nominal=nominal,
        view=view,
    )
    if dim not in self.annotations:
        self.annotations.append(dim)
    if view is not None and dim not in view.annotations:
        view.annotations.append(dim)
    return dim

add_radial_dimension(center, radius, angle_deg=45.0, text=None, tolerance=None)

Add a radial dimension in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_radial_dimension(
    self,
    center: tuple[float, float],
    radius: float,
    angle_deg: float = 45.0,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
) -> RadialDimension:
    """Add a radial dimension in sheet paper coordinates."""
    dim = RadialDimension(
        center=center,
        radius=radius,
        angle_deg=angle_deg,
        text=text,
        tolerance=tolerance,
    )
    if dim not in self.annotations:
        self.annotations.append(dim)
    return dim

add_diameter_dimension(center, diameter, angle_deg=45.0, text=None, tolerance=None)

Add a diameter dimension in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_diameter_dimension(
    self,
    center: tuple[float, float],
    diameter: float,
    angle_deg: float = 45.0,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
) -> DiameterDimension:
    """Add a diameter dimension in sheet paper coordinates."""
    dim = DiameterDimension(
        center=center,
        diameter=diameter,
        angle_deg=angle_deg,
        text=text,
        tolerance=tolerance,
    )
    if dim not in self.annotations:
        self.annotations.append(dim)
    return dim

add_angular_dimension(target1, target2, radius=20.0, text=None, tolerance=None, prefix='', suffix='°', apex=None, view=None)

Add an angular dimension to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_angular_dimension(
    self,
    target1: Any,
    target2: Any,
    radius: float = 20.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "°",
    apex: tuple[float, float] | None = None,
    view: SheetView | None = None,
) -> AngularDimension:
    """Add an angular dimension to the sheet."""
    dim = AngularDimension(
        target1=target1,
        target2=target2,
        radius=radius,
        text=text,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        apex=apex,
        view=view,
    )
    if dim not in self.annotations:
        self.annotations.append(dim)
    if view is not None and dim not in view.annotations:
        view.annotations.append(dim)
    return dim

add_ordinate(target, datum_coord=0.0, direction='horizontal', jog=0.0, extension_length=12.0, prefix='', suffix='', view=None)

Add an ordinate dimension point to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_ordinate(
    self,
    target: Any,
    datum_coord: float = 0.0,
    direction: str = "horizontal",
    jog: float = 0.0,
    extension_length: float = 12.0,
    prefix: str = "",
    suffix: str = "",
    view: SheetView | None = None,
) -> OrdinateDimension:
    """Add an ordinate dimension point to the sheet."""
    dim = OrdinateDimension(
        target=target,
        datum_coord=datum_coord,
        direction=direction,
        jog=jog,
        extension_length=extension_length,
        prefix=prefix,
        suffix=suffix,
        view=view,
    )
    if dim not in self.annotations:
        self.annotations.append(dim)
    if view is not None and dim not in view.annotations:
        view.annotations.append(dim)
    return dim

add_chamfer_callout(target, width=None, angle_deg=45.0, style='iso', quantity=None, elbow_offset=(15.0, -12.0), view=None)

Add an ISO/ASME chamfer callout note to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_chamfer_callout(
    self,
    target: Any,
    width: float | None = None,
    angle_deg: float = 45.0,
    style: str = "iso",
    quantity: int | None = None,
    elbow_offset: tuple[float, float] = (15.0, -12.0),
    view: SheetView | None = None,
) -> ChamferCallout:
    """Add an ISO/ASME chamfer callout note to the sheet."""
    cc = ChamferCallout(
        target_or_edge=target,
        width=width,
        angle_deg=angle_deg,
        style=style,
        quantity=quantity,
        elbow_offset=elbow_offset,
        view=view,
    )
    if cc not in self.annotations:
        self.annotations.append(cc)
    if view is not None and cc not in view.annotations:
        view.annotations.append(cc)
    return cc

add_half_diameter_dimension(feature_point, centerline_coord, diameter=None, orientation='vertical', offset=0.0, past_centerline=5.0, text=None, tolerance=None, view=None)

Add an ISO 129-1 §5.2.3 diametral centerline half-dimension in sheet space.

Source code in src/build123d_techdraw/core/sheet.py
def add_half_diameter_dimension(
    self,
    feature_point: tuple[float, float],
    centerline_coord: float,
    diameter: float | None = None,
    orientation: str = "vertical",
    offset: float = 0.0,
    past_centerline: float = 5.0,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
    view: SheetView | None = None,
) -> HalfDiameterDimension:
    """Add an ISO 129-1 §5.2.3 diametral centerline half-dimension in sheet space."""
    dim = HalfDiameterDimension(
        feature_point=feature_point,
        centerline_coord=centerline_coord,
        diameter=diameter,
        orientation=orientation,
        offset=offset,
        past_centerline=past_centerline,
        text=text,
        tolerance=tolerance,
        view=view,
    )
    if dim not in self.annotations:
        self.annotations.append(dim)
    if view is not None and dim not in view.annotations:
        view.annotations.append(dim)
    return dim

add_undercut_callout(target, spec='E 0.8x0.3', roughness=None, quantity=None, include_standard=True, elbow_offset=(15.0, -12.0), view=None)

Add a DIN 509 relief undercut callout note to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_undercut_callout(
    self,
    target: Any,
    spec: Any = "E 0.8x0.3",
    roughness: str | None = None,
    quantity: int | None = None,
    include_standard: bool = True,
    elbow_offset: tuple[float, float] = (15.0, -12.0),
    view: SheetView | None = None,
) -> UndercutCallout:
    """Add a DIN 509 relief undercut callout note to the sheet."""
    uc = UndercutCallout(
        target=target,
        spec=spec,
        roughness=roughness,
        quantity=quantity,
        include_standard=include_standard,
        elbow_offset=elbow_offset,
        view=view,
    )
    if uc not in self.annotations:
        self.annotations.append(uc)
    if view is not None and uc not in view.annotations:
        view.annotations.append(uc)
    return uc

add_welding_symbol(target, weld_type=WeldType.FILLET, size='a5', length=None, pitch=None, all_around=False, field_weld=False, tail_text=None, arrow_side=True, elbow_offset=(16.0, -12.0), view=None)

Add an ISO 2553 welding annotation to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_welding_symbol(
    self,
    target: Any,
    weld_type: WeldType | str = WeldType.FILLET,
    size: str | float | None = "a5",
    length: str | float | None = None,
    pitch: str | float | None = None,
    all_around: bool = False,
    field_weld: bool = False,
    tail_text: str | None = None,
    arrow_side: bool = True,
    elbow_offset: tuple[float, float] = (16.0, -12.0),
    view: SheetView | None = None,
) -> WeldingSymbol:
    """Add an ISO 2553 welding annotation to the sheet."""
    ws = WeldingSymbol(
        target=target,
        weld_type=weld_type,
        size=size,
        length=length,
        pitch=pitch,
        all_around=all_around,
        field_weld=field_weld,
        tail_text=tail_text,
        arrow_side=arrow_side,
        elbow_offset=elbow_offset,
        view=view,
    )
    if ws not in self.annotations:
        self.annotations.append(ws)
    if view is not None and ws not in view.annotations:
        view.annotations.append(ws)
    return ws

lint()

Inspect sheet layout, annotations, and margins for drawing defects.

Source code in src/build123d_techdraw/core/sheet.py
def lint(self) -> list[LintIssue]:
    """Inspect sheet layout, annotations, and margins for drawing defects."""
    return run_sheet_lint(self)

inspect_layout()

Return a structured layout dictionary of canvas, views, title blocks, and annotations for AI and CI inspection.

Source code in src/build123d_techdraw/core/sheet.py
def inspect_layout(self) -> dict[str, Any]:
    """Return a structured layout dictionary of canvas, views, title blocks, and annotations for AI and CI inspection."""
    drawable = [
        round(self.left_margin, 2),
        round(self.top_margin, 2),
        round(self.width_mm - self.right_margin, 2),
        round(self.height_mm - self.bottom_margin, 2),
    ]
    if self.template is not None:
        tb_bb = self.template.title_block_bbox(self)
        tb_bounds = (
            [round(tb_bb[0], 2), round(tb_bb[1], 2), round(tb_bb[2], 2), round(tb_bb[3], 2)]
            if (self.show_title_block or self.template.mode is TemplateMode.SHEET)
            else [0.0, 0.0, 0.0, 0.0]
        )
    else:
        tb_w = 180.0
        tb_h = 36.0
        tb_bounds = (
            [
                round(self.width_mm - self.right_margin - tb_w, 2),
                round(self.height_mm - self.bottom_margin - tb_h, 2),
                round(self.width_mm - self.right_margin, 2),
                round(self.height_mm - self.bottom_margin, 2),
            ]
            if self.show_title_block
            else [0.0, 0.0, 0.0, 0.0]
        )

    views_info = []
    for v in self.views:
        v_bounds = [
            round(v.min_x, 2),
            round(v.min_y, 2),
            round(v.max_x, 2),
            round(v.max_y, 2),
        ]
        vis_bounds = [round(x, 2) for x in v.get_visual_bounds()]
        views_info.append(
            {
                "label": v.view_label or v.view_type.value.upper(),
                "view_type": v.view_type.value,
                "bounds": v_bounds,
                "visual_bounds": vis_bounds,
                "scale": round(v.scale, 4),
                "center": (round(v.center_x, 2), round(v.center_y, 2)),
                "annotations_count": len(v.annotations),
            }
        )

    mid_x = (drawable[0] + drawable[2]) / 2.0
    mid_y = (drawable[1] + drawable[3]) / 2.0
    quadrants = {
        "top-left": (drawable[0], drawable[1], mid_x, mid_y),
        "top-right": (mid_x, drawable[1], drawable[2], mid_y),
        "bottom-left": (drawable[0], mid_y, mid_x, drawable[3]),
        "bottom-right": (mid_x, mid_y, drawable[2], drawable[3]),
    }

    free_quads = []
    for q_name, (qx1, qy1, qx2, qy2) in quadrants.items():
        occupied = False
        if self.show_title_block and not (
            tb_bounds[2] <= qx1
            or tb_bounds[0] >= qx2
            or tb_bounds[3] <= qy1
            or tb_bounds[1] >= qy2
        ):
            occupied = True
        if not occupied:
            for v in self.views:
                vb = v.get_visual_bounds()
                if not (vb[2] <= qx1 or vb[0] >= qx2 or vb[3] <= qy1 or vb[1] >= qy2):
                    occupied = True
                    break
        if not occupied:
            free_quads.append(q_name)

    lint_res = self.lint()
    return {
        "sheet_size": (round(self.width_mm, 2), round(self.height_mm, 2)),
        "drawable_bounds": drawable,
        "title_block_bounds": tb_bounds,
        "views": views_info,
        "annotations_count": len(self.annotations),
        "free_quadrants": free_quads,
        "lint_issues_count": len(lint_res),
        "lint_issues": [
            {"code": i.code, "severity": i.severity, "message": i.message} for i in lint_res
        ],
    }

add_gdt_frame(position, characteristic, tolerance_value, datum_a=None, datum_b=None, datum_c=None)

Add a GD&T Feature Control Frame in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_gdt_frame(
    self,
    position: tuple[float, float],
    characteristic: GDTCharacteristic,
    tolerance_value: str,
    datum_a: str | None = None,
    datum_b: str | None = None,
    datum_c: str | None = None,
) -> FeatureControlFrame:
    """Add a GD&T Feature Control Frame in sheet paper coordinates."""
    fcf = FeatureControlFrame(
        position=position,
        characteristic=characteristic,
        tolerance_value=tolerance_value,
        datum_a=datum_a,
        datum_b=datum_b,
        datum_c=datum_c,
    )
    if fcf not in self.annotations:
        self.annotations.append(fcf)
    return fcf

add_datum_symbol(target, label='A', direction='up')

Add an ISO datum feature identifier symbol.

Source code in src/build123d_techdraw/core/sheet.py
def add_datum_symbol(
    self,
    target: tuple[float, float],
    label: str = "A",
    direction: str = "up",
) -> DatumFeatureSymbol:
    """Add an ISO datum feature identifier symbol."""
    sym = DatumFeatureSymbol(target=target, label=label, direction=direction)
    if sym not in self.annotations:
        self.annotations.append(sym)
    return sym

add_surface_finish(position, ra_value='Ra 3.2', material_removal=MaterialRemoval.REQUIRED, process=None)

Add an ISO 1302 surface roughness / finish symbol.

Source code in src/build123d_techdraw/core/sheet.py
def add_surface_finish(
    self,
    position: tuple[float, float],
    ra_value: str = "Ra 3.2",
    material_removal: MaterialRemoval = MaterialRemoval.REQUIRED,
    process: str | None = None,
) -> SurfaceFinishSymbol:
    """Add an ISO 1302 surface roughness / finish symbol."""
    sym = SurfaceFinishSymbol(
        position=position,
        ra_value=ra_value,
        material_removal=material_removal,
        process=process,
    )
    if sym not in self.annotations:
        self.annotations.append(sym)
    return sym

add_centerline(start, end, stroke_width=0.25)

Add an ISO dash-dot centerline between two sheet points.

Source code in src/build123d_techdraw/core/sheet.py
def add_centerline(
    self,
    start: tuple[float, float],
    end: tuple[float, float],
    stroke_width: float = 0.25,
) -> Centerline:
    """Add an ISO dash-dot centerline between two sheet points."""
    cl = Centerline(start=start, end=end, stroke_width=stroke_width)
    if cl not in self.annotations:
        self.annotations.append(cl)
    return cl

add_centermark(center, size=6.0)

Add an ISO center crosshair.

Source code in src/build123d_techdraw/core/sheet.py
def add_centermark(
    self,
    center: tuple[float, float],
    size: float = 6.0,
) -> CenterMark:
    """Add an ISO center crosshair."""
    cm = CenterMark(center=center, size=size)
    if cm not in self.annotations:
        self.annotations.append(cm)
    return cm

add_bolt_circle(center, diameter, num_holes=4, start_angle_deg=0.0)

Add a bolt pitch circle diameter (PCD) annotation.

Source code in src/build123d_techdraw/core/sheet.py
def add_bolt_circle(
    self,
    center: tuple[float, float],
    diameter: float,
    num_holes: int = 4,
    start_angle_deg: float = 0.0,
) -> BoltCircle:
    """Add a bolt pitch circle diameter (PCD) annotation."""
    bc = BoltCircle(
        center=center,
        diameter=diameter,
        num_holes=num_holes,
        start_angle_deg=start_angle_deg,
    )
    if bc not in self.annotations:
        self.annotations.append(bc)
    return bc

add_leader_note(target, lines, elbow_offset=(15.0, -12.0), shelf_length=20.0, align_right=None, terminator='dot')

Add a leader note with pointer dot/arrow, elbow, and horizontal text shelf.

Source code in src/build123d_techdraw/core/sheet.py
def add_leader_note(
    self,
    target: tuple[float, float],
    lines: list[str] | str,
    elbow_offset: tuple[float, float] = (15.0, -12.0),
    shelf_length: float = 20.0,
    align_right: bool | None = None,
    terminator: str = "dot",
) -> LeaderNote:
    """Add a leader note with pointer dot/arrow, elbow, and horizontal text shelf."""
    line_list = [lines] if isinstance(lines, str) else list(lines)
    note = LeaderNote(
        target=target,
        lines=line_list,
        elbow_offset=elbow_offset,
        shelf_length=shelf_length,
        align_right=align_right,
        terminator=terminator,
    )
    if note not in self.annotations:
        self.annotations.append(note)
    return note

add_hole_callout(center, diameter=None, depth=None, countersink_dia=None, countersink_angle=90.0, counterbore_dia=None, counterbore_depth=None, quantity=None, tolerance=None, clearance_for=None, fit='medium', elbow_offset=(15.0, -12.0))

Add a standard engineering hole callout in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_hole_callout(
    self,
    center: tuple[float, float],
    diameter: float | None = None,
    depth: float | str | None = None,
    countersink_dia: float | None = None,
    countersink_angle: float = 90.0,
    counterbore_dia: float | None = None,
    counterbore_depth: float | None = None,
    quantity: int | None = None,
    tolerance: str | None = None,
    clearance_for: str | None = None,
    fit: str = "medium",
    elbow_offset: tuple[float, float] = (15.0, -12.0),
) -> HoleCallout:
    """Add a standard engineering hole callout in sheet paper coordinates."""
    hc = HoleCallout(
        center=center,
        diameter=diameter,
        depth=depth,
        countersink_dia=countersink_dia,
        countersink_angle=countersink_angle,
        counterbore_dia=counterbore_dia,
        counterbore_depth=counterbore_depth,
        quantity=quantity,
        tolerance=tolerance,
        clearance_for=clearance_for,
        fit=fit,
        elbow_offset=elbow_offset,
    )
    if hc not in self.annotations:
        self.annotations.append(hc)
    return hc

add_thread_callout(center, thread='M5x0.8', depth='THRU', class_fit=None, quantity=None, show_tap_drill=False, elbow_offset=(15.0, -12.0))

Add a standard engineering thread callout in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_thread_callout(
    self,
    center: tuple[float, float],
    thread: str = "M5x0.8",
    depth: float | str | None = "THRU",
    class_fit: str | None = None,
    quantity: int | None = None,
    show_tap_drill: bool = False,
    elbow_offset: tuple[float, float] = (15.0, -12.0),
) -> ThreadCallout:
    """Add a standard engineering thread callout in sheet paper coordinates."""
    tc = ThreadCallout(
        center=center,
        thread=thread,
        depth=depth,
        class_fit=class_fit,
        quantity=quantity,
        show_tap_drill=show_tap_drill,
        elbow_offset=elbow_offset,
    )
    if tc not in self.annotations:
        self.annotations.append(tc)
    return tc

add_cosmetic_thread(center=None, thread=None, nominal_diameter=None, minor_diameter=None, thread_type='internal', depth=None, start=None, end=None, view_mode=None)

Add an ISO 6410-1 cosmetic thread in sheet paper coordinates.

Source code in src/build123d_techdraw/core/sheet.py
def add_cosmetic_thread(
    self,
    center: tuple[float, float] | None = None,
    thread: str | Any | None = None,
    nominal_diameter: float | None = None,
    minor_diameter: float | None = None,
    thread_type: str = "internal",
    depth: float | None = None,
    start: tuple[float, float] | None = None,
    end: tuple[float, float] | None = None,
    view_mode: str | None = None,
) -> CosmeticThread:
    """Add an ISO 6410-1 cosmetic thread in sheet paper coordinates."""
    ct = CosmeticThread(
        thread=thread,
        nominal_diameter=nominal_diameter,
        minor_diameter=minor_diameter,
        thread_type=thread_type,
        depth=depth,
        center=center,
        start=start,
        end=end,
        view_mode=view_mode,
    )
    if ct not in self.annotations:
        self.annotations.append(ct)
    return ct

add_table(headers=None, rows=None, position=(0.0, 0.0), col_widths=None, title=None, **kwargs)

Add a tabular schedule to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_table(
    self,
    headers: list[str] | None = None,
    rows: list[list[Any]] | None = None,
    position: tuple[float, float] = (0.0, 0.0),
    col_widths: list[float] | None = None,
    title: str | None = None,
    **kwargs: Any,
) -> Table:
    """Add a tabular schedule to the sheet."""
    tbl = Table(
        headers=headers,
        rows=rows,
        position=position,
        col_widths=col_widths,
        title=title,
        sheet=self,
        **kwargs,
    )
    if tbl not in self.annotations:
        self.annotations.append(tbl)
    return tbl

add_raw_svg(content, position=(0.0, 0.0), **kwargs)

Add a raw SVG vector element to the sheet.

Source code in src/build123d_techdraw/core/sheet.py
def add_raw_svg(
    self,
    content: str,
    position: tuple[float, float] = (0.0, 0.0),
    **kwargs: Any,
) -> RawSVG:
    """Add a raw SVG vector element to the sheet."""
    raw = RawSVG(content=content, position=position, sheet=self, **kwargs)
    if raw not in self.annotations:
        self.annotations.append(raw)
    return raw

add_balloon(item_no, target, balloon_center, radius=4.5, terminator='dot')

Add an ISO BOM balloon callout circle connected to component via leader.

Source code in src/build123d_techdraw/core/sheet.py
def add_balloon(
    self,
    item_no: int,
    target: tuple[float, float],
    balloon_center: tuple[float, float],
    radius: float = 4.5,
    terminator: str = "dot",
) -> BOMBalloon:
    """Add an ISO BOM balloon callout circle connected to component via leader."""
    balloon = BOMBalloon(
        item_no=item_no,
        target=target,
        balloon_center=balloon_center,
        radius=radius,
        terminator=terminator,
    )
    if balloon not in self.annotations:
        self.annotations.append(balloon)
    return balloon

add_section_cutting_line(points, label='A', arrow_dir='up')

Add an ISO section cutting plane line.

Source code in src/build123d_techdraw/core/sheet.py
def add_section_cutting_line(
    self,
    points: Sequence[Any],
    label: str = "A",
    arrow_dir: str | tuple[float, float] = "up",
) -> SectionCuttingLine:
    """Add an ISO section cutting plane line."""
    cut = SectionCuttingLine(
        points=points,
        label=label,
        arrow_dir=arrow_dir,
    )
    if cut not in self.annotations:
        self.annotations.append(cut)
    return cut

render_border_and_grid()

Render ISO 5457 borders, centering marks, and alphanumeric grid zones.

Source code in src/build123d_techdraw/core/sheet.py
def render_border_and_grid(self) -> str:
    """Render ISO 5457 borders, centering marks, and alphanumeric grid zones."""
    if not self.show_border and not self.show_grid:
        return ""
    w = self.width_mm
    h = self.height_mm
    bx = self.left_margin
    by = self.top_margin
    bw = w - self.left_margin - self.right_margin
    bh = h - self.top_margin - self.bottom_margin

    num_cols = 8 if w > 350 else 6
    num_rows = 6 if h > 250 else 4
    col_w = bw / num_cols
    row_h = bh / num_rows

    grid_lines: list[str] = []
    labels: list[str] = []

    # Vertical grid ticks and column numbers
    for i in range(num_cols + 1):
        gx = bx + i * col_w
        grid_lines.append(
            f'<line x1="{gx:.2f}" y1="{by - 3.0:.2f}" x2="{gx:.2f}" y2="{by:.2f}" class="border-sub"/>'
        )
        grid_lines.append(
            f'<line x1="{gx:.2f}" y1="{by + bh:.2f}" x2="{gx:.2f}" y2="{by + bh + 3.0:.2f}" class="border-sub"/>'
        )
        if i < num_cols:
            zone_num = str(num_cols - i)
            labels.append(
                f'<text x="{gx + col_w / 2:.2f}" y="{by - 1.0:.2f}" class="zone-text">{zone_num}</text>'
            )
            labels.append(
                f'<text x="{gx + col_w / 2:.2f}" y="{by + bh + 4.5:.2f}" class="zone-text">{zone_num}</text>'
            )

    # Horizontal grid ticks and row letters
    row_letters = ["A", "B", "C", "D", "E", "F", "G", "H"]
    for j in range(num_rows + 1):
        gy = by + j * row_h
        grid_lines.append(
            f'<line x1="{bx - 3.0:.2f}" y1="{gy:.2f}" x2="{bx:.2f}" y2="{gy:.2f}" class="border-sub"/>'
        )
        grid_lines.append(
            f'<line x1="{bx + bw:.2f}" y1="{gy:.2f}" x2="{bx + bw + 3.0:.2f}" y2="{gy:.2f}" class="border-sub"/>'
        )
        if j < num_rows:
            zone_let = row_letters[j % len(row_letters)]
            labels.append(
                f'<text x="{bx - 1.8:.2f}" y="{gy + row_h / 2 + 1.2:.2f}" class="zone-text">{zone_let}</text>'
            )
            labels.append(
                f'<text x="{bx + bw + 1.8:.2f}" y="{gy + row_h / 2 + 1.2:.2f}" class="zone-text">{zone_let}</text>'
            )

    # Centering marks (ISO 5457 section 4.3)
    mid_x = bx + bw / 2.0
    mid_y = by + bh / 2.0
    cm_len = 5.0
    centering_marks = f"""
    <line x1="{mid_x:.2f}" y1="0" x2="{mid_x:.2f}" y2="{cm_len}" class="border-main" stroke-width="0.7"/>
    <line x1="{mid_x:.2f}" y1="{h - cm_len:.2f}" x2="{mid_x:.2f}" y2="{h:.2f}" class="border-main" stroke-width="0.7"/>
    <line x1="0" y1="{mid_y:.2f}" x2="{cm_len}" y2="{mid_y:.2f}" class="border-main" stroke-width="0.7"/>
    <line x1="{w - cm_len:.2f}" y1="{mid_y:.2f}" x2="{w:.2f}" y2="{mid_y:.2f}" class="border-main" stroke-width="0.7"/>
    """

    return f"""
    <rect x="0" y="0" width="{w}" height="{h}" class="sheet-bg"/>
    <rect x="0" y="0" width="{w}" height="{h}" class="blueprint-grid" fill="url(#techGrid)"/>
    <rect x="2" y="2" width="{w - 4}" height="{h - 4}" class="border-sub" stroke-width="0.25" fill="none"/>
    <rect x="{bx:.2f}" y="{by:.2f}" width="{bw:.2f}" height="{bh:.2f}" class="border-main" stroke-width="0.7" fill="none"/>
    {centering_marks}
    <g class="grid-ticks">{"".join(grid_lines)}</g>
    <g class="zone-labels">{"".join(labels)}</g>
    """

render_notes()

Render general notes block in bottom-left.

Source code in src/build123d_techdraw/core/sheet.py
def render_notes(self) -> str:
    """Render general notes block in bottom-left."""
    if not self.notes:
        return ""
    bx = self.left_margin + 5.0
    by = self.height_mm - self.bottom_margin - 30.0

    notes_svg: list[str] = [
        '<text x="0" y="0" class="tb-field-label" font-weight="bold">GENERAL NOTES:</text>'
    ]
    for i, note in enumerate(self.notes):
        notes_svg.append(
            f'<text x="0" y="{4.5 + i * 4.2:.2f}" class="notes-text">{note}</text>'
        )

    return f"""
    <g class="sheet-notes" transform="translate({bx:.2f}, {by:.2f})">
        {"".join(notes_svg)}
    </g>
    """

render_view_labels()

Render view titles and scale notes positioned cleanly below annotations.

Source code in src/build123d_techdraw/core/sheet.py
def render_view_labels(self) -> str:
    """Render view titles and scale notes positioned cleanly below annotations."""
    out: list[str] = []
    for v in self.views:
        if v.view_label and v.scale_label:
            vx = v.center_x
            # Position label dynamically below any bottom annotations with clearance
            vy = max(
                v.bottom_annotation_y + 8.0,
                v.view_label_pos[1] if v.view_label_pos else v.max_y + 8.0,
            )
            line_w = max(len(v.view_label) * 2.8, 20.0)
            out.append(f"""
            <text x="{vx:.2f}" y="{vy:.2f}" class="view-title" text-anchor="middle" font-size="4.2" font-weight="bold">{v.view_label}</text>
            <text x="{vx:.2f}" y="{vy + 3.8:.2f}" class="view-scale" text-anchor="middle" font-size="2.8">{v.scale_label}</text>
            <line x1="{vx - line_w / 2:.2f}" y1="{vy + 1.0:.2f}" x2="{vx + line_w / 2:.2f}" y2="{vy + 1.0:.2f}" class="border-sub" stroke-width="0.3"/>
            """)
    return f'<g class="view-labels">{"".join(out)}</g>'

render_hatch_defs()

Render standard ISO 128 / ANSI hatch patterns in SVG defs.

Source code in src/build123d_techdraw/core/sheet.py
def render_hatch_defs(self) -> str:
    """Render standard ISO 128 / ANSI hatch patterns in SVG defs."""
    patterns = [
        """<pattern id="sectionHatch" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>""",
        """<pattern id="hatch_steel" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>""",
        """<pattern id="hatch_aluminum" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
  <line x1="1.2" y1="0" x2="1.2" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>""",
        """<pattern id="hatch_brass" width="4" height="4" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
  <line x1="2" y1="0" x2="2" y2="4" stroke="var(--hatch-color)" stroke-width="0.35" stroke-dasharray="1.5,1.5"/>
</pattern>""",
        """<pattern id="hatch_plastic" width="4" height="4" patternTransform="rotate(60 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="4" stroke="var(--hatch-color)" stroke-width="0.35"/>
  <line x1="0" y1="0" x2="4" y2="0" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>""",
        """<pattern id="hatch_rubber" width="4" height="4" patternUnits="userSpaceOnUse">
  <circle cx="2" cy="2" r="0.45" fill="var(--hatch-color)"/>
  <circle cx="0" cy="0" r="0.45" fill="var(--hatch-color)"/>
  <circle cx="4" cy="0" r="0.45" fill="var(--hatch-color)"/>
  <circle cx="0" cy="4" r="0.45" fill="var(--hatch-color)"/>
  <circle cx="4" cy="4" r="0.45" fill="var(--hatch-color)"/>
</pattern>""",
    ]
    for v in self.views:
        h_id = v.hatch_id
        if h_id and not any(f'id="{h_id}"' in p for p in patterns):
            mat = v.hatch or "steel"
            pitch = v.hatch_pitch if v.hatch_pitch is not None else 4.0
            angle = v.hatch_angle if v.hatch_angle is not None else 45.0
            if mat in ("aluminum", "ansi38"):
                p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
  <line x1="{pitch * 0.3:.2f}" y1="0" x2="{pitch * 0.3:.2f}" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>"""
            elif mat in ("brass", "ansi32"):
                p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
  <line x1="{pitch * 0.5:.2f}" y1="0" x2="{pitch * 0.5:.2f}" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35" stroke-dasharray="1.5,1.5"/>
</pattern>"""
            elif mat in ("plastic", "rubber"):
                p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
  <line x1="0" y1="0" x2="{pitch:.2f}" y2="0" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>"""
            else:
                p_svg = f"""<pattern id="{h_id}" width="{pitch:.2f}" height="{pitch:.2f}" patternTransform="rotate({angle:.1f} 0 0)" patternUnits="userSpaceOnUse">
  <line x1="0" y1="0" x2="0" y2="{pitch:.2f}" stroke="var(--hatch-color)" stroke-width="0.35"/>
</pattern>"""
            patterns.append(p_svg)
    return "\n    ".join(patterns)

to_svg(theme=Theme.DARK_BLUEPRINT)

Render the complete drawing sheet to an SVG vector string.

Source code in src/build123d_techdraw/core/sheet.py
    def to_svg(self, theme: Theme | str = Theme.DARK_BLUEPRINT) -> str:
        """Render the complete drawing sheet to an SVG vector string."""
        if isinstance(theme, str):
            theme = (
                Theme.ISO_WHITE
                if theme.lower() in ("print", "white", "iso_white")
                else Theme.DARK_BLUEPRINT
            )
        w, h = self.width_mm, self.height_mm
        theme_class = "theme-iso-white" if theme == Theme.ISO_WHITE else "theme-dark-blueprint"

        view_elements = "".join([v.svg_content for v in self.views])

        # Annotation SVG rendering (dimensions, leaders, GD&T, tables, raw SVG, etc.)
        annotation_svgs = "".join([a.to_svg() for a in self.annotations])

        # Position BOM table (bottom-up above title block or top-right below revisions)
        if self.bom_position == "top_right":
            rev_h = 10.0 if self.revision_rows else 0.0
            bom_top_y = self.top_margin + rev_h + 2.0
        elif self.template is not None:
            tb_y = self.template.title_block_bbox(self)[1]
            bom_h = 5.5 + len(self.bom_items) * 5.2
            bom_top_y = tb_y - bom_h - 1.0
        else:
            extra_fields = self.title_info.extra_fields
            extra_rows = (
                (len(extra_fields) + min(3, len(extra_fields)) - 1) // min(3, len(extra_fields))
                if extra_fields
                else 0
            )
            tb_y = h - self.bottom_margin - 36.0 - extra_rows * 7.0
            bom_h = 5.5 + len(self.bom_items) * 5.2
            bom_top_y = tb_y - bom_h - 1.0

        template_defs = ""
        if self.template is None:
            border_svg = (
                self.render_border_and_grid() if (self.show_border or self.show_grid) else ""
            )
            tb_svg = (
                render_title_block_svg(self.title_info, w, h, self.right_margin, self.bottom_margin)
                if self.show_title_block and self.title_info
                else ""
            )
            rev_svg = (
                render_revision_table_svg(self.revision_rows, w, self.right_margin, self.top_margin)
                if self.show_title_block and self.revision_rows
                else ""
            )
        else:
            should_render_tpl = self.template.mode is TemplateMode.SHEET or self.show_title_block
            template_defs, template_body = (
                self.template.render_parts(self) if should_render_tpl else ("", "")
            )
            if self.template.mode is TemplateMode.SHEET:
                bg_rect = f'<rect x="0" y="0" width="{w}" height="{h}" class="sheet-bg"/>'
                grid_rect = (
                    f'\n        <rect x="0" y="0" width="{w}" height="{h}" class="blueprint-grid" fill="url(#techGrid)"/>'
                    if self.show_grid
                    else ""
                )
                border_svg = f"{bg_rect}{grid_rect}\n        {template_body}"
                tb_svg = ""
                show_rev = self.template.show_revision_table
                include_rev = bool(self.revision_rows) and (
                    (show_rev is True) or (show_rev is None and not self._revision_placeholder)
                )
                rev_svg = (
                    render_revision_table_svg(
                        self.revision_rows, w, self.right_margin, self.top_margin
                    )
                    if include_rev
                    else ""
                )
            else:
                border_svg = (
                    self.render_border_and_grid() if (self.show_border or self.show_grid) else ""
                )
                tb_svg = template_body if self.show_title_block else ""
                rev_svg = (
                    render_revision_table_svg(
                        self.revision_rows, w, self.right_margin, self.top_margin
                    )
                    if self.show_title_block and self.revision_rows
                    else ""
                )
        bom_svg = (
            render_bom_table_svg(self.bom_items, w, self.right_margin, bom_top_y)
            if self.bom_items
            else ""
        )
        notes_svg = self.render_notes() if self.show_notes else ""
        extra_defs = f"\n    {template_defs}" if template_defs else ""

        has_shaded = any(v.style is not ViewStyle.WIREFRAME for v in self.views)
        has_sheet_metal = any(
            v.view_type == ViewType.FLAT_PATTERN or v.flat_pattern is not None for v in self.views
        ) or any(
            isinstance(a, (BendLineAnnotation, PunchMarker, BendTable, PunchTable))
            for a in self.annotations
        )
        return f"""<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 {w} {h}"
     width="{w}mm"
     height="{h}mm"
     class="{theme_class}"
     id="sheet_{self.title_info.drawing_no}">
  <defs>
    <style type="text/css">
      {generate_theme_css(theme, include_shaded=has_shaded, include_sheet_metal=has_sheet_metal)}
    </style>
    <pattern id="techGrid" width="10" height="10" patternUnits="userSpaceOnUse">
      <path d="M 10 0 L 0 0 0 10" fill="none" stroke="var(--grid-color)" stroke-width="0.15"/>
      <circle cx="0" cy="0" r="0.3" fill="var(--grid-color)"/>
    </pattern>
    {self.render_hatch_defs()}{extra_defs}
  </defs>

  {border_svg}
  {tb_svg}
  {rev_svg}
  {bom_svg}
  {notes_svg}

  <g class="drawing-views">
    {view_elements}
  </g>

  {self.render_view_labels()}

  <g class="annotations">
    {annotation_svgs}
  </g>
</svg>
"""

export_svg(path, theme=Theme.DARK_BLUEPRINT)

Export sheet to an SVG file.

Source code in src/build123d_techdraw/core/sheet.py
def export_svg(self, path: str, theme: Theme | str = Theme.DARK_BLUEPRINT) -> None:
    """Export sheet to an SVG file."""
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    svg = self.to_svg(theme=theme)
    with open(path, "w", encoding="utf-8") as f:
        f.write(svg)

export_pdf(path, theme=Theme.DARK_BLUEPRINT)

Export sheet to a vector PDF file.

Source code in src/build123d_techdraw/core/sheet.py
def export_pdf(self, path: str, theme: Theme | str = Theme.DARK_BLUEPRINT) -> None:
    """Export sheet to a vector PDF file."""
    from build123d_techdraw.renderers.pdf import PDFRenderer

    resolved_theme = (
        Theme.ISO_WHITE
        if (isinstance(theme, str) and theme.lower() in ("print", "white", "iso_white"))
        or theme == Theme.ISO_WHITE
        else Theme.DARK_BLUEPRINT
    )
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    PDFRenderer.render_sheets_to_pdf(
        [(self.width_mm, self.height_mm, self.to_svg(resolved_theme))], path, resolved_theme
    )

export_dxf(path, flat_pattern=False, dxfversion='R2010')

Export sheet to a multi-layer DXF CAD drawing. If flat_pattern=True, exports 1:1 unannotated CNC geometry.

Source code in src/build123d_techdraw/core/sheet.py
def export_dxf(self, path: str, flat_pattern: bool = False, dxfversion: str = "R2010") -> None:
    """Export sheet to a multi-layer DXF CAD drawing. If flat_pattern=True, exports 1:1 unannotated CNC geometry."""
    from build123d_techdraw.renderers.dxf import DXFRenderer

    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    if flat_pattern:
        for v in self.views:
            if v.flat_pattern is not None:
                DXFRenderer.export_flat_pattern_to_dxf(
                    v.flat_pattern, path, dxfversion=dxfversion
                )
                return

        unique_shapes: list[Any] = []
        for v in self.views:
            if v.shape is not None and v.shape not in unique_shapes:
                unique_shapes.append(v.shape)

        if unique_shapes:
            shape_to_export = (
                unique_shapes[0]
                if len(unique_shapes) == 1
                else bd.Compound(children=unique_shapes)
            )
            DXFRenderer.export_shape_to_dxf(shape_to_export, path, dxfversion=dxfversion)
        else:
            from ezdxf.filemanagement import new as ezdxf_new

            doc = ezdxf_new(dxfversion=dxfversion)
            doc.saveas(path)
    else:
        DXFRenderer.export_sheet_to_dxf(self, path, dxfversion=dxfversion)

export_html(filepath, theme=Theme.DARK_BLUEPRINT, *, shape=None, linear_deflection=0.08, angular_deflection=0.25, crease_angle_deg=20.0, title=None, initial_layout='split')

Export sheet to a self-contained interactive 3D-in-2D HTML5 blueprint.

Source code in src/build123d_techdraw/core/sheet.py
def export_html(
    self,
    filepath: str | os.PathLike[str],
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    *,
    shape: Any | None = None,
    linear_deflection: float = 0.08,
    angular_deflection: float = 0.25,
    crease_angle_deg: float = 20.0,
    title: str | None = None,
    initial_layout: str = "split",
) -> None:
    """Export sheet to a self-contained interactive 3D-in-2D HTML5 blueprint."""
    from build123d_techdraw.renderers.html import export_interactive_html

    export_interactive_html(
        self,
        filepath,
        theme=theme,
        shape=shape,
        linear_deflection=linear_deflection,
        angular_deflection=angular_deflection,
        crease_angle_deg=crease_angle_deg,
        title=title,
        initial_layout=initial_layout,
    )

SheetSize

Bases: Enum

Standard ISO 216 and ANSI/US paper sheet sizes in millimeters (width, height).

Source code in src/build123d_techdraw/core/sheet.py
class SheetSize(Enum):
    """Standard ISO 216 and ANSI/US paper sheet sizes in millimeters (width, height)."""

    A0_LANDSCAPE = (1189.0, 841.0)
    A0_PORTRAIT = (841.0, 1189.0)
    A0 = (1189.0, 841.0)
    A1_LANDSCAPE = (841.0, 594.0)
    A1_PORTRAIT = (594.0, 841.0)
    A1 = (841.0, 594.0)
    A2_LANDSCAPE = (594.0, 420.0)
    A2_PORTRAIT = (420.0, 594.0)
    A2 = (594.0, 420.0)
    A3_LANDSCAPE = (420.0, 297.0)
    A3_PORTRAIT = (297.0, 420.0)
    A3 = (420.0, 297.0)
    A4_LANDSCAPE = (297.0, 210.0)
    A4_PORTRAIT = (210.0, 297.0)
    A4 = (297.0, 210.0)
    LETTER_LANDSCAPE = (279.4, 215.9)
    LETTER_PORTRAIT = (215.9, 279.4)
    LETTER = (279.4, 215.9)
    ANSI_A = (279.4, 215.9)
    LEGAL_LANDSCAPE = (355.6, 215.9)
    LEGAL_PORTRAIT = (215.9, 355.6)
    LEGAL = (355.6, 215.9)
    TABLOID_LANDSCAPE = (431.8, 279.4)
    TABLOID_PORTRAIT = (279.4, 431.8)
    TABLOID = (431.8, 279.4)
    ANSI_B = (431.8, 279.4)
    ANSI_C = (558.8, 431.8)
    ANSI_D = (863.6, 558.8)
    ANSI_E = (1117.6, 863.6)

    @property
    def width(self) -> float:
        return self.value[0]

    @property
    def height(self) -> float:
        return self.value[1]

    @classmethod
    def coerce(cls, value: SheetSize | str) -> SheetSize:
        """Coerce a SheetSize enum or case-insensitive string into a SheetSize."""
        if isinstance(value, cls):
            return value
        if isinstance(value, str):
            key = value.strip().upper().replace("-", "_").replace(" ", "_")
            if key.startswith("US_"):
                key = key[3:]
            if key in cls.__members__:
                return cls.__members__[key]
            if f"{key}_LANDSCAPE" in cls.__members__:
                return cls.__members__[f"{key}_LANDSCAPE"]
            raise ValueError(
                f"Unknown sheet_size '{value}'. Expected SheetSize or string like 'A3', 'A4_LANDSCAPE', 'LETTER'."
            )
        raise TypeError(f"Expected SheetSize or str, got {type(value).__name__}")

coerce(value) classmethod

Coerce a SheetSize enum or case-insensitive string into a SheetSize.

Source code in src/build123d_techdraw/core/sheet.py
@classmethod
def coerce(cls, value: SheetSize | str) -> SheetSize:
    """Coerce a SheetSize enum or case-insensitive string into a SheetSize."""
    if isinstance(value, cls):
        return value
    if isinstance(value, str):
        key = value.strip().upper().replace("-", "_").replace(" ", "_")
        if key.startswith("US_"):
            key = key[3:]
        if key in cls.__members__:
            return cls.__members__[key]
        if f"{key}_LANDSCAPE" in cls.__members__:
            return cls.__members__[f"{key}_LANDSCAPE"]
        raise ValueError(
            f"Unknown sheet_size '{value}'. Expected SheetSize or string like 'A3', 'A4_LANDSCAPE', 'LETTER'."
        )
    raise TypeError(f"Expected SheetSize or str, got {type(value).__name__}")

build123d_techdraw.core.view

SheetView representations, view projection mathematics, and coordinate transformations.

SheetView

Represents an orthographic, isometric, or section view placed on a DrawingSheet.

Provides bidirectional coordinate transformations between 3D model space, 2D view projection space, and 2D paper sheet space (mm).

Source code in src/build123d_techdraw/core/view.py
 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
class SheetView:
    """Represents an orthographic, isometric, or section view placed on a DrawingSheet.

    Provides bidirectional coordinate transformations between 3D model space,
    2D view projection space, and 2D paper sheet space (mm).
    """

    def __init__(
        self,
        view_type: ViewType,
        center_x: float,
        center_y: float,
        scale: float,
        width: float,
        height: float,
        model_origin: tuple[float, float] = (0.0, 0.0),
        projection_origin: bd.Vector | None = None,
        proj_x: bd.Vector | None = None,
        proj_y: bd.Vector | None = None,
        orig_cx: float = 0.0,
        orig_cy: float = 0.0,
        svg_content: str = "",
        view_label: str | None = None,
        view_label_pos: tuple[float, float] | None = None,
        scale_label: str | None = None,
        sheet: DrawingSheet | None = None,
        shape: Any | None = None,
        enforce_iso_scale: bool = True,
        show_hidden: bool = True,
        style: ViewStyle = ViewStyle.WIREFRAME,
    ):
        self.sheet = sheet
        self.shape = shape
        self.enforce_iso_scale = enforce_iso_scale
        self.show_hidden = show_hidden
        self.style = style
        self.view_type = view_type
        self.center_x = center_x
        self.center_y = center_y
        self.scale = scale
        self.width = width
        self.height = height
        self.unbroken_width = width
        self.unbroken_height = height
        self.breaks: list[BreakInfo] = []
        self.min_x = center_x - width / 2.0
        self.max_x = center_x + width / 2.0
        self.min_y = center_y - height / 2.0
        self.max_y = center_y + height / 2.0

        self.model_origin = model_origin
        self.origin_x = model_origin[0]
        self.origin_y = model_origin[1]

        self.projection_origin = projection_origin
        self.proj_x = proj_x
        self.proj_y = proj_y
        self.orig_cx = orig_cx
        self.orig_cy = orig_cy

        self.svg_content = svg_content
        self.inner_svg_content: str = ""
        self.rotation_angle_deg: float = 0.0
        self.view_label = view_label
        self.view_label_pos = view_label_pos
        self.scale_label = scale_label
        self.bottom_annotation_y: float = self.max_y
        self.annotations: list[Annotation] = []
        self._ctx_token: Any = None
        self.hatch: str | None = None
        self.hatch_pitch: float | None = None
        self.hatch_angle: float | None = None
        self.hatch_id: str | None = None
        self.section_half: str | None = None
        self.parent_view: SheetView | None = None
        self.detail_shape: str | None = None
        self.flat_pattern: FlatPattern | None = None
        # Factory + build parameters used by ``update_shape`` to regenerate this view.
        # Placement (center, scale, rotation) is taken from the live view at regeneration
        # time so that ``locate``/``align_to``/``scale_to`` are honoured.
        self._regen_factory: Callable[..., SheetView] | None = None
        self._regen_kwargs: dict[str, Any] = {}
        # Callout SVG a detail view appended to its parent (removed before re-projection).
        self._parent_callout_svg: str | None = None
        # Projected 2D visible circular edges (cx, cy, radius) cached from HLR projection
        # so auto_centerlines does not need to re-run OCCT Drawing a second time.
        self._visible_circles: list[tuple[float, float, float]] | None = None

    def __enter__(self) -> Self:
        self._ctx_token = CURRENT_VIEW.set(self)
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: Any,
    ) -> None:
        if self._ctx_token is not None:
            CURRENT_VIEW.reset(self._ctx_token)
            self._ctx_token = None

    def __iadd__(self, item: Annotation | Iterable[Annotation]) -> Self:
        return self.add(item)

    def __add__(self, item: Annotation | Iterable[Annotation]) -> Self:
        return self.add(item)

    def add(self, item: Annotation | Iterable[Annotation]) -> Self:
        """Attach an annotation or collection of annotations to this view."""
        if not isinstance(item, Annotation):
            if not isinstance(item, Iterable) or isinstance(item, str):
                raise TypeError(f"Cannot add {type(item).__name__} to a SheetView.")
            for sub_item in item:
                self.add(sub_item)
            return self

        item._attach_to_view(self)

        if item not in self.annotations:
            self.annotations.append(item)

        if self.sheet is not None and item not in self.sheet.annotations:
            self.sheet.annotations.append(item)

        return self

    add_annotation = add

    def _update_transform(self) -> None:
        """Regenerate the view's SVG transform after moving or scaling."""
        if not self.inner_svg_content:
            return
        rot_str = (
            f" rotate({self.rotation_angle_deg:.1f}, {self.orig_cx:.2f}, {self.orig_cy:.2f})"
            if self.rotation_angle_deg != 0.0
            else ""
        )
        transform = (
            f"translate({self.center_x:.2f}, {self.center_y:.2f}) "
            f"scale({self.scale:.4f}, {self.scale:.4f}){rot_str} "
            f"translate({-self.orig_cx:.2f}, {-self.orig_cy:.2f})"
        )
        view_id = f"view_{self.view_type.value}_{int(self.center_x)}_{int(self.center_y)}"
        self.svg_content = f"""
    <!-- View: {self.view_type.value.upper()} at ({self.center_x}, {self.center_y}) scale={self.scale} -->
    <g id="{view_id}" class="sheet-view" transform="{transform}">
        {self.inner_svg_content}
    </g>
    """
        if self.breaks:
            self._apply_breaks()

    def add_break(
        self,
        interval: tuple[float, float],
        axis: str = "X",
        style: str = "zigzag",
        gap: float = 10.0,
    ) -> Self:
        """Cut a uniform span out of the view (ISO 128-3 interrupted view).

        Args:
            interval: Start and end of the removed span in absolute model coordinates along
                ``axis`` (the frame used by ``to_sheet_x`` / ``to_sheet_y``). Both ends must lie
                strictly inside the part so material remains on both sides.
            axis: ``"X"`` (horizontal break) or ``"Y"`` (vertical break). All breaks of one
                view must use the same axis.
            style: ``"zigzag"`` or ``"wavy"`` break lines.
            gap: Paper distance in mm between the two break lines.

        Dimensions keep reporting true model lengths; only the drawn span is shortened.
        """
        axis_u = axis.upper()
        style_l = style.lower()
        if axis_u not in ("X", "Y"):
            raise ValueError(f"Break axis must be 'X' or 'Y', got {axis!r}.")
        if style_l not in ("zigzag", "wavy"):
            raise ValueError(f"Break style must be 'zigzag' or 'wavy', got {style!r}.")
        if gap <= 0.0:
            raise ValueError(f"Break gap must be positive, got {gap}.")
        lo, hi = min(interval[0], interval[1]), max(interval[0], interval[1])
        half = self._unbroken_paper_length(axis_u) / (2.0 * self.scale) if self.scale else 0.0
        origin = self.origin_x if axis_u == "X" else self.origin_y
        part_min, part_max = origin - half, origin + half
        if not (part_min < lo < hi < part_max):
            raise ValueError(
                f"Break interval {interval} must lie strictly inside the part "
                f"({part_min:g} < start < end < {part_max:g} along {axis_u}, model coordinates)."
            )
        if (hi - lo) * self.scale <= gap:
            raise ValueError(
                f"Break interval {interval} is shorter on paper than the gap ({gap} mm)."
            )
        for other in self.breaks:
            if other.axis != axis_u:
                raise ValueError("All breaks of a view must use the same axis.")
            if lo < other.interval[1] and other.interval[0] < hi:
                raise ValueError(f"Break interval {interval} overlaps {other.interval}.")
        self.breaks.append(BreakInfo(interval=(lo, hi), axis=axis_u, style=style_l, gap=gap))
        self.breaks.sort(key=lambda b: b.interval[0])
        self._apply_breaks()
        return self

    def _unbroken_paper_length(self, axis: str) -> float:
        return self.unbroken_width if axis == "X" else self.unbroken_height

    def _break_cuts(self, axis: str) -> list[tuple[float, float, BreakInfo]]:
        """Unbroken paper-space spans removed by the breaks along ``axis``, sorted ascending."""
        cuts: list[tuple[float, float, BreakInfo]] = []
        for b in self.breaks:
            if b.axis != axis:
                continue
            lo, hi = b.interval
            if axis == "X":
                x_lo = self.center_x + (lo - self.origin_x) * self.scale
                x_hi = self.center_x + (hi - self.origin_x) * self.scale
                cuts.append((x_lo, x_hi, b))
            else:
                # Paper Y grows downward, so the model's upper bound maps to the smaller paper Y.
                y_top = self.center_y - (hi - self.origin_y) * self.scale
                y_bottom = self.center_y - (lo - self.origin_y) * self.scale
                cuts.append((y_top, y_bottom, b))
        cuts.sort(key=lambda c: c[0])
        return cuts

    def _removed_length(self, axis: str) -> float:
        return sum(c1 - c0 - b.gap for c0, c1, b in self._break_cuts(axis))

    def _map_through_breaks(self, raw: float, axis: str) -> float:
        """Map an unbroken paper coordinate along ``axis`` to its position in the broken view.

        The broken view stays centred on the view centre. Points inside a removed span are
        spread proportionally across the gap between the break lines.
        """
        cuts = self._break_cuts(axis)
        if not cuts:
            return raw
        pos = raw + sum(c1 - c0 - b.gap for c0, c1, b in cuts) / 2.0
        for c0, c1, b in cuts:
            if raw >= c1:
                pos -= c1 - c0 - b.gap
            elif raw > c0:
                inside = raw - c0
                pos -= inside - inside / (c1 - c0) * b.gap
                break
            else:
                break
        return pos

    def break_gap_centers(self, axis: str) -> list[float]:
        """Broken-view paper positions (mm) of the middle of each break gap along ``axis``."""
        return [
            self._map_through_breaks((c0 + c1) / 2.0, axis) for c0, c1, _ in self._break_cuts(axis)
        ]

    def _refresh_bounds(self) -> None:
        """Recompute ``width``/``height`` and the min/max extents from the unbroken size."""
        self.width = self.unbroken_width - self._removed_length("X")
        self.height = self.unbroken_height - self._removed_length("Y")
        self.min_x = self.center_x - self.width / 2.0
        self.max_x = self.center_x + self.width / 2.0
        self.min_y = self.center_y - self.height / 2.0
        self.max_y = self.center_y + self.height / 2.0

    def _apply_breaks(self) -> None:
        """Regenerate bounds and SVG: one clipped, shifted copy of the view per kept segment."""
        if not self.breaks:
            return
        self._refresh_bounds()
        if not self.inner_svg_content:
            return

        axis = self.breaks[0].axis
        cuts = self._break_cuts(axis)
        horizontal = axis == "X"
        centre = self.center_x if horizontal else self.center_y
        half = self._unbroken_paper_length(axis) / 2.0

        # Kept segments in unbroken paper coordinates along the break axis.
        edges = [centre - half]
        for c0, c1, _ in cuts:
            edges.extend((c0, c1))
        edges.append(centre + half)
        segments = [(edges[i], edges[i + 1]) for i in range(0, len(edges), 2)]

        view_id = f"view_{self.view_type.value}_{int(self.center_x)}_{int(self.center_y)}"
        rot_str = (
            f" rotate({self.rotation_angle_deg:.1f}, {self.orig_cx:.2f}, {self.orig_cy:.2f})"
            if self.rotation_angle_deg != 0.0
            else ""
        )
        pad = 10.0
        clips: list[str] = []
        groups: list[str] = []
        break_positions: list[tuple[float, BreakInfo]] = []
        for i, (a, b) in enumerate(segments):
            mid = (a + b) / 2.0
            shift = self._map_through_breaks(mid, axis) - mid
            new_a, new_b = a + shift, b + shift
            lo = new_a - (pad if i == 0 else 0.0)
            hi = new_b + (pad if i == len(segments) - 1 else 0.0)
            clip_id = f"clip{i + 1}_{view_id}"
            if horizontal:
                rect = (lo, self.min_y - pad, hi - lo, self.height + 2.0 * pad)
                tx, ty = self.center_x + shift, self.center_y
            else:
                rect = (self.min_x - pad, lo, self.width + 2.0 * pad, hi - lo)
                tx, ty = self.center_x, self.center_y + shift
            clips.append(
                f'<clipPath id="{clip_id}"><rect x="{rect[0]:.2f}" y="{rect[1]:.2f}" '
                f'width="{rect[2]:.2f}" height="{rect[3]:.2f}"/></clipPath>'
            )
            transform = (
                f"translate({tx:.2f}, {ty:.2f}) "
                f"scale({self.scale:.4f}, {self.scale:.4f}){rot_str} "
                f"translate({-self.orig_cx:.2f}, {-self.orig_cy:.2f})"
            )
            groups.append(
                f'<g clip-path="url(#{clip_id})"><g transform="{transform}">'
                f"{self.inner_svg_content}</g></g>"
            )
            if i > 0:
                break_positions.append((new_a, cuts[i - 1][2]))
            if i < len(cuts):
                break_positions.append((new_b, cuts[i][2]))

        break_lines = [
            _break_line_svg(
                pos,
                (self.min_y if horizontal else self.min_x) - 2.0,
                (self.max_y if horizontal else self.max_x) + 2.0,
                style=b.style,
                horizontal=horizontal,
            )
            for pos, b in break_positions
        ]

        self.svg_content = f"""
    <!-- View: {self.view_type.value.upper()} (Broken View) at ({self.center_x}, {self.center_y}) scale={self.scale} -->
    <defs>{"".join(clips)}</defs>
    <g id="{view_id}" class="sheet-view broken-view">
        {"".join(groups)}
        {"".join(break_lines)}
    </g>
    """

    def export_dxf(
        self,
        filepath: str,
        layers: dict[str, str] | None = None,
        scale: float = 1.0,
        dxfversion: str = "R2010",
    ) -> None:
        """Export 1:1 CAM manufacturing DXF from this 2D view (outer profile, holes, centerlines)."""
        if self.flat_pattern is not None:
            from build123d_techdraw.renderers.dxf import DXFRenderer

            DXFRenderer.export_flat_pattern_to_dxf(
                self.flat_pattern,
                filepath,
                layers=layers,
                dxfversion=dxfversion,
            )
            return

        from build123d_techdraw.recognizers.features import recognize_holes

        os.makedirs(os.path.dirname(os.path.abspath(filepath)), exist_ok=True)
        exporter = bd.ExportDXF(version=dxfversion, unit=bd.Unit.MM)
        doc = exporter._document
        msp = exporter._modelspace

        layer_map = {
            "outer_profile": "CUT_OUTER",
            "inner_holes": "CUT_INNER",
            "centerlines": "MARK",
            "countersinks": "ETCH",
        }
        if layers:
            layer_map.update(layers)

        layer_colors = {
            layer_map["outer_profile"]: 7,
            layer_map["inner_holes"]: 1,
            layer_map["centerlines"]: 4,
            layer_map["countersinks"]: 2,
        }
        for lname in set(layer_map.values()):
            color = layer_colors.get(lname, 7)
            with contextlib.suppress(Exception):
                doc.layers.new(name=lname, dxfattribs={"color": color})

        shape = self.shape
        if shape is None:
            exporter.write(filepath)
            return

        def _export_edge(edge: Any, layer: str) -> None:
            exporter.add_shape(edge.scale(scale) if scale != 1.0 else edge, layer=layer)

        look_from, look_up = VIEW_VECTORS.get(self.view_type, ((0.0, -1.0, 0.0), (0.0, 0.0, 1.0)))
        dwg = Drawing(shape, look_from=look_from, look_up=look_up, with_hidden=False)
        edges = dwg.visible_lines.edges()

        # Identify holes/countersinks via feature recognizer
        rec_holes = recognize_holes(shape)
        csink_radii: list[float] = []
        for rh in rec_holes:
            if rh.countersink_dia:
                csink_radii.append(round(rh.countersink_dia / 2.0, 2))
            if rh.counterbore_dia:
                csink_radii.append(round(rh.counterbore_dia / 2.0, 2))

        # Combine edges into closed wires
        wires: list[bd.Wire] = []
        try:
            wires = bd.Wire.combine(edges)
        except Exception:
            wires = []

        if wires:
            wires.sort(
                key=lambda w: bd.Face(w).area if w.is_closed else 0.0,
                reverse=True,
            )
            outer_wire = wires[0]
            inner_wires = wires[1:]

            for edge in outer_wire.edges():
                _export_edge(edge, layer_map["outer_profile"])

            # Detect concentric circular wires where outer step is countersink/counterbore
            concentric_csinks: set[int] = set()
            circle_wires: list[tuple[int, tuple[float, float], float]] = []
            for idx, iw in enumerate(inner_wires):
                cw_edges = iw.edges()
                if len(cw_edges) == 1 and cw_edges[0].geom_type == bd.GeomType.CIRCLE:
                    c = cw_edges[0].arc_center
                    circle_wires.append((idx, (float(c.X), float(c.Y)), float(cw_edges[0].radius)))

            for i in range(len(circle_wires)):
                for j in range(i + 1, len(circle_wires)):
                    idx_i, center_i, r_i = circle_wires[i]
                    idx_j, center_j, r_j = circle_wires[j]
                    dist = (
                        (center_i[0] - center_j[0]) ** 2 + (center_i[1] - center_j[1]) ** 2
                    ) ** 0.5
                    if dist < 0.5:
                        if r_i > r_j:
                            concentric_csinks.add(idx_i)
                        else:
                            concentric_csinks.add(idx_j)

            for idx, iw in enumerate(inner_wires):
                is_csink = idx in concentric_csinks
                if not is_csink:
                    for edge in iw.edges():
                        if edge.geom_type == bd.GeomType.CIRCLE:
                            r = round(float(edge.radius), 2)
                            if any(abs(r - cr) < 0.5 for cr in csink_radii):
                                is_csink = True
                                break
                target_l = layer_map["countersinks"] if is_csink else layer_map["inner_holes"]
                for edge in iw.edges():
                    _export_edge(edge, target_l)
        else:
            for edge in edges:
                _export_edge(edge, layer_map["outer_profile"])

        center_layer = layer_map["centerlines"]
        has_ann_centerlines = False
        for ann in self.annotations:
            if isinstance(ann, (CenterMark, BoltCircle, DiameterDimension, RadialDimension)):
                has_ann_centerlines = True
                cx, cy = ann.center
                r = ann.radius if isinstance(ann, RadialDimension) else 5.0
                msp.add_line(
                    ((cx - r - 2.0) * scale, cy * scale),
                    ((cx + r + 2.0) * scale, cy * scale),
                    dxfattribs={"layer": center_layer},
                )
                msp.add_line(
                    (cx * scale, (cy - r - 2.0) * scale),
                    (cx * scale, (cy + r + 2.0) * scale),
                    dxfattribs={"layer": center_layer},
                )

        if not has_ann_centerlines and rec_holes:
            for rh in rec_holes:
                c3d = rh.center_3d
                if self.projection_origin and self.proj_x and self.proj_y:
                    p = bd.Vector(c3d[0], c3d[1], c3d[2]) - self.projection_origin
                    cx2d = float(p.dot(self.proj_x))
                    cy2d = float(p.dot(self.proj_y))
                else:
                    cx2d, cy2d = float(c3d[0]), float(c3d[1])
                r = float(rh.diameter) / 2.0
                msp.add_line(
                    ((cx2d - r - 2.0) * scale, cy2d * scale),
                    ((cx2d + r + 2.0) * scale, cy2d * scale),
                    dxfattribs={"layer": center_layer},
                )
                msp.add_line(
                    (cx2d * scale, (cy2d - r - 2.0) * scale),
                    (cx2d * scale, (cy2d + r + 2.0) * scale),
                    dxfattribs={"layer": center_layer},
                )

        exporter.write(filepath)

    def _rebind_annotations(self) -> None:
        """Re-resolve all anchored/topological annotations attached to this view."""
        for ann in list(self.annotations):
            ann._rebind_to_view(self)

    def _copy_projection_from(self, reproj: SheetView) -> None:
        """Adopt the layout fields of a fresh projection of the same view (``update_shape``)."""
        self.width = reproj.width
        self.height = reproj.height
        self.unbroken_width = reproj.unbroken_width
        self.unbroken_height = reproj.unbroken_height
        self.min_x = reproj.min_x
        self.max_x = reproj.max_x
        self.min_y = reproj.min_y
        self.max_y = reproj.max_y
        self.bottom_annotation_y = reproj.bottom_annotation_y
        self.model_origin = reproj.model_origin
        self.origin_x = reproj.origin_x
        self.origin_y = reproj.origin_y
        self.projection_origin = reproj.projection_origin
        self.proj_x = reproj.proj_x
        self.proj_y = reproj.proj_y
        self.orig_cx = reproj.orig_cx
        self.orig_cy = reproj.orig_cy
        self.svg_content = reproj.svg_content
        self.inner_svg_content = reproj.inner_svg_content
        self.view_label_pos = reproj.view_label_pos
        self._visible_circles = reproj._visible_circles
        self.style = reproj.style
        self.flat_pattern = reproj.flat_pattern

    def can_regenerate(self) -> bool:
        """Return True if ``update_shape`` is able to re-project this view's geometry."""
        if self.view_type == ViewType.DETAIL:
            return self._regen_factory is not None and self.parent_view is not None
        if self.view_type in (ViewType.SECTION, ViewType.AUXILIARY, ViewType.FLAT_PATTERN):
            return self._regen_factory is not None
        return True

    def _regen_label_y(self) -> float | None:
        """Explicit label Y to reuse on regeneration (tracks moves), or None for auto."""
        if self._regen_kwargs.get("view_label_y") is not None and self.view_label_pos is not None:
            return self.view_label_pos[1]
        return None

    def _reproject(self, new_shape: Any) -> SheetView:
        """Re-run the factory this view was built with against ``new_shape``."""
        kwargs = dict(self._regen_kwargs)
        kwargs["view_label_y"] = self._regen_label_y()

        if self.view_type == ViewType.DETAIL:
            parent = self.parent_view
            assert parent is not None and self._regen_factory is not None
            if parent.shape is not new_shape:
                parent.update_shape(new_shape)
            if self._parent_callout_svg and self._parent_callout_svg in parent.svg_content:
                parent.svg_content = parent.svg_content.replace(self._parent_callout_svg, "", 1)
            return self._regen_factory(
                parent_view=parent,
                center_x=self.center_x,
                center_y=self.center_y,
                scale=self.scale,
                **kwargs,
            )

        if self._regen_factory is None:
            # Standard view built without a recorded spec (e.g. a hand-made SheetView).
            return project_shape_to_view(
                new_shape,
                self.view_type,
                self.center_x,
                self.center_y,
                scale=self.scale,
                show_hidden=self.show_hidden,
                view_label=self.view_label,
                rotation_angle_deg=self.rotation_angle_deg,
                view_label_y=kwargs["view_label_y"],
            )

        if self._regen_factory is project_shape_to_view:
            kwargs["rotation_angle_deg"] = self.rotation_angle_deg
        return self._regen_factory(
            new_shape,
            center_x=self.center_x,
            center_y=self.center_y,
            scale=self.scale,
            **kwargs,
        )

    def update_shape(self, new_shape: Any) -> Self:
        """Update the view's 3D shape, re-project geometry, and re-bind all anchored annotations.

        Every view type is regenerated from the parameters it was built with (cut plane,
        section path, detail region, auxiliary direction, explicit ``model_origin``,
        label placement). Detail views follow their parent view: the parent is updated to
        ``new_shape`` first if needed, then the detail is re-cut from it. Space reserved
        below the view by dimensions (``bottom_annotation_y``) is kept, shifted with the
        view's new bottom edge.

        Raises:
            ValueError: if this view has no recorded build parameters and cannot be
                regenerated (section/detail/auxiliary views constructed by hand).
        """
        if not self.can_regenerate():
            raise ValueError(
                f"Cannot update shape of {self.view_type.value} view "
                f"{self.view_label or ''!r}: it was not created by a projection factory, "
                "so its build parameters are unknown. Recreate the view instead."
            )

        old_max_y = self.max_y
        old_bottom = self.bottom_annotation_y
        reproj = self._reproject(new_shape)

        self.shape = reproj.shape if self.view_type == ViewType.DETAIL else new_shape
        self._copy_projection_from(reproj)
        if reproj.hatch_id is not None:
            self.hatch = reproj.hatch
            self.hatch_pitch = reproj.hatch_pitch
            self.hatch_angle = reproj.hatch_angle
            self.hatch_id = reproj.hatch_id
        if reproj.parent_view is not None:
            self.parent_view = reproj.parent_view
        self._parent_callout_svg = reproj._parent_callout_svg
        if self.breaks:
            self._apply_breaks()

        # Keep annotation space reserved below the view, moved with the view's bottom edge.
        self.bottom_annotation_y = max(self.max_y, old_bottom + (self.max_y - old_max_y))

        self._rebind_annotations()
        return self

    def locate(self, center: tuple[float, float]) -> Self:
        """Reposition the view center on the sheet (in paper mm)."""
        dx = float(center[0]) - self.center_x
        dy = float(center[1]) - self.center_y
        self.center_x = float(center[0])
        self.center_y = float(center[1])
        self.min_x = self.center_x - self.width / 2.0
        self.max_x = self.center_x + self.width / 2.0
        self.min_y = self.center_y - self.height / 2.0
        self.max_y = self.center_y + self.height / 2.0
        if self.breaks:
            self._refresh_bounds()
        self.bottom_annotation_y = self.max_y
        if self.view_label_pos is not None:
            self.view_label_pos = (self.view_label_pos[0] + dx, self.view_label_pos[1] + dy)
        self._update_transform()
        self._rebind_annotations()
        return self

    def scale_to(self, scale: float) -> Self:
        """Change the view scale factor and update its bounding box."""
        if self.scale != 0.0:
            ratio = scale / self.scale
            self.width *= ratio
            self.height *= ratio
            self.unbroken_width *= ratio
            self.unbroken_height *= ratio
        self.scale = scale
        self.min_x = self.center_x - self.width / 2.0
        self.max_x = self.center_x + self.width / 2.0
        self.min_y = self.center_y - self.height / 2.0
        self.max_y = self.center_y + self.height / 2.0
        if self.breaks:
            self._refresh_bounds()
        self.bottom_annotation_y = self.max_y
        self.scale_label = format_iso_scale(scale)
        self._update_transform()
        self._rebind_annotations()
        return self

    def get_visual_bounds(
        self,
        include_annotations: bool = True,
        include_label: bool = True,
    ) -> tuple[float, float, float, float]:
        """Compute the visual bounding box (min_x, min_y, max_x, max_y) of this view in paper mm."""
        min_x = self.min_x
        min_y = self.min_y
        max_x = self.max_x
        max_y = self.max_y

        if include_annotations:
            for ann in self.annotations:
                bbox = ann.bounding_box_2d()
                if bbox is not None:
                    min_x = min(min_x, bbox[0])
                    min_y = min(min_y, bbox[1])
                    max_x = max(max_x, bbox[2])
                    max_y = max(max_y, bbox[3])

        if include_label and (self.view_label or self.scale_label):
            label_y = self.bottom_annotation_y + 8.0
            max_y = max(max_y, label_y + 4.0)

        return (min_x, min_y, max_x, max_y)

    def align_to(
        self,
        other: AlignSpec,
        direction: str = "right",
        spacing: float = 25.0,
        include_annotations: bool = False,
        include_label: bool = True,
    ) -> Self:
        if isinstance(other, (tuple, list, dict)):
            _apply_align_to(self, other)
            return self
        """Align this view relative to another view on the sheet."""
        d = direction.lower()
        if include_annotations:
            other_min_x, other_min_y, other_max_x, other_max_y = other.get_visual_bounds(
                include_annotations=True, include_label=include_label
            )
            self_min_x, self_min_y, self_max_x, self_max_y = self.get_visual_bounds(
                include_annotations=True, include_label=include_label
            )
            self_left_extent = self.center_x - self_min_x
            self_right_extent = self_max_x - self.center_x
            self_top_extent = self.center_y - self_min_y
            self_bottom_extent = self_max_y - self.center_y

            if d in ("right", "east"):
                new_cx = other_max_x + spacing + self_left_extent
                new_cy = other.center_y
            elif d in ("left", "west"):
                new_cx = other_min_x - spacing - self_right_extent
                new_cy = other.center_y
            elif d in ("above", "top", "north"):
                new_cx = other.center_x
                new_cy = other_min_y - spacing - self_bottom_extent
            elif d in ("below", "bottom", "south"):
                new_cx = other.center_x
                new_cy = other_max_y + spacing + self_top_extent
            else:
                raise ValueError(
                    f"Unknown alignment direction '{direction}'. Use 'above', 'below', 'right', or 'left'."
                )
        else:
            if d in ("right", "east"):
                new_cx = other.max_x + spacing + self.width / 2.0
                new_cy = other.center_y
            elif d in ("left", "west"):
                new_cx = other.min_x - spacing - self.width / 2.0
                new_cy = other.center_y
            elif d in ("above", "top", "north"):
                new_cx = other.center_x
                new_cy = other.min_y - spacing - self.height / 2.0
            elif d in ("below", "bottom", "south"):
                new_cx = other.center_x
                new_cy = other.max_y + spacing + self.height / 2.0
            else:
                raise ValueError(
                    f"Unknown alignment direction '{direction}'. Use 'above', 'below', 'right', or 'left'."
                )
        return self.locate((new_cx, new_cy))

    @property
    def center(self) -> tuple[float, float]:
        """View center on the drawing sheet in paper mm."""
        return (self.center_x, self.center_y)

    def __getitem__(self, key: str) -> Any:
        """Provide dictionary-style access for backward compatibility."""
        attrs = {
            "view_type": self.view_type,
            "center_x": self.center_x,
            "center_y": self.center_y,
            "scale": self.scale,
            "width": self.width,
            "height": self.height,
            "min_x": self.min_x,
            "max_x": self.max_x,
            "min_y": self.min_y,
            "max_y": self.max_y,
            "origin_x": self.origin_x,
            "origin_y": self.origin_y,
        }
        if key in attrs:
            return attrs[key]
        raise KeyError(key)

    def to_sheet_x(self, model_x: float) -> float:
        """Transform 2D model X coordinate to sheet paper coordinate (mm), honouring breaks."""
        raw_x = self.center_x + ((model_x - self.origin_x) * self.scale)
        return self._map_through_breaks(raw_x, "X")

    def to_sheet_y(self, model_y: float) -> float:
        """Transform 2D model Y coordinate to sheet paper coordinate (mm), honouring breaks."""
        raw_y = self.center_y - ((model_y - self.origin_y) * self.scale)
        return self._map_through_breaks(raw_y, "Y")

    def to_sheet_coords(self, model_x: float, model_y: float) -> tuple[float, float]:
        """Transform 2D model (X, Y) to sheet paper (X, Y) coordinates (mm)."""
        return (self.to_sheet_x(model_x), self.to_sheet_y(model_y))

    def to_sheet_3d(self, x: float, y: float, z: float) -> tuple[float, float]:
        """Project a 3D part point (X, Y, Z) to 2D sheet paper coordinate space (mm)."""
        if self.projection_origin is None or self.proj_x is None or self.proj_y is None:
            return self.to_sheet_coords(x, y)
        p = bd.Vector(x, y, z) - self.projection_origin
        x2d = p.dot(self.proj_x)
        y2d = p.dot(self.proj_y)
        sx = self.center_x + (x2d - self.orig_cx) * self.scale
        sy = self.center_y + (-y2d - self.orig_cy) * self.scale
        return (self._map_through_breaks(sx, "X"), self._map_through_breaks(sy, "Y"))

    def dimension(
        self,
        target: Any,
        offset: float = -8.0,
        direction: str | None = None,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add a dimension for a topological Edge, Face, or pair of points in this view.

        Automatically determines dimension direction and length from the model entity.
        """
        dim = LinearDimension(
            target_or_start=target,
            offset=offset,
            direction=direction,
            text=text,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        return dim

    def dimension_between(
        self,
        target1: Any,
        target2: Any,
        direction: str = "horizontal",
        offset: float = -8.0,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add a linear dimension between two model vertices, edges, or points in this view."""
        from build123d_techdraw.annotations.resolver import is_topological_entity

        if (
            isinstance(target1, (tuple, list))
            and isinstance(target2, (tuple, list))
            and not is_topological_entity(target1)
            and not is_topological_entity(target2)
        ):
            if len(target1) == 2 and len(target2) == 2:
                s1 = self.to_sheet_coords(float(target1[0]), float(target1[1]))
                s2 = self.to_sheet_coords(float(target2[0]), float(target2[1]))
                d_lower = direction.lower() if direction else "horizontal"
                if text is None:
                    from build123d_techdraw.annotations.dimensions import format_dimension_value

                    if d_lower == "horizontal":
                        m_dist = abs(float(target2[0]) - float(target1[0]))
                    elif d_lower == "vertical":
                        m_dist = abs(float(target2[1]) - float(target1[1]))
                    else:
                        m_dist = math.hypot(
                            float(target2[0]) - float(target1[0]),
                            float(target2[1]) - float(target1[1]),
                        )
                    text = format_dimension_value(m_dist)
                dim = LinearDimension(
                    start=s1,
                    end=s2,
                    direction=direction,
                    offset=offset,
                    text=text,
                    tolerance=tolerance,
                    prefix=prefix,
                    suffix=suffix,
                    view=self,
                )
                self.add(dim)
                return dim
            elif len(target1) == 3 and len(target2) == 3:
                s1 = self.to_sheet_3d(float(target1[0]), float(target1[1]), float(target1[2]))
                s2 = self.to_sheet_3d(float(target2[0]), float(target2[1]), float(target2[2]))
                if text is None:
                    from build123d_techdraw.annotations.dimensions import format_dimension_value

                    dx = float(target2[0]) - float(target1[0])
                    dy = float(target2[1]) - float(target1[1])
                    dz = float(target2[2]) - float(target1[2])
                    d_lower = direction.lower() if direction else "horizontal"
                    if d_lower == "horizontal":
                        m_dist = abs(dx)
                    elif d_lower == "vertical":
                        m_dist = abs(dz if abs(dz) > 1e-4 else dy)
                    else:
                        m_dist = math.hypot(dx, dy, dz)
                    text = format_dimension_value(m_dist)
                dim = LinearDimension(
                    start=s1,
                    end=s2,
                    direction=direction,
                    offset=offset,
                    text=text,
                    tolerance=tolerance,
                    prefix=prefix,
                    suffix=suffix,
                    view=self,
                )
                self.add(dim)
                return dim

        dim = LinearDimension(
            target_or_start=target1,
            target2_or_end=target2,
            direction=direction,
            offset=offset,
            text=text,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        return dim

    def dim_horizontal(
        self,
        model_x1: float,
        model_x2: float,
        model_y: float,
        offset_y: float = -8.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add a horizontal dimension between model_x1 and model_x2 at model_y."""
        sx1 = self.to_sheet_x(model_x1)
        sx2 = self.to_sheet_x(model_x2)
        sy = self.to_sheet_y(model_y)
        dim = LinearDimension(
            start=(sx1, sy),
            end=(sx2, sy),
            offset=offset_y,
            dim_type=DimensionType.HORIZONTAL,
            text=text,
            nominal=None if text is not None else abs(model_x2 - model_x1),
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        if dim.offset > 0:
            self.bottom_annotation_y = max(self.bottom_annotation_y, sy + dim.offset + 4.0)
        return dim

    def dim_vertical(
        self,
        model_y1: float,
        model_y2: float,
        model_x: float,
        offset_x: float = -10.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add a vertical dimension between model_y1 and model_y2 at model_x."""
        sy1 = self.to_sheet_y(model_y1)
        sy2 = self.to_sheet_y(model_y2)
        sx = self.to_sheet_x(model_x)
        dim = LinearDimension(
            start=(sx, sy1),
            end=(sx, sy2),
            offset=offset_x,
            dim_type=DimensionType.VERTICAL,
            text=text,
            nominal=None if text is not None else abs(model_y2 - model_y1),
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        return dim

    def dim_aligned(
        self,
        p1_model: tuple[float, float],
        p2_model: tuple[float, float],
        offset: float = 8.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add an aligned dimension between two model points."""
        s1 = self.to_sheet_coords(p1_model[0], p1_model[1])
        s2 = self.to_sheet_coords(p2_model[0], p2_model[1])
        dim = LinearDimension(
            start=s1,
            end=s2,
            offset=offset,
            dim_type=DimensionType.ALIGNED,
            text=text,
            nominal=None if text is not None else math.dist(p1_model, p2_model),
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        return dim

    def add_overall_horizontal(
        self,
        offset_y: float = -8.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add an overall horizontal dimension spanning view's bounding box."""
        y_ref = self.min_y if offset_y < 0 else self.max_y
        dim = LinearDimension(
            start=(self.min_x, y_ref),
            end=(self.max_x, y_ref),
            offset=offset_y,
            dim_type=DimensionType.HORIZONTAL,
            text=text,
            nominal=None
            if text is not None or not self.scale
            else self.unbroken_width / self.scale,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        if dim.offset > 0:
            self.bottom_annotation_y = max(self.bottom_annotation_y, y_ref + dim.offset + 4.0)
        return dim

    def add_overall_vertical(
        self,
        offset_x: float = -10.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> LinearDimension:
        """Add an overall vertical dimension spanning view's bounding box."""
        x_ref = self.min_x if offset_x < 0 else self.max_x
        dim = LinearDimension(
            start=(x_ref, self.min_y),
            end=(x_ref, self.max_y),
            offset=offset_x,
            dim_type=DimensionType.VERTICAL,
            text=text,
            nominal=None
            if text is not None or not self.scale
            else self.unbroken_height / self.scale,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        self.add(dim)
        return dim

    def auto_dimension(self, tolerance: str | None = None) -> list[Any]:
        """Automatically dimension this view using collision-avoiding placement."""
        from build123d_techdraw.layout.auto_dimension import auto_dimension_view

        return auto_dimension_view(self, tolerance=tolerance)

    def dim_radial(
        self,
        center_model: tuple[float, float],
        radius_model: float,
        angle_deg: float = 45.0,
        text: str | None = None,
        tolerance: str | None = None,
    ) -> RadialDimension:
        """Add a radial dimension pointing to an arc defined in model space."""
        cx, cy = self.to_sheet_coords(center_model[0], center_model[1])
        dim = RadialDimension(
            center=(cx, cy),
            radius=radius_model * self.scale,
            angle_deg=angle_deg,
            text=text,
            tolerance=tolerance,
            view=self,
        )
        self.add(dim)
        return dim

    def dim_diameter(
        self,
        center_model: tuple[float, float],
        diameter_model: float,
        angle_deg: float = 45.0,
        text: str | None = None,
        tolerance: str | None = None,
    ) -> DiameterDimension:
        """Add a diameter dimension across a hole/cylinder defined in model space."""
        cx, cy = self.to_sheet_coords(center_model[0], center_model[1])
        dim = DiameterDimension(
            center=(cx, cy),
            diameter=diameter_model * self.scale,
            angle_deg=angle_deg,
            text=text,
            tolerance=tolerance,
            view=self,
        )
        self.add(dim)
        return dim

    def dim_angular(
        self,
        target1: Any,
        target2: Any,
        radius: float = 20.0,
        text: str | None = None,
        tolerance: str | None = None,
        prefix: str = "",
        suffix: str = "°",
    ) -> AngularDimension:
        """Add an angular dimension between two edges, rays, or faces in this view."""
        dim = AngularDimension(
            target1=target1,
            target2=target2,
            radius=radius,
            text=text,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        return dim

    def dim_ordinate(
        self,
        target: Any,
        datum_coord: float = 0.0,
        direction: str = "horizontal",
        jog: float = 0.0,
        extension_length: float = 12.0,
        prefix: str = "",
        suffix: str = "",
    ) -> OrdinateDimension:
        """Add an ordinate dimension point in this view."""
        dim = OrdinateDimension(
            target=target,
            datum_coord=datum_coord,
            direction=direction,
            jog=jog,
            extension_length=extension_length,
            prefix=prefix,
            suffix=suffix,
            view=self,
        )
        return dim

    def chamfer_callout(
        self,
        target: Any = None,
        width: float | None = None,
        angle_deg: float = 45.0,
        style: str = "iso",
        quantity: int | None = None,
        elbow_dx: float = 15.0,
        elbow_dy: float = -12.0,
        *,
        anchor: Any = None,
    ) -> ChamferCallout:
        """Add an ISO/ASME chamfer callout leader note."""
        cc = ChamferCallout(
            target_or_edge=target,
            width=width,
            angle_deg=angle_deg,
            style=style,
            quantity=quantity,
            elbow_offset=(elbow_dx, elbow_dy),
            view=self,
            anchor=anchor,
        )
        return cc

    def weld_symbol(
        self,
        target: Any,
        weld_type: WeldType | str = WeldType.FILLET,
        size: str | float | None = "a5",
        length: str | float | None = None,
        pitch: str | float | None = None,
        all_around: bool = False,
        field_weld: bool = False,
        tail_text: str | None = None,
        arrow_side: bool = True,
        elbow_dx: float = 16.0,
        elbow_dy: float = -12.0,
    ) -> WeldingSymbol:
        """Add an ISO 2553 welding annotation."""
        ws = WeldingSymbol(
            target=target,
            weld_type=weld_type,
            size=size,
            length=length,
            pitch=pitch,
            all_around=all_around,
            field_weld=field_weld,
            tail_text=tail_text,
            arrow_side=arrow_side,
            elbow_offset=(elbow_dx, elbow_dy),
            view=self,
        )
        return ws

    def centermark(
        self,
        model_x: float,
        model_y: float,
        size: float = 6.0,
    ) -> CenterMark:
        """Add a centermark crosshair at (model_x, model_y)."""
        sc = self.to_sheet_coords(model_x, model_y)
        cm = CenterMark(center=sc, size=size, view=self)
        self.add(cm)
        return cm

    def centerline_horizontal(
        self,
        model_y: float = 0.0,
        model_x1: float | None = None,
        model_x2: float | None = None,
        overhang: float = 4.0,
    ) -> Centerline:
        """Draw an ISO centerline across the horizontal axis at model_y."""
        sy = self.to_sheet_y(model_y)
        sx1 = (
            self.to_sheet_x(model_x1) - overhang if model_x1 is not None else self.min_x - overhang
        )
        sx2 = (
            self.to_sheet_x(model_x2) + overhang if model_x2 is not None else self.max_x + overhang
        )
        cl = Centerline(start=(sx1, sy), end=(sx2, sy), view=self)
        self.add(cl)
        return cl

    def centerline_vertical(
        self,
        model_x: float = 0.0,
        model_y1: float | None = None,
        model_y2: float | None = None,
        overhang: float = 4.0,
    ) -> Centerline:
        """Draw an ISO centerline across the vertical axis at model_x."""
        sx = self.to_sheet_x(model_x)
        sy1 = (
            self.to_sheet_y(model_y1) + overhang if model_y1 is not None else self.max_y + overhang
        )
        sy2 = (
            self.to_sheet_y(model_y2) - overhang if model_y2 is not None else self.min_y - overhang
        )
        cl = Centerline(start=(sx, min(sy1, sy2)), end=(sx, max(sy1, sy2)), view=self)
        self.add(cl)
        return cl

    def bolt_circle(
        self,
        center_model: tuple[float, float] = (0.0, 0.0),
        diameter_model: float = 50.0,
        num_holes: int = 4,
        start_angle_deg: float = 0.0,
    ) -> BoltCircle:
        """Add a bolt pitch circle diameter (PCD) annotation in model space."""
        sc = self.to_sheet_coords(center_model[0], center_model[1])
        bc = BoltCircle(
            center=sc,
            diameter=diameter_model * self.scale,
            num_holes=num_holes,
            start_angle_deg=start_angle_deg,
            view=self,
        )
        self.add(bc)
        return bc

    def leader(
        self,
        model_x: float,
        model_y: float,
        lines: list[str] | str,
        elbow_dx: float = 15.0,
        elbow_dy: float = -12.0,
        shelf_length: float = 20.0,
        align_right: bool | None = None,
        terminator: str = "dot",
    ) -> LeaderNote:
        """Add a leader note pointing to (model_x, model_y) on the part."""
        target = self.to_sheet_coords(model_x, model_y)
        line_list = [lines] if isinstance(lines, str) else list(lines)
        note = LeaderNote(
            target=target,
            lines=line_list,
            elbow_offset=(elbow_dx, elbow_dy),
            shelf_length=shelf_length,
            align_right=align_right,
            terminator=terminator,
            view=self,
        )
        self.add(note)
        return note

    def leader_3d(
        self,
        x: float,
        y: float,
        z: float,
        lines: list[str] | str,
        elbow_dx: float = 15.0,
        elbow_dy: float = -12.0,
        shelf_length: float = 20.0,
        align_right: bool | None = None,
        terminator: str = "dot",
    ) -> LeaderNote:
        """Add a leader note pointing to a 3D part point (x, y, z)."""
        target = self.to_sheet_3d(x, y, z)
        line_list = [lines] if isinstance(lines, str) else list(lines)
        note = LeaderNote(
            target=target,
            lines=line_list,
            elbow_offset=(elbow_dx, elbow_dy),
            shelf_length=shelf_length,
            align_right=align_right,
            terminator=terminator,
            view=self,
        )
        self.add(note)
        return note

    def balloon(
        self,
        item_no: int,
        model_x: float,
        model_y: float,
        balloon_x: float,
        balloon_y: float,
    ) -> BOMBalloon:
        """Add a BOM balloon callout pointing to (model_x, model_y)."""
        target = self.to_sheet_coords(model_x, model_y)
        balloon = BOMBalloon(
            item_no=item_no,
            target=target,
            balloon_center=(balloon_x, balloon_y),
            view=self,
        )
        self.add(balloon)
        return balloon

    def add_gdt_frame(
        self,
        model_x: float = 0.0,
        model_y: float = 0.0,
        characteristic: GDTCharacteristic = GDTCharacteristic.POSITION,
        tolerance_value: str = "0.05",
        datum_a: str | None = None,
        datum_b: str | None = None,
        datum_c: str | None = None,
        leader_offset: tuple[float, float] | None = None,
        *,
        anchor: Any = None,
    ) -> FeatureControlFrame:
        """Add a GD&T Feature Control Frame near (model_x, model_y) or an anchor, optionally with a leader line."""
        if anchor is not None:
            fcf = FeatureControlFrame(
                characteristic=characteristic,
                tolerance_value=tolerance_value,
                datum_a=datum_a,
                datum_b=datum_b,
                datum_c=datum_c,
                leader_offset=leader_offset or (12.0, -10.0),
                view=self,
                anchor=anchor,
            )
            self.add(fcf)
            return fcf

        target_pos = self.to_sheet_coords(model_x, model_y)
        if leader_offset is not None:
            pos = (target_pos[0] + leader_offset[0], target_pos[1] + leader_offset[1])
            leader_target: tuple[float, float] | None = target_pos
        else:
            pos = target_pos
            leader_target = None

        fcf = FeatureControlFrame(
            position=pos,
            characteristic=characteristic,
            tolerance_value=tolerance_value,
            datum_a=datum_a,
            datum_b=datum_b,
            datum_c=datum_c,
            leader_target=leader_target,
            view=self,
        )
        self.add(fcf)
        return fcf

    def add_datum_symbol(
        self,
        model_x: float = 0.0,
        model_y: float = 0.0,
        label: str = "A",
        direction: str = "up",
        *,
        anchor: Any = None,
    ) -> DatumFeatureSymbol:
        """Add an ISO datum feature identifier symbol at (model_x, model_y) or an anchor."""
        target = anchor if anchor is not None else self.to_sheet_coords(model_x, model_y)
        sym = DatumFeatureSymbol(target=target, label=label, direction=direction, view=self)
        self.add(sym)
        return sym

    def add_surface_finish(
        self,
        model_x: float = 0.0,
        model_y: float = 0.0,
        ra_value: str = "Ra 3.2",
        material_removal: MaterialRemoval = MaterialRemoval.REQUIRED,
        process: str | None = None,
        *,
        anchor: Any = None,
    ) -> SurfaceFinishSymbol:
        """Add an ISO 1302 surface roughness symbol at (model_x, model_y) or an anchor."""
        sym = SurfaceFinishSymbol(
            position=None if anchor is not None else self.to_sheet_coords(model_x, model_y),
            ra_value=ra_value,
            material_removal=material_removal,
            process=process,
            view=self,
            anchor=anchor,
        )
        self.add(sym)
        return sym

    def hole_callout(
        self,
        model_x: float = 0.0,
        model_y: float = 0.0,
        diameter: float | None = None,
        depth: float | str | None = None,
        countersink_dia: float | None = None,
        countersink_angle: float = 90.0,
        counterbore_dia: float | None = None,
        counterbore_depth: float | None = None,
        quantity: int | None = None,
        tolerance: str | Tolerance | None = None,
        clearance_for: str | None = None,
        fit: str = "medium",
        elbow_dx: float = 15.0,
        elbow_dy: float = -12.0,
        *,
        anchor: Any = None,
    ) -> HoleCallout:
        """Add a standard engineering hole callout at (model_x, model_y) or an anchor."""
        target = anchor if anchor is not None else self.to_sheet_coords(model_x, model_y)
        hc = HoleCallout(
            center=target,
            diameter=diameter,
            depth=depth,
            countersink_dia=countersink_dia,
            countersink_angle=countersink_angle,
            counterbore_dia=counterbore_dia,
            counterbore_depth=counterbore_depth,
            quantity=quantity,
            tolerance=str(tolerance) if tolerance is not None else None,
            clearance_for=clearance_for,
            fit=fit,
            elbow_offset=(elbow_dx, elbow_dy),
            view=self,
        )
        return hc

    def thread_callout(
        self,
        model_x: float = 0.0,
        model_y: float = 0.0,
        thread: str = "M5x0.8",
        depth: float | str | None = "THRU",
        class_fit: str | None = None,
        quantity: int | None = None,
        show_tap_drill: bool = False,
        elbow_dx: float = 15.0,
        elbow_dy: float = -12.0,
        *,
        anchor: Any = None,
    ) -> ThreadCallout:
        """Add a standard engineering thread callout at (model_x, model_y) or an anchor."""
        target = anchor if anchor is not None else self.to_sheet_coords(model_x, model_y)
        tc = ThreadCallout(
            center=target,
            thread=thread,
            depth=depth,
            class_fit=class_fit,
            quantity=quantity,
            show_tap_drill=show_tap_drill,
            elbow_offset=(elbow_dx, elbow_dy),
            view=self,
        )
        return tc

    def cosmetic_thread(
        self,
        target: Any = None,
        thread: str | Any | None = None,
        nominal_diameter: float | None = None,
        minor_diameter: float | None = None,
        thread_type: str = "internal",
        depth: float | None = None,
        model_x: float | None = None,
        model_y: float | None = None,
        view_mode: str | None = None,
    ) -> CosmeticThread:
        """Add an ISO 6410-1 cosmetic thread representation to this view."""
        center_pt = (
            self.to_sheet_coords(model_x, model_y)
            if model_x is not None and model_y is not None
            else None
        )
        return CosmeticThread(
            target=target,
            thread=thread,
            nominal_diameter=nominal_diameter,
            minor_diameter=minor_diameter,
            thread_type=thread_type,
            depth=depth,
            center=center_pt,
            view_mode=view_mode,
            view=self,
        )

    def auto_cosmetic_threads(
        self,
        *,
        threaded_diameters: dict[float, str] | None = None,
        infer_threads: bool = False,
        tolerance: float = 0.08,
    ) -> list[CosmeticThread]:
        """Automatically generate ISO 6410-1 CosmeticThread annotations from recognized holes."""
        return auto_cosmetic_threads(
            self,
            threaded_diameters=threaded_diameters,
            infer_threads=infer_threads,
            tolerance=tolerance,
        )

    def dim_half_diameter(
        self,
        target: Any = None,
        axis_point: Any = None,
        diameter: float | None = None,
        orientation: str = "auto",
        side: str = "auto",
        offset: float = 0.0,
        dim_pos: float | None = None,
        past_centerline: float = 5.0,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        prefix: str = "⌀",
        suffix: str = "",
        *,
        anchor: Any = None,
    ) -> HalfDiameterDimension:
        """Add an ISO 129-1 §5.2.3 diametral centerline half-dimension to this view."""
        dim = HalfDiameterDimension(
            target=target,
            axis_point=axis_point,
            diameter=diameter,
            orientation=orientation,
            side=side,
            offset=offset,
            dim_pos=dim_pos,
            past_centerline=past_centerline,
            text=text,
            tolerance=tolerance,
            prefix=prefix,
            suffix=suffix,
            view=self,
            anchor=anchor,
        )
        self.add(dim)
        return dim

    def undercut_callout(
        self,
        target: Any = None,
        spec: Any = "E 0.8x0.3",
        roughness: str | None = None,
        quantity: int | None = None,
        include_standard: bool = True,
        elbow_dx: float = 15.0,
        elbow_dy: float = -12.0,
        *,
        anchor: Any = None,
    ) -> UndercutCallout:
        """Add a DIN 509 relief undercut callout to this view."""
        uc = UndercutCallout(
            target=target,
            spec=spec,
            roughness=roughness,
            quantity=quantity,
            include_standard=include_standard,
            elbow_offset=(elbow_dx, elbow_dy),
            view=self,
            anchor=anchor,
        )
        return uc

    def auto_dimension_turned(
        self,
        shape: Any | None = None,
        *,
        half_diameters: bool = True,
        include_centerline: bool = True,
        include_diameters: bool = True,
        include_lengths: bool = True,
        include_chamfers: bool = True,
        include_undercuts: bool = True,
        tolerance: str | None = None,
    ) -> list[Annotation]:
        """Automatically dimension a turned/cylindrical view using ISO lathe conventions."""
        from build123d_techdraw.layout.turned import auto_dimension_turned_view

        return auto_dimension_turned_view(
            self,
            shape=shape,
            half_diameters=half_diameters,
            include_centerline=include_centerline,
            include_diameters=include_diameters,
            include_lengths=include_lengths,
            include_chamfers=include_chamfers,
            include_undercuts=include_undercuts,
            tolerance=tolerance,
        )

    def add_bend_annotations(
        self,
        *,
        include_tag: bool = True,
        include_allowance: bool = False,
        show_bend_extents: bool = False,
        label_mode: Literal["auto", "inline", "leader"] = "auto",
    ) -> list[BendLineAnnotation]:
        """Attach ``BendLineAnnotation`` items for every bend on this flat pattern view."""
        from build123d_techdraw.annotations.sheet_metal import BendLineAnnotation

        if self.flat_pattern is None:
            return []
        created: list[BendLineAnnotation] = []
        for bend in self.flat_pattern.bends:
            ann = BendLineAnnotation(
                bend,
                include_tag=include_tag,
                include_allowance=include_allowance,
                show_bend_extents=show_bend_extents,
                label_mode=label_mode,
                view=self,
            )
            created.append(ann)
        return created

    def add_punch_markers(
        self,
        *,
        show_tag: bool = True,
        show_callout: bool = False,
    ) -> list[PunchMarker]:
        """Attach ``PunchMarker`` items for every punch on this flat pattern view."""
        from build123d_techdraw.annotations.sheet_metal import PunchMarker

        if self.flat_pattern is None:
            return []
        created: list[PunchMarker] = []
        for punch in self.flat_pattern.punches:
            ann = PunchMarker(
                punch,
                show_tag=show_tag,
                show_callout=show_callout,
                view=self,
            )
            created.append(ann)
        return created

    def auto_dimension_flat_pattern(
        self,
        *,
        include_overall: bool = True,
        include_bend_stations: bool = True,
        include_punch_dims: bool = False,
        tolerance: str | None = None,
    ) -> list[Annotation]:
        """Auto-dimension this flat pattern view with overall blank and bend-station dims."""
        from build123d_techdraw.layout.sheet_metal import auto_dimension_flat_pattern_view

        return auto_dimension_flat_pattern_view(
            self,
            flat_pattern=self.flat_pattern,
            include_overall=include_overall,
            include_bend_stations=include_bend_stations,
            include_punch_dims=include_punch_dims,
            tolerance=tolerance,
        )

center property

View center on the drawing sheet in paper mm.

add(item)

Attach an annotation or collection of annotations to this view.

Source code in src/build123d_techdraw/core/view.py
def add(self, item: Annotation | Iterable[Annotation]) -> Self:
    """Attach an annotation or collection of annotations to this view."""
    if not isinstance(item, Annotation):
        if not isinstance(item, Iterable) or isinstance(item, str):
            raise TypeError(f"Cannot add {type(item).__name__} to a SheetView.")
        for sub_item in item:
            self.add(sub_item)
        return self

    item._attach_to_view(self)

    if item not in self.annotations:
        self.annotations.append(item)

    if self.sheet is not None and item not in self.sheet.annotations:
        self.sheet.annotations.append(item)

    return self

add_break(interval, axis='X', style='zigzag', gap=10.0)

Cut a uniform span out of the view (ISO 128-3 interrupted view).

Parameters:

Name Type Description Default
interval tuple[float, float]

Start and end of the removed span in absolute model coordinates along axis (the frame used by to_sheet_x / to_sheet_y). Both ends must lie strictly inside the part so material remains on both sides.

required
axis str

"X" (horizontal break) or "Y" (vertical break). All breaks of one view must use the same axis.

'X'
style str

"zigzag" or "wavy" break lines.

'zigzag'
gap float

Paper distance in mm between the two break lines.

10.0

Dimensions keep reporting true model lengths; only the drawn span is shortened.

Source code in src/build123d_techdraw/core/view.py
def add_break(
    self,
    interval: tuple[float, float],
    axis: str = "X",
    style: str = "zigzag",
    gap: float = 10.0,
) -> Self:
    """Cut a uniform span out of the view (ISO 128-3 interrupted view).

    Args:
        interval: Start and end of the removed span in absolute model coordinates along
            ``axis`` (the frame used by ``to_sheet_x`` / ``to_sheet_y``). Both ends must lie
            strictly inside the part so material remains on both sides.
        axis: ``"X"`` (horizontal break) or ``"Y"`` (vertical break). All breaks of one
            view must use the same axis.
        style: ``"zigzag"`` or ``"wavy"`` break lines.
        gap: Paper distance in mm between the two break lines.

    Dimensions keep reporting true model lengths; only the drawn span is shortened.
    """
    axis_u = axis.upper()
    style_l = style.lower()
    if axis_u not in ("X", "Y"):
        raise ValueError(f"Break axis must be 'X' or 'Y', got {axis!r}.")
    if style_l not in ("zigzag", "wavy"):
        raise ValueError(f"Break style must be 'zigzag' or 'wavy', got {style!r}.")
    if gap <= 0.0:
        raise ValueError(f"Break gap must be positive, got {gap}.")
    lo, hi = min(interval[0], interval[1]), max(interval[0], interval[1])
    half = self._unbroken_paper_length(axis_u) / (2.0 * self.scale) if self.scale else 0.0
    origin = self.origin_x if axis_u == "X" else self.origin_y
    part_min, part_max = origin - half, origin + half
    if not (part_min < lo < hi < part_max):
        raise ValueError(
            f"Break interval {interval} must lie strictly inside the part "
            f"({part_min:g} < start < end < {part_max:g} along {axis_u}, model coordinates)."
        )
    if (hi - lo) * self.scale <= gap:
        raise ValueError(
            f"Break interval {interval} is shorter on paper than the gap ({gap} mm)."
        )
    for other in self.breaks:
        if other.axis != axis_u:
            raise ValueError("All breaks of a view must use the same axis.")
        if lo < other.interval[1] and other.interval[0] < hi:
            raise ValueError(f"Break interval {interval} overlaps {other.interval}.")
    self.breaks.append(BreakInfo(interval=(lo, hi), axis=axis_u, style=style_l, gap=gap))
    self.breaks.sort(key=lambda b: b.interval[0])
    self._apply_breaks()
    return self

break_gap_centers(axis)

Broken-view paper positions (mm) of the middle of each break gap along axis.

Source code in src/build123d_techdraw/core/view.py
def break_gap_centers(self, axis: str) -> list[float]:
    """Broken-view paper positions (mm) of the middle of each break gap along ``axis``."""
    return [
        self._map_through_breaks((c0 + c1) / 2.0, axis) for c0, c1, _ in self._break_cuts(axis)
    ]

export_dxf(filepath, layers=None, scale=1.0, dxfversion='R2010')

Export 1:1 CAM manufacturing DXF from this 2D view (outer profile, holes, centerlines).

Source code in src/build123d_techdraw/core/view.py
def export_dxf(
    self,
    filepath: str,
    layers: dict[str, str] | None = None,
    scale: float = 1.0,
    dxfversion: str = "R2010",
) -> None:
    """Export 1:1 CAM manufacturing DXF from this 2D view (outer profile, holes, centerlines)."""
    if self.flat_pattern is not None:
        from build123d_techdraw.renderers.dxf import DXFRenderer

        DXFRenderer.export_flat_pattern_to_dxf(
            self.flat_pattern,
            filepath,
            layers=layers,
            dxfversion=dxfversion,
        )
        return

    from build123d_techdraw.recognizers.features import recognize_holes

    os.makedirs(os.path.dirname(os.path.abspath(filepath)), exist_ok=True)
    exporter = bd.ExportDXF(version=dxfversion, unit=bd.Unit.MM)
    doc = exporter._document
    msp = exporter._modelspace

    layer_map = {
        "outer_profile": "CUT_OUTER",
        "inner_holes": "CUT_INNER",
        "centerlines": "MARK",
        "countersinks": "ETCH",
    }
    if layers:
        layer_map.update(layers)

    layer_colors = {
        layer_map["outer_profile"]: 7,
        layer_map["inner_holes"]: 1,
        layer_map["centerlines"]: 4,
        layer_map["countersinks"]: 2,
    }
    for lname in set(layer_map.values()):
        color = layer_colors.get(lname, 7)
        with contextlib.suppress(Exception):
            doc.layers.new(name=lname, dxfattribs={"color": color})

    shape = self.shape
    if shape is None:
        exporter.write(filepath)
        return

    def _export_edge(edge: Any, layer: str) -> None:
        exporter.add_shape(edge.scale(scale) if scale != 1.0 else edge, layer=layer)

    look_from, look_up = VIEW_VECTORS.get(self.view_type, ((0.0, -1.0, 0.0), (0.0, 0.0, 1.0)))
    dwg = Drawing(shape, look_from=look_from, look_up=look_up, with_hidden=False)
    edges = dwg.visible_lines.edges()

    # Identify holes/countersinks via feature recognizer
    rec_holes = recognize_holes(shape)
    csink_radii: list[float] = []
    for rh in rec_holes:
        if rh.countersink_dia:
            csink_radii.append(round(rh.countersink_dia / 2.0, 2))
        if rh.counterbore_dia:
            csink_radii.append(round(rh.counterbore_dia / 2.0, 2))

    # Combine edges into closed wires
    wires: list[bd.Wire] = []
    try:
        wires = bd.Wire.combine(edges)
    except Exception:
        wires = []

    if wires:
        wires.sort(
            key=lambda w: bd.Face(w).area if w.is_closed else 0.0,
            reverse=True,
        )
        outer_wire = wires[0]
        inner_wires = wires[1:]

        for edge in outer_wire.edges():
            _export_edge(edge, layer_map["outer_profile"])

        # Detect concentric circular wires where outer step is countersink/counterbore
        concentric_csinks: set[int] = set()
        circle_wires: list[tuple[int, tuple[float, float], float]] = []
        for idx, iw in enumerate(inner_wires):
            cw_edges = iw.edges()
            if len(cw_edges) == 1 and cw_edges[0].geom_type == bd.GeomType.CIRCLE:
                c = cw_edges[0].arc_center
                circle_wires.append((idx, (float(c.X), float(c.Y)), float(cw_edges[0].radius)))

        for i in range(len(circle_wires)):
            for j in range(i + 1, len(circle_wires)):
                idx_i, center_i, r_i = circle_wires[i]
                idx_j, center_j, r_j = circle_wires[j]
                dist = (
                    (center_i[0] - center_j[0]) ** 2 + (center_i[1] - center_j[1]) ** 2
                ) ** 0.5
                if dist < 0.5:
                    if r_i > r_j:
                        concentric_csinks.add(idx_i)
                    else:
                        concentric_csinks.add(idx_j)

        for idx, iw in enumerate(inner_wires):
            is_csink = idx in concentric_csinks
            if not is_csink:
                for edge in iw.edges():
                    if edge.geom_type == bd.GeomType.CIRCLE:
                        r = round(float(edge.radius), 2)
                        if any(abs(r - cr) < 0.5 for cr in csink_radii):
                            is_csink = True
                            break
            target_l = layer_map["countersinks"] if is_csink else layer_map["inner_holes"]
            for edge in iw.edges():
                _export_edge(edge, target_l)
    else:
        for edge in edges:
            _export_edge(edge, layer_map["outer_profile"])

    center_layer = layer_map["centerlines"]
    has_ann_centerlines = False
    for ann in self.annotations:
        if isinstance(ann, (CenterMark, BoltCircle, DiameterDimension, RadialDimension)):
            has_ann_centerlines = True
            cx, cy = ann.center
            r = ann.radius if isinstance(ann, RadialDimension) else 5.0
            msp.add_line(
                ((cx - r - 2.0) * scale, cy * scale),
                ((cx + r + 2.0) * scale, cy * scale),
                dxfattribs={"layer": center_layer},
            )
            msp.add_line(
                (cx * scale, (cy - r - 2.0) * scale),
                (cx * scale, (cy + r + 2.0) * scale),
                dxfattribs={"layer": center_layer},
            )

    if not has_ann_centerlines and rec_holes:
        for rh in rec_holes:
            c3d = rh.center_3d
            if self.projection_origin and self.proj_x and self.proj_y:
                p = bd.Vector(c3d[0], c3d[1], c3d[2]) - self.projection_origin
                cx2d = float(p.dot(self.proj_x))
                cy2d = float(p.dot(self.proj_y))
            else:
                cx2d, cy2d = float(c3d[0]), float(c3d[1])
            r = float(rh.diameter) / 2.0
            msp.add_line(
                ((cx2d - r - 2.0) * scale, cy2d * scale),
                ((cx2d + r + 2.0) * scale, cy2d * scale),
                dxfattribs={"layer": center_layer},
            )
            msp.add_line(
                (cx2d * scale, (cy2d - r - 2.0) * scale),
                (cx2d * scale, (cy2d + r + 2.0) * scale),
                dxfattribs={"layer": center_layer},
            )

    exporter.write(filepath)

can_regenerate()

Return True if update_shape is able to re-project this view's geometry.

Source code in src/build123d_techdraw/core/view.py
def can_regenerate(self) -> bool:
    """Return True if ``update_shape`` is able to re-project this view's geometry."""
    if self.view_type == ViewType.DETAIL:
        return self._regen_factory is not None and self.parent_view is not None
    if self.view_type in (ViewType.SECTION, ViewType.AUXILIARY, ViewType.FLAT_PATTERN):
        return self._regen_factory is not None
    return True

update_shape(new_shape)

Update the view's 3D shape, re-project geometry, and re-bind all anchored annotations.

Every view type is regenerated from the parameters it was built with (cut plane, section path, detail region, auxiliary direction, explicit model_origin, label placement). Detail views follow their parent view: the parent is updated to new_shape first if needed, then the detail is re-cut from it. Space reserved below the view by dimensions (bottom_annotation_y) is kept, shifted with the view's new bottom edge.

Raises:

Type Description
ValueError

if this view has no recorded build parameters and cannot be regenerated (section/detail/auxiliary views constructed by hand).

Source code in src/build123d_techdraw/core/view.py
def update_shape(self, new_shape: Any) -> Self:
    """Update the view's 3D shape, re-project geometry, and re-bind all anchored annotations.

    Every view type is regenerated from the parameters it was built with (cut plane,
    section path, detail region, auxiliary direction, explicit ``model_origin``,
    label placement). Detail views follow their parent view: the parent is updated to
    ``new_shape`` first if needed, then the detail is re-cut from it. Space reserved
    below the view by dimensions (``bottom_annotation_y``) is kept, shifted with the
    view's new bottom edge.

    Raises:
        ValueError: if this view has no recorded build parameters and cannot be
            regenerated (section/detail/auxiliary views constructed by hand).
    """
    if not self.can_regenerate():
        raise ValueError(
            f"Cannot update shape of {self.view_type.value} view "
            f"{self.view_label or ''!r}: it was not created by a projection factory, "
            "so its build parameters are unknown. Recreate the view instead."
        )

    old_max_y = self.max_y
    old_bottom = self.bottom_annotation_y
    reproj = self._reproject(new_shape)

    self.shape = reproj.shape if self.view_type == ViewType.DETAIL else new_shape
    self._copy_projection_from(reproj)
    if reproj.hatch_id is not None:
        self.hatch = reproj.hatch
        self.hatch_pitch = reproj.hatch_pitch
        self.hatch_angle = reproj.hatch_angle
        self.hatch_id = reproj.hatch_id
    if reproj.parent_view is not None:
        self.parent_view = reproj.parent_view
    self._parent_callout_svg = reproj._parent_callout_svg
    if self.breaks:
        self._apply_breaks()

    # Keep annotation space reserved below the view, moved with the view's bottom edge.
    self.bottom_annotation_y = max(self.max_y, old_bottom + (self.max_y - old_max_y))

    self._rebind_annotations()
    return self

locate(center)

Reposition the view center on the sheet (in paper mm).

Source code in src/build123d_techdraw/core/view.py
def locate(self, center: tuple[float, float]) -> Self:
    """Reposition the view center on the sheet (in paper mm)."""
    dx = float(center[0]) - self.center_x
    dy = float(center[1]) - self.center_y
    self.center_x = float(center[0])
    self.center_y = float(center[1])
    self.min_x = self.center_x - self.width / 2.0
    self.max_x = self.center_x + self.width / 2.0
    self.min_y = self.center_y - self.height / 2.0
    self.max_y = self.center_y + self.height / 2.0
    if self.breaks:
        self._refresh_bounds()
    self.bottom_annotation_y = self.max_y
    if self.view_label_pos is not None:
        self.view_label_pos = (self.view_label_pos[0] + dx, self.view_label_pos[1] + dy)
    self._update_transform()
    self._rebind_annotations()
    return self

scale_to(scale)

Change the view scale factor and update its bounding box.

Source code in src/build123d_techdraw/core/view.py
def scale_to(self, scale: float) -> Self:
    """Change the view scale factor and update its bounding box."""
    if self.scale != 0.0:
        ratio = scale / self.scale
        self.width *= ratio
        self.height *= ratio
        self.unbroken_width *= ratio
        self.unbroken_height *= ratio
    self.scale = scale
    self.min_x = self.center_x - self.width / 2.0
    self.max_x = self.center_x + self.width / 2.0
    self.min_y = self.center_y - self.height / 2.0
    self.max_y = self.center_y + self.height / 2.0
    if self.breaks:
        self._refresh_bounds()
    self.bottom_annotation_y = self.max_y
    self.scale_label = format_iso_scale(scale)
    self._update_transform()
    self._rebind_annotations()
    return self

get_visual_bounds(include_annotations=True, include_label=True)

Compute the visual bounding box (min_x, min_y, max_x, max_y) of this view in paper mm.

Source code in src/build123d_techdraw/core/view.py
def get_visual_bounds(
    self,
    include_annotations: bool = True,
    include_label: bool = True,
) -> tuple[float, float, float, float]:
    """Compute the visual bounding box (min_x, min_y, max_x, max_y) of this view in paper mm."""
    min_x = self.min_x
    min_y = self.min_y
    max_x = self.max_x
    max_y = self.max_y

    if include_annotations:
        for ann in self.annotations:
            bbox = ann.bounding_box_2d()
            if bbox is not None:
                min_x = min(min_x, bbox[0])
                min_y = min(min_y, bbox[1])
                max_x = max(max_x, bbox[2])
                max_y = max(max_y, bbox[3])

    if include_label and (self.view_label or self.scale_label):
        label_y = self.bottom_annotation_y + 8.0
        max_y = max(max_y, label_y + 4.0)

    return (min_x, min_y, max_x, max_y)

__getitem__(key)

Provide dictionary-style access for backward compatibility.

Source code in src/build123d_techdraw/core/view.py
def __getitem__(self, key: str) -> Any:
    """Provide dictionary-style access for backward compatibility."""
    attrs = {
        "view_type": self.view_type,
        "center_x": self.center_x,
        "center_y": self.center_y,
        "scale": self.scale,
        "width": self.width,
        "height": self.height,
        "min_x": self.min_x,
        "max_x": self.max_x,
        "min_y": self.min_y,
        "max_y": self.max_y,
        "origin_x": self.origin_x,
        "origin_y": self.origin_y,
    }
    if key in attrs:
        return attrs[key]
    raise KeyError(key)

to_sheet_x(model_x)

Transform 2D model X coordinate to sheet paper coordinate (mm), honouring breaks.

Source code in src/build123d_techdraw/core/view.py
def to_sheet_x(self, model_x: float) -> float:
    """Transform 2D model X coordinate to sheet paper coordinate (mm), honouring breaks."""
    raw_x = self.center_x + ((model_x - self.origin_x) * self.scale)
    return self._map_through_breaks(raw_x, "X")

to_sheet_y(model_y)

Transform 2D model Y coordinate to sheet paper coordinate (mm), honouring breaks.

Source code in src/build123d_techdraw/core/view.py
def to_sheet_y(self, model_y: float) -> float:
    """Transform 2D model Y coordinate to sheet paper coordinate (mm), honouring breaks."""
    raw_y = self.center_y - ((model_y - self.origin_y) * self.scale)
    return self._map_through_breaks(raw_y, "Y")

to_sheet_coords(model_x, model_y)

Transform 2D model (X, Y) to sheet paper (X, Y) coordinates (mm).

Source code in src/build123d_techdraw/core/view.py
def to_sheet_coords(self, model_x: float, model_y: float) -> tuple[float, float]:
    """Transform 2D model (X, Y) to sheet paper (X, Y) coordinates (mm)."""
    return (self.to_sheet_x(model_x), self.to_sheet_y(model_y))

to_sheet_3d(x, y, z)

Project a 3D part point (X, Y, Z) to 2D sheet paper coordinate space (mm).

Source code in src/build123d_techdraw/core/view.py
def to_sheet_3d(self, x: float, y: float, z: float) -> tuple[float, float]:
    """Project a 3D part point (X, Y, Z) to 2D sheet paper coordinate space (mm)."""
    if self.projection_origin is None or self.proj_x is None or self.proj_y is None:
        return self.to_sheet_coords(x, y)
    p = bd.Vector(x, y, z) - self.projection_origin
    x2d = p.dot(self.proj_x)
    y2d = p.dot(self.proj_y)
    sx = self.center_x + (x2d - self.orig_cx) * self.scale
    sy = self.center_y + (-y2d - self.orig_cy) * self.scale
    return (self._map_through_breaks(sx, "X"), self._map_through_breaks(sy, "Y"))

dimension(target, offset=-8.0, direction=None, text=None, tolerance=None, prefix='', suffix='')

Add a dimension for a topological Edge, Face, or pair of points in this view.

Automatically determines dimension direction and length from the model entity.

Source code in src/build123d_techdraw/core/view.py
def dimension(
    self,
    target: Any,
    offset: float = -8.0,
    direction: str | None = None,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add a dimension for a topological Edge, Face, or pair of points in this view.

    Automatically determines dimension direction and length from the model entity.
    """
    dim = LinearDimension(
        target_or_start=target,
        offset=offset,
        direction=direction,
        text=text,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    return dim

dimension_between(target1, target2, direction='horizontal', offset=-8.0, text=None, tolerance=None, prefix='', suffix='')

Add a linear dimension between two model vertices, edges, or points in this view.

Source code in src/build123d_techdraw/core/view.py
def dimension_between(
    self,
    target1: Any,
    target2: Any,
    direction: str = "horizontal",
    offset: float = -8.0,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add a linear dimension between two model vertices, edges, or points in this view."""
    from build123d_techdraw.annotations.resolver import is_topological_entity

    if (
        isinstance(target1, (tuple, list))
        and isinstance(target2, (tuple, list))
        and not is_topological_entity(target1)
        and not is_topological_entity(target2)
    ):
        if len(target1) == 2 and len(target2) == 2:
            s1 = self.to_sheet_coords(float(target1[0]), float(target1[1]))
            s2 = self.to_sheet_coords(float(target2[0]), float(target2[1]))
            d_lower = direction.lower() if direction else "horizontal"
            if text is None:
                from build123d_techdraw.annotations.dimensions import format_dimension_value

                if d_lower == "horizontal":
                    m_dist = abs(float(target2[0]) - float(target1[0]))
                elif d_lower == "vertical":
                    m_dist = abs(float(target2[1]) - float(target1[1]))
                else:
                    m_dist = math.hypot(
                        float(target2[0]) - float(target1[0]),
                        float(target2[1]) - float(target1[1]),
                    )
                text = format_dimension_value(m_dist)
            dim = LinearDimension(
                start=s1,
                end=s2,
                direction=direction,
                offset=offset,
                text=text,
                tolerance=tolerance,
                prefix=prefix,
                suffix=suffix,
                view=self,
            )
            self.add(dim)
            return dim
        elif len(target1) == 3 and len(target2) == 3:
            s1 = self.to_sheet_3d(float(target1[0]), float(target1[1]), float(target1[2]))
            s2 = self.to_sheet_3d(float(target2[0]), float(target2[1]), float(target2[2]))
            if text is None:
                from build123d_techdraw.annotations.dimensions import format_dimension_value

                dx = float(target2[0]) - float(target1[0])
                dy = float(target2[1]) - float(target1[1])
                dz = float(target2[2]) - float(target1[2])
                d_lower = direction.lower() if direction else "horizontal"
                if d_lower == "horizontal":
                    m_dist = abs(dx)
                elif d_lower == "vertical":
                    m_dist = abs(dz if abs(dz) > 1e-4 else dy)
                else:
                    m_dist = math.hypot(dx, dy, dz)
                text = format_dimension_value(m_dist)
            dim = LinearDimension(
                start=s1,
                end=s2,
                direction=direction,
                offset=offset,
                text=text,
                tolerance=tolerance,
                prefix=prefix,
                suffix=suffix,
                view=self,
            )
            self.add(dim)
            return dim

    dim = LinearDimension(
        target_or_start=target1,
        target2_or_end=target2,
        direction=direction,
        offset=offset,
        text=text,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    return dim

dim_horizontal(model_x1, model_x2, model_y, offset_y=-8.0, text=None, tolerance=None, prefix='', suffix='')

Add a horizontal dimension between model_x1 and model_x2 at model_y.

Source code in src/build123d_techdraw/core/view.py
def dim_horizontal(
    self,
    model_x1: float,
    model_x2: float,
    model_y: float,
    offset_y: float = -8.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add a horizontal dimension between model_x1 and model_x2 at model_y."""
    sx1 = self.to_sheet_x(model_x1)
    sx2 = self.to_sheet_x(model_x2)
    sy = self.to_sheet_y(model_y)
    dim = LinearDimension(
        start=(sx1, sy),
        end=(sx2, sy),
        offset=offset_y,
        dim_type=DimensionType.HORIZONTAL,
        text=text,
        nominal=None if text is not None else abs(model_x2 - model_x1),
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    if dim.offset > 0:
        self.bottom_annotation_y = max(self.bottom_annotation_y, sy + dim.offset + 4.0)
    return dim

dim_vertical(model_y1, model_y2, model_x, offset_x=-10.0, text=None, tolerance=None, prefix='', suffix='')

Add a vertical dimension between model_y1 and model_y2 at model_x.

Source code in src/build123d_techdraw/core/view.py
def dim_vertical(
    self,
    model_y1: float,
    model_y2: float,
    model_x: float,
    offset_x: float = -10.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add a vertical dimension between model_y1 and model_y2 at model_x."""
    sy1 = self.to_sheet_y(model_y1)
    sy2 = self.to_sheet_y(model_y2)
    sx = self.to_sheet_x(model_x)
    dim = LinearDimension(
        start=(sx, sy1),
        end=(sx, sy2),
        offset=offset_x,
        dim_type=DimensionType.VERTICAL,
        text=text,
        nominal=None if text is not None else abs(model_y2 - model_y1),
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    return dim

dim_aligned(p1_model, p2_model, offset=8.0, text=None, tolerance=None, prefix='', suffix='')

Add an aligned dimension between two model points.

Source code in src/build123d_techdraw/core/view.py
def dim_aligned(
    self,
    p1_model: tuple[float, float],
    p2_model: tuple[float, float],
    offset: float = 8.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add an aligned dimension between two model points."""
    s1 = self.to_sheet_coords(p1_model[0], p1_model[1])
    s2 = self.to_sheet_coords(p2_model[0], p2_model[1])
    dim = LinearDimension(
        start=s1,
        end=s2,
        offset=offset,
        dim_type=DimensionType.ALIGNED,
        text=text,
        nominal=None if text is not None else math.dist(p1_model, p2_model),
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    return dim

add_overall_horizontal(offset_y=-8.0, text=None, tolerance=None, prefix='', suffix='')

Add an overall horizontal dimension spanning view's bounding box.

Source code in src/build123d_techdraw/core/view.py
def add_overall_horizontal(
    self,
    offset_y: float = -8.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add an overall horizontal dimension spanning view's bounding box."""
    y_ref = self.min_y if offset_y < 0 else self.max_y
    dim = LinearDimension(
        start=(self.min_x, y_ref),
        end=(self.max_x, y_ref),
        offset=offset_y,
        dim_type=DimensionType.HORIZONTAL,
        text=text,
        nominal=None
        if text is not None or not self.scale
        else self.unbroken_width / self.scale,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    if dim.offset > 0:
        self.bottom_annotation_y = max(self.bottom_annotation_y, y_ref + dim.offset + 4.0)
    return dim

add_overall_vertical(offset_x=-10.0, text=None, tolerance=None, prefix='', suffix='')

Add an overall vertical dimension spanning view's bounding box.

Source code in src/build123d_techdraw/core/view.py
def add_overall_vertical(
    self,
    offset_x: float = -10.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "",
) -> LinearDimension:
    """Add an overall vertical dimension spanning view's bounding box."""
    x_ref = self.min_x if offset_x < 0 else self.max_x
    dim = LinearDimension(
        start=(x_ref, self.min_y),
        end=(x_ref, self.max_y),
        offset=offset_x,
        dim_type=DimensionType.VERTICAL,
        text=text,
        nominal=None
        if text is not None or not self.scale
        else self.unbroken_height / self.scale,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    self.add(dim)
    return dim

auto_dimension(tolerance=None)

Automatically dimension this view using collision-avoiding placement.

Source code in src/build123d_techdraw/core/view.py
def auto_dimension(self, tolerance: str | None = None) -> list[Any]:
    """Automatically dimension this view using collision-avoiding placement."""
    from build123d_techdraw.layout.auto_dimension import auto_dimension_view

    return auto_dimension_view(self, tolerance=tolerance)

dim_radial(center_model, radius_model, angle_deg=45.0, text=None, tolerance=None)

Add a radial dimension pointing to an arc defined in model space.

Source code in src/build123d_techdraw/core/view.py
def dim_radial(
    self,
    center_model: tuple[float, float],
    radius_model: float,
    angle_deg: float = 45.0,
    text: str | None = None,
    tolerance: str | None = None,
) -> RadialDimension:
    """Add a radial dimension pointing to an arc defined in model space."""
    cx, cy = self.to_sheet_coords(center_model[0], center_model[1])
    dim = RadialDimension(
        center=(cx, cy),
        radius=radius_model * self.scale,
        angle_deg=angle_deg,
        text=text,
        tolerance=tolerance,
        view=self,
    )
    self.add(dim)
    return dim

dim_diameter(center_model, diameter_model, angle_deg=45.0, text=None, tolerance=None)

Add a diameter dimension across a hole/cylinder defined in model space.

Source code in src/build123d_techdraw/core/view.py
def dim_diameter(
    self,
    center_model: tuple[float, float],
    diameter_model: float,
    angle_deg: float = 45.0,
    text: str | None = None,
    tolerance: str | None = None,
) -> DiameterDimension:
    """Add a diameter dimension across a hole/cylinder defined in model space."""
    cx, cy = self.to_sheet_coords(center_model[0], center_model[1])
    dim = DiameterDimension(
        center=(cx, cy),
        diameter=diameter_model * self.scale,
        angle_deg=angle_deg,
        text=text,
        tolerance=tolerance,
        view=self,
    )
    self.add(dim)
    return dim

dim_angular(target1, target2, radius=20.0, text=None, tolerance=None, prefix='', suffix='°')

Add an angular dimension between two edges, rays, or faces in this view.

Source code in src/build123d_techdraw/core/view.py
def dim_angular(
    self,
    target1: Any,
    target2: Any,
    radius: float = 20.0,
    text: str | None = None,
    tolerance: str | None = None,
    prefix: str = "",
    suffix: str = "°",
) -> AngularDimension:
    """Add an angular dimension between two edges, rays, or faces in this view."""
    dim = AngularDimension(
        target1=target1,
        target2=target2,
        radius=radius,
        text=text,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    return dim

dim_ordinate(target, datum_coord=0.0, direction='horizontal', jog=0.0, extension_length=12.0, prefix='', suffix='')

Add an ordinate dimension point in this view.

Source code in src/build123d_techdraw/core/view.py
def dim_ordinate(
    self,
    target: Any,
    datum_coord: float = 0.0,
    direction: str = "horizontal",
    jog: float = 0.0,
    extension_length: float = 12.0,
    prefix: str = "",
    suffix: str = "",
) -> OrdinateDimension:
    """Add an ordinate dimension point in this view."""
    dim = OrdinateDimension(
        target=target,
        datum_coord=datum_coord,
        direction=direction,
        jog=jog,
        extension_length=extension_length,
        prefix=prefix,
        suffix=suffix,
        view=self,
    )
    return dim

chamfer_callout(target=None, width=None, angle_deg=45.0, style='iso', quantity=None, elbow_dx=15.0, elbow_dy=-12.0, *, anchor=None)

Add an ISO/ASME chamfer callout leader note.

Source code in src/build123d_techdraw/core/view.py
def chamfer_callout(
    self,
    target: Any = None,
    width: float | None = None,
    angle_deg: float = 45.0,
    style: str = "iso",
    quantity: int | None = None,
    elbow_dx: float = 15.0,
    elbow_dy: float = -12.0,
    *,
    anchor: Any = None,
) -> ChamferCallout:
    """Add an ISO/ASME chamfer callout leader note."""
    cc = ChamferCallout(
        target_or_edge=target,
        width=width,
        angle_deg=angle_deg,
        style=style,
        quantity=quantity,
        elbow_offset=(elbow_dx, elbow_dy),
        view=self,
        anchor=anchor,
    )
    return cc

weld_symbol(target, weld_type=WeldType.FILLET, size='a5', length=None, pitch=None, all_around=False, field_weld=False, tail_text=None, arrow_side=True, elbow_dx=16.0, elbow_dy=-12.0)

Add an ISO 2553 welding annotation.

Source code in src/build123d_techdraw/core/view.py
def weld_symbol(
    self,
    target: Any,
    weld_type: WeldType | str = WeldType.FILLET,
    size: str | float | None = "a5",
    length: str | float | None = None,
    pitch: str | float | None = None,
    all_around: bool = False,
    field_weld: bool = False,
    tail_text: str | None = None,
    arrow_side: bool = True,
    elbow_dx: float = 16.0,
    elbow_dy: float = -12.0,
) -> WeldingSymbol:
    """Add an ISO 2553 welding annotation."""
    ws = WeldingSymbol(
        target=target,
        weld_type=weld_type,
        size=size,
        length=length,
        pitch=pitch,
        all_around=all_around,
        field_weld=field_weld,
        tail_text=tail_text,
        arrow_side=arrow_side,
        elbow_offset=(elbow_dx, elbow_dy),
        view=self,
    )
    return ws

centermark(model_x, model_y, size=6.0)

Add a centermark crosshair at (model_x, model_y).

Source code in src/build123d_techdraw/core/view.py
def centermark(
    self,
    model_x: float,
    model_y: float,
    size: float = 6.0,
) -> CenterMark:
    """Add a centermark crosshair at (model_x, model_y)."""
    sc = self.to_sheet_coords(model_x, model_y)
    cm = CenterMark(center=sc, size=size, view=self)
    self.add(cm)
    return cm

centerline_horizontal(model_y=0.0, model_x1=None, model_x2=None, overhang=4.0)

Draw an ISO centerline across the horizontal axis at model_y.

Source code in src/build123d_techdraw/core/view.py
def centerline_horizontal(
    self,
    model_y: float = 0.0,
    model_x1: float | None = None,
    model_x2: float | None = None,
    overhang: float = 4.0,
) -> Centerline:
    """Draw an ISO centerline across the horizontal axis at model_y."""
    sy = self.to_sheet_y(model_y)
    sx1 = (
        self.to_sheet_x(model_x1) - overhang if model_x1 is not None else self.min_x - overhang
    )
    sx2 = (
        self.to_sheet_x(model_x2) + overhang if model_x2 is not None else self.max_x + overhang
    )
    cl = Centerline(start=(sx1, sy), end=(sx2, sy), view=self)
    self.add(cl)
    return cl

centerline_vertical(model_x=0.0, model_y1=None, model_y2=None, overhang=4.0)

Draw an ISO centerline across the vertical axis at model_x.

Source code in src/build123d_techdraw/core/view.py
def centerline_vertical(
    self,
    model_x: float = 0.0,
    model_y1: float | None = None,
    model_y2: float | None = None,
    overhang: float = 4.0,
) -> Centerline:
    """Draw an ISO centerline across the vertical axis at model_x."""
    sx = self.to_sheet_x(model_x)
    sy1 = (
        self.to_sheet_y(model_y1) + overhang if model_y1 is not None else self.max_y + overhang
    )
    sy2 = (
        self.to_sheet_y(model_y2) - overhang if model_y2 is not None else self.min_y - overhang
    )
    cl = Centerline(start=(sx, min(sy1, sy2)), end=(sx, max(sy1, sy2)), view=self)
    self.add(cl)
    return cl

bolt_circle(center_model=(0.0, 0.0), diameter_model=50.0, num_holes=4, start_angle_deg=0.0)

Add a bolt pitch circle diameter (PCD) annotation in model space.

Source code in src/build123d_techdraw/core/view.py
def bolt_circle(
    self,
    center_model: tuple[float, float] = (0.0, 0.0),
    diameter_model: float = 50.0,
    num_holes: int = 4,
    start_angle_deg: float = 0.0,
) -> BoltCircle:
    """Add a bolt pitch circle diameter (PCD) annotation in model space."""
    sc = self.to_sheet_coords(center_model[0], center_model[1])
    bc = BoltCircle(
        center=sc,
        diameter=diameter_model * self.scale,
        num_holes=num_holes,
        start_angle_deg=start_angle_deg,
        view=self,
    )
    self.add(bc)
    return bc

leader(model_x, model_y, lines, elbow_dx=15.0, elbow_dy=-12.0, shelf_length=20.0, align_right=None, terminator='dot')

Add a leader note pointing to (model_x, model_y) on the part.

Source code in src/build123d_techdraw/core/view.py
def leader(
    self,
    model_x: float,
    model_y: float,
    lines: list[str] | str,
    elbow_dx: float = 15.0,
    elbow_dy: float = -12.0,
    shelf_length: float = 20.0,
    align_right: bool | None = None,
    terminator: str = "dot",
) -> LeaderNote:
    """Add a leader note pointing to (model_x, model_y) on the part."""
    target = self.to_sheet_coords(model_x, model_y)
    line_list = [lines] if isinstance(lines, str) else list(lines)
    note = LeaderNote(
        target=target,
        lines=line_list,
        elbow_offset=(elbow_dx, elbow_dy),
        shelf_length=shelf_length,
        align_right=align_right,
        terminator=terminator,
        view=self,
    )
    self.add(note)
    return note

leader_3d(x, y, z, lines, elbow_dx=15.0, elbow_dy=-12.0, shelf_length=20.0, align_right=None, terminator='dot')

Add a leader note pointing to a 3D part point (x, y, z).

Source code in src/build123d_techdraw/core/view.py
def leader_3d(
    self,
    x: float,
    y: float,
    z: float,
    lines: list[str] | str,
    elbow_dx: float = 15.0,
    elbow_dy: float = -12.0,
    shelf_length: float = 20.0,
    align_right: bool | None = None,
    terminator: str = "dot",
) -> LeaderNote:
    """Add a leader note pointing to a 3D part point (x, y, z)."""
    target = self.to_sheet_3d(x, y, z)
    line_list = [lines] if isinstance(lines, str) else list(lines)
    note = LeaderNote(
        target=target,
        lines=line_list,
        elbow_offset=(elbow_dx, elbow_dy),
        shelf_length=shelf_length,
        align_right=align_right,
        terminator=terminator,
        view=self,
    )
    self.add(note)
    return note

balloon(item_no, model_x, model_y, balloon_x, balloon_y)

Add a BOM balloon callout pointing to (model_x, model_y).

Source code in src/build123d_techdraw/core/view.py
def balloon(
    self,
    item_no: int,
    model_x: float,
    model_y: float,
    balloon_x: float,
    balloon_y: float,
) -> BOMBalloon:
    """Add a BOM balloon callout pointing to (model_x, model_y)."""
    target = self.to_sheet_coords(model_x, model_y)
    balloon = BOMBalloon(
        item_no=item_no,
        target=target,
        balloon_center=(balloon_x, balloon_y),
        view=self,
    )
    self.add(balloon)
    return balloon

add_gdt_frame(model_x=0.0, model_y=0.0, characteristic=GDTCharacteristic.POSITION, tolerance_value='0.05', datum_a=None, datum_b=None, datum_c=None, leader_offset=None, *, anchor=None)

Add a GD&T Feature Control Frame near (model_x, model_y) or an anchor, optionally with a leader line.

Source code in src/build123d_techdraw/core/view.py
def add_gdt_frame(
    self,
    model_x: float = 0.0,
    model_y: float = 0.0,
    characteristic: GDTCharacteristic = GDTCharacteristic.POSITION,
    tolerance_value: str = "0.05",
    datum_a: str | None = None,
    datum_b: str | None = None,
    datum_c: str | None = None,
    leader_offset: tuple[float, float] | None = None,
    *,
    anchor: Any = None,
) -> FeatureControlFrame:
    """Add a GD&T Feature Control Frame near (model_x, model_y) or an anchor, optionally with a leader line."""
    if anchor is not None:
        fcf = FeatureControlFrame(
            characteristic=characteristic,
            tolerance_value=tolerance_value,
            datum_a=datum_a,
            datum_b=datum_b,
            datum_c=datum_c,
            leader_offset=leader_offset or (12.0, -10.0),
            view=self,
            anchor=anchor,
        )
        self.add(fcf)
        return fcf

    target_pos = self.to_sheet_coords(model_x, model_y)
    if leader_offset is not None:
        pos = (target_pos[0] + leader_offset[0], target_pos[1] + leader_offset[1])
        leader_target: tuple[float, float] | None = target_pos
    else:
        pos = target_pos
        leader_target = None

    fcf = FeatureControlFrame(
        position=pos,
        characteristic=characteristic,
        tolerance_value=tolerance_value,
        datum_a=datum_a,
        datum_b=datum_b,
        datum_c=datum_c,
        leader_target=leader_target,
        view=self,
    )
    self.add(fcf)
    return fcf

add_datum_symbol(model_x=0.0, model_y=0.0, label='A', direction='up', *, anchor=None)

Add an ISO datum feature identifier symbol at (model_x, model_y) or an anchor.

Source code in src/build123d_techdraw/core/view.py
def add_datum_symbol(
    self,
    model_x: float = 0.0,
    model_y: float = 0.0,
    label: str = "A",
    direction: str = "up",
    *,
    anchor: Any = None,
) -> DatumFeatureSymbol:
    """Add an ISO datum feature identifier symbol at (model_x, model_y) or an anchor."""
    target = anchor if anchor is not None else self.to_sheet_coords(model_x, model_y)
    sym = DatumFeatureSymbol(target=target, label=label, direction=direction, view=self)
    self.add(sym)
    return sym

add_surface_finish(model_x=0.0, model_y=0.0, ra_value='Ra 3.2', material_removal=MaterialRemoval.REQUIRED, process=None, *, anchor=None)

Add an ISO 1302 surface roughness symbol at (model_x, model_y) or an anchor.

Source code in src/build123d_techdraw/core/view.py
def add_surface_finish(
    self,
    model_x: float = 0.0,
    model_y: float = 0.0,
    ra_value: str = "Ra 3.2",
    material_removal: MaterialRemoval = MaterialRemoval.REQUIRED,
    process: str | None = None,
    *,
    anchor: Any = None,
) -> SurfaceFinishSymbol:
    """Add an ISO 1302 surface roughness symbol at (model_x, model_y) or an anchor."""
    sym = SurfaceFinishSymbol(
        position=None if anchor is not None else self.to_sheet_coords(model_x, model_y),
        ra_value=ra_value,
        material_removal=material_removal,
        process=process,
        view=self,
        anchor=anchor,
    )
    self.add(sym)
    return sym

hole_callout(model_x=0.0, model_y=0.0, diameter=None, depth=None, countersink_dia=None, countersink_angle=90.0, counterbore_dia=None, counterbore_depth=None, quantity=None, tolerance=None, clearance_for=None, fit='medium', elbow_dx=15.0, elbow_dy=-12.0, *, anchor=None)

Add a standard engineering hole callout at (model_x, model_y) or an anchor.

Source code in src/build123d_techdraw/core/view.py
def hole_callout(
    self,
    model_x: float = 0.0,
    model_y: float = 0.0,
    diameter: float | None = None,
    depth: float | str | None = None,
    countersink_dia: float | None = None,
    countersink_angle: float = 90.0,
    counterbore_dia: float | None = None,
    counterbore_depth: float | None = None,
    quantity: int | None = None,
    tolerance: str | Tolerance | None = None,
    clearance_for: str | None = None,
    fit: str = "medium",
    elbow_dx: float = 15.0,
    elbow_dy: float = -12.0,
    *,
    anchor: Any = None,
) -> HoleCallout:
    """Add a standard engineering hole callout at (model_x, model_y) or an anchor."""
    target = anchor if anchor is not None else self.to_sheet_coords(model_x, model_y)
    hc = HoleCallout(
        center=target,
        diameter=diameter,
        depth=depth,
        countersink_dia=countersink_dia,
        countersink_angle=countersink_angle,
        counterbore_dia=counterbore_dia,
        counterbore_depth=counterbore_depth,
        quantity=quantity,
        tolerance=str(tolerance) if tolerance is not None else None,
        clearance_for=clearance_for,
        fit=fit,
        elbow_offset=(elbow_dx, elbow_dy),
        view=self,
    )
    return hc

thread_callout(model_x=0.0, model_y=0.0, thread='M5x0.8', depth='THRU', class_fit=None, quantity=None, show_tap_drill=False, elbow_dx=15.0, elbow_dy=-12.0, *, anchor=None)

Add a standard engineering thread callout at (model_x, model_y) or an anchor.

Source code in src/build123d_techdraw/core/view.py
def thread_callout(
    self,
    model_x: float = 0.0,
    model_y: float = 0.0,
    thread: str = "M5x0.8",
    depth: float | str | None = "THRU",
    class_fit: str | None = None,
    quantity: int | None = None,
    show_tap_drill: bool = False,
    elbow_dx: float = 15.0,
    elbow_dy: float = -12.0,
    *,
    anchor: Any = None,
) -> ThreadCallout:
    """Add a standard engineering thread callout at (model_x, model_y) or an anchor."""
    target = anchor if anchor is not None else self.to_sheet_coords(model_x, model_y)
    tc = ThreadCallout(
        center=target,
        thread=thread,
        depth=depth,
        class_fit=class_fit,
        quantity=quantity,
        show_tap_drill=show_tap_drill,
        elbow_offset=(elbow_dx, elbow_dy),
        view=self,
    )
    return tc

cosmetic_thread(target=None, thread=None, nominal_diameter=None, minor_diameter=None, thread_type='internal', depth=None, model_x=None, model_y=None, view_mode=None)

Add an ISO 6410-1 cosmetic thread representation to this view.

Source code in src/build123d_techdraw/core/view.py
def cosmetic_thread(
    self,
    target: Any = None,
    thread: str | Any | None = None,
    nominal_diameter: float | None = None,
    minor_diameter: float | None = None,
    thread_type: str = "internal",
    depth: float | None = None,
    model_x: float | None = None,
    model_y: float | None = None,
    view_mode: str | None = None,
) -> CosmeticThread:
    """Add an ISO 6410-1 cosmetic thread representation to this view."""
    center_pt = (
        self.to_sheet_coords(model_x, model_y)
        if model_x is not None and model_y is not None
        else None
    )
    return CosmeticThread(
        target=target,
        thread=thread,
        nominal_diameter=nominal_diameter,
        minor_diameter=minor_diameter,
        thread_type=thread_type,
        depth=depth,
        center=center_pt,
        view_mode=view_mode,
        view=self,
    )

auto_cosmetic_threads(*, threaded_diameters=None, infer_threads=False, tolerance=0.08)

Automatically generate ISO 6410-1 CosmeticThread annotations from recognized holes.

Source code in src/build123d_techdraw/core/view.py
def auto_cosmetic_threads(
    self,
    *,
    threaded_diameters: dict[float, str] | None = None,
    infer_threads: bool = False,
    tolerance: float = 0.08,
) -> list[CosmeticThread]:
    """Automatically generate ISO 6410-1 CosmeticThread annotations from recognized holes."""
    return auto_cosmetic_threads(
        self,
        threaded_diameters=threaded_diameters,
        infer_threads=infer_threads,
        tolerance=tolerance,
    )

dim_half_diameter(target=None, axis_point=None, diameter=None, orientation='auto', side='auto', offset=0.0, dim_pos=None, past_centerline=5.0, text=None, tolerance=None, prefix='⌀', suffix='', *, anchor=None)

Add an ISO 129-1 §5.2.3 diametral centerline half-dimension to this view.

Source code in src/build123d_techdraw/core/view.py
def dim_half_diameter(
    self,
    target: Any = None,
    axis_point: Any = None,
    diameter: float | None = None,
    orientation: str = "auto",
    side: str = "auto",
    offset: float = 0.0,
    dim_pos: float | None = None,
    past_centerline: float = 5.0,
    text: str | None = None,
    tolerance: str | Tolerance | None = None,
    prefix: str = "⌀",
    suffix: str = "",
    *,
    anchor: Any = None,
) -> HalfDiameterDimension:
    """Add an ISO 129-1 §5.2.3 diametral centerline half-dimension to this view."""
    dim = HalfDiameterDimension(
        target=target,
        axis_point=axis_point,
        diameter=diameter,
        orientation=orientation,
        side=side,
        offset=offset,
        dim_pos=dim_pos,
        past_centerline=past_centerline,
        text=text,
        tolerance=tolerance,
        prefix=prefix,
        suffix=suffix,
        view=self,
        anchor=anchor,
    )
    self.add(dim)
    return dim

undercut_callout(target=None, spec='E 0.8x0.3', roughness=None, quantity=None, include_standard=True, elbow_dx=15.0, elbow_dy=-12.0, *, anchor=None)

Add a DIN 509 relief undercut callout to this view.

Source code in src/build123d_techdraw/core/view.py
def undercut_callout(
    self,
    target: Any = None,
    spec: Any = "E 0.8x0.3",
    roughness: str | None = None,
    quantity: int | None = None,
    include_standard: bool = True,
    elbow_dx: float = 15.0,
    elbow_dy: float = -12.0,
    *,
    anchor: Any = None,
) -> UndercutCallout:
    """Add a DIN 509 relief undercut callout to this view."""
    uc = UndercutCallout(
        target=target,
        spec=spec,
        roughness=roughness,
        quantity=quantity,
        include_standard=include_standard,
        elbow_offset=(elbow_dx, elbow_dy),
        view=self,
        anchor=anchor,
    )
    return uc

auto_dimension_turned(shape=None, *, half_diameters=True, include_centerline=True, include_diameters=True, include_lengths=True, include_chamfers=True, include_undercuts=True, tolerance=None)

Automatically dimension a turned/cylindrical view using ISO lathe conventions.

Source code in src/build123d_techdraw/core/view.py
def auto_dimension_turned(
    self,
    shape: Any | None = None,
    *,
    half_diameters: bool = True,
    include_centerline: bool = True,
    include_diameters: bool = True,
    include_lengths: bool = True,
    include_chamfers: bool = True,
    include_undercuts: bool = True,
    tolerance: str | None = None,
) -> list[Annotation]:
    """Automatically dimension a turned/cylindrical view using ISO lathe conventions."""
    from build123d_techdraw.layout.turned import auto_dimension_turned_view

    return auto_dimension_turned_view(
        self,
        shape=shape,
        half_diameters=half_diameters,
        include_centerline=include_centerline,
        include_diameters=include_diameters,
        include_lengths=include_lengths,
        include_chamfers=include_chamfers,
        include_undercuts=include_undercuts,
        tolerance=tolerance,
    )

add_bend_annotations(*, include_tag=True, include_allowance=False, show_bend_extents=False, label_mode='auto')

Attach BendLineAnnotation items for every bend on this flat pattern view.

Source code in src/build123d_techdraw/core/view.py
def add_bend_annotations(
    self,
    *,
    include_tag: bool = True,
    include_allowance: bool = False,
    show_bend_extents: bool = False,
    label_mode: Literal["auto", "inline", "leader"] = "auto",
) -> list[BendLineAnnotation]:
    """Attach ``BendLineAnnotation`` items for every bend on this flat pattern view."""
    from build123d_techdraw.annotations.sheet_metal import BendLineAnnotation

    if self.flat_pattern is None:
        return []
    created: list[BendLineAnnotation] = []
    for bend in self.flat_pattern.bends:
        ann = BendLineAnnotation(
            bend,
            include_tag=include_tag,
            include_allowance=include_allowance,
            show_bend_extents=show_bend_extents,
            label_mode=label_mode,
            view=self,
        )
        created.append(ann)
    return created

add_punch_markers(*, show_tag=True, show_callout=False)

Attach PunchMarker items for every punch on this flat pattern view.

Source code in src/build123d_techdraw/core/view.py
def add_punch_markers(
    self,
    *,
    show_tag: bool = True,
    show_callout: bool = False,
) -> list[PunchMarker]:
    """Attach ``PunchMarker`` items for every punch on this flat pattern view."""
    from build123d_techdraw.annotations.sheet_metal import PunchMarker

    if self.flat_pattern is None:
        return []
    created: list[PunchMarker] = []
    for punch in self.flat_pattern.punches:
        ann = PunchMarker(
            punch,
            show_tag=show_tag,
            show_callout=show_callout,
            view=self,
        )
        created.append(ann)
    return created

auto_dimension_flat_pattern(*, include_overall=True, include_bend_stations=True, include_punch_dims=False, tolerance=None)

Auto-dimension this flat pattern view with overall blank and bend-station dims.

Source code in src/build123d_techdraw/core/view.py
def auto_dimension_flat_pattern(
    self,
    *,
    include_overall: bool = True,
    include_bend_stations: bool = True,
    include_punch_dims: bool = False,
    tolerance: str | None = None,
) -> list[Annotation]:
    """Auto-dimension this flat pattern view with overall blank and bend-station dims."""
    from build123d_techdraw.layout.sheet_metal import auto_dimension_flat_pattern_view

    return auto_dimension_flat_pattern_view(
        self,
        flat_pattern=self.flat_pattern,
        include_overall=include_overall,
        include_bend_stations=include_bend_stations,
        include_punch_dims=include_punch_dims,
        tolerance=tolerance,
    )

ViewType

Bases: Enum

Standard technical drawing view types and projections.

Source code in src/build123d_techdraw/core/view.py
class ViewType(Enum):
    """Standard technical drawing view types and projections."""

    FRONT = "front"
    TOP = "top"
    RIGHT = "right"
    LEFT = "left"
    REAR = "rear"
    BOTTOM = "bottom"
    ISOMETRIC = "isometric"
    ISOMETRIC_LEFT = "isometric_left"
    ISOMETRIC_REAR = "isometric_rear"
    SECTION = "section"
    DETAIL = "detail"
    AUXILIARY = "auxiliary"
    FLAT_PATTERN = "flat_pattern"

build123d_techdraw.core.title_block

ISO 7200 title blocks, BOM tables, and revision tables.

TitleBlockInfo dataclass

Metadata fields for ISO 7200 compliant title blocks.

Source code in src/build123d_techdraw/core/title_block.py
@dataclass
class TitleBlockInfo:
    """Metadata fields for ISO 7200 compliant title blocks."""

    drawing_title: str
    drawing_no: str
    sheet_no: str = "1 OF 1"
    scale: str = "1:1"
    rev: str = "REV A"
    date: str = "2026-11-06"
    material: str = "SEE NOTES"
    finish: str = "STANDARD"
    author: str = "ENG / CAD"
    project: str = "MECHANICAL PROJECT"
    status: str = "APPROVED"
    units: str = "METRIC (mm)"
    third_angle: bool = False
    subtitle: str | None = None
    total_sheets: str | None = None
    fields: dict[str, str] = field(default_factory=dict)

    @property
    def title(self) -> str:
        return self.drawing_title

    @title.setter
    def title(self, value: str) -> None:
        self.drawing_title = value

    def __post_init__(self) -> None:
        if self.fields:
            self.apply_custom_fields(self.fields)

    def apply_custom_fields(self, custom_fields: dict[str, str]) -> None:
        """Merge custom metadata key-values and sync any standard ISO 7200 fields."""
        for k, v in custom_fields.items():
            str_k = str(k).strip()
            str_v = str(v)
            self.fields[str_k] = str_v
            norm_k = str_k.upper()
            if norm_k in _STANDARD_FIELD_MAP:
                self._set_standard_field(_STANDARD_FIELD_MAP[norm_k], str_v)

    def _set_standard_field(self, name: str, value: str) -> None:
        """Assign one of the built-in title block cells named in ``_STANDARD_FIELD_MAP``."""
        match name:
            case "project":
                self.project = value
            case "drawing_title":
                self.drawing_title = value
            case "subtitle":
                self.subtitle = value
            case "drawing_no":
                self.drawing_no = value
            case "rev":
                self.rev = value
            case "material":
                self.material = value
            case "finish":
                self.finish = value
            case "scale":
                self.scale = value
            case "sheet_no":
                self.sheet_no = value
            case "total_sheets":
                self.total_sheets = value
            case "date":
                self.date = value
            case "author":
                self.author = value
            case "status":
                self.status = value
            case "units":
                self.units = value
            case _:
                raise KeyError(name)

    @property
    def extra_fields(self) -> list[tuple[str, str]]:
        """Return custom fields that do not map to built-in title block cells."""
        return [
            (k, v) for k, v in self.fields.items() if k.strip().upper() not in _STANDARD_FIELD_MAP
        ]

extra_fields property

Return custom fields that do not map to built-in title block cells.

apply_custom_fields(custom_fields)

Merge custom metadata key-values and sync any standard ISO 7200 fields.

Source code in src/build123d_techdraw/core/title_block.py
def apply_custom_fields(self, custom_fields: dict[str, str]) -> None:
    """Merge custom metadata key-values and sync any standard ISO 7200 fields."""
    for k, v in custom_fields.items():
        str_k = str(k).strip()
        str_v = str(v)
        self.fields[str_k] = str_v
        norm_k = str_k.upper()
        if norm_k in _STANDARD_FIELD_MAP:
            self._set_standard_field(_STANDARD_FIELD_MAP[norm_k], str_v)

BOMItem dataclass

Bill of Materials table row item.

Source code in src/build123d_techdraw/core/title_block.py
@dataclass
class BOMItem:
    """Bill of Materials table row item."""

    item_no: int
    qty: int
    part_no: str
    description: str
    material: str

RevisionEntry dataclass

Drawing revision history entry.

Source code in src/build123d_techdraw/core/title_block.py
@dataclass
class RevisionEntry:
    """Drawing revision history entry."""

    rev: str
    description: str
    date: str
    approved_by: str

build123d_techdraw.core.template

Custom corporate title block and sheet template engine (SVG & DXF).

SheetTemplate

Bases: SheetDirective

Reusable corporate SVG or DXF drawing sheet / title block template.

Supports both full-sheet templates (TemplateMode.SHEET, replacing the built-in ISO 5457 border and ISO 7200 title block) and standalone title-block templates (TemplateMode.TITLE_BLOCK, anchored inside the sheet's standard border).

Source code in src/build123d_techdraw/core/template.py
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
class SheetTemplate(SheetDirective):
    """Reusable corporate SVG or DXF drawing sheet / title block template.

    Supports both full-sheet templates (``TemplateMode.SHEET``, replacing the built-in
    ISO 5457 border and ISO 7200 title block) and standalone title-block templates
    (``TemplateMode.TITLE_BLOCK``, anchored inside the sheet's standard border).
    """

    def __init__(
        self,
        *,
        source_format: Literal["svg", "dxf"],
        mode: TemplateMode,
        width_mm: float,
        height_mm: float,
        viewbox: tuple[float, float, float, float],
        root: ET.Element,
        defs_children: list[ET.Element],
        id_prefix: str,
        scope_class: str,
        detected_placeholders: tuple[str, ...],
        inline_defaults: dict[str, str],
        detected_tb_bbox_mm: BBox2D | None,
        anchor: AnchorMode = "bottom_right",
        position: tuple[float, float] | None = None,
        offset: tuple[float, float] = (0.0, 0.0),
        scale: float = 1.0,
        fit_mode: FitMode = "fit",
        theme_adapt: bool = True,
        missing_placeholder: MissingBehavior = "empty",
        defaults: Mapping[str, str] | None = None,
        title_block_bbox_mm: BBox2D | None = None,
        margins: tuple[float, float, float, float] | None = None,
        show_revision_table: bool | None = None,
    ) -> None:
        if width_mm <= 0.0 or height_mm <= 0.0:
            raise ValueError(
                f"Template dimensions must be positive, got ({width_mm}, {height_mm})."
            )
        if scale <= 0.0:
            raise ValueError(f"Template scale must be positive, got {scale}.")
        if anchor not in ("bottom_right", "bottom_left", "top_right", "top_left"):
            raise ValueError(f"Invalid anchor {anchor!r}.")
        if fit_mode not in ("fit", "stretch", "exact"):
            raise ValueError(f"Invalid fit_mode {fit_mode!r}.")
        if missing_placeholder not in ("empty", "keep", "error"):
            raise ValueError(f"Invalid missing_placeholder {missing_placeholder!r}.")

        self.source_format: Literal["svg", "dxf"] = source_format
        self.mode: TemplateMode = mode
        self.width_mm: float = float(width_mm)
        self.height_mm: float = float(height_mm)
        self.viewbox: tuple[float, float, float, float] = viewbox
        self.anchor: AnchorMode = anchor
        self.position: tuple[float, float] | None = (
            (float(position[0]), float(position[1])) if position is not None else None
        )
        self.offset: tuple[float, float] = (float(offset[0]), float(offset[1]))
        self.scale: float = float(scale)
        self.fit_mode: FitMode = fit_mode
        self.theme_adapt: bool = bool(theme_adapt)
        self.missing_placeholder: MissingBehavior = missing_placeholder
        self.defaults: dict[str, str] = {str(k): str(v) for k, v in (defaults or {}).items()}
        self.title_block_bbox_mm: BBox2D | None = title_block_bbox_mm
        self.margins: tuple[float, float, float, float] | None = margins
        self.show_revision_table: bool | None = show_revision_table

        self._root: ET.Element = root
        self._defs_children: list[ET.Element] = defs_children
        self._id_prefix: str = id_prefix
        self._scope_class: str = scope_class
        self._detected_placeholders: tuple[str, ...] = detected_placeholders
        self._inline_defaults: dict[str, str] = inline_defaults
        self._detected_tb_bbox_mm: BBox2D | None = detected_tb_bbox_mm

    @classmethod
    def from_file(
        cls,
        path: str | os.PathLike[str],
        *,
        mode: TemplateMode | str = "auto",
        anchor: AnchorMode = "bottom_right",
        position: tuple[float, float] | None = None,
        offset: tuple[float, float] = (0.0, 0.0),
        scale: float = 1.0,
        fit_mode: FitMode = "fit",
        theme_adapt: bool = True,
        missing_placeholder: MissingBehavior = "empty",
        defaults: Mapping[str, str] | None = None,
        title_block_bbox_mm: BBox2D | None = None,
        margins: tuple[float, float, float, float] | None = None,
        show_revision_table: bool | None = None,
        layout: str = "auto",
        unit_scale: float | None = None,
        bind_dxf_attributes: bool = True,
    ) -> SheetTemplate:
        """Load an SVG or DXF template file based on its file extension."""
        p = Path(path)
        if not p.is_file():
            raise FileNotFoundError(f"Template file not found: {p}")
        suffix = p.suffix.lower()
        if suffix == ".svg":
            return cls.from_svg(
                p,
                mode=mode,
                anchor=anchor,
                position=position,
                offset=offset,
                scale=scale,
                fit_mode=fit_mode,
                theme_adapt=theme_adapt,
                missing_placeholder=missing_placeholder,
                defaults=defaults,
                title_block_bbox_mm=title_block_bbox_mm,
                margins=margins,
                show_revision_table=show_revision_table,
            )
        if suffix == ".dxf":
            return cls.from_dxf(
                p,
                mode=mode,
                layout=layout,
                unit_scale=unit_scale,
                bind_dxf_attributes=bind_dxf_attributes,
                anchor=anchor,
                position=position,
                offset=offset,
                scale=scale,
                fit_mode=fit_mode,
                theme_adapt=theme_adapt,
                missing_placeholder=missing_placeholder,
                defaults=defaults,
                title_block_bbox_mm=title_block_bbox_mm,
                margins=margins,
                show_revision_table=show_revision_table,
            )
        raise ValueError(f"Unsupported template extension {p.suffix!r}; expected '.svg' or '.dxf'.")

    @classmethod
    def from_svg(
        cls,
        source: str | os.PathLike[str],
        *,
        mode: TemplateMode | str = "auto",
        anchor: AnchorMode = "bottom_right",
        position: tuple[float, float] | None = None,
        offset: tuple[float, float] = (0.0, 0.0),
        scale: float = 1.0,
        fit_mode: FitMode = "fit",
        theme_adapt: bool = True,
        missing_placeholder: MissingBehavior = "empty",
        defaults: Mapping[str, str] | None = None,
        title_block_bbox_mm: BBox2D | None = None,
        margins: tuple[float, float, float, float] | None = None,
        show_revision_table: bool | None = None,
    ) -> SheetTemplate:
        """Create a template from an SVG file path or raw SVG XML string."""
        if isinstance(source, os.PathLike):
            p = Path(source)
            if not p.is_file():
                raise FileNotFoundError(f"SVG template file not found: {p}")
            svg_xml = p.read_text(encoding="utf-8")
        else:
            if "<svg" not in source.lower() and not os.path.isfile(source):
                raise FileNotFoundError(f"SVG template file not found: {source}")
            svg_xml = Path(source).read_text(encoding="utf-8") if os.path.isfile(source) else source

        src_root = ET.fromstring(svg_xml)
        return cls._build_from_svg_root(
            src_root,
            source_format="svg",
            hash_seed=svg_xml.encode("utf-8"),
            mode=mode,
            anchor=anchor,
            position=position,
            offset=offset,
            scale=scale,
            fit_mode=fit_mode,
            theme_adapt=theme_adapt,
            missing_placeholder=missing_placeholder,
            defaults=defaults,
            title_block_bbox_mm=title_block_bbox_mm,
            margins=margins,
            show_revision_table=show_revision_table,
        )

    @classmethod
    def from_dxf(
        cls,
        source: str | os.PathLike[str] | Drawing,
        *,
        mode: TemplateMode | str = "auto",
        layout: str = "auto",
        unit_scale: float | None = None,
        bind_dxf_attributes: bool = True,
        anchor: AnchorMode = "bottom_right",
        position: tuple[float, float] | None = None,
        offset: tuple[float, float] = (0.0, 0.0),
        scale: float = 1.0,
        fit_mode: FitMode = "fit",
        theme_adapt: bool = True,
        missing_placeholder: MissingBehavior = "empty",
        defaults: Mapping[str, str] | None = None,
        title_block_bbox_mm: BBox2D | None = None,
        margins: tuple[float, float, float, float] | None = None,
        show_revision_table: bool | None = None,
    ) -> SheetTemplate:
        """Create a template from a DXF file path or an in-memory ``ezdxf`` ``Drawing``."""
        if isinstance(source, Drawing):
            doc = source
        else:
            p = Path(source)
            if not p.is_file():
                raise FileNotFoundError(f"DXF template file not found: {p}")
            doc = dxf_readfile(str(p))

        if isinstance(mode, str) and mode.strip().lower() == "auto":
            target_mode: TemplateMode | Literal["auto"] = "auto"
        else:
            target_mode = TemplateMode.coerce(mode)

        svg_root, _, _ = _dxf_to_svg_element_tree(
            doc,
            layout=layout,
            unit_scale=unit_scale,
            bind_dxf_attributes=bind_dxf_attributes,
            target_mode=target_mode,
        )
        seed = ET.tostring(svg_root, encoding="utf-8")
        return cls._build_from_svg_root(
            svg_root,
            source_format="dxf",
            hash_seed=seed,
            mode=target_mode,
            anchor=anchor,
            position=position,
            offset=offset,
            scale=scale,
            fit_mode=fit_mode,
            theme_adapt=theme_adapt,
            missing_placeholder=missing_placeholder,
            defaults=defaults,
            title_block_bbox_mm=title_block_bbox_mm,
            margins=margins,
            show_revision_table=show_revision_table,
        )

    @classmethod
    def _build_from_svg_root(
        cls,
        src_root: ET.Element,
        *,
        source_format: Literal["svg", "dxf"],
        hash_seed: bytes,
        mode: TemplateMode | str,
        anchor: AnchorMode,
        position: tuple[float, float] | None,
        offset: tuple[float, float],
        scale: float,
        fit_mode: FitMode,
        theme_adapt: bool,
        missing_placeholder: MissingBehavior,
        defaults: Mapping[str, str] | None,
        title_block_bbox_mm: BBox2D | None,
        margins: tuple[float, float, float, float] | None,
        show_revision_table: bool | None,
    ) -> SheetTemplate:
        if _local_name(src_root.tag).lower() != "svg":
            raise ValueError(f"Expected root <svg> element, got <{_local_name(src_root.tag)}>.")

        vb = _parse_viewbox(src_root.attrib.get("viewBox"))
        w_mm = _parse_length_mm(src_root.attrib.get("width"))
        h_mm = _parse_length_mm(src_root.attrib.get("height"))

        if w_mm is not None and h_mm is not None:
            width_mm, height_mm = w_mm, h_mm
            if vb is None:
                vb = (0.0, 0.0, width_mm, height_mm)
        elif vb is not None:
            width_mm, height_mm = vb[2], vb[3]
        else:
            raise ValueError("SVG template must define positive width/height or viewBox.")

        if width_mm <= 0.0 or height_mm <= 0.0:
            raise ValueError(
                f"SVG template dimensions must be positive, got ({width_mm}, {height_mm})."
            )

        if isinstance(mode, str) and mode.strip().lower() == "auto":
            resolved_mode = (
                TemplateMode.SHEET
                if width_mm >= 200.0 and height_mm >= 180.0
                else TemplateMode.TITLE_BLOCK
            )
        else:
            resolved_mode = TemplateMode.coerce(mode)

        digest = hashlib.sha256(hash_seed).hexdigest()[:8]
        id_prefix = f"tpl_{digest}_"
        scope_class = f"tpl-scope-{digest}"

        clean_root, defs_children = _sanitize_svg_tree(
            src_root,
            scope_class=scope_class,
            id_prefix=id_prefix,
            theme_adapt=theme_adapt,
            mode=resolved_mode,
            vb_w=vb[2],
            vb_h=vb[3],
        )
        placeholders, inline_defaults = _scan_placeholders(clean_root)

        detected_tb_bb: BBox2D | None = None
        if resolved_mode is TemplateMode.SHEET:
            detected_tb_bb = _detect_sheet_tb_bbox_mm(
                clean_root, vb[0], vb[1], vb[2], vb[3], width_mm, height_mm
            )

        return cls(
            source_format=source_format,
            mode=resolved_mode,
            width_mm=width_mm,
            height_mm=height_mm,
            viewbox=vb,
            root=clean_root,
            defs_children=defs_children,
            id_prefix=id_prefix,
            scope_class=scope_class,
            detected_placeholders=placeholders,
            inline_defaults=inline_defaults,
            detected_tb_bbox_mm=detected_tb_bb,
            anchor=anchor,
            position=position,
            offset=offset,
            scale=scale,
            fit_mode=fit_mode,
            theme_adapt=theme_adapt,
            missing_placeholder=missing_placeholder,
            defaults=defaults,
            title_block_bbox_mm=title_block_bbox_mm,
            margins=margins,
            show_revision_table=show_revision_table,
        )

    def with_defaults(
        self,
        fields: Mapping[str, str] | None = None,
        **kwargs: str,
    ) -> SheetTemplate:
        """Return a copy of this template with additional/overridden default field values."""
        merged = dict(self.defaults)
        if fields:
            for k, v in fields.items():
                merged[str(k)] = str(v)
        for k, v in kwargs.items():
            merged[str(k)] = str(v)
        return SheetTemplate(
            source_format=self.source_format,
            mode=self.mode,
            width_mm=self.width_mm,
            height_mm=self.height_mm,
            viewbox=self.viewbox,
            root=copy.deepcopy(self._root),
            defs_children=[copy.deepcopy(d) for d in self._defs_children],
            id_prefix=self._id_prefix,
            scope_class=self._scope_class,
            detected_placeholders=self._detected_placeholders,
            inline_defaults=dict(self._inline_defaults),
            detected_tb_bbox_mm=self._detected_tb_bbox_mm,
            anchor=self.anchor,
            position=self.position,
            offset=self.offset,
            scale=self.scale,
            fit_mode=self.fit_mode,
            theme_adapt=self.theme_adapt,
            missing_placeholder=self.missing_placeholder,
            defaults=merged,
            title_block_bbox_mm=self.title_block_bbox_mm,
            margins=self.margins,
            show_revision_table=self.show_revision_table,
        )

    @property
    def placeholders(self) -> tuple[str, ...]:
        """Normalized placeholder names discovered in this template."""
        return self._detected_placeholders

    def _apply_to_sheet(self, sheet: DrawingSheet) -> None:
        sheet.set_template(self)

    def _build_field_lookup(
        self,
        info: TitleBlockInfo,
        *,
        sheet: DrawingSheet | None = None,
        extra_fields: Mapping[str, str] | None = None,
        include_inline_defaults: bool = True,
    ) -> dict[str, str]:
        """Resolve normalized placeholder keys according to template precedence."""
        resolved: dict[str, str] = {}

        # 6. Inline ${KEY:-default} / FreeCAD initial text
        if include_inline_defaults:
            for k, v in self._inline_defaults.items():
                resolved[k] = v

        # Compute sheet display values
        if info.total_sheets and "OF" not in info.sheet_no.upper():
            sheet_display = f"{info.sheet_no} OF {info.total_sheets}"
        else:
            sheet_display = info.sheet_no

        if "OF" in sheet_display.upper():
            parts = [p.strip() for p in re.split(r"\bOF\b", sheet_display, flags=re.IGNORECASE)]
            sheet_num_val = parts[0] if parts else sheet_display
            total_sheets_val = info.total_sheets or (parts[-1] if len(parts) > 1 else "1")
        else:
            sheet_num_val = sheet_display.strip()
            total_sheets_val = info.total_sheets or "1"

        proj_str = "THIRD ANGLE" if info.third_angle else "FIRST ANGLE"
        sheet_size_str = ""
        if sheet is not None:
            ss = sheet.sheet_size
            if abs(sheet.width_mm - ss.width) < 0.5 and abs(sheet.height_mm - ss.height) < 0.5:
                sheet_size_str = ss.name.split("_", 1)[0]
            else:
                sheet_size_str = f"{sheet.width_mm:g}x{sheet.height_mm:g}mm"

        # 5. Built-in defaults from TitleBlockInfo
        builtin_values: dict[str, str] = {
            "PROJECT": info.project,
            "TITLE": info.drawing_title,
            "DRAWING_TITLE": info.drawing_title,
            "SUBTITLE": info.subtitle or "",
            "DRAWING_NO": info.drawing_no,
            "DRAWING_NUMBER": info.drawing_no,
            "DWG_NO": info.drawing_no,
            "REV": info.rev,
            "REVISION": info.rev,
            "MATERIAL": info.material,
            "FINISH": info.finish,
            "SCALE": info.scale,
            "SHEET": sheet_display,
            "SHEET_NO": sheet_num_val,
            "SHEET_NUM": sheet_num_val,
            "SHEET_NUMBER": sheet_num_val,
            "TOTAL_SHEETS": total_sheets_val,
            "SHEET_COUNT": total_sheets_val,
            "NUM_SHEETS": total_sheets_val,
            "DATE": info.date,
            "DRAWN_BY": info.author,
            "AUTHOR": info.author,
            "STATUS": info.status,
            "UNITS": info.units,
            "PROJECTION": proj_str,
            "PROJECTION_METHOD": proj_str,
        }
        if sheet_size_str:
            builtin_values["SHEET_SIZE"] = sheet_size_str

        for k, v in builtin_values.items():
            resolved[k] = v

        def _set_aliased_field(raw_key: str, raw_val: str) -> None:
            norm_k = _normalize_key(raw_key)
            str_v = str(raw_val)
            resolved[norm_k] = str_v
            mapped_attr = _NORM_STANDARD_FIELD_MAP.get(norm_k)
            if mapped_attr is not None:
                for alias_k, alias_attr in _NORM_STANDARD_FIELD_MAP.items():
                    if alias_attr == mapped_attr:
                        resolved[alias_k] = str_v

        # 4. Template corporate defaults (override TitleBlockInfo built-in defaults)
        for k, v in self.defaults.items():
            _set_aliased_field(k, v)

        # 3. Explicit (non-default) TitleBlockInfo attributes
        explicit_attrs: list[tuple[str, str]] = [
            ("drawing_title", info.drawing_title),
            ("drawing_no", info.drawing_no),
        ]
        for attr_name in (
            "project",
            "subtitle",
            "rev",
            "material",
            "finish",
            "scale",
            "date",
            "author",
            "status",
            "units",
        ):
            val = getattr(info, attr_name)
            if val is not None and val != _TB_FIELD_DEFAULTS.get(attr_name):
                explicit_attrs.append((attr_name, str(val)))

        for attr_name, val in explicit_attrs:
            for alias_k, alias_attr in _NORM_STANDARD_FIELD_MAP.items():
                if alias_attr == attr_name:
                    resolved[alias_k] = val

        if info.sheet_no != _TB_FIELD_DEFAULTS.get("sheet_no") or info.total_sheets is not None:
            resolved["SHEET"] = sheet_display
            resolved["SHEET_NO"] = sheet_num_val
            resolved["SHEET_NUM"] = sheet_num_val
            resolved["SHEET_NUMBER"] = sheet_num_val
            resolved["TOTAL_SHEETS"] = total_sheets_val
            resolved["SHEET_COUNT"] = total_sheets_val
            resolved["NUM_SHEETS"] = total_sheets_val

        if info.third_angle:
            resolved["PROJECTION"] = "THIRD ANGLE"
            resolved["PROJECTION_METHOD"] = "THIRD ANGLE"

        # 2. TitleBlockInfo.fields (case/punctuation-insensitive)
        for k, v in info.fields.items():
            _set_aliased_field(k, v)

        # 1. Explicit per-render overrides
        if extra_fields:
            for k, v in extra_fields.items():
                _set_aliased_field(k, v)

        return resolved

    def resolve_fields(
        self,
        info: TitleBlockInfo,
        *,
        sheet: DrawingSheet | None = None,
        extra_fields: Mapping[str, str] | None = None,
    ) -> dict[str, str]:
        """Return resolved placeholder key -> value mapping for all placeholders in the template."""
        lookup = self._build_field_lookup(info, sheet=sheet, extra_fields=extra_fields)
        return {k: lookup[k] for k in self._detected_placeholders if k in lookup}

    def missing_fields(
        self,
        info: TitleBlockInfo,
        *,
        sheet: DrawingSheet | None = None,
        extra_fields: Mapping[str, str] | None = None,
    ) -> list[str]:
        """Return placeholder keys that have no bound value or inline default."""
        lookup = self._build_field_lookup(info, sheet=sheet, extra_fields=extra_fields)
        return [k for k in self._detected_placeholders if k not in lookup]

    def placement_transform(self, sheet: DrawingSheet) -> tuple[float, float, float, float]:
        """Return ``(tx, ty, sx, sy)`` mapping template ``viewBox`` units into sheet mm."""
        vb_x, vb_y, vb_w, vb_h = self.viewbox
        if self.mode is TemplateMode.SHEET:
            if self.fit_mode == "exact":
                sx = self.width_mm / vb_w
                sy = self.height_mm / vb_h
                tx = -vb_x * sx
                ty = -vb_y * sy
            elif self.fit_mode == "stretch":
                sx = sheet.width_mm / vb_w
                sy = sheet.height_mm / vb_h
                tx = -vb_x * sx
                ty = -vb_y * sy
            else:  # "fit"
                fit_s = min(sheet.width_mm / self.width_mm, sheet.height_mm / self.height_mm)
                rw = self.width_mm * fit_s
                rh = self.height_mm * fit_s
                sx = rw / vb_w
                sy = rh / vb_h
                tx = (sheet.width_mm - rw) * 0.5 - vb_x * sx
                ty = (sheet.height_mm - rh) * 0.5 - vb_y * sy
            return (tx, ty, sx, sy)

        # TITLE_BLOCK mode
        rw = self.width_mm * self.scale
        rh = self.height_mm * self.scale
        sx = rw / vb_w
        sy = rh / vb_h
        if self.position is not None:
            bx, by = self.position
        else:
            if "right" in self.anchor:
                bx = sheet.width_mm - sheet.right_margin - rw
            else:
                bx = sheet.left_margin
            if "bottom" in self.anchor:
                by = sheet.height_mm - sheet.bottom_margin - rh
            else:
                by = sheet.top_margin
        bx += self.offset[0]
        by += self.offset[1]
        return (bx - vb_x * sx, by - vb_y * sy, sx, sy)

    def title_block_bbox(self, sheet: DrawingSheet) -> BBox2D:
        """Return the rendered title block bounding box in sheet mm ``(min_x, min_y, max_x, max_y)``."""
        tx, ty, sx, sy = self.placement_transform(sheet)
        vb_x, vb_y, vb_w, vb_h = self.viewbox
        if self.mode is TemplateMode.TITLE_BLOCK:
            x0 = tx + vb_x * sx
            y0 = ty + vb_y * sy
            return (x0, y0, x0 + vb_w * sx, y0 + vb_h * sy)

        local_mm = self.title_block_bbox_mm or self._detected_tb_bbox_mm
        if local_mm is None:
            return (
                max(0.0, sheet.width_mm - sheet.right_margin - 180.0),
                max(0.0, sheet.height_mm - sheet.bottom_margin - 40.0),
                sheet.width_mm - sheet.right_margin,
                sheet.height_mm - sheet.bottom_margin,
            )
        # Convert template mm -> viewBox units -> sheet mm
        u_per_mm_x = vb_w / self.width_mm
        u_per_mm_y = vb_h / self.height_mm
        return (
            tx + (vb_x + local_mm[0] * u_per_mm_x) * sx,
            ty + (vb_y + local_mm[1] * u_per_mm_y) * sy,
            tx + (vb_x + local_mm[2] * u_per_mm_x) * sx,
            ty + (vb_y + local_mm[3] * u_per_mm_y) * sy,
        )

    def _substitute_placeholders_and_slots(
        self,
        root: ET.Element,
        info: TitleBlockInfo,
        lookup: Mapping[str, str],
    ) -> list[str]:
        """Substitute placeholders, FreeCAD editables, and projection symbol slots on cloned tree."""
        missing_keys: list[str] = []

        def _resolve_match(m: re.Match[str]) -> str:
            norm_k = _normalize_key(m.group(1))
            if norm_k in lookup:
                return lookup[norm_k]
            if m.group(2) is not None:
                return m.group(2)
            if norm_k not in missing_keys:
                missing_keys.append(norm_k)
            if self.missing_placeholder == "keep":
                return m.group(0)
            return ""

        def _apply_multiline_text(el: ET.Element, value: str, *, anchor_x: str) -> None:
            lines = value.splitlines()
            if len(lines) <= 1:
                el.text = value
                return
            el.text = lines[0]
            fs_raw = el.attrib.get("font-size") or _parse_inline_style(el.attrib.get("style")).get(
                "font-size"
            )
            fs = _parse_length_mm(fs_raw) or 3.0
            dy = fs * 1.25
            for extra_line in lines[1:]:
                ts = ET.SubElement(el, "tspan", {"x": anchor_x, "dy": f"{dy:.2f}"})
                ts.text = extra_line

        def _replace_projection_slot(parent: ET.Element, idx: int, slot_el: ET.Element) -> None:
            tag = _local_name(slot_el.tag).lower()
            bx = _parse_length_mm(slot_el.attrib.get("x")) or 0.0
            by = _parse_length_mm(slot_el.attrib.get("y")) or 0.0
            bw = _parse_length_mm(slot_el.attrib.get("width"))
            bh = _parse_length_mm(slot_el.attrib.get("height"))

            if tag == "text":
                fs = _parse_length_mm(slot_el.attrib.get("font-size")) or 3.5
                bw = bw or fs * 6.5
                bh = bh or fs * 3.6
                bx = bx - bw * 0.5
                by = by - bh * 0.65
            elif (bw is None or bh is None) and len(slot_el) > 0:
                first = slot_el[0]
                bx = _parse_length_mm(first.attrib.get("x")) or bx
                by = _parse_length_mm(first.attrib.get("y")) or by
                bw = _parse_length_mm(first.attrib.get("width")) or 24.0
                bh = _parse_length_mm(first.attrib.get("height")) or 14.0
            else:
                bw = bw or 24.0
                bh = bh or 14.0

            s = min((bw * 0.85) / 30.0, (bh * 0.85) / 18.0)
            cx = bx + bw * 0.5 + (-3.0 if info.third_angle else 3.0) * s
            cy = by + bh * 0.5
            inner_svg = projection_symbol_elements(
                info.third_angle,
                centerline_dasharray="8,1.5,1.5,1.5",
                centerline_width=0.25,
            )
            group_xml = (
                f'<g class="projection-symbol" transform="translate({cx:.2f}, {cy:.2f}) '
                f'scale({s:.4f})">{inner_svg}</g>'
            )
            parent[idx] = ET.fromstring(group_xml)

        def _walk_replace(parent: ET.Element) -> None:
            for idx, child in enumerate(list(parent)):
                tag = _local_name(child.tag).lower()
                td_role = child.attrib.get("data-techdraw", "").lower()
                fc_key = child.attrib.get("data-freecad-editable")
                full_text = "".join(child.itertext())

                if td_role == "projection_symbol" or (
                    tag == "text"
                    and (
                        full_text.strip().upper() == "${PROJECTION_SYMBOL}"
                        or (fc_key is not None and _normalize_key(fc_key) == "PROJECTION_SYMBOL")
                    )
                ):
                    _replace_projection_slot(parent, idx, child)
                    continue

                if tag == "text":
                    children_tspans = list(child)
                    x_attr = child.attrib.get("x", "0")
                    if fc_key and not _PLACEHOLDER_RE.search(full_text):
                        norm_fc = _normalize_key(fc_key)
                        if norm_fc in lookup:
                            val = lookup[norm_fc]
                        else:
                            if norm_fc not in missing_keys:
                                missing_keys.append(norm_fc)
                            val = full_text if self.missing_placeholder == "keep" else ""
                        if children_tspans:
                            first_ts = children_tspans[0]
                            for extra_ts in children_tspans[1:]:
                                child.remove(extra_ts)
                            _apply_multiline_text(
                                first_ts, val, anchor_x=first_ts.attrib.get("x", x_attr)
                            )
                            child.text = None
                        else:
                            _apply_multiline_text(child, val, anchor_x=x_attr)
                        continue

                    if children_tspans:
                        # Check if a ${...} token was split across multiple <tspan> elements
                        split_match = _PLACEHOLDER_RE.search(full_text) and not any(
                            _PLACEHOLDER_RE.search(ts.text or "") for ts in children_tspans
                        )
                        if split_match:
                            new_full = _PLACEHOLDER_RE.sub(_resolve_match, full_text)
                            first_ts = children_tspans[0]
                            for extra_ts in children_tspans[1:]:
                                extra_ts.text = ""
                                extra_ts.tail = ""
                            child.text = None
                            _apply_multiline_text(
                                first_ts, new_full, anchor_x=first_ts.attrib.get("x", x_attr)
                            )
                        else:
                            if child.text and _PLACEHOLDER_RE.search(child.text):
                                child.text = _PLACEHOLDER_RE.sub(_resolve_match, child.text)
                            for ts in children_tspans:
                                if ts.text and _PLACEHOLDER_RE.search(ts.text):
                                    new_ts = _PLACEHOLDER_RE.sub(_resolve_match, ts.text)
                                    _apply_multiline_text(
                                        ts, new_ts, anchor_x=ts.attrib.get("x", x_attr)
                                    )
                    else:
                        if child.text and _PLACEHOLDER_RE.search(child.text):
                            new_val = _PLACEHOLDER_RE.sub(_resolve_match, child.text)
                            _apply_multiline_text(child, new_val, anchor_x=x_attr)
                    continue

                _walk_replace(child)

        _walk_replace(root)
        return missing_keys

    def render_parts(
        self,
        sheet: DrawingSheet,
        *,
        extra_fields: Mapping[str, str] | None = None,
    ) -> tuple[str, str]:
        """Render scoped ``(defs_svg, body_svg)`` fragments ready to embed in ``sheet.to_svg()``."""
        cloned_root = copy.deepcopy(self._root)
        include_inline = self.missing_placeholder != "error"
        lookup = self._build_field_lookup(
            sheet.title_info,
            sheet=sheet,
            extra_fields=extra_fields,
            include_inline_defaults=include_inline,
        )
        missing_keys = self._substitute_placeholders_and_slots(
            cloned_root, sheet.title_info, lookup
        )
        if self.missing_placeholder == "error" and missing_keys:
            raise KeyError(f"Unbound template placeholders: {', '.join(sorted(set(missing_keys)))}")

        tx, ty, sx, sy = self.placement_transform(sheet)
        role_class = "template-sheet" if self.mode is TemplateMode.SHEET else "template-title-block"
        cloned_root.set("class", f"{role_class} {self._scope_class}".strip())
        if abs(sx - sy) < 1e-6:
            scale_expr = f"scale({sx:.6f})" if abs(sx - 1.0) > 1e-6 else ""
        else:
            scale_expr = f"scale({sx:.6f}, {sy:.6f})"
        tf_parts = [f"translate({tx:.4f}, {ty:.4f})"]
        if scale_expr:
            tf_parts.append(scale_expr)
        cloned_root.set("transform", " ".join(tf_parts))

        defs_svg = "\n    ".join(ET.tostring(d, encoding="unicode") for d in self._defs_children)
        body_svg = ET.tostring(cloned_root, encoding="unicode")
        return defs_svg, body_svg

    def render_svg(
        self,
        sheet: DrawingSheet,
        *,
        extra_fields: Mapping[str, str] | None = None,
    ) -> str:
        """Render a self-contained SVG group containing any scoped defs and the template body."""
        defs_svg, body_svg = self.render_parts(sheet, extra_fields=extra_fields)
        if defs_svg:
            return f"<defs>\n    {defs_svg}\n  </defs>\n  {body_svg}"
        return body_svg

placeholders property

Normalized placeholder names discovered in this template.

from_file(path, *, mode='auto', anchor='bottom_right', position=None, offset=(0.0, 0.0), scale=1.0, fit_mode='fit', theme_adapt=True, missing_placeholder='empty', defaults=None, title_block_bbox_mm=None, margins=None, show_revision_table=None, layout='auto', unit_scale=None, bind_dxf_attributes=True) classmethod

Load an SVG or DXF template file based on its file extension.

Source code in src/build123d_techdraw/core/template.py
@classmethod
def from_file(
    cls,
    path: str | os.PathLike[str],
    *,
    mode: TemplateMode | str = "auto",
    anchor: AnchorMode = "bottom_right",
    position: tuple[float, float] | None = None,
    offset: tuple[float, float] = (0.0, 0.0),
    scale: float = 1.0,
    fit_mode: FitMode = "fit",
    theme_adapt: bool = True,
    missing_placeholder: MissingBehavior = "empty",
    defaults: Mapping[str, str] | None = None,
    title_block_bbox_mm: BBox2D | None = None,
    margins: tuple[float, float, float, float] | None = None,
    show_revision_table: bool | None = None,
    layout: str = "auto",
    unit_scale: float | None = None,
    bind_dxf_attributes: bool = True,
) -> SheetTemplate:
    """Load an SVG or DXF template file based on its file extension."""
    p = Path(path)
    if not p.is_file():
        raise FileNotFoundError(f"Template file not found: {p}")
    suffix = p.suffix.lower()
    if suffix == ".svg":
        return cls.from_svg(
            p,
            mode=mode,
            anchor=anchor,
            position=position,
            offset=offset,
            scale=scale,
            fit_mode=fit_mode,
            theme_adapt=theme_adapt,
            missing_placeholder=missing_placeholder,
            defaults=defaults,
            title_block_bbox_mm=title_block_bbox_mm,
            margins=margins,
            show_revision_table=show_revision_table,
        )
    if suffix == ".dxf":
        return cls.from_dxf(
            p,
            mode=mode,
            layout=layout,
            unit_scale=unit_scale,
            bind_dxf_attributes=bind_dxf_attributes,
            anchor=anchor,
            position=position,
            offset=offset,
            scale=scale,
            fit_mode=fit_mode,
            theme_adapt=theme_adapt,
            missing_placeholder=missing_placeholder,
            defaults=defaults,
            title_block_bbox_mm=title_block_bbox_mm,
            margins=margins,
            show_revision_table=show_revision_table,
        )
    raise ValueError(f"Unsupported template extension {p.suffix!r}; expected '.svg' or '.dxf'.")

from_svg(source, *, mode='auto', anchor='bottom_right', position=None, offset=(0.0, 0.0), scale=1.0, fit_mode='fit', theme_adapt=True, missing_placeholder='empty', defaults=None, title_block_bbox_mm=None, margins=None, show_revision_table=None) classmethod

Create a template from an SVG file path or raw SVG XML string.

Source code in src/build123d_techdraw/core/template.py
@classmethod
def from_svg(
    cls,
    source: str | os.PathLike[str],
    *,
    mode: TemplateMode | str = "auto",
    anchor: AnchorMode = "bottom_right",
    position: tuple[float, float] | None = None,
    offset: tuple[float, float] = (0.0, 0.0),
    scale: float = 1.0,
    fit_mode: FitMode = "fit",
    theme_adapt: bool = True,
    missing_placeholder: MissingBehavior = "empty",
    defaults: Mapping[str, str] | None = None,
    title_block_bbox_mm: BBox2D | None = None,
    margins: tuple[float, float, float, float] | None = None,
    show_revision_table: bool | None = None,
) -> SheetTemplate:
    """Create a template from an SVG file path or raw SVG XML string."""
    if isinstance(source, os.PathLike):
        p = Path(source)
        if not p.is_file():
            raise FileNotFoundError(f"SVG template file not found: {p}")
        svg_xml = p.read_text(encoding="utf-8")
    else:
        if "<svg" not in source.lower() and not os.path.isfile(source):
            raise FileNotFoundError(f"SVG template file not found: {source}")
        svg_xml = Path(source).read_text(encoding="utf-8") if os.path.isfile(source) else source

    src_root = ET.fromstring(svg_xml)
    return cls._build_from_svg_root(
        src_root,
        source_format="svg",
        hash_seed=svg_xml.encode("utf-8"),
        mode=mode,
        anchor=anchor,
        position=position,
        offset=offset,
        scale=scale,
        fit_mode=fit_mode,
        theme_adapt=theme_adapt,
        missing_placeholder=missing_placeholder,
        defaults=defaults,
        title_block_bbox_mm=title_block_bbox_mm,
        margins=margins,
        show_revision_table=show_revision_table,
    )

from_dxf(source, *, mode='auto', layout='auto', unit_scale=None, bind_dxf_attributes=True, anchor='bottom_right', position=None, offset=(0.0, 0.0), scale=1.0, fit_mode='fit', theme_adapt=True, missing_placeholder='empty', defaults=None, title_block_bbox_mm=None, margins=None, show_revision_table=None) classmethod

Create a template from a DXF file path or an in-memory ezdxf Drawing.

Source code in src/build123d_techdraw/core/template.py
@classmethod
def from_dxf(
    cls,
    source: str | os.PathLike[str] | Drawing,
    *,
    mode: TemplateMode | str = "auto",
    layout: str = "auto",
    unit_scale: float | None = None,
    bind_dxf_attributes: bool = True,
    anchor: AnchorMode = "bottom_right",
    position: tuple[float, float] | None = None,
    offset: tuple[float, float] = (0.0, 0.0),
    scale: float = 1.0,
    fit_mode: FitMode = "fit",
    theme_adapt: bool = True,
    missing_placeholder: MissingBehavior = "empty",
    defaults: Mapping[str, str] | None = None,
    title_block_bbox_mm: BBox2D | None = None,
    margins: tuple[float, float, float, float] | None = None,
    show_revision_table: bool | None = None,
) -> SheetTemplate:
    """Create a template from a DXF file path or an in-memory ``ezdxf`` ``Drawing``."""
    if isinstance(source, Drawing):
        doc = source
    else:
        p = Path(source)
        if not p.is_file():
            raise FileNotFoundError(f"DXF template file not found: {p}")
        doc = dxf_readfile(str(p))

    if isinstance(mode, str) and mode.strip().lower() == "auto":
        target_mode: TemplateMode | Literal["auto"] = "auto"
    else:
        target_mode = TemplateMode.coerce(mode)

    svg_root, _, _ = _dxf_to_svg_element_tree(
        doc,
        layout=layout,
        unit_scale=unit_scale,
        bind_dxf_attributes=bind_dxf_attributes,
        target_mode=target_mode,
    )
    seed = ET.tostring(svg_root, encoding="utf-8")
    return cls._build_from_svg_root(
        svg_root,
        source_format="dxf",
        hash_seed=seed,
        mode=target_mode,
        anchor=anchor,
        position=position,
        offset=offset,
        scale=scale,
        fit_mode=fit_mode,
        theme_adapt=theme_adapt,
        missing_placeholder=missing_placeholder,
        defaults=defaults,
        title_block_bbox_mm=title_block_bbox_mm,
        margins=margins,
        show_revision_table=show_revision_table,
    )

with_defaults(fields=None, **kwargs)

Return a copy of this template with additional/overridden default field values.

Source code in src/build123d_techdraw/core/template.py
def with_defaults(
    self,
    fields: Mapping[str, str] | None = None,
    **kwargs: str,
) -> SheetTemplate:
    """Return a copy of this template with additional/overridden default field values."""
    merged = dict(self.defaults)
    if fields:
        for k, v in fields.items():
            merged[str(k)] = str(v)
    for k, v in kwargs.items():
        merged[str(k)] = str(v)
    return SheetTemplate(
        source_format=self.source_format,
        mode=self.mode,
        width_mm=self.width_mm,
        height_mm=self.height_mm,
        viewbox=self.viewbox,
        root=copy.deepcopy(self._root),
        defs_children=[copy.deepcopy(d) for d in self._defs_children],
        id_prefix=self._id_prefix,
        scope_class=self._scope_class,
        detected_placeholders=self._detected_placeholders,
        inline_defaults=dict(self._inline_defaults),
        detected_tb_bbox_mm=self._detected_tb_bbox_mm,
        anchor=self.anchor,
        position=self.position,
        offset=self.offset,
        scale=self.scale,
        fit_mode=self.fit_mode,
        theme_adapt=self.theme_adapt,
        missing_placeholder=self.missing_placeholder,
        defaults=merged,
        title_block_bbox_mm=self.title_block_bbox_mm,
        margins=self.margins,
        show_revision_table=self.show_revision_table,
    )

resolve_fields(info, *, sheet=None, extra_fields=None)

Return resolved placeholder key -> value mapping for all placeholders in the template.

Source code in src/build123d_techdraw/core/template.py
def resolve_fields(
    self,
    info: TitleBlockInfo,
    *,
    sheet: DrawingSheet | None = None,
    extra_fields: Mapping[str, str] | None = None,
) -> dict[str, str]:
    """Return resolved placeholder key -> value mapping for all placeholders in the template."""
    lookup = self._build_field_lookup(info, sheet=sheet, extra_fields=extra_fields)
    return {k: lookup[k] for k in self._detected_placeholders if k in lookup}

missing_fields(info, *, sheet=None, extra_fields=None)

Return placeholder keys that have no bound value or inline default.

Source code in src/build123d_techdraw/core/template.py
def missing_fields(
    self,
    info: TitleBlockInfo,
    *,
    sheet: DrawingSheet | None = None,
    extra_fields: Mapping[str, str] | None = None,
) -> list[str]:
    """Return placeholder keys that have no bound value or inline default."""
    lookup = self._build_field_lookup(info, sheet=sheet, extra_fields=extra_fields)
    return [k for k in self._detected_placeholders if k not in lookup]

placement_transform(sheet)

Return (tx, ty, sx, sy) mapping template viewBox units into sheet mm.

Source code in src/build123d_techdraw/core/template.py
def placement_transform(self, sheet: DrawingSheet) -> tuple[float, float, float, float]:
    """Return ``(tx, ty, sx, sy)`` mapping template ``viewBox`` units into sheet mm."""
    vb_x, vb_y, vb_w, vb_h = self.viewbox
    if self.mode is TemplateMode.SHEET:
        if self.fit_mode == "exact":
            sx = self.width_mm / vb_w
            sy = self.height_mm / vb_h
            tx = -vb_x * sx
            ty = -vb_y * sy
        elif self.fit_mode == "stretch":
            sx = sheet.width_mm / vb_w
            sy = sheet.height_mm / vb_h
            tx = -vb_x * sx
            ty = -vb_y * sy
        else:  # "fit"
            fit_s = min(sheet.width_mm / self.width_mm, sheet.height_mm / self.height_mm)
            rw = self.width_mm * fit_s
            rh = self.height_mm * fit_s
            sx = rw / vb_w
            sy = rh / vb_h
            tx = (sheet.width_mm - rw) * 0.5 - vb_x * sx
            ty = (sheet.height_mm - rh) * 0.5 - vb_y * sy
        return (tx, ty, sx, sy)

    # TITLE_BLOCK mode
    rw = self.width_mm * self.scale
    rh = self.height_mm * self.scale
    sx = rw / vb_w
    sy = rh / vb_h
    if self.position is not None:
        bx, by = self.position
    else:
        if "right" in self.anchor:
            bx = sheet.width_mm - sheet.right_margin - rw
        else:
            bx = sheet.left_margin
        if "bottom" in self.anchor:
            by = sheet.height_mm - sheet.bottom_margin - rh
        else:
            by = sheet.top_margin
    bx += self.offset[0]
    by += self.offset[1]
    return (bx - vb_x * sx, by - vb_y * sy, sx, sy)

title_block_bbox(sheet)

Return the rendered title block bounding box in sheet mm (min_x, min_y, max_x, max_y).

Source code in src/build123d_techdraw/core/template.py
def title_block_bbox(self, sheet: DrawingSheet) -> BBox2D:
    """Return the rendered title block bounding box in sheet mm ``(min_x, min_y, max_x, max_y)``."""
    tx, ty, sx, sy = self.placement_transform(sheet)
    vb_x, vb_y, vb_w, vb_h = self.viewbox
    if self.mode is TemplateMode.TITLE_BLOCK:
        x0 = tx + vb_x * sx
        y0 = ty + vb_y * sy
        return (x0, y0, x0 + vb_w * sx, y0 + vb_h * sy)

    local_mm = self.title_block_bbox_mm or self._detected_tb_bbox_mm
    if local_mm is None:
        return (
            max(0.0, sheet.width_mm - sheet.right_margin - 180.0),
            max(0.0, sheet.height_mm - sheet.bottom_margin - 40.0),
            sheet.width_mm - sheet.right_margin,
            sheet.height_mm - sheet.bottom_margin,
        )
    # Convert template mm -> viewBox units -> sheet mm
    u_per_mm_x = vb_w / self.width_mm
    u_per_mm_y = vb_h / self.height_mm
    return (
        tx + (vb_x + local_mm[0] * u_per_mm_x) * sx,
        ty + (vb_y + local_mm[1] * u_per_mm_y) * sy,
        tx + (vb_x + local_mm[2] * u_per_mm_x) * sx,
        ty + (vb_y + local_mm[3] * u_per_mm_y) * sy,
    )

render_parts(sheet, *, extra_fields=None)

Render scoped (defs_svg, body_svg) fragments ready to embed in sheet.to_svg().

Source code in src/build123d_techdraw/core/template.py
def render_parts(
    self,
    sheet: DrawingSheet,
    *,
    extra_fields: Mapping[str, str] | None = None,
) -> tuple[str, str]:
    """Render scoped ``(defs_svg, body_svg)`` fragments ready to embed in ``sheet.to_svg()``."""
    cloned_root = copy.deepcopy(self._root)
    include_inline = self.missing_placeholder != "error"
    lookup = self._build_field_lookup(
        sheet.title_info,
        sheet=sheet,
        extra_fields=extra_fields,
        include_inline_defaults=include_inline,
    )
    missing_keys = self._substitute_placeholders_and_slots(
        cloned_root, sheet.title_info, lookup
    )
    if self.missing_placeholder == "error" and missing_keys:
        raise KeyError(f"Unbound template placeholders: {', '.join(sorted(set(missing_keys)))}")

    tx, ty, sx, sy = self.placement_transform(sheet)
    role_class = "template-sheet" if self.mode is TemplateMode.SHEET else "template-title-block"
    cloned_root.set("class", f"{role_class} {self._scope_class}".strip())
    if abs(sx - sy) < 1e-6:
        scale_expr = f"scale({sx:.6f})" if abs(sx - 1.0) > 1e-6 else ""
    else:
        scale_expr = f"scale({sx:.6f}, {sy:.6f})"
    tf_parts = [f"translate({tx:.4f}, {ty:.4f})"]
    if scale_expr:
        tf_parts.append(scale_expr)
    cloned_root.set("transform", " ".join(tf_parts))

    defs_svg = "\n    ".join(ET.tostring(d, encoding="unicode") for d in self._defs_children)
    body_svg = ET.tostring(cloned_root, encoding="unicode")
    return defs_svg, body_svg

render_svg(sheet, *, extra_fields=None)

Render a self-contained SVG group containing any scoped defs and the template body.

Source code in src/build123d_techdraw/core/template.py
def render_svg(
    self,
    sheet: DrawingSheet,
    *,
    extra_fields: Mapping[str, str] | None = None,
) -> str:
    """Render a self-contained SVG group containing any scoped defs and the template body."""
    defs_svg, body_svg = self.render_parts(sheet, extra_fields=extra_fields)
    if defs_svg:
        return f"<defs>\n    {defs_svg}\n  </defs>\n  {body_svg}"
    return body_svg

TemplateMode

Bases: Enum

How a SheetTemplate integrates with a DrawingSheet.

Source code in src/build123d_techdraw/core/template.py
class TemplateMode(Enum):
    """How a ``SheetTemplate`` integrates with a ``DrawingSheet``."""

    SHEET = "sheet"
    TITLE_BLOCK = "title_block"

    @classmethod
    def coerce(cls, value: TemplateMode | str) -> TemplateMode:
        """Coerce a ``TemplateMode`` or case-insensitive string into a ``TemplateMode``."""
        if isinstance(value, cls):
            return value
        if isinstance(value, str):
            norm = _normalize_key(value).lower()
            if norm == "sheet":
                return cls.SHEET
            if norm in ("title_block", "titleblock"):
                return cls.TITLE_BLOCK
            raise ValueError(
                f"Unknown template mode {value!r}; expected 'sheet', 'title_block', or 'auto'."
            )
        raise TypeError(f"Expected TemplateMode or str, got {type(value).__name__}")

coerce(value) classmethod

Coerce a TemplateMode or case-insensitive string into a TemplateMode.

Source code in src/build123d_techdraw/core/template.py
@classmethod
def coerce(cls, value: TemplateMode | str) -> TemplateMode:
    """Coerce a ``TemplateMode`` or case-insensitive string into a ``TemplateMode``."""
    if isinstance(value, cls):
        return value
    if isinstance(value, str):
        norm = _normalize_key(value).lower()
        if norm == "sheet":
            return cls.SHEET
        if norm in ("title_block", "titleblock"):
            return cls.TITLE_BLOCK
        raise ValueError(
            f"Unknown template mode {value!r}; expected 'sheet', 'title_block', or 'auto'."
        )
    raise TypeError(f"Expected TemplateMode or str, got {type(value).__name__}")

build123d_techdraw.core.part_info

Typed bill-of-materials metadata for build123d shapes.

build123d already carries label (BOM description) and material (a typed FinishedMaterial) on every shape. It has no field for a part number or a free-text material specification, so this module attaches a frozen PartInfo to a shape. This is the only place that reads or writes that attribute.

The attribute lives in the shape's __dict__, so it survives copy/deepcopy (and therefore moved()/located() copies). Boolean operations (a - b) create a new shape without it: set the part info on the finished shape.

PartInfo dataclass

BOM metadata for one assembly component.

Attributes:

Name Type Description
part_no str

Part / drawing number shown in the BOM. Empty -> PART-<item no>.

material_spec str

Material designation text for the BOM (e.g. "AL 6061-T6"). Empty -> derived from the shape's build123d material, else "STANDARD".

Source code in src/build123d_techdraw/core/part_info.py
@dataclass(frozen=True)
class PartInfo:
    """BOM metadata for one assembly component.

    Attributes:
        part_no: Part / drawing number shown in the BOM. Empty -> ``PART-<item no>``.
        material_spec: Material designation text for the BOM (e.g. ``"AL 6061-T6"``).
            Empty -> derived from the shape's build123d ``material``, else ``"STANDARD"``.
    """

    part_no: str = ""
    material_spec: str = ""

set_part_info(shape, info)

Attach BOM metadata to shape (replacing any previous value).

Source code in src/build123d_techdraw/core/part_info.py
def set_part_info(shape: Shape[Any], info: PartInfo) -> None:
    """Attach BOM metadata to ``shape`` (replacing any previous value)."""
    setattr(shape, _PART_INFO_ATTR, info)

get_part_info(shape)

Return the BOM metadata attached with set_part_info, if any.

Source code in src/build123d_techdraw/core/part_info.py
def get_part_info(shape: Shape[Any]) -> PartInfo | None:
    """Return the BOM metadata attached with `set_part_info`, if any."""
    info = shape.__dict__.get(_PART_INFO_ATTR)
    return info if isinstance(info, PartInfo) else None

build123d_techdraw.core.directive

Base class for objects that configure a DrawingSheet when added to it.

SheetDirective

Bases: ABC

Something DrawingSheet.add applies to the sheet instead of storing as an annotation.

Examples: title block and notes settings, revision rows, BOMs and multiview layouts.

Source code in src/build123d_techdraw/core/directive.py
class SheetDirective(ABC):
    """Something ``DrawingSheet.add`` applies to the sheet instead of storing as an annotation.

    Examples: title block and notes settings, revision rows, BOMs and multiview layouts.
    """

    @abstractmethod
    def _apply_to_sheet(self, sheet: DrawingSheet) -> None:
        """Apply this directive's content to ``sheet``."""

build123d_techdraw.core.booklet

Multi-page drawing booklets and PDF/SVG package generation.

DrawingBooklet

Manages an ordered package of multiple technical drawing sheets with auto-pagination.

Source code in src/build123d_techdraw/core/booklet.py
class DrawingBooklet:
    """Manages an ordered package of multiple technical drawing sheets with auto-pagination."""

    def __init__(
        self,
        title: str = "ENGINEERING DRAWING PACKAGE",
        sheets: Iterable[DrawingSheet] | None = None,
    ):
        self.title = title
        self.sheets: list[DrawingSheet] = []
        if sheets:
            for s in sheets:
                self.add_sheet(s)

    def _paginate(self) -> None:
        """Dynamically assign sheet_no and total_sheets across all booklet sheets."""
        total = len(self.sheets)
        for idx, sheet in enumerate(self.sheets):
            sheet.title_info.sheet_no = f"{idx + 1}"
            sheet.title_info.total_sheets = f"{total}"

    def add_sheet(self, sheet: DrawingSheet) -> Self:
        """Add a sheet to the drawing booklet and update pagination."""
        self.sheets.append(sheet)
        self._paginate()
        return self

    def __iadd__(self, sheet: DrawingSheet | Iterable[DrawingSheet]) -> Self:
        if isinstance(sheet, DrawingSheet):
            return self.add_sheet(sheet)
        for s in sheet:
            self.add_sheet(s)
        return self

    def __add__(self, sheet: DrawingSheet | Iterable[DrawingSheet]) -> Self:
        return self.__iadd__(sheet)

    def export_svgs(self, output_dir: str, theme: Theme | str = Theme.DARK_BLUEPRINT) -> list[str]:
        """Export each sheet in the booklet as an individual SVG file with auto-pagination."""
        self._paginate()
        os.makedirs(output_dir, exist_ok=True)
        paths: list[str] = []
        for i, s in enumerate(self.sheets):
            dwg_no = s.title_info.drawing_no.lower().replace("-", "_")
            fname = f"{i + 1:02d}_{dwg_no}.svg"
            path = os.path.join(output_dir, fname)
            s.export_svg(path, theme=theme)
            paths.append(path)
        return paths

    def export_pdf(
        self,
        output_path: str,
        theme: Theme | str = Theme.DARK_BLUEPRINT,
        bookmarks: bool = True,
    ) -> None:
        """Compile all sheets into a single multi-page vector PDF file with auto-pagination and document outline bookmarks."""
        self._paginate()
        resolved_theme = (
            Theme.ISO_WHITE
            if (isinstance(theme, str) and theme.lower() in ("print", "white", "iso_white"))
            or theme == Theme.ISO_WHITE
            else Theme.DARK_BLUEPRINT
        )
        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        sheet_data = [
            (sheet.width_mm, sheet.height_mm, sheet.to_svg(resolved_theme)) for sheet in self.sheets
        ]
        sheet_titles = []
        for i, s in enumerate(self.sheets):
            d_title = s.title_info.drawing_title
            d_no = s.title_info.drawing_no
            if d_no and d_title:
                sheet_titles.append(f"{d_no} - {d_title}")
            elif d_title:
                sheet_titles.append(d_title)
            elif d_no:
                sheet_titles.append(d_no)
            else:
                sheet_titles.append(f"Sheet {i + 1}")
        PDFRenderer.render_sheets_to_pdf(
            sheet_data,
            output_path,
            resolved_theme,
            bookmarks=bookmarks,
            booklet_title=self.title,
            sheet_titles=sheet_titles,
        )

add_sheet(sheet)

Add a sheet to the drawing booklet and update pagination.

Source code in src/build123d_techdraw/core/booklet.py
def add_sheet(self, sheet: DrawingSheet) -> Self:
    """Add a sheet to the drawing booklet and update pagination."""
    self.sheets.append(sheet)
    self._paginate()
    return self

export_svgs(output_dir, theme=Theme.DARK_BLUEPRINT)

Export each sheet in the booklet as an individual SVG file with auto-pagination.

Source code in src/build123d_techdraw/core/booklet.py
def export_svgs(self, output_dir: str, theme: Theme | str = Theme.DARK_BLUEPRINT) -> list[str]:
    """Export each sheet in the booklet as an individual SVG file with auto-pagination."""
    self._paginate()
    os.makedirs(output_dir, exist_ok=True)
    paths: list[str] = []
    for i, s in enumerate(self.sheets):
        dwg_no = s.title_info.drawing_no.lower().replace("-", "_")
        fname = f"{i + 1:02d}_{dwg_no}.svg"
        path = os.path.join(output_dir, fname)
        s.export_svg(path, theme=theme)
        paths.append(path)
    return paths

export_pdf(output_path, theme=Theme.DARK_BLUEPRINT, bookmarks=True)

Compile all sheets into a single multi-page vector PDF file with auto-pagination and document outline bookmarks.

Source code in src/build123d_techdraw/core/booklet.py
def export_pdf(
    self,
    output_path: str,
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    bookmarks: bool = True,
) -> None:
    """Compile all sheets into a single multi-page vector PDF file with auto-pagination and document outline bookmarks."""
    self._paginate()
    resolved_theme = (
        Theme.ISO_WHITE
        if (isinstance(theme, str) and theme.lower() in ("print", "white", "iso_white"))
        or theme == Theme.ISO_WHITE
        else Theme.DARK_BLUEPRINT
    )
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    sheet_data = [
        (sheet.width_mm, sheet.height_mm, sheet.to_svg(resolved_theme)) for sheet in self.sheets
    ]
    sheet_titles = []
    for i, s in enumerate(self.sheets):
        d_title = s.title_info.drawing_title
        d_no = s.title_info.drawing_no
        if d_no and d_title:
            sheet_titles.append(f"{d_no} - {d_title}")
        elif d_title:
            sheet_titles.append(d_title)
        elif d_no:
            sheet_titles.append(d_no)
        else:
            sheet_titles.append(f"Sheet {i + 1}")
    PDFRenderer.render_sheets_to_pdf(
        sheet_data,
        output_path,
        resolved_theme,
        bookmarks=bookmarks,
        booklet_title=self.title,
        sheet_titles=sheet_titles,
    )

build123d_techdraw.core.scale

ISO 5455 scale ladders and auto-scale utilities.

format_iso_scale(scale)

Format a view scale label per ISO 5455 (e.g. 'SCALE 1:1', 'SCALE 1:2').

Source code in src/build123d_techdraw/core/scale.py
def format_iso_scale(scale: float) -> str:
    """Format a view scale label per ISO 5455 (e.g. 'SCALE 1:1', 'SCALE 1:2')."""
    return f"SCALE {format_iso_ratio(scale)}"

find_closest_iso_scale(ratio)

Find the largest standard ISO 5455 scale that is <= the specified ratio.

Source code in src/build123d_techdraw/core/scale.py
def find_closest_iso_scale(ratio: float) -> float:
    """Find the largest standard ISO 5455 scale that is <= the specified ratio."""
    valid_scales = [s for s in STANDARD_SCALES if s <= ratio * 1.02]
    if valid_scales:
        return max(valid_scales)
    return STANDARD_SCALES[-1]

calculate_auto_scale(model_bbox_size, available_size, margin_factor=0.75, enforce_iso_scale=True)

Calculate the best standard ISO 5455 scale fitting model dimensions into available space.

Source code in src/build123d_techdraw/core/scale.py
def calculate_auto_scale(
    model_bbox_size: tuple[float, float],
    available_size: tuple[float, float],
    margin_factor: float = 0.75,
    enforce_iso_scale: bool = True,
) -> float:
    """Calculate the best standard ISO 5455 scale fitting model dimensions into available space."""
    m_w, m_h = model_bbox_size
    a_w, a_h = available_size

    if m_w <= 0.0 or m_h <= 0.0 or a_w <= 0.0 or a_h <= 0.0:
        return 1.0

    target_w = a_w * margin_factor
    target_h = a_h * margin_factor

    ratio_w = target_w / m_w
    ratio_h = target_h / m_h
    max_ratio = min(ratio_w, ratio_h)

    return find_closest_iso_scale(max_ratio) if enforce_iso_scale else max_ratio