Repository navigation
Expand file tree
/
Copy pathdtm12p_command.py
More file actions
747 lines (648 loc) · 27.3 KB
/
Copy pathdtm12p_command.py
File metadata and controls
747 lines (648 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
"""FreeCAD command and task-panel UI for the DTM12P Termination Housing tool."""
import os
import FreeCAD
import FreeCADGui
import Part
from FreeCAD import Vector
from PySide import QtWidgets, QtCore
_plugin_dir = os.path.dirname(os.path.abspath(__file__))
# ---------------------------------------------------------------------------
# FeaturePython proxy & ViewProvider (enables double-click re-edit)
# ---------------------------------------------------------------------------
class _DTM12PProxy:
"""Data proxy for a DTM12P PartDesign::FeatureAdditivePython."""
def __init__(self, obj):
obj.Proxy = self
def execute(self, obj):
"""Recompute the fused shape."""
FreeCAD.Console.PrintMessage(
"DTM12P.execute() called for {}\n".format(obj.Name))
if not hasattr(obj, "DTM12P_FaceName"):
FreeCAD.Console.PrintWarning(
"DTM12P.execute(): no DTM12P_FaceName property yet\n")
return
# Ensure the frame storage properties exist (added in v2.4 — older
# documents won't have them yet).
_ensure_frame_properties(obj)
if hasattr(obj, "BaseFeature") and obj.BaseFeature is not None:
base_shape = obj.BaseFeature.Shape
elif hasattr(obj, "DTM12P_OriginalBody") and obj.DTM12P_OriginalBody:
original = FreeCAD.ActiveDocument.getObject(
obj.DTM12P_OriginalBody)
if original is None or original.Shape.isNull():
return
base_shape = original.Shape
else:
return
try:
from dtm12p_geometry import (
place_housing_from_frame,
compute_face_frame, compute_edge_frame,
)
anchor, u_axis, v_axis, normal = _resolve_frame(obj, base_shape)
if anchor is None:
return
new_shape = place_housing_from_frame(
base_shape, anchor, u_axis, v_axis, normal,
x_offset=getattr(obj, "DTM12P_XOffset", 0.0),
y_offset=getattr(obj, "DTM12P_YOffset", 0.0),
rotation=getattr(obj, "DTM12P_Rotation", 0.0),
)
if new_shape and not new_shape.isNull():
new_shape.transformShape(
obj.Placement.inverse().toMatrix(), True)
obj.Shape = new_shape
if hasattr(obj, "AddSubShape"):
tool = new_shape.cut(base_shape)
tool.transformShape(
obj.Placement.inverse().toMatrix(), True)
obj.AddSubShape = tool
except Exception as e:
FreeCAD.Console.PrintError(
"DTM12P recompute failed: {}\n".format(e))
def __getstate__(self):
return None
def __setstate__(self, state):
return None
class _DTM12PViewProvider:
"""ViewProvider that enables double-click re-editing of DTM12P objects."""
def __init__(self, vobj):
vobj.Proxy = self
def attach(self, vobj):
self.Object = vobj.Object
def _open_edit_panel(self, obj):
if not hasattr(obj, "DTM12P_FaceName"):
return False
original = _get_dtm12p_base_object(obj)
if original is None:
QtWidgets.QMessageBox.warning(
None, "DTM12P",
"Cannot re-edit: the original body object was deleted.",
)
return True
prefill = {
"x_offset": getattr(obj, "DTM12P_XOffset", 0.0),
"y_offset": getattr(obj, "DTM12P_YOffset", 0.0),
"rotation": getattr(obj, "DTM12P_Rotation", 0.0),
}
edge_name = getattr(obj, "DTM12P_EdgeName", "")
initial_frame = None
_ensure_frame_properties(obj)
if _frame_is_set(obj):
initial_frame = (
Vector(obj.DTM12P_FrameAnchor),
Vector(obj.DTM12P_FrameU),
Vector(obj.DTM12P_FrameV),
Vector(obj.DTM12P_FrameNormal),
)
panel = DTM12PTaskPanel(
original, obj.DTM12P_FaceName,
edge_name=edge_name,
edit_obj=obj, prefill=prefill,
initial_frame=initial_frame,
)
FreeCADGui.Control.showDialog(panel)
return True
def doubleClicked(self, vobj):
try:
return self._open_edit_panel(vobj.Object)
except Exception as e:
FreeCAD.Console.PrintError(
"DTM12P doubleClicked error: {}\n".format(e))
return False
def setEdit(self, vobj, mode=0):
if mode != 0:
return False
try:
return self._open_edit_panel(vobj.Object)
except Exception as e:
FreeCAD.Console.PrintError(
"DTM12P setEdit error: {}\n".format(e))
return False
def unsetEdit(self, vobj, mode=0):
FreeCADGui.Control.closeDialog()
return True
def getIcon(self):
return os.path.join(
_plugin_dir, "resources", "icons", "DTM12P.svg"
)
def __getstate__(self):
return None
def __setstate__(self, state):
return None
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _find_body(obj):
"""Return the PartDesign::Body that *obj* belongs to, or None."""
if hasattr(obj, "TypeId") and obj.TypeId == "PartDesign::Body":
return obj
if hasattr(obj, "getParentGeoFeatureGroup"):
parent = obj.getParentGeoFeatureGroup()
if (parent is not None
and hasattr(parent, "TypeId")
and parent.TypeId == "PartDesign::Body"):
return parent
return None
def _add_dtm12p_properties(obj):
"""Add custom storage properties to a DTM12P feature object."""
obj.addProperty(
"App::PropertyFloat", "DTM12P_XOffset", "DTM12P",
"Offset along the face U axis (mm)")
obj.addProperty(
"App::PropertyFloat", "DTM12P_YOffset", "DTM12P",
"Offset along the face V axis (mm)")
obj.addProperty(
"App::PropertyFloat", "DTM12P_Rotation", "DTM12P",
"Rotation angle on the face (degrees)")
obj.addProperty(
"App::PropertyString", "DTM12P_FaceName", "DTM12P",
"Face used on the original body (display only)")
obj.addProperty(
"App::PropertyString", "DTM12P_EdgeName", "DTM12P",
"Edge used for front alignment (display only)")
obj.addProperty(
"App::PropertyString", "DTM12P_OriginalBody", "DTM12P",
"Original body object name")
_ensure_frame_properties(obj)
def _ensure_frame_properties(obj):
"""Add frame-storage properties if not already present.
The frame (anchor + U/V/normal) is the source of truth for placement
at execute time. Storing it directly decouples the housing position
from face/edge index lookups, which is what made placement break when
other DTM features were added or removed from the body chain.
"""
if not hasattr(obj, "DTM12P_FrameAnchor"):
obj.addProperty(
"App::PropertyVector", "DTM12P_FrameAnchor", "DTM12P",
"Frame anchor point in world coordinates")
if not hasattr(obj, "DTM12P_FrameU"):
obj.addProperty(
"App::PropertyVector", "DTM12P_FrameU", "DTM12P",
"Frame U axis (housing local X)")
if not hasattr(obj, "DTM12P_FrameV"):
obj.addProperty(
"App::PropertyVector", "DTM12P_FrameV", "DTM12P",
"Frame V axis (housing local Y)")
if not hasattr(obj, "DTM12P_FrameNormal"):
obj.addProperty(
"App::PropertyVector", "DTM12P_FrameNormal", "DTM12P",
"Frame normal (housing local Z, outward from face)")
def _frame_is_set(obj):
"""Return True if the stored frame on *obj* looks valid."""
n = getattr(obj, "DTM12P_FrameNormal", None)
return n is not None and n.Length > 1e-9
def _store_frame(obj, anchor, u_axis, v_axis, normal):
_ensure_frame_properties(obj)
obj.DTM12P_FrameAnchor = Vector(anchor)
obj.DTM12P_FrameU = Vector(u_axis)
obj.DTM12P_FrameV = Vector(v_axis)
obj.DTM12P_FrameNormal = Vector(normal)
def _resolve_frame(obj, base_shape):
"""Return (anchor, u, v, normal) for *obj*.
Prefers the stored frame. Falls back to looking up face/edge by name
on *base_shape* (one-time migration) for older documents.
"""
from dtm12p_geometry import compute_face_frame, compute_edge_frame
if _frame_is_set(obj):
return (
Vector(obj.DTM12P_FrameAnchor),
Vector(obj.DTM12P_FrameU),
Vector(obj.DTM12P_FrameV),
Vector(obj.DTM12P_FrameNormal),
)
# Migration path: derive frame from face_name on the current base.
face_name = getattr(obj, "DTM12P_FaceName", "")
if not face_name:
return (None, None, None, None)
try:
face_idx = int(face_name.replace("Face", ""))
except ValueError:
return (None, None, None, None)
if face_idx < 1 or face_idx > len(base_shape.Faces):
FreeCAD.Console.PrintWarning(
"DTM12P: stored {} no longer resolves on base shape "
"({} faces). Open the edit panel and click "
"'Re-attach to selection' to point it at the correct face.\n"
.format(face_name, len(base_shape.Faces)))
return (None, None, None, None)
face = base_shape.Faces[face_idx - 1]
edge = None
edge_name = getattr(obj, "DTM12P_EdgeName", "")
if edge_name:
try:
edge_idx = int(edge_name.replace("Edge", ""))
if 1 <= edge_idx <= len(base_shape.Edges):
edge = base_shape.Edges[edge_idx - 1]
except ValueError:
pass
if edge is not None:
anchor, u, v, n = compute_edge_frame(face, edge)
else:
anchor, u, v, n = compute_face_frame(face)
_store_frame(obj, anchor, u, v, n)
FreeCAD.Console.PrintMessage(
"DTM12P: migrated {} frame to absolute coordinates.\n"
.format(obj.Name))
return anchor, u, v, n
def _get_dtm12p_base_object(obj):
"""Return the base object that a DTM12P result was derived from."""
if hasattr(obj, "BaseFeature") and obj.BaseFeature is not None:
return obj.BaseFeature
orig_name = getattr(obj, "DTM12P_OriginalBody", None)
if orig_name:
return FreeCAD.ActiveDocument.getObject(orig_name)
return None
def _read_face_edge_from_selection(skip_obj=None):
"""Read the first Face (and optional Edge) from the active selection.
Returns (source_obj, face_name, face, edge_name, edge) or
(None, "", None, "", None) if nothing usable is selected.
Selections matching *skip_obj* are ignored so the panel can scan past
a re-selected DTM feature itself.
"""
sel = FreeCADGui.Selection.getSelectionEx()
for s in sel:
if skip_obj is not None and s.Object is skip_obj:
continue
if not s.SubElementNames:
continue
face_name = ""
edge_name = ""
for n in s.SubElementNames:
if n.startswith("Face") and not face_name:
face_name = n
elif n.startswith("Edge") and not edge_name:
edge_name = n
if not face_name:
continue
try:
face = getattr(s.Object.Shape, face_name)
except Exception:
continue
edge = None
if edge_name:
try:
edge = getattr(s.Object.Shape, edge_name)
except Exception:
edge_name = ""
return s.Object, face_name, face, edge_name, edge
return None, "", None, "", None
# ---------------------------------------------------------------------------
# Task Panel (sidebar UI)
# ---------------------------------------------------------------------------
class DTM12PTaskPanel:
"""Task panel shown in the FreeCAD sidebar when the DTM12P command is active."""
def __init__(self, body_obj, face_name, edge_name="",
edit_obj=None, prefill=None, initial_frame=None):
self.body_obj = body_obj
self.face_name = face_name
self.edge_name = edge_name
self.edit_obj = edit_obj
# Frame is computed lazily from face/edge in accept(), or refreshed
# by the "Re-attach to selection" button while editing. For edit
# mode an initial_frame from stored properties keeps the housing
# in place even if face_name no longer resolves on base_shape.
self._frame = initial_frame
self.form = self._build_ui()
if prefill:
self._apply_prefill(prefill)
self._refresh_attachment_label()
def _build_ui(self):
widget = QtWidgets.QWidget()
layout = QtWidgets.QFormLayout(widget)
layout.setFieldGrowthPolicy(
QtWidgets.QFormLayout.AllNonFixedFieldsGrow
)
header = QtWidgets.QLabel("<b>DTM12P Termination Housing</b>")
header.setAlignment(QtCore.Qt.AlignCenter)
layout.addRow(header)
info = QtWidgets.QLabel(
"<i>Places a Deutsch DTM04-12PA termination housing\n"
"onto the selected face, extending outward.</i>"
)
info.setWordWrap(True)
layout.addRow(info)
self.attachment_label = QtWidgets.QLabel("")
self.attachment_label.setWordWrap(True)
layout.addRow(self.attachment_label)
# Re-attach button is only useful when editing an existing feature.
if self.edit_obj is not None:
self.reattach_btn = QtWidgets.QPushButton(
"Re-attach to selection"
)
self.reattach_btn.setToolTip(
"Select a Face (and optional Edge) in the 3D view, then\n"
"click here to re-anchor this housing without rebuilding\n"
"the model. Useful when upstream geometry has changed."
)
self.reattach_btn.clicked.connect(self._on_reattach_clicked)
layout.addRow(self.reattach_btn)
sep = QtWidgets.QFrame()
sep.setFrameShape(QtWidgets.QFrame.HLine)
layout.addRow(sep)
self.x_offset_spin = QtWidgets.QDoubleSpinBox()
self.x_offset_spin.setRange(-500.0, 500.0)
self.x_offset_spin.setValue(0.0)
self.x_offset_spin.setSingleStep(1.0)
self.x_offset_spin.setDecimals(1)
self.x_offset_spin.setSuffix(" mm")
self.x_label = QtWidgets.QLabel("X Offset:")
layout.addRow(self.x_label, self.x_offset_spin)
self.y_offset_spin = QtWidgets.QDoubleSpinBox()
self.y_offset_spin.setRange(-500.0, 500.0)
self.y_offset_spin.setValue(0.0)
self.y_offset_spin.setSingleStep(1.0)
self.y_offset_spin.setDecimals(1)
self.y_offset_spin.setSuffix(" mm")
self.y_label = QtWidgets.QLabel("Y Offset:")
layout.addRow(self.y_label, self.y_offset_spin)
self.rotation_spin = QtWidgets.QDoubleSpinBox()
self.rotation_spin.setRange(-180.0, 180.0)
self.rotation_spin.setValue(0.0)
self.rotation_spin.setSingleStep(5.0)
self.rotation_spin.setDecimals(1)
self.rotation_spin.setSuffix(" deg")
self.rotation_spin.setToolTip(
"Rotation angle on the face (degrees)."
)
layout.addRow("Rotation:", self.rotation_spin)
return widget
def _refresh_attachment_label(self):
body_label = (self.body_obj.Label
if self.body_obj is not None else "?")
if self.edge_name:
self.attachment_label.setText(
"<b>Attached to:</b> {}.{}<br/>"
"<b>Front aligned to:</b> {}".format(
body_label, self.face_name, self.edge_name)
)
self.x_label.setText("Along Edge:")
self.x_offset_spin.setToolTip(
"Offset along the edge direction.")
self.y_label.setText("From Edge:")
self.y_offset_spin.setToolTip(
"Offset perpendicular to the edge (positive = away from edge).")
else:
self.attachment_label.setText(
"<b>Attached to:</b> {}.{}<br/>"
"<i>Tip: Select a Face + Edge to align the housing front "
"to the edge.</i>".format(body_label, self.face_name)
)
self.x_label.setText("X Offset:")
self.x_offset_spin.setToolTip(
"Offset along the model X axis (projected onto the face).")
self.y_label.setText("Y Offset:")
self.y_offset_spin.setToolTip(
"Offset along the model Y axis (projected onto the face).")
def _on_reattach_clicked(self):
src_obj, face_name, face, edge_name, edge = \
_read_face_edge_from_selection(skip_obj=self.edit_obj)
if src_obj is None or face is None:
QtWidgets.QMessageBox.information(
None, "DTM12P",
"Select a Face (and optionally an Edge) on a body in the\n"
"3D view, then click 'Re-attach to selection' again."
)
return
surface = face.Surface
is_planar = hasattr(surface, "Axis") or isinstance(
surface, Part.Plane)
if not is_planar:
QtWidgets.QMessageBox.warning(
None, "Non-Planar Face",
"Please select a flat (planar) face."
)
return
from dtm12p_geometry import compute_face_frame, compute_edge_frame
if edge is not None:
self._frame = compute_edge_frame(face, edge)
else:
self._frame = compute_face_frame(face)
self.body_obj = src_obj
self.face_name = face_name
self.edge_name = edge_name
self._refresh_attachment_label()
FreeCAD.Console.PrintMessage(
"DTM12P: re-attached to {}.{}{}\n".format(
src_obj.Label, face_name,
" + " + edge_name if edge_name else ""))
def _apply_prefill(self, p):
if "x_offset" in p:
self.x_offset_spin.setValue(p["x_offset"])
if "y_offset" in p:
self.y_offset_spin.setValue(p["y_offset"])
if "rotation" in p:
self.rotation_spin.setValue(p["rotation"])
def _resolve_frame_for_accept(self):
"""Return (anchor, u, v, normal) — refresh from current selection if needed."""
if self._frame is not None:
return self._frame
from dtm12p_geometry import compute_face_frame, compute_edge_frame
body_shape = self.body_obj.Shape
face = getattr(body_shape, self.face_name)
edge = (getattr(body_shape, self.edge_name, None)
if self.edge_name else None)
if edge is not None:
return compute_edge_frame(face, edge)
return compute_face_frame(face)
def accept(self):
from dtm12p_geometry import place_housing_from_frame
doc = FreeCAD.ActiveDocument
x_offset = self.x_offset_spin.value()
y_offset = self.y_offset_spin.value()
rotation = self.rotation_spin.value()
try:
anchor, u_axis, v_axis, normal = self._resolve_frame_for_accept()
except Exception as e:
FreeCAD.Console.PrintError(
"DTM12P frame computation failed: {}\n".format(e))
QtWidgets.QMessageBox.critical(
None, "DTM12P Error",
"Could not compute a placement frame from the\n"
"selected face/edge:\n\n{}".format(e))
return False
# For new placements (no existing PD edit) we need the body shape
# for the fuse preview path; for PD edits the proxy.execute() will
# do the fuse against BaseFeature, so we just need to validate.
body = _find_body(self.body_obj)
is_pd_edit = (self.edit_obj is not None
and hasattr(self.edit_obj, "BaseFeature"))
# Validate the fuse for the non-PartDesign path so we can show a
# helpful error before mutating the document.
if not is_pd_edit:
try:
new_shape = place_housing_from_frame(
self.body_obj.Shape,
anchor, u_axis, v_axis, normal,
x_offset=x_offset,
y_offset=y_offset,
rotation=rotation,
)
except Exception as e:
FreeCAD.Console.PrintError(
"DTM12P placement failed: {}\n".format(e))
QtWidgets.QMessageBox.critical(
None, "DTM12P Error",
"Fuse operation failed:\n\n{}\n\n"
"Make sure you selected a flat face with enough "
"room for the housing.".format(e))
return False
if is_pd_edit:
result_obj = self.edit_obj
result_obj.DTM12P_XOffset = x_offset
result_obj.DTM12P_YOffset = y_offset
result_obj.DTM12P_Rotation = rotation
result_obj.DTM12P_FaceName = self.face_name
result_obj.DTM12P_EdgeName = self.edge_name
_store_frame(result_obj, anchor, u_axis, v_axis, normal)
elif body is not None:
result_obj = doc.addObject(
"PartDesign::FeatureAdditivePython", "DTM12P")
_DTM12PProxy(result_obj)
_DTM12PViewProvider(result_obj.ViewObject)
_add_dtm12p_properties(result_obj)
result_obj.DTM12P_XOffset = x_offset
result_obj.DTM12P_YOffset = y_offset
result_obj.DTM12P_Rotation = rotation
result_obj.DTM12P_FaceName = self.face_name
result_obj.DTM12P_EdgeName = self.edge_name
result_obj.DTM12P_OriginalBody = body.Name
_store_frame(result_obj, anchor, u_axis, v_axis, normal)
body.addObject(result_obj)
else:
if self.edit_obj is not None:
doc.removeObject(self.edit_obj.Name)
result_obj = doc.addObject("Part::FeaturePython", "DTM12P")
_DTM12PProxy(result_obj)
_DTM12PViewProvider(result_obj.ViewObject)
_add_dtm12p_properties(result_obj)
result_obj.DTM12P_XOffset = x_offset
result_obj.DTM12P_YOffset = y_offset
result_obj.DTM12P_Rotation = rotation
result_obj.DTM12P_FaceName = self.face_name
result_obj.DTM12P_EdgeName = self.edge_name
result_obj.DTM12P_OriginalBody = self.body_obj.Name
_store_frame(result_obj, anchor, u_axis, v_axis, normal)
result_obj.Shape = new_shape
self.body_obj.ViewObject.Visibility = False
if hasattr(self.body_obj, "ViewObject"):
src_vo = self.body_obj.ViewObject
dst_vo = result_obj.ViewObject
if hasattr(src_vo, "ShapeColor"):
dst_vo.ShapeColor = src_vo.ShapeColor
if hasattr(src_vo, "Transparency"):
dst_vo.Transparency = src_vo.Transparency
doc.recompute()
FreeCADGui.Control.closeDialog()
FreeCAD.Console.PrintMessage(
"DTM12P housing placed onto {}.{}{}\n"
.format(self.body_obj.Label, self.face_name,
" aligned to " + self.edge_name if self.edge_name else "")
)
return True
def reject(self):
FreeCADGui.Control.closeDialog()
return True
def getStandardButtons(self):
return (
QtWidgets.QDialogButtonBox.Ok
| QtWidgets.QDialogButtonBox.Cancel
)
# ---------------------------------------------------------------------------
# FreeCAD Command
# ---------------------------------------------------------------------------
class DTM12PCommand:
"""FreeCAD command that places a DTM12P termination housing onto a face."""
def GetResources(self):
return {
"Pixmap": os.path.join(
_plugin_dir, "resources", "icons", "DTM12P.svg"
),
"MenuText": "Place DTM12P Housing",
"ToolTip": (
"DTM12P\n"
"Place a Deutsch DTM04-12PA termination housing onto the\n"
"selected flat face, extending outward from the surface.\n"
"Select a Face + Edge to align the housing front to the edge.\n"
"Select an existing DTM12P result to re-edit."
),
}
def IsActive(self):
sel = FreeCADGui.Selection.getSelectionEx()
if len(sel) != 1:
return False
obj = sel[0].Object
if hasattr(obj, "DTM12P_FaceName"):
return True
if not sel[0].SubElementNames:
return False
# Active if at least one Face is selected
return any(n.startswith("Face") for n in sel[0].SubElementNames)
def Activated(self):
sel = FreeCADGui.Selection.getSelectionEx()
if not sel:
return
obj = sel[0].Object
sub_names = sel[0].SubElementNames
has_face_sub = (
bool(sub_names) and any(n.startswith("Face") for n in sub_names)
)
# --- Re-edit an existing DTM12P result (only when no face is selected) ---
if hasattr(obj, "DTM12P_FaceName") and not has_face_sub:
original = _get_dtm12p_base_object(obj)
if original is None:
QtWidgets.QMessageBox.warning(
None, "DTM12P",
"Cannot re-edit: the original body object was deleted.",
)
return
prefill = {
"x_offset": getattr(obj, "DTM12P_XOffset", 0.0),
"y_offset": getattr(obj, "DTM12P_YOffset", 0.0),
"rotation": getattr(obj, "DTM12P_Rotation", 0.0),
}
edge_name = getattr(obj, "DTM12P_EdgeName", "")
initial_frame = None
_ensure_frame_properties(obj)
if _frame_is_set(obj):
initial_frame = (
Vector(obj.DTM12P_FrameAnchor),
Vector(obj.DTM12P_FrameU),
Vector(obj.DTM12P_FrameV),
Vector(obj.DTM12P_FrameNormal),
)
panel = DTM12PTaskPanel(
original, obj.DTM12P_FaceName,
edge_name=edge_name,
edit_obj=obj, prefill=prefill,
initial_frame=initial_frame,
)
FreeCADGui.Control.showDialog(panel)
return
# --- New placement: extract face and optional edge ---
face_name = ""
edge_name = ""
for name in sub_names:
if name.startswith("Face") and not face_name:
face_name = name
elif name.startswith("Edge") and not edge_name:
edge_name = name
if not face_name:
return
face = getattr(obj.Shape, face_name)
# Validate: face must be planar
surface = face.Surface
is_planar = hasattr(surface, "Axis") or isinstance(
surface, Part.Plane
)
if not is_planar:
QtWidgets.QMessageBox.warning(
None,
"Non-Planar Face",
"Please select a flat (planar) face.\n"
"The DTM12P housing can only be placed on flat surfaces.",
)
return
panel = DTM12PTaskPanel(obj, face_name, edge_name=edge_name)
FreeCADGui.Control.showDialog(panel)
FreeCADGui.addCommand("TrailCurrent_DTM12P", DTM12PCommand())