Debian Codegraph @

src/Gui/Dialogs/DlgPropertyLink.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <algorithm>
24 #include <sstream>
25 #include <QStyledItemDelegate>
26 #include <QTreeWidgetItem>
27
28 #include <App/Document.h>
29 #include <App/DocumentObject.h>
30 #include <App/GeoFeature.h>
31 #include <App/ObjectIdentifier.h>
32 #include <App/PropertyPythonObject.h>
33 #include <Base/Interpreter.h>
34 #include <Base/Tools.h>
35
36 #include "Dialogs/DlgPropertyLink.h"
37 #include "ui_DlgPropertyLink.h"
38 #include "Application.h"
39 #include "Document.h"
40 #include "BitmapFactory.h"
41 #include "PropertyView.h"
42 #include "Selection.h"
43 #include "Tree.h"
44 #include "TreeParams.h"
45 #include "View3DInventor.h"
46 #include "ViewProviderDocumentObject.h"
47
48
49 using namespace Gui::Dialog;
50
51 class ItemDelegate: public QStyledItemDelegate
52 {
53 public:
54 explicit ItemDelegate(QObject* parent = nullptr)
55 : QStyledItemDelegate(parent)
56 {}
57
58 QWidget* createEditor(
59 QWidget* parent,
60 const QStyleOptionViewItem& option,
61 const QModelIndex& index
62 ) const override
63 {
64 if (index.column() != 1) {
65 return nullptr;
66 }
67 return QStyledItemDelegate::createEditor(parent, option, index);
68 }
69 };
70
71 /* TRANSLATOR Gui::Dialog::DlgPropertyLink */
72
73 DlgPropertyLink::DlgPropertyLink(QWidget* parent)
74 : QDialog(parent)
75 , SelectionObserver(false, ResolveMode::NoResolve)
76 , ui(new Ui_DlgPropertyLink)
77 {
78 #if defined(Q_OS_MACOS)
79 // Clicking the 3D view would push this window behind the main window without this.
80 setWindowFlag(Qt::WindowStaysOnTopHint);
81 #endif
82 // clang-format off
83 ui->setupUi(this);
84 connect(ui->checkObjectType, &QCheckBox::toggled,
85 this, &DlgPropertyLink::onObjectTypeToggled);
86 connect(ui->typeTree, &QTreeWidget::itemSelectionChanged,
87 this, &DlgPropertyLink::onTypeTreeItemSelectionChanged);
88 connect(ui->searchBox, &ExpressionLineEdit::textChanged,
89 this, &DlgPropertyLink::onSearchBoxTextChanged);
90
91 ui->typeTree->hide();
92 ui->searchBox->installEventFilter(this);
93 ui->searchBox->setNoProperty(true);
94 ui->searchBox->setExactMatch(Gui::ExpressionParameter::instance()->isExactMatch());
95
96 timer = new QTimer(this);
97 timer->setSingleShot(true);
98
99 connect(timer, &QTimer::timeout, this, &DlgPropertyLink::onTimer);
100
101 ui->treeWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
102 ui->treeWidget->setItemDelegate(new ItemDelegate(this));
103 ui->treeWidget->setMouseTracking(true);
104 connect(ui->treeWidget, &QTreeWidget::itemEntered,
105 this, &DlgPropertyLink::onItemEntered);
106
107 connect(ui->treeWidget, &QTreeWidget::itemExpanded,
108 this, &DlgPropertyLink::onItemExpanded);
109
110 connect(ui->treeWidget, &QTreeWidget::itemSelectionChanged, this, &DlgPropertyLink::onItemSelectionChanged);
111
112 connect(ui->searchBox, &QLineEdit::returnPressed, this, &DlgPropertyLink::onItemSearch);
113
114 connect(ui->buttonBox, &QDialogButtonBox::clicked, this, &DlgPropertyLink::onClicked);
115
116 refreshButton = ui->buttonBox->addButton(tr("Reset"), QDialogButtonBox::ActionRole);
117 resetButton = ui->buttonBox->addButton(tr("Clear"), QDialogButtonBox::ResetRole);
118 // clang-format on
119 }
120
121 /**
122 * Destroys the object and frees any allocated resources
123 */
124 DlgPropertyLink::~DlgPropertyLink()
125 {
126 detachObserver();
127
128 // no need to delete child widgets, Qt does it all for us
129 delete ui;
130 }
131
132 QList<App::SubObjectT> DlgPropertyLink::getLinksFromProperty(const App::PropertyLinkBase* prop)
133 {
134 QList<App::SubObjectT> res;
135 if (!prop) {
136 return res;
137 }
138
139 std::vector<App::DocumentObject*> objs;
140 std::vector<std::string> subs;
141 prop->getLinks(objs, true, &subs, false);
142 if (subs.empty()) {
143 for (auto obj : objs) {
144 res.push_back(App::SubObjectT(obj, nullptr));
145 }
146 }
147 else if (objs.size() == 1) {
148 for (auto& sub : subs) {
149 res.push_back(App::SubObjectT(objs.front(), sub.c_str()));
150 }
151 }
152 else {
153 int i = 0;
154 for (auto obj : objs) {
155 res.push_back(App::SubObjectT(obj, subs[i++].c_str()));
156 }
157 }
158 return res;
159 }
160
161 QString DlgPropertyLink::formatObject(App::Document* ownerDoc, App::DocumentObject* obj, const char* sub)
162 {
163 if (!obj || !obj->isAttachedToDocument()) {
164 return QLatin1String("?");
165 }
166
167 const char* objName = obj->getNameInDocument();
168 std::string _objName;
169 if (ownerDoc && ownerDoc != obj->getDocument()) {
170 _objName = obj->getFullName();
171 objName = _objName.c_str();
172 }
173
174 if (!sub || !sub[0]) {
175 if (obj->Label.getStrValue() == obj->getNameInDocument()) {
176 return QLatin1String(objName);
177 }
178 return QStringLiteral("%1 (%2)").arg(
179 QString::fromUtf8(obj->Label.getValue()),
180 QLatin1String(objName)
181 );
182 }
183
184 auto sobj = obj->getSubObject(sub);
185 if (!sobj || sobj->Label.getStrValue() == sobj->getNameInDocument()) {
186 return QStringLiteral("%1.%2").arg(QLatin1String(objName), QString::fromUtf8(sub));
187 }
188
189 return QStringLiteral("%1 (%2.%3)")
190 .arg(QString::fromUtf8(sobj->Label.getValue()), QLatin1String(objName), QString::fromUtf8(sub));
191 }
192
193 static inline bool isLinkSub(const QList<App::SubObjectT>& links)
194 {
195 for (const auto& link : links) {
196 if (&link == &links.front()) {
197 continue;
198 }
199 if (link.getDocumentName() != links.front().getDocumentName()
200 || link.getObjectName() != links.front().getObjectName()) {
201 return false;
202 }
203 }
204 return true;
205 }
206
207 QString DlgPropertyLink::formatLinks(App::Document* ownerDoc, QList<App::SubObjectT> links)
208 {
209 if (!ownerDoc || links.empty()) {
210 return {};
211 }
212
213 auto obj = links.front().getObject();
214 if (!obj) {
215 return QLatin1String("?");
216 }
217
218 if (links.size() == 1 && links.front().getSubName().empty()) {
219 return formatObject(ownerDoc, links.front());
220 }
221
222 QStringList list;
223 if (isLinkSub(links)) {
224 int i = 0;
225 for (auto& link : links) {
226 list << QString::fromUtf8(link.getSubName().c_str());
227 if (++i >= 3) {
228 break;
229 }
230 }
231 return QStringLiteral("%1 [%2%3]")
232 .arg(
233 formatObject(ownerDoc, obj, nullptr),
234 list.join(QLatin1String(", ")),
235 QLatin1String(links.size() > 3 ? " ..." : "")
236 );
237 }
238
239 int i = 0;
240 for (auto& link : links) {
241 list << formatObject(ownerDoc, link);
242 if (++i >= 3) {
243 break;
244 }
245 }
246 return QStringLiteral("[%1%2]").arg(
247 list.join(QLatin1String(", ")),
248 QLatin1String(links.size() > 3 ? " ..." : "")
249 );
250 }
251
252 void DlgPropertyLink::init(const App::DocumentObjectT& prop, bool tryFilter)
253 {
254 ui->treeWidget->blockSignals(true);
255 ui->treeWidget->clear();
256 ui->treeWidget->blockSignals(false);
257
258 ui->typeTree->blockSignals(true);
259 ui->typeTree->clear();
260 ui->typeTree->blockSignals(false);
261
262 oldLinks.clear();
263 docItems.clear();
264 typeItems.clear();
265 itemMap.clear();
266 inList.clear();
267 selectedTypes.clear();
268 currentObj = nullptr;
269 searchItem = nullptr;
270 subSelections.clear();
271 selections.clear();
272
273 objProp = prop;
274 auto owner = objProp.getObject();
275 if (!owner || !owner->isAttachedToDocument()) {
276 return;
277 }
278
279 ui->searchBox->setDocumentObject(owner);
280
281 auto propLink = freecad_cast<App::PropertyLinkBase*>(objProp.getProperty());
282 if (!propLink) {
283 return;
284 }
285
286 oldLinks = getLinksFromProperty(propLink);
287
288 if (propLink->getScope() != App::LinkScope::Hidden) {
289 // populate inList to filter out any objects that contains the owner object
290 // of the editing link property
291 inList = owner->getInListEx(true);
292 inList.insert(owner);
293 }
294
295 std::vector<App::Document*> docs;
296
297 singleSelect = false;
298 if (propLink->isDerivedFrom<App::PropertyXLinkSub>()
299 || propLink->isDerivedFrom<App::PropertyLinkSub>()) {
300 allowSubObject = true;
301 singleParent = true;
302 }
303 else if (propLink->isDerivedFrom<App::PropertyLink>()) {
304 singleSelect = true;
305 }
306 else if (propLink->isDerivedFrom<App::PropertyLinkSubList>()) {
307 allowSubObject = true;
308 }
309
310 if (App::PropertyXLink::supportXLink(propLink)) {
311 allowSubObject = true;
312 docs = App::GetApplication().getDocuments();
313 }
314 else {
315 docs.push_back(owner->getDocument());
316 }
317
318 bool isLinkList = false;
319 if (propLink->isDerivedFrom<App::PropertyXLinkList>()
320 || propLink->isDerivedFrom<App::PropertyLinkList>()) {
321 isLinkList = true;
322 allowSubObject = false;
323 }
324
325 if (singleSelect) {
326 singleParent = true;
327 ui->treeWidget->setSelectionMode(QAbstractItemView::SingleSelection);
328 }
329 else {
330 ui->treeWidget->setSelectionMode(QAbstractItemView::MultiSelection);
331 }
332
333 ui->checkSubObject->setVisible(allowSubObject);
334
335 if (!allowSubObject) {
336 ui->treeWidget->setColumnCount(1);
337 }
338 else {
339 ui->treeWidget->setColumnCount(2);
340
341 // make sure to show a horizontal scrollbar if needed
342 ui->treeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
343 }
344
345 std::set<App::Document*> expandDocs;
346
347 if (oldLinks.empty()) {
348 expandDocs.insert(owner->getDocument());
349 }
350 else {
351 for (auto& link : oldLinks) {
352 auto doc = link.getDocument();
353 if (doc) {
354 expandDocs.insert(doc);
355 }
356 }
357 }
358
359 QPixmap docIcon(Gui::BitmapFactory().pixmap("Document"));
360 for (auto d : docs) {
361 auto item = new QTreeWidgetItem(ui->treeWidget);
362 item->setIcon(0, docIcon);
363 item->setText(0, QString::fromUtf8(d->Label.getValue()));
364 item->setData(0, Qt::UserRole, QByteArray(""));
365 item->setData(0, Qt::UserRole + 1, QByteArray(d->getName()));
366 item->setFlags(Qt::ItemIsEnabled);
367 item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
368 if (expandDocs.count(d)) {
369 item->setExpanded(true);
370 }
371 docItems[d] = item;
372 }
373
374 if (allowSubObject) {
375 if (propLink->testFlag(App::PropertyLinkBase::LinkSyncSubObject)) {
376 ui->checkSubObject->setChecked(true);
377 }
378 else {
379 for (auto& link : oldLinks) {
380 auto sobj = link.getSubObject();
381 if (sobj && sobj != link.getObject()) {
382 ui->checkSubObject->setChecked(true);
383 break;
384 }
385 }
386 }
387 }
388
389 if (oldLinks.isEmpty()) {
390 return;
391 }
392
393 // Try to select items corresponding to the current links inside the
394 // property
395 {
396 QSignalBlocker blockTree(ui->treeWidget);
397 QSignalBlocker blockSelectionModel(ui->treeWidget->selectionModel());
398 for (auto& link : oldLinks) {
399 onSelectionChanged(
400 Gui::SelectionChanges(
401 SelectionChanges::AddSelection,
402 link.getDocumentName(),
403 link.getObjectName(),
404 link.getSubName()
405 )
406 );
407 }
408 }
409
410 // For link list type property, try to auto filter type
411 if (tryFilter && isLinkList) {
412 Base::Type objType;
413 for (const auto& link : std::as_const(oldLinks)) {
414 auto obj = link.getSubObject();
415 if (!obj) {
416 continue;
417 }
418 if (objType.isBad()) {
419 objType = obj->getTypeId();
420 continue;
421 }
422 for (; objType != App::DocumentObject::getClassTypeId(); objType = objType.getParent()) {
423 if (obj->isDerivedFrom(objType)) {
424 break;
425 }
426 }
427 }
428
429 Base::Type baseType;
430 // get only geometric types
431 if (objType.isDerivedFrom(App::GeoFeature::getClassTypeId())) {
432 baseType = App::GeoFeature::getClassTypeId();
433 }
434 else {
435 baseType = App::DocumentObject::getClassTypeId();
436 }
437
438 // get the direct base class of App::DocumentObject which 'obj' is derived from
439 while (!objType.isBad()) {
440 Base::Type parType = objType.getParent();
441 if (parType == baseType) {
442 baseType = objType;
443 break;
444 }
445 objType = parType;
446 }
447
448 if (!baseType.isBad()) {
449 const char* name = baseType.getName();
450 auto it = typeItems.find(QByteArray::fromRawData(name, strlen(name) + 1));
451 if (it != typeItems.end()) {
452 it->second->setSelected(true);
453 }
454 ui->checkObjectType->setChecked(true);
455 }
456 }
457 }
458
459 void DlgPropertyLink::onClicked(QAbstractButton* button)
460 {
461 if (button == resetButton) {
462 ui->treeWidget->blockSignals(true);
463 ui->treeWidget->selectionModel()->clearSelection();
464 for (auto item : subSelections) {
465 item->setText(1, QString());
466 }
467 ui->treeWidget->blockSignals(false);
468 subSelections.clear();
469 Gui::Selection().clearSelection();
470 }
471 else if (button == refreshButton) {
472 init(objProp);
473 }
474 }
475
476 void DlgPropertyLink::hideEvent(QHideEvent* ev)
477 {
478 detachObserver();
479 QDialog::hideEvent(ev);
480 }
481
482 void DlgPropertyLink::closeEvent(QCloseEvent* ev)
483 {
484 detachObserver();
485 QDialog::closeEvent(ev);
486 }
487
488 void DlgPropertyLink::attachObserver()
489 {
490 if (isSelectionAttached()) {
491 return;
492 }
493
494 Gui::Selection().selStackPush();
495 attachSelection();
496
497 if (!parentView) {
498 for (auto p = parent(); p; p = p->parent()) {
499 auto view = qobject_cast<Gui::PropertyView*>(p);
500 if (view) {
501 parentView = view;
502 for (auto& sel : Gui::Selection().getCompleteSelection(ResolveMode::NoResolve)) {
503 savedSelections.emplace_back(sel.DocName, sel.FeatName, sel.SubName);
504 }
505 break;
506 }
507 }
508 }
509 auto view = qobject_cast<Gui::PropertyView*>(parentView.data());
510 if (view) {
511 view->blockSelection(true);
512 }
513 }
514
515 void DlgPropertyLink::showEvent(QShowEvent* ev)
516 {
517 attachObserver();
518 QDialog::showEvent(ev);
519 }
520
521 void DlgPropertyLink::onItemEntered(QTreeWidgetItem*)
522 {
523 int timeout = Gui::TreeParams::getPreSelectionDelay() / 2;
524 if (timeout < 0) {
525 timeout = 1;
526 }
527 timer->start(timeout);
528 Gui::Selection().rmvPreselect();
529 }
530
531 void DlgPropertyLink::leaveEvent(QEvent* ev)
532 {
533 Gui::Selection().rmvPreselect();
534 QDialog::leaveEvent(ev);
535 }
536
537 void DlgPropertyLink::detachObserver()
538 {
539 if (isSelectionAttached()) {
540 detachSelection();
541 }
542
543 auto view = qobject_cast<Gui::PropertyView*>(parentView.data());
544 if (view && !savedSelections.empty()) {
545 try {
546 Gui::Selection().clearSelection();
547 }
548 catch (Py::Exception& e) {
549 e.clear();
550 }
551 for (auto& sel : savedSelections) {
552 if (sel.getSubObject()) {
553 Gui::Selection().addSelection(
554 sel.getDocumentName().c_str(),
555 sel.getObjectName().c_str(),
556 sel.getSubName().c_str()
557 );
558 }
559 }
560 savedSelections.clear();
561 }
562 if (view) {
563 view->blockSelection(false);
564 }
565
566 parentView = nullptr;
567 }
568
569 void DlgPropertyLink::onItemSelectionChanged()
570 {
571 auto newSelections = ui->treeWidget->selectedItems();
572
573 if (newSelections.isEmpty() || selections.contains(newSelections.back())) {
574 selections = newSelections;
575 if (newSelections.isEmpty()) {
576 currentObj = nullptr;
577 }
578 return;
579 }
580
581 selections = newSelections;
582
583 auto sobjs = getLinkFromItem(newSelections.back());
584 App::DocumentObject* obj = !sobjs.empty() ? sobjs.front().getObject() : nullptr;
585 if (!obj) {
586 Gui::Selection().clearSelection();
587 return;
588 }
589
590 bool focus = false;
591 // Do auto view switch if tree view does not do it
592 if (!TreeParams::getSyncView()) {
593 focus = ui->treeWidget->hasFocus();
594 auto doc = Gui::Application::Instance->getDocument(sobjs.front().getDocumentName().c_str());
595 if (doc) {
596 auto vp = freecad_cast<Gui::ViewProviderDocumentObject*>(doc->getViewProvider(obj));
597 if (vp) {
598 // If the view provider uses a special window for rendering, switch to it
599 MDIView* view = vp->getMDIView();
600 if (view) {
601 doc->setActiveWindow(view);
602 }
603 else {
604 doc->setActiveView(vp, Gui::View3DInventor::getClassTypeId());
605 }
606 }
607 }
608 }
609
610 // Sync 3d view selection. To give a better visual feedback, we
611 // only keep the latest selection.
612 bool blocked = blockSelection(true);
613 Gui::Selection().clearSelection();
614 for (auto& sobj : sobjs) {
615 Gui::Selection().addSelection(
616 sobj.getDocumentName().c_str(),
617 sobj.getObjectName().c_str(),
618 sobj.getSubName().c_str()
619 );
620 }
621 blockSelection(blocked);
622
623 // Enforce single parent
624 if (singleParent && currentObj && currentObj != obj) {
625 ui->treeWidget->blockSignals(true);
626 const auto items = ui->treeWidget->selectedItems();
627 for (auto item : items) {
628 if (item != selections.back()) {
629 item->setSelected(false);
630 }
631 }
632 auto last = selections.back();
633 selections.clear();
634 selections.append(last);
635 ui->treeWidget->blockSignals(false);
636 }
637 currentObj = obj;
638
639 if (focus) {
640 // FIXME: does not work, why?
641 ui->treeWidget->setFocus();
642 }
643 }
644
645 QTreeWidgetItem* DlgPropertyLink::findItem(App::DocumentObject* obj, const char* subname, bool* pfound)
646 {
647 if (pfound) {
648 *pfound = false;
649 }
650
651 if (!obj || !obj->isAttachedToDocument()) {
652 return nullptr;
653 }
654
655 std::vector<App::DocumentObject*> sobjs;
656 if (!Base::Tools::isNullOrEmpty(subname)) {
657 if (!allowSubObject) {
658 obj = obj->getSubObject(subname);
659 if (!obj) {
660 return nullptr;
661 }
662 }
663 else {
664 sobjs = obj->getSubObjectList(subname);
665 }
666 }
667
668 auto itDoc = docItems.find(obj->getDocument());
669 if (itDoc == docItems.end()) {
670 return nullptr;
671 }
672 onItemExpanded(itDoc->second);
673
674 auto it = itemMap.find(obj);
675 if (it == itemMap.end() || it->second->isHidden()) {
676 return nullptr;
677 }
678
679 if (!allowSubObject) {
680 if (pfound) {
681 *pfound = true;
682 }
683 return it->second;
684 }
685
686 QTreeWidgetItem* item = it->second;
687
688 bool first = true;
689 for (auto o : sobjs) {
690 if (first) {
691 first = false;
692 continue;
693 }
694 onItemExpanded(item);
695 bool found = false;
696 for (int i = 0, count = item->childCount(); i < count; ++i) {
697 auto child = item->child(i);
698 if (strcmp(o->getNameInDocument(), child->data(0, Qt::UserRole).toByteArray().constData())
699 == 0) {
700 item = child;
701 found = true;
702 break;
703 }
704 }
705 if (!found) {
706 return item;
707 }
708 }
709 if (pfound) {
710 *pfound = true;
711 }
712 return item;
713 }
714
715 void DlgPropertyLink::onSelectionChanged(const Gui::SelectionChanges& msg)
716 {
717 if (msg.Type != SelectionChanges::AddSelection) {
718 return;
719 }
720
721 bool found = false;
722 auto selObj = msg.Object.getObject();
723
724 App::ElementNamePair elementName;
725 const char* subname = msg.pSubName;
726 if (!ui->checkSubObject->isChecked()) {
727 selObj = App::GeoFeature::resolveElement(selObj, subname, elementName);
728 if (!selObj) {
729 return;
730 }
731 subname = elementName.oldName.c_str();
732 }
733
734 auto item = findItem(selObj, msg.pSubName, &found);
735 if (!item) {
736 return;
737 }
738
739 if (!item->isSelected()) {
740 ui->treeWidget->blockSignals(true);
741 if (singleSelect || (singleParent && currentObj && currentObj != selObj)) {
742 ui->treeWidget->selectionModel()->clearSelection();
743 }
744 currentObj = selObj;
745 item->setSelected(true);
746 selections.append(item);
747 ui->treeWidget->blockSignals(false);
748 }
749
750 ui->treeWidget->scrollToItem(item);
751 if (allowSubObject) {
752 QString element = QString::fromUtf8(msg.Object.getOldElementName().c_str());
753 if (element.size()) {
754 QStringList list;
755 QString text = item->text(1);
756 if (text.size()) {
757 list = text.split(QLatin1Char(','));
758 }
759 if (list.indexOf(element) < 0) {
760 list << element;
761 item->setText(1, list.join(QLatin1String(",")));
762 subSelections.insert(item);
763 }
764 }
765 else if (subSelections.erase(item)) {
766 item->setText(1, QString());
767 }
768 }
769 }
770
771 void DlgPropertyLink::accept()
772 {
773 QDialog::accept();
774 }
775
776 static QTreeWidgetItem* _getLinkFromItem(std::ostringstream& ss, QTreeWidgetItem* item, const char* objName)
777 {
778 auto parent = item->parent();
779 assert(parent);
780 QByteArray nextName = parent->data(0, Qt::UserRole).toByteArray();
781 if (nextName.isEmpty()) {
782 return item;
783 }
784
785 item = _getLinkFromItem(ss, parent, nextName);
786 ss << objName << '.';
787 return item;
788 }
789
790 QList<App::SubObjectT> DlgPropertyLink::getLinkFromItem(QTreeWidgetItem* item, bool needSubName) const
791 {
792 QList<App::SubObjectT> res;
793
794 auto parent = item->parent();
795 if (!parent) {
796 return res;
797 }
798
799 std::ostringstream ss;
800 auto parentItem = _getLinkFromItem(ss, item, item->data(0, Qt::UserRole).toByteArray().constData());
801
802 App::SubObjectT sobj(
803 parentItem->data(0, Qt::UserRole + 1).toByteArray().constData(),
804 parentItem->data(0, Qt::UserRole).toByteArray().constData(),
805 ss.str().c_str()
806 );
807
808 QString elements;
809 if (needSubName && allowSubObject) {
810 elements = item->text(1);
811 }
812
813 if (elements.isEmpty()) {
814 res.append(App::SubObjectT());
815 res.last() = std::move(sobj);
816 return res;
817 }
818
819 const auto split = elements.split(QLatin1Char(','));
820 for (const QString& element : split) {
821 res.append(App::SubObjectT());
822 res.last() = App::SubObjectT(
823 sobj.getDocumentName().c_str(),
824 sobj.getObjectName().c_str(),
825 (sobj.getSubName() + element.toLatin1().constData()).c_str()
826 );
827 }
828 return res;
829 }
830
831 void DlgPropertyLink::onTimer()
832 {
833 auto item = ui->treeWidget->itemAt(ui->treeWidget->viewport()->mapFromGlobal(QCursor::pos()));
834 if (!item) {
835 return;
836 }
837 auto sobjs = getLinkFromItem(item);
838 if (sobjs.isEmpty()) {
839 return;
840 }
841 const auto& sobj = sobjs.front();
842 Gui::Selection().setPreselect(
843 sobj.getDocumentName().c_str(),
844 sobj.getObjectName().c_str(),
845 sobj.getSubName().c_str(),
846 0,
847 0,
848 0,
849 Gui::SelectionChanges::MsgSource::TreeView
850 );
851 }
852
853 QList<App::SubObjectT> DlgPropertyLink::currentLinks() const
854 {
855 auto items = ui->treeWidget->selectedItems();
856 QList<App::SubObjectT> res;
857 for (auto item : items) {
858 res.append(getLinkFromItem(item));
859 }
860 return res;
861 }
862
863 QList<App::SubObjectT> DlgPropertyLink::originalLinks() const
864 {
865 return oldLinks;
866 }
867
868 QString DlgPropertyLink::linksToPython(const QList<App::SubObjectT>& links)
869 {
870 if (links.isEmpty()) {
871 return QLatin1String("None");
872 }
873
874 if (links.size() == 1) {
875 return QString::fromUtf8(links.front().getSubObjectPython(false).c_str());
876 }
877
878 std::ostringstream ss;
879
880 if (isLinkSub(links)) {
881 ss << '(' << links.front().getObjectPython() << ", [";
882 for (const auto& link : links) {
883 const auto& sub = link.getSubName();
884 if (!sub.empty()) {
885 ss << "u'" << Base::Tools::escapedUnicodeFromUtf8(sub.c_str()) << "',";
886 }
887 }
888 ss << "])";
889 }
890 else {
891 ss << '[';
892 for (const auto& link : links) {
893 ss << link.getSubObjectPython(false) << ',';
894 }
895 ss << ']';
896 }
897
898 return QString::fromUtf8(ss.str().c_str());
899 }
900
901 void DlgPropertyLink::filterObjects()
902 {
903 for (int i = 0, count = ui->treeWidget->topLevelItemCount(); i < count; ++i) {
904 auto item = ui->treeWidget->topLevelItem(i);
905 for (int j = 0, c = item->childCount(); j < c; ++j) {
906 filterItem(item->child(j));
907 }
908 }
909 }
910
911 void DlgPropertyLink::filterItem(QTreeWidgetItem* item)
912 {
913 if (filterType(item)) {
914 item->setHidden(true);
915 return;
916 }
917 item->setHidden(false);
918 for (int i = 0, count = item->childCount(); i < count; ++i) {
919 filterItem(item->child(i));
920 }
921 }
922
923 bool DlgPropertyLink::eventFilter(QObject* obj, QEvent* e)
924 {
925 if (obj == ui->searchBox && e->type() == QEvent::KeyPress
926 && static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
927 ui->searchBox->setText(QString());
928 return true;
929 }
930 return QDialog::eventFilter(obj, e);
931 }
932
933 void DlgPropertyLink::onItemSearch()
934 {
935 itemSearch(ui->searchBox->text(), true);
936 }
937
938 void DlgPropertyLink::keyPressEvent(QKeyEvent* ev)
939 {
940 if (ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return) {
941 if (ui->searchBox->hasFocus()) {
942 return;
943 }
944 }
945 QDialog::keyPressEvent(ev);
946 }
947
948 void DlgPropertyLink::itemSearch(const QString& text, bool select)
949 {
950 if (searchItem) {
951 searchItem->setBackground(0, bgBrush);
952 }
953
954 auto owner = objProp.getObject();
955 if (!owner) {
956 return;
957 }
958
959 std::string txt(text.toUtf8().constData());
960 try {
961 if (txt.empty()) {
962 return;
963 }
964 if (txt.find("<<") == std::string::npos) {
965 auto pos = txt.find('.');
966 if (pos == std::string::npos) {
967 txt += '.';
968 }
969 else if (pos != txt.size() - 1) {
970 txt.insert(pos + 1, "<<");
971 if (txt.back() != '.') {
972 txt += '.';
973 }
974 txt += ">>.";
975 }
976 }
977 else if (txt.back() != '.') {
978 txt += '.';
979 }
980 txt += "_self";
981 auto path = App::ObjectIdentifier::parse(owner, txt);
982 if (path.getPropertyName() != "_self") {
983 return;
984 }
985
986 App::DocumentObject* obj = path.getDocumentObject();
987 if (!obj) {
988 return;
989 }
990
991 bool found;
992 const char* subname = path.getSubObjectName().c_str();
993 QTreeWidgetItem* item = findItem(obj, subname, &found);
994 if (!item) {
995 return;
996 }
997
998 if (select) {
999 if (!found) {
1000 return;
1001 }
1002 Gui::Selection()
1003 .addSelection(obj->getDocument()->getName(), obj->getNameInDocument(), subname);
1004 }
1005 else {
1006 Selection().setPreselect(
1007 obj->getDocument()->getName(),
1008 obj->getNameInDocument(),
1009 subname,
1010 0,
1011 0,
1012 0,
1013 Gui::SelectionChanges::MsgSource::TreeView
1014 );
1015 searchItem = item;
1016 ui->treeWidget->scrollToItem(searchItem);
1017 bgBrush = searchItem->background(0);
1018 searchItem->setBackground(0, QColor(255, 255, 0, 100));
1019 }
1020 }
1021 catch (...) {
1022 }
1023 }
1024
1025 QTreeWidgetItem* DlgPropertyLink::createItem(App::DocumentObject* obj, QTreeWidgetItem* parent)
1026 {
1027 if (!obj || !obj->isAttachedToDocument()) {
1028 return nullptr;
1029 }
1030
1031 if (inList.find(obj) != inList.end()) {
1032 return nullptr;
1033 }
1034
1035 auto vp = freecad_cast<ViewProviderDocumentObject*>(Application::Instance->getViewProvider(obj));
1036 if (!vp) {
1037 return nullptr;
1038 }
1039
1040 QTreeWidgetItem* item;
1041 if (parent) {
1042 item = new QTreeWidgetItem(parent);
1043 }
1044 else {
1045 item = new QTreeWidgetItem(ui->treeWidget);
1046 }
1047 item->setIcon(0, vp->getIcon());
1048 item->setText(0, QString::fromUtf8((obj)->Label.getValue()));
1049 item->setData(0, Qt::UserRole, QByteArray(obj->getNameInDocument()));
1050 item->setData(0, Qt::UserRole + 1, QByteArray(obj->getDocument()->getName()));
1051
1052 if (allowSubObject) {
1053 item->setChildIndicatorPolicy(
1054 !obj->getLinkedObject(true)->getOutList().empty() ? QTreeWidgetItem::ShowIndicator
1055 : QTreeWidgetItem::DontShowIndicator
1056 );
1057 item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable);
1058 }
1059
1060 const char* typeName = obj->getTypeId().getName();
1061 QByteArray typeData = QByteArray::fromRawData(typeName, strlen(typeName) + 1);
1062 item->setData(0, Qt::UserRole + 2, typeData);
1063
1064 QByteArray proxyType;
1065 auto prop = freecad_cast<App::PropertyPythonObject*>(obj->getPropertyByName("Proxy"));
1066 if (prop) {
1067 Base::PyGILStateLocker lock;
1068 Py::Object proxy = prop->getValue();
1069 if (!proxy.isNone() && !proxy.isString()) {
1070 const char* name = nullptr;
1071 if (proxy.hasAttr("__class__")) {
1072 proxyType = QByteArray(proxy.getAttr("__class__").as_string().c_str());
1073 }
1074 else {
1075 name = proxy.ptr()->ob_type->tp_name;
1076 proxyType = QByteArray::fromRawData(name, strlen(name) + 1);
1077 }
1078 auto it = typeItems.find(proxyType);
1079 if (it != typeItems.end()) {
1080 proxyType = it->first;
1081 }
1082 else if (name) {
1083 proxyType = QByteArray(name, proxyType.size());
1084 }
1085 }
1086 }
1087 item->setData(0, Qt::UserRole + 3, proxyType);
1088
1089 filterItem(item);
1090 return item;
1091 }
1092
1093 QTreeWidgetItem* DlgPropertyLink::createTypeItem(Base::Type type)
1094 {
1095 if (type.isBad()) {
1096 return nullptr;
1097 }
1098
1099 QTreeWidgetItem* item = nullptr;
1100 if (!type.isBad() && type != App::DocumentObject::getClassTypeId()) {
1101 Base::Type parentType = type.getParent();
1102 if (!parentType.isBad()) {
1103 const char* name = parentType.getName();
1104 auto typeData = QByteArray::fromRawData(name, strlen(name) + 1);
1105 auto& typeItem = typeItems[typeData];
1106 if (!typeItem) {
1107 typeItem = createTypeItem(parentType);
1108 typeItem->setData(0, Qt::UserRole, typeData);
1109 }
1110 item = typeItem;
1111 }
1112 }
1113
1114 if (!item) {
1115 item = new QTreeWidgetItem(ui->typeTree);
1116 }
1117 else {
1118 item = new QTreeWidgetItem(item);
1119 }
1120 item->setExpanded(true);
1121 item->setText(0, QString::fromUtf8(type.getName()));
1122 if (type == App::DocumentObject::getClassTypeId()) {
1123 item->setFlags(Qt::ItemIsEnabled);
1124 }
1125 return item;
1126 }
1127
1128 bool DlgPropertyLink::filterType(QTreeWidgetItem* item)
1129 {
1130 auto proxyType = item->data(0, Qt::UserRole + 3).toByteArray();
1131 QTreeWidgetItem* proxyItem = nullptr;
1132 if (proxyType.size()) {
1133 auto& pitem = typeItems[proxyType];
1134 if (!pitem) {
1135 pitem = new QTreeWidgetItem(ui->typeTree);
1136 pitem->setText(0, QString::fromUtf8(proxyType));
1137 pitem->setIcon(0, item->icon(0));
1138 pitem->setData(0, Qt::UserRole, proxyType);
1139 }
1140 proxyItem = pitem;
1141 }
1142
1143 auto typeData = item->data(0, Qt::UserRole + 2).toByteArray();
1144 Base::Type type = Base::Type::fromName(typeData.constData());
1145 if (type.isBad()) {
1146 return false;
1147 }
1148
1149 QTreeWidgetItem*& typeItem = typeItems[typeData];
1150 if (!typeItem) {
1151 typeItem = createTypeItem(type);
1152 typeItem->setData(0, Qt::UserRole, typeData);
1153 }
1154
1155 if (!proxyType.size()) {
1156 QIcon icon = typeItem->icon(0);
1157 if (icon.isNull()) {
1158 typeItem->setIcon(0, item->icon(0));
1159 }
1160 }
1161
1162 if (!ui->checkObjectType->isChecked() || selectedTypes.empty()) {
1163 return false;
1164 }
1165
1166 if (proxyItem && selectedTypes.count(proxyType)) {
1167 return false;
1168 }
1169
1170 for (auto t = type; !t.isBad() && t != App::DocumentObject::getClassTypeId(); t = t.getParent()) {
1171 const char* name = t.getName();
1172 if (selectedTypes.count(QByteArray::fromRawData(name, strlen(name) + 1))) {
1173 return false;
1174 }
1175 }
1176
1177 return true;
1178 }
1179
1180 void DlgPropertyLink::onItemExpanded(QTreeWidgetItem* item)
1181 {
1182 if (item->childCount()) {
1183 return;
1184 }
1185
1186 QByteArray docName = item->data(0, Qt::UserRole + 1).toByteArray();
1187 auto doc = App::GetApplication().getDocument(docName);
1188 if (!doc) {
1189 return;
1190 }
1191
1192 QByteArray objName = item->data(0, Qt::UserRole).toByteArray();
1193 if (objName.isEmpty()) {
1194 for (auto obj : doc->getObjects()) {
1195 auto newItem = createItem(obj, item);
1196 if (newItem) {
1197 itemMap[obj] = newItem;
1198 }
1199 }
1200 }
1201 else if (allowSubObject) {
1202 auto obj = doc->getObject(objName);
1203 if (!obj) {
1204 return;
1205 }
1206 std::set<App::DocumentObject*> childSet;
1207 std::string sub;
1208 for (auto child : obj->getLinkedObject(true)->getOutList()) {
1209 if (!childSet.insert(child).second) {
1210 continue;
1211 }
1212 sub = child->getNameInDocument();
1213 sub += ".";
1214 if (obj->getSubObject(sub.c_str())) {
1215 createItem(child, item);
1216 }
1217 }
1218 }
1219 }
1220
1221 void DlgPropertyLink::onObjectTypeToggled(bool on)
1222 {
1223 ui->typeTree->setVisible(on);
1224 filterObjects();
1225 }
1226
1227 void DlgPropertyLink::onTypeTreeItemSelectionChanged()
1228 {
1229
1230 selectedTypes.clear();
1231 const auto items = ui->typeTree->selectedItems();
1232 for (auto item : items) {
1233 selectedTypes.insert(item->data(0, Qt::UserRole).toByteArray());
1234 }
1235
1236 if (ui->checkObjectType->isChecked()) {
1237 filterObjects();
1238 }
1239 }
1240
1241 void DlgPropertyLink::onSearchBoxTextChanged(const QString& text)
1242 {
1243 itemSearch(text, false);
1244 }
1245
1246 #include "moc_DlgPropertyLink.cpp"