1 // Copyright (C) 2014-2024 CEA, EDF
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include <Model_Document.h>
21 #include <Model_Data.h>
22 #include <Model_Objects.h>
23 #include <Model_Application.h>
24 #include <Model_Session.h>
25 #include <Model_Events.h>
26 #include <Model_Tools.h>
27 #include <ModelAPI_ResultPart.h>
28 #include <ModelAPI_Validator.h>
29 #include <ModelAPI_CompositeFeature.h>
30 #include <ModelAPI_AttributeSelectionList.h>
31 #include <ModelAPI_Tools.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <Events_Loop.h>
34 #include <Events_InfoMessage.h>
35 #include <GeomAPI_Tools.h>
37 #include <Locale_Convert.h>
39 #include <TDataStd_Integer.hxx>
40 #include <TDataStd_Comment.hxx>
41 #include <TDF_ChildIDIterator.hxx>
42 #include <TDataStd_ReferenceArray.hxx>
43 #include <TDataStd_ReferenceList.hxx>
44 #include <TDataStd_IntegerArray.hxx>
45 #include <TDataStd_HLabelArray1.hxx>
46 #include <TDataStd_Name.hxx>
47 #include <TDataStd_AsciiString.hxx>
48 #include <TDF_Reference.hxx>
49 #include <TDF_ChildIDIterator.hxx>
50 #include <TDF_Delta.hxx>
51 #include <TDF_AttributeDelta.hxx>
52 #include <TDF_AttributeDeltaList.hxx>
53 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
54 #include <TDF_ListIteratorOfLabelList.hxx>
55 #include <TDF_LabelMap.hxx>
56 #include <TDF_Tool.hxx>
57 #include <TDF_DeltaOnAddition.hxx>
58 #include <TDataStd_ExtStringList.hxx>
59 #include <TDataStd_UAttribute.hxx>
60 #include <TNaming_Builder.hxx>
61 #include <TNaming_SameShapeIterator.hxx>
62 #include <TNaming_Iterator.hxx>
63 #include <TNaming_NamedShape.hxx>
64 #include <TNaming_Tool.hxx>
65 #include <TNaming_OldShapeIterator.hxx>
66 #include <TopTools_DataMapOfShapeShape.hxx>
67 #include <TopTools_ListOfShape.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopoDS_Shape.hxx>
72 #include <OSD_Directory.hxx>
73 #include <OSD_File.hxx>
74 #include <OSD_Path.hxx>
75 #include <OSD_Protection.hxx>
85 # define _separator_ '\\'
87 # define _separator_ '/'
90 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
92 static const int TAG_GENERAL = 1; // general properties tag
95 /// where the reference to the current feature label is located (or no attribute if null feature)
96 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
97 /// integer, index of the transaction + GUID for auto recomputation blocking
98 static const int TAG_CURRENT_TRANSACTION = 2;
99 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
100 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
101 ///< naming structures constructions selected from other document
102 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
104 /// reference to the shape in external document: sting list attribute identifier
105 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
107 Model_Document::Model_Document(const int theID, const std::string theKind)
111 myIsSetCurrentFeature(false)
113 Model_Application::getApplication()->NewDocument("BinOcaf", myDoc);
114 myObjs = new Model_Objects(myDoc->Main());
115 myDoc->SetUndoLimit(UNDO_LIMIT);
116 myTransactionSave = 0;
117 myExecuteFeatures = true;
118 // to have something in the document and avoid empty doc open/save problem
119 // in transaction for nesting correct working
121 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
122 // this to avoid creation of integer attribute outside the transaction after undo
124 myDoc->CommitCommand();
127 Model_Document::~Model_Document()
136 void Model_Document::setThis(DocumentPtr theDoc)
138 myObjs->setOwner(theDoc);
141 /// Returns the file name of this document by the name of directory and identifier of a document
142 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
144 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
145 // remove end-separators
146 while(aPath.Length() &&
147 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
148 aPath.Remove(aPath.Length());
149 aPath += _separator_;
150 aPath += theID.c_str();
151 aPath += ".cbf"; // standard binary file extension
155 bool Model_Document::isRoot() const
157 return this == Model_Session::get()->moduleDocument().get();
161 /// Makes all modification and generation naming shapes that have old shapes corresponding to
162 /// shapes in a root document be equal to this root document
163 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
165 TopTools_DataMapOfShapeShape aCurrentToRoot; // shapes that must be updated: from this to root
166 TDF_ChildIDIterator aThisIter(theThisAccess.Root(), kEXTERNAL_SHAPE_REF, true);
167 for(; aThisIter.More(); aThisIter.Next()) {
168 aCurrentToRoot.Clear();
169 Handle(TNaming_NamedShape) aNS;
170 if (!aThisIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS))
172 if (aNS->Evolution() != TNaming_GENERATED && aNS->Evolution() != TNaming_MODIFY)
174 for (TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
175 const TopoDS_Shape& anOld = aNSIter.OldShape();
178 TNaming_OldShapeIterator aNewIter(anOld, theThisAccess);
179 for (; aNewIter.More(); aNewIter.Next()) {
180 TNaming_Evolution anEvolution = aNewIter.NamedShape()->Evolution();
181 if (anEvolution != TNaming_SELECTED && anEvolution != TNaming_DELETE)
186 GeomShapePtr anOldShape(new GeomAPI_Shape), aRootShape(new GeomAPI_Shape);
187 anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOld));
188 anOldShape = GeomAPI_Tools::getTypedShape(anOldShape);
190 // search the same shape in the root document
191 Handle(TDataStd_ExtStringList) anEntries =
192 Handle(TDataStd_ExtStringList)::DownCast(aThisIter.Value());
193 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
194 for (; anIter.More(); anIter.Next()) {
196 TDF_Tool::Label(theRootAccess.Data(), anIter.Value(), aRootLab);
197 if (aRootLab.IsNull())
199 Handle(TNaming_NamedShape) aRootNS;
200 if (!aRootLab.FindAttribute(TNaming_NamedShape::GetID(), aRootNS))
202 TNaming_Iterator aRootShapes(aRootNS);
203 for (; aRootShapes.More(); aRootShapes.Next()) {
204 if (aRootShapes.NewShape().IsNull())
206 aRootShape->setImpl(new TopoDS_Shape(aRootShapes.NewShape()));
207 aRootShape = GeomAPI_Tools::getTypedShape(aRootShape);
208 if (!anOldShape->isEqual(aRootShape)) // special checking by geometry
210 // found a good corresponded shape
211 if (!anOld.IsEqual(aRootShapes.NewShape()))
212 aCurrentToRoot.Bind(anOld, aRootShapes.NewShape());
216 if (!aCurrentToRoot.IsEmpty()) { // update the whole named shape content
217 TopTools_ListOfShape anOld, aNew;
218 TNaming_Evolution anEvol = aNS->Evolution();
219 for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
220 anOld.Prepend(aCurrentToRoot.IsBound(aNSIter.OldShape()) ?
221 aCurrentToRoot.Find(aNSIter.OldShape()) : aNSIter.OldShape());
222 aNew.Prepend(aNSIter.NewShape());
224 TNaming_Builder aBuilder(aNS->Label());
225 TopTools_ListOfShape::Iterator anOldIter(anOld), aNewIter(aNew);
226 for(; anOldIter.More(); anOldIter.Next(), aNewIter.Next()) {
227 if (anEvol == TNaming_GENERATED) {
228 aBuilder.Generated(anOldIter.Value(), aNewIter.Value());
229 } else if (anEvol == TNaming_MODIFY) {
230 aBuilder.Modify(anOldIter.Value(), aNewIter.Value());
238 static bool loadDocument(Handle(Model_Application) theApp,
239 Handle(TDocStd_Document)& theDoc,
240 const TCollection_ExtendedString& theFilename)
242 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus)-1;
244 aStatus = theApp->Open(theFilename, theDoc);
245 } catch (Standard_Failure const& anException) {
246 Events_InfoMessage("Model_Document",
247 "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
250 bool isOk = aStatus == PCDM_RS_OK;
254 case PCDM_RS_UnknownDocument:
255 Events_InfoMessage("Model_Document", "Can not open document").send();
257 case PCDM_RS_AlreadyRetrieved:
258 Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
260 case PCDM_RS_AlreadyRetrievedAndModified:
261 Events_InfoMessage("Model_Document",
262 "Can not open document: already opened and modified").send();
264 case PCDM_RS_NoDriver:
265 Events_InfoMessage("Model_Document",
266 "Can not open document: driver library is not found").send();
268 case PCDM_RS_UnknownFileDriver:
269 Events_InfoMessage("Model_Document",
270 "Can not open document: unknown driver for opening").send();
272 case PCDM_RS_OpenError:
273 Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
275 case PCDM_RS_NoVersion:
276 Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
278 case PCDM_RS_NoModel:
279 Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
281 case PCDM_RS_NoDocument:
282 Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
284 case PCDM_RS_FormatFailure:
285 Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
287 case PCDM_RS_TypeNotFoundInSchema:
288 Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
290 case PCDM_RS_UnrecognizedFileFormat:
291 Events_InfoMessage("Model_Document",
292 "Can not open document: unrecognized file format").send();
294 case PCDM_RS_MakeFailure:
295 Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
297 case PCDM_RS_PermissionDenied:
298 Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
300 case PCDM_RS_DriverFailure:
301 Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
304 Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
312 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
314 Handle(Model_Application) anApp = Model_Application::getApplication();
316 anApp->setLoadPath(theDirName);
318 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
319 Handle(TDocStd_Document) aLoaded;
320 bool isOk = loadDocument(anApp, aLoaded, aPath);
322 std::shared_ptr<Model_Session> aSession =
323 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
325 // keep handle to avoid destruction of the document until myObjs works on it
326 Handle(TDocStd_Document) anOldDoc = myDoc;
328 myDoc->SetUndoLimit(UNDO_LIMIT);
330 // to avoid the problem that feature is created in the current, not this, document
331 aSession->setActiveDocument(anApp->document(myID), false);
332 aSession->setCheckTransactions(false);
335 anOldDoc->ClearRedos();
336 anOldDoc->ClearUndos();
338 myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
339 myObjs->setOwner(theThis);
340 // update the current features status
341 setCurrentFeature(currentFeature(false), false);
342 aSession->setCheckTransactions(true);
343 aSession->setActiveDocument(aSession->moduleDocument(), false);
344 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
345 // aSession->setActiveDocument(anApp->getDocument(myID), true);
347 // make sub-parts as loaded by demand
348 std::list<ResultPtr> aPartResults;
349 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
350 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
351 for(; aPartRes != aPartResults.end(); aPartRes++) {
352 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
354 anApp->setLoadByDemand(aPart->data()->name(),
355 aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
358 updateShapesFromRoot(myDoc->Main(),
359 std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument())->generalLabel());
361 } else { // open failed, but new document was created to work with it: inform the model
362 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
367 bool Model_Document::importPart(const char* theFileName,
368 std::list<std::shared_ptr<ModelAPI_Feature> >& theImported,
371 Handle(Model_Application) anApp = Model_Application::getApplication();
372 TCollection_ExtendedString aFormat;
373 if (!anApp->Format(theFileName, aFormat))
376 Handle(TDocStd_Document) aTempDoc;
377 bool isOk = loadDocument(anApp, aTempDoc, theFileName);
379 if (isOk && theCheckOnly) {
380 // verify all features are applicable for the current document type (e.g. PartSet)
381 std::shared_ptr<Model_Session> aSession =
382 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
383 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More() && isOk; anIt.Next()) {
384 TDF_Label aCurrentLab = anIt.Value();
385 Handle(TDataStd_Comment) aFeatureID;
386 TDF_Label aNewFeatuerLab;
387 if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
388 TCollection_AsciiString anID(aFeatureID->Get());
389 std::string aFeatureKind(anID.ToCString());
390 if (aSession->myPlugins.find(aFeatureKind) != aSession->myPlugins.end()) {
391 std::string& aDocKind = aSession->myPlugins[aFeatureKind].second;
392 isOk = aDocKind.empty() || aDocKind == kind();
398 if (isOk && !theCheckOnly) {
399 // copy features from the temporary document to the current
400 Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable();
401 // add to relocation table source root label to the destination label because
402 // sometimes there could be a reference to root (issue 3267 on import part
403 // with sketch with removed features)
404 aRelocTable->SetRelocation(aTempDoc->Main().Root(), myDoc->Main().Root());
405 TDF_LabelList anAllNewFeatures;
406 // Perform the copying twice for correct references:
407 // 1. copy labels hierarchy and fill the relocation table
408 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
409 TDF_Label aCurrentLab = anIt.Value();
410 Handle(TDataStd_Comment) aFeatureID;
411 TDF_Label aNewFeatuerLab;
412 if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
413 TCollection_AsciiString anID(aFeatureID->Get());
414 FeaturePtr aNewFeature = addFeature(anID.ToCString());
415 std::shared_ptr<Model_Data> aData =
416 std::dynamic_pointer_cast<Model_Data>(aNewFeature->data());
417 aNewFeatuerLab = aData->label().Father();
418 Model_Tools::copyLabels(aCurrentLab, aNewFeatuerLab, aRelocTable);
419 theImported.push_back(aNewFeature);
421 anAllNewFeatures.Append(aNewFeatuerLab);
423 // 2. copy attributes
424 std::set<TCollection_AsciiString> aCoordinateLabels;
425 Model_Tools::labelsOfCoordinates(aCoordinateLabels, aRelocTable);
426 TDF_ListIteratorOfLabelList aNewIt(anAllNewFeatures);
427 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
428 TDF_Label aCurrentLab = anIt.Value();
429 TDF_Label aFeatureLab = aNewIt.Value();
430 if (aFeatureLab.IsNull())
431 anAllNewFeatures.Remove(aNewIt);
433 Model_Tools::copyAttrsAndKeepRefsToCoordinates(
434 aCurrentLab, aFeatureLab, aCoordinateLabels, aRelocTable);
439 myObjs->synchronizeFeatures(anAllNewFeatures, true, false, false, true);
442 if (anApp->CanClose(aTempDoc) == CDM_CCS_OK)
443 anApp->Close(aTempDoc);
447 static bool saveDocument(Handle(Model_Application) theApp,
448 Handle(TDocStd_Document) theDoc,
449 const TCollection_ExtendedString& theFilename)
451 PCDM_StoreStatus aStatus;
453 // create the directory to save the document
454 OSD_Path aPathToFile = UTL::Path(theFilename);
455 aPathToFile.SetName("");
456 aPathToFile.SetExtension("");
457 OSD_Directory aBaseDir(aPathToFile);
458 if (aPathToFile.TrekLength() != 0 && !aBaseDir.Exists())
459 aBaseDir.Build(OSD_Protection());
461 aStatus = theApp->SaveAs(theDoc, theFilename);
463 catch (Standard_Failure const& anException) {
464 Events_InfoMessage("Model_Document",
465 "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
468 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
471 case PCDM_SS_DriverFailure:
472 Events_InfoMessage("Model_Document",
473 "Can not save document: save driver-library failure").send();
475 case PCDM_SS_WriteFailure:
476 Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
478 case PCDM_SS_Failure:
480 Events_InfoMessage("Model_Document", "Can not save document").send();
487 bool Model_Document::save(
488 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
490 // if the history line is not in the end, move it to the end before save, otherwise
491 // problems with results restore and (the most important) naming problems will appear
492 // due to change evolution to SELECTION (problems in NamedShape and Name)
493 FeaturePtr aWasCurrent;
494 std::shared_ptr<Model_Session> aSession =
495 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
496 if (currentFeature(false) != lastFeature()) {
497 aSession->setCheckTransactions(false);
498 aWasCurrent = currentFeature(false);
499 // if last is nested into something else, make this something else as last:
500 // otherwise it will look like edition of sub-element, so, the main will be disabled
501 FeaturePtr aLast = lastFeature();
503 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
506 aMain = ModelAPI_Tools::compositeOwner(aLast);
509 setCurrentFeature(aLast, true);
511 // create a directory in the root document if it is not yet exist
512 Handle(Model_Application) anApp = Model_Application::getApplication();
515 size_t aDirLen = strlen(theDirName);
516 std::wstring aWStr(aDirLen, L'#');
517 mbstowcs(&aWStr[0], theDirName, aDirLen);
518 CreateDirectory(aWStr.c_str(), NULL);
520 mkdir(theDirName, 0x1ff);
523 // filename in the dir is id of document inside of the given directory
524 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
525 bool isDone = saveDocument(anApp, myDoc, aPath);
527 if (aWasCurrent.get()) { // return the current feature to the initial position
528 setCurrentFeature(aWasCurrent, false);
529 aSession->setCheckTransactions(true);
532 myTransactionSave = int(myTransactions.size());
533 if (isDone) { // save also sub-documents if any
534 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
535 // iterate all result parts to find all loaded or not yet loaded documents
536 std::list<ResultPtr> aPartResults;
537 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
538 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
539 for(; aPartRes != aPartResults.end(); aPartRes++) {
540 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
541 if (!aPart->isActivated()) {
542 // copy not-activated document that is not in the memory
543 std::string aDocName = Locale::Convert::toString(aPart->data()->name());
544 if (!aDocName.empty()) {
546 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
547 OSD_Path aCopyPath(aSubPath);
548 OSD_File aFile(aCopyPath);
549 if (aFile.Exists()) {
550 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
551 OSD_Path aDestination(aDestinationDir);
552 aFile.Copy(aDestination);
553 theResults.push_back(aDestinationDir.ToCString());
555 Events_InfoMessage("Model_Document",
556 "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
559 } else { // simply save opened document
560 std::string aDocName = Locale::Convert::toString(aPart->data()->name());
561 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
562 save(theDirName, aDocName.c_str(), theResults);
569 bool Model_Document::save(const char* theFilename,
570 const std::list<FeaturePtr>& theExportFeatures) const
572 Handle(Model_Application) anApp = Model_Application::getApplication();
573 TCollection_ExtendedString aFormat;
574 if (!anApp->Format(theFilename, aFormat))
577 Handle(TDocStd_Document) aTempDoc = new TDocStd_Document(aFormat);
578 TDF_Label aMain = aTempDoc->Main();
580 Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable();
581 std::list<FeaturePtr>::const_iterator anIt = theExportFeatures.begin();
582 // Perform the copying twice for correct references:
583 // 1. copy labels hierarchy and fill the relocation table
584 for (; anIt != theExportFeatures.end(); ++anIt) {
585 TDF_Label aFeatureLab = aMain.NewChild();
586 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
587 Model_Tools::copyLabels(aData->label().Father(), aFeatureLab, aRelocTable);
589 // 2. copy attributes
590 std::set<TCollection_AsciiString> aCoordinateLabels;
591 Model_Tools::labelsOfCoordinates(aCoordinateLabels, aRelocTable);
592 TDF_ChildIterator aChildIt(aMain);
593 for (anIt = theExportFeatures.begin(); anIt != theExportFeatures.end(); ++anIt) {
594 TDF_Label aFeatureLab = aChildIt.Value();
595 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
596 Model_Tools::copyAttrsAndKeepRefsToCoordinates(
597 aData->label().Father(), aFeatureLab, aCoordinateLabels, aRelocTable);
601 bool isDone = saveDocument(anApp, aTempDoc, theFilename);
602 if (aTempDoc->CanClose() == CDM_CCS_OK)
607 void Model_Document::close(const bool theForever)
609 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
610 if (!isRoot() && this == aPM->activeDocument().get()) {
611 aPM->setActiveDocument(aPM->moduleDocument());
612 } else if (isRoot()) {
613 // erase the active document if root is closed
614 aPM->setActiveDocument(DocumentPtr());
617 const std::set<int> aSubs = subDocuments();
618 std::set<int>::iterator aSubIter = aSubs.begin();
619 for (; aSubIter != aSubs.end(); aSubIter++) {
620 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
621 if (aSub->myObjs) // if it was not closed before
622 aSub->close(theForever);
625 // close for this document needs no transaction in this document
626 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
628 // close all only if it is really asked, otherwise it can be undone/redone
630 // flush everything to avoid messages with bad objects
633 if (myDoc->CanClose() == CDM_CCS_OK)
635 mySelectionFeature.reset();
637 setCurrentFeature(FeaturePtr(), false); // disables all features
638 // update the OB: features are disabled (on remove of Part)
639 Events_Loop* aLoop = Events_Loop::loop();
640 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
641 aLoop->flush(aDeleteEvent);
644 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
647 void Model_Document::startOperation()
649 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
650 if (myDoc->HasOpenCommand()) { // start of nested command
651 if (myDoc->CommitCommand()) {
652 // commit the current: it will contain all nested after compactification
653 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
655 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
656 myDoc->OpenCommand();
657 } else { // start the simple command
660 // starts a new operation
661 myTransactions.push_back(Transaction());
662 if (!myNestedNum.empty())
663 (*myNestedNum.rbegin())++;
665 // new command for all subs
666 const std::set<int> aSubs = subDocuments();
667 std::set<int>::iterator aSubIter = aSubs.begin();
668 for (; aSubIter != aSubs.end(); aSubIter++)
669 subDoc(*aSubIter)->startOperation();
672 void Model_Document::compactNested()
674 if (!myNestedNum.empty()) {
675 int aNumToCompact = *(myNestedNum.rbegin());
676 int aSumOfTransaction = 0;
677 for(int a = 0; a < aNumToCompact; a++) {
678 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
679 myTransactions.pop_back();
681 // the latest transaction is the start of lower-level operation which starts the nested
682 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
683 myNestedNum.pop_back();
687 /// Compares the content of the given attributes, returns true if equal.
688 /// This method is used to avoid empty transactions when only "current" is changed
689 /// to some value and then comes back in this transaction, so, it compares only
690 /// references and Boolean and Integer Arrays for the current moment.
691 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
693 Standard_GUID aGUID1 = theAttr1->ID();
694 if (aGUID1 == TDF_Reference::GetID()) { // reference
695 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
696 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
697 if (aRef1.IsNull() && aRef2.IsNull())
699 if (aRef1.IsNull() || aRef2.IsNull())
701 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
702 } else if (aGUID1 == TDataStd_BooleanArray::GetID()) {
703 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
704 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
705 if (anArr1.IsNull() && anArr2.IsNull())
707 if (anArr1.IsNull() || anArr2.IsNull())
709 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
710 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
711 if (a == 1 && // second is for display
712 anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
713 anArr2->Label().Depth() == 6))
715 if (anArr1->Value(a) != anArr2->Value(a))
720 } else if (aGUID1 == TDataStd_IntegerArray::GetID()) {
721 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
722 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
723 if (anArr1.IsNull() && anArr2.IsNull())
725 if (anArr1.IsNull() || anArr2.IsNull())
727 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
728 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
729 if (anArr1->Value(a) != anArr2->Value(a)) {
730 // avoid the transaction ID checking
731 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
732 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
738 } else if (aGUID1 == TDataStd_ReferenceArray::GetID()) {
739 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
740 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
741 if (anArr1.IsNull() && anArr2.IsNull())
743 if (anArr1.IsNull() || anArr2.IsNull())
745 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
746 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
747 if (anArr1->Value(a) != anArr2->Value(a)) {
748 // avoid the transaction ID checking
749 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
750 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
756 } else if (aGUID1 == TDataStd_ReferenceList::GetID()) {
757 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
758 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
759 if (aList1.IsNull() && aList2.IsNull())
761 if (aList1.IsNull() || aList2.IsNull())
763 const TDF_LabelList& aLList1 = aList1->List();
764 const TDF_LabelList& aLList2 = aList2->List();
765 TDF_ListIteratorOfLabelList aLIter1(aLList1);
766 TDF_ListIteratorOfLabelList aLIter2(aLList2);
767 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
768 if (aLIter1.Value() != aLIter2.Value())
771 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
772 } else if (aGUID1 == TDF_TagSource::GetID()) {
773 return true; // it just for created and removed feature: nothing is changed
778 /// Returns true if the last transaction is actually empty: modification to the same values
779 /// were performed only
780 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
781 Handle(TDF_Delta) aDelta;
782 aDelta = theDoc->GetUndos().Last();
783 TDF_LabelList aDeltaList;
784 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
785 if (!aDeltaList.IsEmpty()) {
788 // add also label of the modified attributes
789 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
790 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
791 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
792 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
793 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
794 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
795 Handle(TDF_Attribute) aCurrentAttr;
796 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
797 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
798 continue; // attribute is not changed actually
801 if (anADelta->Attribute()->ID() == TDataStd_AsciiString::GetID()) {
802 continue; // error message is disappeared
811 bool Model_Document::finishOperation()
813 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
814 static std::shared_ptr<Model_Session> aSession =
815 std::static_pointer_cast<Model_Session>(Model_Session::get());
817 // open transaction if nested is closed to fit inside
818 // all synchronizeBackRefs and flushed consequences
819 if (isNestedClosed) {
820 myDoc->OpenCommand();
822 // do it before flashes to enable and recompute nesting features correctly
823 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
824 // if all nested operations are closed, make current the higher level objects (to perform
825 // it in the python scripts correctly): sketch become current after creation of sub-elements
826 FeaturePtr aCurrent = currentFeature(false);
827 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
830 aNext = ModelAPI_Tools::compositeOwner(aMain);
832 if (aMain.get() && aMain != aCurrent)
833 setCurrentFeature(aMain, false);
835 myObjs->synchronizeBackRefs();
836 Events_Loop* aLoop = Events_Loop::loop();
837 static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
838 static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
839 static const Events_ID kRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
840 static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
841 aLoop->flush(kCreatedEvent);
842 aLoop->flush(kUpdatedEvent);
843 aLoop->flush(kRedispEvent);
844 aLoop->flush(kDeletedEvent);
846 if (isNestedClosed) {
847 if (myDoc->CommitCommand())
848 myTransactions.rbegin()->myOCAFNum++;
851 // this must be here just after everything is finished but before real transaction stop
852 // to avoid messages about modifications outside of the transaction
853 // and to rebuild everything after all updates and creates
854 if (isRoot()) { // once for root document
855 static std::shared_ptr<Events_Message> aFinishMsg
856 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
857 Events_Loop::loop()->send(aFinishMsg);
860 // for open of document with primitive box inside (finish transaction in initAttributes)
861 bool aWasActivatedFlushes = aLoop->activateFlushes(true);
862 while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
863 aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
864 aLoop->flush(kCreatedEvent);
865 aLoop->flush(kUpdatedEvent);
866 aLoop->flush(kRedispEvent);
867 aLoop->flush(kDeletedEvent);
869 aLoop->activateFlushes(aWasActivatedFlushes);
871 // to avoid "updated" message appearance by updater
872 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
874 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
875 bool aResult = false;
876 const std::set<int> aSubs = subDocuments();
877 std::set<int>::iterator aSubIter = aSubs.begin();
878 for (; aSubIter != aSubs.end(); aSubIter++)
879 if (subDoc(*aSubIter)->finishOperation())
882 // transaction may be empty if this document was created during this transaction (create part)
883 if (!myTransactions.empty() && myDoc->CommitCommand()) {
884 // if commit is successful, just increment counters
885 if (isEmptyTransaction(myDoc)) { // erase this transaction
889 myTransactions.rbegin()->myOCAFNum++;
894 if (isNestedClosed) {
897 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
898 aResult = myTransactions.rbegin()->myOCAFNum != 0;
900 if (!aResult && isRoot()) {
901 // nothing inside in all documents, so remove this transaction from the transactions list
902 undoInternal(true, false);
904 // on finish clear redo in any case (issue 446) and for all subs (issue 408)
907 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
908 subDoc(*aSubIter)->myDoc->ClearRedos();
909 subDoc(*aSubIter)->myRedos.clear();
915 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
916 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
917 const bool isRedo = false) {
918 Handle(TDF_Delta) aDelta;
920 aDelta = theDoc->GetRedos().First();
922 aDelta = theDoc->GetUndos().Last();
923 TDF_LabelList aDeltaList;
924 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
925 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
926 theDelta.Append(aListIter.Value());
928 // add also label of the modified attributes
929 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
930 /// named shape evolution also modifies integer on this label: exclude it
931 TDF_LabelMap anExcludedInt;
932 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
933 if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
934 // Boolean array is used for feature auxiliary attributes only, feature args are not modified
937 if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
938 anExcludedInt.Add(anAttr.Value()->Label());
939 // named shape evolution is changed in history update => skip them,
940 // they are not the features arguments
943 if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
944 if (anExcludedInt.Contains(anAttr.Value()->Label()))
947 theDelta.Append(anAttr.Value()->Label());
949 TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
950 for(; aDeltaIter.More(); aDeltaIter.Next()) {
951 if (anExcludedInt.Contains(aDeltaIter.Value())) {
952 theDelta.Remove(aDeltaIter);
953 if (!aDeltaIter.More())
959 void Model_Document::abortOperation()
961 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
962 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
964 // store undo-delta here as undo actually does in the method later
965 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
966 for(a = 0; a < aNumTransactions; a++) {
967 modifiedLabels(myDoc, aDeltaLabels);
970 for(a = 0; a < aNumTransactions; a++) {
974 undoInternal(false, false);
977 } else { // abort the current
978 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
979 myTransactions.pop_back();
980 if (!myNestedNum.empty())
981 (*myNestedNum.rbegin())--;
982 // roll back the needed number of transactions
983 //myDoc->AbortCommand();
984 // instead of abort, do commit and undo: to get the delta of modifications
985 if (myDoc->CommitCommand()) {
986 modifiedLabels(myDoc, aDeltaLabels);
989 for(int a = 0; a < aNumTransactions; a++) {
990 modifiedLabels(myDoc, aDeltaLabels);
995 // abort for all subs, flushes will be later, in the end of root abort
996 const std::set<int> aSubs = subDocuments();
997 std::set<int>::iterator aSubIter = aSubs.begin();
998 for (; aSubIter != aSubs.end(); aSubIter++)
999 subDoc(*aSubIter)->abortOperation();
1000 // references may be changed because they are set in attributes on the fly
1001 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1004 bool Model_Document::isOperation() const
1006 // operation is opened for all documents: no need to check subs
1007 return myDoc->HasOpenCommand() == Standard_True ;
1010 bool Model_Document::isModified()
1012 // is modified if at least one operation was committed and not undone
1013 return (int)myTransactions.size() != myTransactionSave || isOperation();
1016 bool Model_Document::canUndo()
1018 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
1019 int aCurrentNum = isOperation() ? 1 : 0;
1020 if (myDoc->GetAvailableUndos() > 0 &&
1021 // there is something to undo in nested
1022 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
1023 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
1025 // check other subs contains operation that can be undone
1026 const std::set<int> aSubs = subDocuments();
1027 std::set<int>::iterator aSubIter = aSubs.begin();
1028 for (; aSubIter != aSubs.end(); aSubIter++) {
1029 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
1030 if (aSub->myObjs) {// if it was not closed before
1031 if (aSub->canUndo())
1039 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
1041 if (myTransactions.empty())
1043 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
1044 myRedos.push_back(*myTransactions.rbegin());
1045 myTransactions.pop_back();
1046 if (!myNestedNum.empty())
1047 (*myNestedNum.rbegin())--;
1048 // roll back the needed number of transactions
1049 TDF_LabelList aDeltaLabels;
1050 for(int a = 0; a < aNumTransactions; a++) {
1052 modifiedLabels(myDoc, aDeltaLabels);
1056 std::set<int> aSubs;
1058 // undo for all subs
1059 aSubs = subDocuments();
1060 std::set<int>::iterator aSubIter = aSubs.begin();
1061 for (; aSubIter != aSubs.end(); aSubIter++) {
1062 if (!subDoc(*aSubIter)->myObjs)
1064 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
1067 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
1068 if (theSynchronize) {
1069 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1070 // update the current features status
1071 setCurrentFeature(currentFeature(false), false);
1074 // undo for all subs
1075 const std::set<int> aNewSubs = subDocuments();
1076 std::set<int>::iterator aNewSubIter = aNewSubs.begin();
1077 for (; aNewSubIter != aNewSubs.end(); aNewSubIter++) {
1078 // synchronize only newly appeared documents
1079 if (!subDoc(*aNewSubIter)->myObjs || aSubs.find(*aNewSubIter) != aSubs.end())
1081 TDF_LabelList anEmptyDeltas;
1082 subDoc(*aNewSubIter)->myObjs->synchronizeFeatures(anEmptyDeltas, true, false, true, true);
1088 void Model_Document::undo()
1090 undoInternal(true, true);
1093 bool Model_Document::canRedo()
1095 if (!myRedos.empty())
1097 // check other subs contains operation that can be redone
1098 const std::set<int> aSubs = subDocuments();
1099 std::set<int>::iterator aSubIter = aSubs.begin();
1100 for (; aSubIter != aSubs.end(); aSubIter++) {
1101 if (!subDoc(*aSubIter)->myObjs)
1103 if (subDoc(*aSubIter)->canRedo())
1109 void Model_Document::redo()
1111 if (!myNestedNum.empty())
1112 (*myNestedNum.rbegin())++;
1113 int aNumRedos = myRedos.rbegin()->myOCAFNum;
1114 myTransactions.push_back(*myRedos.rbegin());
1116 TDF_LabelList aDeltaLabels;
1117 for(int a = 0; a < aNumRedos; a++) {
1118 modifiedLabels(myDoc, aDeltaLabels, true);
1122 // redo for all subs
1123 const std::set<int> aSubs = subDocuments();
1124 std::set<int>::iterator aSubIter = aSubs.begin();
1125 for (; aSubIter != aSubs.end(); aSubIter++)
1126 subDoc(*aSubIter)->redo();
1128 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
1129 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1130 // update the current features status
1131 setCurrentFeature(currentFeature(false), false);
1134 void Model_Document::clearUndoRedo()
1136 myNestedNum.clear();
1137 myTransactions.clear();
1139 myTransactionSave = 0;
1140 myDoc->ClearUndos();
1141 myDoc->ClearRedos();
1142 // clear for all subs
1143 const std::set<int> aSubs = subDocuments();
1144 for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++)
1145 subDoc(*aSubIter)->clearUndoRedo();
1148 // this is used for creation of undo/redo1-list by GUI
1150 std::list<std::string> Model_Document::undoList() const
1152 std::list<std::string> aResult;
1153 // the number of skipped current operations (on undo they will be aborted)
1154 int aSkipCurrent = isOperation() ? 1 : 0;
1155 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
1156 int aNumUndo = int(myTransactions.size());
1157 if (!myNestedNum.empty())
1158 aNumUndo = *myNestedNum.rbegin();
1159 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
1160 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
1161 else aSkipCurrent--;
1166 std::list<std::string> Model_Document::redoList() const
1168 std::list<std::string> aResult;
1169 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
1170 for( ; aTrIter != myRedos.crend(); aTrIter++) {
1171 aResult.push_back(aTrIter->myId);
1177 void Model_Document::operationId(const std::string& theId)
1179 myTransactions.rbegin()->myId = theId;
1182 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
1184 std::shared_ptr<Model_Session> aSession =
1185 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
1186 if (!aSession->hasModuleDocument() || !myObjs)
1187 return FeaturePtr(); // this may be on close of the document
1188 FeaturePtr aFeature = aSession->createFeature(theID, this);
1192 Model_Document* aDocToAdd;
1193 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
1194 if (aFeature->documentToAdd() != kind()) { // the root document by default
1195 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
1199 } else { // if customized is not presented, add to "this" document
1203 // searching for feature after which must be added the next feature: this is the current feature
1204 // but also all sub-features of this feature
1205 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
1206 bool isModified = true;
1207 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
1208 aComp.get() && isModified;
1209 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
1211 int aSubs = aComp->numberOfSubs(false);
1212 for(int a = 0; a < aSubs; a++) {
1213 FeaturePtr aSub = aComp->subFeature(a, false);
1214 if (aSub && myObjs->isLater(aSub, aCurrent)) {
1220 // #2861,3029: if the parameter is added, add it after parameters existing in the list
1221 if (aCurrent.get() &&
1222 (aFeature->getKind() == "Parameter" || aFeature->getKind() == "ParametersMgr")) {
1223 int anIndex = kUNDEFINED_FEATURE_INDEX;
1224 for(FeaturePtr aNextFeat = myObjs->nextFeature(aCurrent, anIndex);
1225 aNextFeat.get() && aNextFeat->getKind() == "Parameter";
1226 aNextFeat = myObjs->nextFeature(aCurrent, anIndex))
1227 aCurrent = aNextFeat;
1229 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
1230 if (!aFeature->isAction()) { // do not add action to the data model
1231 if (theMakeCurrent) // after all this feature stays in the document, so make it current
1232 aDocToAdd->setCurrentFeature(aFeature, false);
1233 } else { // feature must be executed
1234 // no creation event => updater not working, problem with remove part
1235 aFeature->execute();
1241 void Model_Document::refsToFeature(FeaturePtr theFeature,
1242 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
1244 myObjs->refsToFeature(theFeature, theRefs, isSendError);
1247 void Model_Document::removeFeature(FeaturePtr theFeature)
1249 myObjs->removeFeature(theFeature);
1250 // fix for #2723: send signal that part is updated
1251 if (!isRoot() && isOperation()) {
1252 std::shared_ptr<Model_Document> aRoot =
1253 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1254 std::list<ResultPtr> allParts;
1255 aRoot->objects()->allResults(ModelAPI_ResultPart::group(), allParts);
1256 std::list<ResultPtr>::iterator aParts = allParts.begin();
1257 for(; aParts != allParts.end(); aParts++) {
1258 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aParts);
1259 if (aPart->partDoc().get() == this) {
1260 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1261 ModelAPI_EventCreator::get()->sendUpdated(aRoot->feature(aPart), anEvent);
1268 // recursive function to check if theSub is a child of theMain composite feature
1269 // through all the hierarchy of parents
1270 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
1271 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
1274 if (aParent == theMain)
1276 return isSub(theMain, aParent);
1279 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis, const bool theSplit)
1281 bool aCurrentUp = theMoved == currentFeature(false);
1283 setCurrentFeatureUp();
1285 // if user adds after high-level feature with nested,
1286 // add it after all nested (otherwise the nested will be disabled)
1287 CompositeFeaturePtr aCompositeAfter =
1288 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
1289 FeaturePtr anAfterThisSub = theAfterThis;
1290 if (aCompositeAfter.get()) {
1291 FeaturePtr aSub = aCompositeAfter;
1292 int anIndex = kUNDEFINED_FEATURE_INDEX;
1294 FeaturePtr aNext = myObjs->nextFeature(aSub, anIndex);
1295 if (!isSub(aCompositeAfter, aNext)) {
1296 anAfterThisSub = aSub;
1300 } while (aSub.get());
1303 AttributeSelectionListPtr aMovedList;
1304 if (theMoved->getKind() == "Group") {
1305 aMovedList = theMoved->selectionList("group_list");
1306 if (aMovedList.get())
1307 aMovedList->setMakeCopy(true);
1309 myObjs->moveFeature(theMoved, anAfterThisSub);
1311 if (theSplit) { // split the group into sub-features
1312 theMoved->customAction("split");
1315 if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
1316 setCurrentFeature(currentFeature(false), false);
1317 } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
1318 // must be after move to make enabled all features which are before theMoved
1319 setCurrentFeature(theMoved, true);
1321 if (aMovedList.get())
1322 aMovedList->setMakeCopy(false);
1325 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
1328 myObjs->updateHistory(theObject);
1331 void Model_Document::updateHistory(const std::string theGroup)
1334 myObjs->updateHistory(theGroup);
1337 const std::set<int> Model_Document::subDocuments() const
1339 std::set<int> aResult;
1340 std::list<ResultPtr> aPartResults;
1341 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
1342 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
1343 for(; aPartRes != aPartResults.end(); aPartRes++) {
1344 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
1345 if (aPart && aPart->isActivated()) {
1346 aResult.insert(aPart->original()->partDoc()->id());
1352 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1354 // just store sub-document identifier here to manage it later
1355 return std::dynamic_pointer_cast<Model_Document>(
1356 Model_Application::getApplication()->document(theDocID));
1359 ObjectPtr Model_Document::object(const std::string& theGroupID,
1361 const bool theAllowFolder)
1363 return myObjs->object(theGroupID, theIndex, theAllowFolder);
1366 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1367 const std::string& theGroupID, const std::wstring& theName)
1369 return myObjs->objectByName(theGroupID, theName);
1372 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject,
1373 const bool theAllowFolder)
1375 return myObjs->index(theObject, theAllowFolder);
1378 int Model_Document::size(const std::string& theGroupID, const bool theAllowFolder)
1380 if (myObjs == 0) // may be on close
1382 return myObjs->size(theGroupID, theAllowFolder);
1385 std::shared_ptr<ModelAPI_Object> Model_Document::parent(
1386 const std::shared_ptr<ModelAPI_Object> theChild)
1388 if(myObjs == 0) // may be on close
1390 return myObjs->parent(theChild);
1393 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1395 if (!myObjs) // on close document feature destruction it may call this method
1396 return std::shared_ptr<ModelAPI_Feature>();
1397 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1398 Handle(TDF_Reference) aRef;
1399 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1400 TDF_Label aLab = aRef->Get();
1401 FeaturePtr aResult = myObjs->feature(aLab);
1402 if (theVisible) { // get nearest visible (in history) going up
1403 int anIndex = kUNDEFINED_FEATURE_INDEX;
1404 while(aResult.get() && !aResult->isInHistory()) {
1405 aResult = myObjs->nextFeature(aResult, anIndex, true);
1410 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1413 void Model_Document::setCurrentFeature(
1414 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1416 if (myIsSetCurrentFeature)
1418 myIsSetCurrentFeature = true;
1419 // blocks the flush signals to avoid each objects visualization in the viewer
1420 // they should not be shown once after all modifications are performed
1421 Events_Loop* aLoop = Events_Loop::loop();
1422 bool isActive = aLoop->activateFlushes(false);
1424 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1425 CompositeFeaturePtr aMain; // main feature that may nest the new current
1426 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1427 if (theCurrent.get()) {
1428 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1429 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1430 while(anOwner.get()) {
1434 anOwners.insert(anOwner);
1435 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1439 if (theVisible && !theCurrent.get()) {
1440 // needed to avoid disabling of PartSet initial constructions
1441 int anIndex = kUNDEFINED_FEATURE_INDEX;
1443 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1444 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1445 if (aNext->isInHistory()) {
1446 break; // next in history is not needed
1447 } else { // next not in history is good for making current
1452 if (theVisible) { // make RemoveResults feature be active even it is performed after the current
1453 int anIndex = kUNDEFINED_FEATURE_INDEX;
1455 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1456 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1457 if (aNext->isInHistory()) {
1458 break; // next in history is not needed
1459 } else if (aNext->getKind() == "RemoveResults"){
1464 if (theCurrent.get()) {
1465 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1466 if (!aData.get() || !aData->isValid()) {
1467 aLoop->activateFlushes(isActive);
1468 myIsSetCurrentFeature = false;
1471 TDF_Label aFeatureLabel = aData->label().Father();
1473 Handle(TDF_Reference) aRef;
1474 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1475 aRef->Set(aFeatureLabel);
1477 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1479 } else { // remove reference for the null feature
1480 aRefLab.ForgetAttribute(TDF_Reference::GetID());
1482 // make all features after this feature disabled in reversed order
1483 // (to remove results without dependencies)
1484 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1486 bool aPassed = false; // flag that the current object is already passed in cycle
1487 FeaturePtr anIter = myObjs->lastFeature();
1488 bool aWasChanged = false;
1489 bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1490 int anIndex = kUNDEFINED_FEATURE_INDEX;
1491 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, anIndex, true)) {
1492 // check this before passed become enabled: the current feature is enabled!
1493 if (anIter == theCurrent) aPassed = true;
1495 bool aDisabledFlag = !aPassed;
1497 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1498 aDisabledFlag = false;
1499 else if (anOwners.find(anIter) != anOwners.end())
1500 // disable the higher-level feature if the nested is the current
1501 if (aMain->getKind() != "Import") // exception for the import XAO feature with Group (2430)
1502 aDisabledFlag = true;
1505 if (anIter->getKind() == "Parameter") {
1506 // parameters are always out of the history of features, but not parameters
1507 // due to the issue 1491 all parameters are kept enabled any time
1508 //if (!isCurrentParameter)
1509 aDisabledFlag = false;
1510 } else if (isCurrentParameter) {
1511 // if parameter is active, all other features become enabled (issue 1307)
1512 aDisabledFlag = false;
1515 if (anIter->setDisabled(aDisabledFlag)) {
1516 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1517 // state of feature is changed => so inform that it must be updated if it has such state
1518 if (!aDisabledFlag &&
1519 (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1520 anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1521 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1522 // flush is in the end of this method
1523 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1526 // update for everyone concealment flag immediately: on edit feature in the middle of history
1528 std::list<ResultPtr> aResults;
1529 ModelAPI_Tools::allResults(anIter, aResults);
1530 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1531 for(; aRes != aResults.end(); aRes++) {
1532 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1533 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1535 // update the concealment status for display in isConcealed of ResultBody
1536 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1537 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1538 (*aRes)->isConcealed();
1542 myIsSetCurrentFeature = false;
1543 // unblock the flush signals and up them after this
1544 aLoop->activateFlushes(isActive);
1546 static Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
1547 aLoop->flush(kUpdatedSel);
1550 void Model_Document::setCurrentFeatureUp()
1552 // on remove just go up for minimum step: highlight external objects in sketch causes
1553 // problems if it is true: here and in "setCurrentFeature"
1554 FeaturePtr aCurrent = currentFeature(false);
1555 if (aCurrent.get()) { // if not, do nothing because null is the upper
1556 int anIndex = kUNDEFINED_FEATURE_INDEX;
1557 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, anIndex, true);
1558 // make the higher level composite as current (sketch becomes disabled if line is enabled)
1560 FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1561 // without cycle (issue 1555): otherwise extrusion fuse
1562 // will be enabled and displayed when inside sketch
1566 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1567 setCurrentFeature(aPrev, false);
1571 TDF_Label Model_Document::generalLabel() const
1573 return myDoc->Main().FindChild(TAG_GENERAL);
1576 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1577 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1579 return myObjs->createConstruction(theFeatureData, theIndex);
1582 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1583 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1585 return myObjs->createBody(theFeatureData, theIndex);
1588 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1589 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1591 return myObjs->createPart(theFeatureData, theIndex);
1594 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1595 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1596 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1598 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1601 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1602 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1604 return myObjs->createGroup(theFeatureData, theIndex);
1607 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1608 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1610 return myObjs->createField(theFeatureData, theIndex);
1613 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1614 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1616 return myObjs->createParameter(theFeatureData, theIndex);
1619 std::shared_ptr<ModelAPI_Folder> Model_Document::addFolder(
1620 std::shared_ptr<ModelAPI_Feature> theAddBefore)
1622 return myObjs->createFolder(theAddBefore);
1625 void Model_Document::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1628 myObjs->removeFolder(theFolder);
1631 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderAbove(
1632 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1634 return myObjs->findFolder(theFeatures, false);
1637 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderBelow(
1638 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1640 return myObjs->findFolder(theFeatures, true);
1643 std::shared_ptr<ModelAPI_Folder> Model_Document::findContainingFolder(
1644 const std::shared_ptr<ModelAPI_Feature>& theFeature,
1645 int& theIndexInFolder)
1647 return myObjs->findContainingFolder(theFeature, theIndexInFolder);
1650 bool Model_Document::moveToFolder(
1651 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1652 const std::shared_ptr<ModelAPI_Folder>& theFolder)
1654 return myObjs->moveToFolder(theFeatures, theFolder);
1657 bool Model_Document::removeFromFolder(
1658 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1659 const bool theBefore)
1661 return myObjs->removeFromFolder(theFeatures, theBefore);
1664 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1665 const std::shared_ptr<ModelAPI_Result>& theResult)
1667 if (myObjs == 0) // may be on close
1668 return std::shared_ptr<ModelAPI_Feature>();
1669 return myObjs->feature(theResult);
1672 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
1673 TDF_Label aCurrentLab = theLab;
1674 while(aCurrentLab.Depth() > 3)
1675 aCurrentLab = aCurrentLab.Father();
1676 return myObjs->feature(aCurrentLab);
1679 ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
1681 TDF_Label aCurrentLab = theLab;
1682 while(aCurrentLab.Depth() > 3) {
1683 ObjectPtr aResultObj = myObjs->object(aCurrentLab);
1684 if (aResultObj.get()) {
1685 return std::dynamic_pointer_cast<ModelAPI_Result>(aResultObj); // this may be null if feature
1687 aCurrentLab = aCurrentLab.Father();
1689 return ResultPtr(); // not found
1692 void Model_Document::addNamingName(const TDF_Label theLabel, std::wstring theName)
1694 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1696 if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
1697 // to keep correct order in spite of history line management
1698 std::list<TDF_Label>::iterator anAddAfterThis = aFind->second.end();
1699 FeaturePtr anAddedFeature = featureByLab(theLabel);
1700 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1701 while(aLabIter != aFind->second.end()) {
1702 if (theLabel.IsEqual(*aLabIter)) {
1703 std::list<TDF_Label>::iterator aTmpIter = aLabIter;
1705 aFind->second.erase(aTmpIter);
1707 FeaturePtr aCurFeature = featureByLab(*aLabIter);
1708 if (aCurFeature.get() && anAddedFeature.get() &&
1709 myObjs->isLater(anAddedFeature, aCurFeature))
1710 anAddAfterThis = aLabIter;
1715 if (anAddAfterThis != aFind->second.end()) {
1717 if (anAddAfterThis != aFind->second.end()) {
1718 myNamingNames[theName].insert(anAddAfterThis, theLabel); // inserts before anAddAfterThis
1723 myNamingNames[theName].push_back(theLabel);
1726 void Model_Document::changeNamingName(const std::wstring theOldName,
1727 const std::wstring theNewName,
1728 const TDF_Label& theLabel)
1730 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
1731 if (aFind != myNamingNames.end()) {
1732 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1733 for(; aLabIter != aFind->second.end(); aLabIter++) {
1734 if (theLabel.IsEqual(*aLabIter)) { // found the label
1735 myNamingNames[theNewName].push_back(theLabel);
1736 if (aFind->second.size() == 1) { // only one element, so, just change the name
1737 myNamingNames.erase(theOldName);
1738 } else { // remove from the list
1739 aFind->second.erase(aLabIter);
1741 // check the sketch vertex name located under renamed sketch line
1742 TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
1743 for(; aChild.More(); aChild.Next()) {
1744 Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
1745 std::wstring aName = Locale::Convert::toWString(aSubName->Get().ToExtString());
1746 if (aName.find(theOldName) == 0) { // started from parent name
1747 std::wstring aNewSubName = theNewName + aName.substr(theOldName.size());
1748 changeNamingName(aName, aNewSubName, aSubName->Label());
1749 aSubName->Set(aNewSubName.c_str());
1758 // returns true if names consist of the same sub-elements but with different order.
1759 // Sub-elements are separated by "-" symbol. First part must be "Face", second at the same place.
1760 static bool IsExchangedName(const TCollection_ExtendedString& theName1,
1761 const TCollection_ExtendedString& theName2)
1763 static const TCollection_ExtendedString aSepStr("-");
1764 static const Standard_ExtString aSep = aSepStr.ToExtString();
1765 static const TCollection_ExtendedString aWireTail("_wire");
1766 if (theName1.Token(aSep, 1) != "Face" || theName2.Token(aSep, 1) != "Face")
1768 if (theName1.Token(aSep, 2) != theName2.Token(aSep, 2))
1770 // Collect Map of the sub-elements of the first name
1771 NCollection_Map<TCollection_ExtendedString> aSubsMap;
1772 TCollection_ExtendedString aWireSuffix;
1774 for (; true ; a++) {
1775 TCollection_ExtendedString aToken = theName1.Token(aSep, a);
1776 if (aToken.IsEmpty())
1778 int aTailPos = aToken.Search(aWireTail);
1780 aWireSuffix = aToken.Split(aTailPos - 1);
1782 aSubsMap.Add(aToken);
1784 // check all subs in the second name are in the map
1785 for (int a2 = 3; true; a2++) {
1786 TCollection_ExtendedString aToken = theName2.Token(aSep, a2);
1787 if (aToken.IsEmpty()) {
1788 if (a2 != a) // number of sub-elements is not equal
1792 int aTailPos = aToken.Search(aWireTail);
1794 TCollection_ExtendedString aSuffix = aToken.Split(aTailPos - 1);
1795 if (aWireSuffix != aSuffix)
1798 if (!aSubsMap.Contains(aToken))
1804 TDF_Label Model_Document::findNamingName(std::wstring theName, ResultPtr theContext)
1806 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1807 if (aFind != myNamingNames.end()) {
1808 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1809 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1810 if (theContext.get()) {
1811 // context is defined and not like this, so, skip
1812 if (theContext == myObjs->object(aLabIter->Father()))
1816 return *(aFind->second.rbegin()); // no more variants, so, return the last
1818 // not found exact name, try to find by sub-components
1819 std::wstring::size_type aSlash = theName.rfind(L'/');
1820 if (aSlash != std::wstring::npos) {
1821 std::wstring anObjName = theName.substr(0, aSlash);
1822 aFind = myNamingNames.find(anObjName);
1823 if (aFind != myNamingNames.end()) {
1824 TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1825 // iterate all possible same-named labels starting from the last one (the recent)
1826 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1827 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1828 if (theContext.get()) {
1829 // context is defined and not like this, so, skip
1830 if (theContext != myObjs->object(aLabIter->Father()))
1833 // copy aSubName to avoid incorrect further processing after its suffix cutting
1834 TCollection_ExtendedString aSubNameCopy(aSubName);
1835 TDF_Label aFaceLabelWithExchangedSubs; // check also exchanged sub-elements of the name
1836 // searching sub-labels with this name
1837 TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1838 for(; aNamesIter.More(); aNamesIter.Next()) {
1839 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1840 if (aName->Get() == aSubNameCopy)
1841 return aName->Label();
1842 if (aName->Get().Length() == aSubNameCopy.Length() &&
1843 IsExchangedName(aName->Get(), aSubNameCopy))
1844 aFaceLabelWithExchangedSubs = aName->Label();
1846 if (!aFaceLabelWithExchangedSubs.IsNull())
1847 return aFaceLabelWithExchangedSubs;
1848 // If not found child label with the exact sub-name, then try to find compound with
1849 // such sub-name without suffix.
1850 Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
1851 if (aSuffixPos != -1 && aSuffixPos != aSubNameCopy.Length()) {
1852 TCollection_ExtendedString anIndexStr = aSubNameCopy.Split(aSuffixPos);
1853 aSubNameCopy.Remove(aSuffixPos);
1854 aNamesIter.Initialize(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1855 for(; aNamesIter.More(); aNamesIter.Next()) {
1856 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1857 if (aName->Get() == aSubNameCopy) {
1858 return aName->Label();
1861 // check also "this" label
1862 Handle(TDataStd_Name) aName;
1863 if (aLabIter->FindAttribute(TDataStd_Name::GetID(), aName)) {
1864 if (aName->Get() == aSubName) {
1865 return aName->Label();
1870 // verify context's name is same as sub-component's and use context's label
1871 if (aSubName.IsEqual(anObjName.c_str()))
1872 return *(aFind->second.rbegin());
1875 return TDF_Label(); // not found
1878 bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
1879 // check dependencies first: if theOther depends on theThis, theThis is not later
1880 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1881 theOther->data()->referencesToObjects(aRefs);
1882 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
1883 aRefIt = aRefs.begin();
1884 for(; aRefIt != aRefs.end(); aRefIt++) {
1885 std::list<ObjectPtr>::iterator aRefObjIt = aRefIt->second.begin();
1886 for(; aRefObjIt != aRefIt->second.end(); aRefObjIt++) {
1887 ObjectPtr aRefObj = *aRefObjIt;
1888 if (aRefObj.get()) {
1889 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aRefObj);
1890 if (!aRefFeat.get()) { // take feature of the result
1891 aRefFeat = feature(std::dynamic_pointer_cast<ModelAPI_Result>(aRefObj));
1893 if (aRefFeat.get()) {
1894 if (aRefFeat == theThis)
1895 return false; // other references to this, so other later than this
1896 //if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeat)) {
1897 // if (!isLaterByDep(theThis, aRefFeat)) // nested composites: recursion
1904 FeaturePtr aThisOwner = ModelAPI_Tools::compositeOwner(theThis);
1905 if (aThisOwner.get()) {
1906 if (aThisOwner == theOther)
1907 return true; // composite owner is later that its sub
1908 if (!isLaterByDep(aThisOwner, theOther))
1911 return myObjs->isLater(theThis, theOther);
1914 int Model_Document::numberOfNameInHistory(
1915 const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
1917 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind =
1918 myNamingNames.find(theNameObject->data()->name());
1919 if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
1920 return 1; // no need to specify the name by additional identifiers
1922 // get the feature of the object for relative compare
1923 FeaturePtr aStart = myObjs->feature(theStartFrom);
1924 if (!aStart.get()) // strange, but can not find feature by the label
1926 // feature that contain result with this name
1927 FeaturePtr aNameFeature;
1928 ResultPtr aNameResult = std::dynamic_pointer_cast<ModelAPI_Result>(theNameObject);
1930 aNameFeature = myObjs->feature(aNameResult);
1932 aNameFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theNameObject);
1933 // iterate all labels with this name to find the nearest just before or equal relative
1934 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1935 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1936 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1937 if (!aLabFeat.get())
1939 if (isLaterByDep(aStart, aLabFeat)) // skip also start: its result don't used
1943 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1944 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1945 if (!aLabFeat.get())
1947 if (aLabFeat == aNameFeature || isLaterByDep(aNameFeature, aLabFeat))
1951 return aResIndex; // strange
1954 ResultPtr Model_Document::findByName(
1955 std::wstring& theName, std::wstring& theSubShapeName, bool& theUniqueContext)
1957 int aNumInHistory = 0;
1958 std::wstring aName = theName;
1959 ResultPtr aRes = myObjs->findByName(aName);
1960 theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
1961 while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
1963 aName = aName.substr(1);
1964 aRes = myObjs->findByName(aName);
1966 if (aNumInHistory) {
1967 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
1968 if (aFind != myNamingNames.end() && (int)aFind->second.size() > aNumInHistory) {
1969 std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
1970 for(; aNumInHistory != 0; aNumInHistory--)
1972 const TDF_Label& aResultLab = *aLibIt;
1973 aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObjs->object(aResultLab.Father()));
1974 if (aRes) { // modify the incoming names
1975 if (!theSubShapeName.empty())
1976 theSubShapeName = theSubShapeName.substr(theName.size() - aName.size());
1984 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1986 return myObjs->allFeatures();
1989 std::list<std::shared_ptr<ModelAPI_Object> > Model_Document::allObjects()
1991 return myObjs->allObjects();
1994 void Model_Document::setActive(const bool theFlag)
1996 if (theFlag != myIsActive) {
1997 myIsActive = theFlag;
1998 // redisplay all the objects of this part
1999 static Events_Loop* aLoop = Events_Loop::loop();
2000 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2002 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
2003 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
2004 object(ModelAPI_Feature::group(), a));
2005 if (aFeature.get() && aFeature->data()->isValid()) {
2006 std::list<ResultPtr> aResults;
2007 ModelAPI_Tools::allResults(aFeature, aResults);
2008 for (std::list<ResultPtr>::iterator aRes = aResults.begin();
2009 aRes != aResults.end(); aRes++) {
2010 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
2017 bool Model_Document::isActive() const
2022 int Model_Document::transactionID()
2024 Handle(TDataStd_Integer) anIndex;
2025 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
2026 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
2027 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
2029 return anIndex->Get();
2032 void Model_Document::incrementTransactionID()
2034 int aNewVal = transactionID() + 1;
2035 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
2038 TDF_Label Model_Document::extConstructionsLabel() const
2040 return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
2043 bool Model_Document::isOpened()
2045 return myObjs && !myDoc.IsNull();
2048 int Model_Document::numInternalFeatures()
2050 return myObjs->numInternalFeatures();
2053 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
2055 return myObjs->internalFeature(theIndex);
2058 void Model_Document::synchronizeTransactions()
2060 Model_Document* aRoot =
2061 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
2063 return; // don't need to synchronize root with root
2065 std::shared_ptr<Model_Session> aSession =
2066 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
2067 while(myRedos.size() > aRoot->myRedos.size()) { // remove redo in this
2068 aSession->setCheckTransactions(false);
2070 aSession->setCheckTransactions(true);
2072 /* this case can not be reproduced in any known case for the current moment, so, just comment
2073 while(myRedos.size() < aRoot->myRedos.size()) { // add more redo in this
2074 undoInternal(false, true);
2078 /// Feature that is used for selection in the Part document by the external request
2079 class Model_SelectionInPartFeature : public ModelAPI_Feature {
2081 /// Nothing to do in constructor
2082 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
2084 /// Returns the unique kind of a feature
2085 virtual const std::string& getKind() {
2086 static std::string MY_KIND("InternalSelectionInPartFeature");
2089 /// Request for initialization of data model of the object: adding all attributes
2090 virtual void initAttributes() {
2091 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
2093 /// Nothing to do in the execution function
2094 virtual void execute() {}
2098 //! Returns the feature that is used for calculation of selection externally from the document
2099 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
2101 // return already created, otherwise create
2102 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
2104 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
2106 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
2107 std::shared_ptr<Model_Data> aData(new Model_Data);
2108 aData->setLabel(aFeatureLab.FindChild(1));
2109 aData->setObject(mySelectionFeature);
2110 mySelectionFeature->setDoc(myObjs->owner());
2111 mySelectionFeature->setData(aData);
2112 std::wstring aName = id() + L"_Part";
2113 mySelectionFeature->data()->setName(aName);
2114 mySelectionFeature->setDoc(myObjs->owner());
2115 mySelectionFeature->initAttributes();
2116 mySelectionFeature->init(); // to make it enabled and Update correctly
2117 // this update may cause recomputation of the part after selection on it, that is not needed
2118 mySelectionFeature->data()->blockSendAttributeUpdated(true);
2120 return mySelectionFeature->selectionList("selection");
2123 FeaturePtr Model_Document::lastFeature()
2126 return myObjs->lastFeature();
2127 return FeaturePtr();
2130 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
2131 Handle(TNaming_NamedShape) aResult;
2132 while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
2133 TopoDS_Shape aShape = theShape;
2135 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
2136 if (!TNaming_Tool::HasLabel(aMain, aShape))
2138 for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
2139 TDF_Label aNSLab = anIter.Label();
2140 Handle(TNaming_NamedShape) aNS;
2141 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
2142 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2143 if (aShapesIter.Evolution() == TNaming_SELECTED ||
2144 aShapesIter.Evolution() == TNaming_DELETE)
2145 continue; // don't use the selection evolution
2146 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2148 if (aResult->Evolution() == TNaming_MODIFY)
2149 theShape = aShapesIter.OldShape();
2150 // otherwise may me searching for another item of this shape with longer history
2151 if (!theShape.IsNull())
2161 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
2162 std::shared_ptr<ModelAPI_Result> theResult,
2163 const std::shared_ptr<GeomAPI_Shape>& theShape)
2165 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
2167 return feature(theResult); // for not-body just returns the feature that produced this result
2169 // otherwise get the shape and search the very initial label for it
2170 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
2171 if (aShape.IsNull())
2172 return FeaturePtr();
2174 // for compsolids and compounds all the naming is located in the main object, so, try to use
2176 ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theResult);
2177 while (aMain.get()) { // get the top-most main
2178 ResultBodyPtr aNextMain = ModelAPI_Tools::bodyOwner(aMain);
2179 if (aNextMain.get())
2184 FeaturePtr aMainRes = producedByFeature(aMain, theShape);
2189 std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
2190 if (!aBodyData.get() || !aBodyData->isValid())
2191 return FeaturePtr();
2193 TopoDS_Shape anOldShape; // old shape in the pair old shape->theShape in the named shape
2194 TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
2195 Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
2196 TDF_Label aBodyLab = aBodyData->shapeLab();
2197 // use child and this label (the lowest priority)
2198 TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
2199 bool aUseThis = !aNSIter.More();
2200 while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
2201 Handle(TNaming_NamedShape) aNS;
2203 if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
2206 aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
2208 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2209 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
2210 continue; // don't use the selection evolution
2211 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2212 aCandidatInThis = aNS;
2213 if (aCandidatInThis->Evolution() == TNaming_MODIFY)
2214 anOldShape = aShapesIter.OldShape();
2215 // otherwise may me searching for another item of this shape with longer history
2216 if (!anOldShape.IsNull())
2219 // check that the shape contains aShape as sub-shape to fill container
2220 if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
2221 TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
2222 for(; anExp.More(); anExp.Next()) {
2223 if (aShape.IsSame(anExp.Current())) {
2224 aCandidatContainer = aNS;
2225 aShapeContainer = aShapesIter.NewShape();
2230 // iterate to the next label or to the body label in the end
2233 if (!aNSIter.More()) {
2239 if (aCandidatInThis.IsNull()) {
2240 // to fix 1512: searching for original shape of this shape
2241 // if modification of it is not in this result
2242 aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
2243 if (aCandidatInThis.IsNull()) {
2244 if (aCandidatContainer.IsNull())
2245 return FeaturePtr();
2246 // with the lower priority use the higher level shape that contains aShape
2247 aCandidatInThis = aCandidatContainer;
2248 anOldShape = aShapeContainer;
2250 // to stop the searching by the following searchForOriginalShape
2251 anOldShape.Nullify();
2255 Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
2257 aCandidatInThis = aNS;
2260 TDF_Label aResultLab = aCandidatInThis->Label();
2261 while(aResultLab.Depth() > 3)
2262 aResultLab = aResultLab.Father();
2263 FeaturePtr aFeature = myObjs->feature(aResultLab);
2264 if (aFeature.get()) {
2265 if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
2272 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2274 return myObjs->isLater(theLater, theCurrent);
2277 // Object Browser nodes states
2279 void Model_Document::storeNodesState(const std::list<bool>& theStates)
2281 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2282 aLab.ForgetAllAttributes();
2283 if (!theStates.empty()) {
2284 Handle(TDataStd_BooleanArray) anArray =
2285 TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
2286 std::list<bool>::const_iterator aState = theStates.begin();
2287 for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
2288 anArray->SetValue(anIndex, *aState);
2293 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
2295 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2296 Handle(TDataStd_BooleanArray) anArray;
2297 if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
2298 int anUpper = anArray->Upper();
2299 for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
2300 theStates.push_back(anArray->Value(anIndex) == Standard_True);
2306 void Model_Document::eraseAllFeatures()
2309 myObjs->eraseAllFeatures();
2312 std::shared_ptr<ModelAPI_Feature> Model_Document::nextFeature(
2313 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse) const
2315 if (theCurrent.get() && myObjs) {
2316 int anIndex = kUNDEFINED_FEATURE_INDEX;
2317 return myObjs->nextFeature(theCurrent, anIndex, theReverse);
2319 return FeaturePtr(); // nothing by default
2322 void Model_Document::setExecuteFeatures(const bool theFlag)
2324 myExecuteFeatures = theFlag;
2325 const std::set<int> aSubs = subDocuments();
2326 std::set<int>::iterator aSubIter = aSubs.begin();
2327 for (; aSubIter != aSubs.end(); aSubIter++) {
2328 if (!subDoc(*aSubIter)->myObjs)
2330 subDoc(*aSubIter)->setExecuteFeatures(theFlag);
2334 void Model_Document::appendTransactionToPrevious()
2336 Transaction anAppended = myTransactions.back();
2337 myTransactions.pop_back();
2338 if (!myNestedNum.empty())
2339 (*myNestedNum.rbegin())--;
2340 if (!myTransactions.empty()) { // if it is empty, just forget the appended
2341 myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
2343 // propagate the same action to sub-documents
2344 const std::set<int> aSubs = subDocuments();
2345 for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
2346 subDoc(*aSubIter)->appendTransactionToPrevious();
2350 /// GUID for keeping information about the auto-recomputation state
2351 static const Standard_GUID kAutoRecomputationID("8493fb74-0674-4912-a100-1cf46c7cfab3");
2353 void Model_Document::setAutoRecomutationState(const bool theState)
2356 generalLabel().FindChild(TAG_CURRENT_TRANSACTION).ForgetAttribute(kAutoRecomputationID);
2358 TDataStd_UAttribute::Set(
2359 generalLabel().FindChild(TAG_CURRENT_TRANSACTION), kAutoRecomputationID);
2362 bool Model_Document::autoRecomutationState() const
2364 return !generalLabel().FindChild(TAG_CURRENT_TRANSACTION).IsAttribute(kAutoRecomputationID);