Debian Codegraph @

src/Gui/Selection/SelectionView.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /***************************************************************************
3 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
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 <QCheckBox>
25 #include <QLabel>
26 #include <QLineEdit>
27 #include <QListWidget>
28 #include <QListWidgetItem>
29 #include <QMenu>
30 #include <QTextStream>
31 #include <QToolButton>
32 #include <QVBoxLayout>
33 #include <set>
34
35 #include <App/ComplexGeoData.h>
36 #include <App/Document.h>
37 #include <App/ElementNamingUtils.h>
38 #include <App/GeoFeature.h>
39 #include <App/IndexedName.h>
40 #include <Base/Console.h>
41
42 #include "SelectionView.h"
43 #include "Application.h"
44 #include "BitmapFactory.h"
45 #include "Command.h"
46 #include "Document.h"
47 #include "ViewProvider.h"
48
49
50 FC_LOG_LEVEL_INIT("Selection", true, true, true)
51
52 using namespace Gui;
53 using namespace Gui::DockWnd;
54
55
56 /* TRANSLATOR Gui::DockWnd::SelectionView */
57
58 SelectionView::SelectionView(Gui::Document* pcDocument, QWidget* parent)
59 : DockWindow(pcDocument, parent)
60 , SelectionObserver(true, ResolveMode::NoResolve)
61 , x(0.0f)
62 , y(0.0f)
63 , z(0.0f)
64 , openedAutomatically(false)
65 {
66 setWindowTitle(tr("Selection View"));
67
68 QVBoxLayout* vLayout = new QVBoxLayout(this);
69 vLayout->setSpacing(0);
70 vLayout->setContentsMargins(0, 0, 0, 0);
71
72 QLineEdit* searchBox = new QLineEdit(this);
73 searchBox->setPlaceholderText(tr("Search"));
74 searchBox->setToolTip(tr("Searches object labels"));
75 QHBoxLayout* hLayout = new QHBoxLayout();
76 hLayout->setSpacing(2);
77 QToolButton* clearButton = new QToolButton(this);
78 clearButton->setFixedSize(18, 21);
79 clearButton->setCursor(Qt::ArrowCursor);
80 clearButton->setStyleSheet(QStringLiteral("QToolButton {margin-bottom:1px}"));
81 clearButton->setIcon(BitmapFactory().pixmap(":/icons/edit-cleartext.svg"));
82 clearButton->setToolTip(tr("Clears the search field"));
83 clearButton->setAutoRaise(true);
84 countLabel = new QLabel(this);
85 countLabel->setText(QStringLiteral("0"));
86 countLabel->setToolTip(tr("The number of selected items"));
87 hLayout->addWidget(searchBox);
88 hLayout->addWidget(clearButton, 0, Qt::AlignRight);
89 hLayout->addWidget(countLabel, 0, Qt::AlignRight);
90 vLayout->addLayout(hLayout);
91
92 selectionView = new QListWidget(this);
93 selectionView->setContextMenuPolicy(Qt::CustomContextMenu);
94 vLayout->addWidget(selectionView);
95
96 enablePickList = new QCheckBox(this);
97 enablePickList->setText(tr("Picked object list"));
98 vLayout->addWidget(enablePickList);
99 pickList = new QListWidget(this);
100 pickList->setVisible(false);
101 vLayout->addWidget(pickList);
102
103 selectionView->setMouseTracking(true); // needed for itemEntered() to work
104 pickList->setMouseTracking(true);
105
106 resize(200, 200);
107
108 // clang-format off
109 connect(clearButton, &QToolButton::clicked, searchBox, &QLineEdit::clear);
110 connect(searchBox, &QLineEdit::textChanged, this, &SelectionView::search);
111 connect(searchBox, &QLineEdit::editingFinished, this, &SelectionView::validateSearch);
112 connect(selectionView, &QListWidget::itemDoubleClicked, this, &SelectionView::toggleSelect);
113 connect(selectionView, &QListWidget::itemEntered, this, &SelectionView::preselect);
114 connect(pickList, &QListWidget::itemDoubleClicked, this, &SelectionView::toggleSelect);
115 connect(pickList, &QListWidget::itemEntered, this, &SelectionView::preselect);
116 connect(selectionView, &QListWidget::customContextMenuRequested, this, &SelectionView::onItemContextMenu);
117 #if QT_VERSION >= QT_VERSION_CHECK(6,7,0)
118 connect(enablePickList, &QCheckBox::checkStateChanged, this, &SelectionView::onEnablePickList);
119 #else
120 connect(enablePickList, &QCheckBox::stateChanged, this, &SelectionView::onEnablePickList);
121 #endif
122 // clang-format on
123 }
124
125 SelectionView::~SelectionView() = default;
126
127 void SelectionView::leaveEvent(QEvent*)
128 {
129 Selection().rmvPreselect();
130 }
131
132 /// @cond DOXERR
133 void SelectionView::onSelectionChanged(const SelectionChanges& Reason)
134 {
135 ParameterGrp::handle hGrp = App::GetApplication()
136 .GetUserParameter()
137 .GetGroup("BaseApp")
138 ->GetGroup("Preferences")
139 ->GetGroup("Selection");
140 bool autoShow = hGrp->GetBool("AutoShowSelectionView", false);
141 hGrp->SetBool(
142 "AutoShowSelectionView",
143 autoShow
144 ); // Remove this line once the preferences window item is implemented
145
146 if (autoShow) {
147 if (!parentWidget()->isVisible() && Selection().hasSelection()) {
148 parentWidget()->show();
149 openedAutomatically = true;
150 }
151 else if (openedAutomatically && !Selection().hasSelection()) {
152 parentWidget()->hide();
153 openedAutomatically = false;
154 }
155 }
156
157 QString selObject;
158 QTextStream str(&selObject);
159
160 auto getSelectionName = [](QTextStream& str,
161 const char* docName,
162 const char* objName,
163 const char* subName,
164 App::DocumentObject* obj) {
165 str << QString::fromUtf8(docName);
166 str << "#";
167 str << QString::fromUtf8(objName);
168 if (subName != 0 && subName[0] != 0) {
169 str << ".";
170 /* Original code doesn't take account of histories in subelement names and displays
171 * them inadvertently. Let's not do that.
172 str << subName;
173 */
174 /* Remove the history from the displayed subelement name */
175 App::ElementNamePair elementName;
176 App::GeoFeature::resolveElement(obj, subName, elementName);
177 str << elementName.oldName.c_str(); // Use the shortened element name not the full one.
178 /* Mark it visually if there was a history as a "tell" for if a given selection has TNP
179 * fixes in it. */
180 if (elementName.newName.size() > 0) {
181 str << " []";
182 }
183 auto subObj = obj->getSubObject(subName);
184 if (subObj) {
185 obj = subObj;
186 }
187 }
188 str << " (";
189 str << QString::fromUtf8(obj->Label.getValue());
190 str << ")";
191 };
192
193 if (Reason.Type == SelectionChanges::AddSelection) {
194 // save as user data
195 QStringList list;
196 list << QString::fromUtf8(Reason.pDocName);
197 list << QString::fromUtf8(Reason.pObjectName);
198 App::Document* doc = App::GetApplication().getDocument(Reason.pDocName);
199 App::DocumentObject* obj = doc->getObject(Reason.pObjectName);
200 getSelectionName(str, Reason.pDocName, Reason.pObjectName, Reason.pSubName, obj);
201
202 // insert the selection as item
203 QListWidgetItem* item = new QListWidgetItem(selObject, selectionView);
204 item->setData(Qt::UserRole, list);
205 }
206 else if (Reason.Type == SelectionChanges::ClrSelection) {
207 if (!Reason.pDocName[0]) {
208 // remove all items
209 selectionView->clear();
210 }
211 else {
212 // build name
213 str << Reason.pDocName;
214 str << "#";
215 // remove all items
216 const auto items = selectionView->findItems(selObject, Qt::MatchStartsWith);
217 for (auto item : items) {
218 delete item;
219 }
220 }
221 }
222 else if (Reason.Type == SelectionChanges::RmvSelection) {
223 App::Document* doc = App::GetApplication().getDocument(Reason.pDocName);
224 App::DocumentObject* obj = doc->getObject(Reason.pObjectName);
225 getSelectionName(str, Reason.pDocName, Reason.pObjectName, Reason.pSubName, obj);
226 // remove all items
227 QList<QListWidgetItem*> l = selectionView->findItems(selObject, Qt::MatchStartsWith);
228 if (l.size() == 1) {
229 delete l[0];
230 }
231 }
232 else if (Reason.Type == SelectionChanges::SetSelection) {
233 // remove all items
234 selectionView->clear();
235 std::vector<SelectionSingleton::SelObj> objs
236 = Gui::Selection().getSelection(Reason.pDocName, ResolveMode::NoResolve);
237 for (const auto& it : objs) {
238 // save as user data
239 QStringList list;
240 list << QString::fromUtf8(it.DocName);
241 list << QString::fromUtf8(it.FeatName);
242
243 App::Document* doc = App::GetApplication().getDocument(it.DocName);
244 App::DocumentObject* obj = doc->getObject(it.FeatName);
245 getSelectionName(str, it.DocName, it.FeatName, it.SubName, obj);
246 QListWidgetItem* item = new QListWidgetItem(selObject, selectionView);
247 item->setData(Qt::UserRole, list);
248 selObject.clear();
249 }
250 }
251 else if (Reason.Type == SelectionChanges::PickedListChanged) {
252 bool picking = Selection().needPickedList();
253 enablePickList->setChecked(picking);
254 pickList->setVisible(picking);
255 pickList->clear();
256 if (picking) {
257 const auto& sels = Selection().getPickedList(Reason.pDocName);
258 for (const auto& sel : sels) {
259 App::Document* doc = App::GetApplication().getDocument(sel.DocName);
260 if (!doc) {
261 continue;
262 }
263 App::DocumentObject* obj = doc->getObject(sel.FeatName);
264 if (!obj) {
265 continue;
266 }
267
268 QString selObject;
269 QTextStream str(&selObject);
270 getSelectionName(str, sel.DocName, sel.FeatName, sel.SubName, obj);
271
272 this->x = sel.x;
273 this->y = sel.y;
274 this->z = sel.z;
275
276 new QListWidgetItem(selObject, pickList);
277 }
278 }
279 }
280
281 countLabel->setText(QString::number(selectionView->count()));
282 }
283
284 void SelectionView::search(const QString& text)
285 {
286 if (!text.isEmpty()) {
287 searchList.clear();
288 App::Document* doc = App::GetApplication().getActiveDocument();
289 std::vector<App::DocumentObject*> objects;
290 if (doc) {
291 objects = doc->getObjects();
292 selectionView->clear();
293 for (auto it : objects) {
294 QString label = QString::fromUtf8(it->Label.getValue());
295 if (label.contains(text, Qt::CaseInsensitive)) {
296 searchList.push_back(it);
297 // save as user data
298 QString selObject;
299 QTextStream str(&selObject);
300 QStringList list;
301 list << QString::fromUtf8(doc->getName());
302 list << QString::fromUtf8(it->getNameInDocument());
303 // build name
304 str << QString::fromUtf8(doc->Label.getValue());
305 str << "#";
306 str << it->getNameInDocument();
307 str << " (";
308 str << label;
309 str << ")";
310 QListWidgetItem* item = new QListWidgetItem(selObject, selectionView);
311 item->setData(Qt::UserRole, list);
312 }
313 }
314 countLabel->setText(QString::number(selectionView->count()));
315 }
316 }
317 }
318
319 void SelectionView::validateSearch()
320 {
321 if (!searchList.empty()) {
322 App::Document* doc = App::GetApplication().getActiveDocument();
323 if (doc) {
324 Gui::Selection().clearSelection();
325 for (auto it : searchList) {
326 Gui::Selection().addSelection(doc->getName(), it->getNameInDocument(), nullptr);
327 }
328 }
329 }
330 }
331
332 void SelectionView::select(QListWidgetItem* item)
333 {
334 if (!item) {
335 item = selectionView->currentItem();
336 }
337 if (!item) {
338 return;
339 }
340 QStringList elements = item->data(Qt::UserRole).toStringList();
341 if (elements.size() < 2) {
342 return;
343 }
344
345 try {
346 // Gui::Selection().clearSelection();
347 Gui::Command::runCommand(Gui::Command::Gui, "Gui.Selection.clearSelection()");
348 // Gui::Selection().addSelection(elements[0].toLatin1(),elements[1].toLatin1(),0);
349 QString cmd = QString::fromUtf8(
350 R"(Gui.Selection.addSelection(App.getDocument("%1").getObject("%2")))"
351 )
352 .arg(elements[0], elements[1]);
353 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
354 }
355 catch (Base::Exception& e) {
356 e.reportException();
357 }
358 }
359
360 void SelectionView::deselect()
361 {
362 QListWidgetItem* item = selectionView->currentItem();
363 if (!item) {
364 return;
365 }
366 QStringList elements = item->data(Qt::UserRole).toStringList();
367 if (elements.size() < 2) {
368 return;
369 }
370
371 // Gui::Selection().rmvSelection(elements[0].toLatin1(),elements[1].toLatin1(),0);
372 QString cmd = QString::fromUtf8(
373 R"(Gui.Selection.removeSelection(App.getDocument("%1").getObject("%2")))"
374 )
375 .arg(elements[0], elements[1]);
376 try {
377 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
378 }
379 catch (Base::Exception& e) {
380 e.reportException();
381 }
382 }
383
384 void SelectionView::toggleSelect(QListWidgetItem* item)
385 {
386 if (!item) {
387 return;
388 }
389 std::string name = item->text().toUtf8().constData();
390 char* docname = &name.at(0);
391 char* objname = std::strchr(docname, '#');
392 if (!objname) {
393 return;
394 }
395 *objname++ = 0;
396 char* subname = std::strchr(objname, '.');
397 if (subname) {
398 *subname++ = 0;
399 char* end = std::strchr(subname, ' ');
400 if (end) {
401 *end = 0;
402 }
403 }
404 else {
405 char* end = std::strchr(objname, ' ');
406 if (end) {
407 *end = 0;
408 }
409 }
410 QString cmd;
411 if (Gui::Selection().isSelected(docname, objname, subname)) {
412 cmd = QString::fromUtf8(
413 "Gui.Selection.removeSelection("
414 "App.getDocument('%1').getObject('%2'),'%3')"
415 )
416 .arg(
417 QString::fromUtf8(docname),
418 QString::fromUtf8(objname),
419 QString::fromUtf8(subname)
420 );
421 }
422 else {
423 cmd = QString::fromUtf8(
424 "Gui.Selection.addSelection("
425 "App.getDocument('%1').getObject('%2'),'%3',%4,%5,%6)"
426 )
427 .arg(QString::fromUtf8(docname), QString::fromUtf8(objname), QString::fromUtf8(subname))
428 .arg(x)
429 .arg(y)
430 .arg(z);
431 }
432 try {
433 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
434 }
435 catch (Base::Exception& e) {
436 e.reportException();
437 }
438 }
439
440 void SelectionView::preselect(QListWidgetItem* item)
441 {
442 if (!item) {
443 return;
444 }
445 std::string name = item->text().toUtf8().constData();
446 char* docname = &name.at(0);
447 char* objname = std::strchr(docname, '#');
448 if (!objname) {
449 return;
450 }
451 *objname++ = 0;
452 char* subname = std::strchr(objname, '.');
453 if (subname) {
454 *subname++ = 0;
455 char* end = std::strchr(subname, ' ');
456 if (end) {
457 *end = 0;
458 }
459 }
460 else {
461 char* end = std::strchr(objname, ' ');
462 if (end) {
463 *end = 0;
464 }
465 }
466 QString cmd
467 = QString::fromUtf8(
468 "Gui.Selection.setPreselection("
469 "App.getDocument('%1').getObject('%2'),'%3',tp=2)"
470 )
471 .arg(QString::fromUtf8(docname), QString::fromUtf8(objname), QString::fromUtf8(subname));
472 try {
473 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
474 }
475 catch (Base::Exception& e) {
476 e.reportException();
477 }
478 }
479
480 void SelectionView::zoom()
481 {
482 select();
483 try {
484 Gui::Command::runCommand(Gui::Command::Gui, "Gui.SendMsgToActiveView(\"ViewSelection\")");
485 }
486 catch (Base::Exception& e) {
487 e.reportException();
488 }
489 }
490
491 void SelectionView::treeSelect()
492 {
493 select();
494 try {
495 Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand(\"Std_TreeSelection\")");
496 }
497 catch (Base::Exception& e) {
498 e.reportException();
499 }
500 }
501
502 void SelectionView::touch()
503 {
504 QListWidgetItem* item = selectionView->currentItem();
505 if (!item) {
506 return;
507 }
508 QStringList elements = item->data(Qt::UserRole).toStringList();
509 if (elements.size() < 2) {
510 return;
511 }
512 QString cmd = QString::fromUtf8(R"(App.getDocument("%1").getObject("%2").touch())")
513 .arg(elements[0], elements[1]);
514 try {
515 Gui::Command::runCommand(Gui::Command::Doc, cmd.toUtf8());
516 }
517 catch (Base::Exception& e) {
518 e.reportException();
519 }
520 }
521
522 void SelectionView::toPython()
523 {
524 QListWidgetItem* item = selectionView->currentItem();
525 if (!item) {
526 return;
527 }
528 QStringList elements = item->data(Qt::UserRole).toStringList();
529 if (elements.size() < 2) {
530 return;
531 }
532
533 try {
534 QString cmd = QString::fromUtf8(R"(obj = App.getDocument("%1").getObject("%2"))")
535 .arg(elements[0], elements[1]);
536 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
537 if (elements.length() > 2) {
538 App::Document* doc = App::GetApplication().getDocument(elements[0].toUtf8());
539 App::DocumentObject* obj = doc->getObject(elements[1].toUtf8());
540 QString property = getProperty(obj);
541
542 cmd = QString::fromUtf8(R"(shp = App.getDocument("%1").getObject("%2").%3)")
543 .arg(elements[0], elements[1], property);
544 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
545
546 if (supportPart(obj, elements[2])) {
547 cmd = QString::fromUtf8(R"(elt = App.getDocument("%1").getObject("%2").%3.%4)")
548 .arg(elements[0], elements[1], property, elements[2]);
549 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
550 }
551 }
552 }
553 catch (const Base::Exception& e) {
554 e.reportException();
555 }
556 }
557
558 void SelectionView::showPart()
559 {
560 QListWidgetItem* item = selectionView->currentItem();
561 if (!item) {
562 return;
563 }
564 QStringList elements = item->data(Qt::UserRole).toStringList();
565 if (elements.length() > 2) {
566 App::Document* doc = App::GetApplication().getDocument(elements[0].toUtf8());
567 App::DocumentObject* obj = doc->getObject(elements[1].toUtf8());
568 QString module = getModule(obj->getTypeId().getName());
569 QString property = getProperty(obj);
570 if (!module.isEmpty() && !property.isEmpty() && supportPart(obj, elements[2])) {
571 try {
572 Gui::Command::addModule(Gui::Command::Gui, module.toUtf8());
573 QString cmd = QString::fromUtf8(
574 R"(%1.show(App.getDocument("%2").getObject("%3").%4.%5))"
575 )
576 .arg(module, elements[0], elements[1], property, elements[2]);
577 Gui::Command::runCommand(Gui::Command::Gui, cmd.toUtf8());
578 }
579 catch (const Base::Exception& e) {
580 e.reportException();
581 }
582 }
583 }
584 }
585
586 QString SelectionView::getModule(const char* type) const
587 {
588 // go up the inheritance tree and find the module name of the first
589 // sub-class that has not the prefix "App::"
590 std::string prefix;
591 Base::Type typeId = Base::Type::fromName(type);
592
593 while (!typeId.isBad()) {
594 std::string temp(typeId.getName());
595 std::string::size_type pos = temp.find_first_of("::");
596
597 std::string module;
598 if (pos != std::string::npos) {
599 module = std::string(temp, 0, pos);
600 }
601 if (module != "App") {
602 prefix = module;
603 }
604 else {
605 break;
606 }
607 typeId = typeId.getParent();
608 }
609
610 return QString::fromStdString(prefix);
611 }
612
613 QString SelectionView::getProperty(App::DocumentObject* obj) const
614 {
615 QString property;
616 if (obj->isDerivedFrom<App::GeoFeature>()) {
617 App::GeoFeature* geo = static_cast<App::GeoFeature*>(obj);
618 const App::PropertyComplexGeoData* data = geo->getPropertyOfGeometry();
619 const char* name = data ? data->getName() : nullptr;
620 if (App::Property::isValidName(name)) {
621 property = QString::fromUtf8(name);
622 }
623 }
624
625 return property;
626 }
627
628 bool SelectionView::supportPart(App::DocumentObject* obj, const QString& part) const
629 {
630 if (obj->isDerivedFrom<App::GeoFeature>()) {
631 App::GeoFeature* geo = static_cast<App::GeoFeature*>(obj);
632 const App::PropertyComplexGeoData* data = geo->getPropertyOfGeometry();
633 if (data) {
634 const Data::ComplexGeoData* geometry = data->getComplexData();
635 std::vector<const char*> types = geometry->getElementTypes();
636 for (auto it : types) {
637 if (part.startsWith(QString::fromUtf8(it))) {
638 return true;
639 }
640 }
641 }
642 }
643
644 return false;
645 }
646
647 void SelectionView::onItemContextMenu(const QPoint& point)
648 {
649 QListWidgetItem* item = selectionView->itemAt(point);
650 if (!item) {
651 return;
652 }
653 QMenu menu;
654 QAction* selectAction = menu.addAction(tr("Select Only"), this, [&] { this->select(nullptr); });
655 selectAction->setIcon(QIcon::fromTheme(QStringLiteral("view-select")));
656 selectAction->setToolTip(tr("Selects only this object"));
657
658 QAction* deselectAction = menu.addAction(tr("Deselect"), this, &SelectionView::deselect);
659 deselectAction->setIcon(QIcon::fromTheme(QStringLiteral("view-unselectable")));
660 deselectAction->setToolTip(tr("Deselects this object"));
661
662 QAction* zoomAction = menu.addAction(tr("Zoom Fit"), this, &SelectionView::zoom);
663 zoomAction->setIcon(QIcon::fromTheme(QStringLiteral("zoom-fit-best")));
664 zoomAction->setToolTip(tr("Selects and fits this object in the 3D window"));
665
666 QAction* gotoAction = menu.addAction(tr("Go to Selection"), this, &SelectionView::treeSelect);
667 gotoAction->setToolTip(tr("Selects and locates this object in the tree view"));
668
669 QAction* touchAction = menu.addAction(tr("Mark to Recompute"), this, &SelectionView::touch);
670 touchAction->setIcon(QIcon::fromTheme(QStringLiteral("view-refresh")));
671 touchAction->setToolTip(tr("Marks this object to be recomputed"));
672
673 QAction* toPythonAction = menu.addAction(tr("To Python Console"), this, &SelectionView::toPython);
674 toPythonAction->setIcon(QIcon::fromTheme(QStringLiteral("applications-python")));
675 toPythonAction->setToolTip(tr("Reveals this object and its subelements in the Python console."));
676
677 QStringList elements = item->data(Qt::UserRole).toStringList();
678 if (elements.length() > 2) {
679 // subshape-specific entries
680 QAction* showPart = menu.addAction(tr("Duplicate Subshape"), this, &SelectionView::showPart);
681 showPart->setIcon(QIcon(QStringLiteral(":/icons/ClassBrowser/member.svg")));
682 showPart->setToolTip(tr("Creates a standalone copy of this subshape in the document"));
683 }
684 menu.exec(selectionView->mapToGlobal(point));
685 }
686
687 void SelectionView::onUpdate()
688 {}
689
690 bool SelectionView::onMsg(const char* /*pMsg*/, const char** /*ppReturn*/)
691 {
692 return false;
693 }
694
695 void SelectionView::hideEvent(QHideEvent* ev)
696 {
697 DockWindow::hideEvent(ev);
698 }
699
700 void SelectionView::showEvent(QShowEvent* ev)
701 {
702 enablePickList->setChecked(Selection().needPickedList());
703 Gui::DockWindow::showEvent(ev);
704 }
705
706 void SelectionView::onEnablePickList()
707 {
708 bool enabled = enablePickList->isChecked();
709 Selection().enablePickedList(enabled);
710 pickList->setVisible(enabled);
711 }
712
713 /// @endcond
714
715 // SelectionMenu implementation
716 SelectionMenu::SelectionMenu(QWidget* parent)
717 : QMenu(parent)
718 {
719 connect(this, &QMenu::hovered, this, &SelectionMenu::onHover);
720 }
721
722 struct ElementInfo
723 {
724 QMenu* menu = nullptr;
725 QIcon icon;
726 std::vector<int> indices;
727 };
728
729 struct SubMenuInfo
730 {
731 QMenu* menu = nullptr;
732 // Map from sub-object label to map from object path to element info
733 std::map<std::string, std::map<std::string, ElementInfo>> items;
734 };
735
736 PickData SelectionMenu::doPick(const std::vector<PickData>& sels, const QPoint& pos)
737 {
738 clear();
739 Gui::Selection().setClarifySelectionActive(true);
740
741 currentSelections = sels;
742
743 std::map<std::string, SubMenuInfo> menus;
744 processSelections(currentSelections, menus);
745 buildMenuStructure(menus, currentSelections);
746
747 QAction* picked = this->exec(pos);
748 return onPicked(picked, currentSelections);
749 }
750
751 void SelectionMenu::processSelections(
752 std::vector<PickData>& selections,
753 std::map<std::string, SubMenuInfo>& menus
754 )
755 {
756 std::map<App::DocumentObject*, QIcon> icons;
757 std::set<std::string> createdElementTypes;
758 std::set<std::string> processedItems;
759
760 for (int i = 0; i < (int)selections.size(); ++i) {
761 const auto& sel = selections[i];
762
763 App::DocumentObject* sobj = getSubObject(sel);
764 std::string elementType = extractElementType(sel);
765 std::string objKey = createObjectKey(sel);
766 std::string itemId = elementType + "|" + std::string(sobj->Label.getValue()) + "|"
767 + sel.subName;
768
769 if (processedItems.find(itemId) != processedItems.end()) {
770 continue;
771 }
772 processedItems.insert(itemId);
773
774 QIcon icon = getOrCreateIcon(sobj, icons);
775
776 auto& elementInfo = menus[elementType].items[sobj->Label.getValue()][objKey];
777 elementInfo.icon = icon;
778 elementInfo.indices.push_back(i);
779
780 addGeoFeatureTypes(sobj, menus, createdElementTypes);
781 addWholeObjectSelection(sel, sobj, selections, menus, icon);
782 }
783 }
784
785 void SelectionMenu::buildMenuStructure(
786 std::map<std::string, SubMenuInfo>& menus,
787 const std::vector<PickData>& selections
788 )
789 {
790 std::vector<std::string> preferredOrder
791 = {"Object", "Solid", "Face", "Edge", "Vertex", "Wire", "Shell", "Compound", "CompSolid"};
792 std::vector<std::map<std::string, SubMenuInfo>::iterator> menuArray;
793 menuArray.reserve(menus.size());
794
795 for (const auto& category : preferredOrder) {
796 if (auto it = menus.find(category); it != menus.end()) {
797 menuArray.push_back(it);
798 }
799 }
800
801 for (auto it = menus.begin(); it != menus.end(); ++it) {
802 if (std::find(preferredOrder.begin(), preferredOrder.end(), it->first)
803 == preferredOrder.end()) {
804 menuArray.push_back(it);
805 }
806 }
807
808 for (auto elementTypeIterator : menuArray) {
809 auto& elementTypeEntry = *elementTypeIterator;
810 auto& subMenuInfo = elementTypeEntry.second;
811 const std::string& elementType = elementTypeEntry.first;
812
813 if (subMenuInfo.items.empty()) {
814 continue;
815 }
816
817 subMenuInfo.menu = addMenu(QString::fromUtf8(elementType.c_str()));
818
819 // for "Object" type, and "Other", always use flat menu (no submenus for individual objects)
820 bool groupMenu = (elementType != "Object" && elementType != "Other")
821 && shouldGroupMenu(subMenuInfo);
822
823 for (auto& objectLabelEntry : subMenuInfo.items) {
824 const std::string& objectLabel = objectLabelEntry.first;
825
826 for (auto& objectPathEntry : objectLabelEntry.second) {
827 auto& elementInfo = objectPathEntry.second;
828
829 if (!groupMenu) {
830 createFlatMenu(elementInfo, subMenuInfo.menu, objectLabel, elementType, selections);
831 }
832 else {
833 createGroupedMenu(elementInfo, subMenuInfo.menu, objectLabel, elementType, selections);
834 }
835 }
836 }
837 }
838 }
839
840 PickData SelectionMenu::onPicked(QAction* picked, const std::vector<PickData>& sels)
841 {
842 // Clear the ClarifySelection active flag when menu is done
843 Gui::Selection().setClarifySelectionActive(false);
844
845 Gui::Selection().rmvPreselect();
846 if (!picked) {
847 return PickData {};
848 }
849
850 int index = picked->data().toInt();
851 if (index >= 0 && index < (int)sels.size()) {
852 const auto& sel = sels[index];
853 if (sel.obj) {
854 Gui::Selection().addSelection(sel.docName.c_str(), sel.objName.c_str(), sel.subName.c_str());
855 }
856 return sel;
857 }
858 return PickData {};
859 }
860
861 void SelectionMenu::onHover(QAction* action)
862 {
863 if (!action || currentSelections.empty()) {
864 return;
865 }
866
867 // Clear previous preselection
868 Gui::Selection().rmvPreselect();
869
870 // Get the selection index from the action data
871 bool ok;
872 int index = action->data().toInt(&ok);
873 if (!ok || index < 0 || index >= (int)currentSelections.size()) {
874 return;
875 }
876
877 const auto& sel = currentSelections[index];
878 if (!sel.obj) {
879 return;
880 }
881
882 // set preselection for both sub-objects and whole objects
883 Gui::Selection().setPreselect(
884 sel.docName.c_str(),
885 sel.objName.c_str(),
886 !sel.subName.empty() ? sel.subName.c_str() : "",
887 0,
888 0,
889 0,
890 SelectionChanges::MsgSource::TreeView
891 );
892 }
893
894 bool SelectionMenu::eventFilter(QObject* obj, QEvent* event)
895 {
896 return QMenu::eventFilter(obj, event);
897 }
898
899 void SelectionMenu::leaveEvent(QEvent* e)
900 {
901 Gui::Selection().rmvPreselect();
902 QMenu::leaveEvent(e);
903 }
904
905 App::DocumentObject* SelectionMenu::getSubObject(const PickData& sel)
906 {
907 App::DocumentObject* sobj = sel.obj;
908 if (!sel.subName.empty()) {
909 sobj = sel.obj->getSubObject(sel.subName.c_str());
910 if (!sobj) {
911 sobj = sel.obj;
912 }
913 }
914 return sobj;
915 }
916
917 std::string SelectionMenu::extractElementType(const PickData& sel)
918 {
919 std::string actualElement;
920
921 if (!sel.element.empty()) {
922 actualElement = sel.element;
923 }
924 else if (!sel.subName.empty()) {
925 const char* elementName = Data::findElementName(sel.subName.c_str());
926 if (elementName && elementName[0]) {
927 actualElement = elementName;
928 }
929 else {
930 // for link objects like "Bucket.Edge222", extract "Edge222"
931 std::string subName = sel.subName;
932 std::size_t lastDot = subName.find_last_of('.');
933 if (lastDot != std::string::npos && lastDot + 1 < subName.length()) {
934 actualElement = subName.substr(lastDot + 1);
935 }
936 }
937 }
938
939 if (!actualElement.empty()) {
940 std::size_t pos = actualElement.find_first_of("0123456789");
941 if (pos != std::string::npos) {
942 return actualElement.substr(0, pos);
943 }
944 return actualElement;
945 }
946
947 return "Other";
948 }
949
950 std::string SelectionMenu::createObjectKey(const PickData& sel)
951 {
952 std::string objKey = std::string(sel.objName);
953 if (!sel.subName.empty()) {
954 std::string subNameNoElement = sel.subName;
955 const char* elementName = Data::findElementName(sel.subName.c_str());
956 if (elementName && elementName[0]) {
957 std::string elementStr = elementName;
958 std::size_t elementPos = subNameNoElement.rfind(elementStr);
959 if (elementPos != std::string::npos) {
960 subNameNoElement = subNameNoElement.substr(0, elementPos);
961 }
962 }
963 objKey += "." + subNameNoElement;
964 }
965 return objKey;
966 }
967
968 QIcon SelectionMenu::getOrCreateIcon(
969 App::DocumentObject* sobj,
970 std::map<App::DocumentObject*, QIcon>& icons
971 )
972 {
973 auto& icon = icons[sobj];
974 if (icon.isNull()) {
975 auto vp = Application::Instance->getViewProvider(sobj);
976 if (vp) {
977 icon = vp->getIcon();
978 }
979 }
980 return icon;
981 }
982
983 void SelectionMenu::addGeoFeatureTypes(
984 App::DocumentObject* sobj,
985 std::map<std::string, SubMenuInfo>& menus,
986 std::set<std::string>& createdTypes
987 )
988 {
989 auto geoFeature = freecad_cast<App::GeoFeature*>(sobj->getLinkedObject(true));
990 if (geoFeature) {
991 std::vector<const char*> types = geoFeature->getElementTypes(true);
992 for (const char* type : types) {
993 if (type && type[0] && createdTypes.find(type) == createdTypes.end()) {
994 menus[type];
995 createdTypes.insert(type);
996 }
997 }
998 }
999 }
1000
1001 void SelectionMenu::addWholeObjectSelection(
1002 const PickData& sel,
1003 App::DocumentObject* sobj,
1004 std::vector<PickData>& selections,
1005 std::map<std::string, SubMenuInfo>& menus,
1006 const QIcon& icon
1007 )
1008 {
1009 if (sel.subName.empty()) {
1010 return;
1011 }
1012
1013 std::string actualElement = extractElementType(sel) != "Other" ? sel.element : "";
1014 if (actualElement.empty() && !sel.subName.empty()) {
1015 const char* elementName = Data::findElementName(sel.subName.c_str());
1016 if (elementName) {
1017 actualElement = elementName;
1018 }
1019 }
1020 if (actualElement.empty()) {
1021 return;
1022 }
1023
1024 bool shouldAdd = false;
1025 if (sobj) {
1026 if (sobj != sel.obj) {
1027 // sub-objects
1028 std::string typeName = sobj->getTypeId().getName();
1029 if (typeName == "App::Part" || typeName == "PartDesign::Body") {
1030 shouldAdd = true;
1031 }
1032 else {
1033 auto geoFeature = freecad_cast<App::GeoFeature*>(sobj->getLinkedObject(true));
1034 if (geoFeature) {
1035 std::vector<const char*> types = geoFeature->getElementTypes(true);
1036 if (types.size() > 1) {
1037 shouldAdd = true;
1038 }
1039 }
1040 }
1041 }
1042 else {
1043 // top-level objects (sobj == sel.obj)
1044 // check if subName is just an element name
1045 if (sel.subName.find('.') == std::string::npos) {
1046 auto geoFeature = freecad_cast<App::GeoFeature*>(sobj->getLinkedObject(true));
1047 if (geoFeature) {
1048 std::vector<const char*> types = geoFeature->getElementTypes(true);
1049 if (!types.empty()) {
1050 shouldAdd = true;
1051 }
1052 }
1053 }
1054 }
1055 }
1056
1057 if (shouldAdd) {
1058 std::string wholeObjKey;
1059 std::string wholeObjSubName;
1060
1061 if (sobj != sel.obj) {
1062 // sub-objects
1063 std::string subNameStr = sel.subName;
1064 std::size_t lastDot = subNameStr.find_last_of('.');
1065 if (lastDot != std::string::npos && lastDot > 0) {
1066 std::size_t prevDot = subNameStr.find_last_of('.', lastDot - 1);
1067 std::string subObjName;
1068 if (prevDot != std::string::npos) {
1069 subObjName = subNameStr.substr(prevDot + 1, lastDot - prevDot - 1);
1070 }
1071 else {
1072 subObjName = subNameStr.substr(0, lastDot);
1073 }
1074
1075 if (!subObjName.empty()) {
1076 wholeObjKey = std::string(sel.objName) + "." + subObjName + ".";
1077 wholeObjSubName = subObjName + ".";
1078 }
1079 }
1080 }
1081 else {
1082 // top-level objects (sobj == sel.obj)
1083 wholeObjKey = std::string(sel.objName) + ".";
1084 wholeObjSubName = ""; // empty subName for top-level whole object
1085 }
1086
1087 if (!wholeObjKey.empty()) {
1088 auto& objItems = menus["Object"].items[sobj->Label.getValue()];
1089 if (objItems.find(wholeObjKey) == objItems.end()) {
1090 PickData wholeObjSel = sel;
1091 wholeObjSel.subName = wholeObjSubName;
1092 wholeObjSel.element = "";
1093
1094 selections.push_back(wholeObjSel);
1095
1096 auto& wholeObjInfo = objItems[wholeObjKey];
1097 wholeObjInfo.icon = icon;
1098 wholeObjInfo.indices.push_back(selections.size() - 1);
1099 }
1100 }
1101 }
1102 }
1103
1104 bool SelectionMenu::shouldGroupMenu(const SubMenuInfo& info)
1105 {
1106 constexpr std::size_t MAX_MENU_ITEMS_BEFORE_GROUPING = 20;
1107 if (info.items.size() > MAX_MENU_ITEMS_BEFORE_GROUPING) {
1108 return true;
1109 }
1110
1111 std::size_t objCount = 0;
1112 std::size_t count = 0;
1113 constexpr std::size_t MAX_SELECTION_COUNT_BEFORE_GROUPING = 5;
1114 for (auto& objectLabelEntry : info.items) {
1115 objCount += objectLabelEntry.second.size();
1116 for (auto& objectPathEntry : objectLabelEntry.second) {
1117 count += objectPathEntry.second.indices.size();
1118 }
1119 if (count > MAX_SELECTION_COUNT_BEFORE_GROUPING && objCount > 1) {
1120 return true;
1121 }
1122 }
1123 return false;
1124 }
1125
1126 void SelectionMenu::createFlatMenu(
1127 ElementInfo& elementInfo,
1128 QMenu* parentMenu,
1129 const std::string& label,
1130 const std::string& elementType,
1131 const std::vector<PickData>& selections
1132 )
1133 {
1134 for (int idx : elementInfo.indices) {
1135 const auto& sel = selections[idx];
1136 QString text = QString::fromUtf8(label.c_str());
1137 if (!sel.element.empty()) {
1138 text += QStringLiteral(" (%1)").arg(QString::fromUtf8(sel.element.c_str()));
1139 }
1140 else if (!sel.subName.empty() && elementType != "Object" && elementType != "Other") {
1141 // For link objects, extract element name from subName
1142 // For "Bucket.Face74", we want to show "Bucket001 (Face74)"
1143 std::string subName = sel.subName;
1144 std::size_t lastDot = subName.find_last_of('.');
1145 if (lastDot != std::string::npos && lastDot + 1 < subName.length()) {
1146 QString elementName = QString::fromUtf8(subName.substr(lastDot + 1).c_str());
1147 text += QStringLiteral(" (%1)").arg(elementName);
1148 }
1149 }
1150
1151 QAction* action = parentMenu->addAction(elementInfo.icon, text);
1152 action->setData(idx);
1153 connect(action, &QAction::hovered, this, [this, action]() { onHover(action); });
1154 }
1155 }
1156
1157 void SelectionMenu::createGroupedMenu(
1158 ElementInfo& elementInfo,
1159 QMenu* parentMenu,
1160 const std::string& label,
1161 const std::string& elementType,
1162 const std::vector<PickData>& selections
1163 )
1164 {
1165 if (!elementInfo.menu) {
1166 elementInfo.menu = parentMenu->addMenu(elementInfo.icon, QString::fromUtf8(label.c_str()));
1167 }
1168
1169 for (int idx : elementInfo.indices) {
1170 const auto& sel = selections[idx];
1171 QString text;
1172 if (!sel.element.empty()) {
1173 text = QString::fromUtf8(sel.element.c_str());
1174 }
1175 else if (elementType == "Object" && !sel.subName.empty() && sel.subName.back() == '.') {
1176 text = tr("Whole Object");
1177 }
1178 else if (!sel.subName.empty()) {
1179 // extract just the element name from subName for link objects
1180 // for "Bucket.Edge222", we want just "Edge222"
1181 std::string subName = sel.subName;
1182 std::size_t lastDot = subName.find_last_of('.');
1183 if (lastDot != std::string::npos && lastDot + 1 < subName.length()) {
1184 text = QString::fromUtf8(subName.substr(lastDot + 1).c_str());
1185 }
1186 else {
1187 text = QString::fromUtf8(sel.subName.c_str());
1188 }
1189 }
1190 else {
1191 text = QString::fromUtf8(sel.subName.c_str());
1192 }
1193
1194 QAction* action = elementInfo.menu->addAction(text);
1195 action->setData(idx);
1196 connect(action, &QAction::hovered, this, [this, action]() { onHover(action); });
1197 }
1198 }
1199
1200 #include "moc_SelectionView.cpp"