File size: 15,184 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: LGPL-2.1-or-later

# ***************************************************************************
# *   Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net>        *
# *   Copyright (c) 2009, 2010 Ken Cline <cline@frii.com>                   *
# *   Copyright (c) 2020 FreeCAD Developers                                 *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   This program 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 program; if not, write to the Free Software   *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************
"""Provides the object code for the ShapeString object."""
## @package shapestring
# \ingroup draftobjects
# \brief Provides the object code for the ShapeString object.

## \addtogroup draftobjects
# @{
import os
import math
from PySide.QtCore import QT_TRANSLATE_NOOP

import FreeCAD as App
import Part
from draftgeoutils import faces
from draftobjects.base import DraftObject
from draftutils import gui_utils
from draftutils.messages import _err, _log
from draftutils.translate import translate


class ShapeString(DraftObject):
    """The ShapeString object"""

    def __init__(self, obj):
        super().__init__(obj, "ShapeString")
        self.set_properties(obj)

    def set_properties(self, obj):
        """Add properties to the object and set them."""
        properties = obj.PropertiesList

        if "String" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Text string")
            obj.addProperty("App::PropertyString", "String", "Draft", _tip, locked=True)

        if "FontFile" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Font file name")
            obj.addProperty("App::PropertyFile", "FontFile", "Draft", _tip, locked=True)

        if "Size" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Height of text")
            obj.addProperty("App::PropertyLength", "Size", "Draft", _tip, locked=True)

        if "Justification" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Horizontal and vertical alignment")
            obj.addProperty("App::PropertyEnumeration", "Justification", "Draft", _tip, locked=True)
            obj.Justification = [
                "Top-Left",
                "Top-Center",
                "Top-Right",
                "Middle-Left",
                "Middle-Center",
                "Middle-Right",
                "Bottom-Left",
                "Bottom-Center",
                "Bottom-Right",
            ]
            obj.Justification = "Bottom-Left"

        if "JustificationReference" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Height reference used for justification")
            obj.addProperty(
                "App::PropertyEnumeration", "JustificationReference", "Draft", _tip, locked=True
            )
            obj.JustificationReference = ["Cap Height", "Shape Height"]
            obj.JustificationReference = "Cap Height"

        if "KeepLeftMargin" not in properties:
            _tip = QT_TRANSLATE_NOOP(
                "App::Property",
                "Keep left margin and leading white space when justification is left",
            )
            obj.addProperty(
                "App::PropertyBool", "KeepLeftMargin", "Draft", _tip, locked=True
            ).KeepLeftMargin = False

        if "ScaleToSize" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Scale to ensure cap height is equal to size")
            obj.addProperty(
                "App::PropertyBool", "ScaleToSize", "Draft", _tip, locked=True
            ).ScaleToSize = True

        if "Tracking" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Inter-character spacing")
            obj.addProperty("App::PropertyDistance", "Tracking", "Draft", _tip, locked=True)

        if "ObliqueAngle" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Oblique (slant) angle")
            obj.addProperty("App::PropertyAngle", "ObliqueAngle", "Draft", _tip, locked=True)

        if "MakeFace" not in properties:
            _tip = QT_TRANSLATE_NOOP("App::Property", "Fill letters with faces")
            obj.addProperty(
                "App::PropertyBool", "MakeFace", "Draft", _tip, locked=True
            ).MakeFace = True

        if "Fuse" not in properties:
            _tip = QT_TRANSLATE_NOOP(
                "App::Property",
                "Fuse faces if faces overlap, usually not required (can be very slow)",
            )
            obj.addProperty("App::PropertyBool", "Fuse", "Draft", _tip, locked=True).Fuse = False

    def onDocumentRestored(self, obj):
        super().onDocumentRestored(obj)
        gui_utils.restore_view_object(
            obj, vp_module="view_shapestring", vp_class="ViewProviderShapeString"
        )
        if not hasattr(obj, "ObliqueAngle"):  # several more properties were added
            self.update_properties_1v0(obj)

    def update_properties_1v0(self, obj):
        """Update view properties."""
        old_tracking = obj.Tracking  # no need for obj.getTypeIdOfProperty("Tracking")
        obj.removeProperty("Tracking")
        self.set_properties(obj)
        obj.KeepLeftMargin = True
        obj.ScaleToSize = False
        obj.Tracking = old_tracking
        _log(
            "v1.0, "
            + obj.Name
            + ", "
            + "added 'Fuse', 'Justification', 'JustificationReference', 'KeepLeftMargin', "
            + "'ObliqueAngle' and 'ScaleToSize' properties"
        )
        _log("v1.0, " + obj.Name + ", changed 'Tracking' property type")

    def execute(self, obj):
        if self.props_changed_placement_only() or not obj.String or not obj.FontFile:
            obj.positionBySupport()
            self.props_changed_clear()
            return

        if obj.FontFile[0] == ".":
            # FontFile path relative to the FreeCAD file directory.
            font_file = os.path.join(os.path.dirname(obj.Document.FileName), obj.FontFile)
            # We need the absolute path to do some file checks.
            font_file = os.path.abspath(font_file)
        else:
            font_file = obj.FontFile

        # File checks:
        if not os.path.exists(font_file):
            _err(obj.Label + ": " + translate("draft", "Font file not found"))
            self.props_changed_clear()
            return
        if not os.path.isfile(font_file):
            _err(obj.Label + ": " + translate("draft", "Specified font file is not a file"))
            self.props_changed_clear()
            return
        if not os.path.splitext(font_file)[1].lower() in (".ttc", ".ttf", ".otf", ".pfb"):
            _err(obj.Label + ": " + translate("draft", "Specified font type is not supported"))
            self.props_changed_clear()
            return

        plm = obj.Placement
        fill = obj.MakeFace
        if fill is True:
            # Test a simple letter to know if we have a sticky font or not.
            # If the font is sticky change fill to `False`.
            # The 0.03 total area minimum is based on tests with:
            # 1CamBam_Stick_0.ttf and 1CamBam_Stick_0C.ttf.
            # See the make_faces function for more information.
            char = Part.makeWireString("L", font_file, 1, 0)[0]
            shapes = self.make_faces(char)  # char is list of wires
            if not shapes:
                fill = False
            else:
                # Depending on the font the size of char can be very small.
                # For the area check to make sense we need to use a scale factor.
                # https://github.com/FreeCAD/FreeCAD/issues/21501
                char_comp = Part.Compound(char)
                factor = 1 / char_comp.BoundBox.YLength
                fill = sum([shape.Area for shape in shapes]) > (0.03 / factor**2) and math.isclose(
                    char_comp.BoundBox.DiagonalLength,
                    Part.Compound(shapes).BoundBox.DiagonalLength,
                    rel_tol=1e-7,
                )

        chars = Part.makeWireString(obj.String, font_file, obj.Size, obj.Tracking)
        shapes = []

        for char in chars:
            if fill is False:
                shapes.extend(char)
            elif char:
                shapes.extend(self.make_faces(char))
        if shapes:
            if fill and obj.Fuse:
                ss_shape = shapes[0].fuse(shapes[1:])
                ss_shape = faces.concatenate(ss_shape)
                # Concatenate returns a Face or a Compound. We always
                # need a Compound as we use ss_shape.SubShapes later.
                if ss_shape.ShapeType == "Face":
                    ss_shape = Part.Compound([ss_shape])
            else:
                ss_shape = Part.Compound(shapes)
            cap_char = Part.makeWireString("M", font_file, obj.Size, obj.Tracking)[0]
            cap_height = Part.Compound(cap_char).BoundBox.YMax
            if obj.ScaleToSize:
                ss_shape.scale(obj.Size / cap_height)
                cap_height = obj.Size
            if obj.ObliqueAngle:
                if -80 <= obj.ObliqueAngle <= 80:
                    mtx = App.Matrix()
                    mtx.A12 = math.tan(math.radians(obj.ObliqueAngle))
                    ss_shape = ss_shape.transformGeometry(mtx)
                else:
                    wrn = (
                        translate(
                            "draft",
                            "ShapeString: oblique angle must be in the -80 to +80 degree range",
                        )
                        + "\n"
                    )
                    App.Console.PrintWarning(wrn)
            just_vec = self.justification_vector(
                ss_shape,
                cap_height,
                obj.Justification,
                obj.JustificationReference,
                obj.KeepLeftMargin,
            )
            shapes = ss_shape.SubShapes
            for shape in shapes:
                shape.translate(just_vec)
            obj.Shape = Part.Compound(shapes)
        else:
            App.Console.PrintWarning(translate("draft", "ShapeString: string has no wires") + "\n")

        obj.Placement = plm
        obj.positionBySupport()
        self.props_changed_clear()

    def onChanged(self, obj, prop):
        self.props_changed_store(prop)

    def justification_vector(
        self, ss_shape, cap_height, just, just_ref, keep_left_margin
    ):  # ss_shape is a compound
        box = ss_shape.optimalBoundingBox()
        if keep_left_margin is True and "Left" in just:
            vec = App.Vector(0, 0, 0)
        else:
            vec = App.Vector(
                -box.XMin, 0, 0
            )  # remove left margin caused by kerning and white space characters
        width = box.XLength
        if "Shape" in just_ref:
            vec = vec + App.Vector(0, -box.YMin, 0)
            height = box.YLength
        else:
            height = cap_height
        if "Top" in just:
            vec = vec + App.Vector(0, -height, 0)
        elif "Middle" in just:
            vec = vec + App.Vector(0, -height / 2, 0)
        if "Right" in just:
            vec = vec + App.Vector(-width, 0, 0)
        elif "Center" in just:
            vec = vec + App.Vector(-width / 2, 0, 0)
        return vec

    def make_faces(self, wireChar):
        wrn = translate("draft", "ShapeString: face creation failed for one character") + "\n"

        wirelist = []
        for w in wireChar:
            compEdges = Part.Compound(w.Edges)
            compEdges = compEdges.connectEdgesToWires()
            if compEdges.Wires[0].isClosed():
                wirelist.append(compEdges.Wires[0])

        if not wirelist:
            App.Console.PrintWarning(wrn)
            return []

        # Some test fonts:
        # https://raw.githubusercontent.com/FreeCAD/FPA/main/images/freecad_logo_official.svg
        #     https://evolventa.github.io/
        #     not a problem font, but it is used by FreeCAD
        # https://forum.freecad.org/viewtopic.php?t=57774
        #     https://www.dafont.com/mutlu-ornamental.font
        # https://forum.freecad.org/viewtopic.php?t=65110&p=559810#p559886
        #     http://www.atelier-des-fougeres.fr/Cambam/Aide/Plugins/stickfonts.html

        # 1CamBam_Stick_0.ttf is actually not a stick font.

        # FaceMakerBullseye:
        #     1CamBam_Stick_0.ttf face validation problem with A, E, F, H, K, R, Y and y.
        # FaceMakerCheese:
        #     1CamBam_Stick_0.ttf face creation problem with: A, E, F, H, Q, R, e and y.
        #     All fonts: face creation problem in case of double-nested wires f.e. with: ©.
        # FaceMakerSimple:
        #     All fonts: overlapping faces in case of nested wires f.e. with: O.
        try:
            # print("try Bullseye")
            faces = Part.makeFace(wirelist, "Part::FaceMakerBullseye").Faces
            for face in faces:
                face.validate()
        except Part.OCCError:
            try:
                # print("try Cheese")
                faces = Part.makeFace(wirelist, "Part::FaceMakerCheese").Faces
                for face in faces:
                    face.validate()
            except Part.OCCError:
                try:
                    # print("try Simple")
                    faces = Part.makeFace(wirelist, "Part::FaceMakerSimple").Faces
                    for face in faces:
                        face.validate()
                except Part.OCCError:
                    App.Console.PrintWarning(wrn)
                    return []

        for face in faces:
            try:
                # some fonts fail here
                if face.normalAt(0, 0).z < 0:  # Does not seem to occur for FaceMakerBullseye.
                    face.reverse()
            except Exception:
                pass

        return faces


# Alias for compatibility with v0.18 and earlier
_ShapeString = ShapeString

## @}