Debian Codegraph @

src/Gui/Selection/Selection.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /***************************************************************************
3 * Copyright (c) 2011 Jürgen Riegel <[email protected]> *
4 * Copyright (c) 2011 Werner Mayer <wmayer[at]users.sourceforge.net> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25
26 #include <array>
27 #include <set>
28 #include <boost/algorithm/string/predicate.hpp>
29 #include <QApplication>
30
31
32 #include <App/Application.h>
33 #include <App/Document.h>
34 #include <App/DocumentObject.h>
35 #include <App/DocumentObjectPy.h>
36 #include <App/GeoFeature.h>
37 #include <Base/Console.h>
38 #include <Base/Exception.h>
39 #include <Base/Interpreter.h>
40 #include <Base/Tools.h>
41 #include <Base/PyWrapParseTupleAndKeywords.h>
42 #include <Base/UnitsApi.h>
43
44 #include "Selection.h"
45 #include "SelectionObject.h"
46 #include "Application.h"
47 #include "Document.h"
48 #include "Macro.h"
49 #include "MainWindow.h"
50 #include "MDIView.h"
51 #include "SelectionFilter.h"
52 #include "SelectionFilterPy.h"
53 #include "SelectionObserverPython.h"
54 #include "Tree.h"
55 #include "ViewProvider.h"
56 #include "ViewProviderDocumentObject.h"
57
58
59 FC_LOG_LEVEL_INIT("Selection", false, true, true)
60
61 using namespace Gui;
62 using namespace std;
63 namespace sp = std::placeholders;
64
65 SelectionGateFilterExternal::SelectionGateFilterExternal(const char* docName, const char* objName)
66 {
67 if (docName) {
68 DocName = docName;
69 if (objName) {
70 ObjName = objName;
71 }
72 }
73 }
74
75 bool SelectionGateFilterExternal::allow(App::Document* doc, App::DocumentObject* obj, const char*)
76 {
77 if (!doc || !obj) {
78 return true;
79 }
80 if (!DocName.empty() && doc->getName() != DocName) {
81 notAllowedReason = "Cannot select external object";
82 }
83 else if (!ObjName.empty() && ObjName == obj->getNameInDocument()) {
84 notAllowedReason = "Cannot select self";
85 }
86 else {
87 return true;
88 }
89 return false;
90 }
91
92 //////////////////////////////////////////////////////////////////////////////////////////
93
94 SelectionObserver::SelectionObserver(bool attach, ResolveMode resolve)
95 : resolve(resolve)
96 , blockedSelection(false)
97 {
98 if (attach) {
99 attachSelection();
100 }
101 }
102
103 SelectionObserver::SelectionObserver(const ViewProviderDocumentObject* vp, bool attach, ResolveMode resolve)
104 : resolve(resolve)
105 , blockedSelection(false)
106 {
107 if (vp && vp->getObject() && vp->getObject()->getDocument()) {
108 filterDocName = vp->getObject()->getDocument()->getName();
109 filterObjName = vp->getObject()->getNameInDocument();
110 }
111 if (attach) {
112 attachSelection();
113 }
114 }
115
116
117 SelectionObserver::~SelectionObserver()
118 {
119 detachSelection();
120 }
121
122 bool SelectionObserver::blockSelection(bool block)
123 {
124 bool ok = blockedSelection;
125 blockedSelection = block;
126 return ok;
127 }
128
129 bool SelectionObserver::isSelectionBlocked() const
130 {
131 return blockedSelection;
132 }
133
134 bool SelectionObserver::isSelectionAttached() const
135 {
136 return connectSelection.connected();
137 }
138
139 void SelectionObserver::attachSelection()
140 {
141 if (!connectSelection.connected()) {
142 bool newStyle = (resolve >= ResolveMode::NewStyleElement);
143 bool oldStyle = (resolve == ResolveMode::OldStyleElement);
144 auto& signal = newStyle ? Selection().signalSelectionChanged3
145 : oldStyle ? Selection().signalSelectionChanged2
146 : Selection().signalSelectionChanged;
147 // NOLINTBEGIN
148 connectSelection = signal.connect(
149 std::bind(&SelectionObserver::_onSelectionChanged, this, sp::_1)
150 );
151 // NOLINTEND
152
153 if (!filterDocName.empty()) {
154 Selection().addSelectionGate(
155 new SelectionGateFilterExternal(filterDocName.c_str(), filterObjName.c_str())
156 );
157 }
158 }
159 }
160
161 void SelectionObserver::_onSelectionChanged(const SelectionChanges& msg)
162 {
163 try {
164 if (blockedSelection) {
165 return;
166 }
167 onSelectionChanged(msg);
168 }
169 catch (Base::Exception& e) {
170 e.reportException();
171 FC_ERR("Unhandled Base::Exception caught in selection observer: ");
172 }
173 catch (std::exception& e) {
174 FC_ERR("Unhandled std::exception caught in selection observer: " << e.what());
175 }
176 catch (...) {
177 FC_ERR("Unhandled unknown exception caught in selection observer");
178 }
179 }
180
181 void SelectionObserver::detachSelection()
182 {
183 if (connectSelection.connected()) {
184 connectSelection.disconnect();
185 if (!filterDocName.empty()) {
186 Selection().rmvSelectionGate();
187 }
188 }
189 }
190
191 // -------------------------------------------
192
193 bool SelectionSingleton::hasSelection() const
194 {
195 return !_SelList.empty();
196 }
197
198 bool SelectionSingleton::hasPreselection() const
199 {
200 return !CurrentPreselection.Object.getObjectName().empty();
201 }
202
203 std::vector<SelectionSingleton::SelObj> SelectionSingleton::getCompleteSelection(ResolveMode resolve) const
204 {
205 return getSelection("*", resolve);
206 }
207
208 std::vector<SelectionSingleton::SelObj> SelectionSingleton::getSelection(
209 const char* pDocName,
210 ResolveMode resolve,
211 bool single
212 ) const
213 {
214 std::vector<SelObj> temp;
215 if (single) {
216 temp.reserve(1);
217 }
218 SelObj tempSelObj;
219
220 App::Document* pcDoc = nullptr;
221 if (!pDocName || strcmp(pDocName, "*") != 0) {
222 pcDoc = getDocument(pDocName);
223 if (!pcDoc) {
224 return temp;
225 }
226 }
227
228 std::map<App::DocumentObject*, std::set<std::string>> objMap;
229
230 for (auto& sel : _SelList) {
231 if (!sel.pDoc) {
232 continue;
233 }
234 const char* subelement = nullptr;
235 auto obj = getObjectOfType(sel, App::DocumentObject::getClassTypeId(), resolve, &subelement);
236 if (!obj || (pcDoc && sel.pObject->getDocument() != pcDoc)) {
237 continue;
238 }
239
240 // In case we are resolving objects, make sure no duplicates
241 if (resolve != ResolveMode::NoResolve
242 && !objMap[obj].insert(std::string(subelement ? subelement : "")).second) {
243 continue;
244 }
245
246 if (single && !temp.empty()) {
247 temp.clear();
248 break;
249 }
250
251 tempSelObj.DocName = obj->getDocument()->getName();
252 tempSelObj.FeatName = obj->getNameInDocument();
253 tempSelObj.SubName = subelement;
254 tempSelObj.TypeName = obj->getTypeId().getName();
255 tempSelObj.pObject = obj;
256 tempSelObj.pResolvedObject = sel.pResolvedObject;
257 tempSelObj.pDoc = obj->getDocument();
258 tempSelObj.x = sel.x;
259 tempSelObj.y = sel.y;
260 tempSelObj.z = sel.z;
261
262 temp.push_back(tempSelObj);
263 }
264
265 return temp;
266 }
267
268 bool SelectionSingleton::hasSelection(const char* doc, ResolveMode resolve) const
269 {
270 App::Document* pcDoc = nullptr;
271 if (!doc || strcmp(doc, "*") != 0) {
272 pcDoc = getDocument(doc);
273 if (!pcDoc) {
274 return false;
275 }
276 }
277 for (auto& sel : _SelList) {
278 if (!sel.pDoc) {
279 continue;
280 }
281 auto obj = getObjectOfType(sel, App::DocumentObject::getClassTypeId(), resolve);
282 if (obj && (!pcDoc || sel.pObject->getDocument() == pcDoc)) {
283 return true;
284 }
285 }
286
287 return false;
288 }
289
290 bool SelectionSingleton::hasSubSelection(const char* doc, bool subElement) const
291 {
292 App::Document* pcDoc = nullptr;
293 if (!doc || strcmp(doc, "*") != 0) {
294 pcDoc = getDocument(doc);
295 if (!pcDoc) {
296 return false;
297 }
298 }
299 for (auto& sel : _SelList) {
300 if (pcDoc && pcDoc != sel.pDoc) {
301 continue;
302 }
303 if (sel.SubName.empty()) {
304 continue;
305 }
306 if (subElement && sel.SubName.back() != '.') {
307 return true;
308 }
309 if (sel.pObject != sel.pResolvedObject) {
310 return true;
311 }
312 }
313
314 return false;
315 }
316
317 std::vector<SelectionSingleton::SelObj> SelectionSingleton::getPickedList(const char* pDocName) const
318 {
319 std::vector<SelObj> temp;
320 SelObj tempSelObj;
321
322 App::Document* pcDoc = nullptr;
323 if (!pDocName || strcmp(pDocName, "*") != 0) {
324 pcDoc = getDocument(pDocName);
325 if (!pcDoc) {
326 return temp;
327 }
328 }
329
330 for (std::list<_SelObj>::const_iterator It = _PickedList.begin(); It != _PickedList.end(); ++It) {
331 if (!pcDoc || It->pDoc == pcDoc) {
332 tempSelObj.DocName = It->DocName.c_str();
333 tempSelObj.FeatName = It->FeatName.c_str();
334 tempSelObj.SubName = It->SubName.c_str();
335 tempSelObj.TypeName = It->TypeName.c_str();
336 tempSelObj.pObject = It->pObject;
337 tempSelObj.pResolvedObject = It->pResolvedObject;
338 tempSelObj.pDoc = It->pDoc;
339 tempSelObj.x = It->x;
340 tempSelObj.y = It->y;
341 tempSelObj.z = It->z;
342 temp.push_back(tempSelObj);
343 }
344 }
345
346 return temp;
347 }
348
349 std::vector<Gui::SelectionObject> SelectionSingleton::getSelectionIn(
350 App::DocumentObject* container,
351 Base::Type typeId,
352 bool single
353 ) const
354 {
355 if (!container) {
356 return getSelectionEx(nullptr, typeId, ResolveMode::NoResolve, single);
357 }
358
359 std::vector<SelectionObject> sels
360 = getSelectionEx(nullptr, App::DocumentObject::getClassTypeId(), ResolveMode::NoResolve, single);
361
362 std::vector<SelectionObject> ret;
363 std::map<App::DocumentObject*, size_t> SortMap;
364
365 for (auto& sel : sels) {
366 auto* rootObj = sel.getObject();
367 App::Document* doc = rootObj->getDocument();
368 std::vector<std::string> subs = sel.getSubNames();
369 bool objPassed = false;
370
371 for (size_t i = 0; i < subs.size(); ++i) {
372 auto& sub = subs[i];
373 App::DocumentObject* newRootObj = nullptr;
374 std::string newSub = "";
375
376 std::vector<std::string> names = Base::Tools::splitSubName(sub);
377
378 if (container == rootObj) {
379 objPassed = true;
380 }
381
382 if (rootObj->isLink()) {
383 // Update doc in case its an external link.
384 doc = rootObj->getLinkedObject()->getDocument();
385 }
386
387 for (auto& name : names) {
388 App::DocumentObject* obj = doc->getObject(name.c_str());
389 if (!obj) { // We reached the element name (for example 'edge1')
390 newSub += name;
391 break;
392 }
393
394 if (objPassed) {
395 if (!newRootObj) {
396 // We are the first object after the container is passed.
397 newRootObj = obj;
398 }
399 else {
400 newSub += name + ".";
401 }
402 }
403
404 if (obj == container) {
405 objPassed = true;
406 }
407 if (obj->isLink()) {
408 // Update doc in case its an external link.
409 doc = obj->getLinkedObject()->getDocument();
410 }
411 }
412
413 if (newRootObj) {
414 // Make sure selected object is of correct type
415 auto* lastObj = newRootObj->resolve(newSub.c_str());
416 if (!lastObj || !lastObj->isDerivedFrom(typeId)) {
417 continue;
418 }
419
420 auto it = SortMap.find(newRootObj);
421 if (it != SortMap.end()) {
422 // only add sub-element
423 if (newSub != "") {
424 ret[it->second].SubNames.emplace_back(newSub);
425 ret[it->second].SelPoses.emplace_back(sel.SelPoses[i]);
426 }
427 }
428 else {
429 if (single && !ret.empty()) {
430 ret.clear();
431 break;
432 }
433 // create a new entry
434 ret.emplace_back(newRootObj);
435 if (newSub != "") {
436 ret.back().SubNames.emplace_back(newSub);
437 ret.back().SelPoses.emplace_back(sel.SelPoses[i]);
438 }
439 SortMap.insert(std::make_pair(newRootObj, ret.size() - 1));
440 }
441 }
442 }
443 }
444
445 return ret;
446 }
447
448 std::vector<SelectionObject> SelectionSingleton::getSelectionEx(
449 const char* pDocName,
450 Base::Type typeId,
451 ResolveMode resolve,
452 bool single
453 ) const
454 {
455 return getObjectList(pDocName, typeId, _SelList, resolve, single);
456 }
457
458 std::vector<SelectionObject> SelectionSingleton::getPickedListEx(
459 const char* pDocName,
460 Base::Type typeId
461 ) const
462 {
463 return getObjectList(pDocName, typeId, _PickedList, ResolveMode::NoResolve);
464 }
465
466 std::vector<SelectionObject> SelectionSingleton::getObjectList(
467 const char* pDocName,
468 Base::Type typeId,
469 std::list<_SelObj>& objList,
470 ResolveMode resolve,
471 bool single
472 ) const
473 {
474 std::vector<SelectionObject> temp;
475 if (single) {
476 temp.reserve(1);
477 }
478 std::map<App::DocumentObject*, size_t> SortMap;
479
480 // check the type
481 if (typeId.isBad()) {
482 return temp;
483 }
484
485 App::Document* pcDoc = nullptr;
486 if (!pDocName || strcmp(pDocName, "*") != 0) {
487 pcDoc = getDocument(pDocName);
488 if (!pcDoc) {
489 return temp;
490 }
491 }
492
493 for (auto& sel : objList) {
494 if (!sel.pDoc) {
495 continue;
496 }
497 const char* subelement = nullptr;
498 auto obj = getObjectOfType(sel, typeId, resolve, &subelement);
499 if (!obj || (pcDoc && sel.pObject->getDocument() != pcDoc)) {
500 continue;
501 }
502 auto it = SortMap.find(obj);
503 if (it != SortMap.end()) {
504 // only add sub-element
505 if (subelement && *subelement) {
506 if (resolve != ResolveMode::NoResolve
507 && !temp[it->second]._SubNameSet.insert(subelement).second) {
508 continue;
509 }
510 temp[it->second].SubNames.emplace_back(subelement);
511 temp[it->second].SelPoses.emplace_back(sel.x, sel.y, sel.z);
512 }
513 }
514 else {
515 if (single && !temp.empty()) {
516 temp.clear();
517 break;
518 }
519 // create a new entry
520 temp.emplace_back(obj);
521 if (subelement && *subelement) {
522 temp.back().SubNames.emplace_back(subelement);
523 temp.back().SelPoses.emplace_back(sel.x, sel.y, sel.z);
524 if (resolve != ResolveMode::NoResolve) {
525 temp.back()._SubNameSet.insert(subelement);
526 }
527 }
528 SortMap.insert(std::make_pair(obj, temp.size() - 1));
529 }
530 }
531
532 return temp;
533 }
534
535 bool SelectionSingleton::needPickedList() const
536 {
537 return _needPickedList;
538 }
539
540 void SelectionSingleton::enablePickedList(bool enable)
541 {
542 if (enable != _needPickedList) {
543 _needPickedList = enable;
544 _PickedList.clear();
545 notify(SelectionChanges(SelectionChanges::PickedListChanged));
546 }
547 }
548
549 static void notifyDocumentObjectViewProvider(const SelectionChanges& changes)
550 {
551 const auto* doc = App::GetApplication().getDocument(changes.pDocName);
552 if (!doc) {
553 return;
554 }
555
556 const auto* obj = doc->getObject(changes.pObjectName);
557 if (!obj) {
558 return;
559 }
560
561 auto* vp = Application::Instance->getViewProvider(obj);
562 if (!vp) {
563 return;
564 }
565
566 vp->onSelectionChanged(changes);
567 }
568
569 void SelectionSingleton::notify(SelectionChanges&& Chng)
570 {
571 if (Notifying) {
572 NotificationQueue.push_back(std::move(Chng));
573 return;
574 }
575 Base::FlagToggler<bool> flag(Notifying);
576 NotificationQueue.push_back(std::move(Chng));
577 while (!NotificationQueue.empty()) {
578 const auto& msg = NotificationQueue.front();
579 bool notify = false;
580 switch (msg.Type) {
581 case SelectionChanges::AddSelection:
582 notify = isSelected(msg.pDocName, msg.pObjectName, msg.pSubName, ResolveMode::NoResolve);
583 break;
584 case SelectionChanges::RmvSelection:
585 notify = !isSelected(msg.pDocName, msg.pObjectName, msg.pSubName, ResolveMode::NoResolve);
586 break;
587 case SelectionChanges::SetPreselect:
588 notify = CurrentPreselection.Type == SelectionChanges::SetPreselect
589 && CurrentPreselection.Object == msg.Object;
590 break;
591 case SelectionChanges::RmvPreselect:
592 notify = CurrentPreselection.Type == SelectionChanges::ClrSelection;
593 break;
594 default:
595 notify = true;
596 }
597 if (notify) {
598 // Notify the view provider of the object.
599 notifyDocumentObjectViewProvider(msg);
600
601 Notify(msg);
602 try {
603 signalSelectionChanged(msg);
604 }
605 catch (const boost::exception&) {
606 // reported by code analyzers
607 Base::Console().warning("notify: Unexpected boost exception\n");
608 }
609 }
610 NotificationQueue.pop_front();
611 }
612 }
613
614 bool SelectionSingleton::hasPickedList() const
615 {
616 return !_PickedList.empty();
617 }
618
619 int SelectionSingleton::getAsPropertyLinkSubList(App::PropertyLinkSubList& prop) const
620 {
621 std::vector<Gui::SelectionObject> sel = this->getSelectionEx();
622 std::vector<App::DocumentObject*> objs;
623 objs.reserve(sel.size() * 2);
624 std::vector<std::string> subs;
625 subs.reserve(sel.size() * 2);
626 for (auto& selitem : sel) {
627 App::DocumentObject* obj = selitem.getObject();
628 const std::vector<std::string>& subnames = selitem.getSubNames();
629
630 // whole object is selected
631 if (subnames.empty()) {
632 objs.push_back(obj);
633 subs.emplace_back();
634 }
635 else {
636 for (const auto& subname : subnames) {
637 objs.push_back(obj);
638 subs.push_back(subname);
639 }
640 }
641 }
642 assert(objs.size() == subs.size());
643 prop.setValues(objs, subs);
644 return objs.size();
645 }
646
647 App::DocumentObject* SelectionSingleton::getObjectOfType(
648 _SelObj& sel,
649 Base::Type typeId,
650 ResolveMode resolve,
651 const char** subelement
652 )
653 {
654 auto obj = sel.pObject;
655 if (!obj || !obj->isAttachedToDocument()) {
656 return nullptr;
657 }
658 const char* subname = sel.SubName.c_str();
659 if (resolve != ResolveMode::NoResolve) {
660 obj = sel.pResolvedObject;
661 if (resolve == ResolveMode::NewStyleElement && !sel.elementName.newName.empty()) {
662 subname = sel.elementName.newName.c_str();
663 }
664 else {
665 subname = sel.elementName.oldName.c_str();
666 }
667 }
668
669 if (!obj) {
670 return nullptr;
671 }
672
673 if (!obj->isDerivedFrom(typeId)
674 && (resolve != ResolveMode::FollowLink || !obj->getLinkedObject(true)->isDerivedFrom(typeId))) {
675 return nullptr;
676 }
677
678 if (subelement) {
679 *subelement = subname;
680 }
681
682 return obj;
683 }
684
685 vector<App::DocumentObject*> SelectionSingleton::getObjectsOfType(
686 const Base::Type& typeId,
687 const char* pDocName,
688 ResolveMode resolve
689 ) const
690 {
691 std::vector<App::DocumentObject*> temp;
692
693 App::Document* pcDoc = nullptr;
694 if (!pDocName || strcmp(pDocName, "*") != 0) {
695 pcDoc = getDocument(pDocName);
696 if (!pcDoc) {
697 return temp;
698 }
699 }
700
701 std::set<App::DocumentObject*> objs;
702 for (auto& sel : _SelList) {
703 if (pcDoc && pcDoc != sel.pDoc) {
704 continue;
705 }
706 App::DocumentObject* pObject = getObjectOfType(sel, typeId, resolve);
707 if (pObject) {
708 auto ret = objs.insert(pObject);
709 if (ret.second) {
710 temp.push_back(pObject);
711 }
712 }
713 }
714
715 return temp;
716 }
717
718 std::vector<App::DocumentObject*> SelectionSingleton::getObjectsOfType(
719 const char* typeName,
720 const char* pDocName,
721 ResolveMode resolve
722 ) const
723 {
724 Base::Type typeId = Base::Type::fromName(typeName);
725 if (typeId.isBad()) {
726 return {};
727 }
728 return getObjectsOfType(typeId, pDocName, resolve);
729 }
730
731 unsigned int SelectionSingleton::countObjectsOfType(
732 const Base::Type& typeId,
733 const char* pDocName,
734 ResolveMode resolve
735 ) const
736 {
737 App::Document* pcDoc = nullptr;
738 if (!pDocName || strcmp(pDocName, "*") != 0) {
739 pcDoc = getDocument(pDocName);
740 if (!pcDoc) {
741 return 0;
742 }
743 }
744
745 return std::count_if(_SelList.begin(), _SelList.end(), [&](auto& sel) {
746 return (!pcDoc || pcDoc == sel.pDoc) && getObjectOfType(sel, typeId, resolve);
747 });
748 }
749
750 unsigned int SelectionSingleton::countObjectsOfType(
751 const char* typeName,
752 const char* pDocName,
753 ResolveMode resolve
754 ) const
755 {
756 Base::Type typeId = Base::Type::fromName(typeName);
757 if (typeId.isBad()) {
758 return 0;
759 }
760 return countObjectsOfType(typeId, pDocName, resolve);
761 }
762
763
764 void SelectionSingleton::slotSelectionChanged(const SelectionChanges& msg)
765 {
766 if (msg.Type == SelectionChanges::SetPreselectSignal || msg.Type == SelectionChanges::ShowSelection
767 || msg.Type == SelectionChanges::HideSelection) {
768 return;
769 }
770
771 if (!msg.Object.getSubName().empty()) {
772 auto pParent = msg.Object.getObject();
773 if (!pParent) {
774 return;
775 }
776 App::ElementNamePair elementName;
777 auto& newElementName = elementName.newName;
778 auto& oldElementName = elementName.oldName;
779 auto pObject = App::GeoFeature::resolveElement(pParent, msg.pSubName, elementName);
780 if (!pObject) {
781 return;
782 }
783 SelectionChanges msg2(
784 msg.Type,
785 pObject->getDocument()->getName(),
786 pObject->getNameInDocument(),
787 !newElementName.empty() ? newElementName.c_str() : oldElementName.c_str(),
788 pObject->getTypeId().getName(),
789 msg.x,
790 msg.y,
791 msg.z
792 );
793
794 try {
795 msg2.pOriginalMsg = &msg;
796 signalSelectionChanged3(msg2);
797
798 msg2.Object.setSubName(oldElementName.c_str());
799 msg2.pSubName = msg2.Object.getSubName().c_str();
800 signalSelectionChanged2(msg2);
801 }
802 catch (const boost::exception&) {
803 // reported by code analyzers
804 Base::Console().warning("slotSelectionChanged: Unexpected boost exception\n");
805 }
806 }
807 else {
808 try {
809 signalSelectionChanged3(msg);
810 signalSelectionChanged2(msg);
811 }
812 catch (const boost::exception&) {
813 // reported by code analyzers
814 Base::Console().warning("slotSelectionChanged: Unexpected boost exception\n");
815 }
816 }
817 }
818
819 int SelectionSingleton::setPreselect(
820 const char* pDocName,
821 const char* pObjectName,
822 const char* pSubName,
823 float x,
824 float y,
825 float z,
826 SelectionChanges::MsgSource signal
827 )
828 {
829 if (!pDocName || !pObjectName) {
830 rmvPreselect();
831 return 0;
832 }
833 if (!pSubName) {
834 pSubName = "";
835 }
836
837 if (DocName == pDocName && FeatName == pObjectName && SubName == pSubName) {
838 return -1;
839 }
840
841 rmvPreselect();
842
843 if (ActiveGate && signal != SelectionChanges::MsgSource::Internal) {
844 App::Document* pDoc = getDocument(pDocName);
845 if (!pDoc || !pObjectName) {
846 return 0;
847 }
848 App::ElementNamePair elementName;
849 auto pObject = pDoc->getObject(pObjectName);
850 if (!pObject) {
851 return 0;
852 }
853
854 const char* subelement = pSubName;
855 if (gateResolve != ResolveMode::NoResolve) {
856 auto& newElementName = elementName.newName;
857 auto& oldElementName = elementName.oldName;
858 pObject = App::GeoFeature::resolveElement(pObject, pSubName, elementName);
859 if (!pObject) {
860 return 0;
861 }
862 if (gateResolve > ResolveMode::OldStyleElement) {
863 subelement = !newElementName.empty() ? newElementName.c_str()
864 : oldElementName.c_str();
865 }
866 else {
867 subelement = oldElementName.c_str();
868 }
869 }
870 if (!ActiveGate->allow(pObject->getDocument(), pObject, subelement)) {
871 QString msg;
872 if (ActiveGate->notAllowedReason.length() > 0) {
873 msg = QObject::tr(ActiveGate->notAllowedReason.c_str());
874 }
875 else {
876 msg = QCoreApplication::translate("SelectionFilter", "Not allowed:");
877 }
878 msg.append(QStringLiteral(" %1.%2.%3 ")
879 .arg(
880 QString::fromLatin1(pDocName),
881 QString::fromLatin1(pObjectName),
882 QString::fromLatin1(pSubName)
883 ));
884
885 if (getMainWindow()) {
886 getMainWindow()->showMessage(msg);
887 Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
888 mdi->setOverrideCursor(QCursor(Qt::ForbiddenCursor));
889 }
890 return 0;
891 }
892 Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
893 mdi->restoreOverrideCursor();
894 }
895
896 DocName = pDocName;
897 FeatName = pObjectName;
898 SubName = pSubName;
899 hx = x;
900 hy = y;
901 hz = z;
902
903 // set up the change object
904 SelectionChanges Chng(
905 signal == SelectionChanges::MsgSource::Internal ? SelectionChanges::SetPreselectSignal
906 : SelectionChanges::SetPreselect,
907 DocName,
908 FeatName,
909 SubName,
910 std::string(),
911 x,
912 y,
913 z,
914 signal
915 );
916
917 if (Chng.Type == SelectionChanges::SetPreselect) {
918 CurrentPreselection = Chng;
919 FC_TRACE("preselect " << DocName << '#' << FeatName << '.' << SubName);
920 }
921 else {
922 FC_TRACE("preselect signal " << DocName << '#' << FeatName << '.' << SubName);
923 }
924
925 notify(Chng);
926
927 if (signal == SelectionChanges::MsgSource::Internal && !DocName.empty()) {
928 FC_TRACE("preselect " << DocName << '#' << FeatName << '.' << SubName);
929 Chng.Type = SelectionChanges::SetPreselect;
930 CurrentPreselection = Chng;
931 notify(std::move(Chng));
932 }
933
934 // It is possible the preselect is removed during notification
935 return DocName.empty() ? 0 : 1;
936 }
937
938 namespace Gui
939 {
940 std::array<std::pair<double, std::string>, 3> schemaTranslatePoint(
941 double x,
942 double y,
943 double z,
944 double precision
945 )
946 {
947 Base::Quantity mmx(Base::Quantity::MilliMetre);
948 mmx.setValue(fabs(x) > precision ? x : 0.0);
949 Base::Quantity mmy(Base::Quantity::MilliMetre);
950 mmy.setValue(fabs(y) > precision ? y : 0.0);
951 Base::Quantity mmz(Base::Quantity::MilliMetre);
952 mmz.setValue(fabs(z) > precision ? z : 0.0);
953
954 double xfactor, yfactor, zfactor;
955 std::string xunit, yunit, zunit;
956
957 Base::UnitsApi::schemaTranslate(mmx, xfactor, xunit);
958 Base::UnitsApi::schemaTranslate(mmy, yfactor, yunit);
959 Base::UnitsApi::schemaTranslate(mmz, zfactor, zunit);
960
961 double xuser = fabs(x) > precision ? x / xfactor : 0.0;
962 double yuser = fabs(y) > precision ? y / yfactor : 0.0;
963 double zuser = fabs(z) > precision ? z / zfactor : 0.0;
964
965 std::array<std::pair<double, std::string>, 3> ret
966 = {std::make_pair(xuser, xunit), std::make_pair(yuser, yunit), std::make_pair(zuser, zunit)};
967 return ret;
968 }
969
970 QString getPreselectionInfo(
971 const char* documentName,
972 const char* objectName,
973 const char* subElementName,
974 float x,
975 float y,
976 float z,
977 double precision
978 )
979 {
980 auto pts = schemaTranslatePoint(x, y, z, precision);
981
982 int numberDecimals = std::min(6, static_cast<int>(Base::UnitsApi::getDecimals()));
983
984 QString message = QStringLiteral("Preselected: %1.%2.%3 (%4 %5, %6 %7, %8 %9)")
985 .arg(QString::fromUtf8(documentName))
986 .arg(QString::fromUtf8(objectName))
987 .arg(QString::fromUtf8(subElementName))
988 .arg(QString::number(pts[0].first, 'f', numberDecimals))
989 .arg(QString::fromStdString(pts[0].second))
990 .arg(QString::number(pts[1].first, 'f', numberDecimals))
991 .arg(QString::fromStdString(pts[1].second))
992 .arg(QString::number(pts[2].first, 'f', numberDecimals))
993 .arg(QString::fromStdString(pts[2].second));
994 return message;
995 }
996
997 void printPreselectionInfo(
998 const char* documentName,
999 const char* objectName,
1000 const char* subElementName,
1001 float x,
1002 float y,
1003 float z,
1004 double precision
1005 )
1006 {
1007 if (getMainWindow()) {
1008 QString message
1009 = getPreselectionInfo(documentName, objectName, subElementName, x, y, z, precision);
1010 getMainWindow()->showMessage(message);
1011 }
1012 }
1013 } // namespace Gui
1014
1015 void SelectionSingleton::setPreselectCoord(float x, float y, float z)
1016 {
1017 // if nothing is in preselect ignore
1018 if (CurrentPreselection.Object.getObjectName().empty()) {
1019 return;
1020 }
1021
1022 CurrentPreselection.x = x;
1023 CurrentPreselection.y = y;
1024 CurrentPreselection.z = z;
1025
1026 printPreselectionInfo(
1027 CurrentPreselection.pDocName,
1028 CurrentPreselection.pObjectName,
1029 CurrentPreselection.pSubName,
1030 x,
1031 y,
1032 z,
1033 0.0
1034 );
1035 }
1036
1037 void SelectionSingleton::rmvPreselect(bool signal)
1038 {
1039 if (DocName.empty()) {
1040 return;
1041 }
1042
1043 if (signal) {
1044 SelectionChanges Chng(SelectionChanges::RmvPreselectSignal, DocName, FeatName, SubName);
1045 notify(std::move(Chng));
1046 return;
1047 }
1048
1049 SelectionChanges Chng(SelectionChanges::RmvPreselect, DocName, FeatName, SubName);
1050
1051 // reset the current preselection
1052 CurrentPreselection = SelectionChanges();
1053
1054 DocName = "";
1055 FeatName = "";
1056 SubName = "";
1057 hx = 0;
1058 hy = 0;
1059 hz = 0;
1060
1061 if (ActiveGate && getMainWindow()) {
1062 Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
1063 mdi->restoreOverrideCursor();
1064 }
1065
1066 FC_TRACE("rmv preselect");
1067
1068 // notify observing objects
1069 notify(std::move(Chng));
1070 }
1071
1072 const SelectionChanges& SelectionSingleton::getPreselection() const
1073 {
1074 return CurrentPreselection;
1075 }
1076
1077 // add a SelectionGate to control what is selectable
1078 void SelectionSingleton::addSelectionGate(Gui::SelectionGate* gate, ResolveMode resolve)
1079 {
1080 if (ActiveGate) {
1081 rmvSelectionGate();
1082 }
1083
1084 ActiveGate = gate;
1085 gateResolve = resolve;
1086 }
1087
1088 // remove the active SelectionGate
1089 void SelectionSingleton::rmvSelectionGate()
1090 {
1091 if (ActiveGate) {
1092 delete ActiveGate;
1093 ActiveGate = nullptr;
1094
1095 Gui::Document* doc = Gui::Application::Instance->activeDocument();
1096 if (doc) {
1097 // if a document is about to be closed it has no MDI view any more
1098 Gui::MDIView* mdi = doc->getActiveView();
1099 if (mdi) {
1100 mdi->restoreOverrideCursor();
1101 }
1102 }
1103 }
1104 }
1105
1106
1107 App::Document* SelectionSingleton::getDocument(const char* pDocName) const
1108 {
1109 if (!Base::Tools::isNullOrEmpty(pDocName)) {
1110 return App::GetApplication().getDocument(pDocName);
1111 }
1112 else {
1113 return App::GetApplication().getActiveDocument();
1114 }
1115 }
1116
1117 int SelectionSingleton::disableCommandLog()
1118 {
1119 if (!logDisabled) {
1120 logHasSelection = hasSelection();
1121 }
1122 return ++logDisabled;
1123 }
1124
1125 int SelectionSingleton::enableCommandLog(bool silent)
1126 {
1127 --logDisabled;
1128 if (!logDisabled && !silent) {
1129 auto manager = Application::Instance->macroManager();
1130 if (!hasSelection()) {
1131 if (logHasSelection) {
1132 manager->addLine(MacroManager::Cmt, "Gui.Selection.clearSelection()");
1133 }
1134 }
1135 else {
1136 for (auto& sel : _SelList) {
1137 sel.log();
1138 }
1139 }
1140 }
1141 return logDisabled;
1142 }
1143
1144 void SelectionSingleton::_SelObj::log(bool remove, bool clearPreselect)
1145 {
1146 if (logged && !remove) {
1147 return;
1148 }
1149 logged = true;
1150 std::ostringstream ss;
1151 ss << "Gui.Selection." << (remove ? "removeSelection" : "addSelection") << "('" << DocName
1152 << "','" << FeatName << "'";
1153 if (!SubName.empty()) {
1154 ss << "," << getSubString();
1155 }
1156 if (!remove && (x || y || z || !clearPreselect)) {
1157 if (SubName.empty()) {
1158 ss << ",''";
1159 }
1160 ss << ',' << x << ',' << y << ',' << z;
1161 if (!clearPreselect) {
1162 ss << ",False";
1163 }
1164 }
1165 ss << ')';
1166 Application::Instance->macroManager()->addLine(MacroManager::Cmt, ss.str().c_str());
1167 }
1168
1169 std::string SelectionSingleton::_SelObj::getSubString() const
1170 {
1171 if (!SubName.empty()) {
1172 if (!elementName.oldName.empty() && !elementName.newName.empty()) {
1173 return "'" + SubName.substr(0, SubName.size() - elementName.newName.size())
1174 + elementName.oldName + "'";
1175 }
1176 return "'" + SubName + "'";
1177 }
1178 return "";
1179 }
1180
1181 bool SelectionSingleton::addSelection(
1182 const char* pDocName,
1183 const char* pObjectName,
1184 const char* pSubName,
1185 float x,
1186 float y,
1187 float z,
1188 const std::vector<SelObj>* pickedList,
1189 bool clearPreselect
1190 )
1191 {
1192 if (pickedList) {
1193 _PickedList.clear();
1194 for (const auto& sel : *pickedList) {
1195 _PickedList.emplace_back();
1196 auto& s = _PickedList.back();
1197 s.DocName = sel.DocName;
1198 s.FeatName = sel.FeatName;
1199 s.SubName = sel.SubName;
1200 s.TypeName = sel.TypeName;
1201 s.pObject = sel.pObject;
1202 s.pDoc = sel.pDoc;
1203 s.x = sel.x;
1204 s.y = sel.y;
1205 s.z = sel.z;
1206 }
1207 notify(SelectionChanges(SelectionChanges::PickedListChanged));
1208 }
1209
1210 _SelObj temp;
1211 int ret = checkSelection(pDocName, pObjectName, pSubName, ResolveMode::NoResolve, temp);
1212 if (ret != 0) {
1213 return false;
1214 }
1215
1216 temp.x = x;
1217 temp.y = y;
1218 temp.z = z;
1219
1220 // check for a Selection Gate
1221 if (ActiveGate) {
1222 const char* subelement = nullptr;
1223 auto pObject
1224 = getObjectOfType(temp, App::DocumentObject::getClassTypeId(), gateResolve, &subelement);
1225 if (!ActiveGate->allow(pObject ? pObject->getDocument() : temp.pDoc, pObject, subelement)) {
1226 if (getMainWindow()) {
1227 QString msg;
1228 if (ActiveGate->notAllowedReason.length() > 0) {
1229 msg = QObject::tr(ActiveGate->notAllowedReason.c_str());
1230 }
1231 else {
1232 msg = QCoreApplication::translate(
1233 "SelectionFilter",
1234 "Selection not allowed by filter"
1235 );
1236 }
1237 getMainWindow()->showMessage(msg);
1238 Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
1239 mdi->setOverrideCursor(Qt::ForbiddenCursor);
1240 }
1241 ActiveGate->notAllowedReason.clear();
1242 QApplication::beep();
1243 return false;
1244 }
1245 }
1246
1247 if (!logDisabled) {
1248 temp.log(false, clearPreselect);
1249 }
1250
1251 _SelList.push_back(temp);
1252 _SelStackForward.clear();
1253
1254 if (clearPreselect) {
1255 rmvPreselect();
1256 }
1257
1258 SelectionChanges Chng(
1259 SelectionChanges::AddSelection,
1260 temp.DocName,
1261 temp.FeatName,
1262 temp.SubName,
1263 temp.TypeName,
1264 x,
1265 y,
1266 z
1267 );
1268
1269 FC_LOG(
1270 "Add Selection " << Chng.pDocName << '#' << Chng.pObjectName << '.' << Chng.pSubName << " ("
1271 << x << ", " << y << ", " << z << ')'
1272 );
1273
1274 notify(std::move(Chng));
1275
1276 getMainWindow()->updateActions();
1277
1278 rmvPreselect(true);
1279
1280 // There is a possibility that some observer removes or clears selection
1281 // inside signal handler, hence the check here
1282 return isSelected(temp.DocName.c_str(), temp.FeatName.c_str(), temp.SubName.c_str());
1283 }
1284
1285 void SelectionSingleton::selStackPush(bool clearForward, bool overwrite)
1286 {
1287 static int stackSize;
1288 if (!stackSize) {
1289 stackSize = App::GetApplication()
1290 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
1291 ->GetInt("SelectionStackSize", 100);
1292 }
1293 if (clearForward) {
1294 _SelStackForward.clear();
1295 }
1296 if (_SelList.empty()) {
1297 return;
1298 }
1299 if ((int)_SelStackBack.size() >= stackSize) {
1300 _SelStackBack.pop_front();
1301 }
1302 SelStackItem item;
1303 for (auto& sel : _SelList) {
1304 item.emplace(sel.DocName.c_str(), sel.FeatName.c_str(), sel.SubName.c_str());
1305 }
1306 if (!_SelStackBack.empty() && _SelStackBack.back() == item) {
1307 return;
1308 }
1309 if (!overwrite || _SelStackBack.empty()) {
1310 _SelStackBack.emplace_back();
1311 }
1312 _SelStackBack.back() = std::move(item);
1313 }
1314
1315 void SelectionSingleton::selStackGoBack(int count)
1316 {
1317 if ((int)_SelStackBack.size() < count) {
1318 count = _SelStackBack.size();
1319 }
1320 if (count <= 0) {
1321 return;
1322 }
1323 if (!_SelList.empty()) {
1324 selStackPush(false, true);
1325 clearCompleteSelection();
1326 }
1327 else {
1328 --count;
1329 }
1330 for (int i = 0; i < count; ++i) {
1331 _SelStackForward.push_front(std::move(_SelStackBack.back()));
1332 _SelStackBack.pop_back();
1333 }
1334 std::deque<SelStackItem> tmpStack;
1335 _SelStackForward.swap(tmpStack);
1336 while (!_SelStackBack.empty()) {
1337 bool found = false;
1338 for (auto& sobjT : _SelStackBack.back()) {
1339 if (sobjT.getSubObject()) {
1340 addSelection(
1341 sobjT.getDocumentName().c_str(),
1342 sobjT.getObjectName().c_str(),
1343 sobjT.getSubName().c_str()
1344 );
1345 found = true;
1346 }
1347 }
1348 if (found) {
1349 break;
1350 }
1351 tmpStack.push_front(std::move(_SelStackBack.back()));
1352 _SelStackBack.pop_back();
1353 }
1354 _SelStackForward = std::move(tmpStack);
1355 getMainWindow()->updateActions();
1356 }
1357
1358 void SelectionSingleton::selStackGoForward(int count)
1359 {
1360 if ((int)_SelStackForward.size() < count) {
1361 count = _SelStackForward.size();
1362 }
1363 if (count <= 0) {
1364 return;
1365 }
1366 if (!_SelList.empty()) {
1367 selStackPush(false, true);
1368 clearCompleteSelection();
1369 }
1370 for (int i = 0; i < count; ++i) {
1371 _SelStackBack.push_back(_SelStackForward.front());
1372 _SelStackForward.pop_front();
1373 }
1374 std::deque<SelStackItem> tmpStack;
1375 _SelStackForward.swap(tmpStack);
1376 while (true) {
1377 bool found = false;
1378 for (auto& sobjT : _SelStackBack.back()) {
1379 if (sobjT.getSubObject()) {
1380 addSelection(
1381 sobjT.getDocumentName().c_str(),
1382 sobjT.getObjectName().c_str(),
1383 sobjT.getSubName().c_str()
1384 );
1385 found = true;
1386 }
1387 }
1388 if (found || tmpStack.empty()) {
1389 break;
1390 }
1391 _SelStackBack.push_back(tmpStack.front());
1392 tmpStack.pop_front();
1393 }
1394 _SelStackForward = std::move(tmpStack);
1395 getMainWindow()->updateActions();
1396 }
1397
1398 std::vector<SelectionObject> SelectionSingleton::selStackGet(
1399 const char* pDocName,
1400 ResolveMode resolve,
1401 int index
1402 ) const
1403 {
1404 const SelStackItem* item = nullptr;
1405 if (index >= 0) {
1406 if (index >= (int)_SelStackBack.size()) {
1407 return {};
1408 }
1409 item = &_SelStackBack[_SelStackBack.size() - 1 - index];
1410 }
1411 else {
1412 index = -index - 1;
1413 if (index >= (int)_SelStackForward.size()) {
1414 return {};
1415 }
1416 item = &_SelStackBack[_SelStackForward.size() - 1 - index];
1417 }
1418
1419 std::list<_SelObj> selList;
1420 for (auto& sobjT : *item) {
1421 _SelObj sel;
1422 if (checkSelection(
1423 sobjT.getDocumentName().c_str(),
1424 sobjT.getObjectName().c_str(),
1425 sobjT.getSubName().c_str(),
1426 ResolveMode::NoResolve,
1427 sel,
1428 &selList
1429 )
1430 == 0) {
1431 selList.push_back(sel);
1432 }
1433 }
1434
1435 return getObjectList(pDocName, App::DocumentObject::getClassTypeId(), selList, resolve);
1436 }
1437
1438 bool SelectionSingleton::addSelections(
1439 const char* pDocName,
1440 const char* pObjectName,
1441 const std::vector<std::string>& pSubNames
1442 )
1443 {
1444 if (!_PickedList.empty()) {
1445 _PickedList.clear();
1446 notify(SelectionChanges(SelectionChanges::PickedListChanged));
1447 }
1448
1449 std::ostringstream ss;
1450 bool anyLogged = false;
1451
1452 if (!logDisabled) {
1453 ss << "Gui.Selection.addSelection(App.getDocument('" << pDocName << "').getObject('"
1454 << pObjectName << "'),[";
1455 }
1456
1457 bool update = false;
1458 for (const auto& pSubName : pSubNames) {
1459 _SelObj temp;
1460 int ret = checkSelection(pDocName, pObjectName, pSubName.c_str(), ResolveMode::NoResolve, temp);
1461 if (ret != 0) {
1462 continue;
1463 }
1464
1465 temp.x = 0;
1466 temp.y = 0;
1467 temp.z = 0;
1468
1469 if (!logDisabled && !temp.SubName.empty()) {
1470 temp.logged = true;
1471 if (anyLogged) {
1472 ss << ",";
1473 }
1474 anyLogged = true;
1475
1476 ss << temp.getSubString();
1477 }
1478
1479 _SelList.push_back(temp);
1480 _SelStackForward.clear();
1481
1482 SelectionChanges Chng(
1483 SelectionChanges::AddSelection,
1484 temp.DocName,
1485 temp.FeatName,
1486 temp.SubName,
1487 temp.TypeName
1488 );
1489
1490 FC_LOG("Add Selection " << Chng.pDocName << '#' << Chng.pObjectName << '.' << Chng.pSubName);
1491
1492 notify(std::move(Chng));
1493 update = true;
1494 }
1495
1496 if (!logDisabled && anyLogged) {
1497 ss << "])";
1498 Application::Instance->macroManager()->addLine(MacroManager::Cmt, ss.str().c_str());
1499 }
1500
1501 if (update) {
1502 getMainWindow()->updateActions();
1503 }
1504 return true;
1505 }
1506
1507 bool SelectionSingleton::updateSelection(
1508 bool show,
1509 const char* pDocName,
1510 const char* pObjectName,
1511 const char* pSubName
1512 )
1513 {
1514 if (!pDocName || !pObjectName) {
1515 return false;
1516 }
1517 if (!pSubName) {
1518 pSubName = "";
1519 }
1520 if (DocName == pDocName && FeatName == pObjectName && SubName == pSubName) {
1521 if (show) {
1522 FC_TRACE("preselect signal");
1523 notify(SelectionChanges(SelectionChanges::SetPreselectSignal, DocName, FeatName, SubName));
1524 }
1525 else {
1526 rmvPreselect();
1527 }
1528 }
1529 auto pDoc = getDocument(pDocName);
1530 if (!pDoc) {
1531 return false;
1532 }
1533 auto pObject = pDoc->getObject(pObjectName);
1534 if (!pObject) {
1535 return false;
1536 }
1537 if (!isSelected(pObject, pSubName, ResolveMode::NoResolve)) {
1538 return false;
1539 }
1540
1541 SelectionChanges Chng(
1542 show ? SelectionChanges::ShowSelection : SelectionChanges::HideSelection,
1543 pDocName,
1544 pObjectName,
1545 pSubName,
1546 pObject->getTypeId().getName()
1547 );
1548
1549 FC_LOG("Update Selection " << Chng.pDocName << '#' << Chng.pObjectName << '.' << Chng.pSubName);
1550
1551 notify(std::move(Chng));
1552
1553 return true;
1554 }
1555
1556 bool SelectionSingleton::addSelection(const SelectionObject& obj, bool clearPreselect)
1557 {
1558 const std::vector<std::string>& subNames = obj.getSubNames();
1559 const std::vector<Base::Vector3d> points = obj.getPickedPoints();
1560 if (!subNames.empty() && subNames.size() == points.size()) {
1561 bool ok = true;
1562 for (std::size_t i = 0; i < subNames.size(); i++) {
1563 const std::string& name = subNames[i];
1564 const Base::Vector3d& pnt = points[i];
1565 ok &= addSelection(
1566 obj.getDocName(),
1567 obj.getFeatName(),
1568 name.c_str(),
1569 static_cast<float>(pnt.x),
1570 static_cast<float>(pnt.y),
1571 static_cast<float>(pnt.z),
1572 nullptr,
1573 clearPreselect
1574 );
1575 }
1576 return ok;
1577 }
1578 else if (!subNames.empty()) {
1579 bool ok = true;
1580 for (const std::string& name : subNames) {
1581 ok &= addSelection(obj.getDocName(), obj.getFeatName(), name.c_str());
1582 }
1583 return ok;
1584 }
1585 else {
1586 return addSelection(obj.getDocName(), obj.getFeatName());
1587 }
1588 }
1589
1590
1591 void SelectionSingleton::rmvSelection(
1592 const char* pDocName,
1593 const char* pObjectName,
1594 const char* pSubName,
1595 const std::vector<SelObj>* pickedList
1596 )
1597 {
1598 if (pickedList) {
1599 _PickedList.clear();
1600 for (const auto& sel : *pickedList) {
1601 _PickedList.emplace_back();
1602 auto& s = _PickedList.back();
1603 s.DocName = sel.DocName;
1604 s.FeatName = sel.FeatName;
1605 s.SubName = sel.SubName;
1606 s.TypeName = sel.TypeName;
1607 s.pObject = sel.pObject;
1608 s.pDoc = sel.pDoc;
1609 s.x = sel.x;
1610 s.y = sel.y;
1611 s.z = sel.z;
1612 }
1613 notify(SelectionChanges(SelectionChanges::PickedListChanged));
1614 }
1615
1616 if (!pDocName) {
1617 return;
1618 }
1619
1620 _SelObj temp;
1621 int ret = checkSelection(pDocName, pObjectName, pSubName, ResolveMode::NoResolve, temp);
1622 if (ret < 0) {
1623 return;
1624 }
1625
1626 std::vector<SelectionChanges> changes;
1627 for (auto It = _SelList.begin(), ItNext = It; It != _SelList.end(); It = ItNext) {
1628 ++ItNext;
1629 if (It->DocName != temp.DocName || It->FeatName != temp.FeatName) {
1630 continue;
1631 }
1632 // if no subname is specified, remove all subobjects of the matching object
1633 if (!temp.SubName.empty()) {
1634 // otherwise, match subojects with common prefix, separated by '.'
1635 if (!boost::starts_with(It->SubName, temp.SubName)
1636 || (It->SubName.length() != temp.SubName.length()
1637 && It->SubName[temp.SubName.length() - 1] != '.')) {
1638 continue;
1639 }
1640 }
1641
1642 It->log(true);
1643
1644 changes.emplace_back(
1645 SelectionChanges::RmvSelection,
1646 It->DocName,
1647 It->FeatName,
1648 It->SubName,
1649 It->TypeName
1650 );
1651
1652 // destroy the _SelObj item
1653 _SelList.erase(It);
1654 }
1655
1656 // NOTE: It can happen that there are nested calls of rmvSelection()
1657 // so that it's not safe to invoke the notifications inside the loop
1658 // as this can invalidate the iterators and thus leads to undefined
1659 // behaviour.
1660 // So, the notification is done after the loop, see also #0003469
1661 if (!changes.empty()) {
1662 for (auto& Chng : changes) {
1663 FC_LOG(
1664 "Rmv Selection " << Chng.pDocName << '#' << Chng.pObjectName << '.' << Chng.pSubName
1665 );
1666 notify(std::move(Chng));
1667 }
1668 getMainWindow()->updateActions();
1669 }
1670 }
1671
1672 struct SelInfo
1673 {
1674 std::string DocName;
1675 std::string FeatName;
1676 std::string SubName;
1677 SelInfo(const std::string& docName, const std::string& featName, const std::string& subName)
1678 : DocName(docName)
1679 , FeatName(featName)
1680 , SubName(subName)
1681 {}
1682 };
1683
1684 void SelectionSingleton::setVisible(VisibleState vis)
1685 {
1686 std::set<std::pair<App::DocumentObject*, App::DocumentObject*>> filter;
1687 int visible;
1688 switch (vis) {
1689 case VisShow:
1690 visible = 1;
1691 break;
1692 case VisToggle:
1693 visible = -1;
1694 break;
1695 default:
1696 visible = 0;
1697 }
1698
1699 // Copy the selection in case it changes during this function
1700 std::vector<SelInfo> sels;
1701 sels.reserve(_SelList.size());
1702 for (auto& sel : _SelList) {
1703 if (sel.DocName.empty() || sel.FeatName.empty() || !sel.pObject) {
1704 continue;
1705 }
1706 sels.emplace_back(sel.DocName, sel.FeatName, sel.SubName);
1707 }
1708
1709 for (auto& sel : sels) {
1710 App::Document* doc = App::GetApplication().getDocument(sel.DocName.c_str());
1711 if (!doc) {
1712 continue;
1713 }
1714 App::DocumentObject* obj = doc->getObject(sel.FeatName.c_str());
1715 if (!obj) {
1716 continue;
1717 }
1718
1719 // get parent object
1720 App::DocumentObject* parent = nullptr;
1721 std::string elementName;
1722 obj = obj->resolve(sel.SubName.c_str(), &parent, &elementName);
1723 if (!obj || !obj->isAttachedToDocument() || (parent && !parent->isAttachedToDocument())) {
1724 continue;
1725 }
1726 // try call parent object's setElementVisible
1727 if (parent) {
1728 // prevent setting the same object visibility more than once
1729 if (!filter.insert(std::make_pair(obj, parent)).second) {
1730 continue;
1731 }
1732 int visElement = parent->isElementVisible(elementName.c_str());
1733 if (visElement >= 0) {
1734 if (visElement > 0) {
1735 visElement = 1;
1736 }
1737 if (visible >= 0) {
1738 if (visElement == visible) {
1739 continue;
1740 }
1741 visElement = visible;
1742 }
1743 else {
1744 visElement = !visElement;
1745 }
1746
1747 if (!visElement) {
1748 updateSelection(
1749 false,
1750 sel.DocName.c_str(),
1751 sel.FeatName.c_str(),
1752 sel.SubName.c_str()
1753 );
1754 }
1755 parent->setElementVisible(elementName.c_str(), visElement ? true : false);
1756 if (visElement) {
1757 updateSelection(true, sel.DocName.c_str(), sel.FeatName.c_str(), sel.SubName.c_str());
1758 }
1759 continue;
1760 }
1761
1762 // Fall back to direct object visibility setting
1763 }
1764 if (!filter.insert(std::make_pair(obj, static_cast<App::DocumentObject*>(nullptr))).second) {
1765 continue;
1766 }
1767
1768 auto vp = Application::Instance->getViewProvider(obj);
1769
1770 if (vp) {
1771 bool visObject;
1772 if (visible >= 0) {
1773 visObject = visible ? true : false;
1774 }
1775 else {
1776 visObject = !vp->isShow();
1777 }
1778
1779 if (visObject) {
1780 vp->show();
1781 updateSelection(
1782 visObject,
1783 sel.DocName.c_str(),
1784 sel.FeatName.c_str(),
1785 sel.SubName.c_str()
1786 );
1787 }
1788 else {
1789 updateSelection(
1790 visObject,
1791 sel.DocName.c_str(),
1792 sel.FeatName.c_str(),
1793 sel.SubName.c_str()
1794 );
1795 vp->hide();
1796 }
1797 }
1798 }
1799 }
1800
1801 void SelectionSingleton::setSelection(const char* pDocName, const std::vector<App::DocumentObject*>& sel)
1802 {
1803 App::Document* pcDoc;
1804 pcDoc = getDocument(pDocName);
1805 if (!pcDoc) {
1806 return;
1807 }
1808
1809 if (!_PickedList.empty()) {
1810 _PickedList.clear();
1811 notify(SelectionChanges(SelectionChanges::PickedListChanged));
1812 }
1813
1814 bool touched = false;
1815 for (auto obj : sel) {
1816 if (!obj || !obj->isAttachedToDocument()) {
1817 continue;
1818 }
1819 _SelObj temp;
1820 int ret
1821 = checkSelection(pDocName, obj->getNameInDocument(), nullptr, ResolveMode::NoResolve, temp);
1822 if (ret != 0) {
1823 continue;
1824 }
1825 touched = true;
1826 _SelList.push_back(temp);
1827 }
1828
1829 if (touched) {
1830 _SelStackForward.clear();
1831 notify(SelectionChanges(SelectionChanges::SetSelection, pDocName));
1832 getMainWindow()->updateActions();
1833 }
1834 }
1835
1836 void SelectionSingleton::clearSelection(const char* pDocName, bool clearPreSelect)
1837 {
1838 // Because the introduction of external editing, it is best to make
1839 // clearSelection(0) behave as clearCompleteSelection(), which is the same
1840 // behavior of python Selection.clearSelection(None)
1841 if (!pDocName || !pDocName[0] || strcmp(pDocName, "*") == 0) {
1842 clearCompleteSelection(clearPreSelect);
1843 return;
1844 }
1845
1846 if (!_PickedList.empty()) {
1847 _PickedList.clear();
1848 notify(SelectionChanges(SelectionChanges::PickedListChanged));
1849 }
1850
1851 App::Document* pDoc;
1852 pDoc = getDocument(pDocName);
1853 if (pDoc) {
1854 std::string docName = pDocName;
1855 if (clearPreSelect && DocName == docName) {
1856 rmvPreselect();
1857 }
1858
1859 bool touched = false;
1860 for (auto it = _SelList.begin(); it != _SelList.end();) {
1861 if (it->DocName == docName) {
1862 touched = true;
1863 it = _SelList.erase(it);
1864 }
1865 else {
1866 ++it;
1867 }
1868 }
1869
1870 if (!touched) {
1871 return;
1872 }
1873
1874 if (!logDisabled) {
1875 std::ostringstream ss;
1876 ss << "Gui.Selection.clearSelection('" << docName << "'";
1877 if (!clearPreSelect) {
1878 ss << ", False";
1879 }
1880 ss << ')';
1881 Application::Instance->macroManager()->addLine(MacroManager::Cmt, ss.str().c_str());
1882 }
1883
1884 notify(SelectionChanges(SelectionChanges::ClrSelection, docName.c_str()));
1885
1886 getMainWindow()->updateActions();
1887 }
1888 }
1889
1890 void SelectionSingleton::clearCompleteSelection(bool clearPreSelect)
1891 {
1892 if (!_PickedList.empty()) {
1893 _PickedList.clear();
1894 notify(SelectionChanges(SelectionChanges::PickedListChanged));
1895 }
1896
1897 if (clearPreSelect) {
1898 rmvPreselect();
1899 }
1900
1901 if (_SelList.empty()) {
1902 return;
1903 }
1904
1905 if (!logDisabled) {
1906 Application::Instance->macroManager()->addLine(
1907 MacroManager::Cmt,
1908 clearPreSelect ? "Gui.Selection.clearSelection()" : "Gui.Selection.clearSelection(False)"
1909 );
1910 }
1911
1912 // Send the clear selection notification to all view providers associated with the
1913 // objects being deselected.
1914
1915 std::set<ViewProvider*> viewProviders;
1916 for (_SelObj& sel : _SelList) {
1917 if (auto vp = Application::Instance->getViewProvider(sel.pObject)) {
1918 viewProviders.insert(vp);
1919 }
1920 }
1921
1922 for (auto& vp : viewProviders) {
1923 SelectionChanges Chng(SelectionChanges::ClrSelection);
1924 vp->onSelectionChanged(Chng);
1925 }
1926
1927 _SelList.clear();
1928
1929 SelectionChanges Chng(SelectionChanges::ClrSelection);
1930
1931 FC_LOG("Clear selection");
1932
1933 notify(std::move(Chng));
1934 getMainWindow()->updateActions();
1935 }
1936
1937 bool SelectionSingleton::isSelected(
1938 const char* pDocName,
1939 const char* pObjectName,
1940 const char* pSubName,
1941 ResolveMode resolve
1942 ) const
1943 {
1944 _SelObj sel;
1945 return checkSelection(pDocName, pObjectName, pSubName, resolve, sel, &_SelList) > 0;
1946 }
1947
1948 bool SelectionSingleton::isSelected(
1949 App::DocumentObject* pObject,
1950 const char* pSubName,
1951 ResolveMode resolve
1952 ) const
1953 {
1954 if (!pObject || !pObject->isAttachedToDocument() || !pObject->getDocument()) {
1955 return false;
1956 }
1957 _SelObj sel;
1958 return checkSelection(
1959 pObject->getDocument()->getName(),
1960 pObject->getNameInDocument(),
1961 pSubName,
1962 resolve,
1963 sel,
1964 &_SelList
1965 )
1966 > 0;
1967 }
1968
1969 int SelectionSingleton::checkSelection(
1970 const char* pDocName,
1971 const char* pObjectName,
1972 const char* pSubName,
1973 ResolveMode resolve,
1974 _SelObj& sel,
1975 const std::list<_SelObj>* selList
1976 ) const
1977 {
1978 sel.pDoc = getDocument(pDocName);
1979 if (!sel.pDoc) {
1980 if (!selList) {
1981 FC_ERR("Cannot find document");
1982 }
1983 return -1;
1984 }
1985 pDocName = sel.pDoc->getName();
1986 sel.DocName = pDocName;
1987
1988 if (pObjectName) {
1989 sel.pObject = sel.pDoc->getObject(pObjectName);
1990 }
1991 else {
1992 sel.pObject = nullptr;
1993 }
1994 if (!sel.pObject) {
1995 if (!selList) {
1996 FC_ERR("Object not found");
1997 }
1998 return -1;
1999 }
2000 if (sel.pObject->testStatus(App::ObjectStatus::Remove)) {
2001 return -1;
2002 }
2003 if (pSubName) {
2004 sel.SubName = pSubName;
2005 }
2006 if (resolve == ResolveMode::NoResolve) {
2007 TreeWidget::checkTopParent(sel.pObject, sel.SubName);
2008 }
2009 pSubName = !sel.SubName.empty() ? sel.SubName.c_str() : nullptr;
2010 sel.FeatName = sel.pObject->getNameInDocument();
2011 sel.TypeName = sel.pObject->getTypeId().getName();
2012 const char* element = nullptr;
2013 sel.pResolvedObject = App::GeoFeature::resolveElement(
2014 sel.pObject,
2015 pSubName,
2016 sel.elementName,
2017 false,
2018 App::GeoFeature::Normal,
2019 nullptr,
2020 &element
2021 );
2022 if (!sel.pResolvedObject) {
2023 if (!selList) {
2024 FC_ERR(
2025 "Sub-object " << sel.DocName << '#' << sel.FeatName << '.' << sel.SubName << " not found"
2026 );
2027 }
2028 return -1;
2029 }
2030 if (sel.pResolvedObject->testStatus(App::ObjectStatus::Remove)) {
2031 return -1;
2032 }
2033 std::string subname;
2034 std::string prefix;
2035 if (pSubName && element) {
2036 prefix = std::string(pSubName, element - pSubName);
2037 if (!sel.elementName.newName.empty()) {
2038 // make sure the selected sub name is a new style if available
2039 subname = prefix + sel.elementName.newName;
2040 pSubName = subname.c_str();
2041 sel.SubName = subname;
2042 }
2043 }
2044 if (!selList) {
2045 selList = &_SelList;
2046 }
2047
2048 if (!pSubName) {
2049 pSubName = "";
2050 }
2051
2052 for (auto& s : *selList) {
2053 if (s.DocName == pDocName && s.FeatName == sel.FeatName) {
2054 if (s.SubName == pSubName) {
2055 return 1;
2056 }
2057 if (resolve > ResolveMode::OldStyleElement && boost::starts_with(s.SubName, prefix)) {
2058 return 1;
2059 }
2060 }
2061 }
2062 if (resolve == ResolveMode::OldStyleElement) {
2063 for (auto& s : *selList) {
2064 if (s.pResolvedObject != sel.pResolvedObject) {
2065 continue;
2066 }
2067 if (!pSubName[0]) {
2068 return 1;
2069 }
2070 if (!s.elementName.newName.empty()) {
2071 if (s.elementName.newName == sel.elementName.newName) {
2072 return 1;
2073 }
2074 }
2075 else if (s.SubName == sel.elementName.oldName) {
2076 return 1;
2077 }
2078 }
2079 }
2080 return 0;
2081 }
2082
2083 const char* SelectionSingleton::getSelectedElement(App::DocumentObject* obj, const char* pSubName) const
2084 {
2085 if (!obj) {
2086 return nullptr;
2087 }
2088
2089 for (list<_SelObj>::const_iterator It = _SelList.begin(); It != _SelList.end(); ++It) {
2090 if (It->pObject == obj) {
2091 auto len = It->SubName.length();
2092 if (!len) {
2093 return "";
2094 }
2095 if (pSubName && strncmp(pSubName, It->SubName.c_str(), It->SubName.length()) == 0) {
2096 if (pSubName[len] == 0 || pSubName[len - 1] == '.') {
2097 return It->SubName.c_str();
2098 }
2099 }
2100 }
2101 }
2102 return nullptr;
2103 }
2104
2105 void SelectionSingleton::slotDeletedObject(const App::DocumentObject& Obj)
2106 {
2107 if (!Obj.isAttachedToDocument()) {
2108 return;
2109 }
2110
2111 // For safety reason, don't bother checking
2112 rmvPreselect();
2113
2114 // Remove also from the selection, if selected
2115 // We don't walk down the hierarchy for each selection, so there may be stray selection
2116 std::vector<SelectionChanges> changes;
2117 for (auto it = _SelList.begin(), itNext = it; it != _SelList.end(); it = itNext) {
2118 ++itNext;
2119 if (it->pResolvedObject == &Obj || it->pObject == &Obj) {
2120 changes.emplace_back(
2121 SelectionChanges::RmvSelection,
2122 it->DocName,
2123 it->FeatName,
2124 it->SubName,
2125 it->TypeName
2126 );
2127 _SelList.erase(it);
2128 }
2129 }
2130 if (!changes.empty()) {
2131 for (auto& Chng : changes) {
2132 FC_LOG(
2133 "Rmv Selection " << Chng.pDocName << '#' << Chng.pObjectName << '.' << Chng.pSubName
2134 );
2135 notify(std::move(Chng));
2136 }
2137 getMainWindow()->updateActions();
2138 }
2139
2140 if (!_PickedList.empty()) {
2141 bool changed = false;
2142 for (auto it = _PickedList.begin(), itNext = it; it != _PickedList.end(); it = itNext) {
2143 ++itNext;
2144 auto& sel = *it;
2145 if (sel.DocName == Obj.getDocument()->getName()
2146 && sel.FeatName == Obj.getNameInDocument()) {
2147 changed = true;
2148 _PickedList.erase(it);
2149 }
2150 }
2151 if (changed) {
2152 notify(SelectionChanges(SelectionChanges::PickedListChanged));
2153 }
2154 }
2155 }
2156
2157 void SelectionSingleton::setSelectionStyle(SelectionStyle selStyle)
2158 {
2159 selectionStyle = selStyle;
2160 }
2161
2162 SelectionSingleton::SelectionStyle SelectionSingleton::getSelectionStyle()
2163 {
2164 return selectionStyle;
2165 }
2166
2167 //**************************************************************************
2168 // Construction/Destruction
2169
2170 /**
2171 * A constructor.
2172 * A more elaborate description of the constructor.
2173 */
2174 SelectionSingleton::SelectionSingleton()
2175 : CurrentPreselection(SelectionChanges::ClrSelection)
2176 , selectionStyle(SelectionStyle::NormalSelection)
2177 {
2178 hx = 0;
2179 hy = 0;
2180 hz = 0;
2181 ActiveGate = nullptr;
2182 gateResolve = ResolveMode::OldStyleElement;
2183 // NOLINTBEGIN
2184 App::GetApplication().signalDeletedObject.connect(
2185 std::bind(&Gui::SelectionSingleton::slotDeletedObject, this, sp::_1)
2186 );
2187 signalSelectionChanged.connect(
2188 std::bind(&Gui::SelectionSingleton::slotSelectionChanged, this, sp::_1)
2189 );
2190 // NOLINTEND
2191 }
2192
2193 /**
2194 * A destructor.
2195 * A more elaborate description of the destructor.
2196 */
2197 SelectionSingleton::~SelectionSingleton() = default;
2198
2199 SelectionSingleton* SelectionSingleton::_pcSingleton = nullptr;
2200
2201 SelectionSingleton& SelectionSingleton::instance()
2202 {
2203 if (!_pcSingleton) {
2204 _pcSingleton = new SelectionSingleton;
2205 }
2206 return *_pcSingleton;
2207 }
2208
2209 void SelectionSingleton::destruct()
2210 {
2211 if (_pcSingleton) {
2212 delete _pcSingleton;
2213 }
2214 _pcSingleton = nullptr;
2215 }
2216
2217 //**************************************************************************
2218 // Python stuff
2219
2220 // SelectionSingleton Methods // Methods structure
2221 PyMethodDef SelectionSingleton::Methods[] = {
2222 {"addSelection",
2223 (PyCFunction)SelectionSingleton::sAddSelection,
2224 METH_VARARGS,
2225 "addSelection(docName, objName, subName, x=0, y=0, z=0, clear=True) -> None\n"
2226 "addSelection(obj, subName, x=0, y=0, z=0, clear=True) -> None\n"
2227 "addSelection(obj, subNames, clear=True) -> None\n"
2228 "\n"
2229 "Add an object to the selection.\n"
2230 "\n"
2231 "docName : str\n Name of the `App.Document`.\n"
2232 "objName : str\n Name of the `App.DocumentObject` to add.\n"
2233 "obj : App.DocumentObject\n Object to add.\n"
2234 "subName : str\n Subelement name.\n"
2235 "x : float\n Coordinate `x` of the point to pick.\n"
2236 "y : float\n Coordinate `y` of the point to pick.\n"
2237 "z : float\n Coordinate `z` of the point to pick.\n"
2238 "subNames : list of str\n List of subelement names.\n"
2239 "clear : bool\n Clear preselection."},
2240 {"updateSelection",
2241 (PyCFunction)SelectionSingleton::sUpdateSelection,
2242 METH_VARARGS,
2243 "updateSelection(show, obj, subName) -> None\n"
2244 "\n"
2245 "Update an object in the selection.\n"
2246 "\n"
2247 "show : bool\n Show or hide the selection.\n"
2248 "obj : App.DocumentObject\n Object to update.\n"
2249 "subName : str\n Name of the subelement to update."},
2250 {"removeSelection",
2251 (PyCFunction)SelectionSingleton::sRemoveSelection,
2252 METH_VARARGS,
2253 "removeSelection(obj, subName) -> None\n"
2254 "removeSelection(docName, objName, subName) -> None\n"
2255 "\n"
2256 "Remove an object from the selection.\n"
2257 "\n"
2258 "docName : str\n Name of the `App.Document`.\n"
2259 "objName : str\n Name of the `App.DocumentObject` to remove.\n"
2260 "obj : App.DocumentObject\n Object to remove.\n"
2261 "subName : str\n Name of the subelement to remove."},
2262 {"clearSelection",
2263 (PyCFunction)SelectionSingleton::sClearSelection,
2264 METH_VARARGS,
2265 "clearSelection(docName, clearPreSelect=True) -> None\n"
2266 "clearSelection(clearPreSelect=True) -> None\n"
2267 "\n"
2268 "Clear the selection in the given document. If no document is\n"
2269 "given the complete selection is cleared.\n"
2270 "\n"
2271 "docName : str\n Name of the `App.Document`.\n"
2272 "clearPreSelect : bool\n Clear preselection."},
2273 {"isSelected",
2274 (PyCFunction)SelectionSingleton::sIsSelected,
2275 METH_VARARGS,
2276 "isSelected(obj, subName, resolve=ResolveMode.OldStyleElement) -> bool\n"
2277 "\n"
2278 "Check if a given object is selected.\n"
2279 "\n"
2280 "obj : App.DocumentObject\n Object to check.\n"
2281 "subName : str\n Name of the subelement.\n"
2282 "resolve : int\n Resolve subelement reference."},
2283 {"setPreselection",
2284 reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(SelectionSingleton::sSetPreselection)),
2285 METH_VARARGS | METH_KEYWORDS,
2286 "setPreselection(obj, subName, x=0, y=0, z=0, type=1) -> None\n"
2287 "\n"
2288 "Set preselected object.\n"
2289 "\n"
2290 "obj : App.DocumentObject\n Object to preselect.\n"
2291 "subName : str\n Subelement name.\n"
2292 "x : float\n Coordinate `x` of the point to preselect.\n"
2293 "y : float\n Coordinate `y` of the point to preselect.\n"
2294 "z : float\n Coordinate `z` of the point to preselect.\n"
2295 "type : int"},
2296 {"getPreselection",
2297 (PyCFunction)SelectionSingleton::sGetPreselection,
2298 METH_VARARGS,
2299 "getPreselection() -> Gui.SelectionObject\n"
2300 "\n"
2301 "Get preselected object."},
2302 {"clearPreselection",
2303 (PyCFunction)SelectionSingleton::sRemPreselection,
2304 METH_VARARGS,
2305 "clearPreselection() -> None\n"
2306 "\n"
2307 "Clear the preselection."},
2308 {"countObjectsOfType",
2309 (PyCFunction)SelectionSingleton::sCountObjectsOfType,
2310 METH_VARARGS,
2311 "countObjectsOfType(type, docName, resolve=ResolveMode.OldStyleElement) -> int\n"
2312 "\n"
2313 "Get the number of selected objects. If no document name is given the\n"
2314 "active document is used and '*' means all documents.\n"
2315 "\n"
2316 "type : str\n Object type id name.\n"
2317 "docName : str\n Name of the `App.Document`.\n"
2318 "resolve : int"},
2319 {"getSelection",
2320 (PyCFunction)SelectionSingleton::sGetSelection,
2321 METH_VARARGS,
2322 "getSelection(docName, resolve=ResolveMode.OldStyleElement, single=False) -> list\n"
2323 "\n"
2324 "Return a list of selected objects. If no document name is given\n"
2325 "the active document is used and '*' means all documents.\n"
2326 "\n"
2327 "docName : str\n Name of the `App.Document`.\n"
2328 "resolve : int\n Resolve the subname references.\n"
2329 " 0: do not resolve, 1: resolve, 2: resolve with element map.\n"
2330 "single : bool\n Only return if there is only one selection."},
2331 {"getPickedList",
2332 (PyCFunction)SelectionSingleton::sGetPickedList,
2333 1,
2334 "getPickedList(docName) -> list of Gui.SelectionObject\n"
2335 "\n"
2336 "Return a list of SelectionObjects generated by the last mouse click.\n"
2337 "If no document name is given the active document is used and '*'\n"
2338 "means all documents.\n"
2339 "\n"
2340 "docName : str\n Name of the `App.Document`."},
2341 {"enablePickedList",
2342 (PyCFunction)SelectionSingleton::sEnablePickedList,
2343 METH_VARARGS,
2344 "enablePickedList(enable=True) -> None\n"
2345 "\n"
2346 "Enable/disable pick list.\n"
2347 "\n"
2348 "enable : bool"},
2349 {"getCompleteSelection",
2350 (PyCFunction)SelectionSingleton::sGetCompleteSelection,
2351 METH_VARARGS,
2352 "getCompleteSelection(resolve=ResolveMode.OldStyleElement) -> list\n"
2353 "\n"
2354 "Return a list of selected objects across all documents.\n"
2355 "\n"
2356 "resolve : int"},
2357 {"getSelectionEx",
2358 (PyCFunction)SelectionSingleton::sGetSelectionEx,
2359 METH_VARARGS,
2360 "getSelectionEx(docName, resolve=ResolveMode.OldStyleElement, single=False) -> list of "
2361 "Gui.SelectionObject\n"
2362 "\n"
2363 "Return a list of SelectionObjects. If no document name is given the\n"
2364 "active document is used and '*' means all documents.\n"
2365 "The SelectionObjects contain a variety of information about the selection,\n"
2366 "e.g. subelement names.\n"
2367 "\n"
2368 "docName : str\n Name of the `App.Document`.\n"
2369 "resolve : int\n Resolve the subname references.\n"
2370 " 0: do not resolve, 1: resolve, 2: resolve with element map.\n"
2371 "single : bool\n Only return if there is only one selection."},
2372 {"getSelectionObject",
2373 (PyCFunction)SelectionSingleton::sGetSelectionObject,
2374 METH_VARARGS,
2375 "getSelectionObject(docName, objName, subName, point) -> Gui.SelectionObject\n"
2376 "\n"
2377 "Return a SelectionObject.\n"
2378 "\n"
2379 "docName : str\n Name of the `App.Document`.\n"
2380 "objName : str\n Name of the `App.DocumentObject` to select.\n"
2381 "subName : str\n Subelement name.\n"
2382 "point : tuple\n Coordinates of the point to pick."},
2383 {"setSelectionStyle",
2384 (PyCFunction)SelectionSingleton::sSetSelectionStyle,
2385 METH_VARARGS,
2386 "setSelectionStyle(selectionStyle) -> None\n"
2387 "\n"
2388 "Change the selection style. 0 for normal selection, 1 for greedy selection\n"
2389 "\n"
2390 "selectionStyle : int"},
2391 {"addObserver",
2392 (PyCFunction)SelectionSingleton::sAddSelObserver,
2393 METH_VARARGS,
2394 "addObserver(object, resolve=ResolveMode.OldStyleElement) -> None\n"
2395 "\n"
2396 "Install an observer.\n"
2397 "\n"
2398 "object : object\n Python object instance.\n"
2399 "resolve : int"},
2400 {"removeObserver",
2401 (PyCFunction)SelectionSingleton::sRemSelObserver,
2402 METH_VARARGS,
2403 "removeObserver(object) -> None\n"
2404 "\n"
2405 "Uninstall an observer.\n"
2406 "\n"
2407 "object : object\n Python object instance."},
2408 {"addSelectionGate",
2409 (PyCFunction)SelectionSingleton::sAddSelectionGate,
2410 METH_VARARGS,
2411 "addSelectionGate(filter, resolve=ResolveMode.OldStyleElement) -> None\n"
2412 "\n"
2413 "Activate the selection gate.\n"
2414 "The selection gate will prohibit all selections that do not match\n"
2415 "the given selection criteria.\n"
2416 "\n"
2417 "filter : str, SelectionFilter, object\n"
2418 "resolve : int\n"
2419 "\n"
2420 "Examples strings are:\n"
2421 "Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Edge')\n"
2422 "Gui.Selection.addSelectionGate('SELECT Robot::RobotObject')\n"
2423 "\n"
2424 "An instance of SelectionFilter can also be set:\n"
2425 "filter = Gui.Selection.Filter('SELECT Part::Feature SUBELEMENT Edge')\n"
2426 "Gui.Selection.addSelectionGate(filter)\n"
2427 "\n"
2428 "The most flexible approach is to write a selection gate class that\n"
2429 "implements the method 'allow':\n"
2430 "class Gate:\n"
2431 " def allow(self,doc,obj,sub):\n"
2432 " return (sub[0:4] == 'Face')\n"
2433 "Gui.Selection.addSelectionGate(Gate())"},
2434 {"removeSelectionGate",
2435 (PyCFunction)SelectionSingleton::sRemoveSelectionGate,
2436 METH_VARARGS,
2437 "removeSelectionGate() -> None\n"
2438 "\n"
2439 "Remove the active selection gate."},
2440 {"setVisible",
2441 (PyCFunction)SelectionSingleton::sSetVisible,
2442 METH_VARARGS,
2443 "setVisible(visible=None) -> None\n"
2444 "\n"
2445 "Set visibility of all selection items.\n"
2446 "\n"
2447 "visible : bool, None\n If None, then toggle visibility."},
2448 {"pushSelStack",
2449 (PyCFunction)SelectionSingleton::sPushSelStack,
2450 METH_VARARGS,
2451 "pushSelStack(clearForward=True, overwrite=False) -> None\n"
2452 "\n"
2453 "Push current selection to stack.\n"
2454 "\n"
2455 "clearForward : bool\n Clear the forward selection stack.\n"
2456 "overwrite : bool\n Overwrite the top back selection stack with current selection."},
2457 {"hasSelection",
2458 (PyCFunction)SelectionSingleton::sHasSelection,
2459 METH_VARARGS,
2460 "hasSelection(docName, resolve=ResolveMode.NoResolve) -> bool\n"
2461 "\n"
2462 "Check if there is any selection. If no document name is given,\n"
2463 "checks selections in all documents.\n"
2464 "\n"
2465 "docName : str\n Name of the `App.Document`.\n"
2466 "resolve : int"},
2467 {"hasSubSelection",
2468 (PyCFunction)SelectionSingleton::sHasSubSelection,
2469 METH_VARARGS,
2470 "hasSubSelection(docName, subElement=False) -> bool\n"
2471 "\n"
2472 "Check if there is any selection with subname. If no document name\n"
2473 "is given the active document is used and '*' means all documents.\n"
2474 "\n"
2475 "docName : str\n Name of the `App.Document`.\n"
2476 "subElement : bool"},
2477 {"getSelectionFromStack",
2478 (PyCFunction)SelectionSingleton::sGetSelectionFromStack,
2479 METH_VARARGS,
2480 "getSelectionFromStack(docName, resolve=ResolveMode.OldStyleElement, index=0) -> list of "
2481 "Gui.SelectionObject\n"
2482 "\n"
2483 "Return SelectionObjects from selection stack. If no document name is given\n"
2484 "the active document is used and '*' means all documents.\n"
2485 "\n"
2486 "docName : str\n Name of the `App.Document`.\n"
2487 "resolve : int\n Resolve the subname references.\n"
2488 " 0: do not resolve, 1: resolve, 2: resolve with element map.\n"
2489 "index : int\n Select stack index.\n"
2490 " 0: last pushed selection, > 0: trace back, < 0: trace forward."},
2491 {nullptr, nullptr, 0, nullptr} /* Sentinel */
2492 };
2493
2494 PyObject* SelectionSingleton::sAddSelection(PyObject* /*self*/, PyObject* args)
2495 {
2496 SelectionLogDisabler disabler(true);
2497 PyObject* clearPreselect = Py_True;
2498 char* objname;
2499 char* docname;
2500 char* subname = nullptr;
2501 float x = 0, y = 0, z = 0;
2502 if (PyArg_ParseTuple(args, "ss|sfffO!", &docname, &objname, &subname, &x, &y, &z, &PyBool_Type, &clearPreselect)) {
2503 Selection()
2504 .addSelection(docname, objname, subname, x, y, z, nullptr, Base::asBoolean(clearPreselect));
2505 Py_Return;
2506 }
2507
2508 PyErr_Clear();
2509 PyObject* object;
2510 subname = nullptr;
2511 x = 0, y = 0, z = 0;
2512 if (PyArg_ParseTuple(
2513 args,
2514 "O!|sfffO!",
2515 &(App::DocumentObjectPy::Type),
2516 &object,
2517 &subname,
2518 &x,
2519 &y,
2520 &z,
2521 &PyBool_Type,
2522 &clearPreselect
2523 )) {
2524 auto docObjPy = static_cast<App::DocumentObjectPy*>(object);
2525 App::DocumentObject* docObj = docObjPy->getDocumentObjectPtr();
2526 if (!docObj || !docObj->isAttachedToDocument()) {
2527 PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot check invalid object");
2528 return nullptr;
2529 }
2530
2531 Selection().addSelection(
2532 docObj->getDocument()->getName(),
2533 docObj->getNameInDocument(),
2534 subname,
2535 x,
2536 y,
2537 z,
2538 nullptr,
2539 Base::asBoolean(clearPreselect)
2540 );
2541 Py_Return;
2542 }
2543
2544 PyErr_Clear();
2545 PyObject* sequence;
2546 if (PyArg_ParseTuple(
2547 args,
2548 "O!O|O!",
2549 &(App::DocumentObjectPy::Type),
2550 &object,
2551 &sequence,
2552 &PyBool_Type,
2553 &clearPreselect
2554 )) {
2555 auto docObjPy = static_cast<App::DocumentObjectPy*>(object);
2556 App::DocumentObject* docObj = docObjPy->getDocumentObjectPtr();
2557 if (!docObj || !docObj->isAttachedToDocument()) {
2558 PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot check invalid object");
2559 return nullptr;
2560 }
2561
2562 try {
2563 if (PyTuple_Check(sequence) || PyList_Check(sequence)) {
2564 Py::Sequence list(sequence);
2565 for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
2566 std::string subname = static_cast<std::string>(Py::String(*it));
2567 Selection().addSelection(
2568 docObj->getDocument()->getName(),
2569 docObj->getNameInDocument(),
2570 subname.c_str(),
2571 0,
2572 0,
2573 0,
2574 nullptr,
2575 Base::asBoolean(clearPreselect)
2576 );
2577 }
2578 Py_Return;
2579 }
2580 }
2581 catch (const Py::Exception&) {
2582 // do nothing here
2583 }
2584 }
2585
2586 PyErr_SetString(PyExc_ValueError, "type must be 'DocumentObject[,subname[,x,y,z]]' or 'DocumentObject, list or tuple of subnames'");
2587
2588 return nullptr;
2589 }
2590
2591 PyObject* SelectionSingleton::sUpdateSelection(PyObject* /*self*/, PyObject* args)
2592 {
2593 PyObject* show;
2594 PyObject* object;
2595 char* subname = nullptr;
2596 if (!PyArg_ParseTuple(
2597 args,
2598 "O!O!|s",
2599 &PyBool_Type,
2600 &show,
2601 &(App::DocumentObjectPy::Type),
2602 &object,
2603 &subname
2604 )) {
2605 return nullptr;
2606 }
2607
2608 auto docObjPy = static_cast<App::DocumentObjectPy*>(object);
2609 App::DocumentObject* docObj = docObjPy->getDocumentObjectPtr();
2610 if (!docObj || !docObj->isAttachedToDocument()) {
2611 PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot check invalid object");
2612 return nullptr;
2613 }
2614
2615 Selection().updateSelection(
2616 Base::asBoolean(show),
2617 docObj->getDocument()->getName(),
2618 docObj->getNameInDocument(),
2619 subname
2620 );
2621
2622 Py_Return;
2623 }
2624
2625
2626 PyObject* SelectionSingleton::sRemoveSelection(PyObject* /*self*/, PyObject* args)
2627 {
2628 SelectionLogDisabler disabler(true);
2629 char *docname, *objname;
2630 char* subname = nullptr;
2631 if (PyArg_ParseTuple(args, "ss|s", &docname, &objname, &subname)) {
2632 Selection().rmvSelection(docname, objname, subname);
2633 Py_Return;
2634 }
2635
2636 PyErr_Clear();
2637 PyObject* object;
2638 subname = nullptr;
2639 if (!PyArg_ParseTuple(args, "O!|s", &(App::DocumentObjectPy::Type), &object, &subname)) {
2640 return nullptr;
2641 }
2642
2643 auto docObjPy = static_cast<App::DocumentObjectPy*>(object);
2644 App::DocumentObject* docObj = docObjPy->getDocumentObjectPtr();
2645 if (!docObj || !docObj->isAttachedToDocument()) {
2646 PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot check invalid object");
2647 return nullptr;
2648 }
2649
2650 Selection().rmvSelection(docObj->getDocument()->getName(), docObj->getNameInDocument(), subname);
2651
2652 Py_Return;
2653 }
2654
2655 PyObject* SelectionSingleton::sClearSelection(PyObject* /*self*/, PyObject* args)
2656 {
2657 SelectionLogDisabler disabler(true);
2658 PyObject* clearPreSelect = Py_True;
2659 char* documentName = nullptr;
2660 if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &clearPreSelect)) {
2661 PyErr_Clear();
2662 if (!PyArg_ParseTuple(args, "|sO!", &documentName, &PyBool_Type, &clearPreSelect)) {
2663 return nullptr;
2664 }
2665 }
2666 Selection().clearSelection(documentName, Base::asBoolean(clearPreSelect));
2667
2668 Py_Return;
2669 }
2670
2671 namespace
2672 {
2673 ResolveMode toEnum(int value)
2674 {
2675 switch (value) {
2676 case 0:
2677 return ResolveMode::NoResolve;
2678 case 1:
2679 return ResolveMode::OldStyleElement;
2680 case 2:
2681 return ResolveMode::NewStyleElement;
2682 case 3:
2683 return ResolveMode::FollowLink;
2684 default:
2685 throw Base::ValueError("Wrong enum value");
2686 }
2687 }
2688 } // namespace
2689
2690 PyObject* SelectionSingleton::sIsSelected(PyObject* /*self*/, PyObject* args)
2691 {
2692 PyObject* object;
2693 char* subname = nullptr;
2694 int resolve = 1;
2695 if (!PyArg_ParseTuple(args, "O!|si", &(App::DocumentObjectPy::Type), &object, &subname, &resolve)) {
2696 return nullptr;
2697 }
2698
2699 try {
2700 auto docObj = static_cast<App::DocumentObjectPy*>(object);
2701 bool ok = Selection().isSelected(docObj->getDocumentObjectPtr(), subname, toEnum(resolve));
2702
2703 return Py_BuildValue("O", (ok ? Py_True : Py_False));
2704 }
2705 catch (const Base::Exception& e) {
2706 e.setPyException();
2707 return nullptr;
2708 }
2709 }
2710
2711 PyObject* SelectionSingleton::sCountObjectsOfType(PyObject* /*self*/, PyObject* args)
2712 {
2713 char* objecttype;
2714 char* document = nullptr;
2715 int resolve = 1;
2716 if (!PyArg_ParseTuple(args, "s|si", &objecttype, &document, &resolve)) {
2717 return nullptr;
2718 }
2719
2720 try {
2721 unsigned int count = Selection().countObjectsOfType(objecttype, document, toEnum(resolve));
2722 return PyLong_FromLong(count);
2723 }
2724 catch (const Base::Exception& e) {
2725 e.setPyException();
2726 return nullptr;
2727 }
2728 }
2729
2730 PyObject* SelectionSingleton::sGetSelection(PyObject* /*self*/, PyObject* args)
2731 {
2732 char* documentName = nullptr;
2733 int resolve = 1;
2734 PyObject* single = Py_False;
2735 if (!PyArg_ParseTuple(args, "|siO!", &documentName, &resolve, &PyBool_Type, &single)) {
2736 return nullptr;
2737 }
2738
2739 try {
2740 std::vector<SelectionSingleton::SelObj> sel;
2741 sel = Selection().getSelection(documentName, toEnum(resolve), Base::asBoolean(single));
2742
2743 std::set<App::DocumentObject*> noduplicates;
2744 std::vector<App::DocumentObject*> selectedObjects; // keep the order of selection
2745 Py::List list;
2746 for (const auto& it : sel) {
2747 if (noduplicates.insert(it.pObject).second) {
2748 selectedObjects.push_back(it.pObject);
2749 }
2750 }
2751 for (const auto& selectedObject : selectedObjects) {
2752 list.append(Py::asObject(selectedObject->getPyObject()));
2753 }
2754 return Py::new_reference_to(list);
2755 }
2756 catch (const Base::Exception& e) {
2757 e.setPyException();
2758 return nullptr;
2759 }
2760 catch (Py::Exception&) {
2761 return nullptr;
2762 }
2763 }
2764
2765 PyObject* SelectionSingleton::sEnablePickedList(PyObject* /*self*/, PyObject* args)
2766 {
2767 PyObject* enable = Py_True;
2768 if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &enable)) {
2769 return nullptr;
2770 }
2771
2772 Selection().enablePickedList(Base::asBoolean(enable));
2773
2774 Py_Return;
2775 }
2776
2777 PyObject* SelectionSingleton::sSetPreselection(PyObject* /*self*/, PyObject* args, PyObject* kwd)
2778 {
2779 PyObject* object;
2780 const char* subname = nullptr;
2781 float x = 0, y = 0, z = 0;
2782 int type = 1;
2783 static const std::array<const char*, 7> kwlist {"obj", "subname", "x", "y", "z", "tp", nullptr};
2784 if (Base::Wrapped_ParseTupleAndKeywords(
2785 args,
2786 kwd,
2787 "O!|sfffi",
2788 kwlist,
2789 &(App::DocumentObjectPy::Type),
2790 &object,
2791 &subname,
2792 &x,
2793 &y,
2794 &z,
2795 &type
2796 )) {
2797 auto docObjPy = static_cast<App::DocumentObjectPy*>(object);
2798 App::DocumentObject* docObj = docObjPy->getDocumentObjectPtr();
2799 if (!docObj || !docObj->isAttachedToDocument()) {
2800 PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot check invalid object");
2801 return nullptr;
2802 }
2803
2804 Selection().setPreselect(
2805 docObj->getDocument()->getName(),
2806 docObj->getNameInDocument(),
2807 subname,
2808 x,
2809 y,
2810 z,
2811 static_cast<SelectionChanges::MsgSource>(type)
2812 );
2813 Py_Return;
2814 }
2815
2816 PyErr_SetString(PyExc_ValueError, "type must be 'DocumentObject[,subname[,x,y,z]]'");
2817
2818 return nullptr;
2819 }
2820
2821 PyObject* SelectionSingleton::sGetPreselection(PyObject* /*self*/, PyObject* args)
2822 {
2823 if (!PyArg_ParseTuple(args, "")) {
2824 return nullptr;
2825 }
2826
2827 const SelectionChanges& sel = Selection().getPreselection();
2828 SelectionObject obj(sel);
2829
2830 return obj.getPyObject();
2831 }
2832
2833 PyObject* SelectionSingleton::sRemPreselection(PyObject* /*self*/, PyObject* args)
2834 {
2835 if (!PyArg_ParseTuple(args, "")) {
2836 return nullptr;
2837 }
2838
2839 Selection().rmvPreselect();
2840
2841 Py_Return;
2842 }
2843
2844 PyObject* SelectionSingleton::sGetCompleteSelection(PyObject* /*self*/, PyObject* args)
2845 {
2846 int resolve = 1;
2847 if (!PyArg_ParseTuple(args, "|i", &resolve)) {
2848 return nullptr;
2849 }
2850
2851 try {
2852 std::vector<SelectionSingleton::SelObj> sel;
2853 sel = Selection().getCompleteSelection(toEnum(resolve));
2854
2855 Py::List list;
2856 for (const auto& it : sel) {
2857 SelectionObject obj(SelectionChanges(
2858 SelectionChanges::AddSelection,
2859 it.DocName,
2860 it.FeatName,
2861 it.SubName,
2862 it.TypeName,
2863 it.x,
2864 it.y,
2865 it.z
2866 ));
2867 list.append(Py::asObject(obj.getPyObject()));
2868 }
2869 return Py::new_reference_to(list);
2870 }
2871 catch (const Base::Exception& e) {
2872 e.setPyException();
2873 return nullptr;
2874 }
2875 catch (Py::Exception&) {
2876 return nullptr;
2877 }
2878 }
2879
2880 PyObject* SelectionSingleton::sGetSelectionEx(PyObject* /*self*/, PyObject* args)
2881 {
2882 char* documentName = nullptr;
2883 int resolve = 1;
2884 PyObject* single = Py_False;
2885 if (!PyArg_ParseTuple(args, "|siO!", &documentName, &resolve, &PyBool_Type, &single)) {
2886 return nullptr;
2887 }
2888
2889 try {
2890 std::vector<SelectionObject> sel;
2891 sel = Selection().getSelectionEx(
2892 documentName,
2893 App::DocumentObject::getClassTypeId(),
2894 toEnum(resolve),
2895 Base::asBoolean(single)
2896 );
2897
2898 Py::List list;
2899 for (auto& it : sel) {
2900 list.append(Py::asObject(it.getPyObject()));
2901 }
2902 return Py::new_reference_to(list);
2903 }
2904 catch (const Base::Exception& e) {
2905 e.setPyException();
2906 return nullptr;
2907 }
2908 catch (Py::Exception&) {
2909 return nullptr;
2910 }
2911 }
2912
2913 PyObject* SelectionSingleton::sGetPickedList(PyObject* /*self*/, PyObject* args)
2914 {
2915 char* documentName = nullptr;
2916 if (!PyArg_ParseTuple(args, "|s", &documentName)) {
2917 return nullptr;
2918 }
2919
2920 std::vector<SelectionObject> sel;
2921 sel = Selection().getPickedListEx(documentName);
2922
2923 try {
2924 Py::List list;
2925 for (auto& it : sel) {
2926 list.append(Py::asObject(it.getPyObject()));
2927 }
2928 return Py::new_reference_to(list);
2929 }
2930 catch (Py::Exception&) {
2931 return nullptr;
2932 }
2933 }
2934
2935 PyObject* SelectionSingleton::sGetSelectionObject(PyObject* /*self*/, PyObject* args)
2936 {
2937 char *docName, *objName, *subName;
2938 PyObject* tuple = nullptr;
2939 if (!PyArg_ParseTuple(args, "sss|O!", &docName, &objName, &subName, &PyTuple_Type, &tuple)) {
2940 return nullptr;
2941 }
2942
2943 try {
2944 SelectionObject selObj;
2945 selObj.DocName = docName;
2946 selObj.FeatName = objName;
2947 std::string sub = subName;
2948 if (!sub.empty()) {
2949 selObj.SubNames.push_back(sub);
2950 if (tuple) {
2951 Py::Tuple t(tuple);
2952 double x = (double)Py::Float(t.getItem(0));
2953 double y = (double)Py::Float(t.getItem(1));
2954 double z = (double)Py::Float(t.getItem(2));
2955 selObj.SelPoses.emplace_back(x, y, z);
2956 }
2957 }
2958
2959 return selObj.getPyObject();
2960 }
2961 catch (const Py::Exception&) {
2962 return nullptr;
2963 }
2964 catch (const Base::Exception& e) {
2965 e.setPyException();
2966 return nullptr;
2967 }
2968 }
2969
2970 PyObject* SelectionSingleton::sSetSelectionStyle(PyObject* /*self*/, PyObject* args)
2971 {
2972 int selStyle = 0;
2973 if (!PyArg_ParseTuple(args, "i", &selStyle)) {
2974 return nullptr;
2975 }
2976
2977 PY_TRY
2978 {
2979 Selection().setSelectionStyle(
2980 selStyle == 0 ? SelectionStyle::NormalSelection : SelectionStyle::GreedySelection
2981 );
2982 Py_Return;
2983 }
2984 PY_CATCH;
2985 }
2986
2987 PyObject* SelectionSingleton::sAddSelObserver(PyObject* /*self*/, PyObject* args)
2988 {
2989 PyObject* o;
2990 int resolve = 1;
2991 if (!PyArg_ParseTuple(args, "O|i", &o, &resolve)) {
2992 return nullptr;
2993 }
2994
2995 PY_TRY
2996 {
2997 SelectionObserverPython::addObserver(Py::Object(o), toEnum(resolve));
2998 Py_Return;
2999 }
3000 PY_CATCH;
3001 }
3002
3003 PyObject* SelectionSingleton::sRemSelObserver(PyObject* /*self*/, PyObject* args)
3004 {
3005 PyObject* o;
3006 if (!PyArg_ParseTuple(args, "O", &o)) {
3007 return nullptr;
3008 }
3009
3010 PY_TRY
3011 {
3012 SelectionObserverPython::removeObserver(Py::Object(o));
3013 Py_Return;
3014 }
3015 PY_CATCH;
3016 }
3017
3018 PyObject* SelectionSingleton::sAddSelectionGate(PyObject* /*self*/, PyObject* args)
3019 {
3020 char* filter;
3021 int resolve = 1;
3022 if (PyArg_ParseTuple(args, "s|i", &filter, &resolve)) {
3023 PY_TRY
3024 {
3025 Selection().addSelectionGate(new SelectionFilterGate(filter), toEnum(resolve));
3026 Py_Return;
3027 }
3028 PY_CATCH;
3029 }
3030
3031 PyErr_Clear();
3032 PyObject* filterPy;
3033 if (PyArg_ParseTuple(args, "O!|i", SelectionFilterPy::type_object(), &filterPy, resolve)) {
3034 PY_TRY
3035 {
3036 Selection().addSelectionGate(
3037 new SelectionFilterGatePython(SelectionFilterPy::cast(filterPy)),
3038 toEnum(resolve)
3039 );
3040 Py_Return;
3041 }
3042 PY_CATCH;
3043 }
3044
3045 PyErr_Clear();
3046 PyObject* gate;
3047 if (PyArg_ParseTuple(args, "O|i", &gate, &resolve)) {
3048 PY_TRY
3049 {
3050 Selection().addSelectionGate(
3051 new SelectionGatePython(Py::Object(gate, false)),
3052 toEnum(resolve)
3053 );
3054 Py_Return;
3055 }
3056 PY_CATCH;
3057 }
3058
3059 PyErr_SetString(PyExc_ValueError, "Argument is neither string nor SelectionFiler nor SelectionGate");
3060
3061 return nullptr;
3062 }
3063
3064 PyObject* SelectionSingleton::sRemoveSelectionGate(PyObject* /*self*/, PyObject* args)
3065 {
3066 if (!PyArg_ParseTuple(args, "")) {
3067 return nullptr;
3068 }
3069
3070 PY_TRY
3071 {
3072 Selection().rmvSelectionGate();
3073 Py_Return;
3074 }
3075 PY_CATCH;
3076 }
3077
3078 PyObject* SelectionSingleton::sSetVisible(PyObject* /*self*/, PyObject* args)
3079 {
3080 PyObject* visible = Py_None;
3081 if (!PyArg_ParseTuple(args, "|O", &visible)) {
3082 return nullptr;
3083 }
3084
3085 PY_TRY
3086 {
3087 VisibleState vis = VisToggle;
3088 Base::PyTypeCheck(&visible, &PyBool_Type);
3089 if (visible) {
3090 vis = PyObject_IsTrue(visible) ? VisShow : VisHide;
3091 }
3092
3093 Selection().setVisible(vis);
3094 Py_Return;
3095 }
3096 PY_CATCH;
3097 }
3098
3099 PyObject* SelectionSingleton::sPushSelStack(PyObject* /*self*/, PyObject* args)
3100 {
3101 PyObject* clear = Py_True;
3102 PyObject* overwrite = Py_False;
3103 if (!PyArg_ParseTuple(args, "|O!O!", &PyBool_Type, &clear, &PyBool_Type, &overwrite)) {
3104 return nullptr;
3105 }
3106
3107 Selection().selStackPush(Base::asBoolean(clear), Base::asBoolean(overwrite));
3108
3109 Py_Return;
3110 }
3111
3112 PyObject* SelectionSingleton::sHasSelection(PyObject* /*self*/, PyObject* args)
3113 {
3114 const char* doc = nullptr;
3115 int resolve = 0;
3116 if (!PyArg_ParseTuple(args, "|si", &doc, &resolve)) {
3117 return nullptr;
3118 }
3119
3120 PY_TRY
3121 {
3122 bool ret;
3123 if (doc || resolve > 0) {
3124 ret = Selection().hasSelection(doc, toEnum(resolve));
3125 }
3126 else {
3127 ret = Selection().hasSelection();
3128 }
3129
3130 return Py::new_reference_to(Py::Boolean(ret));
3131 }
3132 PY_CATCH;
3133 }
3134
3135 PyObject* SelectionSingleton::sHasSubSelection(PyObject* /*self*/, PyObject* args)
3136 {
3137 const char* doc = nullptr;
3138 PyObject* subElement = Py_False;
3139 if (!PyArg_ParseTuple(args, "|sO!", &doc, &PyBool_Type, &subElement)) {
3140 return nullptr;
3141 }
3142
3143 PY_TRY
3144 {
3145 return Py::new_reference_to(
3146 Py::Boolean(Selection().hasSubSelection(doc, Base::asBoolean(subElement)))
3147 );
3148 }
3149 PY_CATCH;
3150 }
3151
3152 PyObject* SelectionSingleton::sGetSelectionFromStack(PyObject* /*self*/, PyObject* args)
3153 {
3154 char* documentName = nullptr;
3155 int resolve = 1;
3156 int index = 0;
3157 if (!PyArg_ParseTuple(args, "|sii", &documentName, &resolve, &index)) {
3158 return nullptr;
3159 }
3160
3161 PY_TRY
3162 {
3163 Py::List list;
3164 for (auto& sel : Selection().selStackGet(documentName, toEnum(resolve), index)) {
3165 list.append(Py::asObject(sel.getPyObject()));
3166 }
3167 return Py::new_reference_to(list);
3168 }
3169 PY_CATCH;
3170 }
3171
3172 bool SelectionSingleton::isClarifySelectionActive()
3173 {
3174 return clarifySelectionActive;
3175 }
3176
3177 void SelectionSingleton::setClarifySelectionActive(bool active)
3178 {
3179 clarifySelectionActive = active;
3180 }