Debian Codegraph @

src/Base/Tools.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25
26 #ifndef SRC_BASE_TOOLS_H_
27 #define SRC_BASE_TOOLS_H_
28
29 #ifndef FC_GLOBAL_H
30 # include <FCGlobal.h>
31 #endif
32 #include <cmath>
33 #include <numbers>
34 #include <ostream>
35 #include <string>
36 #include <vector>
37
38 #include <boost/signals2/shared_connection_block.hpp>
39
40 namespace boost
41 {
42 namespace signals2
43 {
44 class connection;
45 }
46 } // namespace boost
47
48
49 class QString;
50
51 namespace Base
52 {
53
54 template<class T>
55 struct iotaGen
56 {
57 public:
58 T operator()()
59 {
60 return n++;
61 }
62 explicit iotaGen(T v)
63 : n(v)
64 {}
65
66 private:
67 T n;
68 };
69
70 // ----------------------------------------------------------------------------
71
72 template<class T>
73 class manipulator
74 {
75 T i_;
76 std::ostream& (*f_)(std::ostream&, T);
77
78 public:
79 manipulator(std::ostream& (*f)(std::ostream&, T), T i)
80 : i_(i)
81 , f_(f)
82 {}
83 friend std::ostream& operator<<(std::ostream& os, manipulator m)
84 {
85 return m.f_(os, m.i_);
86 }
87 };
88
89 inline std::ostream& tabsN(std::ostream& os, int n)
90 {
91 for (int i = 0; i < n; i++) {
92 os << "\t";
93 }
94 return os;
95 }
96
97 inline std::ostream& blanksN(std::ostream& os, int n)
98 {
99 for (int i = 0; i < n; i++) {
100 os << " ";
101 }
102 return os;
103 }
104
105 inline manipulator<int> tabs(int n)
106 {
107 return {&tabsN, n};
108 }
109
110 inline manipulator<int> blanks(int n)
111 {
112 return {&blanksN, n};
113 }
114
115 // ----------------------------------------------------------------------------
116
117 template<class T>
118 requires std::is_arithmetic_v<T>
119 inline T clamp(T num, T lower, T upper)
120 {
121 return std::clamp<T>(num, lower, upper);
122 }
123
124 /// Returns -1, 0 or 1 depending on if the value is negative, zero or positive
125 /// As this function might be used in hot paths, it uses branchless implementation
126 template<typename T>
127 constexpr std::enable_if_t<std::is_arithmetic_v<T> && std::is_signed_v<T>, T> sgn(T val)
128 {
129 int oneIfPositive = int(0 < val);
130 int oneIfNegative = int(val < 0);
131 return T(oneIfPositive - oneIfNegative); // 0/1 - 0/1 = -1/0/1
132 }
133
134 /// Convert degrees to radians, allow deduction for floating point types
135 template<std::floating_point T>
136 constexpr T toRadians(T degrees)
137 {
138 constexpr auto degToRad = std::numbers::pi_v<T> / T(180);
139 return degrees * degToRad;
140 }
141
142 /// Convert degrees to radians, allow **explicit-only** for any arithmetic type
143 template<typename T>
144 requires(std::is_arithmetic_v<T> && !std::floating_point<T>)
145 constexpr T toRadians(std::type_identity_t<T> degrees)
146 {
147 using ResultT = std::conditional_t<std::is_integral_v<T>, double, T>;
148 return static_cast<T>(toRadians<ResultT>(static_cast<ResultT>(degrees)));
149 }
150
151 /// Convert radians to degrees, allow deduction for floating point types
152 template<std::floating_point T>
153 constexpr T toDegrees(T radians)
154 {
155 constexpr auto radToDeg = T(180) / std::numbers::pi_v<T>;
156 return radians * radToDeg;
157 }
158
159 /// Convert radians to degrees, allow **explicit-only** for any arithmetic type
160 template<typename T>
161 requires(std::is_arithmetic_v<T> && !std::floating_point<T>)
162 constexpr T toDegrees(std::type_identity_t<T> radians)
163 {
164 using ResultT = std::conditional_t<std::is_integral_v<T>, double, T>;
165 return static_cast<T>(toDegrees<ResultT>(static_cast<ResultT>(radians)));
166 }
167
168 inline float fromPercent(const long value)
169 {
170 return std::roundf(static_cast<float>(value)) / 100.0F;
171 }
172
173 inline long toPercent(float value)
174 {
175 return std::lround(100.0 * value);
176 }
177
178 template<std::floating_point T>
179 inline T fmod(T numerator, T denominator)
180 {
181 T modulo = std::fmod(numerator, denominator);
182 return (modulo >= T(0)) ? modulo : modulo + denominator;
183 }
184
185 template<std::floating_point T>
186 inline T angularDist(T v1, T v2)
187 {
188 return std::min(std::fabs(v1 - v2), 360 - std::fabs(v1 - v2));
189 }
190
191 // Returns a value between [0, 360) or (-180, 180] depending on if the
192 // minimum value was positive or negetive. This is done because the taper angle
193 // values in FreeCAD usually treat values like -10 and 350 differently
194 template<std::floating_point T>
195 inline double clampAngle(T value, T min, T max, T precision)
196 {
197 // Normalize the angles between 0 and 360
198 value = Base::fmod(value, 360.0);
199 T nMin = Base::fmod(min, 360.0);
200 T nMax = Base::fmod(max, 360.0);
201
202 if (std::abs(nMax - nMin) > precision) {
203 if (nMax > nMin) {
204 if (value < nMin || value > nMax) {
205 value = angularDist(value, nMin) > angularDist(value, nMax) ? nMax : nMin;
206 }
207 }
208 else {
209 if (value < nMin && value > nMax) {
210 value = angularDist(value, nMin) > angularDist(value, nMax) ? nMax : nMin;
211 }
212 }
213 }
214
215 if (min >= 0.0) {
216 // Return in [0, 360)
217 return value;
218 }
219
220 // Map to (-180, 180]
221 if (value > 180.0) {
222 value = value - 360;
223 }
224 return value;
225 }
226
227
228 // ----------------------------------------------------------------------------
229
230 // NOLINTBEGIN
231 template<typename Flag = bool>
232 struct FlagToggler
233 {
234
235 Flag& flag;
236 bool toggled;
237
238 FlagToggler(Flag& _flag)
239 : flag(_flag)
240 , toggled(true)
241 {
242 flag = !flag;
243 }
244
245 FlagToggler(Flag& _flag, Flag check)
246 : flag(_flag)
247 , toggled(check == _flag)
248 {
249 if (toggled) {
250 flag = !flag;
251 }
252 }
253
254 ~FlagToggler()
255 {
256 if (toggled) {
257 flag = !flag;
258 }
259 }
260 };
261
262 // ----------------------------------------------------------------------------
263
264 template<typename Status, class Object>
265 class ObjectStatusLocker
266 {
267 public:
268 ObjectStatusLocker(Status s, Object* o, bool value = true)
269 : status(s)
270 , obj(o)
271 {
272 old_value = obj->testStatus(status);
273 obj->setStatus(status, value);
274 }
275 ~ObjectStatusLocker()
276 {
277 obj->setStatus(status, old_value);
278 }
279
280 private:
281 Status status;
282 Object* obj;
283 bool old_value;
284 };
285
286 // ----------------------------------------------------------------------------
287
288 class StateLocker
289 {
290 public:
291 StateLocker(bool& flag, bool value = true)
292 : lock(flag)
293 {
294 old_value = lock;
295 lock = value;
296 } // NOLINT
297 ~StateLocker()
298 {
299 lock = old_value;
300 }
301
302 private:
303 bool& lock;
304 bool old_value;
305 };
306
307 // ----------------------------------------------------------------------------
308
309 template<typename T>
310 class BitsetLocker
311 {
312 public:
313 BitsetLocker(T& flags, std::size_t flag, bool value = true)
314 : flags(flags)
315 , flag(flag)
316 {
317 oldValue = flags.test(flag);
318 flags.set(flag, value);
319 }
320 ~BitsetLocker()
321 {
322 flags.set(flag, oldValue);
323 }
324
325 private:
326 T& flags;
327 std::size_t flag;
328 bool oldValue;
329 };
330
331 // ----------------------------------------------------------------------------
332
333 class ConnectionBlocker
334 {
335 using Connection = boost::signals2::connection;
336 using ConnectionBlock = boost::signals2::shared_connection_block;
337 ConnectionBlock blocker;
338
339 public:
340 ConnectionBlocker(Connection& c)
341 : blocker(c)
342 {}
343 ~ConnectionBlocker() = default;
344 };
345 // NOLINTEND
346
347 // ----------------------------------------------------------------------------
348
349 struct BaseExport Tools
350 {
351 /**
352 * Given an arbitrary string, ensure that it conforms to Python3 identifier rules, replacing
353 * invalid characters with an underscore. If the first character is invalid, prepends an
354 * underscore to the name. See https://unicode.org/reports/tr31/ for complete naming rules.
355 * @param String to be checked and sanitized.
356 * @return A std::string that is a valid Python 3 identifier.
357 */
358 static std::string getIdentifier(const std::string& name);
359 static std::wstring widen(const std::string& str);
360 static std::string narrow(const std::wstring& str);
361 static std::string escapedUnicodeFromUtf8(const char* s);
362 static std::string escapedUnicodeToUtf8(const std::string& s);
363 static std::string escapeQuotesFromString(const std::string& s);
364
365 static QString escapeEncodeString(const QString& s);
366 static std::string escapeEncodeString(const std::string& s);
367 static QString escapeEncodeFilename(const QString& s);
368 static std::string escapeEncodeFilename(const std::string& s);
369
370 /**
371 * @brief quoted Creates a quoted string.
372 * @param String to be quoted.
373 * @return A quoted std::string.
374 */
375 static std::string quoted(const char*);
376 /**
377 * @brief quoted Creates a quoted string.
378 * @param String to be quoted.
379 * @return A quoted std::string.
380 */
381 static std::string quoted(const std::string&);
382
383 static constexpr bool isNullOrEmpty(const char* str)
384 {
385 return !str || str[0] == '\0';
386 }
387
388 /**
389 * @brief joinList
390 * Join the vector of strings \a vec using the separator \a sep
391 * @param vec
392 * @param sep
393 * @return
394 */
395 static std::string joinList(const std::vector<std::string>& vec, const std::string& sep = ", ");
396
397 static std::string currentDateTimeString();
398
399 static std::vector<std::string> splitSubName(const std::string& subname);
400 };
401
402 struct BaseExport ZipTools
403 {
404 /**
405 * @brief rewrite Rewrite a zip file under a new name.
406 */
407 static void rewrite(const std::string& source, const std::string& target);
408 };
409
410
411 /**
412 * Helper struct to define inline overloads for the visitor pattern in std::visit.
413 *
414 * It uses type deduction to infer the type from the expression and creates a dedicated type that
415 * essentially is callable using any overload supplied.
416 *
417 * @code
418 * using Base::Overloads;
419 *
420 * const auto visitor = Overloads
421 * {
422 * [](int i){ std::print("int = {}\n", i); },
423 * [](std::string_view s){ std::println("string = “{}”", s); },
424 * [](const Base&){ std::println("base"); },
425 * };
426 * @endcode
427 *
428 * @see https://en.cppreference.com/w/cpp/utility/variant/visit
429 *
430 * @tparam Ts Types for functions that will be used for overloads
431 */
432 template<class... Ts>
433 struct Overloads: Ts...
434 {
435 using Ts::operator()...;
436 };
437
438 template<class... Ts>
439 Overloads(Ts...) -> Overloads<Ts...>;
440
441 } // namespace Base
442
443
444 #endif // SRC_BASE_TOOLS_H_