Debian Codegraph @

src/Gui/ViewProviderLink.cpp

raw
1 /****************************************************************************
2 * Copyright (c) 2017 Zheng Lei (realthunder) <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ****************************************************************************/
22
23
24 #include <atomic>
25 #include <cctype>
26 #include <unordered_set>
27 #include <unordered_map>
28 #include <utility>
29 #include <deque>
30 #include <memory>
31 #include <algorithm>
32 #include <vector>
33 #include <set>
34 #include <map>
35 #include <string>
36 #include <boost/algorithm/string/predicate.hpp>
37 #include <Inventor/SoPickedPoint.h>
38 #include <Inventor/actions/SoGetBoundingBoxAction.h>
39 #include <Inventor/details/SoDetail.h>
40 #include <Inventor/draggers/SoCenterballDragger.h>
41 #include <Inventor/misc/SoChildList.h>
42 #include <Inventor/nodes/SoAnnotation.h>
43 #include <Inventor/nodes/SoCube.h>
44 #include <Inventor/nodes/SoDrawStyle.h>
45 #include <Inventor/nodes/SoPickStyle.h>
46 #include <Inventor/nodes/SoSeparator.h>
47 #include <Inventor/nodes/SoShapeHints.h>
48 #include <Inventor/nodes/SoSurroundScale.h>
49 #include <Inventor/nodes/SoSwitch.h>
50 #include <Inventor/nodes/SoTransform.h>
51 #include <Inventor/sensors/SoNodeSensor.h>
52 #include <QApplication>
53 #include <QMenu>
54 #include <QCheckBox>
55
56
57 #include <boost/range.hpp>
58 #include <App/ElementNamingUtils.h>
59 #include <App/Document.h>
60 #include <Base/BoundBoxPy.h>
61 #include <Base/MatrixPy.h>
62 #include <Base/PlacementPy.h>
63 #include <Base/Tools.h>
64
65 #include "Action.h"
66 #include "MainWindow.h"
67 #include "ViewProviderLink.h"
68 #include "ViewProviderLinkPy.h"
69 #include "Application.h"
70 #include "BitmapFactory.h"
71 #include "Control.h"
72 #include "Inventor/Draggers/SoTransformDragger.h"
73 #include "LinkViewPy.h"
74 #include "Selection.h"
75 #include "SoFCUnifiedSelection.h"
76 #include "TaskTransform.h"
77 #include "TaskElementColors.h"
78 #include "View3DInventor.h"
79 #include "ViewParams.h"
80 #include "ViewProviderGeometryObject.h"
81
82 #include "ActionFunction.h"
83 #include "Command.h"
84 #include "Dialogs/DlgObjectSelection.h"
85
86 FC_LOG_LEVEL_INIT("App::Link", true, true)
87
88 using namespace Gui;
89 using namespace Base;
90
91 using CharRange = boost::iterator_range<const char*>;
92 ////////////////////////////////////////////////////////////////////////////
93
94 static inline bool appendPathSafe(SoPath* path, SoNode* node)
95 {
96 if (path->getLength()) {
97 SoNode* tail = path->getTail();
98 const SoChildList* children = tail->getChildren();
99 if (!children || children->find((void*)node) < 0) {
100 return false;
101 }
102 }
103 path->append(node);
104 return true;
105 }
106
107 #ifdef FC_DEBUG
108 # define appendPath(_path, _node) \
109 do { \
110 if (!appendPathSafe(_path, _node)) \
111 FC_ERR("LinkView: coin path error"); \
112 } while (0)
113 #else
114 # define appendPath(_path, _node) (_path)->append(_node)
115 #endif
116
117 ////////////////////////////////////////////////////////////////////////////
118 class Gui::LinkInfo
119 {
120
121 public:
122 std::atomic<int> ref;
123
124 using Connection = boost::signals2::scoped_connection;
125 Connection connChangeIcon;
126
127 ViewProviderDocumentObject* pcLinked;
128 std::unordered_set<Gui::LinkOwner*> links;
129
130 using Pointer = LinkInfoPtr;
131
132 SoNodeSensor sensor;
133 SoNodeSensor switchSensor;
134 SoNodeSensor childSensor;
135 SoNodeSensor transformSensor;
136
137 std::array<CoinPtr<SoSeparator>, LinkView::SnapshotMax> pcSnapshots;
138 std::array<CoinPtr<SoSwitch>, LinkView::SnapshotMax> pcSwitches;
139 CoinPtr<SoSwitch> pcLinkedSwitch;
140
141 // for group type view providers
142 CoinPtr<SoGroup> pcChildGroup;
143 using NodeMap = std::unordered_map<SoNode*, Pointer>;
144 NodeMap nodeMap;
145
146 std::map<qint64, QIcon> iconMap;
147
148 static ViewProviderDocumentObject* getView(App::DocumentObject* obj)
149 {
150 if (obj && obj->isAttachedToDocument()) {
151 Document* pDoc = Application::Instance->getDocument(obj->getDocument());
152 if (pDoc) {
153 ViewProvider* vp = pDoc->getViewProvider(obj);
154 if (vp && vp->isDerivedFrom<ViewProviderDocumentObject>()) {
155 return static_cast<ViewProviderDocumentObject*>(vp);
156 }
157 }
158 }
159 return nullptr;
160 }
161
162 static Pointer get(App::DocumentObject* obj, Gui::LinkOwner* owner)
163 {
164 return get(getView(obj), owner);
165 }
166
167 static Pointer get(ViewProviderDocumentObject* vp, LinkOwner* owner)
168 {
169 if (!vp) {
170 return Pointer();
171 }
172
173 auto ext = vp->getExtensionByType<ViewProviderLinkObserver>(true);
174 if (!ext) {
175 ext = new ViewProviderLinkObserver();
176 ext->initExtension(vp);
177 }
178 if (!ext->linkInfo) {
179 // extension can be created automatically when restored from document,
180 // with an empty linkInfo. So we need to check here.
181 ext->linkInfo = Pointer(new LinkInfo(vp));
182 ext->linkInfo->update();
183 }
184 if (owner) {
185 ext->linkInfo->links.insert(owner);
186 }
187 return ext->linkInfo;
188 }
189
190 static void sensorCB(void* data, SoSensor*)
191 {
192 static_cast<LinkInfo*>(data)->update();
193 }
194
195 static void switchSensorCB(void* data, SoSensor*)
196 {
197 static_cast<LinkInfo*>(data)->updateSwitch();
198 }
199
200 static void childSensorCB(void* data, SoSensor*)
201 {
202 static_cast<LinkInfo*>(data)->updateChildren();
203 }
204
205 static void transformSensorCB(void* data, SoSensor*)
206 {
207 auto self = static_cast<LinkInfo*>(data);
208 for (size_t i = 0; i < self->pcSnapshots.size(); ++i) {
209 if (self->pcSnapshots[i] && i != LinkView::SnapshotTransform) {
210 self->getSnapshot(i, true);
211 }
212 }
213 }
214
215 explicit LinkInfo(ViewProviderDocumentObject* vp)
216 : ref(0)
217 , pcLinked(vp)
218 {
219 FC_LOG("new link to " << pcLinked->getObject()->getFullName());
220 // NOLINTBEGIN
221 connChangeIcon = vp->signalChangeIcon.connect(std::bind(&LinkInfo::slotChangeIcon, this));
222 // NOLINTEND
223 vp->forceUpdate(true);
224 sensor.setFunction(sensorCB);
225 sensor.setData(this);
226 switchSensor.setFunction(switchSensorCB);
227 switchSensor.setData(this);
228 childSensor.setFunction(childSensorCB);
229 childSensor.setData(this);
230 transformSensor.setFunction(transformSensorCB);
231 transformSensor.setData(this);
232 }
233
234 ~LinkInfo() = default;
235
236 bool checkName(const char* name) const
237 {
238 return isLinked() && strcmp(name, getLinkedName()) == 0;
239 }
240
241 void remove(LinkOwner* owner)
242 {
243 links.erase(owner);
244 }
245
246 bool isLinked() const
247 {
248 return pcLinked && pcLinked->getObject() && pcLinked->getObject()->isAttachedToDocument();
249 }
250
251 const char* getLinkedName() const
252 {
253 return pcLinked->getObject()->getDagKey();
254 }
255
256 const char* getLinkedLabel() const
257 {
258 return pcLinked->getObject()->Label.getValue();
259 }
260
261 const char* getLinkedNameSafe() const
262 {
263 if (isLinked()) {
264 return getLinkedName();
265 }
266 return "<nil>";
267 }
268
269 const char* getDocName() const
270 {
271 return pcLinked->getDocument()->getDocument()->getName();
272 }
273
274 void detach(bool unlink)
275 {
276 FC_LOG("link detach " << getLinkedNameSafe());
277 auto me = LinkInfoPtr(this);
278 if (unlink) {
279 while (!links.empty()) {
280 auto link = *links.begin();
281 links.erase(links.begin());
282 link->unlink(me);
283 }
284 }
285 sensor.detach();
286 switchSensor.detach();
287 childSensor.detach();
288 transformSensor.detach();
289 for (const auto& node : pcSnapshots) {
290 if (node) {
291 coinRemoveAllChildren(node);
292 }
293 }
294 for (const auto& node : pcSwitches) {
295 if (node) {
296 coinRemoveAllChildren(node);
297 }
298 }
299 pcLinkedSwitch.reset();
300 if (pcChildGroup) {
301 coinRemoveAllChildren(pcChildGroup);
302 pcChildGroup.reset();
303 }
304 pcLinked = nullptr;
305 connChangeIcon.disconnect();
306 }
307
308 void updateSwitch(SoSwitch* node = nullptr)
309 {
310 if (!isLinked() || !pcLinkedSwitch) {
311 return;
312 }
313 int index = pcLinkedSwitch->whichChild.getValue();
314 for (size_t i = 0; i < pcSwitches.size(); ++i) {
315 if (!pcSwitches[i] || (node && node != pcSwitches[i])) {
316 continue;
317 }
318 int count = pcSwitches[i]->getNumChildren();
319 if ((index < 0 && i == LinkView::SnapshotChild) || !count) {
320 pcSwitches[i]->whichChild = SO_SWITCH_NONE;
321 }
322 else if (count > pcLinked->getDefaultMode()) {
323 pcSwitches[i]->whichChild = pcLinked->getDefaultMode();
324 }
325 else {
326 pcSwitches[i]->whichChild = 0;
327 }
328 }
329 }
330
331 inline void addref()
332 {
333 ++ref;
334 }
335
336 inline void release()
337 {
338 int r = --ref;
339 assert(r >= 0);
340 if (r == 0) {
341 delete this;
342 }
343 else if (r == 1) {
344 if (pcLinked) {
345 FC_LOG("link release " << getLinkedNameSafe());
346 auto ext = pcLinked->getExtensionByType<ViewProviderLinkObserver>(true);
347 if (ext && ext->linkInfo == this) {
348 pcLinked->forceUpdate(false);
349 detach(true);
350 ext->linkInfo.reset();
351 }
352 }
353 }
354 }
355
356 // MSVC has trouble with template argument dependent lookup in
357 // namespace. Have to put the below functions in global namespace.
358 #if defined(_MSC_VER)
359 friend void Gui::intrusive_ptr_add_ref(LinkInfo* px);
360 friend void Gui::intrusive_ptr_release(LinkInfo* px);
361 #else
362 friend inline void intrusive_ptr_add_ref(LinkInfo* px)
363 {
364 px->addref();
365 }
366 friend inline void intrusive_ptr_release(LinkInfo* px)
367 {
368 px->release();
369 }
370 #endif
371
372 bool isVisible() const
373 {
374 if (!isLinked()) {
375 return true;
376 }
377 int indices[] = {LinkView::SnapshotTransform, LinkView::SnapshotVisible};
378 for (int idx : indices) {
379 if (!pcSwitches[idx]) {
380 continue;
381 }
382 if (pcSwitches[idx]->whichChild.getValue() == SO_SWITCH_NONE) {
383 return false;
384 }
385 }
386 return true;
387 }
388
389 void setVisible(bool visible)
390 {
391 if (!isLinked()) {
392 return;
393 }
394 int indices[] = {LinkView::SnapshotTransform, LinkView::SnapshotVisible};
395 for (int idx : indices) {
396 if (!pcSwitches[idx]) {
397 continue;
398 }
399 if (!visible) {
400 pcSwitches[idx]->whichChild = SO_SWITCH_NONE;
401 }
402 else if (pcSwitches[idx]->getNumChildren() > pcLinked->getDefaultMode()) {
403 pcSwitches[idx]->whichChild = pcLinked->getDefaultMode();
404 }
405 }
406 }
407
408 SoSeparator* getSnapshot(int type, bool update = false)
409 {
410 if (type < 0 || type >= LinkView::SnapshotMax) {
411 return nullptr;
412 }
413
414 SoSeparator* root;
415 if (!isLinked() || !(root = pcLinked->getRoot())) {
416 return nullptr;
417 }
418
419 if (sensor.getAttachedNode() != root) {
420 sensor.detach();
421 sensor.attach(root);
422 }
423
424 auto& pcSnapshot = pcSnapshots[type];
425 auto& pcModeSwitch = pcSwitches[type];
426 if (pcSnapshot) {
427 if (!update) {
428 return pcSnapshot;
429 }
430 }
431 else {
432 if (ViewParams::instance()->getUseSelectionRoot()) {
433 pcSnapshot = new SoFCSelectionRoot;
434 }
435 else {
436 pcSnapshot = new SoSeparator;
437 }
438 pcSnapshot->boundingBoxCaching = SoSeparator::OFF;
439 pcSnapshot->renderCaching = SoSeparator::OFF;
440 std::ostringstream ss;
441 ss << pcLinked->getObject()->getNameInDocument() << "(" << type << ')';
442 pcSnapshot->setName(ss.str().c_str());
443 pcModeSwitch = new SoSwitch;
444 }
445
446 pcLinkedSwitch.reset();
447
448 coinRemoveAllChildren(pcSnapshot);
449 pcModeSwitch->whichChild = SO_SWITCH_NONE;
450 coinRemoveAllChildren(pcModeSwitch);
451
452 SoSwitch* pcUpdateSwitch = pcModeSwitch;
453
454 auto childRoot = pcLinked->getChildRoot();
455
456 for (int i = 0, count = root->getNumChildren(); i < count; ++i) {
457 SoNode* node = root->getChild(i);
458
459 // Exclude the linked object's pick style from the snapshot,
460 // so that the Link's own pick style is the only one in effect.
461 if (node->isOfType(SoPickStyle::getClassTypeId())) {
462 continue;
463 }
464
465 if (node == pcLinked->getTransformNode()) {
466 if (type != LinkView::SnapshotTransform) {
467 pcSnapshot->addChild(node);
468 }
469 else {
470 auto transform = pcLinked->getTransformNode();
471 const auto& scale = transform->scaleFactor.getValue();
472 if (scale[0] != 1.0 || scale[1] != 1.0 || scale[2] != 1.0) {
473 auto trans = new SoTransform;
474 pcSnapshot->addChild(trans);
475 trans->scaleFactor.setValue(scale);
476 trans->scaleOrientation = transform->scaleOrientation;
477 if (transformSensor.getAttachedNode() != transform) {
478 transformSensor.detach();
479 transformSensor.attach(transform);
480 }
481 }
482 }
483 continue;
484 }
485 else if (node != pcLinked->getModeSwitch()) {
486 pcSnapshot->addChild(node);
487 continue;
488 }
489
490 pcLinkedSwitch = static_cast<SoSwitch*>(node);
491 if (switchSensor.getAttachedNode() != pcLinkedSwitch) {
492 switchSensor.detach();
493 switchSensor.attach(pcLinkedSwitch);
494 pcUpdateSwitch = nullptr;
495 }
496
497 pcSnapshot->addChild(pcModeSwitch);
498 for (int i = 0, count = pcLinkedSwitch->getNumChildren(); i < count; ++i) {
499 auto child = pcLinkedSwitch->getChild(i);
500 if (pcChildGroup && child == childRoot) {
501 pcModeSwitch->addChild(pcChildGroup);
502 }
503 else {
504 pcModeSwitch->addChild(child);
505 }
506 }
507 }
508 updateSwitch(pcUpdateSwitch);
509 return pcSnapshot;
510 }
511
512 void updateData(const App::Property* prop)
513 {
514 LinkInfoPtr me(this);
515 for (auto link : links) {
516 link->onLinkedUpdateData(me, prop);
517 }
518 // update();
519 }
520
521 void update()
522 {
523 if (!isLinked() || pcLinked->isRestoring()) {
524 return;
525 }
526
527 updateChildren();
528
529 for (size_t i = 0; i < pcSnapshots.size(); ++i) {
530 if (pcSnapshots[i]) {
531 getSnapshot(i, true);
532 }
533 }
534 }
535
536 void updateChildren()
537 {
538 if (!isLinked()) {
539 return;
540 }
541
542 if (!pcLinked->getChildRoot()) {
543 childSensor.detach();
544 if (pcChildGroup) {
545 coinRemoveAllChildren(pcChildGroup);
546 }
547 return;
548 }
549
550 if (childSensor.getAttachedNode() != pcLinked->getChildRoot()) {
551 childSensor.detach();
552 childSensor.attach(pcLinked->getChildRoot());
553 }
554 if (!pcChildGroup) {
555 pcChildGroup = new SoGroup;
556 }
557 else {
558 coinRemoveAllChildren(pcChildGroup);
559 }
560
561 NodeMap nodeMap;
562
563 for (auto child : pcLinked->claimChildren3D()) {
564 Pointer info = get(child, nullptr);
565 if (!info) {
566 continue;
567 }
568 SoNode* node = info->getSnapshot(LinkView::SnapshotChild);
569 if (!node) {
570 continue;
571 }
572 nodeMap[node] = info;
573 pcChildGroup->addChild(node);
574 }
575
576 // Use swap instead of clear() here to avoid potential link
577 // destruction
578 this->nodeMap.swap(nodeMap);
579 }
580
581 bool getElementPicked(bool addname, int type, const SoPickedPoint* pp, std::ostream& str) const
582 {
583 if (!pp || !isLinked()) {
584 return false;
585 }
586
587 if (addname) {
588 str << getLinkedName() << '.';
589 }
590
591 auto pcSwitch = pcSwitches[type];
592 if (pcChildGroup && pcSwitch && pcSwitch->whichChild.getValue() >= 0
593 && pcSwitch->getChild(pcSwitch->whichChild.getValue()) == pcChildGroup) {
594 SoPath* path = pp->getPath();
595 int index = path->findNode(pcChildGroup);
596 if (index <= 0) {
597 return false;
598 }
599 auto it = nodeMap.find(path->getNode(index + 1));
600 if (it == nodeMap.end()) {
601 return false;
602 }
603 return it->second->getElementPicked(true, LinkView::SnapshotChild, pp, str);
604 }
605 else {
606 std::string subname;
607 if (!pcLinked->getElementPicked(pp, subname)) {
608 return false;
609 }
610 str << subname;
611 }
612 return true;
613 }
614
615 static const char* checkSubname(App::DocumentObject* obj, const char* subname)
616 {
617 #define CHECK_NAME(_name, _end) \
618 do { \
619 if (!_name) \
620 return 0; \
621 const char* _n = _name; \
622 for (; *subname && *_n; ++subname, ++_n) \
623 if (*subname != *_n) \
624 break; \
625 if (*_n || (*subname != 0 && *subname != _end)) \
626 return 0; \
627 if (*subname == _end) \
628 ++subname; \
629 } while (0)
630
631 // if(subname[0] == '*') {
632 // ++subname;
633 // CHECK_NAME(obj->getDocument()->getName(),'*');
634 // }
635 CHECK_NAME(obj->getNameInDocument(), '.');
636 return subname;
637 }
638
639 bool getDetail(bool checkname, int type, const char* subname, SoDetail*& det, SoFullPath* path) const
640 {
641 if (!isLinked()) {
642 return false;
643 }
644
645 if (checkname) {
646 subname = checkSubname(pcLinked->getObject(), subname);
647 if (!subname) {
648 return false;
649 }
650 }
651
652 if (pcSnapshots[type]->findChild(pcSwitches[type]) < 0) {
653 if (path) {
654 if (!appendPathSafe(path, pcSnapshots[type])) {
655 return false;
656 }
657 }
658 // this is possible in case of editing, where the switch node
659 // of the linked view object is temparaly removed from its root
660 return true;
661 }
662 int len = 0;
663 if (path) {
664 len = path->getLength();
665 if (!appendPathSafe(path, pcSnapshots[type])) {
666 return false;
667 }
668 appendPath(path, pcSwitches[type]);
669 }
670 if (*subname == 0) {
671 return true;
672 }
673
674 auto pcSwitch = pcSwitches[type];
675 if (!pcChildGroup || !pcSwitch || pcSwitch->whichChild.getValue() < 0
676 || pcSwitch->getChild(pcSwitch->whichChild.getValue()) != pcChildGroup) {
677 return pcLinked->getDetailPath(subname, path, false, det);
678 }
679 if (path) {
680 appendPath(path, pcChildGroup);
681 if (pcLinked->getChildRoot()) {
682 type = LinkView::SnapshotChild;
683 }
684 else {
685 type = LinkView::SnapshotVisible;
686 }
687 }
688
689 // Special handling of nodes with childRoot, especially geo feature
690 // group. It's object hierarchy in the tree view (i.e. in subname) is
691 // difference from its coin hierarchy. All objects under a geo feature
692 // group is visually grouped directly under the group's childRoot,
693 // even though some object has secondary hierarchy in subname. E.g.
694 //
695 // Body
696 // |--Pad
697 // |--Sketch
698 //
699 // Both Sketch and Pad's coin nodes are grouped directly under Body as,
700 //
701 // Body
702 // |--Pad
703 // |--Sketch
704
705 const char* dot = strchr(subname, '.');
706 const char* nextsub = subname;
707 if (!dot) {
708 return false;
709 }
710 auto geoGroup = pcLinked->getObject();
711 auto sobj = geoGroup;
712 while (true) {
713 std::string objname = std::string(nextsub, dot - nextsub + 1);
714 if (!geoGroup->getSubObject(objname.c_str())) {
715 // this object is not found under the geo group, abort.
716 break;
717 }
718 // Object found under geo group, remember this subname
719 subname = nextsub;
720
721 auto ssobj = sobj->getSubObject(objname.c_str());
722 if (!ssobj) {
723 FC_ERR("invalid sub name " << nextsub << " of object " << sobj->getFullName());
724 return false;
725 }
726 sobj = ssobj;
727 auto vp = Application::Instance->getViewProvider(sobj);
728 if (!vp) {
729 FC_ERR("cannot find view provider of " << sobj->getFullName());
730 return false;
731 }
732 if (vp->getChildRoot()) {
733 // In case the children is also a geo group, it will visually
734 // hold all of its own children, so stop going further down.
735 break;
736 }
737 // new style mapped sub-element
738 if (Data::isMappedElement(dot + 1)) {
739 break;
740 }
741 auto next = strchr(dot + 1, '.');
742 if (!next) {
743 // no dot any more, the following must be a sub-element
744 break;
745 }
746 nextsub = dot + 1;
747 dot = next;
748 }
749
750 for (const auto& v : nodeMap) {
751 if (v.second->getDetail(true, type, subname, det, path)) {
752 return true;
753 }
754 }
755 if (path) {
756 path->truncate(len);
757 }
758 return false;
759 }
760
761 void slotChangeIcon()
762 {
763 iconMap.clear();
764 if (!isLinked()) {
765 return;
766 }
767 LinkInfoPtr me(this);
768 for (auto link : links) {
769 link->onLinkedIconChange(me);
770 }
771 }
772
773 QIcon getIcon(QPixmap px)
774 {
775 static int iconSize = -1;
776 if (iconSize < 0) {
777 auto sampleIcon = QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon);
778 double pixelRatio = sampleIcon.devicePixelRatio();
779 iconSize = static_cast<int>(sampleIcon.width() / pixelRatio);
780 }
781
782 if (!isLinked()) {
783 return QIcon();
784 }
785
786 if (px.isNull()) {
787 return pcLinked->getIcon();
788 }
789 QIcon& iconLink = iconMap[px.cacheKey()];
790 if (iconLink.isNull()) {
791 QIcon icon = pcLinked->getIcon();
792 iconLink = QIcon();
793 iconLink.addPixmap(
794 BitmapFactory().merge(
795 icon.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::Off),
796 px,
797 BitmapFactoryInst::BottomLeft
798 ),
799 QIcon::Normal,
800 QIcon::Off
801 );
802 iconLink.addPixmap(
803 BitmapFactory().merge(
804 icon.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::On),
805 px,
806 BitmapFactoryInst::BottomLeft
807 ),
808 QIcon::Normal,
809 QIcon::On
810 );
811 }
812 return iconLink;
813 }
814 };
815
816 #if defined(_MSC_VER)
817 namespace Gui
818 {
819 void intrusive_ptr_add_ref(Gui::LinkInfo* px)
820 {
821 px->addref();
822 }
823
824 void intrusive_ptr_release(Gui::LinkInfo* px)
825 {
826 px->release();
827 }
828 } // namespace Gui
829 #endif
830
831 ////////////////////////////////////////////////////////////////////////////////////
832
833 EXTENSION_TYPESYSTEM_SOURCE(Gui::ViewProviderLinkObserver, Gui::ViewProviderExtension)
834
835 ViewProviderLinkObserver::ViewProviderLinkObserver()
836 {
837 // TODO: any better way to get deleted automatically?
838 m_isPythonExtension = true;
839 initExtensionType(ViewProviderLinkObserver::getExtensionClassTypeId());
840 }
841
842 ViewProviderLinkObserver::~ViewProviderLinkObserver()
843 {
844 if (linkInfo) {
845 linkInfo->detach(true);
846 linkInfo.reset();
847 }
848 }
849
850 bool ViewProviderLinkObserver::isLinkVisible() const
851 {
852 if (linkInfo) {
853 return linkInfo->isVisible();
854 }
855 return true;
856 }
857
858 void ViewProviderLinkObserver::setLinkVisible(bool visible)
859 {
860 if (linkInfo) {
861 linkInfo->setVisible(visible);
862 }
863 }
864
865 void ViewProviderLinkObserver::extensionBeforeDelete()
866 {
867 if (linkInfo) {
868 linkInfo->detach(false);
869 }
870 }
871
872 void ViewProviderLinkObserver::extensionReattach(App::DocumentObject*)
873 {
874 if (linkInfo) {
875 linkInfo->pcLinked = freecad_cast<ViewProviderDocumentObject*>(getExtendedContainer());
876 linkInfo->update();
877 }
878 }
879
880 void ViewProviderLinkObserver::extensionOnChanged(const App::Property* prop)
881 {
882 (void)prop;
883 }
884
885 void ViewProviderLinkObserver::extensionModeSwitchChange()
886 {
887 auto owner = freecad_cast<ViewProviderDocumentObject*>(getExtendedContainer());
888 if (owner && linkInfo) {
889 linkInfo->updateSwitch();
890 }
891 }
892
893 void ViewProviderLinkObserver::extensionUpdateData(const App::Property* prop)
894 {
895 if (linkInfo && linkInfo->pcLinked && linkInfo->pcLinked->getObject()
896 && prop != &linkInfo->pcLinked->getObject()->Visibility) {
897 linkInfo->updateData(prop);
898 }
899 }
900
901 void ViewProviderLinkObserver::extensionFinishRestoring()
902 {
903 if (linkInfo) {
904 FC_TRACE("linked finish restoing");
905 linkInfo->update();
906 }
907 }
908
909 class LinkView::SubInfo: public LinkOwner
910 {
911 public:
912 LinkInfoPtr linkInfo;
913 LinkView& handle;
914 CoinPtr<SoSeparator> pcNode;
915 CoinPtr<SoTransform> pcTransform;
916 std::set<std::string> subElements;
917
918 friend LinkView;
919
920 SubInfo(LinkView& handle)
921 : handle(handle)
922 {
923 pcNode = new SoFCSelectionRoot(true);
924 pcTransform = new SoTransform;
925 pcNode->addChild(pcTransform);
926 }
927
928 ~SubInfo() override
929 {
930 unlink();
931 auto root = handle.getLinkRoot();
932 if (root) {
933 int idx = root->findChild(pcNode);
934 if (idx >= 0) {
935 root->removeChild(idx);
936 }
937 }
938 }
939
940 void onLinkedIconChange(LinkInfoPtr) override
941 {
942 if (handle.autoSubLink && handle.subInfo.size() == 1) {
943 handle.onLinkedIconChange(handle.linkInfo);
944 }
945 }
946
947 void unlink(LinkInfoPtr info = LinkInfoPtr()) override
948 {
949 (void)info;
950 if (linkInfo) {
951 linkInfo->remove(this);
952 linkInfo.reset();
953 }
954 coinRemoveAllChildren(pcNode);
955 pcNode->addChild(pcTransform);
956 }
957
958 void link(App::DocumentObject* obj)
959 {
960 if (isLinked() && linkInfo->pcLinked->getObject() == obj) {
961 return;
962 }
963 unlink();
964 linkInfo = LinkInfo::get(obj, this);
965 if (linkInfo) {
966 pcNode->addChild(linkInfo->getSnapshot(LinkView::SnapshotTransform));
967 }
968 }
969
970 bool isLinked() const
971 {
972 return linkInfo && linkInfo->isLinked();
973 }
974 };
975
976 //////////////////////////////////////////////////////////////////////////////////
977
978 class LinkView::Element: public LinkOwner
979 {
980 public:
981 LinkInfoPtr linkInfo;
982 LinkView& handle;
983 CoinPtr<SoSwitch> pcSwitch;
984 CoinPtr<SoFCSelectionRoot> pcRoot;
985 CoinPtr<SoTransform> pcTransform;
986 int groupIndex = -1;
987 bool isGroup = false;
988
989 friend LinkView;
990
991 Element(LinkView& handle)
992 : handle(handle)
993 {
994 pcTransform = new SoTransform;
995 pcRoot = new SoFCSelectionRoot(true);
996 pcSwitch = new SoSwitch;
997 pcSwitch->addChild(pcRoot);
998 pcSwitch->whichChild = 0;
999 }
1000
1001 ~Element() override
1002 {
1003 unlink();
1004 auto root = handle.getLinkRoot();
1005 if (root) {
1006 int idx = root->findChild(pcRoot);
1007 if (idx >= 0) {
1008 root->removeChild(idx);
1009 }
1010 }
1011 }
1012
1013 void unlink(LinkInfoPtr info = LinkInfoPtr()) override
1014 {
1015 (void)info;
1016 if (linkInfo) {
1017 linkInfo->remove(this);
1018 linkInfo.reset();
1019 }
1020 coinRemoveAllChildren(pcRoot);
1021 }
1022
1023 void link(App::DocumentObject* obj)
1024 {
1025 if (isLinked() && linkInfo->pcLinked->getObject() == obj) {
1026 return;
1027 }
1028 unlink();
1029 linkInfo = LinkInfo::get(obj, this);
1030 if (isLinked()) {
1031 pcRoot->addChild(linkInfo->getSnapshot(handle.childType));
1032 }
1033 }
1034
1035 bool isLinked() const
1036 {
1037 return linkInfo && linkInfo->isLinked();
1038 }
1039 };
1040
1041 ///////////////////////////////////////////////////////////////////////////////////
1042
1043 TYPESYSTEM_SOURCE(Gui::LinkView, Base::BaseClass)
1044
1045 LinkView::LinkView()
1046 : nodeType(SnapshotTransform)
1047 , childType((SnapshotType)-1)
1048 , autoSubLink(true)
1049 {
1050 pcLinkRoot = new SoFCSelectionRoot;
1051 }
1052
1053 LinkView::~LinkView()
1054 {
1055 unlink(linkInfo);
1056 unlink(linkOwner);
1057 }
1058
1059 PyObject* LinkView::getPyObject()
1060 {
1061 if (PythonObject.is(Py::_None())) {
1062 PythonObject = Py::Object(new LinkViewPy(this), true);
1063 }
1064 return Py::new_reference_to(PythonObject);
1065 }
1066
1067 void LinkView::setInvalid()
1068 {
1069 if (!PythonObject.is(Py::_None())) {
1070 auto obj = static_cast<Base::PyObjectBase*>(PythonObject.ptr());
1071 obj->setInvalid();
1072 obj->DecRef();
1073 }
1074 else {
1075 delete this;
1076 }
1077 }
1078
1079 Base::BoundBox3d _getBoundBox(ViewProviderDocumentObject* vpd, SoNode* rootNode)
1080 {
1081 auto doc = vpd->getDocument();
1082 if (!doc) {
1083 LINK_THROW(Base::RuntimeError, "no document");
1084 }
1085 Gui::MDIView* view = doc->getViewOfViewProvider(vpd);
1086 if (!view) {
1087 LINK_THROW(Base::RuntimeError, "no view");
1088 }
1089
1090 Gui::View3DInventorViewer* viewer = static_cast<Gui::View3DInventor*>(view)->getViewer();
1091 SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion());
1092 bboxAction.apply(rootNode);
1093 auto bbox = bboxAction.getBoundingBox();
1094 float minX, minY, minZ, maxX, maxY, maxZ;
1095 bbox.getMax().getValue(maxX, maxY, maxZ);
1096 bbox.getMin().getValue(minX, minY, minZ);
1097 return Base::BoundBox3d(minX, minY, minZ, maxX, maxY, maxZ);
1098 }
1099
1100 Base::BoundBox3d LinkView::getBoundBox(ViewProviderDocumentObject* vpd) const
1101 {
1102 if (!vpd) {
1103 if (!linkOwner || !linkOwner->isLinked()) {
1104 LINK_THROW(Base::ValueError, "no ViewProvider");
1105 }
1106 vpd = linkOwner->pcLinked;
1107 }
1108 return _getBoundBox(vpd, pcLinkRoot);
1109 }
1110
1111 ViewProviderDocumentObject* LinkView::getOwner() const
1112 {
1113 if (linkOwner && linkOwner->isLinked()) {
1114 return linkOwner->pcLinked;
1115 }
1116 return nullptr;
1117 }
1118
1119 void LinkView::setOwner(ViewProviderDocumentObject* vpd)
1120 {
1121 unlink(linkOwner);
1122 linkOwner = LinkInfo::get(vpd, this);
1123 }
1124
1125 bool LinkView::isLinked() const
1126 {
1127 return linkInfo && linkInfo->isLinked();
1128 }
1129
1130 void LinkView::setDrawStyle(int style, double lineWidth, double pointSize)
1131 {
1132 if (!pcDrawStyle) {
1133 if (!style) {
1134 return;
1135 }
1136 pcDrawStyle = new SoDrawStyle;
1137 pcDrawStyle->style = SoDrawStyle::FILLED;
1138 pcLinkRoot->insertChild(pcDrawStyle, 0);
1139 }
1140 if (!style) {
1141 pcDrawStyle->setOverride(false);
1142 return;
1143 }
1144 pcDrawStyle->lineWidth = lineWidth;
1145 pcDrawStyle->pointSize = pointSize;
1146 switch (style) {
1147 case 2:
1148 pcDrawStyle->linePattern = 0xf00f;
1149 break;
1150 case 3:
1151 pcDrawStyle->linePattern = 0x0f0f;
1152 break;
1153 case 4:
1154 pcDrawStyle->linePattern = 0xff88;
1155 break;
1156 default:
1157 pcDrawStyle->linePattern = 0xffff;
1158 }
1159 pcDrawStyle->setOverride(true);
1160 }
1161
1162 void LinkView::renderDoubleSide(bool enable)
1163 {
1164 if (enable) {
1165 if (!pcShapeHints) {
1166 pcShapeHints = new SoShapeHints;
1167 pcShapeHints->vertexOrdering = SoShapeHints::CLOCKWISE;
1168 pcShapeHints->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE;
1169 pcLinkRoot->insertChild(pcShapeHints, 0);
1170 }
1171 pcShapeHints->setOverride(true);
1172 }
1173 else if (pcShapeHints) {
1174 pcShapeHints->setOverride(false);
1175 }
1176 }
1177
1178 void LinkView::setMaterial(int index, const App::Material* material)
1179 {
1180 if (index < 0) {
1181 if (!material) {
1182 pcLinkRoot->removeColorOverride();
1183 return;
1184 }
1185 Base::Color c = material->diffuseColor;
1186 c.setTransparency(material->transparency);
1187 pcLinkRoot->setColorOverride(c);
1188 for (int i = 0; i < getSize(); ++i) {
1189 setMaterial(i, nullptr);
1190 }
1191 }
1192 else if (index >= (int)nodeArray.size()) {
1193 LINK_THROW(Base::ValueError, "LinkView: material index out of range");
1194 }
1195 else {
1196 auto& info = *nodeArray[index];
1197 if (!material) {
1198 info.pcRoot->removeColorOverride();
1199 return;
1200 }
1201 Base::Color c = material->diffuseColor;
1202 c.setTransparency(material->transparency);
1203 info.pcRoot->setColorOverride(c);
1204 }
1205 }
1206
1207 void LinkView::setLink(App::DocumentObject* obj, const std::vector<std::string>& subs)
1208 {
1209 setLinkViewObject(
1210 freecad_cast<ViewProviderDocumentObject*>(Application::Instance->getViewProvider(obj)),
1211 subs
1212 );
1213 }
1214
1215 void LinkView::setLinkViewObject(ViewProviderDocumentObject* vpd, const std::vector<std::string>& subs)
1216 {
1217 if (!isLinked() || linkInfo->pcLinked != vpd) {
1218 unlink(linkInfo);
1219 linkInfo = LinkInfo::get(vpd, this);
1220 if (!linkInfo) {
1221 return;
1222 }
1223 }
1224 subInfo.clear();
1225 for (const auto& sub : subs) {
1226 if (sub.empty()) {
1227 continue;
1228 }
1229 const char* subelement = Data::findElementName(sub.c_str());
1230 std::string subname = sub.substr(0, subelement - sub.c_str());
1231 auto it = subInfo.find(subname);
1232 if (it == subInfo.end()) {
1233 it = subInfo.insert(std::make_pair(subname, std::unique_ptr<SubInfo>())).first;
1234 it->second = std::make_unique<SubInfo>(*this);
1235 }
1236 if (subelement[0]) {
1237 it->second->subElements.insert(subelement);
1238 }
1239 }
1240 updateLink();
1241 }
1242
1243 void LinkView::setTransform(SoTransform* pcTransform, const Base::Matrix4D& mat)
1244 {
1245 double dMtrx[16];
1246 mat.getGLMatrix(dMtrx);
1247 pcTransform->setMatrix(SbMatrix(
1248 dMtrx[0],
1249 dMtrx[1],
1250 dMtrx[2],
1251 dMtrx[3],
1252 dMtrx[4],
1253 dMtrx[5],
1254 dMtrx[6],
1255 dMtrx[7],
1256 dMtrx[8],
1257 dMtrx[9],
1258 dMtrx[10],
1259 dMtrx[11],
1260 dMtrx[12],
1261 dMtrx[13],
1262 dMtrx[14],
1263 dMtrx[15]
1264 ));
1265 }
1266
1267 void LinkView::setSize(int _size)
1268 {
1269 size_t size = _size < 0 ? 0 : (size_t)_size;
1270 if (childType < 0 && size == nodeArray.size()) {
1271 return;
1272 }
1273 resetRoot();
1274 if (!size || childType >= 0) {
1275 nodeArray.clear();
1276 nodeMap.clear();
1277 if (!size && childType < 0) {
1278 if (pcLinkedRoot) {
1279 pcLinkRoot->addChild(pcLinkedRoot);
1280 }
1281 return;
1282 }
1283 childType = SnapshotContainer;
1284 }
1285 if (size < nodeArray.size()) {
1286 for (size_t i = size; i < nodeArray.size(); ++i) {
1287 nodeMap.erase(nodeArray[i]->pcSwitch);
1288 }
1289 nodeArray.resize(size);
1290 }
1291 for (const auto& info : nodeArray) {
1292 pcLinkRoot->addChild(info->pcSwitch);
1293 }
1294
1295 while (nodeArray.size() < size) {
1296 nodeArray.push_back(std::make_unique<Element>(*this));
1297 auto& info = *nodeArray.back();
1298 info.pcRoot->addChild(info.pcTransform);
1299 if (pcLinkedRoot) {
1300 info.pcRoot->addChild(pcLinkedRoot);
1301 }
1302 pcLinkRoot->addChild(info.pcSwitch);
1303 nodeMap.emplace(info.pcSwitch, (int)nodeArray.size() - 1);
1304 }
1305 }
1306
1307 void LinkView::resetRoot()
1308 {
1309 coinRemoveAllChildren(pcLinkRoot);
1310 if (pcTransform) {
1311 pcLinkRoot->addChild(pcTransform);
1312 }
1313 if (pcShapeHints) {
1314 pcLinkRoot->addChild(pcShapeHints);
1315 }
1316 if (pcDrawStyle) {
1317 pcLinkRoot->addChild(pcDrawStyle);
1318 }
1319 }
1320
1321 void LinkView::setChildren(
1322 const std::vector<App::DocumentObject*>& children,
1323 const boost::dynamic_bitset<>& vis,
1324 SnapshotType type
1325 )
1326 {
1327 if (children.empty()) {
1328 if (!nodeArray.empty()) {
1329 nodeArray.clear();
1330 nodeMap.clear();
1331 childType = SnapshotContainer;
1332 resetRoot();
1333 if (pcLinkedRoot) {
1334 pcLinkRoot->addChild(pcLinkedRoot);
1335 }
1336 }
1337 return;
1338 }
1339
1340 if (type < 0 || type >= SnapshotMax) {
1341 LINK_THROW(Base::ValueError, "invalid children type");
1342 }
1343
1344 resetRoot();
1345
1346 if (childType < 0) {
1347 nodeArray.clear();
1348 }
1349 childType = type;
1350
1351 if (nodeArray.size() > children.size()) {
1352 nodeArray.resize(children.size());
1353 }
1354 else {
1355 nodeArray.reserve(children.size());
1356 }
1357
1358 std::map<App::DocumentObject*, size_t> groups;
1359 for (size_t i = 0; i < children.size(); ++i) {
1360 auto obj = children[i];
1361 if (nodeArray.size() <= i) {
1362 nodeArray.push_back(std::make_unique<Element>(*this));
1363 }
1364 auto& info = *nodeArray[i];
1365 info.isGroup = false;
1366 info.groupIndex = -1;
1367 info.pcSwitch->whichChild = (vis.size() <= i || vis[i]) ? 0 : SO_SWITCH_NONE;
1368 info.link(obj);
1369 if (obj->hasExtension(App::GroupExtension::getExtensionClassTypeId(), false)) {
1370 info.isGroup = true;
1371 coinRemoveAllChildren(info.pcRoot);
1372 groups.emplace(obj, i);
1373 }
1374 }
1375 nodeMap.clear();
1376 for (size_t i = 0; i < nodeArray.size(); ++i) {
1377 auto& info = *nodeArray[i];
1378 nodeMap.emplace(info.pcSwitch, i);
1379 if (info.isLinked() && !groups.empty()) {
1380 auto iter = groups.find(
1381 App::GroupExtension::getGroupOfObject(info.linkInfo->pcLinked->getObject())
1382 );
1383 if (iter != groups.end()) {
1384 info.groupIndex = iter->second;
1385 auto& groupInfo = *nodeArray[iter->second];
1386 groupInfo.pcRoot->addChild(info.pcSwitch);
1387 continue;
1388 }
1389 }
1390 pcLinkRoot->addChild(info.pcSwitch);
1391 }
1392 }
1393
1394 std::vector<ViewProviderDocumentObject*> LinkView::getChildren() const
1395 {
1396 std::vector<ViewProviderDocumentObject*> ret;
1397 for (const auto& info : nodeArray) {
1398 if (info->isLinked()) {
1399 ret.push_back(info->linkInfo->pcLinked);
1400 }
1401 }
1402 return ret;
1403 }
1404
1405 void LinkView::setTransform(int index, const Base::Matrix4D& mat)
1406 {
1407 if (index < 0) {
1408 if (!pcTransform) {
1409 pcTransform = new SoTransform;
1410 pcLinkRoot->insertChild(pcTransform, 0);
1411 }
1412 setTransform(pcTransform, mat);
1413 return;
1414 }
1415 if (index < 0 || index >= (int)nodeArray.size()) {
1416 LINK_THROW(Base::ValueError, "LinkView: index out of range");
1417 }
1418 setTransform(nodeArray[index]->pcTransform, mat);
1419 }
1420
1421 void LinkView::setElementVisible(int idx, bool visible)
1422 {
1423 if (idx >= 0 && idx < (int)nodeArray.size()) {
1424 nodeArray[idx]->pcSwitch->whichChild = visible ? 0 : SO_SWITCH_NONE;
1425 }
1426 }
1427
1428 bool LinkView::isElementVisible(int idx) const
1429 {
1430 if (idx >= 0 && idx < (int)nodeArray.size()) {
1431 return nodeArray[idx]->pcSwitch->whichChild.getValue() >= 0;
1432 }
1433 return false;
1434 }
1435
1436 ViewProviderDocumentObject* LinkView::getLinkedView() const
1437 {
1438 auto link = linkInfo;
1439 if (autoSubLink && subInfo.size() == 1) {
1440 link = subInfo.begin()->second->linkInfo;
1441 }
1442 return link ? link->pcLinked : nullptr;
1443 }
1444
1445 std::vector<std::string> LinkView::getSubNames() const
1446 {
1447 std::vector<std::string> ret;
1448 for (const auto& v : subInfo) {
1449 if (v.second->subElements.empty()) {
1450 ret.push_back(v.first);
1451 continue;
1452 }
1453 for (const auto& s : v.second->subElements) {
1454 ret.push_back(v.first + s);
1455 }
1456 }
1457 return ret;
1458 }
1459
1460 void LinkView::setNodeType(SnapshotType type, bool sublink)
1461 {
1462 autoSubLink = sublink;
1463 if (nodeType == type) {
1464 return;
1465 }
1466 if (type >= SnapshotMax
1467 || (type < 0 && type != SnapshotContainer && type != SnapshotContainerTransform)) {
1468 LINK_THROW(Base::ValueError, "LinkView: invalid node type");
1469 }
1470
1471 if (nodeType >= 0 && type < 0) {
1472 if (pcLinkedRoot) {
1473 SoSelectionElementAction action(SoSelectionElementAction::None, true);
1474 action.apply(pcLinkedRoot);
1475 }
1476 replaceLinkedRoot(CoinPtr<SoSeparator>(new SoFCSelectionRoot));
1477 }
1478 else if (nodeType < 0 && type >= 0) {
1479 if (isLinked()) {
1480 replaceLinkedRoot(linkInfo->getSnapshot(type));
1481 }
1482 else {
1483 replaceLinkedRoot(nullptr);
1484 }
1485 }
1486 nodeType = type;
1487 updateLink();
1488 }
1489
1490 void LinkView::replaceLinkedRoot(SoSeparator* root)
1491 {
1492 if (root == pcLinkedRoot) {
1493 return;
1494 }
1495 if (nodeArray.empty()) {
1496 if (pcLinkedRoot && root) {
1497 pcLinkRoot->replaceChild(pcLinkedRoot, root);
1498 }
1499 else if (root) {
1500 pcLinkRoot->addChild(root);
1501 }
1502 else {
1503 resetRoot();
1504 }
1505 }
1506 else if (childType < 0) {
1507 if (pcLinkedRoot && root) {
1508 for (const auto& info : nodeArray) {
1509 info->pcRoot->replaceChild(pcLinkedRoot, root);
1510 }
1511 }
1512 else if (root) {
1513 for (const auto& info : nodeArray) {
1514 info->pcRoot->addChild(root);
1515 }
1516 }
1517 else {
1518 for (const auto& info : nodeArray) {
1519 info->pcRoot->removeChild(pcLinkedRoot);
1520 }
1521 }
1522 }
1523 pcLinkedRoot = root;
1524 }
1525
1526 void LinkView::onLinkedIconChange(LinkInfoPtr info)
1527 {
1528 if (info == linkInfo && info != linkOwner && linkOwner && linkOwner->isLinked()) {
1529 linkOwner->pcLinked->signalChangeIcon();
1530 }
1531 }
1532
1533 void LinkView::onLinkedUpdateData(LinkInfoPtr info, const App::Property* prop)
1534 {
1535 if (info != linkInfo || !linkOwner || !linkOwner->isLinked() || info == linkOwner) {
1536 return;
1537 }
1538 auto ext = linkOwner->pcLinked->getObject()->getExtensionByType<App::LinkBaseExtension>(true);
1539 if (ext && !(prop->getType() & App::Prop_Output) && !prop->testStatus(App::Property::Output)) {
1540 // propagate the signalChangedObject to potentially multiple levels
1541 // of links, to inform tree view of children change, and other
1542 // parent objects about the change. But we need to be careful to not
1543 // touch the object if the property of change is marked as output.
1544 ext->_LinkTouched.touch();
1545 }
1546 else {
1547 // In case the owner object does not have link extension, here is a
1548 // trick to link the signalChangedObject from linked object to the
1549 // owner
1550 linkOwner->pcLinked->getDocument()->signalChangedObject(
1551 *linkOwner->pcLinked,
1552 linkOwner->pcLinked->getObject()->Label
1553 );
1554 }
1555 }
1556
1557 void LinkView::updateLink()
1558 {
1559 if (!isLinked()) {
1560 return;
1561 }
1562
1563 if (linkOwner && linkOwner->isLinked() && linkOwner->pcLinked->isRestoring()) {
1564 FC_TRACE("restoring '" << linkOwner->pcLinked->getObject()->getFullName() << "'");
1565 return;
1566 }
1567
1568 // TODO: is it a good idea to clear any selection here?
1569 pcLinkRoot->resetContext();
1570
1571 if (nodeType >= 0) {
1572 replaceLinkedRoot(linkInfo->getSnapshot(nodeType));
1573 return;
1574 }
1575
1576 // rebuild link sub objects tree
1577 CoinPtr<SoSeparator> linkedRoot = pcLinkedRoot;
1578 if (!linkedRoot) {
1579 linkedRoot = new SoFCSelectionRoot;
1580 }
1581 else {
1582 SoSelectionElementAction action(SoSelectionElementAction::None, true);
1583 action.apply(linkedRoot);
1584 coinRemoveAllChildren(linkedRoot);
1585 }
1586
1587 SoTempPath path(10);
1588 path.ref();
1589 appendPath(&path, linkedRoot);
1590 auto obj = linkInfo->pcLinked->getObject();
1591 for (const auto& v : subInfo) {
1592 auto& sub = *v.second;
1593 Base::Matrix4D mat;
1594 App::DocumentObject* sobj
1595 = obj->getSubObject(v.first.c_str(), nullptr, &mat, nodeType == SnapshotContainer);
1596 if (!sobj) {
1597 sub.unlink();
1598 continue;
1599 }
1600 sub.link(sobj);
1601 linkedRoot->addChild(sub.pcNode);
1602 setTransform(sub.pcTransform, mat);
1603
1604 if (!sub.subElements.empty()) {
1605 path.truncate(1);
1606 appendPath(&path, sub.pcNode);
1607 SoSelectionElementAction action(SoSelectionElementAction::Append, true);
1608 for (const auto& subelement : sub.subElements) {
1609 path.truncate(2);
1610 SoDetail* det = nullptr;
1611 if (!sub.linkInfo->getDetail(false, SnapshotTransform, subelement.c_str(), det, &path)) {
1612 continue;
1613 }
1614 action.setElement(det);
1615 action.apply(&path);
1616 delete det;
1617 }
1618 }
1619 }
1620 path.unrefNoDelete();
1621 replaceLinkedRoot(linkedRoot);
1622 }
1623
1624 bool LinkView::linkGetElementPicked(const SoPickedPoint* pp, std::string& subname) const
1625 {
1626 std::ostringstream ss;
1627 CoinPtr<SoPath> path {pp->getPath()};
1628 if (!nodeArray.empty()) {
1629 auto idx = path->findNode(pcLinkRoot);
1630 if (idx < 0 || idx + 2 >= path->getLength()) {
1631 return false;
1632 }
1633 auto node = path->getNode(idx + 1);
1634 auto it = nodeMap.find(node);
1635 if (it == nodeMap.end() || !isElementVisible(it->second)) {
1636 return false;
1637 }
1638 int nodeIdx = it->second;
1639 ++idx;
1640 while (nodeArray[nodeIdx]->isGroup) {
1641 auto& info = *nodeArray[nodeIdx];
1642 if (!info.isLinked()) {
1643 return false;
1644 }
1645 ss << info.linkInfo->getLinkedName() << '.';
1646 idx += 2;
1647 if (idx >= path->getLength()) {
1648 return false;
1649 }
1650 auto iter = nodeMap.find(path->getNode(idx));
1651 if (iter == nodeMap.end() || !isElementVisible(iter->second)) {
1652 return false;
1653 }
1654 nodeIdx = iter->second;
1655 }
1656
1657 auto& info = *nodeArray[nodeIdx];
1658 if (!info.linkInfo) {
1659 ss << it->second << '.';
1660 }
1661 else {
1662 ss << info.linkInfo->getLinkedName() << '.';
1663 }
1664
1665 if (info.isLinked()) {
1666 if (!info.linkInfo->getElementPicked(false, childType, pp, ss)) {
1667 return false;
1668 }
1669 subname = ss.str();
1670 return true;
1671 }
1672 }
1673
1674 if (!isLinked()) {
1675 return false;
1676 }
1677
1678 if (nodeType >= 0) {
1679 if (linkInfo->getElementPicked(false, nodeType, pp, ss)) {
1680 subname = ss.str();
1681 return true;
1682 }
1683 return false;
1684 }
1685 auto idx = path->findNode(pcLinkedRoot);
1686 if (idx < 0 || idx + 1 >= path->getLength()) {
1687 return false;
1688 }
1689 auto node = path->getNode(idx + 1);
1690 for (const auto& v : subInfo) {
1691 auto& sub = *v.second;
1692 if (node != sub.pcNode) {
1693 continue;
1694 }
1695
1696 std::ostringstream ss2;
1697 if (!sub.linkInfo->getElementPicked(false, SnapshotTransform, pp, ss2)) {
1698 return false;
1699 }
1700 const std::string& element = ss2.str();
1701 if (!sub.subElements.empty()) {
1702 if (sub.subElements.find(element) == sub.subElements.end()) {
1703 auto pos = element.find('.');
1704 if (pos == std::string::npos
1705 || sub.subElements.find(element.c_str() + pos + 1) == sub.subElements.end()) {
1706 return false;
1707 }
1708 }
1709 }
1710 if (!autoSubLink || subInfo.size() > 1) {
1711 ss << v.first;
1712 }
1713 ss << element;
1714 subname = ss.str();
1715 return true;
1716 }
1717 return false;
1718 }
1719
1720 bool LinkView::getGroupHierarchy(int index, SoFullPath* path) const
1721 {
1722 if (index > (int)nodeArray.size()) {
1723 return false;
1724 }
1725 auto& info = *nodeArray[index];
1726 if (info.groupIndex >= 0 && !getGroupHierarchy(info.groupIndex, path)) {
1727 return false;
1728 }
1729 appendPath(path, info.pcSwitch);
1730 appendPath(path, info.pcRoot);
1731 return true;
1732 }
1733
1734 bool LinkView::linkGetDetailPath(const char* subname, SoFullPath* path, SoDetail*& det) const
1735 {
1736 if (!subname || *subname == 0) {
1737 return true;
1738 }
1739 auto len = path->getLength();
1740 if (nodeArray.empty()) {
1741 if (!appendPathSafe(path, pcLinkRoot)) {
1742 return false;
1743 }
1744 }
1745 else {
1746 int idx = -1;
1747 if (subname[0] >= '0' && subname[0] <= '9') {
1748 idx = App::LinkBaseExtension::getArrayIndex(subname, &subname);
1749 }
1750 else {
1751 while (true) {
1752 const char* dot = strchr(subname, '.');
1753 if (!dot) {
1754 break;
1755 }
1756 int i = 0;
1757 if (subname[0] == '$') {
1758 CharRange name(subname + 1, dot);
1759 for (const auto& info : nodeArray) {
1760 if (info->isLinked()
1761 && boost::equals(name, info->linkInfo->getLinkedLabel())) {
1762 idx = i;
1763 break;
1764 }
1765 ++i;
1766 }
1767 }
1768 else {
1769 CharRange name(subname, dot);
1770 for (const auto& info : nodeArray) {
1771 if (info->isLinked() && boost::equals(name, info->linkInfo->getLinkedName())) {
1772 idx = i;
1773 break;
1774 }
1775 ++i;
1776 }
1777 }
1778
1779 if (idx < 0) {
1780 return false;
1781 }
1782
1783 subname = dot + 1;
1784 if (!subname[0] || nodeArray[idx]->isGroup == 0) {
1785 break;
1786 }
1787 idx = -1;
1788 }
1789 }
1790
1791 if (idx < 0 || idx >= (int)nodeArray.size()) {
1792 return false;
1793 }
1794 auto& info = *nodeArray[idx];
1795 if (!appendPathSafe(path, pcLinkRoot)) {
1796 return false;
1797 }
1798 if (info.groupIndex >= 0 && !getGroupHierarchy(info.groupIndex, path)) {
1799 return false;
1800 }
1801 appendPath(path, info.pcSwitch);
1802 appendPath(path, info.pcRoot);
1803
1804 if (*subname == 0) {
1805 return true;
1806 }
1807
1808 if (info.isLinked()) {
1809 if (info.linkInfo->getDetail(false, childType, subname, det, path)) {
1810 return true;
1811 }
1812 }
1813 }
1814 if (isLinked()) {
1815 if (nodeType >= 0) {
1816 if (linkInfo->getDetail(false, nodeType, subname, det, path)) {
1817 return true;
1818 }
1819 }
1820 else {
1821 appendPath(path, pcLinkedRoot);
1822 for (const auto& v : subInfo) {
1823 auto& sub = *v.second;
1824 if (!sub.isLinked()) {
1825 continue;
1826 }
1827 const char* nextsub;
1828 if (autoSubLink && subInfo.size() == 1) {
1829 nextsub = subname;
1830 }
1831 else {
1832 if (!boost::algorithm::starts_with(subname, v.first)) {
1833 continue;
1834 }
1835 nextsub = subname + v.first.size();
1836 if (*nextsub != '.') {
1837 continue;
1838 }
1839 ++nextsub;
1840 }
1841 if (*nextsub && !sub.subElements.empty()
1842 && sub.subElements.find(nextsub) == sub.subElements.end()) {
1843 break;
1844 }
1845 appendPath(path, sub.pcNode);
1846 len = path->getLength();
1847 if (sub.linkInfo->getDetail(false, SnapshotTransform, nextsub, det, path)) {
1848 return true;
1849 }
1850 break;
1851 }
1852 }
1853 }
1854 path->truncate(len);
1855 return false;
1856 }
1857
1858 void LinkView::unlink(LinkInfoPtr info)
1859 {
1860 if (!info) {
1861 return;
1862 }
1863 if (info == linkOwner) {
1864 linkOwner->remove(this);
1865 linkOwner.reset();
1866 }
1867 if (info != linkInfo) {
1868 return;
1869 }
1870 if (linkInfo) {
1871 linkInfo->remove(this);
1872 linkInfo.reset();
1873 }
1874 pcLinkRoot->resetContext();
1875 if (pcLinkedRoot) {
1876 if (nodeArray.empty()) {
1877 resetRoot();
1878 }
1879 else {
1880 for (const auto& info : nodeArray) {
1881 int idx;
1882 if (info->isLinked() && (idx = info->pcRoot->findChild(pcLinkedRoot)) >= 0) {
1883 info->pcRoot->removeChild(idx);
1884 }
1885 }
1886 }
1887 pcLinkedRoot.reset();
1888 }
1889 subInfo.clear();
1890 return;
1891 }
1892
1893 QIcon LinkView::getLinkedIcon(QPixmap px) const
1894 {
1895 auto link = linkInfo;
1896 if (autoSubLink && subInfo.size() == 1) {
1897 link = subInfo.begin()->second->linkInfo;
1898 }
1899 if (!link || !link->isLinked()) {
1900 return QIcon();
1901 }
1902 return link->getIcon(px);
1903 }
1904
1905 bool LinkView::hasSubs() const
1906 {
1907 return isLinked() && !subInfo.empty();
1908 }
1909
1910 ///////////////////////////////////////////////////////////////////////////////////
1911
1912 PROPERTY_SOURCE(Gui::ViewProviderLink, Gui::ViewProviderDocumentObject)
1913
1914 static const char* _LinkIcon = "Link";
1915 // static const char *_LinkArrayIcon = "LinkArray";
1916 static const char* _LinkGroupIcon = "LinkGroup";
1917 static const char* _LinkElementIcon = "LinkElement";
1918
1919 ViewProviderLink::ViewProviderLink()
1920 : linkType(LinkTypeNone)
1921 , hasSubName(false)
1922 , hasSubElement(false)
1923 , childVp(nullptr)
1924 , overlayCacheKey(0)
1925 {
1926 sPixmap = _LinkIcon;
1927
1928 ADD_PROPERTY_TYPE(Selectable, (true), " Link", App::Prop_None, 0);
1929
1930 ADD_PROPERTY_TYPE(
1931 OverrideMaterial,
1932 (false),
1933 " Link",
1934 App::Prop_None,
1935 "Override linked object's material"
1936 );
1937
1938 App::Material mat(App::Material::DEFAULT);
1939 mat.diffuseColor.setPackedValue(ViewParams::instance()->getDefaultLinkColor());
1940 ADD_PROPERTY_TYPE(ShapeMaterial, (mat), " Link", App::Prop_None, 0);
1941 ShapeMaterial.setStatus(App::Property::MaterialEdit, true);
1942
1943 ADD_PROPERTY_TYPE(DrawStyle, ((long int)0), " Link", App::Prop_None, "");
1944 static const char* DrawStyleEnums[] = {"None", "Solid", "Dashed", "Dotted", "Dashdot", nullptr};
1945 DrawStyle.setEnums(DrawStyleEnums);
1946
1947 int lwidth = ViewParams::instance()->getDefaultShapeLineWidth();
1948 ADD_PROPERTY_TYPE(LineWidth, (lwidth), " Link", App::Prop_None, "");
1949
1950 static App::PropertyFloatConstraint::Constraints sizeRange = {1.0, 64.0, 1.0};
1951 LineWidth.setConstraints(&sizeRange);
1952
1953 ADD_PROPERTY_TYPE(PointSize, (lwidth), " Link", App::Prop_None, "");
1954 PointSize.setConstraints(&sizeRange);
1955
1956 ADD_PROPERTY(MaterialList, ());
1957 MaterialList.setStatus(App::Property::NoMaterialListEdit, true);
1958
1959 ADD_PROPERTY(OverrideMaterialList, ());
1960 ADD_PROPERTY(OverrideColorList, ());
1961
1962 ADD_PROPERTY(ChildViewProvider, (""));
1963 ChildViewProvider.setStatus(App::Property::Hidden, true);
1964
1965 DisplayMode.setStatus(App::Property::Status::Hidden, true);
1966
1967 linkView = new LinkView;
1968
1969 pcPickStyle = new SoPickStyle;
1970 pcPickStyle->ref();
1971 }
1972
1973 ViewProviderLink::~ViewProviderLink()
1974 {
1975 pcPickStyle->unref();
1976 linkView->setInvalid();
1977 }
1978
1979 bool ViewProviderLink::isSelectable() const
1980 {
1981 return Selectable.getValue();
1982 }
1983
1984 void ViewProviderLink::attach(App::DocumentObject* pcObj)
1985 {
1986 if (pcRoot->findChild(pcPickStyle) < 0) {
1987 pcRoot->insertChild(pcPickStyle, 0);
1988 }
1989
1990 SoNode* node = linkView->getLinkRoot();
1991 node->setName(pcObj->getFullName().c_str());
1992 addDisplayMaskMode(node, "Link");
1993 if (childVp) {
1994 childVpLink = LinkInfo::get(childVp, nullptr);
1995 node = childVpLink->getSnapshot(LinkView::SnapshotTransform);
1996 }
1997 addDisplayMaskMode(node, "ChildView");
1998 setDisplayMaskMode("Link");
1999 inherited::attach(pcObj);
2000 checkIcon();
2001 if (pcObj->isDerivedFrom<App::LinkElement>()) {
2002 hide();
2003 }
2004 linkView->setOwner(this);
2005 }
2006
2007 void ViewProviderLink::reattach(App::DocumentObject* obj)
2008 {
2009 linkView->setOwner(this);
2010 if (childVp) {
2011 childVp->reattach(obj);
2012 }
2013 ViewProviderDocumentObject::reattach(obj);
2014 }
2015
2016 std::vector<std::string> ViewProviderLink::getDisplayModes() const
2017 {
2018 std::vector<std::string> StrList = inherited::getDisplayModes();
2019 StrList.emplace_back("Link");
2020 StrList.emplace_back("ChildView");
2021 return StrList;
2022 }
2023
2024 QIcon ViewProviderLink::getIcon() const
2025 {
2026 auto ext = getLinkExtension();
2027 if (ext) {
2028 auto link = ext->getLinkedObjectValue();
2029 if (link && link != getObject()) {
2030 QPixmap overlay = getOverlayPixmap();
2031 overlayCacheKey = overlay.cacheKey();
2032 QIcon icon = linkView->getLinkedIcon(overlay);
2033 if (!icon.isNull()) {
2034 return icon;
2035 }
2036 }
2037 }
2038 overlayCacheKey = 0;
2039 return Gui::BitmapFactory().pixmap(sPixmap);
2040 }
2041
2042 QPixmap ViewProviderLink::getOverlayPixmap() const
2043 {
2044 auto ext = getLinkExtension();
2045 constexpr int px = 12;
2046 if (ext && ext->getLinkedObjectProperty() && ext->_getElementCountValue()) {
2047 return BitmapFactory().pixmapFromSvg("LinkArrayOverlay", QSizeF(px, px));
2048 }
2049 else if (hasSubElement) {
2050 return BitmapFactory().pixmapFromSvg("LinkSubElement", QSizeF(px, px));
2051 }
2052 else if (hasSubName) {
2053 return BitmapFactory().pixmapFromSvg("LinkSubOverlay", QSizeF(px, px));
2054 }
2055 else {
2056 return BitmapFactory().pixmapFromSvg("LinkOverlay", QSizeF(px, px));
2057 }
2058 }
2059
2060 void ViewProviderLink::onChanged(const App::Property* prop)
2061 {
2062 if (prop == &Selectable) {
2063 pcPickStyle->style = Selectable.getValue() ? SoPickStyle::SHAPE : SoPickStyle::UNPICKABLE;
2064 }
2065
2066 if (prop == &ChildViewProvider) {
2067 childVp = freecad_cast<ViewProviderDocumentObject*>(ChildViewProvider.getObject().get());
2068 if (childVp && getObject()) {
2069 if (strcmp(childVp->getTypeId().getName(), getObject()->getViewProviderName()) != 0
2070 && !childVp->allowOverride(*getObject())) {
2071 FC_ERR(
2072 "Child view provider type '" << childVp->getTypeId().getName()
2073 << "' does not support "
2074 << getObject()->getFullName()
2075 );
2076 }
2077 else {
2078 childVp->setPropertyPrefix("ChildViewProvider.");
2079 childVp->Visibility.setValue(getObject()->Visibility.getValue());
2080 childVp->attach(getObject());
2081 childVp->updateView();
2082 childVp->setActiveMode();
2083 if (pcModeSwitch->getNumChildren() > 1) {
2084 childVpLink = LinkInfo::get(childVp, nullptr);
2085 pcModeSwitch->replaceChild(1, childVpLink->getSnapshot(LinkView::SnapshotTransform));
2086 }
2087 }
2088 }
2089 }
2090 else if (!isRestoring()) {
2091 if (prop == &OverrideMaterial || prop == &ShapeMaterial || prop == &MaterialList
2092 || prop == &OverrideMaterialList) {
2093 applyMaterial();
2094 }
2095 else if (prop == &OverrideColorList) {
2096 applyColors();
2097 }
2098 else if (prop == &DrawStyle || prop == &PointSize || prop == &LineWidth) {
2099 if (!DrawStyle.getValue()) {
2100 linkView->setDrawStyle(0);
2101 }
2102 else {
2103 linkView->setDrawStyle(DrawStyle.getValue(), LineWidth.getValue(), PointSize.getValue());
2104 }
2105 }
2106 }
2107
2108 inherited::onChanged(prop);
2109 }
2110
2111 bool ViewProviderLink::setLinkType(App::LinkBaseExtension* ext)
2112 {
2113 auto propLink = ext->getLinkedObjectProperty();
2114 if (!propLink) {
2115 return false;
2116 }
2117 LinkType type;
2118 if (hasSubName) {
2119 type = LinkTypeSubs;
2120 }
2121 else {
2122 type = LinkTypeNormal;
2123 }
2124 if (linkType != type) {
2125 linkType = type;
2126 }
2127 switch (type) {
2128 case LinkTypeSubs:
2129 linkView->setNodeType(
2130 ext->linkTransform() ? LinkView::SnapshotContainer : LinkView::SnapshotContainerTransform
2131 );
2132 break;
2133 case LinkTypeNormal:
2134 linkView->setNodeType(
2135 ext->linkTransform() ? LinkView::SnapshotVisible : LinkView::SnapshotTransform
2136 );
2137 break;
2138 default:
2139 break;
2140 }
2141 return true;
2142 }
2143
2144 App::LinkBaseExtension* ViewProviderLink::getLinkExtension()
2145 {
2146 if (!pcObject || !pcObject->isAttachedToDocument()) {
2147 return nullptr;
2148 }
2149 return pcObject->getExtensionByType<App::LinkBaseExtension>(true);
2150 }
2151
2152 const App::LinkBaseExtension* ViewProviderLink::getLinkExtension() const
2153 {
2154 if (!pcObject || !pcObject->isAttachedToDocument()) {
2155 return nullptr;
2156 }
2157 return const_cast<App::DocumentObject*>(pcObject)->getExtensionByType<App::LinkBaseExtension>(true);
2158 }
2159
2160 void ViewProviderLink::updateData(const App::Property* prop)
2161 {
2162 if (childVp) {
2163 childVp->updateData(prop);
2164 }
2165
2166 inherited::updateData(prop);
2167
2168 if (!isRestoring() && !pcObject->isRestoring()) {
2169 auto ext = getLinkExtension();
2170 if (ext) {
2171 updateDataPrivate(getLinkExtension(), prop);
2172 }
2173 }
2174 }
2175
2176 static inline bool canScale(const Base::Vector3d& v)
2177 {
2178 return fabs(v.x) > 1e-7 && fabs(v.y) > 1e-7 && fabs(v.z) > 1e-7;
2179 }
2180
2181 void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension* ext, const App::Property* prop)
2182 {
2183 if (!prop) {
2184 return;
2185 }
2186 if (prop == &ext->_ChildCache) {
2187 updateElementList(ext);
2188 }
2189 else if (prop == &ext->_LinkTouched) {
2190 if (linkView->hasSubs()) {
2191 linkView->updateLink();
2192 }
2193 applyColors();
2194 checkIcon(ext);
2195 }
2196 else if (prop == ext->getColoredElementsProperty()) {
2197 if (!prop->testStatus(App::Property::User3)) {
2198 applyColors();
2199 }
2200 }
2201 else if (prop == ext->getScaleProperty() || prop == ext->getScaleVectorProperty()) {
2202 if (!prop->testStatus(App::Property::User3)) {
2203 const auto& v = ext->getScaleVector();
2204 if (canScale(v)) {
2205 pcTransform->scaleFactor.setValue(v.x, v.y, v.z);
2206 }
2207 SbMatrix matrix = convert(ext->getTransform(false));
2208 linkView->renderDoubleSide(matrix.det3() < 1e-7);
2209 }
2210 }
2211 else if (prop == ext->getPlacementProperty() || prop == ext->getLinkPlacementProperty()) {
2212 auto propLinkPlacement = ext->getLinkPlacementProperty();
2213 if (!propLinkPlacement || propLinkPlacement == prop || prop == ext->getPlacementProperty()) {
2214 const auto& v = ext->getScaleVector();
2215 if (canScale(v)) {
2216 pcTransform->scaleFactor.setValue(v.x, v.y, v.z);
2217 }
2218 SbMatrix matrix = convert(ext->getTransform(false));
2219 linkView->renderDoubleSide(matrix.det3() < 1e-7);
2220 }
2221 }
2222 else if (prop == ext->getLinkCopyOnChangeGroupProperty()) {
2223 if (auto group = ext->getLinkCopyOnChangeGroupValue()) {
2224 auto vp = freecad_cast<ViewProviderDocumentObject*>(
2225 Application::Instance->getViewProvider(group)
2226 );
2227 if (vp) {
2228 vp->hide();
2229 vp->ShowInTree.setValue(false);
2230 }
2231 }
2232 }
2233 else if (prop == ext->getLinkedObjectProperty()) {
2234
2235 if (!prop->testStatus(App::Property::User3)) {
2236 std::vector<std::string> subs;
2237 const char* subname = ext->getSubName();
2238 std::string sub;
2239 if (subname) {
2240 sub = subname;
2241 }
2242 hasSubElement = false;
2243 for (const auto& s : ext->getSubElements()) {
2244 if (s.empty()) {
2245 continue;
2246 }
2247 hasSubElement = true;
2248 subs.push_back(sub + s);
2249 }
2250
2251 if (subs.empty() && !sub.empty()) {
2252 subs.push_back(sub);
2253 }
2254
2255 hasSubName = !subs.empty();
2256 setLinkType(ext);
2257
2258 auto obj = ext->getLinkedObjectValue();
2259 linkView->setLink(obj, subs);
2260
2261 if (ext->_getShowElementValue()) {
2262 updateElementList(ext);
2263 }
2264 else {
2265 updateDataPrivate(ext, ext->_getElementCountProperty());
2266 }
2267
2268 // applyColors();
2269 signalChangeIcon();
2270 }
2271 }
2272 else if (prop == ext->getLinkTransformProperty()) {
2273 setLinkType(ext);
2274 applyColors();
2275 }
2276 else if (prop == ext->_getElementCountProperty()) {
2277 if (!ext->_getShowElementValue()) {
2278 linkView->setSize(ext->_getElementCountValue());
2279 updateDataPrivate(ext, ext->getVisibilityListProperty());
2280 updateDataPrivate(ext, ext->getPlacementListProperty());
2281 }
2282 }
2283 else if (prop == ext->_getShowElementProperty()) {
2284 if (!ext->_getShowElementValue()) {
2285
2286 auto linked = freecad_cast<ViewProviderDocumentObject*>(getLinkedView(true, ext));
2287 if (linked && linked->getDocument() == getDocument()) {
2288 linked->hide();
2289 }
2290
2291 const auto& elements = ext->_getElementListValue();
2292 // elements is about to be collapsed, preserve the materials
2293 if (!elements.empty()) {
2294 std::vector<App::Material> materials;
2295 boost::dynamic_bitset<> overrideMaterials;
2296 overrideMaterials.resize(elements.size(), false);
2297 bool overrideMaterial = false;
2298 bool hasMaterial = false;
2299 materials.reserve(elements.size());
2300 for (size_t i = 0; i < elements.size(); ++i) {
2301 auto element = freecad_cast<App::LinkElement*>(elements[i]);
2302 if (!element) {
2303 continue;
2304 }
2305 auto vp = freecad_cast<ViewProviderLink*>(
2306 Application::Instance->getViewProvider(element)
2307 );
2308 if (!vp) {
2309 continue;
2310 }
2311 overrideMaterial = overrideMaterial || vp->OverrideMaterial.getValue();
2312 hasMaterial = overrideMaterial || hasMaterial
2313 || vp->ShapeMaterial.getValue() != ShapeMaterial.getValue();
2314 materials.push_back(vp->ShapeMaterial.getValue());
2315 overrideMaterials[i] = vp->OverrideMaterial.getValue();
2316 }
2317 if (!overrideMaterial) {
2318 overrideMaterials.clear();
2319 }
2320 OverrideMaterialList.setStatus(App::Property::User3, true);
2321 OverrideMaterialList.setValue(overrideMaterials);
2322 OverrideMaterialList.setStatus(App::Property::User3, false);
2323 if (!hasMaterial) {
2324 materials.clear();
2325 }
2326 MaterialList.setStatus(App::Property::User3, true);
2327 MaterialList.setValue(materials);
2328 MaterialList.setStatus(App::Property::User3, false);
2329
2330 linkView->setSize(ext->_getElementCountValue());
2331 updateDataPrivate(ext, ext->getVisibilityListProperty());
2332 applyMaterial();
2333 applyColors();
2334 }
2335 }
2336 }
2337 else if (prop == ext->getScaleListProperty() || prop == ext->getPlacementListProperty()) {
2338 if (!prop->testStatus(App::Property::User3) && linkView->getSize()
2339 && !ext->_getShowElementValue()) {
2340 auto propPlacements = ext->getPlacementListProperty();
2341 auto propScales = ext->getScaleListProperty();
2342 if (propPlacements && linkView->getSize()) {
2343 const auto& touched = prop == propScales ? propScales->getTouchList()
2344 : propPlacements->getTouchList();
2345 if (touched.empty()) {
2346 for (int i = 0; i < linkView->getSize(); ++i) {
2347 Base::Matrix4D mat;
2348 if (propPlacements && propPlacements->getSize() > i) {
2349 mat = (*propPlacements)[i].toMatrix();
2350 }
2351 if (propScales && propScales->getSize() > i && canScale((*propScales)[i])) {
2352 Base::Matrix4D s;
2353 s.scale((*propScales)[i]);
2354 mat *= s;
2355 }
2356 linkView->setTransform(i, mat);
2357 }
2358 }
2359 else {
2360 for (int i : touched) {
2361 if (i < 0 || i >= linkView->getSize()) {
2362 continue;
2363 }
2364 Base::Matrix4D mat;
2365 if (propPlacements && propPlacements->getSize() > i) {
2366 mat = (*propPlacements)[i].toMatrix();
2367 }
2368 if (propScales && propScales->getSize() > i && canScale((*propScales)[i])) {
2369 Base::Matrix4D s;
2370 s.scale((*propScales)[i]);
2371 mat *= s;
2372 }
2373 linkView->setTransform(i, mat);
2374 }
2375 }
2376 }
2377 }
2378 }
2379 else if (prop == ext->getVisibilityListProperty()) {
2380 const auto& vis = ext->getVisibilityListValue();
2381 for (size_t i = 0; i < (size_t)linkView->getSize(); ++i) {
2382 if (vis.size() > i) {
2383 linkView->setElementVisible(i, vis[i]);
2384 }
2385 else {
2386 linkView->setElementVisible(i, true);
2387 }
2388 }
2389 }
2390 else if (prop == ext->_getElementListProperty()) {
2391 if (ext->_getShowElementValue()) {
2392 updateElementList(ext);
2393 }
2394 }
2395 }
2396
2397 void ViewProviderLink::updateElementList(App::LinkBaseExtension* ext)
2398 {
2399 const auto& elements = ext->_getElementListValue();
2400 if (OverrideMaterialList.getSize() || MaterialList.getSize()) {
2401 int i = -1;
2402 for (auto obj : elements) {
2403 ++i;
2404 auto vp = freecad_cast<ViewProviderLink*>(Application::Instance->getViewProvider(obj));
2405 if (!vp) {
2406 continue;
2407 }
2408 if (OverrideMaterialList.getSize() > i) {
2409 vp->OverrideMaterial.setValue(OverrideMaterialList[i]);
2410 }
2411 if (MaterialList.getSize() > i) {
2412 vp->ShapeMaterial.setValue(MaterialList[i]);
2413 }
2414 }
2415 OverrideMaterialList.setSize(0);
2416 MaterialList.setSize(0);
2417 }
2418 linkView->setChildren(elements, ext->getVisibilityListValue());
2419 applyColors();
2420 }
2421
2422 void ViewProviderLink::checkIcon(const App::LinkBaseExtension* ext)
2423 {
2424 if (!ext) {
2425 ext = getLinkExtension();
2426 if (!ext) {
2427 return;
2428 }
2429 }
2430 const char* icon;
2431 auto element = getObject<App::LinkElement>();
2432 if (element) {
2433 icon = _LinkElementIcon;
2434 }
2435 else if (!ext->getLinkedObjectProperty() && ext->getElementListProperty()) {
2436 icon = _LinkGroupIcon;
2437 }
2438 // else if(ext->_getElementCountValue())
2439 // icon = _LinkArrayIcon;
2440 else {
2441 icon = _LinkIcon;
2442 }
2443 qint64 cacheKey = 0;
2444 if (getObject()->getLinkedObject(false) != getObject()) {
2445 cacheKey = getOverlayPixmap().cacheKey();
2446 }
2447 if (icon != sPixmap || cacheKey != overlayCacheKey) {
2448 sPixmap = icon;
2449 signalChangeIcon();
2450 }
2451 }
2452
2453 void ViewProviderLink::applyMaterial()
2454 {
2455 if (OverrideMaterial.getValue()) {
2456 // Dispatch a generic Coin3D action to the linked object's scene graph.
2457 // If the linked object is a Part shape, its SoBrepFaceSet node will
2458 // handle this action and apply the color to all its faces.
2459 // This is decoupled and respects the core/module architecture.
2460
2461 // 1. Get the material from our property.
2462 const auto& material = ShapeMaterial.getValue();
2463
2464 // 2. Prepare the color for the rendering action. The action's ultimate
2465 // consumer (SoBrepFaceSet) expects a Base::Color where .a is transparency,
2466 // so we must perform the conversion here at the boundary.
2467 Base::Color renderColor = material.diffuseColor;
2468 renderColor.a = 1.0f - material.transparency;
2469
2470 // 3. Create a map with the "Face" wildcard to signify "all faces".
2471 std::map<std::string, Base::Color> colorMap;
2472 colorMap["Face"] = renderColor;
2473
2474 // 4. Create and dispatch the action. We use a secondary context action,
2475 // which is the established mechanism for this kind of override.
2476 SoSelectionElementAction action(
2477 SoSelectionElementAction::Color,
2478 true
2479 ); // true for secondary
2480 action.swapColors(colorMap);
2481 linkView->getLinkRoot()->doAction(&action);
2482
2483 // 5. Ensure the old global override mechanism is not used.
2484 linkView->setMaterial(-1, nullptr);
2485 }
2486 else {
2487 // OVERRIDE IS DISABLED:
2488 // We must clear the per-face override we just applied.
2489
2490 // 1. Dispatch an empty Color action to clear the secondary context.
2491 SoSelectionElementAction action(SoSelectionElementAction::Color, true);
2492 linkView->getLinkRoot()->doAction(&action);
2493
2494 // 2. Re-apply any other material settings (e.g., for array elements,
2495 // or clear the old global override if it was set).
2496 linkView->setMaterial(-1, nullptr);
2497 for (int i = 0; i < linkView->getSize(); ++i) {
2498 if (MaterialList.getSize() > i && OverrideMaterialList.getSize() > i
2499 && OverrideMaterialList[i]) {
2500 linkView->setMaterial(i, &MaterialList[i]);
2501 }
2502 else {
2503 linkView->setMaterial(i, nullptr);
2504 }
2505 }
2506 }
2507 }
2508
2509 void ViewProviderLink::finishRestoring()
2510 {
2511 FC_TRACE("finish restoring");
2512 auto ext = getLinkExtension();
2513 if (!ext) {
2514 return;
2515 }
2516 linkView->setDrawStyle(DrawStyle.getValue(), LineWidth.getValue(), PointSize.getValue());
2517 updateDataPrivate(ext, ext->getLinkedObjectProperty());
2518 if (ext->getLinkPlacementProperty()) {
2519 updateDataPrivate(ext, ext->getLinkPlacementProperty());
2520 }
2521 else {
2522 updateDataPrivate(ext, ext->getPlacementProperty());
2523 }
2524 updateDataPrivate(ext, ext->_getElementCountProperty());
2525 if (ext->getPlacementListProperty()) {
2526 updateDataPrivate(ext, ext->getPlacementListProperty());
2527 }
2528 else {
2529 updateDataPrivate(ext, ext->getScaleListProperty());
2530 }
2531 updateDataPrivate(ext, ext->_getElementListProperty());
2532 applyMaterial();
2533 applyColors();
2534
2535 // TODO: notify the tree. This is ugly, any other way?
2536 getDocument()->signalChangedObject(*this, ext->_LinkTouched);
2537
2538 if (childVp) {
2539 childVp->finishRestoring();
2540 }
2541 }
2542
2543 bool ViewProviderLink::hasElements(const App::LinkBaseExtension* ext) const
2544 {
2545 if (!ext) {
2546 ext = getLinkExtension();
2547 if (!ext) {
2548 return false;
2549 }
2550 }
2551 const auto& elements = ext->getElementListValue();
2552 return !elements.empty() && (int)elements.size() == ext->_getElementCountValue();
2553 }
2554
2555 bool ViewProviderLink::isGroup(const App::LinkBaseExtension* ext, bool plainGroup) const
2556 {
2557 if (!ext) {
2558 ext = getLinkExtension();
2559 if (!ext) {
2560 return false;
2561 }
2562 }
2563 return (plainGroup && ext->linkedPlainGroup())
2564 || (ext->getElementListProperty() && !ext->getLinkedObjectProperty());
2565 }
2566
2567 ViewProvider* ViewProviderLink::getLinkedView(bool real, const App::LinkBaseExtension* ext) const
2568 {
2569 if (!ext) {
2570 ext = getLinkExtension();
2571 }
2572 auto obj = ext && real ? ext->getTrueLinkedObject(true) : getObject()->getLinkedObject(true);
2573 if (obj && obj != getObject()) {
2574 return Application::Instance->getViewProvider(obj);
2575 }
2576 return nullptr;
2577 }
2578
2579 std::vector<App::DocumentObject*> ViewProviderLink::claimChildren() const
2580 {
2581 auto ext = getLinkExtension();
2582 std::vector<App::DocumentObject*> ret;
2583
2584 if (ext && !ext->_getShowElementValue() && ext->_getElementCountValue()) {
2585 // in array mode without element objects, we'd better not show the
2586 // linked object's children to avoid inconsistent behavior on selection.
2587 // We claim the linked object instead
2588 if (ext) {
2589 auto obj = ext->getLinkedObjectValue();
2590 if (obj) {
2591 ret.push_back(obj);
2592 }
2593 }
2594 }
2595 else if (hasElements(ext) || isGroup(ext)) {
2596 ret = ext->getElementListValue();
2597 if (ext->_getElementCountValue() && ext->getLinkClaimChildValue()
2598 && ext->getLinkedObjectValue()) {
2599 ret.insert(ret.begin(), ext->getLinkedObjectValue());
2600 }
2601 }
2602 else if (!hasSubName) {
2603 auto linked = getLinkedView(true);
2604 if (linked) {
2605 ret = linked->claimChildren();
2606 if (ext->getLinkClaimChildValue() && ext->getLinkedObjectValue()) {
2607 ret.insert(ret.begin(), ext->getLinkedObjectValue());
2608 }
2609 }
2610 }
2611 if (ext && ext->getLinkCopyOnChangeGroupValue()) {
2612 ret.insert(ret.begin(), ext->getLinkCopyOnChangeGroupValue());
2613 }
2614 return ret;
2615 }
2616
2617 bool ViewProviderLink::canDragObject(App::DocumentObject* obj) const
2618 {
2619 auto ext = getLinkExtension();
2620 if (isGroup(ext)) {
2621 return true;
2622 }
2623 if (hasElements(ext)) {
2624 return false;
2625 }
2626 auto linked = getLinkedView(false, ext);
2627 if (linked) {
2628 return linked->canDragObject(obj);
2629 }
2630 return false;
2631 }
2632
2633 bool ViewProviderLink::canDragObjects() const
2634 {
2635 auto ext = getLinkExtension();
2636 if (isGroup(ext)) {
2637 return true;
2638 }
2639 if (hasElements(ext)) {
2640 return false;
2641 }
2642 auto linked = getLinkedView(false, ext);
2643 if (linked) {
2644 return linked->canDragObjects();
2645 }
2646 return false;
2647 }
2648
2649 void ViewProviderLink::dragObject(App::DocumentObject* obj)
2650 {
2651 auto ext = getLinkExtension();
2652 if (isGroup(ext)) {
2653 const auto& objs = ext->getElementListValue();
2654 for (size_t i = 0; i < objs.size(); ++i) {
2655 if (obj == objs[i]) {
2656 ext->setLink(i, nullptr);
2657 break;
2658 }
2659 }
2660 return;
2661 }
2662 if (hasElements(ext)) {
2663 return;
2664 }
2665 auto linked = getLinkedView(false);
2666 if (linked) {
2667 linked->dragObject(obj);
2668 }
2669 }
2670
2671 bool ViewProviderLink::canDropObjects() const
2672 {
2673 auto ext = getLinkExtension();
2674 if (isGroup(ext)) {
2675 return true;
2676 }
2677 if (hasElements(ext)) {
2678 return false;
2679 }
2680 if (hasSubElement) {
2681 return true;
2682 }
2683 else if (hasSubName) {
2684 return false;
2685 }
2686 auto linked = getLinkedView(false, ext);
2687 if (linked) {
2688 return linked->canDropObjects();
2689 }
2690 return true;
2691 }
2692
2693 bool ViewProviderLink::canDropObjectEx(
2694 App::DocumentObject* obj,
2695 App::DocumentObject* owner,
2696 const char* subname,
2697 const std::vector<std::string>& subElements
2698 ) const
2699 {
2700 if (pcObject == obj || pcObject == owner) {
2701 return false;
2702 }
2703 auto ext = getLinkExtension();
2704 if (isGroup(ext)) {
2705 return true;
2706 }
2707 if (!ext || !ext->getLinkedObjectProperty() || hasElements(ext)) {
2708 return false;
2709 }
2710 if (!hasSubName && linkView->isLinked()) {
2711 auto linked = getLinkedView(false, ext);
2712 if (linked) {
2713 auto linkedVdp = freecad_cast<ViewProviderDocumentObject*>(linked);
2714 if (linkedVdp) {
2715 if (linkedVdp->getObject() == obj || linkedVdp->getObject() == owner) {
2716 return false;
2717 }
2718 }
2719 return linked->canDropObjectEx(obj, owner, subname, subElements);
2720 }
2721 }
2722 if (obj->getDocument() != getObject()->getDocument()
2723 && !freecad_cast<App::PropertyXLink*>(ext->getLinkedObjectProperty())) {
2724 return false;
2725 }
2726
2727 return true;
2728 }
2729
2730 std::string ViewProviderLink::dropObjectEx(
2731 App::DocumentObject* obj,
2732 App::DocumentObject* owner,
2733 const char* subname,
2734 const std::vector<std::string>& subElements
2735 )
2736 {
2737 auto ext = getLinkExtension();
2738 if (!ext) {
2739 return std::string();
2740 }
2741
2742 if (isGroup(ext)) {
2743 size_t size = ext->getElementListValue().size();
2744 ext->setLink(size, obj);
2745 return std::to_string(size) + ".";
2746 }
2747
2748 if (!ext->getLinkedObjectProperty() || hasElements(ext)) {
2749 return std::string();
2750 }
2751
2752 if (!hasSubName) {
2753 auto linked = getLinkedView(false, ext);
2754 if (linked) {
2755 return linked->dropObjectEx(obj, owner, subname, subElements);
2756 }
2757 }
2758 if (owner) {
2759 if (!ext->getSubElements().empty()) {
2760 ext->setLink(-1, owner, subname, subElements);
2761 }
2762 else {
2763 ext->setLink(-1, owner, subname);
2764 }
2765 }
2766 else if (!ext->getSubElements().empty()) {
2767 ext->setLink(-1, obj, nullptr, subElements);
2768 }
2769 else {
2770 ext->setLink(-1, obj, nullptr);
2771 }
2772 return std::string();
2773 }
2774
2775 bool ViewProviderLink::canDragAndDropObject(App::DocumentObject* obj) const
2776 {
2777 auto ext = getLinkExtension();
2778 if (!ext) {
2779 return true;
2780 }
2781 if (isGroup(ext)) {
2782 return ext->getLinkModeValue() < App::LinkBaseExtension::LinkModeAutoLink
2783 && obj->getDocument() == getObject()->getDocument();
2784 }
2785 if (!ext->getLinkedObjectProperty() || hasElements(ext)) {
2786 return false;
2787 }
2788 if (!hasSubName) {
2789 auto linked = getLinkedView(false, ext);
2790 if (linked) {
2791 return linked->canDragAndDropObject(obj);
2792 }
2793 }
2794 return false;
2795 }
2796
2797 bool ViewProviderLink::getElementPicked(const SoPickedPoint* pp, std::string& subname) const
2798 {
2799 if (!isSelectable()) {
2800 return false;
2801 }
2802 auto ext = getLinkExtension();
2803 if (!ext) {
2804 return false;
2805 }
2806 if (childVpLink && childVp) {
2807 auto path = pp->getPath();
2808 int idx = path->findNode(childVpLink->getSnapshot(LinkView::SnapshotTransform));
2809 if (idx >= 0) {
2810 return childVp->getElementPicked(pp, subname);
2811 }
2812 }
2813 bool ret = linkView->linkGetElementPicked(pp, subname);
2814 if (!ret) {
2815 return ret;
2816 }
2817 if (isGroup(ext, true)) {
2818 const char* sub = nullptr;
2819 int idx = App::LinkBaseExtension::getArrayIndex(subname.c_str(), &sub);
2820 if (idx >= 0) {
2821 --sub;
2822 assert(*sub == '.');
2823 const auto& elements = ext->_getElementListValue();
2824 subname.replace(0, sub - subname.c_str(), elements[idx]->getNameInDocument());
2825 }
2826 }
2827 return ret;
2828 }
2829
2830 bool ViewProviderLink::getDetailPath(const char* subname, SoFullPath* pPath, bool append, SoDetail*& det) const
2831 {
2832 auto ext = getLinkExtension();
2833 if (!ext) {
2834 return false;
2835 }
2836
2837 auto len = pPath->getLength();
2838 if (append) {
2839 appendPath(pPath, pcRoot);
2840 appendPath(pPath, pcModeSwitch);
2841 }
2842 if (childVpLink && getDefaultMode() == 1) {
2843 if (childVpLink->getDetail(false, LinkView::SnapshotTransform, subname, det, pPath)) {
2844 return true;
2845 }
2846 pPath->truncate(len);
2847 return false;
2848 }
2849 std::string _subname;
2850 if (!Base::Tools::isNullOrEmpty(subname)) {
2851 if (auto linked = ext->getLinkedObjectValue()) {
2852 if (const char* dot = strchr(subname, '.')) {
2853 if (subname[0] == '$') {
2854 CharRange sub(subname + 1, dot);
2855 if (!boost::equals(sub, linked->Label.getValue())) {
2856 dot = nullptr;
2857 }
2858 }
2859 else {
2860 CharRange sub(subname, dot);
2861 if (!boost::equals(sub, linked->getNameInDocument())) {
2862 dot = nullptr;
2863 }
2864 }
2865 if (dot && linked->getSubObject(dot + 1)) {
2866 subname = dot + 1;
2867 }
2868 }
2869 }
2870
2871 if (isGroup(ext, true) || hasElements(ext) || ext->getElementCountValue()) {
2872 int index = ext->getElementIndex(subname, &subname);
2873 if (index >= 0) {
2874 _subname = std::to_string(index) + '.' + subname;
2875 subname = _subname.c_str();
2876 }
2877 }
2878 }
2879 if (linkView->linkGetDetailPath(subname, pPath, det)) {
2880 return true;
2881 }
2882 pPath->truncate(len);
2883 return false;
2884 }
2885
2886 bool ViewProviderLink::onDelete(const std::vector<std::string>&)
2887 {
2888 auto element = getObject<App::LinkElement>();
2889 if (element && !element->canDelete()) {
2890 return false;
2891 }
2892
2893 auto link = getObject<App::Link>();
2894 if (link && link->ElementCount.getValue() != 0) {
2895 auto doc = link->getDocument();
2896 auto elements = link->ElementList.getValues();
2897 for (auto element : elements) {
2898 doc->removeObject(element->getNameInDocument());
2899 }
2900 }
2901
2902 auto ext = getLinkExtension();
2903 if (ext->isLinkMutated()) {
2904 auto linked = ext->getLinkedObjectValue();
2905 auto doc = ext->getContainer()->getDocument();
2906 if (linked->getDocument() == doc) {
2907 std::deque<std::string> objs;
2908 for (auto obj : ext->getOnChangeCopyObjects(nullptr, linked)) {
2909 if (obj->getDocument() == doc) {
2910 // getOnChangeCopyObjects() returns object in depending
2911 // order. So we delete it in reverse to avoid error
2912 // reported by some parent object failing to find child
2913 objs.emplace_front(obj->getNameInDocument());
2914 }
2915 }
2916 for (const auto& name : objs) {
2917 doc->removeObject(name.c_str());
2918 }
2919 }
2920 }
2921 return true;
2922 }
2923
2924 bool ViewProviderLink::canDelete(App::DocumentObject* obj) const
2925 {
2926 auto ext = getLinkExtension();
2927 if (isGroup(ext) || hasElements(ext) || hasSubElement) {
2928 return true;
2929 }
2930 auto linked = getLinkedView(false, ext);
2931 if (linked) {
2932 return linked->canDelete(obj);
2933 }
2934 return false;
2935 }
2936
2937 bool ViewProviderLink::linkEdit(const App::LinkBaseExtension* ext) const
2938 {
2939 if (!ext) {
2940 ext = getLinkExtension();
2941 }
2942 if (!ext || (!ext->_getShowElementValue() && ext->_getElementCountValue()) || hasElements(ext)
2943 || isGroup(ext) || hasSubName) {
2944 return false;
2945 }
2946 return linkView->isLinked();
2947 }
2948
2949 bool ViewProviderLink::doubleClicked()
2950 {
2951 if (linkEdit()) {
2952 return linkView->getLinkedView()->doubleClicked();
2953 }
2954 return getDocument()->setEdit(this, ViewProvider::Transform);
2955 }
2956
2957 void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
2958 {
2959 auto ext = getLinkExtension();
2960 if (!ext) {
2961 return;
2962 }
2963
2964 _setupContextMenu(ext, menu, receiver, member);
2965 Gui::ActionFunction* func = nullptr;
2966
2967 if (ext->isLinkedToConfigurableObject()) {
2968 auto src = ext->getLinkCopyOnChangeSourceValue();
2969 if (!src) {
2970 src = ext->getLinkedObjectValue();
2971 }
2972 if (src && !ext->getOnChangeCopyObjects(nullptr, src).empty()) {
2973 QAction* act = menu->addAction(QObject::tr("Setup Configurable Object"));
2974 act->setToolTip(
2975 QObject::tr(
2976 "Selects which object to copy or exclude when configuration changes. "
2977 "All external linked objects are excluded by default."
2978 )
2979 );
2980 act->setData(-1);
2981 if (!func) {
2982 func = new Gui::ActionFunction(menu);
2983 }
2984 func->trigger(act, [ext]() {
2985 try {
2986 std::vector<App::DocumentObject*> excludes;
2987 auto src = ext->getLinkCopyOnChangeSourceValue();
2988 if (!src) {
2989 src = ext->getLinkedObjectValue();
2990 }
2991 auto objs = ext->getOnChangeCopyObjects(&excludes, src);
2992 if (objs.empty()) {
2993 return;
2994 }
2995 DlgObjectSelection dlg({src}, excludes, getMainWindow());
2996 dlg.setMessage(
2997 QObject::tr("Select which objects to copy when the configuration is changed")
2998 );
2999 auto box = new QCheckBox(QObject::tr("Apply to all"), &dlg);
3000 box->setToolTip(QObject::tr("Applies the setting to all links"));
3001 box->setChecked(App::LinkParams::getCopyOnChangeApplyToAll());
3002 dlg.addCheckBox(box);
3003 if (dlg.exec() != QDialog::Accepted) {
3004 return;
3005 }
3006
3007 bool applyAll = box->isChecked();
3008 App::LinkParams::setCopyOnChangeApplyToAll(applyAll);
3009
3010 App::Link::OnChangeCopyOptions options {App::Link::OnChangeCopyOptions::None};
3011 if (applyAll) {
3012 options |= App::Link::OnChangeCopyOptions::ApplyAll;
3013 }
3014
3015 App::AutoTransaction guard("Setup configurable object");
3016 auto sels = dlg.getSelections(DlgObjectSelection::SelectionOptions::InvertSort);
3017 for (const auto& exclude : excludes) {
3018 auto iter = std::lower_bound(sels.begin(), sels.end(), exclude);
3019 if (iter == sels.end() || *iter != exclude) {
3020 ext->setOnChangeCopyObject(exclude, options);
3021 }
3022 else {
3023 sels.erase(iter);
3024 }
3025 }
3026 options |= App::Link::OnChangeCopyOptions::Exclude;
3027 for (auto obj : sels) {
3028 ext->setOnChangeCopyObject(obj, options);
3029 }
3030 if (!applyAll) {
3031 ext->monitorOnChangeCopyObjects(ext->getOnChangeCopyObjects());
3032 }
3033 else {
3034 std::set<App::LinkBaseExtension*> exts;
3035 for (auto o : App::Document::getDependencyList(objs)) {
3036 if (auto ext = o->getExtensionByType<App::LinkBaseExtension>(true)) {
3037 exts.insert(ext);
3038 }
3039 }
3040 for (auto ext : exts) {
3041 ext->monitorOnChangeCopyObjects(ext->getOnChangeCopyObjects());
3042 }
3043 }
3044 Command::updateActive();
3045 }
3046 catch (Base::Exception& e) {
3047 e.reportException();
3048 }
3049 });
3050 }
3051
3052 if (ext->getLinkCopyOnChangeValue() == 0) {
3053 auto submenu = menu->addMenu(QObject::tr("Copy on Change"));
3054 auto act = submenu->addAction(QObject::tr("Enable"));
3055 act->setToolTip(
3056 QObject::tr("Enable auto copy of linked object when its configuration is changed")
3057 );
3058 act->setData(-1);
3059 if (!func) {
3060 func = new Gui::ActionFunction(menu);
3061 }
3062 func->trigger(act, [ext]() {
3063 try {
3064 App::AutoTransaction guard("Enable Link copy on change");
3065 ext->getLinkCopyOnChangeProperty()->setValue(1);
3066 Command::updateActive();
3067 }
3068 catch (Base::Exception& e) {
3069 e.reportException();
3070 }
3071 });
3072 act = submenu->addAction(QObject::tr("Tracking"));
3073 act->setToolTip(
3074 QObject::tr(
3075 "Copies the linked object when its configuration is changed.\n"
3076 "Also auto redo the copy if the original linked object is changed.\n"
3077 )
3078 );
3079 act->setData(-1);
3080 func->trigger(act, [ext]() {
3081 try {
3082 App::AutoTransaction guard("Enable Link tracking");
3083 ext->getLinkCopyOnChangeProperty()->setValue(3);
3084 Command::updateActive();
3085 }
3086 catch (Base::Exception& e) {
3087 e.reportException();
3088 }
3089 });
3090 }
3091 }
3092
3093 if (ext->getLinkCopyOnChangeValue() != 2 && ext->getLinkCopyOnChangeValue() != 0) {
3094 QAction* act = menu->addAction(QObject::tr("Disable Copy on Change"));
3095 act->setData(-1);
3096 if (!func) {
3097 func = new Gui::ActionFunction(menu);
3098 }
3099 func->trigger(act, [ext]() {
3100 try {
3101 App::AutoTransaction guard("Disable copy on change");
3102 ext->getLinkCopyOnChangeProperty()->setValue((long)0);
3103 Command::updateActive();
3104 }
3105 catch (Base::Exception& e) {
3106 e.reportException();
3107 }
3108 });
3109 }
3110
3111 if (ext->isLinkMutated()) {
3112 QAction* act = menu->addAction(QObject::tr("Refresh Configurable Object"));
3113 act->setToolTip(
3114 QObject::tr(
3115 "Synchronizes the original configurable source object by\n"
3116 "creating a new deep copy. Any changes made to\n"
3117 "the current copy will be lost.\n"
3118 )
3119 );
3120 act->setData(-1);
3121 if (!func) {
3122 func = new Gui::ActionFunction(menu);
3123 }
3124 func->trigger(act, [ext]() {
3125 try {
3126 App::AutoTransaction guard("Link refresh");
3127 ext->syncCopyOnChange();
3128 Command::updateActive();
3129 }
3130 catch (Base::Exception& e) {
3131 e.reportException();
3132 }
3133 });
3134 }
3135 }
3136
3137 void ViewProviderLink::_setupContextMenu(
3138 App::LinkBaseExtension* ext,
3139 QMenu* menu,
3140 QObject* receiver,
3141 const char* member
3142 )
3143 {
3144 if (linkEdit(ext)) {
3145 if (auto linkvp = freecad_cast<ViewProviderLink*>(linkView->getLinkedView())) {
3146 linkvp->_setupContextMenu(ext, menu, receiver, member);
3147 }
3148 else {
3149 linkView->getLinkedView()->setupContextMenu(menu, receiver, member);
3150 }
3151 }
3152
3153 if (ext->getLinkedObjectProperty() && ext->_getShowElementProperty()
3154 && ext->_getElementCountValue() > 1) {
3155 auto action = menu->addAction(QObject::tr("Toggle Array Elements"), [ext] {
3156 try {
3157 App::AutoTransaction guard(QT_TRANSLATE_NOOP("Command", "Toggle array elements"));
3158 ext->getShowElementProperty()->setValue(!ext->getShowElementValue());
3159 Command::updateActive();
3160 }
3161 catch (Base::Exception& e) {
3162 e.reportException();
3163 }
3164 });
3165 action->setToolTip(
3166 QObject::tr("Changes whether to show each link array element as individual objects")
3167 );
3168 }
3169
3170 if ((ext->getPlacementProperty() && !ext->getPlacementProperty()->isReadOnly())
3171 || (ext->getLinkPlacementProperty() && !ext->getLinkPlacementProperty()->isReadOnly())) {
3172 bool found = false;
3173 const auto actions = menu->actions();
3174 for (auto action : actions) {
3175 if (action->data().toInt() == ViewProvider::Transform) {
3176 found = true;
3177 break;
3178 }
3179 }
3180 if (!found) {
3181 QIcon iconObject = mergeGreyableOverlayIcons(
3182 Gui::BitmapFactory().pixmap("Std_TransformManip.svg")
3183 );
3184 QAction* act = menu->addAction(iconObject, QObject::tr("Transform"), receiver, member);
3185 act->setToolTip(QObject::tr("Transforms the object at the origin of the placement"));
3186 act->setData(QVariant((int)ViewProvider::Transform));
3187 }
3188 }
3189
3190 if (ext->getColoredElementsProperty()) {
3191 bool found = false;
3192 const auto actions = menu->actions();
3193 for (auto action : actions) {
3194 if (action->data().toInt() == ViewProvider::Color) {
3195 action->setText(QObject::tr("Override Colors"));
3196 found = true;
3197 break;
3198 }
3199 }
3200 if (!found) {
3201 QAction* act = menu->addAction(QObject::tr("Override Colors"), receiver, member);
3202 act->setData(QVariant((int)ViewProvider::Color));
3203 }
3204 }
3205
3206 auto cmd = Application::Instance->commandManager().getCommandByName("Std_LinkSelectLinked");
3207 menu->addAction(cmd->getAction()->action());
3208 }
3209
3210 bool ViewProviderLink::initDraggingPlacement()
3211 {
3212 Base::PyGILStateLocker lock;
3213 try {
3214 auto* proxy = getPropertyByName("Proxy");
3215 if (proxy && proxy->is<App::PropertyPythonObject>()) {
3216 Py::Object feature = static_cast<App::PropertyPythonObject*>(proxy)->getValue();
3217 const char* fname = "initDraggingPlacement";
3218 if (feature.hasAttr(fname)) {
3219 Py::Callable method(feature.getAttr(fname));
3220 Py::Tuple arg;
3221 Py::Object ret(method.apply(arg));
3222 if (ret.isTuple()) {
3223 PyObject *pymat, *pypla, *pybbox;
3224 if (!PyArg_ParseTuple(
3225 ret.ptr(),
3226 "O!O!O!",
3227 &Base::MatrixPy::Type,
3228 &pymat,
3229 &Base::PlacementPy::Type,
3230 &pypla,
3231 &Base::BoundBoxPy::Type,
3232 &pybbox
3233 )) {
3234 FC_ERR("initDraggingPlacement() expects return of type tuple(matrix,placement,boundbox)");
3235 return false;
3236 }
3237 dragCtx = std::make_unique<DraggerContext>();
3238 dragCtx->initialPlacement
3239 = *static_cast<Base::PlacementPy*>(pypla)->getPlacementPtr();
3240 dragCtx->preTransform = *static_cast<Base::MatrixPy*>(pymat)->getMatrixPtr();
3241 dragCtx->bbox = *static_cast<Base::BoundBoxPy*>(pybbox)->getBoundBoxPtr();
3242 return true;
3243 }
3244 else if (!ret.isTrue()) {
3245 return false;
3246 }
3247 }
3248 }
3249 }
3250 catch (Py::Exception&) {
3251 Base::PyException e;
3252 e.reportException();
3253 return false;
3254 }
3255
3256 auto ext = getLinkExtension();
3257 if (!ext) {
3258 FC_ERR("no link extension");
3259 return false;
3260 }
3261 if (!ext->hasPlacement()) {
3262 FC_ERR("no placement");
3263 return false;
3264 }
3265 auto doc = Application::Instance->editDocument();
3266 if (!doc) {
3267 FC_ERR("no editing document");
3268 return false;
3269 }
3270
3271 dragCtx = std::make_unique<DraggerContext>();
3272
3273 dragCtx->preTransform = doc->getEditingTransform();
3274 const auto& pla = getObject()->getPlacementProperty()->getValue();
3275
3276 // Cancel out our own transformation from the editing transform, because
3277 // the dragger is meant to change our transformation.
3278 dragCtx->preTransform *= pla.inverse().toMatrix();
3279
3280 dragCtx->bbox = getBoundingBox(nullptr, false);
3281 // The returned bounding box is before our own transform, but we still need
3282 // to scale it to get the correct center.
3283 auto scale = ext->getScaleVector();
3284 dragCtx->bbox.ScaleX(scale.x);
3285 dragCtx->bbox.ScaleY(scale.y);
3286 dragCtx->bbox.ScaleZ(scale.z);
3287
3288 App::PropertyPlacement* propPla = nullptr;
3289 if (ext->getLinkTransformValue() && ext->getLinkedObjectValue()) {
3290 propPla = freecad_cast<App::PropertyPlacement*>(
3291 ext->getLinkedObjectValue()->getPropertyByName("Placement")
3292 );
3293 }
3294 if (propPla) {
3295 dragCtx->initialPlacement = pla * propPla->getValue();
3296 dragCtx->mat *= propPla->getValue().inverse().toMatrix();
3297 }
3298 else {
3299 dragCtx->initialPlacement = pla;
3300 }
3301
3302 return true;
3303 }
3304
3305 ViewProvider* ViewProviderLink::startEditing(int mode)
3306 {
3307 if (mode == ViewProvider::Color) {
3308 auto ext = getLinkExtension();
3309 if (!ext || !ext->getColoredElementsProperty()) {
3310 if (linkEdit(ext)) {
3311 return linkView->getLinkedView()->startEditing(mode);
3312 }
3313 }
3314 return inherited::startEditing(mode);
3315 }
3316
3317 static thread_local bool _pendingTransform;
3318 static thread_local Matrix4D _editingTransform;
3319
3320 auto doc = Application::Instance->editDocument();
3321
3322 if (mode == ViewProvider::Transform) {
3323 if (_pendingTransform && doc) {
3324 doc->setEditingTransform(_editingTransform);
3325 }
3326
3327 if (!initDraggingPlacement()) {
3328 return nullptr;
3329 }
3330
3331 if (auto result = inherited::startEditing(mode)) {
3332 if (transformDragger.get()) {
3333 transformDragger->addStartCallback(dragStartCallback, this);
3334 transformDragger->addFinishCallback(dragFinishCallback, this);
3335 transformDragger->addMotionCallback(dragMotionCallback, this);
3336
3337 setDraggerPlacement(dragCtx->initialPlacement);
3338 }
3339
3340 return result;
3341 }
3342 }
3343
3344 if (!linkEdit()) {
3345 FC_ERR("unsupported edit mode " << mode);
3346 return nullptr;
3347 }
3348
3349 // TODO: the 0x8000 mask here is for caller to disambiguate the intention
3350 // here, whether they want to, say transform the link itself or the linked
3351 // object. Use of a mask here will allow forwarding those editing modes that
3352 // are supported by both the link and the linked object, such as transform
3353 // and set color. We need to find a better place to declare this constant.
3354 mode &= ~0x8000;
3355
3356 if (!doc) {
3357 FC_ERR("no editing document");
3358 return nullptr;
3359 }
3360
3361 // We are forwarding the editing request to linked object. We need to
3362 // adjust the editing transformation.
3363 Base::Matrix4D mat;
3364 auto linked = getObject()->getLinkedObject(true, &mat, false);
3365 if (!linked || linked == getObject()) {
3366 FC_ERR("no linked object");
3367 return nullptr;
3368 }
3369 auto vpd = freecad_cast<ViewProviderDocumentObject*>(
3370 Application::Instance->getViewProvider(linked)
3371 );
3372 if (!vpd) {
3373 FC_ERR("no linked viewprovider");
3374 return nullptr;
3375 }
3376 // Amend the editing transformation with the link transformation.
3377 // But save it first in case the linked object reroute the editing request
3378 // back to us.
3379 _editingTransform = doc->getEditingTransform();
3380 doc->setEditingTransform(doc->getEditingTransform() * mat);
3381 Base::FlagToggler<> guard(_pendingTransform);
3382 return vpd->startEditing(mode);
3383 }
3384
3385 bool ViewProviderLink::setEdit(int ModNum)
3386 {
3387 if (ModNum == ViewProvider::Color) {
3388 auto ext = getLinkExtension();
3389 if (!ext || !ext->getColoredElementsProperty()) {
3390 return false;
3391 }
3392 TaskView::TaskDialog* dlg = Control().activeDialog();
3393 if (dlg) {
3394 Control().showDialog(dlg);
3395 return false;
3396 }
3397 Selection().clearSelection();
3398 return true;
3399 }
3400
3401 return inherited::setEdit(ModNum);
3402 }
3403
3404 void ViewProviderLink::setEditViewer(Gui::View3DInventorViewer* viewer, int ModNum)
3405 {
3406 if (ModNum == ViewProvider::Color) {
3407 Gui::Control().showDialog(new TaskElementColors(this));
3408 return;
3409 }
3410
3411 ViewProviderDragger::setEditViewer(viewer, ModNum);
3412
3413 viewer->setupEditingRoot(transformDragger, &dragCtx->preTransform);
3414 }
3415
3416 void ViewProviderLink::unsetEditViewer(Gui::View3DInventorViewer* viewer)
3417 {
3418 dragCtx.reset();
3419
3420 inherited::unsetEditViewer(viewer);
3421 }
3422
3423 bool ViewProviderLink::callDraggerProxy(const char* fname)
3424 {
3425 if (!transformDragger) {
3426 return false;
3427 }
3428
3429 Base::PyGILStateLocker lock;
3430 try {
3431 auto* proxy = getPropertyByName("Proxy");
3432 if (proxy && proxy->is<App::PropertyPythonObject>()) {
3433 Py::Object feature = static_cast<App::PropertyPythonObject*>(proxy)->getValue();
3434 if (feature.hasAttr(fname)) {
3435 Py::Callable method(feature.getAttr(fname));
3436 Py::Tuple args;
3437 if (method.apply(args).isTrue()) {
3438 return true;
3439 }
3440 }
3441 }
3442 }
3443 catch (Py::Exception&) {
3444 Base::PyException e;
3445 e.reportException();
3446 return true;
3447 }
3448
3449 return false;
3450 }
3451
3452 void ViewProviderLink::dragStartCallback(void* data, SoDragger*)
3453 {
3454 auto me = static_cast<ViewProviderLink*>(data);
3455
3456 me->dragCtx->initialPlacement = me->getDraggerPlacement();
3457 me->callDraggerProxy("onDragStart");
3458 }
3459
3460 void ViewProviderLink::dragFinishCallback(void* data, SoDragger*)
3461 {
3462 auto me = static_cast<ViewProviderLink*>(data);
3463 me->callDraggerProxy("onDragEnd");
3464
3465 if (me->dragCtx->cmdPending) {
3466 if (me->getDraggerPlacement() == me->dragCtx->initialPlacement) {
3467 me->getDocument()->abortCommand();
3468 }
3469 else {
3470 me->getDocument()->commitCommand();
3471 }
3472 }
3473 }
3474
3475 void ViewProviderLink::dragMotionCallback(void* data, SoDragger*)
3476 {
3477 auto me = static_cast<ViewProviderLink*>(data);
3478 me->callDraggerProxy("onDragMotion");
3479 }
3480
3481 void ViewProviderLink::updateLinks(ViewProvider* vp)
3482 {
3483 try {
3484 auto ext = vp->getExtensionByType<ViewProviderLinkObserver>(true);
3485 if (ext && ext->linkInfo) {
3486 ext->linkInfo->update();
3487 }
3488 }
3489 catch (const Base::TypeError& e) {
3490 e.reportException();
3491 }
3492 catch (const Base::ValueError& e) {
3493 e.reportException();
3494 }
3495 }
3496
3497 PyObject* ViewProviderLink::getPyObject()
3498 {
3499 if (!pyViewObject) {
3500 pyViewObject = new ViewProviderLinkPy(this);
3501 }
3502 pyViewObject->IncRef();
3503 return pyViewObject;
3504 }
3505
3506 PyObject* ViewProviderLink::getPyLinkView()
3507 {
3508 return linkView->getPyObject();
3509 }
3510
3511 std::map<std::string, Base::Color> ViewProviderLink::getElementColors(const char* subname) const
3512 {
3513 bool isPrefix = true;
3514 if (!subname) {
3515 subname = "";
3516 }
3517 else {
3518 auto len = strlen(subname);
3519 isPrefix = !len || subname[len - 1] == '.';
3520 }
3521 std::map<std::string, Base::Color> colors;
3522 auto ext = getLinkExtension();
3523 if (!ext || !ext->getColoredElementsProperty()) {
3524 return colors;
3525 }
3526 const auto& subs = ext->getColoredElementsProperty()->getShadowSubs();
3527 int size = OverrideColorList.getSize();
3528
3529 std::string wildcard(subname);
3530 if (wildcard == "Face" || wildcard == "Face*" || wildcard.empty()) {
3531 if (wildcard.size() == 4 || OverrideMaterial.getValue()) {
3532 Base::Color c = ShapeMaterial.getValue().diffuseColor;
3533 c.setTransparency(ShapeMaterial.getValue().transparency);
3534 colors["Face"] = c;
3535 if (wildcard.size() == 4) {
3536 return colors;
3537 }
3538 }
3539 if (!wildcard.empty()) {
3540 wildcard.resize(4);
3541 }
3542 }
3543 else if (wildcard == "Edge*") {
3544 wildcard.resize(4);
3545 }
3546 else if (wildcard == "Vertex*") {
3547 wildcard.resize(5);
3548 }
3549 else if (wildcard == ViewProvider::hiddenMarker() + "*") {
3550 wildcard.resize(ViewProvider::hiddenMarker().size());
3551 }
3552 else {
3553 wildcard.clear();
3554 }
3555
3556 int i = -1;
3557 if (!wildcard.empty()) {
3558 for (const auto& sub : subs) {
3559 if (++i >= size) {
3560 break;
3561 }
3562 auto pos = sub.oldName.rfind('.');
3563 if (pos == std::string::npos) {
3564 pos = 0;
3565 }
3566 else {
3567 ++pos;
3568 }
3569 const char* element = sub.oldName.c_str() + pos;
3570 if (boost::starts_with(element, wildcard)) {
3571 colors[sub.oldName] = OverrideColorList[i];
3572 }
3573 else if (!element[0] && wildcard == "Face") {
3574 colors[sub.oldName.substr(0, element - sub.oldName.c_str()) + wildcard]
3575 = OverrideColorList[i];
3576 }
3577 }
3578
3579 // In case of multi-level linking, we recursively call into each level,
3580 // and merge the colors
3581 auto vp = this;
3582 while (true) {
3583 if (wildcard != ViewProvider::hiddenMarker() && vp->OverrideMaterial.getValue()) {
3584 auto color = ShapeMaterial.getValue().diffuseColor;
3585 color.setTransparency(ShapeMaterial.getValue().transparency);
3586 colors.emplace(wildcard, color);
3587 }
3588 auto link = vp->getObject()->getLinkedObject(false);
3589 if (!link || link == vp->getObject()) {
3590 break;
3591 }
3592 auto next = freecad_cast<ViewProviderLink*>(Application::Instance->getViewProvider(link));
3593 if (!next) {
3594 break;
3595 }
3596 for (const auto& v : next->getElementColors(subname)) {
3597 colors.insert(v);
3598 }
3599 vp = next;
3600 }
3601 if (wildcard != ViewProvider::hiddenMarker()) {
3602 // Get collapsed array color override.
3603 auto ext = vp->getLinkExtension();
3604 if (ext->_getElementCountValue() && !ext->_getShowElementValue()) {
3605 const auto& overrides = vp->OverrideMaterialList.getValues();
3606 int i = -1;
3607 for (const auto& mat : vp->MaterialList.getValues()) {
3608 if (++i >= (int)overrides.size()) {
3609 break;
3610 }
3611 if (!overrides[i]) {
3612 continue;
3613 }
3614 auto color = mat.diffuseColor;
3615 color.setTransparency(mat.transparency);
3616 colors.emplace(std::to_string(i) + "." + wildcard, color);
3617 }
3618 }
3619 }
3620 return colors;
3621 }
3622
3623 int element_count = ext->getElementCountValue();
3624
3625 for (const auto& sub : subs) {
3626 if (++i >= size) {
3627 break;
3628 }
3629
3630 int offset = 0;
3631
3632 if (!sub.oldName.empty() && element_count && !std::isdigit(sub.oldName[0])) {
3633 // For checking and expanding color override of array base
3634 if (!subname[0]) {
3635 std::ostringstream ss;
3636 ss << "0." << sub.oldName;
3637 if (getObject()->getSubObject(ss.str().c_str())) {
3638 for (int j = 0; j < element_count; ++j) {
3639 ss.str("");
3640 ss << j << '.' << sub.oldName;
3641 colors.emplace(ss.str(), OverrideColorList[i]);
3642 }
3643 continue;
3644 }
3645 }
3646 else if (std::isdigit(subname[0])) {
3647 const char* dot = strchr(subname, '.');
3648 if (dot) {
3649 offset = dot - subname + 1;
3650 }
3651 }
3652 }
3653
3654 if (isPrefix) {
3655 if (!boost::starts_with(sub.newName, subname + offset)
3656 && !boost::starts_with(sub.oldName, subname + offset)) {
3657 continue;
3658 }
3659 }
3660 else if (sub.newName != subname + offset && sub.oldName != subname + offset) {
3661 continue;
3662 }
3663
3664 if (offset) {
3665 colors.emplace(std::string(subname, offset) + sub.oldName, OverrideColorList[i]);
3666 }
3667 else {
3668 colors[sub.oldName] = OverrideColorList[i];
3669 }
3670 }
3671
3672 if (!subname[0]) {
3673 return colors;
3674 }
3675
3676 bool found = true;
3677 if (colors.empty()) {
3678 found = false;
3679 colors.emplace(subname, Base::Color());
3680 }
3681 std::map<std::string, Base::Color> ret;
3682 for (const auto& v : colors) {
3683 const char* pos = nullptr;
3684 auto sobj = getObject()->resolve(v.first.c_str(), nullptr, nullptr, &pos);
3685 if (!sobj || !pos) {
3686 continue;
3687 }
3688 auto link = sobj->getLinkedObject(true);
3689 if (!link || link == getObject()) {
3690 continue;
3691 }
3692 auto vp = Application::Instance->getViewProvider(sobj->getLinkedObject(true));
3693 if (!vp) {
3694 continue;
3695 }
3696 for (const auto& v2 : vp->getElementColors(!pos[0] ? "Face" : pos)) {
3697 std::string name;
3698 if (pos[0]) {
3699 name = v.first.substr(0, pos - v.first.c_str()) + v2.first;
3700 }
3701 else {
3702 name = v.first;
3703 }
3704 ret[name] = found ? v.second : v2.second;
3705 }
3706 }
3707 return ret;
3708 }
3709
3710 void ViewProviderLink::setElementColors(const std::map<std::string, Base::Color>& colorMap)
3711 {
3712 auto ext = getLinkExtension();
3713 if (!ext || !ext->getColoredElementsProperty()) {
3714 return;
3715 }
3716
3717 // For checking and collapsing array element color
3718 std::map<std::string, std::map<int, Base::Color>> subMap;
3719 int element_count = ext->getElementCountValue();
3720
3721 std::vector<std::string> subs;
3722 std::vector<Base::Color> colors;
3723 Base::Color faceColor;
3724 bool hasFaceColor = false;
3725 for (const auto& v : colorMap) {
3726 if (!hasFaceColor && v.first == "Face") {
3727 hasFaceColor = true;
3728 faceColor = v.second;
3729 continue;
3730 }
3731
3732 if (element_count && !v.first.empty() && std::isdigit(v.first[0])) {
3733 // In case of array, check if there are override of the same
3734 // sub-element for every array element. And collapse those overrides
3735 // into one without the index.
3736 const char* dot = strchr(v.first.c_str(), '.');
3737 if (dot) {
3738 subMap[dot + 1][std::atoi(v.first.c_str())] = v.second;
3739 continue;
3740 }
3741 }
3742 subs.push_back(v.first);
3743 colors.push_back(v.second);
3744 }
3745 for (auto& v : subMap) {
3746 if (element_count == (int)v.second.size()) {
3747 Base::Color firstColor = v.second.begin()->second;
3748 subs.push_back(v.first);
3749 colors.push_back(firstColor);
3750 for (auto it = v.second.begin(); it != v.second.end();) {
3751 if (it->second == firstColor) {
3752 it = v.second.erase(it);
3753 }
3754 else {
3755 ++it;
3756 }
3757 }
3758 }
3759 std::ostringstream ss;
3760 for (const auto& colorInfo : v.second) {
3761 ss.str("");
3762 ss << colorInfo.first << '.' << v.first;
3763 subs.push_back(ss.str());
3764 colors.push_back(colorInfo.second);
3765 }
3766 }
3767
3768 auto prop = ext->getColoredElementsProperty();
3769 if (subs != prop->getSubValues() || colors != OverrideColorList.getValues()) {
3770 prop->setStatus(App::Property::User3, true);
3771 prop->setValue(getObject(), subs);
3772 prop->setStatus(App::Property::User3, false);
3773 OverrideColorList.setValues(colors);
3774 }
3775 if (hasFaceColor) {
3776 auto mat = ShapeMaterial.getValue();
3777 mat.diffuseColor = faceColor;
3778 mat.transparency = faceColor.transparency();
3779 ShapeMaterial.setStatus(App::Property::User3, true);
3780 ShapeMaterial.setValue(mat);
3781 ShapeMaterial.setStatus(App::Property::User3, false);
3782 }
3783 OverrideMaterial.setValue(hasFaceColor);
3784 }
3785
3786 void ViewProviderLink::applyColors()
3787 {
3788 auto ext = getLinkExtension();
3789 if (!ext || !ext->getColoredElementsProperty()) {
3790 return;
3791 }
3792
3793 SoSelectionElementAction action(SoSelectionElementAction::Color, true);
3794 // reset color and visibility first
3795 action.apply(linkView->getLinkRoot());
3796
3797 std::map<std::string, std::map<std::string, Base::Color>> colorMap;
3798 std::set<std::string> hideList;
3799 auto colors = getElementColors();
3800 colors.erase("Face");
3801 for (const auto& v : colors) {
3802 const char* subname = v.first.c_str();
3803 const char* element = nullptr;
3804 auto sobj = getObject()->resolve(subname, nullptr, nullptr, &element);
3805 if (!sobj || !element) {
3806 continue;
3807 }
3808 if (ViewProvider::hiddenMarker() == element) {
3809 hideList.emplace(subname, element - subname);
3810 }
3811 else {
3812 colorMap[std::string(subname, element - subname)][element] = v.second;
3813 }
3814 }
3815
3816 SoTempPath path(10);
3817 path.ref();
3818 for (auto& v : colorMap) {
3819 action.swapColors(v.second);
3820 if (v.first.empty()) {
3821 action.apply(linkView->getLinkRoot());
3822 continue;
3823 }
3824 SoDetail* det = nullptr;
3825 path.truncate(0);
3826 if (getDetailPath(v.first.c_str(), &path, false, det)) {
3827 action.apply(&path);
3828 }
3829 delete det;
3830 }
3831
3832 action.setType(SoSelectionElementAction::Hide);
3833 for (const auto& sub : hideList) {
3834 SoDetail* det = nullptr;
3835 path.truncate(0);
3836 if (!sub.empty() && getDetailPath(sub.c_str(), &path, false, det)) {
3837 action.apply(&path);
3838 }
3839 delete det;
3840 }
3841 path.unrefNoDelete();
3842 }
3843
3844 void ViewProviderLink::setOverrideMode(const std::string& mode)
3845 {
3846 auto ext = getLinkExtension();
3847 if (!ext) {
3848 return;
3849 }
3850 auto obj = ext->getTrueLinkedObject(false);
3851 if (obj && obj != getObject()) {
3852 auto vp = Application::Instance->getViewProvider(obj);
3853 vp->setOverrideMode(mode);
3854 }
3855 if (childVp) {
3856 childVp->setOverrideMode(mode);
3857 }
3858 }
3859
3860 void ViewProviderLink::onBeforeChange(const App::Property* prop)
3861 {
3862 if (prop == &ChildViewProvider) {
3863 if (childVp) {
3864 childVp->beforeDelete();
3865 pcModeSwitch->replaceChild(1, linkView->getLinkRoot());
3866 childVpLink.reset();
3867 childVp = nullptr;
3868 }
3869 }
3870 inherited::onBeforeChange(prop);
3871 }
3872
3873 static bool isExcludedProperties(const char* name)
3874 {
3875 #define CHECK_EXCLUDE_PROP(_name) \
3876 if (strcmp(name, #_name) == 0) \
3877 return true;
3878 CHECK_EXCLUDE_PROP(Proxy);
3879 return false;
3880 }
3881
3882 App::Property* ViewProviderLink::getPropertyByName(const char* name) const
3883 {
3884 auto prop = inherited::getPropertyByName(name);
3885 if (prop || isExcludedProperties(name)) {
3886 return prop;
3887 }
3888 if (childVp) {
3889 prop = childVp->getPropertyByName(name);
3890 if (prop && !prop->testStatus(App::Property::Hidden)) {
3891 return prop;
3892 }
3893 prop = nullptr;
3894 }
3895 if (pcObject && pcObject->canLinkProperties()) {
3896 auto linked = getLinkedViewProvider(nullptr, true);
3897 if (linked && linked != this) {
3898 prop = linked->getPropertyByName(name);
3899 }
3900 }
3901 return prop;
3902 }
3903
3904 void ViewProviderLink::getPropertyMap(std::map<std::string, App::Property*>& Map) const
3905 {
3906 inherited::getPropertyMap(Map);
3907 if (!childVp) {
3908 return;
3909 }
3910 std::map<std::string, App::Property*> childMap;
3911 childVp->getPropertyMap(childMap);
3912 for (const auto& v : childMap) {
3913 auto ret = Map.insert(v);
3914 if (!ret.second) {
3915 auto myProp = ret.first->second;
3916 if (myProp->testStatus(App::Property::Hidden)) {
3917 ret.first->second = v.second;
3918 }
3919 }
3920 }
3921 }
3922
3923 void ViewProviderLink::visitProperties(const std::function<void(App::Property*)>& visitor) const
3924 {
3925 inherited::visitProperties(visitor);
3926 if (childVp != nullptr) {
3927 childVp->visitProperties(visitor);
3928 }
3929 }
3930
3931 void ViewProviderLink::getPropertyList(std::vector<App::Property*>& List) const
3932 {
3933 std::map<std::string, App::Property*> Map;
3934 getPropertyMap(Map);
3935 List.reserve(List.size() + Map.size());
3936 for (const auto& v : Map) {
3937 List.push_back(v.second);
3938 }
3939 }
3940
3941 ViewProviderDocumentObject* ViewProviderLink::getLinkedViewProvider(
3942 std::string* subname,
3943 bool recursive
3944 ) const
3945 {
3946 auto self = const_cast<ViewProviderLink*>(this);
3947 auto ext = getLinkExtension();
3948 if (!ext) {
3949 return self;
3950 }
3951 App::DocumentObject* linked = nullptr;
3952 if (!recursive) {
3953 linked = ext->getLink();
3954 const char* s = ext->getSubName();
3955 if (subname && s) {
3956 *subname = s;
3957 }
3958 }
3959 else {
3960 linked = ext->getTrueLinkedObject(recursive);
3961 }
3962 if (!linked) {
3963 return self;
3964 }
3965 auto res = freecad_cast<ViewProviderDocumentObject*>(
3966 Application::Instance->getViewProvider(linked)
3967 );
3968 if (res) {
3969 return res;
3970 }
3971 return self;
3972 }
3973
3974 void ViewProviderLink::setTransformation(const Base::Matrix4D& rcMatrix)
3975 {
3976 inherited::setTransformation(rcMatrix);
3977 auto ext = getLinkExtension();
3978 if (ext) {
3979 if (ext->getScaleVectorProperty()) {
3980 updateDataPrivate(getLinkExtension(), ext->getScaleVectorProperty());
3981 }
3982 else {
3983 updateDataPrivate(getLinkExtension(), ext->getScaleProperty());
3984 }
3985 }
3986 }
3987
3988 void ViewProviderLink::setTransformation(const SbMatrix& rcMatrix)
3989 {
3990 inherited::setTransformation(rcMatrix);
3991 auto ext = getLinkExtension();
3992 if (ext) {
3993 if (ext->getScaleVectorProperty()) {
3994 updateDataPrivate(getLinkExtension(), ext->getScaleVectorProperty());
3995 }
3996 else {
3997 updateDataPrivate(getLinkExtension(), ext->getScaleProperty());
3998 }
3999 }
4000 }
4001
4002 ////////////////////////////////////////////////////////////////////////////////////////
4003
4004 namespace Gui
4005 {
4006 PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderLinkPython, Gui::ViewProviderLink)
4007 template class GuiExport ViewProviderFeaturePythonT<ViewProviderLink>;
4008 } // namespace Gui