Debian Codegraph @

src/App/DocumentObject.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2011 Jürgen Riegel <[email protected]> *
3 * Copyright (c) 2011 Werner Mayer <wmayer[at]users.sourceforge.net> *
4 * *
5 * This file is part of the FreeCAD CAx development system. *
6 * *
7 * This library is free software; you can redistribute it and/or *
8 * modify it under the terms of the GNU Library General Public *
9 * License as published by the Free Software Foundation; either *
10 * version 2 of the License, or (at your option) any later version. *
11 * *
12 * This library is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with this library; see the file COPYING.LIB. If not, *
19 * write to the Free Software Foundation, Inc., 59 Temple Place, *
20 * Suite 330, Boston, MA 02111-1307, USA *
21 * *
22 ***************************************************************************/
23
24 #include <stack>
25 #include <memory>
26 #include <map>
27 #include <set>
28 #include <vector>
29 #include <string>
30
31 #include <Base/Console.h>
32 #include <Base/Matrix.h>
33 #include <Base/Placement.h>
34 #include <Base/Tools.h>
35 #include <Base/Writer.h>
36
37 #include "Expression.h"
38 #include "Application.h"
39 #include "ElementNamingUtils.h"
40 #include "Document.h"
41 #include "DocumentObject.h"
42 #include "DocumentObjectPy.h"
43 #include "DocumentObjectExtension.h"
44 #include "DocumentObjectGroup.h"
45 #include "GeoFeatureGroupExtension.h"
46 #include "Link.h"
47 #include "ObjectIdentifier.h"
48 #include "PropertyExpressionEngine.h"
49 #include "PropertyLinks.h"
50
51
52 FC_LOG_LEVEL_INIT("App", true, true)
53
54 using namespace App;
55
56
57 PROPERTY_SOURCE(App::DocumentObject, App::TransactionalObject)
58
59 DocumentObjectExecReturn* DocumentObject::StdReturn = nullptr;
60
61 //===========================================================================
62 // DocumentObject
63 //===========================================================================
64
65 DocumentObject::DocumentObject()
66 : ExpressionEngine()
67 {
68 // define Label of type 'Output' to avoid being marked as touched after relabeling
69 ADD_PROPERTY_TYPE(Label, ("Unnamed"), "Base", Prop_Output, "User name of the object (UTF8)");
70 ADD_PROPERTY_TYPE(Label2, (""), "Base", Prop_Hidden, "User description of the object (UTF8)");
71 Label2.setStatus(App::Property::Output, true);
72 ADD_PROPERTY_TYPE(ExpressionEngine, (), "Base", Prop_Hidden, "Property expressions");
73
74 ADD_PROPERTY(Visibility, (true));
75
76 // default set Visibility status to hidden and output (no touch) for
77 // compatibitily reason. We use setStatus instead of PropertyType to
78 // allow user to change its status later
79 Visibility.setStatus(Property::Output, true);
80 Visibility.setStatus(Property::Hidden, true);
81 Visibility.setStatus(Property::NoModify, true);
82 }
83
84 DocumentObject::~DocumentObject()
85 {
86 if (!PythonObject.is(Py::_None())) {
87 Base::PyGILStateLocker lock;
88 // Remark: The API of Py::Object has been changed to set whether the wrapper owns the passed
89 // Python object or not. In the constructor we forced the wrapper to own the object so we
90 // need not to dec'ref the Python object any more. But we must still invalidate the Python
91 // object because it need not to be destructed right now because the interpreter can own
92 // several references to it.
93 Base::PyObjectBase* obj = static_cast<Base::PyObjectBase*>(PythonObject.ptr());
94 // Call before decrementing the reference counter, otherwise a heap error can occur
95 obj->setInvalid();
96 }
97 }
98
99 void DocumentObject::printInvalidLinks() const
100 {
101 try {
102 // Get objects that have invalid link scope, and print their names.
103 // Truncate the invalid object list name strings for readability, if they happen to be very
104 // long.
105 std::vector<App::DocumentObject*> invalid_linkobjs;
106 std::string objnames, scopenames;
107 GeoFeatureGroupExtension::getInvalidLinkObjects(this, invalid_linkobjs);
108 for (auto& obj : invalid_linkobjs) {
109 objnames += obj->getNameInDocument();
110 objnames += " ";
111 for (auto& scope : obj->getParents()) {
112 if (scopenames.length() > 80) {
113 scopenames += "... ";
114 break;
115 }
116
117 scopenames += scope.first->getNameInDocument();
118 scopenames += " ";
119 }
120
121 if (objnames.length() > 80) {
122 objnames += "... ";
123 break;
124 }
125 }
126
127 if (objnames.empty()) {
128 objnames = "N/A";
129 }
130 else {
131 objnames.pop_back();
132 }
133
134 if (scopenames.empty()) {
135 scopenames = "N/A";
136 }
137 else {
138 scopenames.pop_back();
139 }
140
141 Base::Console().warning("%s: Link(s) to object(s) '%s' go out of the allowed scope '%s'. "
142 "Instead, the linked object(s) reside within '%s'.\n",
143 getTypeId().getName(),
144 objnames.c_str(),
145 getNameInDocument(),
146 scopenames.c_str());
147 }
148 catch (const Base::Exception& e) {
149 e.reportException();
150 }
151 }
152
153 App::DocumentObjectExecReturn* DocumentObject::recompute()
154 {
155 // check if the links are valid before making the recompute
156 if (!GeoFeatureGroupExtension::areLinksValid(this)) {
157 printInvalidLinks();
158 }
159
160 // set/unset the execution bit
161 Base::ObjectStatusLocker<ObjectStatus, DocumentObject> exe(App::Recompute, this);
162
163 // mark the object to recompute its extensions
164 this->setStatus(App::RecomputeExtension, true);
165
166 auto ret = this->execute();
167 if (ret == StdReturn) {
168 // most feature classes don't call the execute() method of its base class
169 // so execute the extensions now
170 if (this->testStatus(App::RecomputeExtension)) {
171 ret = executeExtensions();
172 }
173 }
174
175 return ret;
176 }
177
178 DocumentObjectExecReturn* DocumentObject::execute()
179 {
180 return executeExtensions();
181 }
182
183 App::DocumentObjectExecReturn* DocumentObject::executeExtensions()
184 {
185 // execute extensions but stop on error
186 this->setStatus(App::RecomputeExtension, false); // reset the flag
187 auto vector = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
188 for (auto ext : vector) {
189 auto ret = ext->extensionExecute();
190 if (ret != StdReturn) {
191 return ret;
192 }
193 }
194
195 return StdReturn;
196 }
197
198 bool DocumentObject::recomputeFeature(bool recursive)
199 {
200 Document* doc = this->getDocument();
201 if (doc) {
202 return doc->recomputeFeature(this, recursive);
203 }
204 return isValid();
205 }
206
207 /**
208 * @brief Set this document object touched.
209 * Touching a document object does not mean to recompute it, it only means that
210 * other document objects that link it (i.e. its InList) will be recomputed.
211 * If it should be forced to recompute a document object then use
212 * \ref enforceRecompute() instead.
213 */
214 void DocumentObject::touch(bool noRecompute)
215 {
216 if (!noRecompute) {
217 StatusBits.set(ObjectStatus::Enforce);
218 }
219 StatusBits.set(ObjectStatus::Touch);
220 if (_pDoc) {
221 _pDoc->signalTouchedObject(*this);
222 }
223 }
224
225 /**
226 * @brief Set this document object freezed.
227 * A freezed document object does not recompute ever.
228 */
229 void DocumentObject::freeze()
230 {
231 StatusBits.set(ObjectStatus::Freeze);
232
233 // store read-only property names
234 this->readOnlyProperties.clear();
235 std::vector<std::pair<const char*, Property*>> list;
236 static_cast<App::PropertyContainer*>(this)->getPropertyNamedList(list);
237 for (auto pair: list){
238 if (pair.second->isReadOnly()){
239 this->readOnlyProperties.push_back(pair.first);
240 } else {
241 pair.second->setReadOnly(true);
242 }
243 }
244
245 // use the signalTouchedObject to refresh the Gui
246 if (_pDoc) {
247 _pDoc->signalTouchedObject(*this);
248 }
249 }
250
251 /**
252 * @brief Set this document object unfreezed.
253 * A freezed document object does not recompute ever.
254 */
255 void DocumentObject::unfreeze(bool noRecompute)
256 {
257 StatusBits.reset(ObjectStatus::Freeze);
258
259 // reset read-only property status
260 std::vector<std::pair<const char*, Property*>> list;
261 static_cast<App::PropertyContainer*>(this)->getPropertyNamedList(list);
262
263 for (auto pair: list){
264 if (! std::count(readOnlyProperties.begin(), readOnlyProperties.end(), pair.first)){
265 pair.second->setReadOnly(false);
266 }
267 }
268
269 touch(noRecompute);
270 }
271
272 /**
273 * @brief Check whether the document object is touched or not.
274 * @return true if document object is touched, false if not.
275 */
276 bool DocumentObject::isTouched() const
277 {
278 return ExpressionEngine.isTouched() || StatusBits.test(ObjectStatus::Touch);
279 }
280
281 /**
282 * @brief Enforces this document object to be recomputed.
283 * This can be useful to recompute the feature without
284 * having to change one of its input properties.
285 */
286 void DocumentObject::enforceRecompute()
287 {
288 touch(false);
289 }
290
291 /**
292 * @brief Check whether the document object must be recomputed or not.
293 * This means that the 'Enforce' flag is set or that \ref mustExecute()
294 * returns a value > 0.
295 * @return true if document object must be recomputed, false if not.
296 */
297 bool DocumentObject::mustRecompute() const
298 {
299 if (StatusBits.test(ObjectStatus::Freeze)) {
300 return false;
301 }
302
303 if (StatusBits.test(ObjectStatus::Enforce)) {
304 return true;
305 }
306
307 return mustExecute() > 0;
308 }
309
310 short DocumentObject::mustExecute() const
311 {
312 if (ExpressionEngine.isTouched()) {
313 return 1;
314 }
315
316 // ask all extensions
317 auto vector = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
318 for (auto ext : vector) {
319 if (ext->extensionMustExecute()) {
320 return 1;
321 }
322 }
323
324 return 0;
325 }
326
327 const char* DocumentObject::getStatusString() const
328 {
329 if (isError()) {
330 const char* text = getDocument()->getErrorDescription(this);
331 return text ? text : "Error";
332 }
333 else if (isFreezed()){
334 return "Freezed";
335 }
336 else if (isTouched()) {
337 return "Touched";
338 }
339 else {
340 return "Valid";
341 }
342 }
343
344 std::string DocumentObject::getFullName() const
345 {
346 if (!getDocument() || !isAttachedToDocument()) {
347 return "?";
348 }
349 std::string name(getDocument()->getName());
350 name += '#';
351 name += *pcNameInDocument;
352 return name;
353 }
354
355 std::string DocumentObject::getFullLabel() const
356 {
357 if (!getDocument()) {
358 return "?";
359 }
360
361 auto name = getDocument()->Label.getStrValue();
362 name += "#";
363 name += Label.getStrValue();
364 return name;
365 }
366
367 const char* DocumentObject::getDagKey() const
368 {
369 if (!pcNameInDocument) {
370 return nullptr;
371 }
372 return pcNameInDocument->c_str();
373 }
374
375 const char* DocumentObject::getNameInDocument() const
376 {
377 // Note: It can happen that we query the internal name of an object even if it is not
378 // part of a document (anymore). This is the case e.g. if we have a reference in Python
379 // to an object that has been removed from the document. In this case we should rather
380 // return 0.
381 // assert(pcNameInDocument);
382 if (!pcNameInDocument) {
383 return nullptr;
384 }
385 return pcNameInDocument->c_str();
386 }
387
388 int DocumentObject::isExporting() const
389 {
390 if (!getDocument() || !isAttachedToDocument()) {
391 return 0;
392 }
393 return getDocument()->isExporting(this);
394 }
395
396 std::string DocumentObject::getExportName(bool forced) const
397 {
398 if (!isAttachedToDocument()) {
399 return {};
400 }
401
402 if (!forced && !isExporting()) {
403 return *pcNameInDocument;
404 }
405
406 // '@' is an invalid character for an internal name, which ensures the
407 // following returned name will be unique in any document. Saving external
408 // object like that shall only happens in Document::exportObjects(). We
409 // shall strip out this '@' and the following document name during restoring.
410 return *pcNameInDocument + '@' + getDocument()->getName();
411 }
412
413 bool DocumentObject::isAttachedToDocument() const
414 {
415 return (pcNameInDocument != nullptr);
416 }
417
418 const char* DocumentObject::detachFromDocument()
419 {
420 const std::string* name = pcNameInDocument;
421 pcNameInDocument = nullptr;
422 return name ? name->c_str() : nullptr;
423 }
424
425 const std::vector<DocumentObject*>& DocumentObject::getOutList() const
426 {
427 if (!_outListCached) {
428 _outList.clear();
429 getOutList(0, _outList);
430 _outListCached = true;
431 }
432 return _outList;
433 }
434
435 std::vector<DocumentObject*> DocumentObject::getOutList(int options) const
436 {
437 std::vector<DocumentObject*> res;
438 getOutList(options, res);
439 return res;
440 }
441
442 void DocumentObject::getOutList(int options, std::vector<DocumentObject*>& res) const
443 {
444 if (_outListCached && !options) {
445 res.insert(res.end(), _outList.begin(), _outList.end());
446 return;
447 }
448 std::vector<Property*> props;
449 getPropertyList(props);
450 bool noHidden = !!(options & OutListNoHidden);
451 std::size_t size = res.size();
452 for (auto prop : props) {
453 auto link = freecad_cast<PropertyLinkBase*>(prop);
454 if (link) {
455 link->getLinks(res, noHidden);
456 }
457 }
458 if (!(options & OutListNoExpression)) {
459 ExpressionEngine.getLinks(res);
460 }
461
462 if (options & OutListNoXLinked) {
463 for (auto it = res.begin() + size; it != res.end();) {
464 auto obj = *it;
465 if (obj && obj->getDocument() != getDocument()) {
466 it = res.erase(it);
467 }
468 else {
469 ++it;
470 }
471 }
472 }
473 }
474
475 std::vector<App::DocumentObject*> DocumentObject::getOutListOfProperty(App::Property* prop) const
476 {
477 std::vector<DocumentObject*> ret;
478 if (!prop || prop->getContainer() != this) {
479 return ret;
480 }
481
482 auto link = freecad_cast<PropertyLinkBase*>(prop);
483 if (link) {
484 link->getLinks(ret);
485 }
486 return ret;
487 }
488
489 const std::vector<App::DocumentObject*>& DocumentObject::getInList() const
490 {
491 return _inList;
492 }
493
494 // The original algorithm is highly inefficient in some special case.
495 // Considering an object is linked by every other objects. After excluding this
496 // object, there is another object linked by every other of the remaining
497 // objects, and so on. The vector 'result' above will be of magnitude n^2.
498 // Even if we replace the vector with a set, we still need to visit that amount
499 // of objects. And this may not be the worst case. getInListEx() has no such
500 // problem.
501
502 std::vector<App::DocumentObject*> DocumentObject::getInListRecursive() const
503 {
504 std::set<App::DocumentObject*> inSet;
505 std::vector<App::DocumentObject*> res;
506 getInListEx(inSet, true, &res);
507 return res;
508 }
509
510
511 // More efficient algorithm to find the recursive inList of an object,
512 // including possible external parents. One shortcoming of this algorithm is
513 // it does not detect cyclic reference, althgouth it won't crash either.
514 void DocumentObject::getInListEx(std::set<App::DocumentObject*>& inSet,
515 bool recursive,
516 std::vector<App::DocumentObject*>* inList) const
517 {
518 if (!recursive) {
519 inSet.insert(_inList.begin(), _inList.end());
520 if (inList) {
521 *inList = _inList;
522 }
523 return;
524 }
525
526 std::stack<DocumentObject*> pendings;
527 pendings.push(const_cast<DocumentObject*>(this));
528 while (!pendings.empty()) {
529 auto obj = pendings.top();
530 pendings.pop();
531 for (auto o : obj->getInList()) {
532 if (o && o->isAttachedToDocument() && inSet.insert(o).second) {
533 pendings.push(o);
534 if (inList) {
535 inList->push_back(o);
536 }
537 }
538 }
539 }
540 }
541
542 std::set<App::DocumentObject*> DocumentObject::getInListEx(bool recursive) const
543 {
544 std::set<App::DocumentObject*> ret;
545 getInListEx(ret, recursive);
546 return ret;
547 }
548
549 void _getOutListRecursive(std::set<DocumentObject*>& objSet,
550 const DocumentObject* obj,
551 const DocumentObject* checkObj,
552 int depth)
553 {
554 for (const auto objIt : obj->getOutList()) {
555 // if the check object is in the recursive inList we have a cycle!
556 if (objIt == checkObj || depth <= 0) {
557 throw Base::BadGraphError(
558 "DocumentObject::getOutListRecursive(): cyclic dependency detected!");
559 }
560
561 // if the element was already in the set then there is no need to process it again
562 auto pair = objSet.insert(objIt);
563 if (pair.second) {
564 _getOutListRecursive(objSet, objIt, checkObj, depth - 1);
565 }
566 }
567 }
568
569 std::vector<App::DocumentObject*> DocumentObject::getOutListRecursive() const
570 {
571 // number of objects in document is a good estimate in result size
572 int maxDepth = GetApplication().checkLinkDepth(0);
573 std::set<App::DocumentObject*> result;
574
575 // using a recursive helper to collect all OutLists
576 _getOutListRecursive(result, this, this, maxDepth);
577
578 std::vector<App::DocumentObject*> array;
579 array.insert(array.begin(), result.begin(), result.end());
580 return array;
581 }
582
583 // helper for isInInListRecursive()
584 bool _isInInListRecursive(const DocumentObject* act, const DocumentObject* checkObj, int depth)
585 {
586 for (auto obj : act->getInList()) {
587 if (obj == checkObj) {
588 return true;
589 }
590 // if we reach the depth limit we have a cycle!
591 if (depth <= 0) {
592 throw Base::BadGraphError(
593 "DocumentObject::isInInListRecursive(): cyclic dependency detected!");
594 }
595
596 if (_isInInListRecursive(obj, checkObj, depth - 1)) {
597 return true;
598 }
599 }
600
601 return false;
602 }
603
604 bool DocumentObject::isInInListRecursive(DocumentObject* linkTo) const
605 {
606 return this == linkTo || getInListEx(true).contains(linkTo);
607 }
608
609 bool DocumentObject::isInInList(DocumentObject* linkTo) const
610 {
611 if (std::ranges::find(_inList, linkTo) != _inList.end()) {
612 return true;
613 }
614 else {
615 return false;
616 }
617 }
618
619 // helper for isInOutListRecursive()
620 bool _isInOutListRecursive(const DocumentObject* act, const DocumentObject* checkObj, int depth)
621 {
622 for (auto obj : act->getOutList()) {
623 if (obj == checkObj) {
624 return true;
625 }
626 // if we reach the depth limit we have a cycle!
627 if (depth <= 0) {
628 throw Base::BadGraphError(
629 "DocumentObject::isInOutListRecursive(): cyclic dependency detected!");
630 }
631
632 if (_isInOutListRecursive(obj, checkObj, depth - 1)) {
633 return true;
634 }
635 }
636
637 return false;
638 }
639
640 bool DocumentObject::isInOutListRecursive(DocumentObject* linkTo) const
641 {
642 int maxDepth = getDocument()->countObjects() + 2;
643 return _isInOutListRecursive(this, linkTo, maxDepth);
644 }
645
646 std::vector<std::list<App::DocumentObject*>>
647 DocumentObject::getPathsByOutList(App::DocumentObject* to) const
648 {
649 return _pDoc->getPathsByOutList(this, to);
650 }
651
652 DocumentObjectGroup* DocumentObject::getGroup() const
653 {
654 return freecad_cast<DocumentObjectGroup*>(GroupExtension::getGroupOfObject(this));
655 }
656
657 bool DocumentObject::testIfLinkDAGCompatible(DocumentObject* linkTo) const
658 {
659 std::vector<App::DocumentObject*> linkTo_in_vector;
660 linkTo_in_vector.push_back(linkTo);
661 return this->testIfLinkDAGCompatible(linkTo_in_vector);
662 }
663
664 bool DocumentObject::testIfLinkDAGCompatible(const std::vector<DocumentObject*>& linksTo) const
665 {
666 auto inLists = getInListEx(true);
667 inLists.emplace(const_cast<DocumentObject*>(this));
668 for (auto obj : linksTo) {
669 if (inLists.contains(obj)) {
670 return false;
671 }
672 }
673 return true;
674 }
675
676 bool DocumentObject::testIfLinkDAGCompatible(PropertyLinkSubList& linksTo) const
677 {
678 const std::vector<App::DocumentObject*>& linksTo_in_vector = linksTo.getValues();
679 return this->testIfLinkDAGCompatible(linksTo_in_vector);
680 }
681
682 bool DocumentObject::testIfLinkDAGCompatible(PropertyLinkSub& linkTo) const
683 {
684 std::vector<App::DocumentObject*> linkTo_in_vector;
685 linkTo_in_vector.reserve(1);
686 linkTo_in_vector.push_back(linkTo.getValue());
687 return this->testIfLinkDAGCompatible(linkTo_in_vector);
688 }
689
690 void DocumentObject::onLostLinkToObject(DocumentObject*)
691 {}
692
693 App::Document* DocumentObject::getDocument() const
694 {
695 return _pDoc;
696 }
697
698 void DocumentObject::setDocument(App::Document* doc)
699 {
700 _pDoc = doc;
701 onSettingDocument();
702 }
703
704 bool DocumentObject::removeDynamicProperty(const char* name)
705 {
706 if (!_pDoc || testStatus(ObjectStatus::Destroy)) {
707 return false;
708 }
709
710 Property* prop = getDynamicPropertyByName(name);
711 if (!prop || prop->testStatus(App::Property::LockDynamic)) {
712 return false;
713 }
714
715 if (prop->isDerivedFrom<PropertyLinkBase>()) {
716 clearOutListCache();
717 }
718
719 _pDoc->addOrRemovePropertyOfObject(this, prop, false);
720
721 auto expressions = ExpressionEngine.getExpressions();
722 std::vector<App::ObjectIdentifier> removeExpr;
723
724 for (const auto& it : expressions) {
725 if (it.first.getProperty() == prop) {
726 removeExpr.push_back(it.first);
727 }
728 }
729
730 for (const auto& it : removeExpr) {
731 ExpressionEngine.setValue(it, std::shared_ptr<Expression>());
732 }
733
734 return TransactionalObject::removeDynamicProperty(name);
735 }
736
737 bool DocumentObject::renameDynamicProperty(Property* prop, const char* name)
738 {
739 std::string oldName = prop->getName();
740
741 auto expressions = ExpressionEngine.getExpressions();
742 std::vector<std::shared_ptr<Expression>> expressionsToMove;
743 std::vector<App::ObjectIdentifier> idsWithExprsToRemove;
744
745 for (const auto& [id, expr] : expressions) {
746 if (id.getProperty() == prop) {
747 idsWithExprsToRemove.push_back(id);
748 expressionsToMove.emplace_back(expr->copy());
749 }
750 }
751
752 for (const auto& it : idsWithExprsToRemove) {
753 ExpressionEngine.setValue(it, std::shared_ptr<Expression>());
754 }
755
756 bool renamed = TransactionalObject::renameDynamicProperty(prop, name);
757 if (renamed && _pDoc) {
758 _pDoc->renamePropertyOfObject(this, prop, oldName.c_str());
759 }
760
761
762 App::ObjectIdentifier idNewProp(prop->getContainer(), std::string(name));
763 for (auto& exprToMove : expressionsToMove) {
764 ExpressionEngine.setValue(idNewProp, exprToMove);
765 }
766
767 return renamed;
768 }
769
770 App::Property* DocumentObject::addDynamicProperty(const char* type,
771 const char* name,
772 const char* group,
773 const char* doc,
774 short attr,
775 bool ro,
776 bool hidden)
777 {
778 auto prop = TransactionalObject::addDynamicProperty(type, name, group, doc, attr, ro, hidden);
779 if (prop && _pDoc) {
780 _pDoc->addOrRemovePropertyOfObject(this, prop, true);
781 }
782 return prop;
783 }
784
785 void DocumentObject::onBeforeChange(const Property* prop)
786 {
787 if (isFreezed() && prop != &Visibility) {
788 return;
789 }
790
791 // Store current name in oldLabel, to be able to easily retrieve old name of document object later
792 // when renaming expressions.
793 if (prop == &Label)
794 oldLabel = Label.getStrValue();
795
796 if (_pDoc){
797 onBeforeChangeProperty(_pDoc, prop);
798 }
799
800 signalBeforeChange(*this, *prop);
801 }
802
803 std::vector<std::pair<Property*, std::unique_ptr<Property>>>
804 DocumentObject::onProposedLabelChange(std::string& newLabel)
805 {
806 // Note that this work can't be done in onBeforeChangeLabel because FeaturePython overrides this
807 // method and does not initially base-call it.
808
809 // We re only called if the new label differs from the old one, and our code to check duplicates
810 // may not work if this is not the case.
811 std::string oldLabel = Label.getStrValue();
812 assert(newLabel != oldLabel);
813 if (!isAttachedToDocument()) {
814 return {};
815 }
816 App::Document* doc = getDocument();
817 if (doc->isPerformingTransaction()
818 || (doc->testStatus(App::Document::Restoring)
819 && !doc->testStatus(App::Document::Importing))) {
820 return {};
821 }
822 static ParameterGrp::handle _hPGrp;
823 if (!_hPGrp) {
824 _hPGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document");
825 }
826 if (doc && !newLabel.empty() && !_hPGrp->GetBool("DuplicateLabels") && !allowDuplicateLabel()
827 && doc->containsLabel(newLabel)) {
828 // The label already exists but settings are such that duplicate labels should not be assigned.
829 std::string objName = getNameInDocument();
830 if (!doc->containsLabel(objName) && doc->haveSameBaseName(objName, newLabel)) {
831 // The object name is not already a Label and the base name of the proposed label
832 // equals the base name of the object Name, so we use the object Name as the replacement Label.
833 newLabel = objName;
834 }
835 else {
836 // Otherwise we generate a unique Label using newLabel as a prototype name. In doing so,
837 // we must also act as if the current value of the property is not an existing Label
838 // entry.
839 // We deregister the old label so it does not interfere with making the new label,
840 // and re-register it after. This is probably a bit less efficient that having a special
841 // make-unique-label-as-if-this-one-did-not-exist method, but such a method would be a real
842 // ugly wart.
843 doc->unregisterLabel(oldLabel);
844 newLabel = doc->makeUniqueLabel(newLabel);
845 doc->registerLabel(oldLabel);
846 }
847 }
848
849 // Despite our efforts to make a unique label, onBeforeLabelChange can change it.
850 onBeforeChangeLabel(newLabel);
851
852 if (oldLabel == newLabel || getDocument()->testStatus(App::Document::Restoring)) {
853 // Don't update label reference if we are restoring or if the label is unchanged.
854 // When importing (which also counts as restoring), it is possible the
855 // new object changes its label. However, we cannot update label
856 // references here, because object being restored is not based on
857 // dependency order. It can only be done in afterRestore().
858 //
859 // See PropertyLinkBase::restoreLabelReference() for more details.
860 return {};
861 }
862 return PropertyLinkBase::updateLabelReferences(this, newLabel.c_str());
863 }
864
865 void DocumentObject::onEarlyChange(const Property* prop)
866 {
867 if (isFreezed() && prop != &Visibility) {
868 return;
869 }
870
871 if (GetApplication().isClosingAll()) {
872 return;
873 }
874
875 if (!GetApplication().isRestoring() && !prop->testStatus(Property::PartialTrigger)
876 && getDocument() && getDocument()->testStatus(Document::PartialDoc)) {
877 static App::Document* warnedDoc;
878 if (warnedDoc != getDocument()) {
879 warnedDoc = getDocument();
880 FC_WARN("Changes to partial loaded document will not be saved: " << getFullName() << '.'
881 << prop->getName());
882 }
883 }
884
885 signalEarlyChanged(*this, *prop);
886 }
887
888 /// get called by the container when a Property was changed
889 void DocumentObject::onChanged(const Property* prop)
890 {
891 if (prop == &Label && _pDoc && _pDoc->containsObject(this) && oldLabel != Label.getStrValue()) {
892 _pDoc->unregisterLabel(oldLabel);
893 _pDoc->registerLabel(Label.getStrValue());
894 }
895
896 if (isFreezed() && prop != &Visibility) {
897 return;
898 }
899
900 if (GetApplication().isClosingAll()) {
901 return;
902 }
903
904 if (!GetApplication().isRestoring() && !prop->testStatus(Property::PartialTrigger)
905 && getDocument() && getDocument()->testStatus(Document::PartialDoc)) {
906 static App::Document* warnedDoc;
907 if (warnedDoc != getDocument()) {
908 warnedDoc = getDocument();
909 FC_WARN("Changes to partial loaded document will not be saved: " << getFullName() << '.'
910 << prop->getName());
911 }
912 }
913
914 // Delay signaling view provider until the document object has handled the
915 // change
916 // if (_pDoc)
917 // _pDoc->onChangedProperty(this,prop);
918
919 if (prop == &Label && _pDoc && oldLabel != Label.getStrValue()) {
920 _pDoc->signalRelabelObject(*this);
921 }
922
923 // set object touched if it is an input property
924 if (!testStatus(ObjectStatus::NoTouch) && !(prop->getType() & Prop_Output)
925 && !prop->testStatus(Property::Output)) {
926 if (!StatusBits.test(ObjectStatus::Touch)) {
927 FC_TRACE("touch '" << getFullName() << "' on change of '" << prop->getName() << "'");
928 StatusBits.set(ObjectStatus::Touch);
929 }
930 // must execute on document recompute
931 if (!(prop->getType() & Prop_NoRecompute)) {
932 StatusBits.set(ObjectStatus::Enforce);
933 }
934 }
935
936 // call the parent for appropriate handling
937 TransactionalObject::onChanged(prop);
938
939 // Now signal the view provider
940 if (_pDoc) {
941 _pDoc->onChangedProperty(this, prop);
942 }
943
944 signalChanged(*this, *prop);
945 }
946
947 void DocumentObject::clearOutListCache() const
948 {
949 _outList.clear();
950 _outListMap.clear();
951 _outListCached = false;
952 }
953
954 PyObject* DocumentObject::getPyObject()
955 {
956 if (PythonObject.is(Py::_None())) {
957 // ref counter is set to 1
958 PythonObject = Py::Object(new DocumentObjectPy(this), true);
959 }
960 return Py::new_reference_to(PythonObject);
961 }
962
963 DocumentObject* DocumentObject::getSubObject(const char* subname,
964 PyObject** pyObj,
965 Base::Matrix4D* mat,
966 bool transform,
967 int depth) const
968 {
969 DocumentObject* ret = nullptr;
970 auto exts = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
971 for (auto ext : exts) {
972 if (ext->extensionGetSubObject(ret, subname, pyObj, mat, transform, depth)) {
973 return ret;
974 }
975 }
976
977 std::string name;
978 const char* dot = nullptr;
979 if (!subname || !(dot = strchr(subname, '.'))) {
980 ret = const_cast<DocumentObject*>(this);
981 }
982 else if (subname[0] == '$') {
983 name = std::string(subname + 1, dot);
984 for (auto obj : getOutList()) {
985 if (name == obj->Label.getValue()) {
986 ret = obj;
987 break;
988 }
989 }
990 }
991 else {
992 name = std::string(subname, dot);
993 const auto& outList = getOutList();
994 if (outList.size() != _outListMap.size()) {
995 _outListMap.clear();
996 for (auto obj : outList) {
997 _outListMap[obj->getDagKey()] = obj;
998 }
999 }
1000 auto it = _outListMap.find(name.c_str());
1001 if (it != _outListMap.end()) {
1002 ret = it->second;
1003 }
1004 }
1005
1006 // TODO: By right, normal object's placement does not transform its sub
1007 // objects (think of the claimed children of a Fusion). But I do think we
1008 // should change that.
1009 if (transform && mat) {
1010 auto pla = freecad_cast<PropertyPlacement*>(getPropertyByName("Placement"));
1011 if (pla) {
1012 *mat *= pla->getValue().toMatrix();
1013 }
1014 }
1015
1016 if (ret && dot) {
1017 return ret->getSubObject(dot + 1, pyObj, mat, true, depth + 1);
1018 }
1019 return ret;
1020 }
1021
1022 namespace
1023 {
1024 std::vector<DocumentObject*>
1025 getSubObjectListFlatten(const std::vector<App::DocumentObject*>& resNotFlatten,
1026 std::vector<int>* const subsizes,
1027 const App::DocumentObject* sobj,
1028 App::DocumentObject** container,
1029 bool& lastChild)
1030 {
1031 auto res {resNotFlatten};
1032 auto linked = sobj->getLinkedObject();
1033 if (*container) {
1034 auto grp = App::GeoFeatureGroupExtension::getGroupOfObject(linked);
1035 if (grp != *container) {
1036 *container = nullptr;
1037 }
1038 else {
1039 if (lastChild && !res.empty()) {
1040 res.pop_back();
1041 if (subsizes) {
1042 subsizes->pop_back();
1043 }
1044 }
1045 lastChild = true;
1046 }
1047 }
1048 if (linked->getExtensionByType<App::GeoFeatureGroupExtension>(true)) {
1049 *container = linked;
1050 lastChild = false;
1051 }
1052 else if (linked != sobj || sobj->hasChildElement()) {
1053 // Check for Link or LinkGroup
1054 *container = nullptr;
1055 }
1056 else if (auto ext = sobj->getExtensionByType<LinkBaseExtension>(true)) {
1057 // check for Link array
1058 if (ext->getElementCountValue() != 0) {
1059 *container = nullptr;
1060 }
1061 }
1062 return res;
1063 }
1064 } // namespace
1065
1066 std::vector<DocumentObject*> DocumentObject::getSubObjectList(const char* subname,
1067 std::vector<int>* const subsizes,
1068 bool flatten) const
1069 {
1070 std::vector<DocumentObject*> res;
1071 res.push_back(const_cast<DocumentObject*>(this));
1072 if (subsizes) {
1073 subsizes->push_back(0);
1074 }
1075 if (!subname || (subname[0] == '\0')) {
1076 return res;
1077 }
1078 auto element = Data::findElementName(subname);
1079 std::string sub(subname, element - subname);
1080 App::DocumentObject* container = nullptr;
1081
1082 bool lastChild = false;
1083 if (flatten) {
1084 auto linked = getLinkedObject();
1085 if (linked->getExtensionByType<App::GeoFeatureGroupExtension>(true)) {
1086 container = const_cast<DocumentObject*>(this);
1087 }
1088 else if (auto grp = App::GeoFeatureGroupExtension::getGroupOfObject(linked)) {
1089 container = grp;
1090 lastChild = true;
1091 }
1092 }
1093 for (auto pos = sub.find('.'); pos != std::string::npos; pos = sub.find('.', pos + 1)) {
1094 char subTail = sub[pos + 1];
1095 sub[pos + 1] = '\0';
1096 auto sobj = getSubObject(sub.c_str());
1097 if (!sobj || !sobj->isAttachedToDocument()) {
1098 continue;
1099 }
1100
1101 if (flatten) {
1102 res = getSubObjectListFlatten(res, subsizes, sobj, &container, lastChild);
1103 }
1104 res.push_back(sobj);
1105 if (subsizes) {
1106 subsizes->push_back((int)pos + 1);
1107 }
1108 sub[pos + 1] = subTail;
1109 }
1110 return res;
1111 }
1112
1113 std::vector<std::string> DocumentObject::getSubObjects(int reason) const
1114 {
1115 std::vector<std::string> ret;
1116 auto exts = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
1117 for (auto ext : exts) {
1118 if (ext->extensionGetSubObjects(ret, reason)) {
1119 return ret;
1120 }
1121 }
1122 return ret;
1123 }
1124
1125 std::vector<std::pair<App::DocumentObject*, std::string>>
1126 DocumentObject::getParents(int depth) const
1127 {
1128 std::vector<std::pair<App::DocumentObject*, std::string>> ret;
1129 if (!isAttachedToDocument() || !GetApplication().checkLinkDepth(depth, MessageOption::Throw)) {
1130 return ret;
1131 }
1132
1133 std::string name(getNameInDocument());
1134 name += ".";
1135 for (auto parent : getInList()) {
1136 if (!parent || !parent->isAttachedToDocument()) {
1137 continue;
1138 }
1139
1140 if (!parent->hasChildElement()
1141 && !parent->hasExtension(GeoFeatureGroupExtension::getExtensionClassTypeId())) {
1142 continue;
1143 }
1144
1145 if (!parent->getSubObject(name.c_str())) {
1146 continue;
1147 }
1148
1149 auto links = GetApplication().getLinksTo(parent, App::GetLinkRecursive);
1150 links.insert(parent);
1151
1152 for (auto parent : links) {
1153 auto parents = parent->getParents(depth + 1);
1154 if (parents.empty()) {
1155 parents.emplace_back(parent, std::string());
1156 }
1157
1158 for (auto& v : parents) {
1159 ret.emplace_back(v.first, v.second + name);
1160 }
1161 }
1162 }
1163
1164 return ret;
1165 }
1166
1167 App::DocumentObject* DocumentObject::getFirstParent() const
1168 {
1169 for (auto obj : getInList()) {
1170 if (obj->hasExtension(App::GroupExtension::getExtensionClassTypeId(), true)) {
1171 return obj;
1172 }
1173 }
1174
1175 return nullptr;
1176 }
1177
1178 DocumentObject* DocumentObject::getLinkedObject(bool recursive,
1179 Base::Matrix4D* mat,
1180 bool transform,
1181 int depth) const
1182 {
1183 DocumentObject* ret = nullptr;
1184 auto exts = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
1185 for (auto ext : exts) {
1186 if (ext->extensionGetLinkedObject(ret, recursive, mat, transform, depth)) {
1187 return ret;
1188 }
1189 }
1190 if (transform && mat) {
1191 auto pla = freecad_cast<PropertyPlacement*>(getPropertyByName("Placement"));
1192 if (pla) {
1193 *mat *= pla->getValue().toMatrix();
1194 }
1195 }
1196 return const_cast<DocumentObject*>(this);
1197 }
1198
1199 void DocumentObject::Save(Base::Writer& writer) const
1200 {
1201 if (this->isFreezed()) {
1202 throw Base::AbortException("At least one object is frozen, unable to save.");
1203 }
1204
1205 if (this->isAttachedToDocument()){
1206 writer.ObjectName = this->getNameInDocument();
1207 }
1208 App::ExtensionContainer::Save(writer);
1209 }
1210
1211 /**
1212 * @brief Associate the expression \expr with the object identifier \a path in this document object.
1213 * @param path Target object identifier for the result of the expression
1214 * @param expr Expression tree
1215 */
1216
1217 void DocumentObject::setExpression(const ObjectIdentifier& path, std::shared_ptr<Expression> expr)
1218 {
1219 ExpressionEngine.setValue(path, std::move(expr));
1220 }
1221
1222 /**
1223 * @brief Clear the expression of the object identifier \a path in this document object.
1224 * @param path Target object identifier
1225 */
1226
1227 void DocumentObject::clearExpression(const ObjectIdentifier& path)
1228 {
1229 setExpression(path, std::shared_ptr<Expression>());
1230 }
1231
1232 /**
1233 * @brief Get expression information associated with \a path.
1234 * @param path Object identifier
1235 * @return Expression info, containing expression and optional comment.
1236 */
1237
1238 const PropertyExpressionEngine::ExpressionInfo
1239 DocumentObject::getExpression(const ObjectIdentifier& path) const
1240 {
1241 boost::any value = ExpressionEngine.getPathValue(path);
1242
1243 if (value.type() == typeid(PropertyExpressionEngine::ExpressionInfo)) {
1244 return boost::any_cast<PropertyExpressionEngine::ExpressionInfo>(value);
1245 }
1246 else {
1247 return PropertyExpressionEngine::ExpressionInfo();
1248 }
1249 }
1250
1251 /**
1252 * @brief Invoke ExpressionEngine's renameObjectIdentifier, to possibly rewrite expressions using
1253 * the \a paths map with current and new identifiers.
1254 *
1255 * @param paths
1256 */
1257
1258 void DocumentObject::renameObjectIdentifiers(
1259 const std::map<ObjectIdentifier, ObjectIdentifier>& paths)
1260 {
1261 ExpressionEngine.renameObjectIdentifiers(paths);
1262 }
1263
1264 void DocumentObject::onDocumentRestored()
1265 {
1266 // call all extensions
1267 auto vector = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
1268 for (auto ext : vector) {
1269 ext->onExtendedDocumentRestored();
1270 }
1271 if (Visibility.testStatus(Property::Output)) {
1272 Visibility.setStatus(Property::NoModify, true);
1273 }
1274 }
1275
1276 void DocumentObject::restoreFinished()
1277 {
1278 // some link type property cannot restore link information until other
1279 // objects has been restored. For example, PropertyExpressionEngine and
1280 // PropertySheet with expression containing label reference.
1281 // So on document load they are handled in Document::afterRestore, but if the user
1282 // use dumpContent and restoreContent then they need to be handled here.
1283 std::vector<App::Property*> props;
1284 getPropertyList(props);
1285 for (auto prop : props) {
1286 prop->afterRestore();
1287 }
1288 }
1289
1290 void DocumentObject::onUndoRedoFinished()
1291 {}
1292
1293 void DocumentObject::onSettingDocument()
1294 {
1295 // call all extensions
1296 auto vector = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
1297 for (auto ext : vector) {
1298 ext->onExtendedSettingDocument();
1299 }
1300 }
1301
1302 void DocumentObject::setupObject()
1303 {
1304 // call all extensions
1305 auto vector = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
1306 for (auto ext : vector) {
1307 ext->onExtendedSetupObject();
1308 }
1309 }
1310
1311 void DocumentObject::unsetupObject()
1312 {
1313 // call all extensions
1314 auto vector = getExtensionsDerivedFromType<App::DocumentObjectExtension>();
1315 for (auto ext : vector) {
1316 ext->onExtendedUnsetupObject();
1317 }
1318 }
1319
1320 void App::DocumentObject::_removeBackLink(DocumentObject* rmvObj)
1321 {
1322 // do not use erase-remove idom, as this erases ALL entries that match. we only want to remove a
1323 // single one.
1324 auto it = std::ranges::find(_inList, rmvObj);
1325 if (it != _inList.end()) {
1326 _inList.erase(it);
1327 }
1328 }
1329
1330 void App::DocumentObject::_addBackLink(DocumentObject* newObj)
1331 {
1332 // we need to add all links, even if they are available multiple times. The reason for this is
1333 // the removal: If a link loses this object it removes the backlink. If we would have added it
1334 // only once this removal would clear the object from the inlist, even though there may be other
1335 // link properties from this object that link to us.
1336 _inList.push_back(newObj);
1337 }
1338
1339 int DocumentObject::setElementVisible(const char* element, bool visible)
1340 {
1341 for (auto ext : getExtensionsDerivedFromType<DocumentObjectExtension>()) {
1342 int ret = ext->extensionSetElementVisible(element, visible);
1343 if (ret >= 0) {
1344 return ret;
1345 }
1346 }
1347
1348 return -1;
1349 }
1350
1351 int DocumentObject::isElementVisible(const char* element) const
1352 {
1353 for (auto ext : getExtensionsDerivedFromType<DocumentObjectExtension>()) {
1354 int ret = ext->extensionIsElementVisible(element);
1355 if (ret >= 0) {
1356 return ret;
1357 }
1358 }
1359
1360 return -1;
1361 }
1362
1363 bool DocumentObject::hasChildElement() const
1364 {
1365 for (auto ext : getExtensionsDerivedFromType<DocumentObjectExtension>()) {
1366 if (ext->extensionHasChildElement()) {
1367 return true;
1368 }
1369 }
1370 return false;
1371 }
1372
1373 DocumentObject* DocumentObject::resolve(const char* subname,
1374 App::DocumentObject** parent,
1375 std::string* childName,
1376 const char** subElement,
1377 PyObject** pyObj,
1378 Base::Matrix4D* pmat,
1379 bool transform,
1380 int depth) const
1381 {
1382 auto self = const_cast<DocumentObject*>(this);
1383 if (parent) {
1384 *parent = nullptr;
1385 }
1386 if (subElement) {
1387 *subElement = nullptr;
1388 }
1389
1390 auto obj = getSubObject(subname, pyObj, pmat, transform, depth);
1391 if (!obj || !subname || *subname == 0) {
1392 return self;
1393 }
1394
1395 if (!parent && !subElement) {
1396 return obj;
1397 }
1398
1399 // NOTE, the convention of '.' separated SubName demands a mandatory ending
1400 // '.' for each object name in SubName, even if there is no subelement
1401 // following it. So finding the last dot will give us the end of the last
1402 // object name.
1403 const char* dot = nullptr;
1404 if (Data::isMappedElement(subname) || !(dot = strrchr(subname, '.')) || dot == subname) {
1405 if (subElement) {
1406 *subElement = dot ? dot + 1 : subname;
1407 }
1408 return obj; // this means no parent object reference in SubName
1409 }
1410
1411 if (parent) {
1412 *parent = self;
1413 }
1414
1415 bool elementMapChecked = false;
1416 const char* lastDot = dot;
1417 for (--dot;; --dot) {
1418 // check for the second last dot, which is the end of the last parent object
1419 if (*dot == '.' || dot == subname) {
1420 // We can't get parent object by its name, because the object may be
1421 // externally linked (i.e. in a different document). So go through
1422 // getSubObject again.
1423 if (!elementMapChecked) {
1424 elementMapChecked = true;
1425 const char* sub = dot == subname ? dot : dot + 1;
1426 if (Data::isMappedElement(sub)) {
1427 lastDot = dot;
1428 if (dot == subname) {
1429 break;
1430 }
1431 else {
1432 continue;
1433 }
1434 }
1435 }
1436 if (dot == subname) {
1437 break;
1438 }
1439 auto sobj = getSubObject(std::string(subname, dot - subname + 1).c_str());
1440 if (sobj != obj) {
1441 if (parent) {
1442 // Link/LinkGroup has special visibility handling of plain
1443 // group, so keep ascending
1444 if (!sobj->hasExtension(GroupExtension::getExtensionClassTypeId(), false)) {
1445 *parent = sobj;
1446 break;
1447 }
1448 for (auto ddot = dot - 1; ddot != subname; --ddot) {
1449 if (*ddot != '.') {
1450 continue;
1451 }
1452 auto sobj = getSubObject(std::string(subname, ddot - subname + 1).c_str());
1453 if (!sobj->hasExtension(GroupExtension::getExtensionClassTypeId(), false)) {
1454 *parent = sobj;
1455 break;
1456 }
1457 }
1458 }
1459 break;
1460 }
1461 }
1462 }
1463 if (childName && lastDot != dot) {
1464 if (*dot == '.') {
1465 ++dot;
1466 }
1467 const char* nextDot = strchr(dot, '.');
1468 assert(nextDot);
1469 *childName = std::string(dot, nextDot - dot);
1470 }
1471 if (subElement) {
1472 *subElement = *lastDot == '.' ? lastDot + 1 : lastDot;
1473 }
1474 return obj;
1475 }
1476
1477 DocumentObject* DocumentObject::resolveRelativeLink(std::string& subname,
1478 DocumentObject*& link,
1479 std::string& linkSub) const
1480 {
1481 if (!link || !link->isAttachedToDocument() || !isAttachedToDocument()) {
1482 return nullptr;
1483 }
1484 auto ret = const_cast<DocumentObject*>(this);
1485 if (link != ret) {
1486 auto sub = subname.c_str();
1487 auto nextsub = sub;
1488 for (auto dot = strchr(nextsub, '.'); dot; nextsub = dot + 1, dot = strchr(nextsub, '.')) {
1489 std::string subcheck(sub, nextsub - sub);
1490 subcheck += link->getNameInDocument();
1491 subcheck += '.';
1492 if (getSubObject(subcheck.c_str()) == link) {
1493 ret = getSubObject(std::string(sub, dot + 1 - sub).c_str());
1494 if (!ret) {
1495 return nullptr;
1496 }
1497 subname = std::string(dot + 1);
1498 break;
1499 }
1500 }
1501 return ret;
1502 }
1503
1504 size_t pos = 0, linkPos = 0;
1505 std::string linkssub, ssub;
1506 do {
1507 linkPos = linkSub.find('.', linkPos);
1508 if (linkPos == std::string::npos) {
1509 link = nullptr;
1510 return nullptr;
1511 }
1512 ++linkPos;
1513 pos = subname.find('.', pos);
1514 if (pos == std::string::npos) {
1515 subname.clear();
1516 ret = nullptr;
1517 break;
1518 }
1519 ++pos;
1520 } while (subname.compare(0, pos, linkSub, 0, linkPos) == 0);
1521
1522 if (pos != std::string::npos) {
1523 ret = getSubObject(subname.substr(0, pos).c_str());
1524 if (!ret) {
1525 link = nullptr;
1526 return nullptr;
1527 }
1528 subname = subname.substr(pos);
1529 }
1530 if (linkPos) {
1531 link = link->getSubObject(linkSub.substr(0, linkPos).c_str());
1532 if (!link) {
1533 return nullptr;
1534 }
1535 linkSub = linkSub.substr(linkPos);
1536 }
1537 return ret;
1538 }
1539
1540 bool DocumentObject::adjustRelativeLinks(const std::set<App::DocumentObject*>& inList,
1541 std::set<App::DocumentObject*>* visited)
1542 {
1543 if (visited) {
1544 visited->insert(this);
1545 }
1546
1547 bool touched = false;
1548 std::vector<Property*> props;
1549 getPropertyList(props);
1550 for (auto prop : props) {
1551 auto linkProp = freecad_cast<PropertyLinkBase*>(prop);
1552 if (linkProp && linkProp->adjustLink(inList)) {
1553 touched = true;
1554 }
1555 }
1556 if (visited) {
1557 for (auto obj : getOutList()) {
1558 if (!visited->count(obj)) {
1559 if (obj->adjustRelativeLinks(inList, visited)) {
1560 touched = true;
1561 }
1562 }
1563 }
1564 }
1565 return touched;
1566 }
1567
1568 std::string DocumentObject::getElementMapVersion(const App::Property* _prop, bool restored) const
1569 {
1570 auto prop = freecad_cast<const PropertyComplexGeoData*>(_prop);
1571 if (!prop) {
1572 return std::string();
1573 }
1574 return prop->getElementMapVersion(restored);
1575 }
1576
1577 bool DocumentObject::checkElementMapVersion(const App::Property* _prop, const char* ver) const
1578 {
1579 auto prop = freecad_cast<const PropertyComplexGeoData*>(_prop);
1580 if (!prop) {
1581 return false;
1582 }
1583 return prop->checkElementMapVersion(ver);
1584 }
1585
1586 const std::string& DocumentObject::hiddenMarker()
1587 {
1588 static std::string marker("!hide");
1589 return marker;
1590 }
1591
1592 const char* DocumentObject::hasHiddenMarker(const char* subname)
1593 {
1594 if (!subname) {
1595 return nullptr;
1596 }
1597 const char* marker = strrchr(subname, '.');
1598 if (!marker) {
1599 marker = subname;
1600 }
1601 else {
1602 ++marker;
1603 }
1604 return hiddenMarker() == marker ? marker : nullptr;
1605 }
1606
1607 bool DocumentObject::redirectSubName(std::ostringstream&, DocumentObject*, DocumentObject*) const
1608 {
1609 return false;
1610 }
1611
1612 void DocumentObject::onPropertyStatusChanged(const Property& prop, unsigned long oldStatus)
1613 {
1614 (void)oldStatus;
1615 if (!Document::isAnyRestoring() && isAttachedToDocument() && getDocument()) {
1616 getDocument()->signalChangePropertyEditor(*getDocument(), prop);
1617 }
1618 }
1619
1620 Base::Placement DocumentObject::getPlacementOf(const std::string& sub, DocumentObject* targetObj)
1621 {
1622 Base::Placement plc;
1623 auto* propPlacement = freecad_cast<App::PropertyPlacement*>(getPropertyByName("Placement"));
1624 if (propPlacement) {
1625 // If the object has no placement (like a Group), plc stays identity so we can proceed.
1626 plc = propPlacement->getValue();
1627 }
1628
1629 std::vector<std::string> names = Base::Tools::splitSubName(sub);
1630
1631 if (names.empty() || this == targetObj) {
1632 return plc;
1633 }
1634
1635 DocumentObject* subObj = getDocument()->getObject(names.front().c_str());
1636
1637 if (!subObj) {
1638 return plc;
1639 }
1640
1641 std::vector<std::string> newNames(names.begin() + 1, names.end());
1642 std::string newSub = Base::Tools::joinList(newNames, ".");
1643
1644 return plc * subObj->getPlacementOf(newSub, targetObj);
1645 }
1646
1647 Base::Placement DocumentObject::getPlacement() const
1648 {
1649 Base::Placement plc;
1650 if (auto* prop = getPlacementProperty()) {
1651 plc = prop->getValue();
1652 }
1653 return plc;
1654 }
1655
1656 App::PropertyPlacement* DocumentObject::getPlacementProperty() const
1657 {
1658 if (auto linkExtension = getExtensionByType<App::LinkBaseExtension>(true)) {
1659 if (auto linkPlacementProp = linkExtension->getLinkPlacementProperty()) {
1660 return linkPlacementProp;
1661 }
1662
1663 return linkExtension->getPlacementProperty();
1664 }
1665
1666 return getPropertyByName<App::PropertyPlacement>("Placement");
1667 }
1668
1669