Debian Codegraph @

src/Gui/StyleParameters/ParameterManager.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /****************************************************************************
3 * *
4 * Copyright (c) 2025 Kacper Donat <[email protected]> *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 ***************************************************************************/
23
24 #ifndef STYLEPARAMETERS_PARAMETERMANAGER_H
25 #define STYLEPARAMETERS_PARAMETERMANAGER_H
26
27 #include <list>
28 #include <map>
29 #include <optional>
30 #include <set>
31 #include <string>
32 #include <vector>
33
34 #include <QColor>
35
36 #include <App/Application.h>
37 #include <Base/Bitmask.h>
38 #include <Base/Parameter.h>
39
40 // That macro uses inline const because some older compilers to not properly support constexpr
41 // for std::string. It should be changed into static constepxr once we migrate to newer compiler.
42 #define DEFINE_STYLE_PARAMETER(_name_, _defaultValue_) \
43 static inline const Gui::StyleParameters::ParameterDefinition _name_ \
44 { \
45 .name = #_name_, .defaultValue = (_defaultValue_), \
46 }
47
48 namespace Gui::StyleParameters
49 {
50
51 // Forward declaration for Parser
52 class Parser;
53
54 /**
55 * @brief Represents a length in a specified unit.
56 *
57 * This struct is a very simplified representation of lengths that can be used as parameters for
58 * styling purposes. The length basically consists of value and unit. Unit is optional, empty unit
59 * represents a dimensionless length that can be used as a scalar. This struct does not care about
60 * unit conversions as its uses do not require it.
61 */
62 struct Numeric
63 {
64 /// Numeric value of the length.
65 double value;
66 /// Unit of the length, empty if the value is dimensionless.
67 std::string unit = "";
68
69 /**
70 * @name Operators
71 *
72 * This struct supports basic operations on Length. Each operation requires for operands to be
73 * the same unit. Multiplication and division additionally allow one operand to be dimensionless
74 * and hence act as a scalar.
75 *
76 * @code{c++}
77 * Numeric a { 10, "px" };
78 * Numeric b { 5, "px" };
79 *
80 * Numeric differentUnit { 3, "rem" }
81 * Numeric scalar { 2, "" };
82 *
83 * // basic operations with the same unit are allowed
84 * auto sum = a + b; // 15 px
85 * auto difference = a - 5; // 10 px
86 *
87 * // basic operations with mixed units are NOT allowed
88 * auto sumOfIncompatibleUnits = a + differentUnit; // will throw
89 * auto productOfIncompatibleUnits = a * differentUnit; // will throw
90 *
91 * // exception is that for multiplication and division dimensionless units are allowed
92 * auto productWithScalar = a * scalar; // 20 px
93 * @endcode
94 * @{
95 */
96 Numeric operator+(const Numeric& rhs) const;
97 Numeric operator-(const Numeric& rhs) const;
98 Numeric operator-() const;
99
100 Numeric operator/(const Numeric& rhs) const;
101 Numeric operator*(const Numeric& rhs) const;
102 /// @}
103
104 private:
105 void ensureEqualUnits(const Numeric& rhs) const;
106 };
107
108 /**
109 * @brief This struct represents any valid value that can be used as the parameter value.
110 *
111 * The value can be one of three basic types:
112 * - Numbers / Lengths (so any length with optional unit) (Length)
113 * - Colors (QColor)
114 * - Any other generic expression. (std::string)
115 *
116 * As a rule, operations can be only performed over values of the same type.
117 */
118 struct Value: std::variant<Numeric, Base::Color, std::string>
119 {
120 using std::variant<Numeric, Base::Color, std::string>::variant;
121
122 /**
123 * Converts the object into its string representation.
124 *
125 * @return A string representation of the object that can later be used in QSS.
126 */
127 std::string toString() const;
128 };
129
130 /**
131 * @brief A structure to define parameters which can be referenced in the code.
132 *
133 * @tparam T The type of the parameter.
134 *
135 * This structure allows defining parameters which encapsulate a name and a corresponding
136 * default value. Parameters defined this way can be reused across the codebase for consistency.
137 * The supported value types include:
138 * - Numeric types.
139 * - Colors using `Base::Color`.
140 * - Strings.
141 *
142 * Example Usage:
143 * @code{.cpp}
144 * DEFINE_STYLE_PARAMETER(SomeParameter, Numeric { 10 });
145 * DEFINE_STYLE_PARAMETER(TextColor, Base::Color(0.5F, 0.2F, 0.8F));
146 * @endcode
147 */
148 template<typename T>
149 struct ParameterDefinition
150 {
151 /// The name of the parameter, must be unique.
152 const char* name;
153 /// The default value of the parameter.
154 T defaultValue;
155 };
156
157 /**
158 * @struct Parameter
159 *
160 * @brief Represents a named, dynamic expression-based parameter.
161 *
162 * The Parameter structure is used to define reusable named variables in styling or layout systems.
163 * Each parameter consists of a `name` and a `value` string, where the value is a CSS-like
164 * expression that supports numbers, units, arithmetic, colors, functions, and parameter references.
165 *
166 * ### Naming Convention
167 * Parameter names must be unique and follow **CamelCase**.
168 */
169 struct Parameter
170 {
171 /// Comparator that assumes that parameters are equal as long as name is the same
172 struct NameComparator
173 {
174 bool operator()(const Parameter& lhs, const Parameter& rhs) const
175 {
176 return lhs.name < rhs.name;
177 }
178 };
179
180 /// Name of the parameter, name should follow CamelCase
181 std::string name;
182 /// Expression associated with the parameter
183 std::string value;
184 };
185
186 enum class ParameterSourceOption
187 {
188 // clang-format off
189 /// Parameters are read-only and the source does not allow editing
190 ReadOnly = 1 << 0,
191 /// Parameters are expected to be edited by the user, not only theme developers
192 UserEditable = 1 << 1,
193 // clang-format on
194 };
195
196 using ParameterSourceOptions = Base::Flags<ParameterSourceOption>;
197
198 /**
199 * @brief Abstract base class representing a source of style parameters.
200 *
201 * A `ParameterSource` is responsible for managing a collection of named parameters. Each source
202 * has metadata describing its type, characteristics, and behavior.
203 *
204 * ### Key Responsibilities
205 * - Define, update, and remove parameters within the source.
206 * - Provide access to all parameters or specific ones by name.
207 * - Act as a backend for parameter management, feeding the `ParameterManager` with available
208 * parameter data.
209 *
210 * ### Metadata
211 * Each parameter source includes metadata consisting of:
212 * - `name`: Name of the source, for identification purposes.
213 * - `options`: Flags specifying optional behavior (e.g., `ReadOnly`, `UserEditable`).
214 *
215 * ### Notes on Usage
216 * - Subclasses of `ParameterSource` (e.g., `BuiltInParameterSource`, `UserParameterSource`)
217 * implement different storage mechanisms and behaviors based on whether parameters are
218 * pre-defined, user-defined, or loaded in memory.
219 * - Parameters can be retrieved and manipulated globally through the `ParameterManager`, which
220 * aggregates multiple `ParameterSource` instances.
221 *
222 * #### Example
223 * @code{.cpp}
224 * // Create an in-memory parameter source
225 * InMemoryParameterSource source({
226 * Parameter{ "BasePadding", "16px" },
227 * Parameter{ "DefaultColor", "#ff00ff" },
228 * });
229 *
230 * source.define(Parameter{ "Margin", "4px" }); // Adds a new parameter
231 *
232 * auto padding = source.get("BasePadding"); // Retrieves parameter named "BasePadding"
233 * auto parametersList = source.all(); // Retrieve all parameters
234 * @endcode
235 *
236 * ### Subclass Requirements
237 * Derived classes must implement:
238 * - `all()` - Retrieve all parameters in the source.
239 * - `get()` - Retrieve a specific parameter.
240 * - `define()` - Add or update a parameter, can be left empty for readonly sources.
241 * - `remove()` - Remove a parameter by name, can be left empty for readonly sources.
242 */
243 class GuiExport ParameterSource
244 {
245 public:
246 using enum ParameterSourceOption;
247
248 /**
249 * @brief Contains metadata information about a `ParameterSource`.
250 *
251 * The `Metadata` struct provides a way to describe the characteristics and identity
252 * of a `ParameterSource`. It includes a name for identification and a set of options
253 * that define the source's behavior and restrictions.
254 */
255 struct Metadata
256 {
257 /// The name of the parameter source. Should be marked for translation using QT_TR_NOOP
258 std::string name;
259 /// Flags defining the behavior and properties of the parameter source.
260 ParameterSourceOptions options {};
261 };
262
263 /// Metadata of the parameter source
264 Metadata metadata;
265
266 FC_DEFAULT_MOVE(ParameterSource);
267 FC_DISABLE_COPY(ParameterSource);
268
269 explicit ParameterSource(const Metadata& metadata);
270 virtual ~ParameterSource() = default;
271
272 /**
273 * @brief Retrieves a list of all parameters available in the source.
274 *
275 * This method returns every parameter defined within this source, enabling iteration and bulk
276 * access to all stored values.
277 *
278 * @return A list containing all `Parameter` objects stored in the source.
279 */
280 virtual std::list<Parameter> all() const = 0;
281
282 /**
283 * @brief Retrieves a specific parameter by its name.
284 *
285 * @param[in] name The name of the parameter to retrieve.
286 * @return An optional containing the requested parameter if it exists, or empty if not.
287 */
288 virtual std::optional<Parameter> get(const std::string& name) const = 0;
289
290 /**
291 * @brief Defines or updates a parameter in the source.
292 *
293 * Adds a new parameter to the source if it doesn't already exist or updates the value of an
294 * existing parameter with the same name.
295 *
296 * @param[in] parameter The `Parameter` object to define or update in the source.
297 */
298 virtual void define([[maybe_unused]] const Parameter& parameter)
299 {}
300
301 /**
302 * @brief Removes a parameter from the source by its name.
303 *
304 * Deletes the specific parameter from the source if it exists. If no parameter with the given
305 * name is found, the method does nothing.
306 *
307 * @param[in] name The name of the parameter to remove.
308 */
309 virtual void remove([[maybe_unused]] const std::string& name)
310 {}
311
312 /**
313 * @brief Flushes buffered changes into more persistent storage.
314 */
315 virtual void flush()
316 {}
317 };
318
319 /**
320 * @brief In-memory parameter source that stores parameters in a map.
321 *
322 * This source is useful for temporary parameter storage or when you need to
323 * define parameters programmatically without persisting them to disk.
324 */
325 class GuiExport InMemoryParameterSource: public ParameterSource
326 {
327 std::map<std::string, Parameter> parameters;
328
329 public:
330 InMemoryParameterSource(const std::list<Parameter>& parameters, const Metadata& metadata);
331
332 std::list<Parameter> all() const override;
333 std::optional<Parameter> get(const std::string& name) const override;
334 void define(const Parameter& parameter) override;
335 void remove(const std::string& name) override;
336 };
337
338 /**
339 * @brief Built-in parameter source that reads from FreeCAD's parameter system.
340 *
341 * This source provides access to predefined parameters that are stored in
342 * FreeCAD's global parameter system. These parameters are typically defined
343 * by the application and are read-only.
344 */
345 class GuiExport BuiltInParameterSource: public ParameterSource
346 {
347 public:
348 explicit BuiltInParameterSource(const Metadata& metadata = {});
349
350 std::list<Parameter> all() const override;
351 std::optional<Parameter> get(const std::string& name) const override;
352
353 private:
354 ParameterGrp::handle hGrpThemes = App::GetApplication().GetParameterGroupByPath(
355 "User parameter:BaseApp/Preferences/Themes"
356 );
357 ParameterGrp::handle hGrpView = App::GetApplication().GetParameterGroupByPath(
358 "User parameter:BaseApp/Preferences/View"
359 );
360
361 std::map<std::string, ParameterGrp::handle> params = {
362 {"ThemeAccentColor1", hGrpThemes},
363 {"ThemeAccentColor2", hGrpThemes},
364 {"ThemeAccentColor3", hGrpThemes},
365 {"BackgroundColor", hGrpView},
366 };
367 };
368
369 /**
370 * @brief User-defined parameter source that reads from user preferences.
371 *
372 * This source provides access to user-defined parameters that are stored
373 * in the user's preference file. These parameters can be modified by the
374 * user and persist across application sessions.
375 */
376 class GuiExport UserParameterSource: public ParameterSource
377 {
378 ParameterGrp::handle hGrp;
379
380 public:
381 UserParameterSource(ParameterGrp::handle hGrp, const Metadata& metadata);
382
383 std::list<Parameter> all() const override;
384 std::optional<Parameter> get(const std::string& name) const override;
385 void define(const Parameter& parameter) override;
386 void remove(const std::string& name) override;
387 };
388
389 /**
390 * @class YamlParameterSource
391 * @brief A ParameterSource implementation that loads and saves parameters
392 * from a YAML file using yaml-cpp.
393 *
394 * This class maintains an in-memory map of parameters loaded from a YAML file.
395 * Any changes through define() or remove() will also update the file.
396 */
397 class GuiExport YamlParameterSource: public ParameterSource
398 {
399 public:
400 /**
401 * @brief Constructs a YamlParameterSource that reads parameters from the given YAML file.
402 *
403 * If the file exists, all key-value pairs are loaded into memory.
404 * If the file does not exist, an empty parameter set is initialized.
405 *
406 * @param filePath Path to the YAML file used for persistence.
407 * @param metadata Optional metadata describing this source.
408 */
409 explicit YamlParameterSource(const std::string& filePath, const Metadata& metadata = {});
410
411 void changeFilePath(const std::string& path);
412 void reload();
413
414 std::list<Parameter> all() const override;
415 std::optional<Parameter> get(const std::string& name) const override;
416 void define(const Parameter& param) override;
417 void remove(const std::string& name) override;
418
419 void flush() override;
420
421 private:
422 std::string filePath;
423 std::map<std::string, Parameter> parameters;
424 };
425
426 /**
427 * @brief Central manager for style parameters that aggregates multiple sources.
428 *
429 * The ParameterManager is responsible for:
430 * - Managing multiple parameter sources
431 * - Resolving parameter references and expressions
432 * - Caching resolved values for performance
433 * - Handling circular references
434 */
435 class GuiExport ParameterManager
436 {
437 std::list<ParameterSource*> _sources;
438 mutable std::map<std::string, Value> _resolved;
439
440 public:
441 struct ResolveContext
442 {
443 /// Names of parameters currently being resolved.
444 std::set<std::string> visited;
445 };
446
447 ParameterManager();
448
449 /**
450 * @brief Clears the internal cache of resolved values.
451 *
452 * Call this method when parameters have been modified to ensure
453 * that the changes are reflected in subsequent resolutions.
454 */
455 void reload();
456
457 /**
458 * @brief Replaces parameter placeholders in a string with their resolved values.
459 *
460 * This method performs simple string substitution of @parameter references
461 * with their actual values. It does not evaluate expressions, only performs
462 * direct substitution.
463 *
464 * @param expression The string containing parameter placeholders
465 * @param context Resolution context for handling circular references
466 * @return The string with all placeholders replaced
467 */
468 std::string replacePlaceholders(const std::string& expression, ResolveContext context = {}) const;
469
470 /**
471 * @brief Returns all available parameters from all sources.
472 *
473 * Parameters are returned in order of source priority, with later sources
474 * taking precedence over earlier ones.
475 *
476 * @return List of all available parameters
477 */
478 std::list<Parameter> parameters() const;
479
480 /**
481 * @brief Gets the raw expression string for a parameter.
482 *
483 * @param name The name of the parameter
484 * @return The expression string if the parameter exists, empty otherwise
485 */
486 std::optional<std::string> expression(const std::string& name) const;
487
488 /**
489 * @brief Resolves a parameter to its final value.
490 *
491 * This method evaluates the parameter's expression and returns the computed
492 * value. The result is cached for subsequent calls.
493 *
494 * @param name The name of the parameter to resolve
495 * @param context Resolution context for handling circular references
496 * @return The resolved value
497 */
498 std::optional<Value> resolve(const std::string& name, ResolveContext context = {}) const;
499
500 /**
501 * @brief Resolves a parameter to its final value, based on definition.
502 *
503 * This method evaluates the parameter's expression and returns the computed
504 * value or default one from definition if the parameter is not available.
505 *
506 * @param definition Definition of the parameter to resolve
507 * @param context Resolution context for handling circular references
508 * @return The resolved value
509 */
510 template<typename T>
511 T resolve(const ParameterDefinition<T>& definition, ResolveContext context = {}) const
512 {
513 auto value = resolve(definition.name, std::move(context));
514
515 if (!value || !std::holds_alternative<T>(*value)) {
516 return definition.defaultValue;
517 }
518
519 return std::get<T>(*value);
520 }
521
522 /**
523 * @brief Evaluates an expression string and returns the result.
524 *
525 * @param expression The expression to evaluate
526 * @param context Resolution context for handling circular references
527 * @return The evaluated value
528 */
529 Value evaluate(const std::string& expression, ResolveContext context = {}) const;
530
531 /**
532 * @brief Gets a parameter by name from any source.
533 *
534 * @param name The name of the parameter
535 * @return The parameter if found, empty otherwise
536 */
537 std::optional<Parameter> parameter(const std::string& name) const;
538
539 /**
540 * @brief Adds a parameter source to the manager.
541 *
542 * Sources are evaluated in the order they are added, with later sources
543 * taking precedence over earlier ones.
544 *
545 * @param source The parameter source to add
546 */
547 void addSource(ParameterSource* source);
548
549 /**
550 * @brief Returns all registered parameter sources.
551 *
552 * @return List of parameter sources in order of registration
553 */
554 std::list<ParameterSource*> sources() const;
555 };
556
557 } // namespace Gui::StyleParameters
558
559 ENABLE_BITMASK_OPERATORS(Gui::StyleParameters::ParameterSourceOption);
560
561 #endif // STYLEPARAMETERS_PARAMETERMANAGER_H