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
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
# SPDX-License-Identifier: LGPL-2.1-or-later

# /***************************************************************************
# *   Copyright (c) 2016 Victor Titov (DeepSOIC) <vv.titov@gmail.com>       *
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This library is free software; you can redistribute it and/or         *
# *   modify it under the terms of the GNU Library General Public           *
# *   License as published by the Free Software Foundation; either          *
# *   version 2 of the License, or (at your option) any later version.      *
# *                                                                         *
# *   This library  is distributed in the hope that it will be useful,      *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with this library; see the file COPYING.LIB. If not,    *
# *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
# *   Suite 330, Boston, MA  02111-1307, USA                                *
# *                                                                         *
# ***************************************************************************/

__title__ = "BOPTools.JoinFeatures module"
__author__ = "DeepSOIC"
__url__ = "https://www.freecad.org"
__doc__ = "Implementation of document objects (features) for connect, ebmed and cutout operations."

from . import JoinAPI
import FreeCAD
import Part

if FreeCAD.GuiUp:
    import FreeCADGui
    from PySide import QtCore, QtGui

    # -------------------------- common stuff -------------------------------------

    # -------------------------- translation-related code -------------------------
    # Thanks, yorik! (see forum thread "A new Part tool is being born... JoinFeatures!"
    # https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 )

    try:
        _fromUtf8 = QtCore.QString.fromUtf8
    except Exception:

        def _fromUtf8(s):
            return s

    translate = FreeCAD.Qt.translate
# --------------------------/translation-related code -------------------------


def getParamRefine():
    return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool(
        "RefineModel"
    )


def cmdCreateJoinFeature(name, mode):
    """cmdCreateJoinFeature(name, mode): generalized implementation of GUI commands."""
    sel = FreeCADGui.Selection.getSelectionEx()

    FreeCAD.ActiveDocument.openTransaction("Create " + mode)
    FreeCADGui.addModule("BOPTools.JoinFeatures")
    FreeCADGui.doCommand(
        "j = BOPTools.JoinFeatures.make{mode}(name='{name}')".format(mode=mode, name=name)
    )
    if mode == "Embed" or mode == "Cutout":
        FreeCADGui.doCommand("j.Base = App.ActiveDocument." + sel[0].Object.Name)
        FreeCADGui.doCommand("j.Tool = App.ActiveDocument." + sel[1].Object.Name)
    elif mode == "Connect":
        FreeCADGui.doCommand(
            "j.Objects = {sel}".format(
                sel="[" + ", ".join(["App.ActiveDocument." + so.Object.Name for so in sel]) + "]"
            )
        )
    else:
        raise ValueError("cmdCreateJoinFeature: Unexpected mode {mode}".format(mode=repr(mode)))

    try:
        FreeCADGui.doCommand("j.Proxy.execute(j)")
        FreeCADGui.doCommand("j.purgeTouched()")
    except Exception as err:
        mb = QtGui.QMessageBox()
        mb.setIcon(mb.Icon.Warning)
        error_text1 = translate("Part_JoinFeatures", "Computing the result failed with an error:")
        error_text2 = translate(
            "Part_JoinFeatures",
            "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.",
        )
        mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2)
        mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None))
        btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort)
        btnOK = mb.addButton(
            translate("Part_JoinFeatures", "Continue", None),
            QtGui.QMessageBox.ButtonRole.ActionRole,
        )
        mb.setDefaultButton(btnOK)
        mb.exec_()

        if mb.clickedButton() is btnAbort:
            FreeCAD.ActiveDocument.abortTransaction()
            return

    FreeCADGui.doCommand(
        "for obj in j.ViewObject.Proxy.claimChildren():\n" "    obj.ViewObject.hide()"
    )

    FreeCAD.ActiveDocument.commitTransaction()


def getIconPath(icon_dot_svg):
    return icon_dot_svg


# -------------------------- /common stuff ------------------------------------

# -------------------------- Connect ------------------------------------------


def makeConnect(name):
    """makeConnect(name): makes an Connect object."""
    obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name)
    FeatureConnect(obj)
    if FreeCAD.GuiUp:
        ViewProviderConnect(obj.ViewObject)
    return obj


class FeatureConnect:
    """The PartJoinFeature object."""

    def __init__(self, obj):
        obj.addProperty(
            "App::PropertyLinkList", "Objects", "Connect", "Object to be connected.", locked=True
        )
        obj.addProperty(
            "App::PropertyBool",
            "Refine",
            "Connect",
            "True = refine resulting shape. False = output as is.",
            locked=True,
        )
        obj.Refine = getParamRefine()
        obj.addProperty(
            "App::PropertyLength",
            "Tolerance",
            "Connect",
            "Tolerance when intersecting (fuzzy value). "
            "In addition to tolerances of the shapes.",
            locked=True,
        )

        obj.Proxy = self
        self.Type = "FeatureConnect"

    def execute(self, selfobj):
        rst = JoinAPI.connect([obj.Shape for obj in selfobj.Objects], selfobj.Tolerance)
        if selfobj.Refine:
            rst = rst.removeSplitter()
        selfobj.Shape = rst


class ViewProviderConnect:
    """A View Provider for the Part Connect feature."""

    def __init__(self, vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/booleans/Part_JoinConnect.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def dumps(self):
        return None

    def loads(self, state):
        return None

    def claimChildren(self):
        return self.Object.Objects

    def onDelete(self, feature, subelements):
        try:
            for obj in self.claimChildren():
                obj.ViewObject.show()
        except Exception as err:
            FreeCAD.Console.PrintError("Error in onDelete: " + str(err))
        return True

    def canDragObjects(self):
        return True

    def canDropObjects(self):
        return True

    def canDragObject(self, dragged_object):
        return True

    def canDropObject(self, incoming_object):
        return hasattr(incoming_object, "Shape")

    def dragObject(self, selfvp, dragged_object):
        objs = self.Object.Objects
        objs.remove(dragged_object)
        self.Object.Objects = objs

    def dropObject(self, selfvp, incoming_object):
        self.Object.Objects = self.Object.Objects + [incoming_object]


class CommandConnect:
    """Command to create Connect feature."""

    def GetResources(self):
        return {
            "Pixmap": getIconPath("Part_JoinConnect.svg"),
            "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_JoinConnect", "Connect Shapes"),
            "Accel": "",
            "ToolTip": QtCore.QT_TRANSLATE_NOOP(
                "Part_JoinConnect", "Fuses shapes, taking care to preserve voids"
            ),
        }

    def Activated(self):
        if len(FreeCADGui.Selection.getSelectionEx()) >= 1:
            cmdCreateJoinFeature(name="Connect", mode="Connect")
        else:
            mb = QtGui.QMessageBox()
            mb.setIcon(mb.Icon.Warning)
            mb.setText(
                translate(
                    "Part_JoinFeatures",
                    "Select at least two objects, or one or more compounds",
                    None,
                )
            )
            mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None))
            mb.exec_()

    def IsActive(self):
        if FreeCAD.ActiveDocument:
            return True
        else:
            return False


# -------------------------- /Connect -----------------------------------------


# -------------------------- Embed --------------------------------------------


def makeEmbed(name):
    """makeEmbed(name): makes an Embed object."""
    obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name)
    FeatureEmbed(obj)
    if FreeCAD.GuiUp:
        ViewProviderEmbed(obj.ViewObject)
    return obj


class FeatureEmbed:
    """The Part Embed object."""

    def __init__(self, obj):
        obj.addProperty("App::PropertyLink", "Base", "Embed", "Object to embed into.", locked=True)
        obj.addProperty("App::PropertyLink", "Tool", "Embed", "Object to be embedded.", locked=True)
        obj.addProperty(
            "App::PropertyBool",
            "Refine",
            "Embed",
            "True = refine resulting shape. False = output as is.",
            locked=True,
        )
        obj.Refine = getParamRefine()
        obj.addProperty(
            "App::PropertyLength",
            "Tolerance",
            "Embed",
            "Tolerance when intersecting (fuzzy value). "
            "In addition to tolerances of the shapes.",
            locked=True,
        )

        obj.Proxy = self
        self.Type = "FeatureEmbed"

    def execute(self, selfobj):
        rst = JoinAPI.embed_legacy(selfobj.Base.Shape, selfobj.Tool.Shape, selfobj.Tolerance)
        if selfobj.Refine:
            rst = rst.removeSplitter()
        selfobj.Shape = rst


class ViewProviderEmbed:
    """A View Provider for the Part Embed feature."""

    def __init__(self, vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/booleans/Part_JoinEmbed.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def dumps(self):
        return None

    def loads(self, state):
        return None

    def claimChildren(self):
        return [self.Object.Base, self.Object.Tool]

    def onDelete(self, feature, subelements):
        try:
            self.Object.Base.ViewObject.show()
            self.Object.Tool.ViewObject.show()
        except Exception as err:
            FreeCAD.Console.PrintError("Error in onDelete: " + str(err))
        return True


class CommandEmbed:
    """Command to create Part Embed feature."""

    def GetResources(self):
        return {
            "Pixmap": getIconPath("Part_JoinEmbed.svg"),
            "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_JoinEmbed", "Embed Shapes"),
            "Accel": "",
            "ToolTip": QtCore.QT_TRANSLATE_NOOP(
                "Part_JoinEmbed", "Fuses one shape into another, taking care to preserve voids"
            ),
        }

    def Activated(self):
        if len(FreeCADGui.Selection.getSelectionEx()) == 2:
            cmdCreateJoinFeature(name="Embed", mode="Embed")
        else:
            mb = QtGui.QMessageBox()
            mb.setIcon(mb.Icon.Warning)
            mb.setText(
                translate(
                    "Part_JoinFeatures",
                    "Select base object, then the object to embed, and then invoke this tool.",
                    None,
                )
            )
            mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None))
            mb.exec_()

    def IsActive(self):
        if FreeCAD.ActiveDocument:
            return True
        else:
            return False


# -------------------------- /Embed -------------------------------------------


# -------------------------- Cutout -------------------------------------------


def makeCutout(name):
    """makeCutout(name): makes an Cutout object."""
    obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name)
    FeatureCutout(obj)
    if FreeCAD.GuiUp:
        ViewProviderCutout(obj.ViewObject)
    return obj


class FeatureCutout:
    """The Part Cutout object."""

    def __init__(self, obj):
        obj.addProperty("App::PropertyLink", "Base", "Cutout", "Object to be cut.", locked=True)
        obj.addProperty(
            "App::PropertyLink", "Tool", "Cutout", "Object to make cutout for.", locked=True
        )
        obj.addProperty(
            "App::PropertyBool",
            "Refine",
            "Cutout",
            "True = refine resulting shape. False = output as is.",
            locked=True,
        )
        obj.Refine = getParamRefine()
        obj.addProperty(
            "App::PropertyLength",
            "Tolerance",
            "Cutout",
            "Tolerance when intersecting (fuzzy value). In addition to tolerances of the shapes.",
            locked=True,
        )

        obj.Proxy = self
        self.Type = "FeatureCutout"

    def execute(self, selfobj):
        rst = JoinAPI.cutout_legacy(selfobj.Base.Shape, selfobj.Tool.Shape, selfobj.Tolerance)
        if selfobj.Refine:
            rst = rst.removeSplitter()
        selfobj.Shape = rst


class ViewProviderCutout:
    """A View Provider for the Part Cutout feature."""

    def __init__(self, vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/booleans/Part_JoinCutout.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def dumps(self):
        return None

    def loads(self, state):
        return None

    def claimChildren(self):
        return [self.Object.Base, self.Object.Tool]

    def onDelete(self, feature, subelements):
        try:
            self.Object.Base.ViewObject.show()
            self.Object.Tool.ViewObject.show()
        except Exception as err:
            FreeCAD.Console.PrintError("Error in onDelete: " + str(err))
        return True


class CommandCutout:
    """Command to create PartJoinFeature in Cutout mode."""

    def GetResources(self):
        return {
            "Pixmap": getIconPath("Part_JoinCutout.svg"),
            "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_JoinCutout", "Cutout Shape"),
            "Accel": "",
            "ToolTip": QtCore.QT_TRANSLATE_NOOP(
                "Part_JoinCutout", "Creates a cutout in the selected shape to fit another shape"
            ),
        }

    def Activated(self):
        if len(FreeCADGui.Selection.getSelectionEx()) == 2:
            cmdCreateJoinFeature(name="Cutout", mode="Cutout")
        else:
            mb = QtGui.QMessageBox()
            mb.setIcon(mb.Icon.Warning)
            mb.setText(
                translate(
                    "Part_JoinFeatures",
                    "Select the object to make a cutout in, then the object that should fit into the cutout, and then invoke this tool.",
                    None,
                )
            )
            mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None))
            mb.exec_()

    def IsActive(self):
        if FreeCAD.ActiveDocument:
            return True
        else:
            return False


# -------------------------- /Cutout ------------------------------------------


def addCommands():
    FreeCADGui.addCommand("Part_JoinCutout", CommandCutout())
    FreeCADGui.addCommand("Part_JoinEmbed", CommandEmbed())
    FreeCADGui.addCommand("Part_JoinConnect", CommandConnect())