Debian Codegraph @

src/Gui/StyleParameters/ParameterManager.cpp

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 #include "ParameterManager.h"
25 #include "Parser.h"
26
27 #include <QFile>
28 #include <fstream>
29 #include <yaml-cpp/yaml.h>
30
31 #include <QColor>
32 #include <QRegularExpression>
33 #include <QString>
34 #include <ranges>
35 #include <utility>
36 #include <variant>
37
38 #include <Base/Console.h>
39
40 FC_LOG_LEVEL_INIT("Gui", true, true)
41
42 namespace Gui::StyleParameters
43 {
44
45 Numeric Numeric::operator+(const Numeric& rhs) const
46 {
47 ensureEqualUnits(rhs);
48 return {value + rhs.value, unit};
49 }
50
51 Numeric Numeric::operator-(const Numeric& rhs) const
52 {
53 ensureEqualUnits(rhs);
54 return {value - rhs.value, unit};
55 }
56
57 Numeric Numeric::operator-() const
58 {
59 return {-value, unit};
60 }
61
62 Numeric Numeric::operator/(const Numeric& rhs) const
63 {
64 if (rhs.value == 0) {
65 THROWM(Base::RuntimeError, "Division by zero");
66 }
67
68 if (rhs.unit.empty() || unit.empty()) {
69 return {value / rhs.value, unit};
70 }
71
72 ensureEqualUnits(rhs);
73 return {value / rhs.value, unit};
74 }
75
76 Numeric Numeric::operator*(const Numeric& rhs) const
77 {
78 if (rhs.unit.empty() || unit.empty()) {
79 return {value * rhs.value, unit};
80 }
81
82 ensureEqualUnits(rhs);
83 return {value * rhs.value, unit};
84 }
85
86 void Numeric::ensureEqualUnits(const Numeric& rhs) const
87 {
88 if (unit != rhs.unit) {
89 THROWM(
90 Base::RuntimeError,
91 fmt::format("Units mismatch left expression is '{}', right expression is '{}'", unit, rhs.unit)
92 );
93 }
94 }
95
96 std::string Value::toString() const
97 {
98 if (std::holds_alternative<Numeric>(*this)) {
99 auto [value, unit] = std::get<Numeric>(*this);
100 return fmt::format("{}{}", value, unit);
101 }
102
103 if (std::holds_alternative<Base::Color>(*this)) {
104 auto color = std::get<Base::Color>(*this);
105 return fmt::format("#{:0>6x}", color.getPackedRGB() >> 8); // NOLINT(*-magic-numbers)
106 }
107
108 return std::get<std::string>(*this);
109 }
110
111 ParameterSource::ParameterSource(const Metadata& metadata)
112 : metadata(metadata)
113 {}
114
115 InMemoryParameterSource::InMemoryParameterSource(
116 const std::list<Parameter>& parameters,
117 const Metadata& metadata
118 )
119 : ParameterSource(metadata)
120 {
121 for (const auto& parameter : parameters) {
122 InMemoryParameterSource::define(parameter);
123 }
124 }
125
126 std::list<Parameter> InMemoryParameterSource::all() const
127 {
128 auto values = parameters | std::ranges::views::values;
129
130 return std::list<Parameter>(values.begin(), values.end());
131 }
132
133 std::optional<Parameter> InMemoryParameterSource::get(const std::string& name) const
134 {
135 if (parameters.contains(name)) {
136 return parameters.at(name);
137 }
138
139 return std::nullopt;
140 }
141
142 void InMemoryParameterSource::define(const Parameter& parameter)
143 {
144 parameters[parameter.name] = parameter;
145 }
146
147 void InMemoryParameterSource::remove(const std::string& name)
148 {
149 parameters.erase(name);
150 }
151
152 BuiltInParameterSource::BuiltInParameterSource(const Metadata& metadata)
153 : ParameterSource(metadata)
154 {
155 this->metadata.options |= ReadOnly;
156 }
157
158 std::list<Parameter> BuiltInParameterSource::all() const
159 {
160 std::list<Parameter> result;
161
162 for (const auto& name : params | std::views::keys) {
163 result.push_back(*get(name));
164 }
165
166 return result;
167 }
168
169 std::optional<Parameter> BuiltInParameterSource::get(const std::string& name) const
170 {
171 if (params.contains(name)) {
172 unsigned long color = params.at(name)->GetUnsigned(name.c_str(), 0);
173
174 return Parameter {
175 .name = name,
176 .value = fmt::format("#{:0>6x}", 0x00FFFFFF & (color >> 8)), // NOLINT(*-magic-numbers)
177 };
178 }
179
180 return std::nullopt;
181 }
182
183 UserParameterSource::UserParameterSource(ParameterGrp::handle hGrp, const Metadata& metadata)
184 : ParameterSource(metadata)
185 , hGrp(hGrp)
186 {}
187
188 std::list<Parameter> UserParameterSource::all() const
189 {
190 std::list<Parameter> result;
191
192 for (const auto& [token, value] : hGrp->GetASCIIMap()) {
193 result.push_back({
194 .name = token,
195 .value = value,
196 });
197 }
198
199 return result;
200 }
201
202 std::optional<Parameter> UserParameterSource::get(const std::string& name) const
203 {
204 if (auto value = hGrp->GetASCII(name.c_str(), ""); !value.empty()) {
205 return Parameter {
206 .name = name,
207 .value = value,
208 };
209 }
210
211 return {};
212 }
213
214 void UserParameterSource::define(const Parameter& parameter)
215 {
216 hGrp->SetASCII(parameter.name.c_str(), parameter.value);
217 }
218
219 void UserParameterSource::remove(const std::string& name)
220 {
221 hGrp->RemoveASCII(name.c_str());
222 }
223
224 YamlParameterSource::YamlParameterSource(const std::string& filePath, const Metadata& metadata)
225 : ParameterSource(metadata)
226 {
227 changeFilePath(filePath);
228 }
229
230 void YamlParameterSource::changeFilePath(const std::string& path)
231 {
232 this->filePath = path;
233 reload();
234 }
235
236 void YamlParameterSource::reload()
237 {
238 QFile file(QString::fromStdString(filePath));
239
240 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
241 FC_TRACE("StyleParameters: Unable to open file " << filePath);
242 return;
243 }
244
245 if (filePath.starts_with(":/")) {
246 this->metadata.options |= ReadOnly;
247 }
248
249 QTextStream in(&file);
250 std::string content = in.readAll().toStdString();
251
252 YAML::Node root = YAML::Load(content);
253 parameters.clear();
254 for (auto it = root.begin(); it != root.end(); ++it) {
255 auto key = it->first.as<std::string>();
256 auto value = it->second.as<std::string>();
257
258 parameters[key] = Parameter {
259 .name = key,
260 .value = value,
261 };
262 }
263 }
264
265 std::list<Parameter> YamlParameterSource::all() const
266 {
267 std::list<Parameter> result;
268 for (const auto& param : parameters | std::views::values) {
269 result.push_back(param);
270 }
271 return result;
272 }
273
274 std::optional<Parameter> YamlParameterSource::get(const std::string& name) const
275 {
276 if (auto it = parameters.find(name); it != parameters.end()) {
277 return it->second;
278 }
279
280 return std::nullopt;
281 }
282
283 void YamlParameterSource::define(const Parameter& param)
284 {
285 parameters[param.name] = param;
286 }
287
288 void YamlParameterSource::remove(const std::string& name)
289 {
290 parameters.erase(name);
291 }
292
293 void YamlParameterSource::flush()
294 {
295 YAML::Node root;
296 for (const auto& [name, param] : parameters) {
297 root[name] = param.value;
298 }
299
300 QFile file(QString::fromStdString(filePath));
301 if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
302 FC_WARN("StyleParameters: Unable to open file " << filePath);
303 return;
304 }
305
306 QTextStream out(&file);
307 out << QString::fromStdString(YAML::Dump(root));
308 }
309
310 ParameterManager::ParameterManager() = default;
311
312 void ParameterManager::reload()
313 {
314 _resolved.clear();
315 }
316
317 std::string ParameterManager::replacePlaceholders(
318 const std::string& expression,
319 ResolveContext context
320 ) const
321 {
322 static const QRegularExpression regex(QStringLiteral("@(\\w+)"));
323
324 auto substituteWithCallback =
325 [](const QRegularExpression& regex,
326 const QString& input,
327 const std::function<QString(const QRegularExpressionMatch&)>& callback) {
328 QRegularExpressionMatchIterator it = regex.globalMatch(input);
329
330 QString result;
331 qsizetype lastIndex = 0;
332
333 while (it.hasNext()) {
334 QRegularExpressionMatch match = it.next();
335
336 qsizetype start = match.capturedStart();
337 qsizetype end = match.capturedEnd();
338
339 result += input.mid(lastIndex, start - lastIndex);
340 result += callback(match);
341
342 lastIndex = end;
343 }
344
345 // Append any remaining text after the last match
346 result += input.mid(lastIndex);
347
348 return result;
349 };
350
351 // clang-format off
352 return substituteWithCallback(
353 regex,
354 QString::fromStdString(expression),
355 [&](const QRegularExpressionMatch& match) {
356 auto tokenName = match.captured(1).toStdString();
357 auto tokenValue = resolve(tokenName, context);
358
359 if (!tokenValue) {
360 Base::Console().warning("Requested non-existent style parameter token '%s'.\n", tokenName);
361 return QStringLiteral("");
362 }
363
364 context.visited.erase(tokenName);
365 return QString::fromStdString(tokenValue->toString());
366 }
367 ).toStdString();
368 // clang-format on
369 }
370
371 std::list<Parameter> ParameterManager::parameters() const
372 {
373 std::set<Parameter, Parameter::NameComparator> result;
374
375 // we need to traverse it in reverse order so more important tokens will take precedence
376 for (const ParameterSource* source : _sources | std::views::reverse) {
377 for (const Parameter& parameter : source->all()) {
378 result.insert(parameter);
379 }
380 }
381
382 return std::list(result.begin(), result.end());
383 }
384
385 std::optional<std::string> ParameterManager::expression(const std::string& name) const
386 {
387 if (auto param = parameter(name)) {
388 return param->value;
389 }
390
391 return {};
392 }
393
394 std::optional<Value> ParameterManager::resolve(const std::string& name, ResolveContext context) const
395 {
396 std::optional<Parameter> maybeParameter = this->parameter(name);
397
398 if (!maybeParameter) {
399 return std::nullopt;
400 }
401
402 if (context.visited.contains(name)) {
403 Base::Console().warning("The style parameter '%s' contains circular-reference.\n", name);
404 return expression(name);
405 }
406
407 const Parameter& token = *maybeParameter;
408
409 if (!_resolved.contains(token.name)) {
410 context.visited.insert(token.name);
411 try {
412 _resolved[token.name] = evaluate(token.value, context);
413 }
414 catch (Base::Exception&) {
415 // in case of being unable to parse it, we need to treat it as a generic value
416 _resolved[token.name] = replacePlaceholders(token.value, context);
417 }
418 context.visited.erase(token.name);
419 }
420
421 return _resolved[token.name];
422 }
423
424 Value ParameterManager::evaluate(const std::string& expression, ResolveContext context) const
425 {
426 Parser parser(expression);
427 return parser.parse()->evaluate({.manager = this, .context = std::move(context)});
428 }
429
430 std::optional<Parameter> ParameterManager::parameter(const std::string& name) const
431 {
432 for (const ParameterSource* source : _sources) {
433 if (const auto& parameter = source->get(name)) {
434 return parameter;
435 }
436 }
437
438 return {};
439 }
440
441 void ParameterManager::addSource(ParameterSource* source)
442 {
443 _sources.push_front(source);
444 }
445
446 std::list<ParameterSource*> ParameterManager::sources() const
447 {
448 return _sources;
449 }
450
451 } // namespace Gui::StyleParameters