Debian Codegraph @

src/Gui/propertyeditor/PropertyItem.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /***************************************************************************
3 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
4 * *
5 * This file is part of the FreeCAD CAx development system. *
6 * *
7 * This library is free software; you can redistribute it and/or *
8 * modify it under the terms of the GNU Library General Public *
9 * License as published by the Free Software Foundation; either *
10 * version 2 of the License, or (at your option) any later version. *
11 * *
12 * This library is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with this library; see the file COPYING.LIB. If not, *
19 * write to the Free Software Foundation, Inc., 59 Temple Place, *
20 * Suite 330, Boston, MA 02111-1307, USA *
21 * *
22 ***************************************************************************/
23
24
25 #include <algorithm>
26 #include <iomanip>
27 #include <limits>
28 #include <QApplication>
29 #include <QComboBox>
30 #include <QCheckBox>
31 #include <QFontDatabase>
32 #include <QLocale>
33 #include <QMessageBox>
34 #include <QPalette>
35 #include <QPixmap>
36 #include <QTextStream>
37 #include <QTimer>
38 #include <QtGlobal>
39 #include <QMenu>
40
41 #include "PropertyItem.h"
42 #include "PropertyView.h"
43
44 #include <App/Document.h>
45 #include <App/DocumentObject.h>
46 #include <App/Expression.h>
47 #include <App/PropertyGeo.h>
48 #include <App/PropertyFile.h>
49 #include <App/PropertyUnits.h>
50 #include <Base/Console.h>
51 #include <Base/Interpreter.h>
52 #include <Base/Tools.h>
53 #include <Gui/Command.h>
54 #include <Gui/Control.h>
55 #include <Gui/Dialogs/DlgPropertyLink.h>
56 #include <Gui/FileDialog.h>
57 #include <Gui/MainWindow.h>
58 #include <Gui/Placement.h>
59 #include <Gui/QuantitySpinBox.h>
60 #include <Gui/Selection/Selection.h>
61 #include <Gui/SpinBox.h>
62 #include <Gui/VectorListEditor.h>
63 #include <Gui/ViewProviderDocumentObject.h>
64
65 // NOLINTBEGIN(cppcoreguidelines-pro-*,cppcoreguidelines-prefer-member-initializer)
66 using namespace Gui::PropertyEditor;
67 using namespace Gui::Dialog;
68
69 namespace
70 {
71 constexpr const int lowPrec = 2;
72 constexpr const int highPrec = 16;
73 } // namespace
74
75
76 PropertyItemFactory& PropertyItemFactory::instance()
77 {
78 static PropertyItemFactory inst;
79 return inst;
80 }
81
82 PropertyItem* PropertyItemFactory::createPropertyItem(const char* sName) const
83 {
84 return static_cast<PropertyItem*>(Produce(sName));
85 }
86
87 // ----------------------------------------------------
88
89 QString PropertyItemAttorney::toString(PropertyItem* item, const QVariant& value)
90 {
91 return item->toString(value);
92 }
93
94 // ----------------------------------------------------
95
96 Q_DECLARE_METATYPE(Py::Object) // NOLINT
97
98 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyItem)
99
100 PropertyItem::PropertyItem()
101 : parentItem(nullptr)
102 , readonly(false)
103 , precision(Base::UnitsApi::getDecimals())
104 , linked(false)
105 , expanded(false)
106 {
107 setAutoApply(true);
108 }
109
110 PropertyItem::~PropertyItem()
111 {
112 qDeleteAll(childItems);
113 }
114
115 void PropertyItem::initialize()
116 {}
117
118 void PropertyItem::reset()
119 {
120 qDeleteAll(childItems);
121 childItems.clear();
122 }
123
124 void PropertyItem::onChange()
125 {
126 if (hasExpression()) {
127 for (auto child : std::as_const(childItems)) {
128 if (child && child->hasExpression()) {
129 child->setExpression(std::shared_ptr<App::Expression>());
130 }
131 }
132 for (auto item = parentItem; item; item = item->parentItem) {
133 if (item->hasExpression()) {
134 item->setExpression(std::shared_ptr<App::Expression>());
135 }
136 }
137 }
138 }
139
140 bool PropertyItem::hasAnyExpression() const
141 {
142 if (ExpressionBinding::hasExpression()) {
143 return true;
144 }
145 if (parentItem) {
146 return parentItem->hasExpression();
147 }
148 return false;
149 }
150
151 void PropertyItem::setPropertyData(const std::vector<App::Property*>& items)
152 {
153 // if we have a single property we can bind it for expression handling
154 if (items.size() == 1) {
155 const App::Property& prop = *items.front();
156
157 try {
158 // Check for 'DocumentObject' as parent because otherwise 'ObjectIdentifier' raises an
159 // exception
160 auto* docObj = freecad_cast<App::DocumentObject*>(prop.getContainer());
161 if (docObj && !docObj->isReadOnly(&prop)) {
162 App::ObjectIdentifier id(prop);
163 std::vector<App::ObjectIdentifier> paths;
164 prop.getPaths(paths);
165
166 // there may be no paths available in this property (for example an empty constraint
167 // list)
168 if (id.getProperty() && !paths.empty()) {
169 bind(id);
170 }
171 }
172 }
173 // it may happen that setting properties is not possible
174 catch (...) {
175 }
176 }
177
178 propertyItems = items;
179 updateData();
180 this->initialize();
181 }
182
183 void PropertyItem::updateData()
184 {
185 bool ro = true;
186 for (auto it : propertyItems) {
187 App::PropertyContainer* parent = it->getContainer();
188 if (parent) {
189 ro &= (parent->isReadOnly(it) || it->testStatus(App::Property::ReadOnly));
190 }
191 }
192 this->setReadOnly(ro);
193 }
194
195 const std::vector<App::Property*>& PropertyItem::getPropertyData() const
196 {
197 return propertyItems;
198 }
199
200 bool PropertyItem::hasProperty(const App::Property* prop) const
201 {
202 auto it = std::ranges::find(propertyItems, prop);
203 return (it != propertyItems.end());
204 }
205
206 void PropertyItem::assignProperty(const App::Property* prop)
207 {
208 Q_UNUSED(prop)
209 }
210
211 bool PropertyItem::removeProperty(const App::Property* prop)
212 {
213 auto it = std::ranges::find(propertyItems, prop);
214 if (it != propertyItems.end()) {
215 propertyItems.erase(it);
216 }
217
218 return propertyItems.empty();
219 }
220
221 bool PropertyItem::renameProperty(const App::Property* prop)
222 {
223 setPropertyData({const_cast<App::Property*>(prop)});
224 QString name = QString::fromLatin1(prop->getName());
225 setPropertyName(name, name);
226 return true;
227 }
228
229 App::Property* PropertyItem::getFirstProperty()
230 {
231 if (propertyItems.empty()) {
232 return nullptr;
233 }
234 return propertyItems.front();
235 }
236
237 const App::Property* PropertyItem::getFirstProperty() const
238 {
239 if (propertyItems.empty()) {
240 return nullptr;
241 }
242 return propertyItems.front();
243 }
244
245 void PropertyItem::setParent(PropertyItem* parent)
246 {
247 parentItem = parent;
248 }
249
250 PropertyItem* PropertyItem::parent() const
251 {
252 return parentItem;
253 }
254
255 void PropertyItem::appendChild(PropertyItem* item)
256 {
257 childItems.append(item);
258 }
259
260 void PropertyItem::insertChild(int index, PropertyItem* child)
261 {
262 childItems.insert(index, child);
263 }
264
265 /*!
266 * \brief PropertyItem::removeChildren
267 * Deletes the children in the range of [from, to]
268 */
269 void PropertyItem::removeChildren(int from, int to)
270 {
271 int count = to - from + 1;
272 for (int i = 0; i < count; i++) {
273 PropertyItem* child = childItems.takeAt(from);
274 delete child;
275 }
276 }
277
278 void PropertyItem::moveChild(int from, int to)
279 {
280 childItems.move(from, to);
281 }
282
283 /*!
284 * \brief PropertyItem::takeChild
285 * Removes the child at index row but doesn't delete it
286 */
287 PropertyItem* PropertyItem::takeChild(int row)
288 {
289 PropertyItem* child = childItems.takeAt(row);
290 child->setParent(nullptr);
291 return child;
292 }
293
294 PropertyItem* PropertyItem::child(int row)
295 {
296 return childItems.value(row);
297 }
298
299 int PropertyItem::childCount() const
300 {
301 return childItems.count();
302 }
303
304 int PropertyItem::columnCount() const
305 {
306 return PropertyItem::ColumnCount;
307 }
308
309 void PropertyItem::setReadOnly(bool ro)
310 {
311 readonly = ro;
312 for (auto it : std::as_const(childItems)) {
313 it->setReadOnly(ro);
314 }
315 }
316
317 bool PropertyItem::isReadOnly() const
318 {
319 return readonly;
320 }
321
322 void PropertyItem::setLinked(bool value)
323 {
324 linked = value;
325 for (auto it : std::as_const(childItems)) {
326 it->setLinked(value);
327 }
328 }
329
330 bool PropertyItem::isLinked() const
331 {
332 return linked;
333 }
334
335 void PropertyItem::setExpanded(bool enable)
336 {
337 expanded = enable;
338 }
339
340 bool PropertyItem::isExpanded() const
341 {
342 return expanded;
343 }
344
345 bool PropertyItem::testStatus(App::Property::Status pos) const
346 {
347 std::vector<App::Property*>::const_iterator it;
348 for (it = propertyItems.begin(); it != propertyItems.end(); ++it) {
349 if ((*it)->testStatus(pos)) {
350 return true;
351 }
352 }
353 return false;
354 }
355
356 void PropertyItem::setDecimals(int prec)
357 {
358 precision = prec;
359 }
360
361 int PropertyItem::decimals() const
362 {
363 return precision;
364 }
365
366 QVariant PropertyItem::displayName() const
367 {
368 return {displayText};
369 }
370
371 QVariant PropertyItem::toolTip(const App::Property* prop) const
372 {
373 QString str = QApplication::translate("App::Property", prop->getDocumentation());
374 return {str};
375 }
376
377 QVariant PropertyItem::decoration(const QVariant& value) const
378 {
379 Q_UNUSED(value)
380 return {};
381 }
382
383 QString PropertyItem::asNone(const Py::Object& pyobj) const
384 {
385 Q_UNUSED(pyobj)
386 return QStringLiteral("<None>");
387 }
388
389 QString PropertyItem::asString(const Py::Object& pyobj) const
390 {
391 return QString::fromStdString(pyobj.as_string());
392 }
393
394 QString PropertyItem::asSequence(const Py::Object& pyobj) const
395 {
396 std::ostringstream ss;
397 ss << '[';
398 Py::Sequence seq(pyobj);
399 bool first = true;
400 Py_ssize_t i = 0;
401 for (i = 0; i < 2 && i < seq.size(); ++i) {
402 if (first) {
403 first = false;
404 }
405 else {
406 ss << ", ";
407 }
408 ss << Py::Object(seq[i]).as_string();
409 }
410
411 if (i < seq.size()) {
412 ss << "...";
413 }
414 ss << ']';
415 return QString::fromUtf8(ss.str().c_str());
416 }
417
418 QString PropertyItem::asMapping(const Py::Object& pyobj) const
419 {
420 std::ostringstream ss;
421 ss << '{';
422 Py::Mapping map(pyobj);
423 bool first = true;
424 auto it = map.begin();
425 for (int i = 0; i < 2 && it != map.end(); ++it, ++i) {
426 if (first) {
427 first = false;
428 }
429 else {
430 ss << ", ";
431 }
432 const auto& v = *it;
433 ss << Py::Object(v.first).as_string() << ':' << Py::Object(v.second).as_string();
434 }
435
436 if (it != map.end()) {
437 ss << "...";
438 }
439 ss << '}';
440 return QString::fromUtf8(ss.str().c_str());
441 }
442
443 QString PropertyItem::toString(const Py::Object& pyobj) const
444 {
445 if (pyobj.isNone()) {
446 return asNone(pyobj);
447 }
448 if (pyobj.isSequence()) {
449 return asSequence(pyobj);
450 }
451 if (pyobj.isMapping()) {
452 return asMapping(pyobj);
453 }
454
455 return asString(pyobj);
456 }
457
458 QString PropertyItem::toString(const QVariant& prop) const
459 {
460 if (prop != QVariant() || propertyItems.size() != 1) {
461 return prop.toString();
462 }
463
464 std::ostringstream ss;
465 Base::PyGILStateLocker lock;
466 try {
467 Py::Object pyobj(propertyItems[0]->getPyObject(), true);
468 return toString(pyobj);
469 }
470 catch (Py::Exception&) {
471 Base::PyException e;
472 ss.str("");
473 ss << "ERR: " << e.what();
474 }
475 catch (Base::Exception& e) {
476 ss.str("");
477 ss << "ERR: " << e.what();
478 }
479 catch (std::exception& e) {
480 ss.str("");
481 ss << "ERR: " << e.what();
482 }
483 catch (...) {
484 ss.str("");
485 ss << "ERR!";
486 }
487
488 return {QString::fromUtf8(ss.str().c_str())};
489 }
490
491 QVariant PropertyItem::value(const App::Property* /*prop*/) const
492 {
493 return {};
494 }
495
496 void PropertyItem::setValue(const QVariant& /*value*/)
497 {}
498
499 QWidget* PropertyItem::
500 createEditor(QWidget* /*parent*/, const std::function<void()>& /*method*/, FrameOption /*frameOption*/) const
501 {
502 return nullptr;
503 }
504
505 void PropertyItem::setEditorData(QWidget* /*editor*/, const QVariant& /*data*/) const
506 {}
507
508 QVariant PropertyItem::editorData(QWidget* /*editor*/) const
509 {
510 return {};
511 }
512
513 QWidget* PropertyItem::createExpressionEditor(QWidget* parent, const std::function<void()>& method) const
514 {
515 if (!isBound()) {
516 return nullptr;
517 }
518 auto le = new ExpLineEdit(parent, true);
519 le->setFrame(false);
520 le->setReadOnly(true);
521 QObject::connect(le, &ExpLineEdit::textChanged, method);
522 le->bind(getPath());
523 le->setAutoApply(autoApply());
524 return le;
525 }
526
527 void PropertyItem::setExpressionEditorData(QWidget* editor, const QVariant& data) const
528 {
529 auto le = qobject_cast<QLineEdit*>(editor);
530 if (le) {
531 le->setText(data.toString());
532 }
533 }
534
535 QVariant PropertyItem::expressionEditorData(QWidget* editor) const
536 {
537 auto le = qobject_cast<QLineEdit*>(editor);
538 if (le) {
539 return {le->text()};
540 }
541 return {};
542 }
543
544 PropertyEditorWidget* PropertyItem::createPropertyEditorWidget(QWidget* parent) const
545 {
546 auto editor = new PropertyEditorWidget(parent);
547 connect(editor, &PropertyEditorWidget::buttonClick, this, [this]() {
548 const auto& props = this->getPropertyData();
549 if (!props.empty() && props[0]->getName() && props[0]->testStatus(App::Property::UserEdit)
550 && props[0]->getContainer()) {
551 props[0]->getContainer()->editProperty(props[0]->getName());
552 }
553 });
554 return editor;
555 }
556
557 QString PropertyItem::propertyName() const
558 {
559 if (propName.isEmpty()) {
560 return QLatin1String(QT_TRANSLATE_NOOP("App::Property", "<empty>"));
561 }
562 return propName;
563 }
564
565 void PropertyItem::setPropertyName(const QString& name, const QString& realName)
566 {
567 if (realName.size()) {
568 propName = realName;
569 }
570 else {
571 propName = name;
572 }
573
574 setObjectName(propName);
575
576 QString display;
577 bool upper = false;
578 for (auto&& i : name) {
579 if (i.isUpper() && !display.isEmpty()) {
580 // if there is a sequence of capital letters do not insert spaces
581 if (!upper) {
582 QChar last = display.at(display.length() - 1);
583 if (!last.isSpace()) {
584 display += QLatin1String(" ");
585 }
586 }
587 }
588 upper = i.isUpper();
589 display += i;
590 }
591
592 propName = display;
593
594 QString str = QApplication::translate("App::Property", propName.toUtf8());
595 displayText = str;
596 }
597
598 void PropertyItem::setPropertyValue(const std::string& value)
599 {
600 // Construct command for property assignment in one go, in case of any
601 // intermediate changes caused by property change that may potentially
602 // invalidate the current property array.
603 std::ostringstream ss;
604 for (auto prop : propertyItems) {
605 App::PropertyContainer* parent = prop->getContainer();
606 if (!parent || parent->isReadOnly(prop) || prop->testStatus(App::Property::ReadOnly)) {
607 continue;
608 }
609
610 if (parent->isDerivedFrom<App::Document>()) {
611 auto doc = static_cast<App::Document*>(parent);
612 ss << "FreeCAD.getDocument('" << doc->getName() << "').";
613 }
614 else if (parent->isDerivedFrom<App::DocumentObject>()) {
615 auto obj = static_cast<App::DocumentObject*>(parent);
616 App::Document* doc = obj->getDocument();
617 ss << "FreeCAD.getDocument('" << doc->getName() << "').getObject('"
618 << obj->getNameInDocument() << "').";
619 }
620 else if (parent->isDerivedFrom<ViewProviderDocumentObject>()) {
621 App::DocumentObject* obj = static_cast<ViewProviderDocumentObject*>(parent)->getObject();
622 App::Document* doc = obj->getDocument();
623 ss << "FreeCADGui.getDocument('" << doc->getName() << "').getObject('"
624 << obj->getNameInDocument() << "').";
625 }
626 else {
627 continue;
628 }
629
630 ss << parent->getPropertyPrefix() << prop->getName() << " = " << value << '\n';
631 }
632
633 std::string cmd = ss.str();
634 if (cmd.empty()) {
635 return;
636 }
637
638 try {
639 Gui::Command::runCommand(Gui::Command::App, cmd.c_str());
640 }
641 catch (Base::PyException& e) {
642 e.reportException();
643 Base::Console().error("Stack Trace: %s\n", e.getStackTrace().c_str());
644 }
645 catch (Base::Exception& e) {
646 e.reportException();
647 }
648 catch (...) {
649 Base::Console().error("Unknown C++ exception in PropertyItem::setPropertyValue thrown\n");
650 }
651 }
652
653 void PropertyItem::setPropertyValue(const QString& value)
654 {
655 setPropertyValue(value.toStdString());
656 }
657
658 QVariant PropertyItem::dataPropertyName(int role) const
659 {
660 if (role == Qt::ForegroundRole && linked) {
661 return QVariant::fromValue(QColor(0x20, 0xaa, 0x20)); // NOLINT
662 }
663
664 if (role == Qt::BackgroundRole || role == Qt::ForegroundRole) {
665 if (PropertyView::showAll() && propertyItems.size() == 1
666 && propertyItems.front()->testStatus(App::Property::PropDynamic)
667 && !propertyItems.front()->testStatus(App::Property::LockDynamic)) {
668 return role == Qt::BackgroundRole
669 ? QVariant::fromValue(QColor(0xFF, 0xFF, 0x99)) // NOLINT
670 : QVariant::fromValue(QColor(0, 0, 0));
671 }
672 return {};
673 }
674 if (role == Qt::DisplayRole) {
675 return displayName();
676 }
677 // no properties set
678 if (propertyItems.empty()) {
679 return {};
680 }
681 if (role == Qt::ToolTipRole) {
682 QString type
683 = QStringLiteral("Type: %1\nName: %2")
684 .arg(QString::fromLatin1(propertyItems[0]->getTypeId().getName()), objectName());
685
686 QString doc = PropertyItem::toolTip(propertyItems[0]).toString();
687 if (doc.isEmpty()) {
688 doc = toolTip(propertyItems[0]).toString();
689 }
690 if (doc.size()) {
691 return type + QLatin1String("\n\n") + doc;
692 }
693 return type;
694 }
695
696 return {};
697 }
698
699 QVariant PropertyItem::dataValue(int role) const
700 {
701 // no properties set
702 if (propertyItems.empty()) {
703 PropertyItem* parent = this->parent();
704 if (!parent || !parent->parent()) {
705 return {};
706 }
707 if (role == Qt::EditRole) {
708 return parent->property(qPrintable(objectName()));
709 }
710 if (role == Qt::DecorationRole) {
711 QVariant val = parent->property(qPrintable(objectName()));
712 return decoration(val);
713 }
714 if (role == Qt::DisplayRole) {
715 QVariant val = parent->property(qPrintable(objectName()));
716 return toString(val);
717 }
718 if (role == Qt::ForegroundRole) {
719 if (hasExpression()) {
720 return QVariant::fromValue(QApplication::palette().color(QPalette::Link));
721 }
722 return {};
723 }
724
725 return {};
726 }
727 if (role == Qt::EditRole) {
728 return value(propertyItems[0]);
729 }
730 if (role == Qt::DecorationRole) {
731 return decoration(value(propertyItems[0]));
732 }
733 if (role == Qt::DisplayRole) {
734 return toString(value(propertyItems[0]));
735 }
736 if (role == Qt::ToolTipRole) {
737 return toolTip(propertyItems[0]);
738 }
739 if (role == Qt::ForegroundRole) {
740 if (hasExpression()) {
741 return QVariant::fromValue(QApplication::palette().color(QPalette::Link));
742 }
743 return {};
744 }
745
746 return {};
747 }
748
749 QVariant PropertyItem::data(int column, int role) const
750 {
751 if (column == PropertyItem::NameColumn) {
752 return dataPropertyName(role);
753 }
754
755 return dataValue(role);
756 }
757
758 bool PropertyItem::setData(const QVariant& value)
759 {
760 // This is the basic mechanism to set the value to
761 // a property and if no property is set for this item
762 // it delegates it to its parent which sets then the
763 // property or delegates again to its parent...
764 if (propertyItems.empty()) {
765 PropertyItem* parent = this->parent();
766 if (!parent || !parent->parent() || hasAnyExpression()) {
767 return false;
768 }
769
770 parent->setProperty(qPrintable(objectName()), value);
771 return true;
772 }
773
774 setValue(value);
775 return true;
776 }
777
778 Qt::ItemFlags PropertyItem::flags(int column) const
779 {
780 Qt::ItemFlags basicFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
781 if (column == 1 && !isReadOnly()) {
782 return basicFlags | Qt::ItemIsEditable;
783 }
784
785 return basicFlags;
786 }
787
788 int PropertyItem::row() const
789 {
790 if (parentItem) {
791 return parentItem->childItems.indexOf(const_cast<PropertyItem*>(this)); // NOLINT
792 }
793
794 return 0;
795 }
796
797 void PropertyItem::bind(const App::ObjectIdentifier& _path)
798 {
799 Gui::ExpressionBinding::bind(_path);
800 propertyBound();
801 }
802
803 void PropertyItem::bind(const App::Property& prop)
804 {
805 Gui::ExpressionBinding::bind(prop);
806 propertyBound();
807 }
808
809 QString PropertyItem::expressionAsString() const
810 {
811 if (hasExpression()) {
812 try {
813 std::unique_ptr<App::Expression> result(getExpression()->eval());
814 return QString::fromStdString(result->toString());
815 }
816 catch (const Base::Exception& e) {
817 e.reportException();
818 }
819 }
820
821 return {};
822 }
823
824 // --------------------------------------------------------------------
825
826 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyStringItem)
827
828 PropertyStringItem::PropertyStringItem() = default;
829
830 QVariant PropertyStringItem::value(const App::Property* prop) const
831 {
832 assert(prop && prop->isDerivedFrom<App::PropertyString>());
833
834 std::string value = static_cast<const App::PropertyString*>(prop)->getValue();
835 return {QString::fromUtf8(value.c_str())};
836 }
837
838 void PropertyStringItem::setValue(const QVariant& value)
839 {
840 if (!hasExpression() && value.canConvert<QString>()) {
841 std::string val = Base::InterpreterSingleton::strToPython(value.toString().toStdString());
842 setPropertyValue(Base::Tools::quoted(val));
843 }
844 }
845
846 QWidget* PropertyStringItem::createEditor(
847 QWidget* parent,
848 const std::function<void()>& method,
849 FrameOption frameOption
850 ) const
851 {
852 auto le = new ExpLineEdit(parent);
853 le->setFrame(static_cast<bool>(frameOption));
854 QObject::connect(le, &ExpLineEdit::textChanged, method);
855 if (isBound()) {
856 le->bind(getPath());
857 le->setAutoApply(autoApply());
858 }
859
860 return le;
861 }
862
863 void PropertyStringItem::setEditorData(QWidget* editor, const QVariant& data) const
864 {
865 auto le = qobject_cast<QLineEdit*>(editor);
866 le->setText(data.toString());
867 }
868
869 QVariant PropertyStringItem::editorData(QWidget* editor) const
870 {
871 auto le = qobject_cast<QLineEdit*>(editor);
872 return {le->text()};
873 }
874
875 // --------------------------------------------------------------------
876
877 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyFontItem)
878
879 PropertyFontItem::PropertyFontItem() = default;
880
881 QVariant PropertyFontItem::value(const App::Property* prop) const
882 {
883 assert(prop && prop->isDerivedFrom<App::PropertyFont>());
884
885 std::string value = static_cast<const App::PropertyFont*>(prop)->getValue();
886 return {QString::fromUtf8(value.c_str())};
887 }
888
889 void PropertyFontItem::setValue(const QVariant& value)
890 {
891 if (!hasExpression() && value.canConvert<QString>()) {
892 setPropertyValue(Base::Tools::quoted(value.toString().toStdString()));
893 }
894 }
895
896 QWidget* PropertyFontItem::createEditor(
897 QWidget* parent,
898 const std::function<void()>& method,
899 FrameOption frameOption
900 ) const
901 {
902 auto cb = new QComboBox(parent);
903 cb->setFrame(static_cast<bool>(frameOption));
904 QObject::connect(cb, &QComboBox::textActivated, method);
905 return cb;
906 }
907
908 void PropertyFontItem::setEditorData(QWidget* editor, const QVariant& data) const
909 {
910 auto cb = qobject_cast<QComboBox*>(editor);
911 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
912 QStringList familyNames = QFontDatabase().families(QFontDatabase::Any);
913 #else
914 QStringList familyNames = QFontDatabase::families(QFontDatabase::Any);
915 #endif
916 cb->addItems(familyNames);
917 int index = familyNames.indexOf(data.toString());
918 cb->setCurrentIndex(index);
919 }
920
921 QVariant PropertyFontItem::editorData(QWidget* editor) const
922 {
923 auto cb = qobject_cast<QComboBox*>(editor);
924 return {cb->currentText()};
925 }
926
927 // --------------------------------------------------------------------
928
929 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertySeparatorItem)
930
931 QWidget* PropertySeparatorItem::createEditor(
932 QWidget* parent,
933 const std::function<void()>& method,
934 FrameOption frameOption
935 ) const
936 {
937 Q_UNUSED(parent);
938 Q_UNUSED(method);
939 Q_UNUSED(frameOption);
940 return nullptr;
941 }
942
943 // --------------------------------------------------------------------
944
945 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyIntegerItem)
946
947 PropertyIntegerItem::PropertyIntegerItem() = default;
948
949 QVariant PropertyIntegerItem::value(const App::Property* prop) const
950 {
951 assert(prop && prop->isDerivedFrom<App::PropertyInteger>());
952
953 int value = (int)static_cast<const App::PropertyInteger*>(prop)->getValue();
954 return {value};
955 }
956
957 void PropertyIntegerItem::setValue(const QVariant& value)
958 {
959 // if the item has an expression it issues the python code
960 if (!hasExpression() && value.canConvert<int>()) {
961 int val = value.toInt();
962 setPropertyValue(std::to_string(val));
963 }
964 }
965
966 QWidget* PropertyIntegerItem::createEditor(
967 QWidget* parent,
968 const std::function<void()>& method,
969 FrameOption frameOption
970 ) const
971 {
972 auto sb = new Gui::IntSpinBox(parent);
973 sb->setFrame(static_cast<bool>(frameOption));
974 QObject::connect(sb, qOverload<int>(&Gui::IntSpinBox::valueChanged), method);
975
976 if (isBound()) {
977 sb->bind(getPath());
978 sb->setAutoApply(autoApply());
979 }
980
981 return sb;
982 }
983
984 void PropertyIntegerItem::setEditorData(QWidget* editor, const QVariant& data) const
985 {
986 auto sb = qobject_cast<QSpinBox*>(editor);
987 sb->setRange(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
988 sb->setValue(data.toInt());
989 }
990
991 QVariant PropertyIntegerItem::editorData(QWidget* editor) const
992 {
993 auto sb = qobject_cast<QSpinBox*>(editor);
994 return {sb->value()};
995 }
996
997 QString PropertyIntegerItem::toString(const QVariant& v) const
998 {
999 QString string(PropertyItem::toString(v));
1000
1001 if (hasExpression()) {
1002 string += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString()));
1003 }
1004
1005 return string;
1006 }
1007
1008
1009 // --------------------------------------------------------------------
1010
1011 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyIntegerConstraintItem)
1012
1013 PropertyIntegerConstraintItem::PropertyIntegerConstraintItem() = default;
1014
1015 QVariant PropertyIntegerConstraintItem::value(const App::Property* prop) const
1016 {
1017 assert(prop && prop->isDerivedFrom<App::PropertyIntegerConstraint>());
1018
1019 int value = (int)static_cast<const App::PropertyIntegerConstraint*>(prop)->getValue();
1020 return {value};
1021 }
1022
1023 void PropertyIntegerConstraintItem::setValue(const QVariant& value)
1024 {
1025 // if the item has an expression it issues the python code
1026 if (!hasExpression() && value.canConvert<int>()) {
1027 int val = value.toInt();
1028 setPropertyValue(std::to_string(val));
1029 }
1030 }
1031
1032 QWidget* PropertyIntegerConstraintItem::createEditor(
1033 QWidget* parent,
1034 const std::function<void()>& method,
1035 FrameOption frameOption
1036 ) const
1037 {
1038 auto sb = new Gui::IntSpinBox(parent);
1039 sb->setFrame(static_cast<bool>(frameOption));
1040 QObject::connect(sb, qOverload<int>(&Gui::IntSpinBox::valueChanged), method);
1041
1042 if (isBound()) {
1043 sb->bind(getPath());
1044 sb->setAutoApply(autoApply());
1045 }
1046
1047 return sb;
1048 }
1049
1050 void PropertyIntegerConstraintItem::setEditorData(QWidget* editor, const QVariant& data) const
1051 {
1052 const auto prop = static_cast<const App::PropertyIntegerConstraint*>(getFirstProperty());
1053
1054 const App::PropertyIntegerConstraint::Constraints* c = nullptr;
1055 if (prop) {
1056 c = prop->getConstraints();
1057 }
1058
1059 auto sb = qobject_cast<QSpinBox*>(editor);
1060 if (c) {
1061 sb->setMinimum(int(c->LowerBound));
1062 sb->setMaximum(int(c->UpperBound));
1063 sb->setSingleStep(int(c->StepSize));
1064 }
1065 else {
1066 sb->setMinimum(min);
1067 sb->setMaximum(max);
1068 sb->setSingleStep(steps);
1069 }
1070
1071 sb->setValue(data.toInt());
1072 }
1073
1074 QVariant PropertyIntegerConstraintItem::editorData(QWidget* editor) const
1075 {
1076 auto sb = qobject_cast<QSpinBox*>(editor);
1077 return {sb->value()};
1078 }
1079
1080 QString PropertyIntegerConstraintItem::toString(const QVariant& v) const
1081 {
1082 QString string(PropertyItem::toString(v));
1083
1084 if (hasExpression()) {
1085 string += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString()));
1086 }
1087
1088 return string;
1089 }
1090
1091
1092 // --------------------------------------------------------------------
1093
1094 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyFloatItem)
1095
1096 PropertyFloatItem::PropertyFloatItem() = default;
1097
1098 QString PropertyFloatItem::toString(const QVariant& prop) const
1099 {
1100 double value = prop.toDouble();
1101 QString data = QLocale().toString(value, 'f', decimals());
1102
1103 if (hasExpression()) {
1104 data += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString()));
1105 }
1106
1107 return data;
1108 }
1109
1110 QVariant PropertyFloatItem::value(const App::Property* prop) const
1111 {
1112 assert(prop && prop->isDerivedFrom<App::PropertyFloat>());
1113
1114 double value = static_cast<const App::PropertyFloat*>(prop)->getValue();
1115 return {value};
1116 }
1117
1118 void PropertyFloatItem::setValue(const QVariant& value)
1119 {
1120 // if the item has an expression it issues the python code
1121 if (!hasExpression() && value.canConvert<double>()) {
1122 std::ostringstream ss;
1123 ss << std::setprecision(highPrec) << value.toDouble();
1124 setPropertyValue(ss.str());
1125 }
1126 }
1127
1128 QWidget* PropertyFloatItem::createEditor(
1129 QWidget* parent,
1130 const std::function<void()>& method,
1131 FrameOption frameOption
1132 ) const
1133 {
1134 auto sb = new Gui::DoubleSpinBox(parent);
1135 sb->setFrame(static_cast<bool>(frameOption));
1136 sb->setDecimals(decimals());
1137 QObject::connect(sb, qOverload<double>(&Gui::DoubleSpinBox::valueChanged), method);
1138
1139 if (isBound()) {
1140 sb->bind(getPath());
1141 sb->setAutoApply(autoApply());
1142 }
1143
1144 return sb;
1145 }
1146
1147 void PropertyFloatItem::setEditorData(QWidget* editor, const QVariant& data) const
1148 {
1149 auto sb = qobject_cast<QDoubleSpinBox*>(editor);
1150 sb->setRange(
1151 static_cast<double>(std::numeric_limits<int>::min()),
1152 static_cast<double>(std::numeric_limits<int>::max())
1153 );
1154 sb->setValue(data.toDouble());
1155 }
1156
1157 QVariant PropertyFloatItem::editorData(QWidget* editor) const
1158 {
1159 auto sb = qobject_cast<QDoubleSpinBox*>(editor);
1160 return {sb->value()};
1161 }
1162
1163 // --------------------------------------------------------------------
1164
1165
1166 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyUnitItem)
1167
1168 PropertyUnitItem::PropertyUnitItem() = default;
1169
1170 QString PropertyUnitItem::toString(const QVariant& prop) const
1171 {
1172 const Base::Quantity& unit = prop.value<Base::Quantity>();
1173 std::string str = unit.getUserString();
1174 if (hasExpression()) {
1175 str += fmt::format(" ( {} )", getExpressionString());
1176 }
1177
1178 return QString::fromStdString(str);
1179 }
1180
1181 QVariant PropertyUnitItem::value(const App::Property* prop) const
1182 {
1183 assert(prop && prop->isDerivedFrom<App::PropertyQuantity>());
1184
1185 Base::Quantity value = static_cast<const App::PropertyQuantity*>(prop)->getQuantityValue();
1186 return QVariant::fromValue<Base::Quantity>(value);
1187 }
1188
1189 void PropertyUnitItem::setValue(const QVariant& value)
1190 {
1191 // if the item has an expression it handles the python code
1192 if (!hasExpression() && value.canConvert<Base::Quantity>()) {
1193 const Base::Quantity& val = value.value<Base::Quantity>();
1194 Base::QuantityFormat format(Base::QuantityFormat::Default, highPrec);
1195 setPropertyValue(val.toString(format));
1196 }
1197 }
1198
1199 QWidget* PropertyUnitItem::createEditor(
1200 QWidget* parent,
1201 const std::function<void()>& method,
1202 FrameOption frameOption
1203 ) const
1204 {
1205 auto infield = new Gui::QuantitySpinBox(parent);
1206 infield->setFrame(static_cast<bool>(frameOption));
1207 infield->setMinimumHeight(0);
1208
1209 // if we are bound to an expression we need to bind it to the input field
1210 if (isBound()) {
1211 infield->bind(getPath());
1212 infield->setAutoApply(autoApply());
1213 }
1214
1215 QObject::connect(infield, qOverload<double>(&Gui::QuantitySpinBox::valueChanged), method);
1216 return infield;
1217 }
1218
1219 void PropertyUnitItem::setEditorData(QWidget* editor, const QVariant& data) const
1220 {
1221 const Base::Quantity& value = data.value<Base::Quantity>();
1222
1223 auto infield = qobject_cast<Gui::QuantitySpinBox*>(editor);
1224 infield->setValue(value);
1225 infield->selectAll();
1226 }
1227
1228 QVariant PropertyUnitItem::editorData(QWidget* editor) const
1229 {
1230 auto infield = qobject_cast<Gui::QuantitySpinBox*>(editor);
1231 Base::Quantity value = infield->value();
1232 return QVariant::fromValue<Base::Quantity>(value);
1233 }
1234
1235 // --------------------------------------------------------------------
1236
1237
1238 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyUnitConstraintItem)
1239
1240 PropertyUnitConstraintItem::PropertyUnitConstraintItem() = default;
1241
1242 void PropertyUnitConstraintItem::setEditorData(QWidget* editor, const QVariant& data) const
1243 {
1244 const Base::Quantity& value = data.value<Base::Quantity>();
1245
1246 auto infield = qobject_cast<Gui::QuantitySpinBox*>(editor);
1247 infield->setValue(value);
1248 infield->selectAll();
1249
1250 const auto prop = static_cast<const App::PropertyQuantityConstraint*>(getFirstProperty());
1251
1252 const App::PropertyQuantityConstraint::Constraints* c = nullptr;
1253 if (prop) {
1254 c = prop->getConstraints();
1255 }
1256
1257 if (c) {
1258 infield->setMinimum(c->LowerBound);
1259 infield->setMaximum(c->UpperBound);
1260 infield->setSingleStep(c->StepSize);
1261 }
1262 else {
1263 infield->setMinimum(min);
1264 infield->setMaximum(max);
1265 infield->setSingleStep(steps);
1266 }
1267 }
1268
1269 // --------------------------------------------------------------------
1270
1271 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyFloatConstraintItem)
1272
1273 PropertyFloatConstraintItem::PropertyFloatConstraintItem() = default;
1274
1275 QString PropertyFloatConstraintItem::toString(const QVariant& prop) const
1276 {
1277 double value = prop.toDouble();
1278 return QLocale().toString(value, 'f', decimals());
1279 }
1280
1281 QVariant PropertyFloatConstraintItem::value(const App::Property* prop) const
1282 {
1283 assert(prop && prop->isDerivedFrom<App::PropertyFloatConstraint>());
1284
1285 double value = static_cast<const App::PropertyFloatConstraint*>(prop)->getValue();
1286 return {value};
1287 }
1288
1289 void PropertyFloatConstraintItem::setValue(const QVariant& value)
1290 {
1291 // if the item has an expression it issues the python code
1292 if (!hasExpression() && value.canConvert<double>()) {
1293 std::ostringstream ss;
1294 ss << std::setprecision(highPrec) << value.toDouble();
1295 setPropertyValue(ss.str());
1296 }
1297 }
1298
1299 QWidget* PropertyFloatConstraintItem::createEditor(
1300 QWidget* parent,
1301 const std::function<void()>& method,
1302 FrameOption frameOption
1303 ) const
1304 {
1305 auto sb = new Gui::DoubleSpinBox(parent);
1306 sb->setDecimals(decimals());
1307 sb->setFrame(static_cast<bool>(frameOption));
1308 QObject::connect(sb, qOverload<double>(&Gui::DoubleSpinBox::valueChanged), method);
1309
1310 if (isBound()) {
1311 sb->bind(getPath());
1312 sb->setAutoApply(autoApply());
1313 }
1314
1315 return sb;
1316 }
1317
1318 void PropertyFloatConstraintItem::setEditorData(QWidget* editor, const QVariant& data) const
1319 {
1320 const auto prop = static_cast<const App::PropertyFloatConstraint*>(getFirstProperty());
1321
1322 const App::PropertyFloatConstraint::Constraints* c = nullptr;
1323 if (prop) {
1324 c = prop->getConstraints();
1325 }
1326
1327 auto sb = qobject_cast<QDoubleSpinBox*>(editor);
1328 if (c) {
1329 sb->setMinimum(c->LowerBound);
1330 sb->setMaximum(c->UpperBound);
1331 sb->setSingleStep(c->StepSize);
1332 }
1333 else {
1334 sb->setMinimum(min);
1335 sb->setMaximum(max);
1336 sb->setSingleStep(steps);
1337 }
1338
1339 sb->setValue(data.toDouble());
1340 }
1341
1342 QVariant PropertyFloatConstraintItem::editorData(QWidget* editor) const
1343 {
1344 auto sb = qobject_cast<QDoubleSpinBox*>(editor);
1345 return {sb->value()};
1346 }
1347
1348 // --------------------------------------------------------------------
1349
1350 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyPrecisionItem)
1351
1352 PropertyPrecisionItem::PropertyPrecisionItem()
1353 {
1354 setDecimals(highPrec);
1355 }
1356
1357 // --------------------------------------------------------------------
1358
1359 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyAngleItem)
1360
1361 PropertyAngleItem::PropertyAngleItem() = default;
1362
1363 void PropertyAngleItem::setEditorData(QWidget* editor, const QVariant& data) const
1364 {
1365 PropertyUnitConstraintItem::setEditorData(editor, data);
1366 }
1367
1368 QString PropertyAngleItem::toString(const QVariant& prop) const
1369 {
1370 return PropertyUnitConstraintItem::toString(prop);
1371 }
1372
1373 // --------------------------------------------------------------------
1374
1375 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyBoolItem)
1376
1377 PropertyBoolItem::PropertyBoolItem() = default;
1378
1379 QVariant PropertyBoolItem::value(const App::Property* prop) const
1380 {
1381 assert(prop && prop->isDerivedFrom<App::PropertyBool>());
1382
1383 bool value = static_cast<const App::PropertyBool*>(prop)->getValue();
1384 return {value};
1385 }
1386
1387 void PropertyBoolItem::setValue(const QVariant& value)
1388 {
1389 if (!hasExpression() && value.canConvert<bool>()) {
1390 std::string val = value.toBool() ? "True" : "False";
1391 setPropertyValue(val);
1392 }
1393 }
1394
1395 QWidget* PropertyBoolItem::
1396 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
1397 {
1398 auto checkbox = new QCheckBox(parent);
1399 #if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
1400 QObject::connect(checkbox, &QCheckBox::stateChanged, method);
1401 #else
1402 QObject::connect(checkbox, &QCheckBox::checkStateChanged, method);
1403 #endif
1404
1405 return checkbox;
1406 }
1407
1408 void PropertyBoolItem::setEditorData(QWidget* editor, const QVariant& data) const
1409 {
1410 if (auto checkbox = qobject_cast<QCheckBox*>(editor)) {
1411 checkbox->setChecked(data.toBool());
1412 }
1413 }
1414
1415 QVariant PropertyBoolItem::editorData(QWidget* editor) const
1416 {
1417 if (auto checkbox = qobject_cast<QCheckBox*>(editor)) {
1418 return checkbox->isChecked();
1419 }
1420 return false;
1421 }
1422
1423 // ---------------------------------------------------------------
1424
1425 namespace Gui::PropertyEditor
1426 {
1427 class VectorLineEdit: public Gui::ExpLineEdit
1428 {
1429 int decimals;
1430
1431 public:
1432 explicit VectorLineEdit(int decimals, QWidget* parent = nullptr, bool expressionOnly = false)
1433 : Gui::ExpLineEdit(parent, expressionOnly)
1434 , decimals(decimals)
1435 {}
1436
1437 bool apply(const std::string& propName) override
1438 {
1439 // NOLINTNEXTLINE
1440 if (!ExpressionBinding::apply(propName)) { // clazy:exclude=skipped-base-method
1441 QVariant data = property("coords");
1442 if (data.canConvert<Base::Vector3d>()) {
1443 const Base::Vector3d& value = data.value<Base::Vector3d>();
1444
1445 QString str = QStringLiteral("(%1, %2, %3)")
1446 .arg(value.x, 0, 'f', decimals)
1447 .arg(value.y, 0, 'f', decimals)
1448 .arg(value.z, 0, 'f', decimals);
1449
1450 Gui::Command::doCommand(
1451 Gui::Command::Doc,
1452 "%s = %s",
1453 propName.c_str(),
1454 str.toLatin1().constData()
1455 );
1456 return true;
1457 }
1458 }
1459
1460 return false;
1461 }
1462 };
1463 } // namespace Gui::PropertyEditor
1464
1465 // ---------------------------------------------------------------
1466
1467 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyVectorItem)
1468
1469 PropertyVectorItem::PropertyVectorItem()
1470 {
1471 m_x = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1472 m_x->setParent(this);
1473 m_x->setPropertyName(QLatin1String("x"));
1474 this->appendChild(m_x);
1475 m_y = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1476 m_y->setParent(this);
1477 m_y->setPropertyName(QLatin1String("y"));
1478 this->appendChild(m_y);
1479 m_z = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1480 m_z->setParent(this);
1481 m_z->setPropertyName(QLatin1String("z"));
1482 this->appendChild(m_z);
1483 }
1484
1485 QString PropertyVectorItem::toString(const QVariant& prop) const
1486 {
1487 QLocale loc;
1488 const Base::Vector3d& value = prop.value<Base::Vector3d>();
1489 QString data = QStringLiteral("[%1 %2 %3]")
1490 .arg(
1491 loc.toString(value.x, 'f', lowPrec),
1492 loc.toString(value.y, 'f', lowPrec),
1493 loc.toString(value.z, 'f', lowPrec)
1494 );
1495 if (hasExpression()) {
1496 data += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString()));
1497 }
1498 return data;
1499 }
1500
1501 QVariant PropertyVectorItem::value(const App::Property* prop) const
1502 {
1503 assert(prop && prop->isDerivedFrom<App::PropertyVector>());
1504
1505 const Base::Vector3d& value = static_cast<const App::PropertyVector*>(prop)->getValue();
1506 return QVariant::fromValue<Base::Vector3d>(value);
1507 }
1508
1509 void PropertyVectorItem::setValue(const QVariant& value)
1510 {
1511 if (hasExpression() || !value.canConvert<Base::Vector3d>()) {
1512 return;
1513 }
1514 const Base::Vector3d& val = value.value<Base::Vector3d>();
1515 QString data = QStringLiteral("(%1, %2, %3)")
1516 .arg(val.x, 0, 'g', highPrec)
1517 .arg(val.y, 0, 'g', highPrec)
1518 .arg(val.z, 0, 'g', highPrec);
1519 setPropertyValue(data);
1520 }
1521
1522 QWidget* PropertyVectorItem::createEditor(
1523 QWidget* parent,
1524 const std::function<void()>& /*method*/,
1525 FrameOption frameOption
1526 ) const
1527 {
1528 auto le = new VectorLineEdit(decimals(), parent);
1529 le->setFrame(static_cast<bool>(frameOption));
1530 le->setReadOnly(true);
1531
1532 if (isBound()) {
1533 le->bind(getPath());
1534 le->setAutoApply(autoApply());
1535 }
1536
1537 return le;
1538 }
1539
1540 void PropertyVectorItem::setEditorData(QWidget* editor, const QVariant& data) const
1541 {
1542 QLocale loc;
1543 auto le = qobject_cast<QLineEdit*>(editor);
1544 const Base::Vector3d& value = data.value<Base::Vector3d>();
1545 QString text = QStringLiteral("[%1 %2 %3]")
1546 .arg(
1547 loc.toString(value.x, 'f', lowPrec),
1548 loc.toString(value.y, 'f', lowPrec),
1549 loc.toString(value.z, 'f', lowPrec)
1550 );
1551 le->setProperty("coords", data);
1552 le->setText(text);
1553 }
1554
1555 QVariant PropertyVectorItem::editorData(QWidget* editor) const
1556 {
1557 auto le = qobject_cast<QLineEdit*>(editor);
1558 return {le->text()};
1559 }
1560
1561 double PropertyVectorItem::x() const
1562 {
1563 return data(1, Qt::EditRole).value<Base::Vector3d>().x;
1564 }
1565
1566 void PropertyVectorItem::setX(double x)
1567 {
1568 setData(QVariant::fromValue(Base::Vector3d(x, y(), z())));
1569 }
1570
1571 double PropertyVectorItem::y() const
1572 {
1573 return data(1, Qt::EditRole).value<Base::Vector3d>().y;
1574 }
1575
1576 void PropertyVectorItem::setY(double y)
1577 {
1578 setData(QVariant::fromValue(Base::Vector3d(x(), y, z())));
1579 }
1580
1581 double PropertyVectorItem::z() const
1582 {
1583 return data(1, Qt::EditRole).value<Base::Vector3d>().z;
1584 }
1585
1586 void PropertyVectorItem::setZ(double z)
1587 {
1588 setData(QVariant::fromValue(Base::Vector3d(x(), y(), z)));
1589 }
1590
1591 void PropertyVectorItem::propertyBound()
1592 {
1593 m_x->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("x"));
1594 m_y->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("y"));
1595 m_z->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("z"));
1596 }
1597
1598 // ---------------------------------------------------------------
1599
1600 PropertyEditorWidget::PropertyEditorWidget(QWidget* parent)
1601 : QWidget(parent)
1602 {
1603 auto layout = new QHBoxLayout(this);
1604 layout->setContentsMargins(0, 0, 0, 0);
1605 layout->setSpacing(2);
1606
1607 lineEdit = new QLineEdit(this);
1608 lineEdit->setReadOnly(true);
1609 layout->addWidget(lineEdit);
1610
1611 button = new QPushButton(QStringLiteral("…"), this);
1612 #if defined(Q_OS_MACOS)
1613 button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct
1614 #endif
1615 layout->addWidget(button);
1616
1617 connect(button, &QPushButton::clicked, this, &PropertyEditorWidget::buttonClick);
1618
1619 // QAbstractItemView will call selectAll() if a QLineEdit is the focus
1620 // proxy. Since the QLineEdit here is read-only and not meant for editing,
1621 // do not set it as focus proxy. Otherwise, the text won't even shown for
1622 // most stylesheets (which contain a trick to hide the content of a selected
1623 // read-only/disabled editor widgets).
1624 //
1625 // setFocusProxy(lineEdit);
1626 }
1627
1628 PropertyEditorWidget::~PropertyEditorWidget() = default;
1629
1630 void PropertyEditorWidget::resizeEvent(QResizeEvent* e)
1631 {
1632 button->setFixedWidth(e->size().height());
1633 button->setFixedHeight(e->size().height());
1634 }
1635
1636 void PropertyEditorWidget::showValue(const QVariant& d)
1637 {
1638 lineEdit->setText(d.toString());
1639 }
1640
1641 QVariant PropertyEditorWidget::value() const
1642 {
1643 return variant;
1644 }
1645
1646 void PropertyEditorWidget::setValue(const QVariant& val)
1647 {
1648 variant = val;
1649 showValue(variant);
1650 Q_EMIT valueChanged(variant);
1651 }
1652
1653 // ---------------------------------------------------------------
1654
1655 VectorListWidget::VectorListWidget(int decimals, QWidget* parent)
1656 : PropertyEditorWidget(parent)
1657 , decimals(decimals)
1658 {
1659 connect(button, &QPushButton::clicked, this, &VectorListWidget::buttonClicked);
1660 }
1661
1662 void VectorListWidget::buttonClicked()
1663 {
1664 auto dlg = new VectorListEditor(decimals, this);
1665 dlg->setAttribute(Qt::WA_DeleteOnClose);
1666 dlg->setValues(value().value<QList<Base::Vector3d>>());
1667 QPoint p(0, 0);
1668 p = this->mapToGlobal(p);
1669 dlg->move(p);
1670 connect(dlg, &VectorListEditor::accepted, this, [this, dlg] {
1671 QVariant data = QVariant::fromValue<QList<Base::Vector3d>>(dlg->getValues());
1672 setValue(data);
1673 });
1674
1675 Gui::adjustDialogPosition(dlg);
1676 dlg->exec();
1677 }
1678
1679 void VectorListWidget::showValue(const QVariant& d)
1680 {
1681 QLocale loc;
1682 QString data;
1683 const QList<Base::Vector3d>& value = d.value<QList<Base::Vector3d>>();
1684 if (value.isEmpty()) {
1685 data = QStringLiteral("[]");
1686 }
1687 else {
1688 data = QStringLiteral("[%1 %2 %3], ...")
1689 .arg(
1690 loc.toString(value[0].x, 'f', lowPrec),
1691 loc.toString(value[0].y, 'f', lowPrec),
1692 loc.toString(value[0].z, 'f', lowPrec)
1693 );
1694 }
1695 lineEdit->setText(data);
1696 }
1697 // ---------------------------------------------------------------
1698
1699 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyVectorListItem)
1700
1701 PropertyVectorListItem::PropertyVectorListItem() = default;
1702
1703 QString PropertyVectorListItem::toString(const QVariant& prop) const
1704 {
1705 const QList<Base::Vector3d>& value = prop.value<QList<Base::Vector3d>>();
1706 if (value.isEmpty()) {
1707 return QStringLiteral("[]");
1708 }
1709 QLocale loc;
1710 QString data = QStringLiteral("[%1 %2 %3], ...")
1711 .arg(
1712 loc.toString(value[0].x, 'f', lowPrec),
1713 loc.toString(value[0].y, 'f', lowPrec),
1714 loc.toString(value[0].z, 'f', lowPrec)
1715 );
1716
1717 if (hasExpression()) {
1718 data += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString()));
1719 }
1720 return data;
1721 }
1722
1723 QVariant PropertyVectorListItem::value(const App::Property* prop) const
1724 {
1725 assert(prop && prop->isDerivedFrom<App::PropertyVectorList>());
1726
1727 const std::vector<Base::Vector3d>& value
1728 = static_cast<const App::PropertyVectorList*>(prop)->getValue();
1729 QList<Base::Vector3d> list;
1730 std::copy(value.begin(), value.end(), std::back_inserter(list));
1731 return QVariant::fromValue<QList<Base::Vector3d>>(list);
1732 }
1733
1734 void PropertyVectorListItem::setValue(const QVariant& value)
1735 {
1736 if (!value.canConvert<QList<Base::Vector3d>>()) {
1737 return;
1738 }
1739 const QList<Base::Vector3d>& val = value.value<QList<Base::Vector3d>>();
1740 QString data;
1741 QTextStream str(&data);
1742 str << "[";
1743 for (const auto& it : val) {
1744 str << QStringLiteral("(%1, %2, %3), ")
1745 .arg(it.x, 0, 'g', highPrec)
1746 .arg(it.y, 0, 'g', highPrec)
1747 .arg(it.z, 0, 'g', highPrec);
1748 }
1749 str << "]";
1750 setPropertyValue(data);
1751 }
1752
1753 QWidget* PropertyVectorListItem::
1754 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
1755 {
1756 auto pe = new VectorListWidget(decimals(), parent);
1757 QObject::connect(pe, &VectorListWidget::valueChanged, method);
1758 return pe;
1759 }
1760
1761 void PropertyVectorListItem::setEditorData(QWidget* editor, const QVariant& data) const
1762 {
1763 auto pe = qobject_cast<VectorListWidget*>(editor);
1764 pe->setValue(data);
1765 }
1766
1767 QVariant PropertyVectorListItem::editorData(QWidget* editor) const
1768 {
1769 auto pe = qobject_cast<VectorListWidget*>(editor);
1770 return pe->value();
1771 }
1772
1773 // ---------------------------------------------------------------
1774
1775 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyVectorDistanceItem)
1776
1777 PropertyVectorDistanceItem::PropertyVectorDistanceItem()
1778 {
1779 m_x = static_cast<PropertyUnitItem*>(PropertyUnitItem::create());
1780 m_x->setParent(this);
1781 m_x->setPropertyName(QLatin1String("x"));
1782 this->appendChild(m_x);
1783 m_y = static_cast<PropertyUnitItem*>(PropertyUnitItem::create());
1784 m_y->setParent(this);
1785 m_y->setPropertyName(QLatin1String("y"));
1786 this->appendChild(m_y);
1787 m_z = static_cast<PropertyUnitItem*>(PropertyUnitItem::create());
1788 m_z->setParent(this);
1789 m_z->setPropertyName(QLatin1String("z"));
1790 this->appendChild(m_z);
1791 }
1792
1793 QString PropertyVectorDistanceItem::toString(const QVariant& prop) const
1794 {
1795 const Base::Vector3d& value = prop.value<Base::Vector3d>();
1796 std::string str = fmt::format(
1797 "[{} {} {}]",
1798 Base::Quantity(value.x, Base::Unit::Length).getUserString(),
1799 Base::Quantity(value.y, Base::Unit::Length).getUserString(),
1800 Base::Quantity(value.z, Base::Unit::Length).getUserString()
1801 );
1802 if (hasExpression()) {
1803 str += fmt::format(" ( {} )", getExpressionString());
1804 }
1805 return QString::fromStdString(str);
1806 }
1807
1808
1809 QVariant PropertyVectorDistanceItem::value(const App::Property* prop) const
1810 {
1811 assert(prop && prop->isDerivedFrom<App::PropertyVector>());
1812
1813 const Base::Vector3d& value = static_cast<const App::PropertyVector*>(prop)->getValue();
1814 return QVariant::fromValue<Base::Vector3d>(value);
1815 }
1816
1817 void PropertyVectorDistanceItem::setValue(const QVariant& variant)
1818 {
1819 if (hasExpression() || !variant.canConvert<Base::Vector3d>()) {
1820 return;
1821 }
1822 const Base::Vector3d& value = variant.value<Base::Vector3d>();
1823 std::string val = fmt::format(
1824 "({:.{}g}, {:.{}g}, {:.{}g})",
1825 value.x,
1826 highPrec,
1827 value.y,
1828 highPrec,
1829 value.z,
1830 highPrec
1831 );
1832 setPropertyValue(val);
1833 }
1834
1835 void PropertyVectorDistanceItem::setEditorData(QWidget* editor, const QVariant& data) const
1836 {
1837 auto le = qobject_cast<QLineEdit*>(editor);
1838 le->setProperty("coords", data);
1839 le->setText(toString(data));
1840 }
1841
1842 QWidget* PropertyVectorDistanceItem::createEditor(
1843 QWidget* parent,
1844 const std::function<void()>& /*method*/,
1845 FrameOption frameOption
1846 ) const
1847 {
1848 auto le = new VectorLineEdit(decimals(), parent);
1849 le->setFrame(static_cast<bool>(frameOption));
1850 le->setReadOnly(true);
1851
1852 if (isBound()) {
1853 le->bind(getPath());
1854 le->setAutoApply(autoApply());
1855 }
1856
1857 return le;
1858 }
1859
1860 QVariant PropertyVectorDistanceItem::editorData(QWidget* editor) const
1861 {
1862 auto le = qobject_cast<QLineEdit*>(editor);
1863 return {le->text()};
1864 }
1865
1866 Base::Quantity PropertyVectorDistanceItem::x() const
1867 {
1868 return Base::Quantity(data(1, Qt::EditRole).value<Base::Vector3d>().x, Base::Unit::Length);
1869 }
1870
1871 void PropertyVectorDistanceItem::setX(Base::Quantity x)
1872 {
1873 setData(QVariant::fromValue(Base::Vector3d(x.getValue(), y().getValue(), z().getValue())));
1874 }
1875
1876 Base::Quantity PropertyVectorDistanceItem::y() const
1877 {
1878 return Base::Quantity(data(1, Qt::EditRole).value<Base::Vector3d>().y, Base::Unit::Length);
1879 }
1880
1881 void PropertyVectorDistanceItem::setY(Base::Quantity y)
1882 {
1883 setData(QVariant::fromValue(Base::Vector3d(x().getValue(), y.getValue(), z().getValue())));
1884 }
1885
1886 Base::Quantity PropertyVectorDistanceItem::z() const
1887 {
1888 return Base::Quantity(data(1, Qt::EditRole).value<Base::Vector3d>().z, Base::Unit::Length);
1889 }
1890
1891 void PropertyVectorDistanceItem::setZ(Base::Quantity z)
1892 {
1893 setData(QVariant::fromValue(Base::Vector3d(x().getValue(), y().getValue(), z.getValue())));
1894 }
1895
1896 void PropertyVectorDistanceItem::propertyBound()
1897 {
1898 if (isBound()) {
1899 m_x->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("x"));
1900 m_y->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("y"));
1901 m_z->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("z"));
1902 };
1903 }
1904
1905 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyPositionItem)
1906
1907 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyDirectionItem)
1908
1909 // ---------------------------------------------------------------
1910
1911 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyMatrixItem)
1912
1913 PropertyMatrixItem::PropertyMatrixItem()
1914 {
1915 const int decimals = highPrec;
1916 m_a11 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1917 m_a11->setParent(this);
1918 m_a11->setPropertyName(QLatin1String("A11"));
1919 m_a11->setDecimals(decimals);
1920 this->appendChild(m_a11);
1921 m_a12 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1922 m_a12->setParent(this);
1923 m_a12->setPropertyName(QLatin1String("A12"));
1924 m_a12->setDecimals(decimals);
1925 this->appendChild(m_a12);
1926 m_a13 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1927 m_a13->setParent(this);
1928 m_a13->setPropertyName(QLatin1String("A13"));
1929 m_a13->setDecimals(decimals);
1930 this->appendChild(m_a13);
1931 m_a14 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1932 m_a14->setParent(this);
1933 m_a14->setPropertyName(QLatin1String("A14"));
1934 m_a14->setDecimals(decimals);
1935 this->appendChild(m_a14);
1936 m_a21 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1937 m_a21->setParent(this);
1938 m_a21->setPropertyName(QLatin1String("A21"));
1939 m_a21->setDecimals(decimals);
1940 this->appendChild(m_a21);
1941 m_a22 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1942 m_a22->setParent(this);
1943 m_a22->setPropertyName(QLatin1String("A22"));
1944 m_a22->setDecimals(decimals);
1945 this->appendChild(m_a22);
1946 m_a23 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1947 m_a23->setParent(this);
1948 m_a23->setPropertyName(QLatin1String("A23"));
1949 m_a23->setDecimals(decimals);
1950 this->appendChild(m_a23);
1951 m_a24 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1952 m_a24->setParent(this);
1953 m_a24->setPropertyName(QLatin1String("A24"));
1954 m_a24->setDecimals(decimals);
1955 this->appendChild(m_a24);
1956 m_a31 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1957 m_a31->setParent(this);
1958 m_a31->setPropertyName(QLatin1String("A31"));
1959 m_a31->setDecimals(decimals);
1960 this->appendChild(m_a31);
1961 m_a32 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1962 m_a32->setParent(this);
1963 m_a32->setPropertyName(QLatin1String("A32"));
1964 m_a32->setDecimals(decimals);
1965 this->appendChild(m_a32);
1966 m_a33 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1967 m_a33->setParent(this);
1968 m_a33->setPropertyName(QLatin1String("A33"));
1969 m_a33->setDecimals(decimals);
1970 this->appendChild(m_a33);
1971 m_a34 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1972 m_a34->setParent(this);
1973 m_a34->setPropertyName(QLatin1String("A34"));
1974 m_a34->setDecimals(decimals);
1975 this->appendChild(m_a34);
1976 m_a41 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1977 m_a41->setParent(this);
1978 m_a41->setPropertyName(QLatin1String("A41"));
1979 m_a41->setDecimals(decimals);
1980 this->appendChild(m_a41);
1981 m_a42 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1982 m_a42->setParent(this);
1983 m_a42->setPropertyName(QLatin1String("A42"));
1984 m_a42->setDecimals(decimals);
1985 this->appendChild(m_a42);
1986 m_a43 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1987 m_a43->setParent(this);
1988 m_a43->setPropertyName(QLatin1String("A43"));
1989 m_a43->setDecimals(decimals);
1990 this->appendChild(m_a43);
1991 m_a44 = static_cast<PropertyFloatItem*>(PropertyFloatItem::create());
1992 m_a44->setParent(this);
1993 m_a44->setPropertyName(QLatin1String("A44"));
1994 m_a44->setDecimals(decimals);
1995 this->appendChild(m_a44);
1996 }
1997
1998 QString PropertyMatrixItem::toString(const QVariant& prop) const
1999 {
2000 QLocale loc;
2001 const Base::Matrix4D& value = prop.value<Base::Matrix4D>();
2002 // NOLINTBEGIN
2003 QString text = QStringLiteral("[%1 %2 %3 %4 %5 %6 %7 %8 %9 %10 %11 %12 %13 %14 %15 %16]")
2004 .arg(
2005 loc.toString(value[0][0], 'f', lowPrec), //(unsigned short usNdx)
2006 loc.toString(value[0][1], 'f', lowPrec),
2007 loc.toString(value[0][2], 'f', lowPrec),
2008 loc.toString(value[0][3], 'f', lowPrec),
2009 loc.toString(value[1][0], 'f', lowPrec),
2010 loc.toString(value[1][1], 'f', lowPrec),
2011 loc.toString(value[1][2], 'f', lowPrec),
2012 loc.toString(value[1][3], 'f', lowPrec),
2013 loc.toString(value[2][0], 'f', lowPrec)
2014 )
2015 .arg(
2016 loc.toString(value[2][1], 'f', lowPrec),
2017 loc.toString(value[2][2], 'f', lowPrec),
2018 loc.toString(value[2][3], 'f', lowPrec),
2019 loc.toString(value[3][0], 'f', lowPrec),
2020 loc.toString(value[3][1], 'f', lowPrec),
2021 loc.toString(value[3][2], 'f', lowPrec),
2022 loc.toString(value[3][3], 'f', lowPrec)
2023 );
2024 // NOLINTEND
2025 return text;
2026 }
2027
2028 QVariant PropertyMatrixItem::value(const App::Property* prop) const
2029 {
2030 assert(prop && prop->isDerivedFrom<App::PropertyMatrix>());
2031
2032 const Base::Matrix4D& value = static_cast<const App::PropertyMatrix*>(prop)->getValue();
2033 return QVariant::fromValue<Base::Matrix4D>(value);
2034 }
2035
2036 QVariant PropertyMatrixItem::toolTip(const App::Property* prop) const
2037 {
2038 assert(prop && prop->isDerivedFrom<App::PropertyMatrix>());
2039
2040 const Base::Matrix4D& value = static_cast<const App::PropertyMatrix*>(prop)->getValue();
2041 return {QString::fromStdString(value.analyse())};
2042 }
2043
2044 void PropertyMatrixItem::setValue(const QVariant& value)
2045 {
2046 if (hasExpression() || !value.canConvert<Base::Matrix4D>()) {
2047 return;
2048 }
2049 const Base::Matrix4D& val = value.value<Base::Matrix4D>();
2050 // NOLINTBEGIN
2051 QString data
2052 = QStringLiteral("FreeCAD.Matrix(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16)")
2053 .arg(val[0][0], 0, 'g', highPrec)
2054 .arg(val[0][1], 0, 'g', highPrec)
2055 .arg(val[0][2], 0, 'g', highPrec)
2056 .arg(val[0][3], 0, 'g', highPrec)
2057 .arg(val[1][0], 0, 'g', highPrec)
2058 .arg(val[1][1], 0, 'g', highPrec)
2059 .arg(val[1][2], 0, 'g', highPrec)
2060 .arg(val[1][3], 0, 'g', highPrec)
2061 .arg(val[2][0], 0, 'g', highPrec)
2062 .arg(val[2][1], 0, 'g', highPrec)
2063 .arg(val[2][2], 0, 'g', highPrec)
2064 .arg(val[2][3], 0, 'g', highPrec)
2065 .arg(val[3][0], 0, 'g', highPrec)
2066 .arg(val[3][1], 0, 'g', highPrec)
2067 .arg(val[3][2], 0, 'g', highPrec)
2068 .arg(val[3][3], 0, 'g', highPrec);
2069 // NOLINTEND
2070 setPropertyValue(data);
2071 }
2072
2073 QWidget* PropertyMatrixItem::createEditor(
2074 QWidget* parent,
2075 const std::function<void()>& /*method*/,
2076 FrameOption frameOption
2077 ) const
2078 {
2079 auto le = new QLineEdit(parent);
2080 le->setFrame(static_cast<bool>(frameOption));
2081 le->setReadOnly(true);
2082 return le;
2083 }
2084
2085 void PropertyMatrixItem::setEditorData(QWidget* editor, const QVariant& data) const
2086 {
2087 auto le = qobject_cast<QLineEdit*>(editor);
2088 le->setText(toString(data));
2089 }
2090
2091 QVariant PropertyMatrixItem::editorData(QWidget* editor) const
2092 {
2093 auto le = qobject_cast<QLineEdit*>(editor);
2094 return {le->text()};
2095 }
2096
2097 // clang-format off
2098 double PropertyMatrixItem::getA11() const
2099 {
2100 return data(1, Qt::EditRole).value<Base::Matrix4D>()[0][0];
2101 }
2102
2103 void PropertyMatrixItem::setA11(double A11)
2104 {
2105 setData(QVariant::fromValue(Base::Matrix4D(A11, getA12(), getA13(),getA14(),
2106 getA21(), getA22(), getA23(), getA24(),
2107 getA31(), getA32(), getA33(), getA34(),
2108 getA41(), getA42(), getA43(), getA44())));
2109 }
2110
2111 double PropertyMatrixItem::getA12() const
2112 {
2113 return data(1, Qt::EditRole).value<Base::Matrix4D>()[0][1];
2114 }
2115
2116 void PropertyMatrixItem::setA12(double A12)
2117 {
2118 setData(QVariant::fromValue(Base::Matrix4D(getA11(), A12, getA13(), getA14(),
2119 getA21(), getA22(), getA23(), getA24(),
2120 getA31(), getA32(), getA33(), getA34(),
2121 getA41(), getA42(), getA43(), getA44())));
2122 }
2123
2124 double PropertyMatrixItem::getA13() const
2125 {
2126 return data(1, Qt::EditRole).value<Base::Matrix4D>()[0][2];
2127 }
2128
2129 void PropertyMatrixItem::setA13(double A13)
2130 {
2131 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), A13, getA14(),
2132 getA21(), getA22(), getA23(), getA24(),
2133 getA31(), getA32(), getA33(), getA34(),
2134 getA41(), getA42(), getA43(), getA44())));
2135 }
2136
2137 double PropertyMatrixItem::getA14() const
2138 {
2139 return data(1, Qt::EditRole).value<Base::Matrix4D>()[0][3];
2140 }
2141
2142 void PropertyMatrixItem::setA14(double A14)
2143 {
2144 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), A14,
2145 getA21(), getA22(), getA23(), getA24(),
2146 getA31(), getA32(), getA33(), getA34(),
2147 getA41(), getA42(), getA43(), getA44())));
2148 }
2149
2150 double PropertyMatrixItem::getA21() const
2151 {
2152 return data(1, Qt::EditRole).value<Base::Matrix4D>()[1][0];
2153 }
2154
2155 void PropertyMatrixItem::setA21(double A21)
2156 {
2157 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2158 A21, getA22(), getA23(), getA24(),
2159 getA31(), getA32(), getA33(), getA34(),
2160 getA41(), getA42(), getA43(), getA44())));
2161 }
2162
2163 double PropertyMatrixItem::getA22() const
2164 {
2165 return data(1, Qt::EditRole).value<Base::Matrix4D>()[1][1];
2166 }
2167
2168 void PropertyMatrixItem::setA22(double A22)
2169 {
2170 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2171 getA21(), A22, getA23(), getA24(),
2172 getA31(), getA32(), getA33(), getA34(),
2173 getA41(), getA42(), getA43(), getA44())));
2174 }
2175
2176 double PropertyMatrixItem::getA23() const
2177 {
2178 return data(1, Qt::EditRole).value<Base::Matrix4D>()[1][2];
2179 }
2180
2181 void PropertyMatrixItem::setA23(double A23)
2182 {
2183 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2184 getA21(), getA22(), A23, getA24(),
2185 getA31(), getA32(), getA33(), getA34(),
2186 getA41(), getA42(), getA43(), getA44())));
2187 }
2188
2189 double PropertyMatrixItem::getA24() const
2190 {
2191 return data(1, Qt::EditRole).value<Base::Matrix4D>()[1][3];
2192 }
2193
2194 void PropertyMatrixItem::setA24(double A24)
2195 {
2196 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2197 getA21(), getA22(), getA23(), A24,
2198 getA31(), getA32(), getA33(), getA34(),
2199 getA41(), getA42(), getA43(), getA44())));
2200 }
2201
2202 double PropertyMatrixItem::getA31() const
2203 {
2204 return data(1, Qt::EditRole).value<Base::Matrix4D>()[2][0];
2205 }
2206
2207 void PropertyMatrixItem::setA31(double A31)
2208 {
2209 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2210 getA21(), getA22(), getA23(), getA24(),
2211 A31, getA32(), getA33(), getA34(),
2212 getA41(), getA42(), getA43(), getA44())));
2213 }
2214
2215 double PropertyMatrixItem::getA32() const
2216 {
2217 return data(1, Qt::EditRole).value<Base::Matrix4D>()[2][1];
2218 }
2219
2220 void PropertyMatrixItem::setA32(double A32)
2221 {
2222 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2223 getA21(), getA22(), getA23(), getA24(),
2224 getA31(), A32, getA33(), getA34(),
2225 getA41(), getA42(), getA43(), getA44())));
2226 }
2227
2228 double PropertyMatrixItem::getA33() const
2229 {
2230 return data(1, Qt::EditRole).value<Base::Matrix4D>()[2][2];
2231 }
2232
2233 void PropertyMatrixItem::setA33(double A33)
2234 {
2235 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2236 getA21(), getA22(), getA23(), getA24(),
2237 getA31(), getA32(), A33, getA34(),
2238 getA41(), getA42(), getA43(), getA44())));
2239 }
2240
2241 double PropertyMatrixItem::getA34() const
2242 {
2243 return data(1, Qt::EditRole).value<Base::Matrix4D>()[2][3];
2244 }
2245
2246 void PropertyMatrixItem::setA34(double A34)
2247 {
2248 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2249 getA21(), getA22(), getA23(), getA24(),
2250 getA31(), getA32(), getA33(), A34,
2251 getA41(), getA42(), getA43(), getA44())));
2252 }
2253
2254 double PropertyMatrixItem::getA41() const
2255 {
2256 return data(1, Qt::EditRole).value<Base::Matrix4D>()[3][0];
2257 }
2258
2259 void PropertyMatrixItem::setA41(double A41)
2260 {
2261 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2262 getA21(), getA22(), getA23(), getA24(),
2263 getA31(), getA32(), getA33(), getA34(),
2264 A41, getA42(), getA43(), getA44())));
2265 }
2266
2267 double PropertyMatrixItem::getA42() const
2268 {
2269 return data(1, Qt::EditRole).value<Base::Matrix4D>()[3][1];
2270 }
2271
2272 void PropertyMatrixItem::setA42(double A42)
2273 {
2274 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2275 getA21(), getA22(), getA23(), getA24(),
2276 getA31(), getA32(), getA33(), getA34(),
2277 getA41(), A42, getA43(), getA44())));
2278 }
2279
2280 double PropertyMatrixItem::getA43() const
2281 {
2282 return data(1, Qt::EditRole).value<Base::Matrix4D>()[3][2];
2283 }
2284
2285 void PropertyMatrixItem::setA43(double A43)
2286 {
2287 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2288 getA21(), getA22(), getA23(), getA24(),
2289 getA31(), getA32(), getA33(), getA34(),
2290 getA41(), getA42(), A43, getA44())));
2291 }
2292
2293 double PropertyMatrixItem::getA44() const
2294 {
2295 return data(1, Qt::EditRole).value<Base::Matrix4D>()[3][3];
2296 }
2297
2298 void PropertyMatrixItem::setA44(double A44)
2299 {
2300 setData(QVariant::fromValue(Base::Matrix4D(getA11(), getA12(), getA13(), getA14(),
2301 getA21(), getA22(), getA23(), getA24(),
2302 getA31(), getA32(), getA33(), getA34(),
2303 getA41(), getA42(), getA43(), A44)));
2304 }
2305 // clang-format on
2306
2307 // ---------------------------------------------------------------
2308
2309 RotationHelper::RotationHelper()
2310 : init_axis(false)
2311 , changed_value(false)
2312 , rot_angle(0)
2313 , rot_axis(0, 0, 1)
2314 {}
2315
2316 void RotationHelper::setChanged(bool value)
2317 {
2318 changed_value = value;
2319 }
2320
2321 bool RotationHelper::hasChangedAndReset()
2322 {
2323 if (!changed_value) {
2324 return false;
2325 }
2326
2327 changed_value = false;
2328 return true;
2329 }
2330
2331 bool RotationHelper::isAxisInitialized() const
2332 {
2333 return init_axis;
2334 }
2335
2336 void RotationHelper::setValue(const Base::Vector3d& axis, double angle)
2337 {
2338 rot_axis = axis;
2339 rot_angle = angle;
2340 init_axis = true;
2341 }
2342
2343 void RotationHelper::getValue(Base::Vector3d& axis, double& angle) const
2344 {
2345 axis = rot_axis;
2346 angle = rot_angle;
2347 }
2348
2349 double RotationHelper::getAngle(const Base::Rotation& val) const
2350 {
2351 double angle {};
2352 Base::Vector3d dir;
2353 val.getRawValue(dir, angle);
2354 if (dir * this->rot_axis < 0.0) {
2355 angle = -angle;
2356 }
2357 return angle;
2358 }
2359
2360 Base::Rotation RotationHelper::setAngle(double angle)
2361 {
2362 Base::Rotation rot;
2363 rot.setValue(this->rot_axis, Base::toRadians<double>(angle));
2364 changed_value = true;
2365 rot_angle = angle;
2366 return rot;
2367 }
2368
2369 Base::Vector3d RotationHelper::getAxis() const
2370 {
2371 // We must store the rotation axis in a member because
2372 // if we read the value from the property we would always
2373 // get a normalized vector which makes it quite unhandy
2374 // to work with
2375 return this->rot_axis;
2376 }
2377
2378 Base::Rotation RotationHelper::setAxis(const Base::Rotation& value, const Base::Vector3d& axis)
2379 {
2380 this->rot_axis = axis;
2381 Base::Rotation rot = value;
2382 Base::Vector3d dummy;
2383 double angle {};
2384 rot.getValue(dummy, angle);
2385 if (dummy * axis < 0.0) {
2386 angle = -angle;
2387 }
2388 rot.setValue(axis, angle);
2389 changed_value = true;
2390 return rot;
2391 }
2392
2393 void RotationHelper::assignProperty(const Base::Rotation& value, double eps)
2394 {
2395 double angle {};
2396 Base::Vector3d dir;
2397 value.getRawValue(dir, angle);
2398 Base::Vector3d cross = this->rot_axis.Cross(dir);
2399 double len2 = cross.Sqr();
2400 if (angle != 0) {
2401 // vectors are not parallel
2402 if (len2 > eps) {
2403 this->rot_axis = dir;
2404 }
2405 // vectors point into opposite directions
2406 else if (this->rot_axis.Dot(dir) < 0) {
2407 this->rot_axis = -this->rot_axis;
2408 }
2409 }
2410 this->rot_angle = Base::toDegrees(angle);
2411 }
2412
2413 // ---------------------------------------------------------------
2414
2415 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyRotationItem)
2416
2417 PropertyRotationItem::PropertyRotationItem()
2418 {
2419 m_a = static_cast<PropertyUnitItem*>(PropertyUnitItem::create());
2420 m_a->setParent(this);
2421 m_a->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Angle")));
2422 this->appendChild(m_a);
2423 m_d = static_cast<PropertyVectorItem*>(PropertyVectorItem::create());
2424 m_d->setParent(this);
2425 m_d->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Axis")));
2426 m_d->setReadOnly(true);
2427 this->appendChild(m_d);
2428 }
2429
2430 PropertyRotationItem::~PropertyRotationItem() = default;
2431
2432 Base::Quantity PropertyRotationItem::getAngle() const
2433 {
2434 QVariant value = data(1, Qt::EditRole);
2435 if (!value.canConvert<Base::Rotation>()) {
2436 return Base::Quantity(0.0);
2437 }
2438
2439 const Base::Rotation& val = value.value<Base::Rotation>();
2440 double angle = h.getAngle(val);
2441 return Base::Quantity(Base::toDegrees<double>(angle), Base::Unit::Angle);
2442 }
2443
2444 void PropertyRotationItem::setAngle(Base::Quantity angle)
2445 {
2446 QVariant value = data(1, Qt::EditRole);
2447 if (!value.canConvert<Base::Rotation>()) {
2448 return;
2449 }
2450
2451 Base::Rotation rot = h.setAngle(angle.getValue());
2452 setValue(QVariant::fromValue(rot));
2453 }
2454
2455 Base::Vector3d PropertyRotationItem::getAxis() const
2456 {
2457 return h.getAxis();
2458 }
2459
2460 void PropertyRotationItem::setAxis(const Base::Vector3d& axis)
2461 {
2462 QVariant value = data(1, Qt::EditRole);
2463 if (!value.canConvert<Base::Rotation>()) {
2464 return;
2465 }
2466
2467 auto rot = value.value<Base::Rotation>();
2468 rot = h.setAxis(rot, axis);
2469 setValue(QVariant::fromValue(rot));
2470 }
2471
2472 void PropertyRotationItem::assignProperty(const App::Property* prop)
2473 {
2474 // Choose an adaptive epsilon to avoid changing the axis when they are considered to
2475 // be equal. See https://forum.freecad.org/viewtopic.php?f=10&t=24662&start=10
2476 double eps = std::pow(10.0, -2 * (decimals() + 1)); // NOLINT
2477 if (prop->isDerivedFrom<App::PropertyRotation>()) {
2478 const Base::Rotation& value = static_cast<const App::PropertyRotation*>(prop)->getValue();
2479 h.assignProperty(value, eps);
2480 }
2481 }
2482
2483 QVariant PropertyRotationItem::value(const App::Property* prop) const
2484 {
2485 assert(prop && prop->isDerivedFrom<App::PropertyRotation>());
2486
2487 const Base::Rotation& value = static_cast<const App::PropertyRotation*>(prop)->getValue();
2488 double angle {};
2489 Base::Vector3d dir;
2490 value.getRawValue(dir, angle);
2491 if (!h.isAxisInitialized()) {
2492 if (m_a->hasExpression()) {
2493 QString str = m_a->expressionAsString();
2494 angle = str.toDouble();
2495 }
2496 else {
2497 angle = Base::toDegrees(angle);
2498 }
2499
2500 PropertyItem* x = m_d->child(0);
2501 PropertyItem* y = m_d->child(1);
2502 PropertyItem* z = m_d->child(2);
2503 if (x->hasExpression()) {
2504 QString str = x->expressionAsString();
2505 dir.x = str.toDouble();
2506 }
2507 if (y->hasExpression()) {
2508 QString str = y->expressionAsString();
2509 dir.y = str.toDouble();
2510 }
2511 if (z->hasExpression()) {
2512 QString str = z->expressionAsString();
2513 dir.z = str.toDouble();
2514 }
2515 h.setValue(dir, angle);
2516 }
2517 return QVariant::fromValue<Base::Rotation>(value);
2518 }
2519
2520 QVariant PropertyRotationItem::toolTip(const App::Property* prop) const
2521 {
2522 assert(prop && prop->isDerivedFrom<App::PropertyRotation>());
2523
2524 const Base::Rotation& p = static_cast<const App::PropertyRotation*>(prop)->getValue();
2525 double angle {};
2526 Base::Vector3d dir;
2527 p.getRawValue(dir, angle);
2528 angle = Base::toDegrees<double>(angle);
2529
2530 QLocale loc;
2531 QString data
2532 = QStringLiteral(
2533 "Axis: (%1 %2 %3)\n"
2534 "Angle: %4"
2535 )
2536 .arg(
2537 loc.toString(dir.x, 'f', decimals()),
2538 loc.toString(dir.y, 'f', decimals()),
2539 loc.toString(dir.z, 'f', decimals()),
2540 QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString())
2541 );
2542 return {data};
2543 }
2544
2545 QString PropertyRotationItem::toString(const QVariant& prop) const
2546 {
2547 const Base::Rotation& p = prop.value<Base::Rotation>();
2548 double angle {};
2549 Base::Vector3d dir;
2550 p.getRawValue(dir, angle);
2551 angle = Base::toDegrees<double>(angle);
2552
2553 QLocale loc;
2554 QString data
2555 = QStringLiteral("[(%1 %2 %3); %4]")
2556 .arg(
2557 loc.toString(dir.x, 'f', lowPrec),
2558 loc.toString(dir.y, 'f', lowPrec),
2559 loc.toString(dir.z, 'f', lowPrec),
2560 QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString())
2561 );
2562 return data;
2563 }
2564
2565 void PropertyRotationItem::setValue(const QVariant& value)
2566 {
2567 if (!value.canConvert<Base::Rotation>()) {
2568 return;
2569 }
2570 // Accept this only if the user changed the axis, angle or position but
2571 // not if >this< item loses focus
2572 if (!h.hasChangedAndReset()) {
2573 return;
2574 }
2575
2576 Base::Vector3d axis;
2577 double angle {};
2578 h.getValue(axis, angle);
2579 std::string val = fmt::format(
2580 "App.Rotation(App.Vector({:.{}g},{:.{}g},{:.{}g}),{:.{}g})",
2581 axis.x,
2582 highPrec,
2583 axis.y,
2584 highPrec,
2585 axis.z,
2586 highPrec,
2587 angle,
2588 highPrec
2589 );
2590 setPropertyValue(val);
2591 }
2592
2593 QWidget* PropertyRotationItem::createEditor(
2594 QWidget* parent,
2595 const std::function<void()>& method,
2596 FrameOption frameOption
2597 ) const
2598 {
2599 Q_UNUSED(parent)
2600 Q_UNUSED(method)
2601 Q_UNUSED(frameOption)
2602 return nullptr;
2603 }
2604
2605 void PropertyRotationItem::setEditorData(QWidget* editor, const QVariant& data) const
2606 {
2607 Q_UNUSED(editor)
2608 Q_UNUSED(data)
2609 }
2610
2611 QVariant PropertyRotationItem::editorData(QWidget* editor) const
2612 {
2613 Q_UNUSED(editor)
2614 return {};
2615 }
2616
2617 void PropertyRotationItem::propertyBound()
2618 {
2619 if (isBound()) {
2620 m_a->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Angle"));
2621
2622 m_d->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Axis"));
2623 }
2624 }
2625
2626 // --------------------------------------------------------------------
2627
2628 PlacementEditor::PlacementEditor(QString name, QWidget* parent)
2629 : LabelButton(parent)
2630 , _task(nullptr)
2631 , propertyname {std::move(name)}
2632 {
2633 propertyname.replace(QLatin1String(" "), QLatin1String(""));
2634 }
2635
2636 PlacementEditor::~PlacementEditor() = default;
2637
2638 void PlacementEditor::browse()
2639 {
2640 Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog();
2641 Gui::Dialog::TaskPlacement* task {};
2642 task = qobject_cast<Gui::Dialog::TaskPlacement*>(dlg);
2643 if (dlg && !task) {
2644 // there is already another task dialog which must be closed first
2645 Gui::Control().showDialog(dlg);
2646 return;
2647 }
2648 if (!task) {
2649 task = new Gui::Dialog::TaskPlacement();
2650 }
2651 if (!_task) {
2652 _task = task;
2653 connect(task, &TaskPlacement::placementChanged, this, &PlacementEditor::updateValue);
2654 }
2655 task->setPlacement(value().value<Base::Placement>());
2656 task->setPropertyName(propertyname);
2657 task->setSelection(Gui::Selection().getSelectionEx());
2658 task->bindObject();
2659 Gui::Control().showDialog(task);
2660 }
2661
2662 void PlacementEditor::showValue(const QVariant& d)
2663 {
2664 const Base::Placement& p = d.value<Base::Placement>();
2665 double angle {};
2666 Base::Vector3d dir;
2667 Base::Vector3d pos;
2668 p.getRotation().getRawValue(dir, angle);
2669 angle = Base::toDegrees<double>(angle);
2670 pos = p.getPosition();
2671
2672 QLocale loc;
2673 QString data = QString::fromUtf8("[(%1 %2 %3);%4 \xc2\xb0;(%5 %6 %7)]")
2674 .arg(
2675 loc.toString(dir.x, 'f', lowPrec),
2676 loc.toString(dir.y, 'f', lowPrec),
2677 loc.toString(dir.z, 'f', lowPrec),
2678 loc.toString(angle, 'f', lowPrec),
2679 loc.toString(pos.x, 'f', lowPrec),
2680 loc.toString(pos.y, 'f', lowPrec),
2681 loc.toString(pos.z, 'f', lowPrec)
2682 );
2683 getLabel()->setText(data);
2684 }
2685
2686 void PlacementEditor::updateValue(const QVariant& v, bool incr, bool data)
2687 {
2688 if (data) {
2689 if (incr) {
2690 QVariant u = value();
2691 const Base::Placement& plm = u.value<Base::Placement>();
2692 const Base::Placement& rel = v.value<Base::Placement>();
2693 Base::Placement newp = rel * plm;
2694 setValue(QVariant::fromValue<Base::Placement>(newp));
2695 }
2696 else {
2697 setValue(v);
2698 }
2699 }
2700 }
2701
2702 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyPlacementItem)
2703
2704 PropertyPlacementItem::PropertyPlacementItem()
2705 {
2706 m_a = static_cast<PropertyUnitItem*>(PropertyUnitItem::create());
2707 m_a->setParent(this);
2708 m_a->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Angle")));
2709 this->appendChild(m_a);
2710 m_d = static_cast<PropertyVectorItem*>(PropertyVectorItem::create());
2711 m_d->setParent(this);
2712 m_d->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Axis")));
2713 m_d->setReadOnly(true);
2714 this->appendChild(m_d);
2715 m_p = static_cast<PropertyVectorDistanceItem*>(PropertyVectorDistanceItem::create());
2716 m_p->setParent(this);
2717 m_p->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Position")));
2718 m_p->setReadOnly(true);
2719 this->appendChild(m_p);
2720 }
2721
2722 PropertyPlacementItem::~PropertyPlacementItem() = default;
2723
2724 Base::Quantity PropertyPlacementItem::getAngle() const
2725 {
2726 QVariant value = data(1, Qt::EditRole);
2727 if (!value.canConvert<Base::Placement>()) {
2728 return Base::Quantity(0.0);
2729 }
2730
2731 const Base::Placement& val = value.value<Base::Placement>();
2732 double angle = h.getAngle(val.getRotation());
2733 return Base::Quantity(Base::toDegrees<double>(angle), Base::Unit::Angle);
2734 }
2735
2736 void PropertyPlacementItem::setAngle(Base::Quantity angle)
2737 {
2738 QVariant value = data(1, Qt::EditRole);
2739 if (!value.canConvert<Base::Placement>()) {
2740 return;
2741 }
2742
2743 auto val = value.value<Base::Placement>();
2744 Base::Rotation rot = h.setAngle(angle.getValue());
2745 val.setRotation(rot);
2746 setValue(QVariant::fromValue(val));
2747 }
2748
2749 Base::Vector3d PropertyPlacementItem::getAxis() const
2750 {
2751 return h.getAxis();
2752 }
2753
2754 void PropertyPlacementItem::setAxis(const Base::Vector3d& axis)
2755 {
2756 QVariant value = data(1, Qt::EditRole);
2757 if (!value.canConvert<Base::Placement>()) {
2758 return;
2759 }
2760
2761 auto val = value.value<Base::Placement>();
2762 Base::Rotation rot = val.getRotation();
2763 rot = h.setAxis(rot, axis);
2764 val.setRotation(rot);
2765 setValue(QVariant::fromValue(val));
2766 }
2767
2768 Base::Vector3d PropertyPlacementItem::getPosition() const
2769 {
2770 QVariant value = data(1, Qt::EditRole);
2771 if (!value.canConvert<Base::Placement>()) {
2772 return Base::Vector3d(0, 0, 0);
2773 }
2774 const Base::Placement& val = value.value<Base::Placement>();
2775 return val.getPosition();
2776 }
2777
2778 void PropertyPlacementItem::setPosition(const Base::Vector3d& pos)
2779 {
2780 QVariant value = data(1, Qt::EditRole);
2781 if (!value.canConvert<Base::Placement>()) {
2782 return;
2783 }
2784
2785 auto val = value.value<Base::Placement>();
2786 val.setPosition(pos);
2787 h.setChanged(true);
2788 setValue(QVariant::fromValue(val));
2789 }
2790
2791 void PropertyPlacementItem::assignProperty(const App::Property* prop)
2792 {
2793 // Choose an adaptive epsilon to avoid changing the axis when they are considered to
2794 // be equal. See https://forum.freecad.org/viewtopic.php?f=10&t=24662&start=10
2795 double eps = std::pow(10.0, -2 * (decimals() + 1)); // NOLINT
2796 if (prop->isDerivedFrom<App::PropertyPlacement>()) {
2797 const Base::Placement& value = static_cast<const App::PropertyPlacement*>(prop)->getValue();
2798 h.assignProperty(value.getRotation(), eps);
2799 }
2800 }
2801
2802 QVariant PropertyPlacementItem::value(const App::Property* prop) const
2803 {
2804 assert(prop && prop->isDerivedFrom<App::PropertyPlacement>());
2805
2806 const Base::Placement& value = static_cast<const App::PropertyPlacement*>(prop)->getValue();
2807 double angle {};
2808 Base::Vector3d dir;
2809 value.getRotation().getRawValue(dir, angle);
2810 if (!h.isAxisInitialized()) {
2811 if (m_a->hasExpression()) {
2812 QString str = m_a->expressionAsString();
2813 angle = str.toDouble();
2814 }
2815 else {
2816 angle = Base::toDegrees(angle);
2817 }
2818
2819 PropertyItem* x = m_d->child(0);
2820 PropertyItem* y = m_d->child(1);
2821 PropertyItem* z = m_d->child(2);
2822 if (x->hasExpression()) {
2823 QString str = x->expressionAsString();
2824 dir.x = str.toDouble();
2825 }
2826 if (y->hasExpression()) {
2827 QString str = y->expressionAsString();
2828 dir.y = str.toDouble();
2829 }
2830 if (z->hasExpression()) {
2831 QString str = z->expressionAsString();
2832 dir.z = str.toDouble();
2833 }
2834 h.setValue(dir, angle);
2835 }
2836 return QVariant::fromValue<Base::Placement>(value);
2837 }
2838
2839 QVariant PropertyPlacementItem::toolTip(const App::Property* prop) const
2840 {
2841 assert(prop && prop->isDerivedFrom<App::PropertyPlacement>());
2842
2843 const Base::Placement& p = static_cast<const App::PropertyPlacement*>(prop)->getValue();
2844 double angle {};
2845 Base::Vector3d dir;
2846 Base::Vector3d pos;
2847 p.getRotation().getRawValue(dir, angle);
2848 angle = Base::toDegrees<double>(angle);
2849 pos = p.getPosition();
2850
2851 QLocale loc;
2852 QString data
2853 = QStringLiteral(
2854 "Axis: (%1 %2 %3)\n"
2855 "Angle: %4\n"
2856 "Position: (%5 %6 %7)"
2857 )
2858 .arg(
2859 loc.toString(dir.x, 'f', decimals()),
2860 loc.toString(dir.y, 'f', decimals()),
2861 loc.toString(dir.z, 'f', decimals()),
2862 QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()),
2863 QString::fromStdString(Base::Quantity(pos.x, Base::Unit::Length).getUserString()),
2864 QString::fromStdString(Base::Quantity(pos.y, Base::Unit::Length).getUserString()),
2865 QString::fromStdString(Base::Quantity(pos.z, Base::Unit::Length).getUserString())
2866 );
2867 return {data};
2868 }
2869
2870 QString PropertyPlacementItem::toString(const QVariant& prop) const
2871 {
2872 const Base::Placement& p = prop.value<Base::Placement>();
2873 double angle {};
2874 Base::Vector3d dir;
2875 Base::Vector3d pos;
2876 p.getRotation().getRawValue(dir, angle);
2877 angle = Base::toDegrees<double>(angle);
2878 pos = p.getPosition();
2879
2880 QLocale loc;
2881 QString data
2882 = QStringLiteral("[(%1 %2 %3); %4; (%5 %6 %7)]")
2883 .arg(
2884 loc.toString(dir.x, 'f', lowPrec),
2885 loc.toString(dir.y, 'f', lowPrec),
2886 loc.toString(dir.z, 'f', lowPrec),
2887 QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()),
2888 QString::fromStdString(Base::Quantity(pos.x, Base::Unit::Length).getUserString()),
2889 QString::fromStdString(Base::Quantity(pos.y, Base::Unit::Length).getUserString()),
2890 QString::fromStdString(Base::Quantity(pos.z, Base::Unit::Length).getUserString())
2891 );
2892 return data;
2893 }
2894
2895 void PropertyPlacementItem::setValue(const QVariant& value)
2896 {
2897 if (hasExpression() || !value.canConvert<Base::Placement>()) {
2898 return;
2899 }
2900 // Accept this only if the user changed the axis, angle or position but
2901 // not if >this< item loses focus
2902 if (!h.hasChangedAndReset()) {
2903 return;
2904 }
2905
2906 const Base::Placement& val = value.value<Base::Placement>();
2907 Base::Vector3d pos = val.getPosition();
2908
2909 Base::Vector3d axis;
2910 double angle {};
2911 h.getValue(axis, angle);
2912 std::string str = fmt::format(
2913 "App.Placement("
2914 "App.Vector({:.{}g},{:.{}g},{:.{}g}),"
2915 "App.Rotation(App.Vector({:.{}g},{:.{}g},{:.{}g}),{:.{}g}))",
2916 pos.x,
2917 highPrec,
2918 pos.y,
2919 highPrec,
2920 pos.z,
2921 highPrec,
2922 axis.x,
2923 highPrec,
2924 axis.y,
2925 highPrec,
2926 axis.z,
2927 highPrec,
2928 angle,
2929 highPrec
2930 );
2931 setPropertyValue(str);
2932 }
2933
2934 QWidget* PropertyPlacementItem::
2935 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
2936 {
2937 auto pe = new PlacementEditor(this->propertyName(), parent);
2938 QObject::connect(pe, &PlacementEditor::valueChanged, method);
2939
2940 // The Placement dialog only works if property is part of a DocumentObject
2941 bool readonly = isReadOnly();
2942 if (auto prop = getFirstProperty()) {
2943 readonly |= (!prop->getContainer()->isDerivedFrom<App::DocumentObject>());
2944 }
2945 pe->setDisabled(readonly);
2946 return pe;
2947 }
2948
2949 void PropertyPlacementItem::setEditorData(QWidget* editor, const QVariant& data) const
2950 {
2951 auto pe = qobject_cast<PlacementEditor*>(editor);
2952 pe->setValue(data);
2953 }
2954
2955 QVariant PropertyPlacementItem::editorData(QWidget* editor) const
2956 {
2957 auto pe = qobject_cast<PlacementEditor*>(editor);
2958 return pe->value();
2959 }
2960
2961 void PropertyPlacementItem::propertyBound()
2962 {
2963 if (isBound()) {
2964 m_a->bind(
2965 App::ObjectIdentifier(getPath())
2966 << App::ObjectIdentifier::String("Rotation") << App::ObjectIdentifier::String("Angle")
2967 );
2968
2969 m_d->bind(
2970 App::ObjectIdentifier(getPath())
2971 << App::ObjectIdentifier::String("Rotation") << App::ObjectIdentifier::String("Axis")
2972 );
2973
2974 m_p->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Base"));
2975 }
2976 }
2977
2978
2979 // ---------------------------------------------------------------
2980
2981 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyEnumItem)
2982
2983 PropertyEnumItem::PropertyEnumItem()
2984 : m_enum(nullptr)
2985 {
2986 if (PropertyView::showAll()) {
2987 m_enum = static_cast<PropertyStringListItem*>(PropertyStringListItem::create());
2988 m_enum->setParent(this);
2989 m_enum->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Enum")));
2990 this->appendChild(m_enum);
2991 }
2992 }
2993
2994 void PropertyEnumItem::propertyBound()
2995 {
2996 if (m_enum && isBound()) {
2997 m_enum->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Enum"));
2998 }
2999 }
3000
3001 void PropertyEnumItem::setEnum(const QStringList& values)
3002 {
3003 setData(values);
3004 }
3005
3006 QStringList PropertyEnumItem::getEnum() const
3007 {
3008 QStringList res;
3009 auto prop = getFirstProperty();
3010 if (prop && prop->isDerivedFrom<App::PropertyEnumeration>()) {
3011 const auto prop_enum = static_cast<const App::PropertyEnumeration*>(prop);
3012 std::vector<std::string> enums = prop_enum->getEnumVector();
3013 for (const auto& it : enums) {
3014 res.push_back(QString::fromStdString(it));
3015 }
3016 }
3017 return res;
3018 }
3019
3020 QVariant PropertyEnumItem::value(const App::Property* prop) const
3021 {
3022 assert(prop && prop->isDerivedFrom<App::PropertyEnumeration>());
3023
3024 const auto prop_enum = static_cast<const App::PropertyEnumeration*>(prop);
3025 if (!prop_enum->isValid()) {
3026 return {QString()};
3027 }
3028 return {QString::fromUtf8(prop_enum->getValueAsString())};
3029 }
3030
3031 void PropertyEnumItem::setValue(const QVariant& value)
3032 {
3033 if (hasExpression()) {
3034 return;
3035 }
3036
3037 std::ostringstream ss;
3038
3039 if (value.userType() == QMetaType::QStringList) {
3040 QStringList values = value.toStringList();
3041 ss << "[";
3042 for (const auto& it : values) {
3043 QString text(it);
3044 text.replace(QStringLiteral("'"), QStringLiteral("\\'"));
3045
3046 std::string str = Base::Tools::escapedUnicodeFromUtf8(text.toUtf8());
3047 str = Base::InterpreterSingleton::strToPython(str);
3048 ss << "u\"" << str << "\", ";
3049 }
3050 ss << "]";
3051 setPropertyValue(ss.str());
3052 }
3053 else if (value.canConvert<QString>()) {
3054 std::string str = Base::Tools::escapedUnicodeFromUtf8(value.toString().toUtf8());
3055 ss << "u\"" << str << "\"";
3056 setPropertyValue(ss.str());
3057 }
3058 }
3059
3060 namespace
3061 {
3062
3063 class EnumItems;
3064
3065 struct EnumItem
3066 {
3067 QString text;
3068 QString fullText;
3069 std::shared_ptr<EnumItems> children;
3070 explicit EnumItem(QString t = QString(), QString f = QString())
3071 : text(std::move(t))
3072 , fullText(std::move(f))
3073 {}
3074 void populate(QMenu* menu);
3075 };
3076
3077 class EnumItems: public std::vector<EnumItem>
3078 {
3079 };
3080
3081 void EnumItem::populate(QMenu* menu)
3082 {
3083 if (!children || children->empty()) {
3084 auto action = menu->addAction(text);
3085 action->setData(fullText);
3086 return;
3087 }
3088 auto subMenu = menu->addMenu(text);
3089 for (auto& item : *children) {
3090 item.populate(subMenu);
3091 }
3092 }
3093
3094 std::shared_ptr<EnumItems> getEnumItems(const QStringList& commonModes) // NOLINT
3095 {
3096 int index = -1;
3097 std::shared_ptr<EnumItems> enumItems;
3098 for (auto& mode : commonModes) {
3099 ++index;
3100 auto fields = mode.split(QStringLiteral("|"));
3101 if (!enumItems && fields.size() <= 1) {
3102 continue;
3103 }
3104 if (!enumItems) {
3105 enumItems = std::make_shared<EnumItems>();
3106 for (int i = 0; i < index; ++i) {
3107 enumItems->emplace_back(commonModes[i], mode);
3108 }
3109 }
3110 auto children = enumItems;
3111 int j = -1;
3112 for (auto& field : fields) {
3113 ++j;
3114 field = field.trimmed();
3115 auto it = children->end();
3116 if (field.isEmpty()) {
3117 if (!children->empty()) {
3118 --it;
3119 }
3120 else {
3121 continue;
3122 }
3123 }
3124 else {
3125 it = std::find_if(children->begin(), children->end(), [&field](const EnumItem& item) {
3126 return item.text == field;
3127 });
3128 if (it == children->end()) {
3129 it = children->emplace(children->end(), field, mode);
3130 }
3131 }
3132 if (j + 1 == (int)fields.size()) {
3133 break;
3134 }
3135 if (!it->children) {
3136 it->children = std::make_shared<EnumItems>();
3137 }
3138 children = it->children;
3139 }
3140 }
3141
3142 return enumItems;
3143 }
3144
3145 } // anonymous namespace
3146
3147 QStringList PropertyEnumItem::getCommonModes() const
3148 {
3149 const std::vector<App::Property*>& items = getPropertyData();
3150
3151 QStringList commonModes;
3152 QStringList modes;
3153 for (auto it = items.begin(); it != items.end(); ++it) {
3154 if ((*it)->is<App::PropertyEnumeration>()) {
3155 auto prop = static_cast<App::PropertyEnumeration*>(*it);
3156 if (!prop->hasEnums()) {
3157 commonModes.clear();
3158 return {};
3159 }
3160 const std::vector<std::string>& value = prop->getEnumVector();
3161 if (it == items.begin()) {
3162 for (const auto& jt : value) {
3163 commonModes << QString::fromUtf8(jt.c_str());
3164 }
3165 }
3166 else {
3167 for (const auto& jt : value) {
3168 if (commonModes.contains(QString::fromUtf8(jt.c_str()))) {
3169 modes << QString::fromUtf8(jt.c_str());
3170 }
3171 }
3172
3173 commonModes = modes;
3174 modes.clear();
3175 }
3176 }
3177 }
3178
3179 return commonModes;
3180 }
3181
3182 QWidget* PropertyEnumItem::createEditor(
3183 QWidget* parent,
3184 const std::function<void()>& method,
3185 FrameOption frameOption
3186 ) const
3187 {
3188 QStringList commonModes = getCommonModes();
3189 if (commonModes.isEmpty()) {
3190 return nullptr;
3191 }
3192
3193 std::shared_ptr<EnumItems> enumItems = getEnumItems(commonModes);
3194
3195 if (!enumItems) {
3196 auto cb = new QComboBox(parent);
3197 cb->setFrame(static_cast<bool>(frameOption));
3198 cb->addItems(commonModes);
3199 QObject::connect(cb, qOverload<int>(&QComboBox::activated), method);
3200 return cb;
3201 }
3202
3203 auto button = new PropertyEnumButton(parent);
3204 button->setDisabled(isReadOnly());
3205 auto menu = new QMenu(button);
3206 for (auto& item : *enumItems) {
3207 item.populate(menu);
3208 }
3209 button->setMenu(menu);
3210 QObject::connect(menu, &QMenu::aboutToShow, this, [=]() {
3211 menu->setMinimumWidth(button->width());
3212 });
3213 QObject::connect(menu, &QMenu::triggered, this, [=](QAction* action) {
3214 button->setText(action->data().toString());
3215 Q_EMIT button->picked();
3216 });
3217 QObject::connect(button, &PropertyEnumButton::picked, method);
3218 return button;
3219 }
3220
3221 void PropertyEnumItem::setEditorData(QWidget* editor, const QVariant& data) const
3222 {
3223 if (auto cb = qobject_cast<QComboBox*>(editor)) {
3224 cb->setEditable(false);
3225 cb->setCurrentIndex(cb->findText(data.toString()));
3226 }
3227 else if (auto btn = qobject_cast<QPushButton*>(editor)) {
3228 btn->setText(data.toString());
3229 }
3230 }
3231
3232 QVariant PropertyEnumItem::editorData(QWidget* editor) const
3233 {
3234 if (auto cb = qobject_cast<QComboBox*>(editor)) {
3235 return {cb->currentText()};
3236 }
3237 if (auto btn = qobject_cast<QPushButton*>(editor)) {
3238 return btn->text();
3239 }
3240 return {};
3241 }
3242
3243 // ---------------------------------------------------------------
3244
3245 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyStringListItem)
3246
3247 PropertyStringListItem::PropertyStringListItem() = default;
3248
3249 QWidget* PropertyStringListItem::
3250 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
3251 {
3252 auto le = new Gui::LabelEditor(parent);
3253 le->setAutoFillBackground(true);
3254 QObject::connect(le, &Gui::LabelEditor::textChanged, method);
3255 return le;
3256 }
3257
3258 void PropertyStringListItem::setEditorData(QWidget* editor, const QVariant& data) const
3259 {
3260 auto le = qobject_cast<Gui::LabelEditor*>(editor);
3261 QStringList list = data.toStringList();
3262 le->setText(list.join(QChar::fromLatin1('\n')));
3263 }
3264
3265 QVariant PropertyStringListItem::editorData(QWidget* editor) const
3266 {
3267 auto le = qobject_cast<Gui::LabelEditor*>(editor);
3268 QString complete = le->text();
3269 QStringList list = complete.split(QChar::fromLatin1('\n'));
3270 return {list};
3271 }
3272
3273 QString PropertyStringListItem::toString(const QVariant& prop) const
3274 {
3275 QStringList list = prop.toStringList();
3276 const int size = 10;
3277 if (list.size() > size) {
3278 list = list.mid(0, size);
3279 list.append(QStringLiteral("..."));
3280 }
3281
3282 return QStringLiteral("[%1]").arg(list.join(QLatin1Char(',')));
3283 }
3284
3285 QVariant PropertyStringListItem::value(const App::Property* prop) const
3286 {
3287 assert(prop && prop->isDerivedFrom<App::PropertyStringList>());
3288 QStringList list;
3289 const std::vector<std::string>& value
3290 = (static_cast<const App::PropertyStringList*>(prop))->getValues();
3291 for (const auto& jt : value) {
3292 list << QString::fromUtf8(jt.c_str());
3293 }
3294
3295 return {list};
3296 }
3297
3298 void PropertyStringListItem::setValue(const QVariant& value)
3299 {
3300 if (hasExpression() || !value.canConvert<QStringList>()) {
3301 return;
3302 }
3303
3304 QStringList values = value.toStringList();
3305 std::ostringstream ss;
3306 ss << "[";
3307 for (const auto& it : values) {
3308 QString text(it);
3309 std::string pystr = Base::InterpreterSingleton::strToPython(text.toUtf8().constData());
3310 ss << "\"" << pystr << "\", ";
3311 }
3312 ss << "]";
3313 setPropertyValue(ss.str());
3314 }
3315
3316 // ---------------------------------------------------------------
3317
3318 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyFloatListItem)
3319
3320 PropertyFloatListItem::PropertyFloatListItem() = default;
3321
3322 QWidget* PropertyFloatListItem::
3323 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
3324 {
3325 auto le = new Gui::LabelEditor(parent);
3326 le->setAutoFillBackground(true);
3327 le->setInputType(Gui::LabelEditor::Float);
3328 QObject::connect(le, &Gui::LabelEditor::textChanged, method);
3329 return le;
3330 }
3331
3332 void PropertyFloatListItem::setEditorData(QWidget* editor, const QVariant& data) const
3333 {
3334 auto le = qobject_cast<Gui::LabelEditor*>(editor);
3335 QStringList list = data.toStringList();
3336 le->setText(list.join(QChar::fromLatin1('\n')));
3337 }
3338
3339 QVariant PropertyFloatListItem::editorData(QWidget* editor) const
3340 {
3341 auto le = qobject_cast<Gui::LabelEditor*>(editor);
3342 QString complete = le->text();
3343 QStringList list = complete.split(QChar::fromLatin1('\n'));
3344 return {list};
3345 }
3346
3347 QString PropertyFloatListItem::toString(const QVariant& prop) const
3348 {
3349 QStringList list = prop.toStringList();
3350 const int size = 10;
3351 if (list.size() > size) {
3352 list = list.mid(0, size);
3353 list.append(QStringLiteral("..."));
3354 }
3355 return QStringLiteral("[%1]").arg(list.join(QLatin1Char(',')));
3356 }
3357
3358 QVariant PropertyFloatListItem::value(const App::Property* prop) const
3359 {
3360 assert(prop && prop->isDerivedFrom<App::PropertyFloatList>());
3361
3362 QStringList list;
3363 const std::vector<double>& value = static_cast<const App::PropertyFloatList*>(prop)->getValues();
3364 for (double jt : value) {
3365 list << QString::number(jt, 'f', decimals());
3366 }
3367
3368 return {list};
3369 }
3370
3371 void PropertyFloatListItem::setValue(const QVariant& value)
3372 {
3373 if (hasExpression() || !value.canConvert<QStringList>()) {
3374 return;
3375 }
3376
3377 QStringList values = value.toStringList();
3378 QString data;
3379 QTextStream str(&data);
3380 str << "[";
3381 for (auto it = values.begin(); it != values.end(); ++it) {
3382 if (it != values.begin()) {
3383 str << ",";
3384 }
3385 str << *it;
3386 }
3387 str << "]";
3388 setPropertyValue(data);
3389 }
3390
3391 // ---------------------------------------------------------------
3392
3393 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyIntegerListItem)
3394
3395 PropertyIntegerListItem::PropertyIntegerListItem() = default;
3396
3397 QWidget* PropertyIntegerListItem::
3398 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
3399 {
3400 auto le = new Gui::LabelEditor(parent);
3401 le->setAutoFillBackground(true);
3402 le->setInputType(Gui::LabelEditor::Integer);
3403 QObject::connect(le, &Gui::LabelEditor::textChanged, method);
3404 return le;
3405 }
3406
3407 void PropertyIntegerListItem::setEditorData(QWidget* editor, const QVariant& data) const
3408 {
3409 auto le = qobject_cast<Gui::LabelEditor*>(editor);
3410 QStringList list = data.toStringList();
3411 le->setText(list.join(QChar::fromLatin1('\n')));
3412 }
3413
3414 QVariant PropertyIntegerListItem::editorData(QWidget* editor) const
3415 {
3416 auto le = qobject_cast<Gui::LabelEditor*>(editor);
3417 QString complete = le->text();
3418 QStringList list = complete.split(QChar::fromLatin1('\n'));
3419 return {list};
3420 }
3421
3422 QString PropertyIntegerListItem::toString(const QVariant& prop) const
3423 {
3424 QStringList list = prop.toStringList();
3425 const int size = 10;
3426 if (list.size() > size) {
3427 list = list.mid(0, size);
3428 list.append(QStringLiteral("..."));
3429 }
3430 QString text = QStringLiteral("[%1]").arg(list.join(QLatin1Char(',')));
3431
3432 return {text};
3433 }
3434
3435 QVariant PropertyIntegerListItem::value(const App::Property* prop) const
3436 {
3437 assert(prop && prop->isDerivedFrom<App::PropertyIntegerList>());
3438
3439 QStringList list;
3440 const std::vector<long>& value = static_cast<const App::PropertyIntegerList*>(prop)->getValues();
3441 for (long jt : value) {
3442 list << QString::number(jt);
3443 }
3444
3445 return {list};
3446 }
3447
3448 void PropertyIntegerListItem::setValue(const QVariant& value)
3449 {
3450 if (hasExpression() || !value.canConvert<QStringList>()) {
3451 return;
3452 }
3453
3454 QStringList values = value.toStringList();
3455 QString data;
3456 QTextStream str(&data);
3457 str << "[";
3458 for (auto it = values.begin(); it != values.end(); ++it) {
3459 if (it != values.begin()) {
3460 str << ",";
3461 }
3462 str << *it;
3463 }
3464 str << "]";
3465 setPropertyValue(data);
3466 }
3467
3468 // --------------------------------------------------------------------
3469
3470 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyColorItem)
3471
3472 PropertyColorItem::PropertyColorItem() = default;
3473
3474 QVariant PropertyColorItem::decoration(const QVariant& value) const
3475 {
3476 auto color = value.value<QColor>();
3477
3478 int size = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize);
3479 QPixmap p(size, size);
3480 p.fill(color);
3481
3482 return QVariant(p);
3483 }
3484
3485 QString PropertyColorItem::toString(const QVariant& prop) const
3486 {
3487 auto value = prop.value<QColor>();
3488 return QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue());
3489 }
3490
3491 QVariant PropertyColorItem::value(const App::Property* prop) const
3492 {
3493 assert(prop && prop->isDerivedFrom<App::PropertyColor>());
3494
3495 Base::Color value = static_cast<const App::PropertyColor*>(prop)->getValue();
3496 return QVariant(value.asValue<QColor>());
3497 }
3498
3499 void PropertyColorItem::setValue(const QVariant& value)
3500 {
3501 if (hasExpression() || !value.canConvert<QColor>()) {
3502 return;
3503 }
3504 auto col = value.value<QColor>();
3505 QString data = QStringLiteral("(%1,%2,%3)").arg(col.red()).arg(col.green()).arg(col.blue());
3506 setPropertyValue(data);
3507 }
3508
3509 QWidget* PropertyColorItem::
3510 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
3511 {
3512 auto cb = new Gui::ColorButton(parent);
3513 QObject::connect(cb, &Gui::ColorButton::changed, method);
3514 return cb;
3515 }
3516
3517 void PropertyColorItem::setEditorData(QWidget* editor, const QVariant& data) const
3518 {
3519 auto cb = qobject_cast<Gui::ColorButton*>(editor);
3520 auto color = data.value<QColor>();
3521 cb->setColor(color);
3522 }
3523
3524 QVariant PropertyColorItem::editorData(QWidget* editor) const
3525 {
3526 auto cb = qobject_cast<Gui::ColorButton*>(editor);
3527 QVariant var;
3528 var.setValue(cb->color());
3529 return var;
3530 }
3531
3532 // --------------------------------------------------------------------
3533
3534 namespace Gui::PropertyEditor
3535 {
3536 class Material
3537 {
3538 public:
3539 QColor diffuseColor;
3540 QColor ambientColor;
3541 QColor specularColor;
3542 QColor emissiveColor;
3543 float shininess {};
3544 float transparency {};
3545 };
3546 } // namespace Gui::PropertyEditor
3547
3548 Q_DECLARE_METATYPE(Gui::PropertyEditor::Material) // NOLINT
3549
3550 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyMaterialItem)
3551
3552 PropertyMaterialItem::PropertyMaterialItem()
3553 {
3554 const int min = 0;
3555 const int max = 100;
3556 const int steps = 5;
3557 diffuse = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3558 diffuse->setParent(this);
3559 diffuse->setPropertyName(QLatin1String("DiffuseColor"));
3560 this->appendChild(diffuse);
3561
3562 ambient = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3563 ambient->setParent(this);
3564 ambient->setPropertyName(QLatin1String("AmbientColor"));
3565 this->appendChild(ambient);
3566
3567 specular = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3568 specular->setParent(this);
3569 specular->setPropertyName(QLatin1String("SpecularColor"));
3570 this->appendChild(specular);
3571
3572 emissive = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3573 emissive->setParent(this);
3574 emissive->setPropertyName(QLatin1String("EmissiveColor"));
3575 this->appendChild(emissive);
3576
3577 shininess = static_cast<PropertyIntegerConstraintItem*>(PropertyIntegerConstraintItem::create());
3578 shininess->setRange(min, max);
3579 shininess->setStepSize(steps);
3580 shininess->setParent(this);
3581 shininess->setPropertyName(QLatin1String("Shininess"));
3582 this->appendChild(shininess);
3583
3584 transparency = static_cast<PropertyIntegerConstraintItem*>(PropertyIntegerConstraintItem::create());
3585 transparency->setRange(min, max);
3586 transparency->setStepSize(steps);
3587 transparency->setParent(this);
3588 transparency->setPropertyName(QLatin1String("Transparency"));
3589 this->appendChild(transparency);
3590 }
3591
3592 PropertyMaterialItem::~PropertyMaterialItem() = default;
3593
3594 void PropertyMaterialItem::propertyBound()
3595 {}
3596
3597 QColor PropertyMaterialItem::getDiffuseColor() const
3598 {
3599 QVariant value = data(1, Qt::EditRole);
3600 if (!value.canConvert<Material>()) {
3601 return {};
3602 }
3603
3604 auto val = value.value<Material>();
3605 return val.diffuseColor;
3606 }
3607
3608 void PropertyMaterialItem::setDiffuseColor(const QColor& color)
3609 {
3610 QVariant value = data(1, Qt::EditRole);
3611 if (!value.canConvert<Material>()) {
3612 return;
3613 }
3614
3615 auto mat = value.value<Material>();
3616 mat.diffuseColor = color;
3617 setValue(QVariant::fromValue<Material>(mat));
3618 }
3619
3620 QColor PropertyMaterialItem::getAmbientColor() const
3621 {
3622 QVariant value = data(1, Qt::EditRole);
3623 if (!value.canConvert<Material>()) {
3624 return {};
3625 }
3626
3627 auto val = value.value<Material>();
3628 return val.ambientColor;
3629 }
3630
3631 void PropertyMaterialItem::setAmbientColor(const QColor& color)
3632 {
3633 QVariant value = data(1, Qt::EditRole);
3634 if (!value.canConvert<Material>()) {
3635 return;
3636 }
3637
3638 auto mat = value.value<Material>();
3639 mat.ambientColor = color;
3640 setValue(QVariant::fromValue<Material>(mat));
3641 }
3642
3643 QColor PropertyMaterialItem::getSpecularColor() const
3644 {
3645 QVariant value = data(1, Qt::EditRole);
3646 if (!value.canConvert<Material>()) {
3647 return {};
3648 }
3649
3650 auto val = value.value<Material>();
3651 return val.specularColor;
3652 }
3653
3654 void PropertyMaterialItem::setSpecularColor(const QColor& color)
3655 {
3656 QVariant value = data(1, Qt::EditRole);
3657 if (!value.canConvert<Material>()) {
3658 return;
3659 }
3660
3661 auto mat = value.value<Material>();
3662 mat.specularColor = color;
3663 setValue(QVariant::fromValue<Material>(mat));
3664 }
3665
3666 QColor PropertyMaterialItem::getEmissiveColor() const
3667 {
3668 QVariant value = data(1, Qt::EditRole);
3669 if (!value.canConvert<Material>()) {
3670 return {};
3671 }
3672
3673 auto val = value.value<Material>();
3674 return val.emissiveColor;
3675 }
3676
3677 void PropertyMaterialItem::setEmissiveColor(const QColor& color)
3678 {
3679 QVariant value = data(1, Qt::EditRole);
3680 if (!value.canConvert<Material>()) {
3681 return;
3682 }
3683
3684 auto mat = value.value<Material>();
3685 mat.emissiveColor = color;
3686 setValue(QVariant::fromValue<Material>(mat));
3687 }
3688
3689 int PropertyMaterialItem::getShininess() const
3690 {
3691 QVariant value = data(1, Qt::EditRole);
3692 if (!value.canConvert<Material>()) {
3693 return 0;
3694 }
3695
3696 auto val = value.value<Material>();
3697 return Base::toPercent(val.shininess);
3698 }
3699
3700 void PropertyMaterialItem::setShininess(int s)
3701 {
3702 QVariant value = data(1, Qt::EditRole);
3703 if (!value.canConvert<Material>()) {
3704 return;
3705 }
3706
3707 auto mat = value.value<Material>();
3708 mat.shininess = Base::fromPercent(s);
3709 setValue(QVariant::fromValue<Material>(mat));
3710 }
3711
3712 int PropertyMaterialItem::getTransparency() const
3713 {
3714 QVariant value = data(1, Qt::EditRole);
3715 if (!value.canConvert<Material>()) {
3716 return 0;
3717 }
3718
3719 auto val = value.value<Material>();
3720 return Base::toPercent(val.transparency);
3721 }
3722
3723 void PropertyMaterialItem::setTransparency(int t)
3724 {
3725 QVariant value = data(1, Qt::EditRole);
3726 if (!value.canConvert<Material>()) {
3727 return;
3728 }
3729
3730 auto mat = value.value<Material>();
3731 mat.transparency = Base::fromPercent(t);
3732 setValue(QVariant::fromValue<Material>(mat));
3733 }
3734
3735 QVariant PropertyMaterialItem::decoration(const QVariant& value) const
3736 {
3737 // use the diffuse color
3738 auto val = value.value<Material>();
3739 QColor color = val.diffuseColor;
3740
3741 int size = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize);
3742 QPixmap p(size, size);
3743 p.fill(color);
3744
3745 return QVariant(p);
3746 }
3747
3748 QString PropertyMaterialItem::toString(const QVariant& prop) const
3749 {
3750 // use the diffuse color
3751 auto val = prop.value<Material>();
3752 QColor value = val.diffuseColor;
3753 return QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue());
3754 }
3755
3756 QVariant PropertyMaterialItem::toolTip(const App::Property* prop) const
3757 {
3758 assert(prop && prop->isDerivedFrom<App::PropertyMaterial>());
3759
3760 const App::Material& value = static_cast<const App::PropertyMaterial*>(prop)->getValue();
3761 auto dc = value.diffuseColor.asValue<QColor>();
3762 auto ac = value.ambientColor.asValue<QColor>();
3763 auto sc = value.specularColor.asValue<QColor>();
3764 auto ec = value.emissiveColor.asValue<QColor>();
3765
3766 QString data = QStringLiteral(
3767 "Diffuse color: [%1, %2, %3]\n"
3768 "Ambient color: [%4, %5, %6]\n"
3769 "Specular color: [%7, %8, %9]\n"
3770 "Emissive color: [%10, %11, %12]\n"
3771 "Shininess: %13\n"
3772 "Transparency: %14"
3773 )
3774 .arg(dc.red())
3775 .arg(dc.green())
3776 .arg(dc.blue())
3777 .arg(ac.red())
3778 .arg(ac.green())
3779 .arg(ac.blue())
3780 .arg(sc.red())
3781 .arg(sc.green())
3782 .arg(sc.blue())
3783 .arg(ec.red())
3784 .arg(ec.green())
3785 .arg(ec.blue())
3786 .arg(Base::toPercent(value.shininess))
3787 .arg(Base::toPercent(value.transparency));
3788
3789 return {data};
3790 }
3791
3792 QVariant PropertyMaterialItem::value(const App::Property* prop) const
3793 {
3794 assert(prop && prop->isDerivedFrom<App::PropertyMaterial>());
3795
3796 const App::Material& value = static_cast<const App::PropertyMaterial*>(prop)->getValue();
3797 Material mat;
3798
3799 mat.diffuseColor = value.diffuseColor.asValue<QColor>();
3800 mat.ambientColor = value.ambientColor.asValue<QColor>();
3801 mat.specularColor = value.specularColor.asValue<QColor>();
3802 mat.emissiveColor = value.emissiveColor.asValue<QColor>();
3803 mat.shininess = value.shininess;
3804 mat.transparency = value.transparency;
3805
3806 return QVariant::fromValue<Material>(mat);
3807 }
3808
3809 void PropertyMaterialItem::setValue(const QVariant& value)
3810 {
3811 if (hasExpression() || !value.canConvert<Material>()) {
3812 return;
3813 }
3814
3815 auto mat = value.value<Material>();
3816 Base::Color dc;
3817 dc.setValue<QColor>(mat.diffuseColor);
3818 uint32_t dcp = dc.getPackedValue();
3819 Base::Color ac;
3820 ac.setValue<QColor>(mat.ambientColor);
3821 uint32_t acp = ac.getPackedValue();
3822 Base::Color sc;
3823 sc.setValue<QColor>(mat.specularColor);
3824 uint32_t scp = sc.getPackedValue();
3825 Base::Color ec;
3826 ec.setValue<QColor>(mat.emissiveColor);
3827 uint32_t ecp = ec.getPackedValue();
3828 float s = mat.shininess;
3829 float t = mat.transparency;
3830
3831 QString data = QStringLiteral(
3832 "App.Material("
3833 "DiffuseColor = %1,"
3834 "AmbientColor = %2,"
3835 "SpecularColor = %3,"
3836 "EmissiveColor = %4,"
3837 "Shininess = %5,"
3838 "Transparency = %6,"
3839 ")"
3840 )
3841 .arg(dcp)
3842 .arg(acp)
3843 .arg(scp)
3844 .arg(ecp)
3845 .arg(s, 0, 'f', 10)
3846 .arg(t, 0, 'f', 10);
3847
3848 setPropertyValue(data);
3849 }
3850
3851 QWidget* PropertyMaterialItem::
3852 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
3853 {
3854 auto cb = new Gui::ColorButton(parent);
3855 QObject::connect(cb, &Gui::ColorButton::changed, method);
3856 return cb;
3857 }
3858
3859 void PropertyMaterialItem::setEditorData(QWidget* editor, const QVariant& data) const
3860 {
3861 if (!data.canConvert<Material>()) {
3862 return;
3863 }
3864
3865 auto val = data.value<Material>();
3866 auto cb = qobject_cast<Gui::ColorButton*>(editor);
3867 cb->setColor(val.diffuseColor);
3868 }
3869
3870 QVariant PropertyMaterialItem::editorData(QWidget* editor) const
3871 {
3872 auto cb = qobject_cast<Gui::ColorButton*>(editor);
3873 QVariant value = data(1, Qt::EditRole);
3874 if (!value.canConvert<Material>()) {
3875 return {};
3876 }
3877
3878 auto val = value.value<Material>();
3879 val.diffuseColor = cb->color();
3880 return QVariant::fromValue<Material>(val);
3881 }
3882
3883 // --------------------------------------------------------------------
3884
3885 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyMaterialListItem)
3886
3887 PropertyMaterialListItem::PropertyMaterialListItem()
3888 {
3889 const int min = 0;
3890 const int max = 100;
3891 const int steps = 5;
3892
3893 // This editor gets a list of materials but it only edits the first item.
3894 diffuse = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3895 diffuse->setParent(this);
3896 diffuse->setPropertyName(QLatin1String("DiffuseColor"));
3897 this->appendChild(diffuse);
3898
3899 ambient = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3900 ambient->setParent(this);
3901 ambient->setPropertyName(QLatin1String("AmbientColor"));
3902 this->appendChild(ambient);
3903
3904 specular = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3905 specular->setParent(this);
3906 specular->setPropertyName(QLatin1String("SpecularColor"));
3907 this->appendChild(specular);
3908
3909 emissive = static_cast<PropertyColorItem*>(PropertyColorItem::create());
3910 emissive->setParent(this);
3911 emissive->setPropertyName(QLatin1String("EmissiveColor"));
3912 this->appendChild(emissive);
3913
3914 shininess = static_cast<PropertyIntegerConstraintItem*>(PropertyIntegerConstraintItem::create());
3915 shininess->setRange(min, max);
3916 shininess->setStepSize(steps);
3917 shininess->setParent(this);
3918 shininess->setPropertyName(QLatin1String("Shininess"));
3919 this->appendChild(shininess);
3920
3921 transparency = static_cast<PropertyIntegerConstraintItem*>(PropertyIntegerConstraintItem::create());
3922 transparency->setRange(min, max);
3923 transparency->setStepSize(steps);
3924 transparency->setParent(this);
3925 transparency->setPropertyName(QLatin1String("Transparency"));
3926 this->appendChild(transparency);
3927 }
3928
3929 PropertyMaterialListItem::~PropertyMaterialListItem() = default;
3930
3931 void PropertyMaterialListItem::propertyBound()
3932 {}
3933
3934 QColor PropertyMaterialListItem::getDiffuseColor() const
3935 {
3936 QVariant value = data(1, Qt::EditRole);
3937 if (!value.canConvert<QVariantList>()) {
3938 return {};
3939 }
3940
3941 QVariantList list = value.toList();
3942 if (list.isEmpty()) {
3943 return {};
3944 }
3945
3946 if (!list[0].canConvert<Material>()) {
3947 return {};
3948 }
3949
3950 auto mat = list[0].value<Material>();
3951 return mat.diffuseColor;
3952 }
3953
3954 void PropertyMaterialListItem::setDiffuseColor(const QColor& color)
3955 {
3956 QVariant value = data(1, Qt::EditRole);
3957 if (!value.canConvert<QVariantList>()) {
3958 return;
3959 }
3960
3961 QVariantList list = value.toList();
3962 if (list.isEmpty()) {
3963 return;
3964 }
3965
3966 if (!list[0].canConvert<Material>()) {
3967 return;
3968 }
3969
3970 auto mat = list[0].value<Material>();
3971 mat.diffuseColor = color;
3972 list[0] = QVariant::fromValue<Material>(mat);
3973 setValue(list);
3974 }
3975
3976 QColor PropertyMaterialListItem::getAmbientColor() const
3977 {
3978 QVariant value = data(1, Qt::EditRole);
3979 if (!value.canConvert<QVariantList>()) {
3980 return {};
3981 }
3982
3983 QVariantList list = value.toList();
3984 if (list.isEmpty()) {
3985 return {};
3986 }
3987
3988 if (!list[0].canConvert<Material>()) {
3989 return {};
3990 }
3991
3992 auto mat = list[0].value<Material>();
3993 return mat.ambientColor;
3994 }
3995
3996 void PropertyMaterialListItem::setAmbientColor(const QColor& color)
3997 {
3998 QVariant value = data(1, Qt::EditRole);
3999 if (!value.canConvert<QVariantList>()) {
4000 return;
4001 }
4002
4003 QVariantList list = value.toList();
4004 if (list.isEmpty()) {
4005 return;
4006 }
4007
4008 if (!list[0].canConvert<Material>()) {
4009 return;
4010 }
4011
4012 auto mat = list[0].value<Material>();
4013 mat.ambientColor = color;
4014 list[0] = QVariant::fromValue<Material>(mat);
4015 setValue(list);
4016 }
4017
4018 QColor PropertyMaterialListItem::getSpecularColor() const
4019 {
4020 QVariant value = data(1, Qt::EditRole);
4021 if (!value.canConvert<QVariantList>()) {
4022 return {};
4023 }
4024
4025 QVariantList list = value.toList();
4026 if (list.isEmpty()) {
4027 return {};
4028 }
4029
4030 if (!list[0].canConvert<Material>()) {
4031 return {};
4032 }
4033
4034 auto mat = list[0].value<Material>();
4035 return mat.specularColor;
4036 }
4037
4038 void PropertyMaterialListItem::setSpecularColor(const QColor& color)
4039 {
4040 QVariant value = data(1, Qt::EditRole);
4041 if (!value.canConvert<QVariantList>()) {
4042 return;
4043 }
4044
4045 QVariantList list = value.toList();
4046 if (list.isEmpty()) {
4047 return;
4048 }
4049
4050 if (!list[0].canConvert<Material>()) {
4051 return;
4052 }
4053
4054 auto mat = list[0].value<Material>();
4055 mat.specularColor = color;
4056 list[0] = QVariant::fromValue<Material>(mat);
4057 setValue(list);
4058 }
4059
4060 QColor PropertyMaterialListItem::getEmissiveColor() const
4061 {
4062 QVariant value = data(1, Qt::EditRole);
4063 if (!value.canConvert<QVariantList>()) {
4064 return {};
4065 }
4066
4067 QVariantList list = value.toList();
4068 if (list.isEmpty()) {
4069 return {};
4070 }
4071
4072 if (!list[0].canConvert<Material>()) {
4073 return {};
4074 }
4075
4076 auto mat = list[0].value<Material>();
4077 return mat.emissiveColor;
4078 }
4079
4080 void PropertyMaterialListItem::setEmissiveColor(const QColor& color)
4081 {
4082 QVariant value = data(1, Qt::EditRole);
4083 if (!value.canConvert<QVariantList>()) {
4084 return;
4085 }
4086
4087 QVariantList list = value.toList();
4088 if (list.isEmpty()) {
4089 return;
4090 }
4091
4092 if (!list[0].canConvert<Material>()) {
4093 return;
4094 }
4095
4096 auto mat = list[0].value<Material>();
4097 mat.emissiveColor = color;
4098 list[0] = QVariant::fromValue<Material>(mat);
4099 setValue(list);
4100 }
4101
4102 int PropertyMaterialListItem::getShininess() const
4103 {
4104 QVariant value = data(1, Qt::EditRole);
4105 if (!value.canConvert<QVariantList>()) {
4106 return 0;
4107 }
4108
4109 QVariantList list = value.toList();
4110 if (list.isEmpty()) {
4111 return 0;
4112 }
4113
4114 if (!list[0].canConvert<Material>()) {
4115 return 0;
4116 }
4117
4118 auto mat = list[0].value<Material>();
4119 return Base::toPercent(mat.shininess);
4120 }
4121
4122 void PropertyMaterialListItem::setShininess(int s)
4123 {
4124 QVariant value = data(1, Qt::EditRole);
4125 if (!value.canConvert<QVariantList>()) {
4126 return;
4127 }
4128
4129 QVariantList list = value.toList();
4130 if (list.isEmpty()) {
4131 return;
4132 }
4133
4134 if (!list[0].canConvert<Material>()) {
4135 return;
4136 }
4137
4138 auto mat = list[0].value<Material>();
4139 mat.shininess = Base::fromPercent(s);
4140 list[0] = QVariant::fromValue<Material>(mat);
4141 setValue(list);
4142 }
4143
4144 int PropertyMaterialListItem::getTransparency() const
4145 {
4146 QVariant value = data(1, Qt::EditRole);
4147 if (!value.canConvert<QVariantList>()) {
4148 return 0;
4149 }
4150
4151 QVariantList list = value.toList();
4152 if (list.isEmpty()) {
4153 return 0;
4154 }
4155
4156 if (!list[0].canConvert<Material>()) {
4157 return 0;
4158 }
4159
4160 auto mat = list[0].value<Material>();
4161 return Base::toPercent(mat.transparency);
4162 }
4163
4164 void PropertyMaterialListItem::setTransparency(int t)
4165 {
4166 QVariant value = data(1, Qt::EditRole);
4167 if (!value.canConvert<QVariantList>()) {
4168 return;
4169 }
4170
4171 QVariantList list = value.toList();
4172 if (list.isEmpty()) {
4173 return;
4174 }
4175
4176 if (!list[0].canConvert<Material>()) {
4177 return;
4178 }
4179
4180 auto mat = list[0].value<Material>();
4181 mat.transparency = Base::fromPercent(t);
4182 list[0] = QVariant::fromValue<Material>(mat);
4183 setValue(list);
4184 }
4185
4186 QVariant PropertyMaterialListItem::decoration(const QVariant& value) const
4187 {
4188 if (!value.canConvert<QVariantList>()) {
4189 return {};
4190 }
4191
4192 QVariantList list = value.toList();
4193 if (list.isEmpty()) {
4194 return {};
4195 }
4196
4197 if (!list[0].canConvert<Material>()) {
4198 return {};
4199 }
4200
4201 // use the diffuse color
4202 auto mat = list[0].value<Material>();
4203 QColor color = mat.diffuseColor;
4204
4205 int size = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize);
4206 QPixmap p(size, size);
4207 p.fill(color);
4208
4209 return QVariant(p);
4210 }
4211
4212 QString PropertyMaterialListItem::toString(const QVariant& prop) const
4213 {
4214 if (!prop.canConvert<QVariantList>()) {
4215 return {};
4216 }
4217
4218 QVariantList list = prop.toList();
4219 if (list.isEmpty()) {
4220 return {};
4221 }
4222
4223 if (!list[0].canConvert<Material>()) {
4224 return {};
4225 }
4226
4227 // use the diffuse color
4228 auto mat = list[0].value<Material>();
4229 QColor value = mat.diffuseColor;
4230 return QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue());
4231 }
4232
4233 QVariant PropertyMaterialListItem::toolTip(const App::Property* prop) const
4234 {
4235 assert(prop && prop->isDerivedFrom<App::PropertyMaterialList>());
4236
4237 const std::vector<App::Material>& values
4238 = static_cast<const App::PropertyMaterialList*>(prop)->getValues();
4239 if (values.empty()) {
4240 return {};
4241 }
4242
4243 App::Material value = values.front();
4244 auto dc = value.diffuseColor.asValue<QColor>();
4245 auto ac = value.ambientColor.asValue<QColor>();
4246 auto sc = value.specularColor.asValue<QColor>();
4247 auto ec = value.emissiveColor.asValue<QColor>();
4248
4249 QString data = QStringLiteral(
4250 "Diffuse color: [%1, %2, %3]\n"
4251 "Ambient color: [%4, %5, %6]\n"
4252 "Specular color: [%7, %8, %9]\n"
4253 "Emissive color: [%10, %11, %12]\n"
4254 "Shininess: %13\n"
4255 "Transparency: %14"
4256 )
4257 .arg(dc.red())
4258 .arg(dc.green())
4259 .arg(dc.blue())
4260 .arg(ac.red())
4261 .arg(ac.green())
4262 .arg(ac.blue())
4263 .arg(sc.red())
4264 .arg(sc.green())
4265 .arg(sc.blue())
4266 .arg(ec.red())
4267 .arg(ec.green())
4268 .arg(ec.blue())
4269 .arg(Base::toPercent(value.shininess))
4270 .arg(Base::toPercent(value.transparency));
4271
4272 return {data};
4273 }
4274
4275 QVariant PropertyMaterialListItem::value(const App::Property* prop) const
4276 {
4277 assert(prop && prop->isDerivedFrom<App::PropertyMaterialList>());
4278
4279 const std::vector<App::Material>& value
4280 = static_cast<const App::PropertyMaterialList*>(prop)->getValues();
4281 QVariantList variantList;
4282
4283 for (const auto& it : value) {
4284 Material mat;
4285 mat.diffuseColor = it.diffuseColor.asValue<QColor>();
4286 mat.ambientColor = it.ambientColor.asValue<QColor>();
4287 mat.specularColor = it.specularColor.asValue<QColor>();
4288 mat.emissiveColor = it.emissiveColor.asValue<QColor>();
4289 mat.shininess = it.shininess;
4290 mat.transparency = it.transparency;
4291
4292 variantList << QVariant::fromValue<Material>(mat);
4293 }
4294
4295 return variantList;
4296 }
4297
4298 void PropertyMaterialListItem::setValue(const QVariant& value)
4299 {
4300 if (hasExpression() || !value.canConvert<QVariantList>()) {
4301 return;
4302 }
4303
4304 QVariantList list = value.toList();
4305 if (list.isEmpty()) {
4306 return;
4307 }
4308
4309 // Setting an appearance using the property editor resets the
4310 // per-face appearance
4311 list = list.mid(0, 1);
4312
4313 QString data;
4314 QTextStream str(&data);
4315 str << "(";
4316
4317 auto mat = list[0].value<Material>();
4318 Base::Color dc;
4319 dc.setValue<QColor>(mat.diffuseColor);
4320 uint32_t dcp = dc.getPackedValue();
4321 Base::Color ac;
4322 ac.setValue<QColor>(mat.ambientColor);
4323 uint32_t acp = ac.getPackedValue();
4324 Base::Color sc;
4325 sc.setValue<QColor>(mat.specularColor);
4326 uint32_t scp = sc.getPackedValue();
4327 Base::Color ec;
4328 ec.setValue<QColor>(mat.emissiveColor);
4329 uint32_t ecp = ec.getPackedValue();
4330 float s = mat.shininess;
4331 float t = mat.transparency;
4332
4333 QString item = QStringLiteral(
4334 "App.Material("
4335 "DiffuseColor = %1,"
4336 "AmbientColor = %2,"
4337 "SpecularColor = %3,"
4338 "EmissiveColor = %4,"
4339 "Shininess = %5,"
4340 "Transparency = %6,"
4341 ")"
4342 )
4343 .arg(dcp)
4344 .arg(acp)
4345 .arg(scp)
4346 .arg(ecp)
4347 .arg(s, 0, 'f', 10)
4348 .arg(t, 0, 'f', 10);
4349 str << item << ")";
4350
4351 setPropertyValue(data);
4352 }
4353
4354 QWidget* PropertyMaterialListItem::
4355 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
4356 {
4357 auto cb = new Gui::ColorButton(parent);
4358 QObject::connect(cb, &Gui::ColorButton::changed, method);
4359 return cb;
4360 }
4361
4362 void PropertyMaterialListItem::setEditorData(QWidget* editor, const QVariant& data) const
4363 {
4364 if (!data.canConvert<QVariantList>()) {
4365 return;
4366 }
4367
4368 QVariantList list = data.toList();
4369 if (list.isEmpty()) {
4370 return;
4371 }
4372
4373 if (!list[0].canConvert<Material>()) {
4374 return;
4375 }
4376
4377 // use the diffuse color
4378 auto mat = list[0].value<Material>();
4379 QColor color = mat.diffuseColor;
4380
4381 auto cb = qobject_cast<Gui::ColorButton*>(editor);
4382 cb->setColor(color);
4383 }
4384
4385 QVariant PropertyMaterialListItem::editorData(QWidget* editor) const
4386 {
4387 auto cb = qobject_cast<Gui::ColorButton*>(editor);
4388 QVariant value = data(1, Qt::EditRole);
4389 if (!value.canConvert<QVariantList>()) {
4390 return {};
4391 }
4392
4393 QVariantList list = value.toList();
4394 if (list.isEmpty()) {
4395 return {};
4396 }
4397
4398 if (!list[0].canConvert<Material>()) {
4399 return {};
4400 }
4401
4402 // use the diffuse color
4403 auto mat = list[0].value<Material>();
4404 mat.diffuseColor = cb->color();
4405 list[0] = QVariant::fromValue<Material>(mat);
4406
4407 return list;
4408 }
4409
4410 // --------------------------------------------------------------------
4411
4412 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyFileItem)
4413
4414 PropertyFileItem::PropertyFileItem() = default;
4415
4416 QVariant PropertyFileItem::value(const App::Property* prop) const
4417 {
4418 assert(prop && prop->isDerivedFrom<App::PropertyFile>());
4419
4420 std::string value = static_cast<const App::PropertyFile*>(prop)->getValue();
4421 return {QString::fromUtf8(value.c_str())};
4422 }
4423
4424 void PropertyFileItem::setValue(const QVariant& value)
4425 {
4426 if (!hasExpression() && value.canConvert<QString>()) {
4427 setPropertyValue(Base::Tools::quoted(value.toString().toStdString()));
4428 }
4429 }
4430
4431 QVariant PropertyFileItem::toolTip(const App::Property* prop) const
4432 {
4433 return value(prop);
4434 }
4435
4436 QWidget* PropertyFileItem::
4437 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
4438 {
4439 auto fc = new Gui::FileChooser(parent);
4440 fc->setAutoFillBackground(true);
4441 QObject::connect(fc, &Gui::FileChooser::fileNameSelected, method);
4442 return fc;
4443 }
4444
4445 void PropertyFileItem::setEditorData(QWidget* editor, const QVariant& data) const
4446 {
4447 const App::Property* prop = getFirstProperty();
4448 if (const auto propFile = dynamic_cast<const App::PropertyFile*>(prop)) {
4449 std::string filter = propFile->getFilter();
4450 auto fc = qobject_cast<Gui::FileChooser*>(editor);
4451 if (!filter.empty()) {
4452 fc->setFilter(QString::fromStdString(filter));
4453 }
4454 fc->setFileName(data.toString());
4455 }
4456 }
4457
4458 QVariant PropertyFileItem::editorData(QWidget* editor) const
4459 {
4460 auto fc = qobject_cast<Gui::FileChooser*>(editor);
4461 return {fc->fileName()};
4462 }
4463
4464 // --------------------------------------------------------------------
4465
4466 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyPathItem)
4467
4468 PropertyPathItem::PropertyPathItem() = default;
4469
4470 QVariant PropertyPathItem::value(const App::Property* prop) const
4471 {
4472 assert(prop && prop->isDerivedFrom<App::PropertyPath>());
4473
4474 std::string value = static_cast<const App::PropertyPath*>(prop)->getValue().string();
4475 return {QString::fromUtf8(value.c_str())};
4476 }
4477
4478 void PropertyPathItem::setValue(const QVariant& value)
4479 {
4480 if (!hasExpression() && value.canConvert<QString>()) {
4481 setPropertyValue(Base::Tools::quoted(value.toString().toStdString()));
4482 }
4483 }
4484
4485 QVariant PropertyPathItem::toolTip(const App::Property* prop) const
4486 {
4487 return value(prop);
4488 }
4489
4490 QWidget* PropertyPathItem::
4491 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
4492 {
4493 auto fc = new Gui::FileChooser(parent);
4494 fc->setMode(FileChooser::Directory);
4495 fc->setAutoFillBackground(true);
4496 QObject::connect(fc, &Gui::FileChooser::fileNameSelected, method);
4497 return fc;
4498 }
4499
4500 void PropertyPathItem::setEditorData(QWidget* editor, const QVariant& data) const
4501 {
4502 auto fc = qobject_cast<Gui::FileChooser*>(editor);
4503 fc->setFileName(data.toString());
4504 }
4505
4506 QVariant PropertyPathItem::editorData(QWidget* editor) const
4507 {
4508 auto fc = qobject_cast<Gui::FileChooser*>(editor);
4509 return {fc->fileName()};
4510 }
4511
4512 // --------------------------------------------------------------------
4513
4514 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyTransientFileItem)
4515
4516 PropertyTransientFileItem::PropertyTransientFileItem() = default;
4517
4518 QVariant PropertyTransientFileItem::value(const App::Property* prop) const
4519 {
4520 assert(prop && prop->isDerivedFrom<App::PropertyFileIncluded>());
4521
4522 std::string value = static_cast<const App::PropertyFileIncluded*>(prop)->getValue();
4523 return {QString::fromUtf8(value.c_str())};
4524 }
4525
4526 void PropertyTransientFileItem::setValue(const QVariant& value)
4527 {
4528 if (!hasExpression() && value.canConvert<QString>()) {
4529 setPropertyValue(Base::Tools::quoted(value.toString().toStdString()));
4530 }
4531 }
4532
4533 QVariant PropertyTransientFileItem::toolTip(const App::Property* prop) const
4534 {
4535 return value(prop);
4536 }
4537
4538 QWidget* PropertyTransientFileItem::
4539 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
4540 {
4541 auto fc = new Gui::FileChooser(parent);
4542 fc->setAutoFillBackground(true);
4543 QObject::connect(fc, &Gui::FileChooser::fileNameSelected, method);
4544 return fc;
4545 }
4546
4547 void PropertyTransientFileItem::setEditorData(QWidget* editor, const QVariant& data) const
4548 {
4549 auto fc = qobject_cast<Gui::FileChooser*>(editor);
4550 fc->setFileName(data.toString());
4551
4552 const auto prop = dynamic_cast<const App::PropertyFileIncluded*>(getFirstProperty());
4553
4554 if (prop) {
4555 std::string filter = prop->getFilter();
4556 if (!filter.empty()) {
4557 fc->setFilter(QString::fromStdString(filter));
4558 }
4559 }
4560 }
4561
4562 QVariant PropertyTransientFileItem::editorData(QWidget* editor) const
4563 {
4564 auto fc = qobject_cast<Gui::FileChooser*>(editor);
4565 return {fc->fileName()};
4566 }
4567
4568 // ---------------------------------------------------------------
4569
4570 LinkSelection::LinkSelection(App::SubObjectT link)
4571 : link(std::move(link))
4572 {}
4573
4574 LinkSelection::~LinkSelection() = default;
4575
4576 void LinkSelection::select()
4577 {
4578 auto sobj = link.getSubObject();
4579 if (!sobj) {
4580 QMessageBox::critical(getMainWindow(), tr("Error"), tr("Object not found"));
4581 return;
4582 }
4583 Gui::Selection().selStackPush();
4584 Gui::Selection().clearSelection();
4585 Gui::Selection().addSelection(
4586 link.getDocumentName().c_str(),
4587 link.getObjectName().c_str(),
4588 link.getSubName().c_str()
4589 );
4590 this->deleteLater();
4591 }
4592
4593 // ---------------------------------------------------------------
4594
4595 LinkLabel::LinkLabel(QWidget* parent, const App::Property* prop)
4596 : QWidget(parent)
4597 , objProp(prop)
4598 , dlg(nullptr)
4599 {
4600 auto layout = new QHBoxLayout(this);
4601 layout->setContentsMargins(0, 0, 0, 0);
4602 layout->setSpacing(1);
4603
4604 label = new QLabel(this);
4605 label->setAutoFillBackground(true);
4606 label->setTextFormat(Qt::RichText);
4607 // Below is necessary for the hytperlink to be clickable without losing focus
4608 label->setTextInteractionFlags(Qt::TextBrowserInteraction);
4609 layout->addWidget(label);
4610
4611 editButton = new QPushButton(QStringLiteral("…"), this);
4612 #if defined(Q_OS_MACOS)
4613 editButton->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct
4614 #endif
4615 editButton->setToolTip(tr("Changes the linked object"));
4616 layout->addWidget(editButton);
4617
4618 this->setFocusPolicy(Qt::StrongFocus);
4619 this->setFocusProxy(label);
4620
4621 // setLayout(layout);
4622
4623 connect(label, &QLabel::linkActivated, this, &LinkLabel::onLinkActivated);
4624 connect(editButton, &QPushButton::clicked, this, &LinkLabel::onEditClicked);
4625 }
4626
4627 LinkLabel::~LinkLabel() = default;
4628
4629 void LinkLabel::updatePropertyLink()
4630 {
4631 QString text;
4632 auto owner = objProp.getObject();
4633 auto prop = freecad_cast<App::PropertyLinkBase*>(objProp.getProperty());
4634
4635 link = QVariant();
4636
4637 if (owner && prop) {
4638 auto links = DlgPropertyLink::getLinksFromProperty(prop);
4639 if (links.size() == 1) {
4640 auto& sobj = links.front();
4641 link = QVariant::fromValue(sobj);
4642 QString linkcolor = QApplication::palette().color(QPalette::Link).name();
4643 text = QStringLiteral(
4644 "<html><head><style type=\"text/css\">"
4645 "p, li { white-space: pre-wrap; }"
4646 "</style></head><body>"
4647 "<p>"
4648 "<a href=\"%1#%2.%3\"><span style=\" text-decoration: "
4649 "underline; color:%4;\">%5</span></a>"
4650 "</p></body></html>"
4651 )
4652 .arg(
4653 QLatin1String(sobj.getDocumentName().c_str()),
4654 QLatin1String(sobj.getObjectName().c_str()),
4655 QString::fromUtf8(sobj.getSubName().c_str()),
4656 linkcolor,
4657 DlgPropertyLink::formatObject(
4658 owner->getDocument(),
4659 sobj.getObject(),
4660 sobj.getSubName().c_str()
4661 )
4662 );
4663 }
4664 else if (!links.empty()) {
4665 text = DlgPropertyLink::formatLinks(owner->getDocument(), links);
4666 }
4667 }
4668 label->setText(text);
4669 }
4670
4671 QVariant LinkLabel::propertyLink() const
4672 {
4673 return link;
4674 }
4675
4676 void LinkLabel::onLinkActivated(const QString& s)
4677 {
4678 Q_UNUSED(s);
4679 auto select = new LinkSelection(qvariant_cast<App::SubObjectT>(link));
4680 QTimer::singleShot(50, select, &LinkSelection::select); // NOLINT
4681 }
4682
4683 void LinkLabel::onEditClicked()
4684 {
4685 if (!dlg) {
4686 dlg = new DlgPropertyLink(this);
4687 dlg->init(objProp, true);
4688 connect(dlg, &DlgPropertyLink::accepted, this, &LinkLabel::onLinkChanged);
4689 }
4690 else {
4691 dlg->init(objProp, false);
4692 }
4693
4694 dlg->show();
4695 }
4696
4697 void LinkLabel::onLinkChanged()
4698 {
4699 if (dlg) {
4700 auto links = dlg->currentLinks();
4701 if (links != dlg->originalLinks()) {
4702 link = QVariant::fromValue(links);
4703 Q_EMIT linkChanged(link);
4704 updatePropertyLink();
4705 }
4706 }
4707 }
4708
4709 void LinkLabel::resizeEvent(QResizeEvent* e)
4710 {
4711 editButton->setFixedWidth(e->size().height());
4712 }
4713
4714 // --------------------------------------------------------------------
4715
4716 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyLinkItem)
4717
4718 PropertyLinkItem::PropertyLinkItem() = default;
4719
4720 QString PropertyLinkItem::toString(const QVariant& prop) const
4721 {
4722 if (propertyItems.empty()) {
4723 return {};
4724 }
4725 App::DocumentObjectT owner(propertyItems[0]);
4726 return DlgPropertyLink::formatLinks(
4727 owner.getDocument(),
4728 qvariant_cast<QList<App::SubObjectT>>(prop)
4729 );
4730 }
4731
4732 QVariant PropertyLinkItem::data(int column, int role) const
4733 {
4734 if (!propertyItems.empty() && column == 1
4735 && (role == Qt::ForegroundRole || role == Qt::ToolTipRole)) {
4736 if (auto propLink = dynamic_cast<const App::PropertyLinkBase*>(propertyItems[0])) {
4737 if (role == Qt::ForegroundRole && propLink->checkRestore() > 1) {
4738 return QVariant::fromValue(QColor(0xff, 0, 0)); // NOLINT
4739 }
4740 if (role == Qt::ToolTipRole) {
4741 if (auto xlink = dynamic_cast<const App::PropertyXLink*>(propertyItems[0])) {
4742 const char* filePath = xlink->getFilePath();
4743 if (!Base::Tools::isNullOrEmpty(filePath)) {
4744 return QVariant::fromValue(QString::fromUtf8(filePath));
4745 }
4746 }
4747 }
4748 }
4749 }
4750
4751 return PropertyItem::data(column, role);
4752 }
4753
4754 QVariant PropertyLinkItem::value(const App::Property* prop) const
4755 {
4756 auto propLink = freecad_cast<App::PropertyLinkBase*>(prop);
4757 if (!propLink) {
4758 return {};
4759 }
4760
4761 auto links = DlgPropertyLink::getLinksFromProperty(propLink);
4762 if (links.empty()) {
4763 return {};
4764 }
4765
4766 return QVariant::fromValue(links);
4767 }
4768
4769 void PropertyLinkItem::setValue(const QVariant& value)
4770 {
4771 auto links = qvariant_cast<QList<App::SubObjectT>>(value);
4772 setPropertyValue(DlgPropertyLink::linksToPython(links));
4773 }
4774
4775 QWidget* PropertyLinkItem::
4776 createEditor(QWidget* parent, const std::function<void()>& method, FrameOption /*frameOption*/) const
4777 {
4778 if (propertyItems.empty()) {
4779 return nullptr;
4780 }
4781 auto ll = new LinkLabel(parent, propertyItems.front());
4782 ll->setAutoFillBackground(true);
4783 QObject::connect(ll, &LinkLabel::linkChanged, method);
4784 return ll;
4785 }
4786
4787 void PropertyLinkItem::setEditorData(QWidget* editor, const QVariant& data) const
4788 {
4789 (void)data;
4790 auto ll = qobject_cast<LinkLabel*>(editor);
4791 return ll->updatePropertyLink();
4792 }
4793
4794 QVariant PropertyLinkItem::editorData(QWidget* editor) const
4795 {
4796 auto ll = qobject_cast<LinkLabel*>(editor);
4797 return ll->propertyLink();
4798 }
4799
4800 // --------------------------------------------------------------------
4801
4802 PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyLinkListItem)
4803
4804 PropertyLinkListItem::PropertyLinkListItem() = default;
4805
4806 PropertyItemEditorFactory::PropertyItemEditorFactory() = default;
4807
4808 PropertyItemEditorFactory::~PropertyItemEditorFactory() = default;
4809
4810 QWidget* PropertyItemEditorFactory::createEditor(int /*type*/, QWidget* /*parent*/) const
4811 {
4812 // do not allow to create any editor widgets because we do that in subclasses of PropertyItem
4813 return nullptr;
4814 }
4815
4816 QByteArray PropertyItemEditorFactory::valuePropertyName(int /*type*/) const
4817 {
4818 // do not allow to set properties because we do that in subclasses of PropertyItem
4819 return "";
4820 }
4821 // NOLINTEND(cppcoreguidelines-pro-*,cppcoreguidelines-prefer-member-initializer)
4822
4823 #include "moc_PropertyItem.cpp"