Debian Codegraph @

src/Gui/propertyeditor/PropertyEditor.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 #include <algorithm>
25 #include <boost/algorithm/string/predicate.hpp>
26 #include <QApplication>
27 #include <QClipboard>
28 #include <QInputDialog>
29 #include <QHeaderView>
30 #include <QMenu>
31 #include <QPainter>
32 #include <QActionGroup>
33
34 #include <App/Application.h>
35 #include <App/AutoTransaction.h>
36 #include <App/Document.h>
37 #include <Base/Console.h>
38 #include <Base/Tools.h>
39
40 #include "Document.h"
41 #include "Tree.h"
42 #include "PropertyEditor.h"
43 #include "Dialogs/DlgAddProperty.h"
44 #include "MainWindow.h"
45 #include "PropertyItemDelegate.h"
46 #include "PropertyModel.h"
47 #include "PropertyView.h"
48 #include "ViewProviderDocumentObject.h"
49
50
51 FC_LOG_LEVEL_INIT("PropertyView", true, true)
52
53 using namespace Gui::PropertyEditor;
54
55 PropertyEditor::PropertyEditor(QWidget* parent)
56 : QTreeView(parent)
57 , expansionMode(ExpansionMode::DefaultExpand)
58 , autoupdate(false)
59 , committing(false)
60 , delaybuild(false)
61 , binding(false)
62 , checkDocument(false)
63 , closingEditor(false)
64 , dragInProgress(false)
65 {
66 propertyModel = new PropertyModel(this);
67 setModel(propertyModel);
68
69 setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
70 setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
71
72 delegate = new PropertyItemDelegate(this);
73 delegate->setItemEditorFactory(new PropertyItemEditorFactory);
74 setItemDelegate(delegate);
75 // prevent a non-persistent editor when pressing an edit key
76 setEditTriggers(QAbstractItemView::NoEditTriggers);
77
78 setAlternatingRowColors(true);
79 setRootIsDecorated(false);
80 setExpandsOnDoubleClick(false);
81
82 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
83 QStyleOptionViewItem opt = PropertyEditor::viewOptions();
84 #else
85 QStyleOptionViewItem opt;
86 initViewItemOption(&opt);
87 #endif
88 this->background = opt.palette.dark();
89 this->groupColor = opt.palette.color(QPalette::BrightText);
90
91 this->_itemBackground.setColor(QColor(0, 0, 0, 0));
92
93 this->setSelectionMode(QAbstractItemView::ExtendedSelection);
94
95 // clang-format off
96 connect(this, &QTreeView::activated, this, &PropertyEditor::onItemActivated);
97 connect(this, &QTreeView::clicked, this, &PropertyEditor::onItemActivated);
98 connect(this, &QTreeView::expanded, this, &PropertyEditor::onItemExpanded);
99 connect(this, &QTreeView::collapsed, this, &PropertyEditor::onItemCollapsed);
100 connect(propertyModel, &QAbstractItemModel::rowsMoved, this, &PropertyEditor::onRowsMoved);
101 connect(propertyModel, &QAbstractItemModel::rowsRemoved, this, &PropertyEditor::onRowsRemoved);
102 // clang-format on
103
104 setHeaderHidden(true);
105 viewport()->installEventFilter(this);
106 viewport()->setMouseTracking(true);
107
108 auto hGrp = App::GetApplication().GetParameterGroupByPath(
109 "User parameter:BaseApp/Preferences/DockWindows/PropertyView"
110 );
111 int firstColumnSize = hGrp->GetInt("FirstColumnSize", 0);
112 if (firstColumnSize != 0) {
113 header()->resizeSection(0, firstColumnSize);
114 }
115 }
116
117 PropertyEditor::~PropertyEditor()
118 {
119 QItemEditorFactory* f = delegate->itemEditorFactory();
120 delegate->setItemEditorFactory(nullptr);
121 delete f;
122 }
123
124 void PropertyEditor::onItemExpanded(const QModelIndex& index)
125 {
126 auto item = static_cast<PropertyItem*>(index.internalPointer());
127 item->setExpanded(true);
128 for (int i = 0, c = item->childCount(); i < c; ++i) {
129 setExpanded(propertyModel->index(i, 0, index), item->child(i)->isExpanded());
130 }
131 }
132
133 void PropertyEditor::onItemCollapsed(const QModelIndex& index)
134 {
135 auto item = static_cast<PropertyItem*>(index.internalPointer());
136 item->setExpanded(false);
137 }
138
139 void PropertyEditor::setAutomaticDocumentUpdate(bool v)
140 {
141 autoupdate = v;
142 }
143
144 bool PropertyEditor::isAutomaticDocumentUpdate(bool) const
145 {
146 return autoupdate;
147 }
148
149 QBrush PropertyEditor::groupBackground() const
150 {
151 return this->background;
152 }
153
154 void PropertyEditor::setGroupBackground(const QBrush& c)
155 {
156 this->background = c;
157 }
158
159 QColor PropertyEditor::groupTextColor() const
160 {
161 return this->groupColor;
162 }
163
164 void PropertyEditor::setGroupTextColor(const QColor& c)
165 {
166 this->groupColor = c;
167 }
168
169 QBrush PropertyEditor::itemBackground() const
170 {
171 return this->_itemBackground;
172 }
173
174 void PropertyEditor::setItemBackground(const QBrush& c)
175 {
176 this->_itemBackground = c;
177 }
178
179 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
180 QStyleOptionViewItem PropertyEditor::viewOptions() const
181 {
182 QStyleOptionViewItem option = QTreeView::viewOptions();
183 option.showDecorationSelected = true;
184 return option;
185 }
186 #else
187 void PropertyEditor::initViewItemOption(QStyleOptionViewItem* option) const
188 {
189 QTreeView::initViewItemOption(option);
190 option->showDecorationSelected = true;
191 }
192 #endif
193
194 bool PropertyEditor::event(QEvent* event)
195 {
196 if (event->type() == QEvent::ShortcutOverride) {
197 auto kevent = static_cast<QKeyEvent*>(event);
198 Qt::KeyboardModifiers ShiftKeypadModifier = Qt::ShiftModifier | Qt::KeypadModifier;
199 if (kevent->modifiers() == Qt::NoModifier || kevent->modifiers() == Qt::ShiftModifier
200 || kevent->modifiers() == Qt::KeypadModifier
201 || kevent->modifiers() == ShiftKeypadModifier) {
202 switch (kevent->key()) {
203 case Qt::Key_Delete:
204 case Qt::Key_Home:
205 case Qt::Key_End:
206 case Qt::Key_Backspace:
207 case Qt::Key_Left:
208 case Qt::Key_Right:
209 kevent->accept();
210 default:
211 break;
212 }
213 }
214 }
215 return QTreeView::event(event);
216 }
217
218 bool PropertyEditor::removeSelectedDynamicProperties()
219 {
220 std::unordered_set<App::Property*> props = acquireSelectedProperties();
221 if (props.empty()) {
222 return false;
223 }
224
225 bool canRemove = std::ranges::all_of(props, [](auto prop) {
226 return prop->testStatus(App::Property::PropDynamic)
227 && !prop->testStatus(App::Property::LockDynamic);
228 });
229 if (!canRemove) {
230 return false;
231 }
232
233 removeProperties(props);
234 return true;
235 }
236
237 void PropertyEditor::keyPressEvent(QKeyEvent* event)
238 {
239 if (state() == QAbstractItemView::EditingState) {
240 QTreeView::keyPressEvent(event);
241 return;
242 }
243
244 const auto key = event->key();
245 const auto mods = event->modifiers();
246
247 const bool allowedDeleteModifiers = mods == Qt::NoModifier || mods == Qt::KeypadModifier;
248
249 #if defined(Q_OS_MACOS) || defined(Q_OS_MAC)
250 const bool isDeleteKey = key == Qt::Key_Backspace || key == Qt::Key_Delete;
251 const bool isEditKey = (mods == Qt::NoModifier)
252 && (key == Qt::Key_Return || key == Qt::Key_Enter);
253 #else
254 const bool isDeleteKey = key == Qt::Key_Delete;
255 const bool isEditKey = (mods == Qt::NoModifier) && (key == Qt::Key_F2);
256 #endif
257
258 if (allowedDeleteModifiers && isDeleteKey) {
259 if (removeSelectedDynamicProperties()) {
260 event->accept();
261 return;
262 }
263 }
264 else if (isEditKey) {
265 // open a persistent editor when an edit key is pressed
266 event->accept();
267 auto index = model() ? model()->buddy(currentIndex()) : QModelIndex();
268 if (index.isValid()) {
269 openEditor(index);
270 }
271 return;
272 }
273
274 QTreeView::keyPressEvent(event);
275 }
276
277 void PropertyEditor::commitData(QWidget* editor)
278 {
279 committing = true;
280 QTreeView::commitData(editor);
281 committing = false;
282 if (delaybuild) {
283 delaybuild = false;
284 propertyModel->buildUp(PropertyModel::PropertyList());
285 }
286 }
287
288 void PropertyEditor::editorDestroyed(QObject* editor)
289 {
290 QTreeView::editorDestroyed(editor);
291
292 // When editing expression through context menu, the editor (ExpLineEditor)
293 // deletes itself when finished, so it won't trigger closeEditor signal. We
294 // must handle it here to perform auto update.
295 closeTransaction();
296 }
297
298 void PropertyEditor::currentChanged(const QModelIndex& current, const QModelIndex& previous)
299 {
300 FC_LOG(
301 "current changed " << current.row() << "," << current.column() << " " << previous.row()
302 << "," << previous.column()
303 );
304
305 QTreeView::currentChanged(current, previous);
306
307 // if (previous.isValid())
308 // closePersistentEditor(model()->buddy(previous));
309
310 // DO NOT activate editor here, use onItemActivate() which response to
311 // signals of activated and clicked.
312 //
313 // if (current.isValid())
314 // openPersistentEditor(model()->buddy(current));
315 }
316
317 void PropertyEditor::closeEditor()
318 {
319 if (editingIndex.isValid()) {
320 Base::StateLocker guard(closingEditor);
321 bool hasFocus = activeEditor && activeEditor->hasFocus();
322 #ifdef Q_OS_MACOS
323 // Brute-force workaround for https://github.com/FreeCAD/FreeCAD/issues/14350
324 int currentIndex = 0;
325 QTabBar* tabBar = nullptr;
326 if (auto mdiArea = Gui::MainWindow::getInstance()->findChild<QMdiArea*>()) {
327 tabBar = mdiArea->findChild<QTabBar*>();
328 if (tabBar) {
329 currentIndex = tabBar->currentIndex();
330 }
331 }
332 #endif
333 closePersistentEditor(editingIndex);
334 #ifdef Q_OS_MACOS
335 if (tabBar) {
336 tabBar->setCurrentIndex(currentIndex);
337 }
338 #endif
339 editingIndex = QPersistentModelIndex();
340 activeEditor = nullptr;
341 if (hasFocus) {
342 setFocus();
343 }
344 }
345 }
346
347 void PropertyEditor::openEditor(const QModelIndex& index)
348 {
349 if (editingIndex == index && activeEditor) {
350 return;
351 }
352
353 closeEditor();
354
355 openPersistentEditor(model()->buddy(index));
356
357 if (!editingIndex.isValid() || !autoupdate) {
358 return;
359 }
360
361 auto& app = App::GetApplication();
362 if (app.getActiveTransaction()) {
363 FC_LOG("editor already transacting " << app.getActiveTransaction());
364 return;
365 }
366 auto item = static_cast<PropertyItem*>(editingIndex.internalPointer());
367 auto items = item->getPropertyData();
368 for (auto propItem = item->parent(); items.empty() && propItem; propItem = propItem->parent()) {
369 items = propItem->getPropertyData();
370 }
371 if (items.empty()) {
372 FC_LOG("editor no item");
373 return;
374 }
375 auto prop = items[0];
376 auto parent = prop->getContainer();
377 auto obj = freecad_cast<App::DocumentObject*>(parent);
378 if (!obj) {
379 auto view = freecad_cast<ViewProviderDocumentObject*>(parent);
380 if (view) {
381 obj = view->getObject();
382 }
383 }
384 if (!obj || !obj->getDocument()) {
385 FC_LOG("invalid object");
386 return;
387 }
388 if (obj->getDocument()->hasPendingTransaction()) {
389 FC_LOG("pending transaction");
390 return;
391 }
392 std::ostringstream str;
393 str << tr("Edit").toUtf8().constData() << ' ';
394 for (auto prop : items) {
395 if (prop->getContainer() != obj) {
396 obj = nullptr;
397 break;
398 }
399 }
400 if (obj && obj->isAttachedToDocument()) {
401 str << obj->getNameInDocument() << '.';
402 }
403 else {
404 str << tr("property").toUtf8().constData() << ' ';
405 }
406 str << prop->getName();
407 if (items.size() > 1) {
408 str << "...";
409 }
410 transactionID = app.setActiveTransaction(str.str().c_str());
411 FC_LOG("editor transaction " << app.getActiveTransaction());
412 }
413
414 void PropertyEditor::onItemActivated(const QModelIndex& index)
415 {
416 if (!index.isValid()) {
417 return;
418 }
419 if (auto* prop = static_cast<PropertyItem*>(index.internalPointer());
420 prop && prop->isSeparator()) {
421
422 // setExpanded() only works on column 0
423 QModelIndex idxFirstColum = propertyModel->index(index.row(), 0, index.parent());
424 setExpanded(idxFirstColum, !isExpanded(idxFirstColum));
425 return;
426 }
427
428 if (index.column() != 1) {
429 return;
430 }
431 openEditor(index);
432 }
433
434 void PropertyEditor::recomputeDocument(App::Document* doc)
435 {
436 try {
437 if (doc && !doc->isTransactionEmpty()) {
438 // Between opening and committing a transaction a recompute
439 // could already have been done
440 if (doc->isTouched()) {
441 doc->recompute();
442 }
443 }
444 }
445 // do not re-throw
446 catch (const Base::Exception& e) {
447 e.reportException();
448 }
449 catch (const std::exception& e) {
450 Base::Console().error(
451 "Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n"
452 "The error message is: %s\n",
453 e.what()
454 );
455 }
456 catch (...) {
457 Base::Console().error(
458 "Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n"
459 );
460 }
461 }
462
463 void PropertyEditor::closeTransaction()
464 {
465 int tid = 0;
466 if (App::GetApplication().getActiveTransaction(&tid) && tid == transactionID) {
467 if (autoupdate) {
468 App::Document* doc = App::GetApplication().getActiveDocument();
469 recomputeDocument(doc);
470 }
471 App::GetApplication().closeActiveTransaction();
472 }
473 }
474
475 void PropertyEditor::closeEditor(QWidget* editor, QAbstractItemDelegate::EndEditHint hint)
476 {
477 if (closingEditor) {
478 return;
479 }
480
481 if (removingRows) {
482 // When removing rows, QTreeView will temporary hide the editor which
483 // will trigger Event::FocusOut and subsequently trigger call of
484 // closeEditor() here. Since we are using persistent editor, QTreeView
485 // will not destroy the editor. But we still needs to call
486 // QTreeView::closeEditor() here, in case the editor belongs to the
487 // removed rows.
488 QTreeView::closeEditor(editor, hint);
489 return;
490 }
491
492 closeTransaction();
493
494 // If we are not removing rows, then QTreeView::closeEditor() does nothing
495 // because we are using persistent editor, so we have to call our own
496 // version of closeEditor()
497 this->closeEditor();
498
499 QModelIndex indexSaved = currentIndex();
500
501 if (indexSaved.column() == 0) {
502 // Calling setCurrentIndex() to make sure we focus on column 1 instead of 0.
503 setCurrentIndex(propertyModel->buddy(indexSaved));
504 }
505
506 QModelIndex lastIndex = indexSaved;
507 bool wrapped = false;
508 do {
509 QModelIndex index;
510 if (hint == QAbstractItemDelegate::EditNextItem) {
511 index = moveCursor(MoveDown, Qt::NoModifier);
512 }
513 else if (hint == QAbstractItemDelegate::EditPreviousItem) {
514 index = moveCursor(MoveUp, Qt::NoModifier);
515 }
516 else {
517 break;
518 }
519 if (!index.isValid() || index == lastIndex) {
520 if (wrapped) {
521 setCurrentIndex(propertyModel->buddy(indexSaved));
522 break;
523 }
524 wrapped = true;
525 if (hint == QAbstractItemDelegate::EditNextItem) {
526 index = moveCursor(MoveHome, Qt::NoModifier);
527 }
528 else {
529 index = moveCursor(MoveEnd, Qt::NoModifier);
530 }
531 if (!index.isValid() || index == indexSaved) {
532 break;
533 }
534 }
535 lastIndex = index;
536 setCurrentIndex(propertyModel->buddy(index));
537
538 auto item = static_cast<PropertyItem*>(index.internalPointer());
539 // Skip readonly item, because the editor will be disabled and hence
540 // does not accept focus, and in turn break Tab/Backtab navigation.
541 if (item && item->isReadOnly()) {
542 continue;
543 }
544
545 openEditor(index);
546
547 } while (!editingIndex.isValid());
548 }
549
550 void PropertyEditor::reset()
551 {
552 QTreeView::reset();
553
554 closeTransaction();
555
556 QModelIndex parent;
557 int numRows = propertyModel->rowCount(parent);
558 for (int i = 0; i < numRows; ++i) {
559 QModelIndex index = propertyModel->index(i, 0, parent);
560 auto item = static_cast<PropertyItem*>(index.internalPointer());
561 if (item->childCount() == 0) {
562 if (item->isSeparator()) {
563 setRowHidden(i, parent, true);
564 }
565 }
566 else {
567 setEditorMode(index, 0, item->childCount() - 1);
568 }
569 if (item->isExpanded()) {
570 setExpanded(index, true);
571 }
572 }
573 }
574
575 void PropertyEditor::onRowsMoved(const QModelIndex& parent, int start, int end, const QModelIndex& dst, int)
576 {
577 if (parent != dst) {
578 auto item = static_cast<PropertyItem*>(parent.internalPointer());
579 if (item && item->isSeparator() && item->childCount() == 0) {
580 setRowHidden(parent.row(), propertyModel->parent(parent), true);
581 }
582 item = static_cast<PropertyItem*>(dst.internalPointer());
583 if (item && item->isSeparator() && item->childCount() == end - start + 1) {
584 setRowHidden(dst.row(), propertyModel->parent(dst), false);
585 setExpanded(dst, true);
586 }
587 }
588 }
589
590 void PropertyEditor::rowsInserted(const QModelIndex& parent, int start, int end)
591 {
592 QTreeView::rowsInserted(parent, start, end);
593
594 auto item = static_cast<PropertyItem*>(parent.internalPointer());
595 if (item && item->isSeparator() && item->childCount() == end - start + 1) {
596 setRowHidden(parent.row(), propertyModel->parent(parent), false);
597 if (item->isExpanded()) {
598 setExpanded(parent, true);
599 }
600 }
601
602 for (int i = start; i < end; ++i) {
603 QModelIndex index = propertyModel->index(i, 0, parent);
604 auto child = static_cast<PropertyItem*>(index.internalPointer());
605 if (child->isSeparator()) {
606 // Set group header rows to span all columns
607 setFirstColumnSpanned(i, parent, true);
608 }
609 if (child->isExpanded()) {
610 setExpanded(index, true);
611 }
612 }
613
614 if (parent.isValid()) {
615 setEditorMode(parent, start, end);
616 }
617 }
618
619 void PropertyEditor::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
620 {
621 QTreeView::rowsAboutToBeRemoved(parent, start, end);
622
623 auto item = static_cast<PropertyItem*>(parent.internalPointer());
624 if (item && item->isSeparator() && item->childCount() == end - start + 1) {
625 setRowHidden(parent.row(), propertyModel->parent(parent), true);
626 }
627
628 if (editingIndex.isValid()) {
629 if (editingIndex.row() >= start && editingIndex.row() <= end) {
630 closeTransaction();
631 }
632 else {
633 removingRows = 1;
634 for (QWidget* w = qApp->focusWidget(); w; w = w->parentWidget()) {
635 if (w == activeEditor) {
636 removingRows = -1;
637 break;
638 }
639 }
640 }
641 }
642 }
643
644 void PropertyEditor::onRowsRemoved(const QModelIndex&, int, int)
645 {
646 if (removingRows < 0 && activeEditor) {
647 activeEditor->setFocus();
648 }
649 removingRows = 0;
650 }
651
652 void PropertyEditor::drawBranches(QPainter* painter, const QRect& rect, const QModelIndex& index) const
653 {
654 QTreeView::drawBranches(painter, rect, index);
655
656 auto property = static_cast<PropertyItem*>(index.internalPointer());
657
658 if (property && property->isSeparator()) {
659 painter->fillRect(rect, this->background);
660 }
661 }
662
663 void Gui::PropertyEditor::PropertyEditor::drawRow(
664 QPainter* painter,
665 const QStyleOptionViewItem& options,
666 const QModelIndex& index
667 ) const
668 {
669 // render background also for non alternate rows based on the `itemBackground` property.
670 painter->fillRect(options.rect, itemBackground());
671
672 QTreeView::drawRow(painter, options, index);
673 }
674
675 void PropertyEditor::blockCollapseAll()
676 {
677 blockCollapse = true;
678 }
679
680 void PropertyEditor::buildUp(PropertyModel::PropertyList&& props, bool _checkDocument)
681 {
682 checkDocument = _checkDocument;
683
684 if (committing) {
685 Base::Console().warning(
686 "While committing the data to the property the selection has changed.\n"
687 );
688 delaybuild = true;
689 return;
690 }
691
692 // Do not close transaction here, because we are now doing incremental
693 // update in PropertyModel::buildUp()
694 //
695 // closeTransaction();
696
697 QModelIndex index = this->currentIndex();
698 QStringList propertyPath = propertyModel->propertyPathFromIndex(index);
699 if (!propertyPath.isEmpty()) {
700 this->selectedProperty = propertyPath;
701 }
702 propertyModel->buildUp(props);
703 if (!this->selectedProperty.isEmpty()) {
704 QModelIndex index = propertyModel->propertyIndexFromPath(this->selectedProperty);
705 this->setCurrentIndex(index);
706 }
707
708 propList = std::move(props);
709 propOwners.clear();
710 for (auto& v : propList) {
711 for (auto prop : v.second) {
712 auto container = prop->getContainer();
713 if (!container) {
714 continue;
715 }
716 // Include document to get proper handling in PropertyView::slotDeleteDocument()
717 if (checkDocument && container->isDerivedFrom<App::DocumentObject>()) {
718 propOwners.insert(static_cast<App::DocumentObject*>(container)->getDocument());
719 }
720 propOwners.insert(container);
721 }
722 }
723
724 switch (expansionMode) {
725 case ExpansionMode::DefaultExpand:
726 // take the current expansion state
727 break;
728 case ExpansionMode::AutoExpand:
729 expandAll();
730 break;
731 case ExpansionMode::AutoCollapse:
732 if (!blockCollapse) {
733 collapseAll();
734 }
735 blockCollapse = false;
736 break;
737 }
738 }
739
740 void PropertyEditor::updateProperty(const App::Property& prop)
741 {
742 // forward this to the model if the property is changed from outside
743 if (!committing) {
744 propertyModel->updateProperty(prop);
745 }
746 blockCollapseAll();
747 }
748
749 void PropertyEditor::setEditorMode(const QModelIndex& parent, int start, int end)
750 {
751 int column = 1;
752 for (int i = start; i <= end; i++) {
753 QModelIndex item = propertyModel->index(i, column, parent);
754 auto propItem = static_cast<PropertyItem*>(item.internalPointer());
755 if (!PropertyView::showAll() && propItem && propItem->testStatus(App::Property::Hidden)) {
756 setRowHidden(i, parent, true);
757 }
758 }
759 }
760
761 void PropertyEditor::removeProperty(const App::Property& prop)
762 {
763 for (auto it = propList.begin(); it != propList.end(); ++it) {
764 // find the given property in the list and remove it if it's there
765 auto pos = std::ranges::find(it->second, &prop);
766 if (pos != it->second.end()) {
767 it->second.erase(pos);
768 // if the last property of this name is removed then also remove the whole group
769 if (it->second.empty()) {
770 propList.erase(it);
771 }
772 propertyModel->removeProperty(prop);
773 break;
774 }
775 }
776 blockCollapseAll();
777 }
778
779 void PropertyEditor::renameProperty(const App::Property& prop)
780 {
781 for (auto& it : propList) {
782 // find the given property in the list and rename it if it's there
783 auto pos = std::ranges::find(it.second, &prop);
784 if (pos != it.second.end()) {
785 propertyModel->renameProperty(prop);
786 break;
787 }
788 }
789 blockCollapseAll();
790 }
791
792 enum MenuAction
793 {
794 MA_AutoCollapse,
795 MA_AutoExpand,
796 MA_ExpandToDefault,
797 MA_DefaultExpand,
798 MA_CollapseAll,
799 MA_ExpandAll,
800 MA_ShowHidden,
801 MA_Expression,
802 MA_RemoveProp,
803 MA_RenameProp,
804 MA_AddProp,
805 MA_EditPropTooltip,
806 MA_EditPropGroup,
807 MA_Transient,
808 MA_Output,
809 MA_NoRecompute,
810 MA_ReadOnly,
811 MA_Hidden,
812 MA_Touched,
813 MA_EvalOnRestore,
814 MA_CopyOnChange,
815 MA_Copy,
816 };
817
818 void PropertyEditor::setFirstLevelExpanded(bool doExpand)
819 {
820 if (!propertyModel) {
821 return;
822 }
823
824 std::function<void(const QModelIndex&, bool)> setExpanded = [&](const QModelIndex& index,
825 bool doExpand) {
826 if (!index.isValid()) {
827 return;
828 }
829
830 auto* item = static_cast<PropertyItem*>(index.internalPointer());
831 if (item == nullptr || item->childCount() <= 0) {
832 return;
833 }
834
835 if (doExpand) {
836 expand(index);
837 }
838 else {
839 collapse(index);
840 }
841
842 for (int row = 0; row < propertyModel->rowCount(index); ++row) {
843 setExpanded(propertyModel->index(row, 0, index), false);
844 }
845 };
846
847 const QModelIndex root = QModelIndex();
848 for (int row = 0; row < propertyModel->rowCount(root); ++row) {
849 setExpanded(propertyModel->index(row, 0, root), doExpand);
850 }
851 }
852
853 void PropertyEditor::expandToDefault()
854 {
855 setFirstLevelExpanded(true);
856 }
857
858 void PropertyEditor::collapseAll()
859 {
860 setFirstLevelExpanded(false);
861 }
862
863 QMenu* PropertyEditor::setupExpansionSubmenu(QWidget* parent)
864 {
865 auto* expandMenu = new QMenu(tr("Expand/Collapse Properties"), parent);
866
867 QAction* expandToDefault = expandMenu->addAction(tr("Expand to Default"));
868 expandToDefault->setData(QVariant(MA_ExpandToDefault));
869 QAction* expandAll = expandMenu->addAction(tr("Expand All"));
870 expandAll->setData(QVariant(MA_ExpandAll));
871 QAction* collapseAll = expandMenu->addAction(tr("Collapse All"));
872 collapseAll->setData(QVariant(MA_CollapseAll));
873
874 auto* group = new QActionGroup(expandMenu);
875 group->setExclusive(true);
876
877 QAction* defaultExpand = expandMenu->addAction(tr("Default Expand"));
878 defaultExpand->setData(QVariant(MA_DefaultExpand));
879
880 QAction* autoExpand = expandMenu->addAction(tr("Auto Expand"));
881 autoExpand->setData(QVariant(MA_AutoExpand));
882
883 QAction* autoCollapse = expandMenu->addAction(tr("Auto Collapse"));
884 autoCollapse->setData(QVariant(MA_AutoCollapse));
885
886 for (QAction* action : {defaultExpand, autoExpand, autoCollapse}) {
887 action->setCheckable(true);
888 group->addAction(action);
889 }
890
891 switch (expansionMode) {
892 case ExpansionMode::DefaultExpand:
893 defaultExpand->setChecked(true);
894 break;
895 case ExpansionMode::AutoExpand:
896 autoExpand->setChecked(true);
897 break;
898 case ExpansionMode::AutoCollapse:
899 autoCollapse->setChecked(true);
900 break;
901 }
902
903 return expandMenu;
904 }
905
906 static App::PropertyContainer* getSelectedPropertyContainer()
907 {
908 auto sels = Gui::Selection().getSelection("*");
909 if (sels.size() == 1) {
910 return sels[0].pObject;
911 }
912 std::vector<Gui::Document*> docs = Gui::TreeWidget::getSelectedDocuments();
913 if (docs.size() == 1) {
914 return docs[0]->getDocument();
915 }
916 return nullptr;
917 }
918
919 std::unordered_set<App::Property*> PropertyEditor::acquireSelectedProperties() const
920 {
921 std::unordered_set<App::Property*> props;
922 const auto indexes = selectedIndexes();
923 for (const auto& index : indexes) {
924 auto item = static_cast<PropertyItem*>(index.internalPointer());
925 if (item->isSeparator()) {
926 continue;
927 }
928 for (auto parent = item; parent; parent = parent->parent()) {
929 const auto& ps = parent->getPropertyData();
930 if (!ps.empty()) {
931 props.insert(ps.begin(), ps.end());
932 break;
933 }
934 }
935 if (index.column() > 0) {
936 continue;
937 }
938 }
939 return props;
940 }
941
942 void PropertyEditor::removeProperties(const std::unordered_set<App::Property*>& props)
943 {
944 App::AutoTransaction committer("Remove property");
945 for (auto prop : props) {
946 try {
947 prop->getContainer()->removeDynamicProperty(prop->getName());
948 }
949 catch (Base::Exception& e) {
950 e.reportException();
951 }
952 }
953 }
954
955 void PropertyEditor::contextMenuEvent(QContextMenuEvent*)
956 {
957 QMenu menu;
958 auto contextIndex = currentIndex();
959
960 std::unordered_set<App::Property*> props = acquireSelectedProperties();
961
962 // copy value to clipboard
963 if (props.size() == 1) {
964 const QVariant valueToCopy = contextIndex.data(Qt::DisplayRole);
965 if (valueToCopy.isValid()) {
966 QAction* copyAction = menu.addAction(tr("Copy"));
967 copyAction->setData(QVariant(MA_Copy));
968 menu.addSeparator();
969 }
970 }
971
972 // add property
973 if (getSelectedPropertyContainer()) {
974 menu.addAction(tr("Add Property"))->setData(QVariant(MA_AddProp));
975 }
976
977 // rename property group
978 if (!props.empty() && std::all_of(props.begin(), props.end(), [](auto prop) {
979 return prop->testStatus(App::Property::PropDynamic)
980 && !boost::starts_with(prop->getName(), prop->getGroup());
981 })) {
982 menu.addAction(tr("Rename Property Group"))->setData(QVariant(MA_EditPropGroup));
983 }
984
985 // rename property
986 if (props.size() == 1) {
987 auto prop = *props.begin();
988 if (prop->testStatus(App::Property::PropDynamic)
989 && !prop->testStatus(App::Property::LockDynamic)) {
990 menu.addAction(tr("Rename Property"))->setData(QVariant(MA_RenameProp));
991 menu.addAction(tr("Edit Property Tooltip"))->setData(QVariant(MA_EditPropTooltip));
992 }
993 }
994
995 // remove property
996 bool canRemove = !props.empty();
997 unsigned long propType = 0;
998 unsigned long propStatus = 0xffffffff;
999 for (auto prop : props) {
1000 propType |= prop->getType();
1001 propStatus &= prop->getStatus();
1002 if (!prop->testStatus(App::Property::PropDynamic)
1003 || prop->testStatus(App::Property::LockDynamic)) {
1004 canRemove = false;
1005 }
1006 }
1007 if (canRemove) {
1008 menu.addAction(tr("Delete Property"))->setData(QVariant(MA_RemoveProp));
1009 }
1010
1011 // add a separator between adding/removing properties and the rest
1012 menu.addSeparator();
1013
1014 QMenu* expandMenu = setupExpansionSubmenu(&menu);
1015 menu.addMenu(expandMenu);
1016
1017 // show all
1018 QAction* showHidden = menu.addAction(tr("Show Hidden"));
1019 showHidden->setCheckable(true);
1020 showHidden->setChecked(PropertyView::showAll());
1021 showHidden->setData(QVariant(MA_ShowHidden));
1022
1023 menu.addSeparator();
1024
1025 // expression
1026 if (props.size() == 1) {
1027 auto item = static_cast<PropertyItem*>(contextIndex.internalPointer());
1028 auto prop = *props.begin();
1029 if (item->isBound() && !prop->isDerivedFrom<App::PropertyExpressionEngine>()
1030 && !prop->isReadOnly() && !prop->testStatus(App::Property::Immutable)
1031 && !(prop->getType() & App::Prop_ReadOnly)) {
1032 contextIndex = propertyModel->buddy(contextIndex);
1033 setCurrentIndex(contextIndex);
1034 // menu.addSeparator();
1035 menu.addAction(tr("Expression"))->setData(QVariant(MA_Expression));
1036 }
1037 }
1038
1039 // the various flags
1040 if (!props.empty()) {
1041 menu.addSeparator();
1042
1043 // the subMenu is allocated on the heap but managed by menu.
1044 auto subMenu = new QMenu(QStringLiteral("Status"), &menu);
1045
1046 QAction* action;
1047 QString text;
1048 #define _ACTION_SETUP(_name) \
1049 do { \
1050 text = tr(#_name); \
1051 action = subMenu->addAction(text); \
1052 action->setData(QVariant(MA_##_name)); \
1053 action->setCheckable(true); \
1054 if (propStatus & (1 << App::Property::_name)) \
1055 action->setChecked(true); \
1056 } while (0)
1057 #define ACTION_SETUP(_name) \
1058 do { \
1059 _ACTION_SETUP(_name); \
1060 if (propType & App::Prop_##_name) { \
1061 action->setText(text + QStringLiteral(" *")); \
1062 action->setChecked(true); \
1063 } \
1064 } while (0)
1065
1066 ACTION_SETUP(Hidden);
1067 ACTION_SETUP(Output);
1068 ACTION_SETUP(NoRecompute);
1069 ACTION_SETUP(ReadOnly);
1070 ACTION_SETUP(Transient);
1071 _ACTION_SETUP(Touched);
1072 _ACTION_SETUP(EvalOnRestore);
1073 _ACTION_SETUP(CopyOnChange);
1074
1075 menu.addMenu(subMenu);
1076 }
1077
1078 auto action = menu.exec(QCursor::pos());
1079 if (!action) {
1080 return;
1081 }
1082
1083 switch (action->data().toInt()) {
1084 case MA_ExpandToDefault:
1085 expandToDefault();
1086 return;
1087 case MA_CollapseAll:
1088 collapseAll();
1089 return;
1090 case MA_ExpandAll:
1091 expandAll();
1092 return;
1093 case MA_DefaultExpand:
1094 action->setChecked(true);
1095 expansionMode = ExpansionMode::DefaultExpand;
1096 return;
1097 case MA_AutoCollapse:
1098 action->setChecked(true);
1099 expansionMode = ExpansionMode::AutoCollapse;
1100 collapseAll();
1101 return;
1102 case MA_AutoExpand:
1103 action->setChecked(true);
1104 expansionMode = ExpansionMode::AutoExpand;
1105 expandAll();
1106 return;
1107 case MA_ShowHidden:
1108 PropertyView::setShowAll(action->isChecked());
1109 return;
1110 case MA_Copy: {
1111 const QVariant valueToCopy = contextIndex.data(Qt::DisplayRole);
1112 if (valueToCopy.isValid()) {
1113 auto* clipboard = QApplication::clipboard();
1114 clipboard->setText(valueToCopy.toString());
1115 }
1116 return;
1117 }
1118 #define ACTION_CHECK(_name) \
1119 case MA_##_name: \
1120 for (auto prop : props) \
1121 prop->setStatus(App::Property::_name, action->isChecked()); \
1122 break
1123 ACTION_CHECK(Transient);
1124 ACTION_CHECK(ReadOnly);
1125 ACTION_CHECK(Output);
1126 ACTION_CHECK(Hidden);
1127 ACTION_CHECK(EvalOnRestore);
1128 ACTION_CHECK(CopyOnChange);
1129 case MA_Touched:
1130 for (auto prop : props) {
1131 if (action->isChecked()) {
1132 prop->touch();
1133 }
1134 else {
1135 prop->purgeTouched();
1136 }
1137 }
1138 break;
1139 case MA_Expression:
1140 if (contextIndex == currentIndex()) {
1141 Base::FlagToggler<> flag(binding);
1142 closeEditor();
1143 openEditor(contextIndex);
1144 }
1145 break;
1146 case MA_AddProp: {
1147 App::PropertyContainer* container = getSelectedPropertyContainer();
1148 if (container == nullptr) {
1149 return;
1150 }
1151 App::AutoTransaction committer("Add property");
1152 Gui::Dialog::DlgAddProperty dlg(Gui::getMainWindow(), container);
1153 dlg.exec();
1154 return;
1155 }
1156 case MA_EditPropTooltip: {
1157 if (props.size() != 1) {
1158 break;
1159 }
1160
1161 App::Property* prop = *props.begin();
1162 if (!prop->testStatus(App::Property::PropDynamic)
1163 || prop->testStatus(App::Property::LockDynamic)) {
1164 break;
1165 }
1166
1167 bool ok = false;
1168 const QString currentTooltip = QString::fromUtf8(prop->getDocumentation());
1169 QString newTooltip = QInputDialog::getMultiLineText(
1170 Gui::getMainWindow(),
1171 tr("Edit Property Tooltip"),
1172 tr("Tooltip"),
1173 currentTooltip,
1174 &ok
1175 );
1176 if (!ok || newTooltip == currentTooltip) {
1177 break;
1178 }
1179
1180 prop->getContainer()
1181 ->changeDynamicProperty(prop, prop->getGroup(), newTooltip.toUtf8().constData());
1182 break;
1183 }
1184 case MA_RenameProp: {
1185 if (props.size() != 1) {
1186 break;
1187 }
1188
1189 App::Property* prop = *props.begin();
1190 if (!prop->testStatus(App::Property::PropDynamic)
1191 || prop->testStatus(App::Property::LockDynamic)) {
1192 break;
1193 }
1194
1195 App::AutoTransaction committer("Rename property");
1196 const char* oldName = prop->getName();
1197 QString res = QInputDialog::getText(
1198 Gui::getMainWindow(),
1199 tr("Rename property"),
1200 tr("Property name"),
1201 QLineEdit::Normal,
1202 QString::fromUtf8(oldName)
1203 );
1204 if (res.isEmpty()) {
1205 break;
1206 }
1207
1208 std::string newName = res.toUtf8().constData();
1209 try {
1210 prop->getContainer()->renameDynamicProperty(prop, newName.c_str());
1211 }
1212 catch (Base::Exception& e) {
1213 e.reportException();
1214 break;
1215 }
1216 break;
1217 }
1218 case MA_EditPropGroup: {
1219 // This operation is not undoable yet.
1220 const char* groupName = (*props.begin())->getGroup();
1221 if (!groupName) {
1222 groupName = "Base";
1223 }
1224 QString res = QInputDialog::getText(
1225 Gui::getMainWindow(),
1226 tr("Rename property group"),
1227 tr("Group name:"),
1228 QLineEdit::Normal,
1229 QString::fromUtf8(groupName)
1230 );
1231 if (res.size()) {
1232 std::string group = res.toUtf8().constData();
1233 for (auto prop : props) {
1234 prop->getContainer()->changeDynamicProperty(prop, group.c_str(), nullptr);
1235 }
1236 buildUp(PropertyModel::PropertyList(propList), checkDocument);
1237 }
1238 return;
1239 }
1240 case MA_RemoveProp: {
1241 removeProperties(props);
1242 break;
1243 }
1244 default:
1245 break;
1246 }
1247 }
1248
1249
1250 bool PropertyEditor::eventFilter(QObject* object, QEvent* event)
1251 {
1252 if (object == viewport()) {
1253 QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
1254 if (mouse_event) {
1255 if (mouse_event->type() == QEvent::MouseMove) {
1256 if (dragInProgress) { // apply dragging
1257 QHeaderView* header_view = header();
1258 int delta = mouse_event->pos().x() - dragPreviousPos;
1259 dragPreviousPos = mouse_event->pos().x();
1260 // using minimal size = dragSensibility * 2 to prevent collapsing
1261 header_view->resizeSection(
1262 dragSection,
1263 qMax(dragSensibility * 2, header_view->sectionSize(dragSection) + delta)
1264 );
1265 return true;
1266 }
1267 else { // set mouse cursor shape
1268 if (indexResizable(mouse_event->pos()).isValid()) {
1269 viewport()->setCursor(Qt::SplitHCursor);
1270 }
1271 else {
1272 viewport()->setCursor(QCursor());
1273 }
1274 }
1275 }
1276 else if (mouse_event->type() == QEvent::MouseButtonPress
1277 && mouse_event->button() == Qt::LeftButton && !dragInProgress) {
1278 if (indexResizable(mouse_event->pos()).isValid()) {
1279 dragInProgress = true;
1280 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1281 dragPreviousPos = mouse_event->x();
1282 #else
1283 dragPreviousPos = mouse_event->position().toPoint().x();
1284 #endif
1285 dragSection = indexResizable(mouse_event->pos()).column();
1286 return true;
1287 }
1288 }
1289 else if (mouse_event->type() == QEvent::MouseButtonRelease
1290 && mouse_event->button() == Qt::LeftButton && dragInProgress) {
1291 dragInProgress = false;
1292
1293 auto hGrp = App::GetApplication().GetParameterGroupByPath(
1294 "User parameter:BaseApp/Preferences/DockWindows/PropertyView"
1295 );
1296 hGrp->SetInt("FirstColumnSize", header()->sectionSize(0));
1297 return true;
1298 }
1299 }
1300 }
1301 return false;
1302 }
1303
1304 QModelIndex PropertyEditor::indexResizable(QPoint mouse_pos)
1305 {
1306 QModelIndex index = indexAt(mouse_pos - QPoint(dragSensibility + 1, 0));
1307 if (index.isValid()) {
1308 if (qAbs(visualRect(index).right() - mouse_pos.x()) < dragSensibility
1309 && header()->sectionResizeMode(index.column()) == QHeaderView::Interactive) {
1310 return index;
1311 }
1312 }
1313 return QModelIndex();
1314 }
1315
1316 #include "moc_PropertyEditor.cpp"