Debian Codegraph @

src/Gui/SpinBox.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <limits>
24 #include <QKeyEvent>
25 #include <QLineEdit>
26 #include <QStyle>
27 #include <QStyleOptionSpinBox>
28 #include <QStylePainter>
29
30 #include <boost/math/special_functions/round.hpp>
31
32 #include <App/ExpressionParser.h>
33 #include <App/PropertyUnits.h>
34
35 #include "SpinBox.h"
36 #include "Command.h"
37 #include "Dialogs/DlgExpressionInput.h"
38 #include "QuantitySpinBox_p.h"
39 #include "Widgets.h"
40
41
42 using namespace Gui;
43 using namespace App;
44 using namespace Base;
45
46 ExpressionSpinBox::ExpressionSpinBox(QAbstractSpinBox* sb)
47 : spinbox(sb)
48 {
49 lineedit = spinbox->findChild<QLineEdit*>();
50 // Set Margins
51 // https://forum.freecad.org/viewtopic.php?f=8&t=50615
52 // vertical margin, otherwise `,` is clipped to a `.` on some OSX versions
53 int margin = getMargin();
54 lineedit->setTextMargins(margin, margin, margin, margin);
55 lineedit->setAlignment(Qt::AlignVCenter);
56
57 makeLabel(lineedit);
58 QObject::connect(iconLabel, &ExpressionLabel::clicked, [this]() { this->openFormulaDialog(); });
59 }
60
61 ExpressionSpinBox::~ExpressionSpinBox() = default;
62
63 int ExpressionSpinBox::getMargin()
64 {
65 #if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0)
66 return lineedit->style()->pixelMetric(QStyle::PM_LineEditIconMargin, nullptr, lineedit) / 2;
67 #else
68 return lineedit->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, nullptr, lineedit);
69 #endif
70 }
71
72 void ExpressionSpinBox::bind(const App::ObjectIdentifier& _path)
73 {
74 ExpressionBinding::bind(_path);
75
76 showIcon();
77 }
78
79 void ExpressionSpinBox::showIcon()
80 {
81 iconLabel->show();
82 }
83
84 void ExpressionSpinBox::validateInput()
85 {}
86
87 void ExpressionSpinBox::showInvalidExpression(const QString& tip)
88 {
89 spinbox->setReadOnly(true);
90 QPalette p(lineedit->palette());
91 p.setColor(QPalette::Active, QPalette::Text, Qt::red);
92 lineedit->setPalette(p);
93 iconLabel->setToolTip(tip);
94 iconLabel->setPixmap(getIcon(":/icons/button_invalid.svg", QSize(iconHeight, iconHeight)));
95 }
96
97 void ExpressionSpinBox::showValidExpression(ExpressionSpinBox::Number number)
98 {
99 try {
100 showExpression(number);
101 }
102 catch (const Base::Exception& e) {
103 showInvalidExpression(QString::fromUtf8(e.what()));
104 }
105 }
106
107 void ExpressionSpinBox::showExpression(Number number)
108 {
109 std::unique_ptr<Expression> result(getExpression()->eval());
110 auto* value = freecad_cast<NumberExpression*>(result.get());
111
112 if (value) {
113 switch (number) {
114 case Number::SetIfNumber:
115 setNumberExpression(value);
116 break;
117 case Number::KeepCurrent:
118 break;
119 }
120
121 spinbox->setReadOnly(true);
122 iconLabel->setPixmap(getIcon(":/icons/bound-expression.svg", QSize(iconHeight, iconHeight)));
123
124 QPalette p(lineedit->palette());
125 p.setColor(QPalette::Text, Qt::lightGray);
126 lineedit->setPalette(p);
127 }
128 iconLabel->setExpressionText(QString::fromStdString(getExpression()->toString()));
129 }
130
131 void ExpressionSpinBox::clearExpression()
132 {
133 spinbox->setReadOnly(false);
134 QPixmap pixmap = getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight));
135 iconLabel->setPixmap(pixmap);
136
137 QPalette p(lineedit->palette());
138 p.setColor(QPalette::Active, QPalette::Text, defaultPalette.color(QPalette::Text));
139 lineedit->setPalette(p);
140 iconLabel->setExpressionText(QString());
141 }
142
143 void ExpressionSpinBox::updateExpression()
144 {
145 try {
146 if (isBound() && getExpression()) {
147 showValidExpression(Number::KeepCurrent);
148 }
149 else {
150 clearExpression();
151 }
152 }
153 catch (const Base::Exception& e) {
154 showInvalidExpression(QString::fromLatin1(e.what()));
155 }
156 }
157
158 void ExpressionSpinBox::setExpression(std::shared_ptr<Expression> expr)
159 {
160 Q_ASSERT(isBound());
161
162 try {
163 ExpressionBinding::setExpression(expr);
164 validateInput();
165 }
166 catch (const Base::Exception& e) {
167 showInvalidExpression(QString::fromLatin1(e.what()));
168 }
169 }
170
171 void ExpressionSpinBox::onChange()
172 {
173 Q_ASSERT(isBound());
174
175 if (getExpression()) {
176 showValidExpression(Number::SetIfNumber);
177 }
178 else {
179 clearExpression();
180 }
181 }
182
183 void ExpressionSpinBox::resizeWidget()
184 {
185 int iconWidth = iconLabel->width() + getMargin();
186 iconLabel->move(lineedit->width() - iconWidth, (lineedit->height() - iconLabel->height()) / 2);
187 updateExpression();
188 }
189
190 void ExpressionSpinBox::openFormulaDialog()
191 {
192 Q_ASSERT(isBound());
193
194 auto* qprop = freecad_cast<PropertyQuantity*>(getPath().getProperty());
195 Unit unit;
196
197 if (qprop) {
198 unit = qprop->getUnit();
199 }
200
201 auto box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), unit, spinbox);
202 QObject::connect(box, &Gui::Dialog::DlgExpressionInput::finished, [this, box]() {
203 if (box->result() == QDialog::Accepted) {
204 setExpression(box->getExpression());
205 }
206 else if (box->discardedFormula()) {
207 setExpression(std::shared_ptr<Expression>());
208 }
209
210 updateExpression();
211 box->deleteLater();
212 });
213 box->show();
214
215 QPoint pos = spinbox->mapToGlobal(QPoint(0, 0));
216 box->move(pos - box->expressionPosition());
217 Gui::adjustDialogPosition(box);
218 }
219
220 bool ExpressionSpinBox::handleKeyEvent(const QString& text)
221 {
222 if (text == QLatin1String("=") && isBound()) {
223 openFormulaDialog();
224 return true;
225 }
226
227 return false;
228 }
229
230 void ExpressionSpinBox::drawControl(QStyleOptionSpinBox& opt)
231 {
232 if (hasExpression()) {
233 opt.activeSubControls &= ~QStyle::SC_SpinBoxUp;
234 opt.activeSubControls &= ~QStyle::SC_SpinBoxDown;
235 opt.state &= ~QStyle::State_Active;
236 opt.stepEnabled = QAbstractSpinBox::StepNone;
237 }
238
239 QStylePainter p(spinbox);
240 p.drawComplexControl(QStyle::CC_SpinBox, opt);
241 }
242
243 // ----------------------------------------------------------------------------
244
245 UnsignedValidator::UnsignedValidator(QObject* parent)
246 : QValidator(parent)
247 {
248 b = 0;
249 t = std::numeric_limits<unsigned>::max();
250 }
251
252 UnsignedValidator::UnsignedValidator(uint minimum, uint maximum, QObject* parent)
253 : QValidator(parent)
254 {
255 b = minimum;
256 t = maximum;
257 }
258
259 UnsignedValidator::~UnsignedValidator() = default;
260
261 QValidator::State UnsignedValidator::validate(QString& input, int&) const
262 {
263 QString stripped = input.trimmed();
264 if (stripped.isEmpty()) {
265 return Intermediate;
266 }
267 bool ok;
268 uint entered = input.toUInt(&ok);
269 if (!ok) {
270 return Invalid;
271 }
272 else if (entered < b) {
273 return Intermediate;
274 }
275 else if (entered > t) {
276 return Invalid;
277 }
278 // else if ( entered < b || entered > t )
279 // return Invalid;
280 else {
281 return Acceptable;
282 }
283 }
284
285 void UnsignedValidator::setRange(uint minimum, uint maximum)
286 {
287 b = minimum;
288 t = maximum;
289 }
290
291 void UnsignedValidator::setBottom(uint bottom)
292 {
293 setRange(bottom, top());
294 }
295
296 void UnsignedValidator::setTop(uint top)
297 {
298 setRange(bottom(), top);
299 }
300
301 namespace Gui
302 {
303 class UIntSpinBoxPrivate
304 {
305 public:
306 UnsignedValidator* mValidator {nullptr};
307
308 UIntSpinBoxPrivate() = default;
309 unsigned mapToUInt(int v) const
310 {
311 using int_limits = std::numeric_limits<int>;
312 using uint_limits = std::numeric_limits<unsigned>;
313
314 unsigned ui;
315 if (v == int_limits::min()) {
316 ui = 0;
317 }
318 else if (v == int_limits::max()) {
319 ui = uint_limits::max();
320 }
321 else if (v < 0) {
322 v -= int_limits::min();
323 ui = static_cast<unsigned>(v);
324 }
325 else {
326 ui = static_cast<unsigned>(v);
327 ui -= int_limits::min();
328 }
329 return ui;
330 }
331 int mapToInt(unsigned v) const
332 {
333 using int_limits = std::numeric_limits<int>;
334 using uint_limits = std::numeric_limits<unsigned>;
335
336 int in;
337 if (v == uint_limits::max()) {
338 in = int_limits::max();
339 }
340 else if (v == 0) {
341 in = int_limits::min();
342 }
343 else if (v > static_cast<unsigned int>(int_limits::max())) {
344 v += int_limits::min();
345 in = static_cast<int>(v);
346 }
347 else {
348 in = v;
349 in += int_limits::min();
350 }
351 return in;
352 }
353 };
354
355 } // namespace Gui
356
357 UIntSpinBox::UIntSpinBox(QWidget* parent)
358 : QSpinBox(parent)
359 , ExpressionSpinBox(this)
360 {
361 d = new UIntSpinBoxPrivate;
362 d->mValidator = new UnsignedValidator(this->minimum(), this->maximum(), this);
363 connect(this, qOverload<int>(&QSpinBox::valueChanged), this, &UIntSpinBox::valueChange);
364 setRange(0, 99);
365 setValue(0);
366 updateValidator();
367 }
368
369 UIntSpinBox::~UIntSpinBox()
370 {
371 delete d->mValidator;
372 delete d;
373 d = nullptr;
374 }
375
376 void UIntSpinBox::setRange(uint minVal, uint maxVal)
377 {
378 int iminVal = d->mapToInt(minVal);
379 int imaxVal = d->mapToInt(maxVal);
380 QSpinBox::setRange(iminVal, imaxVal);
381 updateValidator();
382 }
383
384 QValidator::State UIntSpinBox::validate(QString& input, int& pos) const
385 {
386 return d->mValidator->validate(input, pos);
387 }
388
389 uint UIntSpinBox::value() const
390 {
391 return d->mapToUInt(QSpinBox::value());
392 }
393
394 void UIntSpinBox::setValue(uint value)
395 {
396 QSpinBox::setValue(d->mapToInt(value));
397 }
398
399 void UIntSpinBox::valueChange(int value)
400 {
401 Q_EMIT unsignedChanged(d->mapToUInt(value));
402 }
403
404 uint UIntSpinBox::minimum() const
405 {
406 return d->mapToUInt(QSpinBox::minimum());
407 }
408
409 void UIntSpinBox::setMinimum(uint minVal)
410 {
411 uint maxVal = maximum();
412 if (maxVal < minVal) {
413 maxVal = minVal;
414 }
415 setRange(minVal, maxVal);
416 }
417
418 uint UIntSpinBox::maximum() const
419 {
420 return d->mapToUInt(QSpinBox::maximum());
421 }
422
423 void UIntSpinBox::setMaximum(uint maxVal)
424 {
425 uint minVal = minimum();
426 if (minVal > maxVal) {
427 minVal = maxVal;
428 }
429 setRange(minVal, maxVal);
430 }
431
432 QString UIntSpinBox::textFromValue(int v) const
433 {
434 uint val = d->mapToUInt(v);
435 QString s;
436 s.setNum(val);
437 return s;
438 }
439
440 int UIntSpinBox::valueFromText(const QString& text) const
441 {
442 bool ok;
443 QString s = text;
444 uint newVal = s.toUInt(&ok);
445 if (!ok && !(prefix().isEmpty() && suffix().isEmpty())) {
446 s = cleanText();
447 newVal = s.toUInt(&ok);
448 }
449
450 return d->mapToInt(newVal);
451 }
452
453 void UIntSpinBox::updateValidator()
454 {
455 d->mValidator->setRange(this->minimum(), this->maximum());
456 }
457
458 bool UIntSpinBox::apply(const std::string& propName)
459 {
460 if (!ExpressionBinding::apply(propName)) {
461 Gui::Command::doCommand(Gui::Command::Doc, "%s = %u", propName.c_str(), value());
462 return true;
463 }
464
465 return false;
466 }
467
468 void UIntSpinBox::setNumberExpression(App::NumberExpression* expr)
469 {
470 setValue(boost::math::round(expr->getValue()));
471 }
472
473 void UIntSpinBox::resizeEvent(QResizeEvent* event)
474 {
475 QAbstractSpinBox::resizeEvent(event);
476 resizeWidget();
477 }
478
479 void UIntSpinBox::keyPressEvent(QKeyEvent* event)
480 {
481 if (!handleKeyEvent(event->text())) {
482 QAbstractSpinBox::keyPressEvent(event);
483 }
484 }
485
486 void UIntSpinBox::paintEvent(QPaintEvent*)
487 {
488 QStyleOptionSpinBox opt;
489 initStyleOption(&opt);
490 drawControl(opt);
491 }
492
493 // ----------------------------------------------------------------------------
494
495 IntSpinBox::IntSpinBox(QWidget* parent)
496 : QSpinBox(parent)
497 , ExpressionSpinBox(this)
498 {}
499
500 IntSpinBox::~IntSpinBox() = default;
501
502 bool IntSpinBox::apply(const std::string& propName)
503 {
504 if (!ExpressionBinding::apply(propName)) {
505 Gui::Command::doCommand(Gui::Command::Doc, "%s = %d", propName.c_str(), value());
506 return true;
507 }
508 else {
509 return false;
510 }
511 }
512
513 void IntSpinBox::setNumberExpression(App::NumberExpression* expr)
514 {
515 setValue(boost::math::round(expr->getValue()));
516 }
517
518 void IntSpinBox::resizeEvent(QResizeEvent* event)
519 {
520 QAbstractSpinBox::resizeEvent(event);
521 resizeWidget();
522 }
523
524 void IntSpinBox::keyPressEvent(QKeyEvent* event)
525 {
526 if (!handleKeyEvent(event->text())) {
527 QAbstractSpinBox::keyPressEvent(event);
528 }
529 }
530
531 void IntSpinBox::paintEvent(QPaintEvent*)
532 {
533 QStyleOptionSpinBox opt;
534 initStyleOption(&opt);
535 drawControl(opt);
536 }
537
538 // ----------------------------------------------------------------------------
539
540 DoubleSpinBox::DoubleSpinBox(QWidget* parent)
541 : QDoubleSpinBox(parent)
542 , ExpressionSpinBox(this)
543 {}
544
545 DoubleSpinBox::~DoubleSpinBox() = default;
546
547 bool DoubleSpinBox::apply(const std::string& propName)
548 {
549 if (!ExpressionBinding::apply(propName)) {
550 Gui::Command::doCommand(Gui::Command::Doc, "%s = %f", propName.c_str(), value());
551 return true;
552 }
553
554 return false;
555 }
556
557 void DoubleSpinBox::setNumberExpression(App::NumberExpression* expr)
558 {
559 setValue(expr->getValue());
560 }
561
562 void DoubleSpinBox::resizeEvent(QResizeEvent* event)
563 {
564 QAbstractSpinBox::resizeEvent(event);
565 resizeWidget();
566 }
567
568 void DoubleSpinBox::keyPressEvent(QKeyEvent* event)
569 {
570 if (!handleKeyEvent(event->text())) {
571 QDoubleSpinBox::keyPressEvent(event);
572 }
573 }
574
575 void DoubleSpinBox::paintEvent(QPaintEvent*)
576 {
577 QStyleOptionSpinBox opt;
578 initStyleOption(&opt);
579 drawControl(opt);
580 }
581
582 #include "moc_SpinBox.cpp"