1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_Document.cxx
4 // Created: 28 Feb 2014
5 // Author: Mikhail PONIKAROV
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Objects.h>
10 #include <Model_Application.h>
11 #include <Model_Session.h>
12 #include <Model_Events.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_Validator.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_AttributeSelectionList.h>
17 #include <ModelAPI_Tools.h>
19 #include <Events_Loop.h>
20 #include <Events_Error.h>
22 #include <TDataStd_Integer.hxx>
23 #include <TDataStd_Comment.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDataStd_ReferenceArray.hxx>
26 #include <TDataStd_HLabelArray1.hxx>
27 #include <TDataStd_Name.hxx>
28 #include <TDF_Reference.hxx>
29 #include <TDF_ChildIDIterator.hxx>
30 #include <TDF_LabelMapHasher.hxx>
31 #include <TDF_Delta.hxx>
32 #include <OSD_File.hxx>
33 #include <OSD_Path.hxx>
34 #include <TDF_AttributeDelta.hxx>
35 #include <TDF_AttributeDeltaList.hxx>
36 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
44 # define _separator_ '\\'
46 # define _separator_ '/'
49 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
51 static const int TAG_GENERAL = 1; // general properties tag
54 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
55 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
56 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
58 Model_Document::Model_Document(const std::string theID, const std::string theKind)
59 : myID(theID), myKind(theKind), myIsActive(false),
60 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
62 myObjs = new Model_Objects(myDoc->Main());
63 myDoc->SetUndoLimit(UNDO_LIMIT);
64 myTransactionSave = 0;
65 myExecuteFeatures = true;
66 // to have something in the document and avoid empty doc open/save problem
67 // in transaction for nesting correct working
69 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
70 myDoc->CommitCommand();
73 void Model_Document::setThis(DocumentPtr theDoc)
75 myObjs->setOwner(theDoc);
78 /// Returns the file name of this document by the nameof directory and identifuer of a document
79 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
81 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
82 // remove end-separators
83 while(aPath.Length() &&
84 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
85 aPath.Remove(aPath.Length());
87 aPath += theID.c_str();
88 aPath += ".cbf"; // standard binary file extension
92 bool Model_Document::isRoot() const
94 return this == Model_Session::get()->moduleDocument().get();
97 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
99 Handle(Model_Application) anApp = Model_Application::getApplication();
101 anApp->setLoadPath(theFileName);
103 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
104 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
106 aStatus = anApp->Open(aPath, myDoc);
107 } catch (Standard_Failure) {
108 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
110 std::string("Exception in opening of document: ") + aFail->GetMessageString());
113 bool isError = aStatus != PCDM_RS_OK;
116 case PCDM_RS_UnknownDocument:
117 Events_Error::send(std::string("Can not open document"));
119 case PCDM_RS_AlreadyRetrieved:
120 Events_Error::send(std::string("Can not open document: already opened"));
122 case PCDM_RS_AlreadyRetrievedAndModified:
124 std::string("Can not open document: already opened and modified"));
126 case PCDM_RS_NoDriver:
127 Events_Error::send(std::string("Can not open document: driver library is not found"));
129 case PCDM_RS_UnknownFileDriver:
130 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
132 case PCDM_RS_OpenError:
133 Events_Error::send(std::string("Can not open document: file open error"));
135 case PCDM_RS_NoVersion:
136 Events_Error::send(std::string("Can not open document: invalid version"));
138 case PCDM_RS_NoModel:
139 Events_Error::send(std::string("Can not open document: no data model"));
141 case PCDM_RS_NoDocument:
142 Events_Error::send(std::string("Can not open document: no document inside"));
144 case PCDM_RS_FormatFailure:
145 Events_Error::send(std::string("Can not open document: format failure"));
147 case PCDM_RS_TypeNotFoundInSchema:
148 Events_Error::send(std::string("Can not open document: invalid object"));
150 case PCDM_RS_UnrecognizedFileFormat:
151 Events_Error::send(std::string("Can not open document: unrecognized file format"));
153 case PCDM_RS_MakeFailure:
154 Events_Error::send(std::string("Can not open document: make failure"));
156 case PCDM_RS_PermissionDenied:
157 Events_Error::send(std::string("Can not open document: permission denied"));
159 case PCDM_RS_DriverFailure:
160 Events_Error::send(std::string("Can not open document: driver failure"));
163 Events_Error::send(std::string("Can not open document: unknown error"));
168 myDoc->SetUndoLimit(UNDO_LIMIT);
169 // to avoid the problem that feature is created in the current, not this, document
170 std::shared_ptr<Model_Session> aSession =
171 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
172 aSession->setActiveDocument(anApp->getDocument(myID), false);
173 aSession->setCheckTransactions(false);
176 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
177 myObjs->setOwner(theThis);
178 // update the current features status
179 setCurrentFeature(currentFeature(false), false);
180 aSession->setCheckTransactions(true);
181 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
182 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
183 // aSession->setActiveDocument(anApp->getDocument(myID), true);
188 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
190 // create a directory in the root document if it is not yet exist
191 Handle(Model_Application) anApp = Model_Application::getApplication();
194 CreateDirectory(theFileName, NULL);
196 mkdir(theFileName, 0x1ff);
199 // filename in the dir is id of document inside of the given directory
200 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
201 PCDM_StoreStatus aStatus;
203 aStatus = anApp->SaveAs(myDoc, aPath);
204 } catch (Standard_Failure) {
205 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
207 std::string("Exception in saving of document: ") + aFail->GetMessageString());
210 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
213 case PCDM_SS_DriverFailure:
214 Events_Error::send(std::string("Can not save document: save driver-library failure"));
216 case PCDM_SS_WriteFailure:
217 Events_Error::send(std::string("Can not save document: file writing failure"));
219 case PCDM_SS_Failure:
221 Events_Error::send(std::string("Can not save document"));
225 myTransactionSave = myTransactions.size();
226 if (isDone) { // save also sub-documents if any
227 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
228 const std::set<std::string> aSubs = subDocuments(false);
229 std::set<std::string>::iterator aSubIter = aSubs.begin();
230 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
231 if (anApp->isLoadByDemand(*aSubIter)) {
232 // copy not-activated document that is not in the memory
233 std::string aDocName = *aSubIter;
234 if (!aDocName.empty()) {
236 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
237 OSD_Path aPath(aSubPath);
238 OSD_File aFile(aPath);
239 if (aFile.Exists()) {
240 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
241 OSD_Path aDestination(aDestinationDir);
242 aFile.Copy(aDestination);
243 theResults.push_back(aDestinationDir.ToCString());
246 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
249 } else { // simply save opened document
250 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
257 void Model_Document::close(const bool theForever)
259 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
260 if (!isRoot() && this == aPM->activeDocument().get()) {
261 aPM->setActiveDocument(aPM->moduleDocument());
262 } else if (isRoot()) {
263 // erase the active document if root is closed
264 aPM->setActiveDocument(DocumentPtr());
267 const std::set<std::string> aSubs = subDocuments(true);
268 std::set<std::string>::iterator aSubIter = aSubs.begin();
269 for (; aSubIter != aSubs.end(); aSubIter++) {
270 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
271 if (aSub->myObjs) // if it was not closed before
272 aSub->close(theForever);
275 // close for thid document needs no transaction in this document
276 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
278 // close all only if it is really asked, otherwise it can be undoed/redoed
282 if (myDoc->CanClose() == CDM_CCS_OK)
284 mySelectionFeature.reset();
286 setCurrentFeature(FeaturePtr(), false); // disables all features
289 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
292 void Model_Document::startOperation()
294 if (myDoc->HasOpenCommand()) { // start of nested command
295 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
296 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
298 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
299 myDoc->OpenCommand();
300 } else { // start the simple command
303 // starts a new operation
304 incrementTransactionID();
305 myTransactions.push_back(Transaction());
306 if (!myNestedNum.empty())
307 (*myNestedNum.rbegin())++;
309 // new command for all subs
310 const std::set<std::string> aSubs = subDocuments(true);
311 std::set<std::string>::iterator aSubIter = aSubs.begin();
312 for (; aSubIter != aSubs.end(); aSubIter++)
313 subDoc(*aSubIter)->startOperation();
316 void Model_Document::compactNested()
318 if (!myNestedNum.empty()) {
319 int aNumToCompact = *(myNestedNum.rbegin());
320 int aSumOfTransaction = 0;
321 for(int a = 0; a < aNumToCompact; a++) {
322 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
323 myTransactions.pop_back();
325 // the latest transaction is the start of lower-level operation which startes the nested
326 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
327 myNestedNum.pop_back();
331 bool Model_Document::finishOperation()
333 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
334 static std::shared_ptr<Model_Session> aSession =
335 std::static_pointer_cast<Model_Session>(Model_Session::get());
336 myObjs->synchronizeBackRefs();
337 Events_Loop* aLoop = Events_Loop::loop();
338 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
339 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
340 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
341 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
342 // this must be here just after everything is finished but before real transaction stop
343 // to avoid messages about modifications outside of the transaction
344 // and to rebuild everything after all updates and creates
345 if (isRoot()) { // once for root document
346 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
347 static std::shared_ptr<Events_Message> aFinishMsg
348 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
349 Events_Loop::loop()->send(aFinishMsg);
350 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
352 // to avoid "updated" message appearance by updater
353 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
355 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
356 bool aResult = false;
357 const std::set<std::string> aSubs = subDocuments(true);
358 std::set<std::string>::iterator aSubIter = aSubs.begin();
359 for (; aSubIter != aSubs.end(); aSubIter++)
360 if (subDoc(*aSubIter)->finishOperation())
363 // transaction may be empty if this document was created during this transaction (create part)
364 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
365 myTransactions.rbegin()->myOCAFNum++;
369 if (isNestedClosed) {
372 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
373 aResult = myTransactions.rbegin()->myOCAFNum != 0;
375 if (!aResult && isRoot()) {
376 // nothing inside in all documents, so remove this transaction from the transactions list
377 undoInternal(true, false);
379 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
382 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
383 subDoc(*aSubIter)->myDoc->ClearRedos();
384 subDoc(*aSubIter)->myRedos.clear();
390 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
391 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
392 const bool isRedo = false) {
393 Handle(TDF_Delta) aDelta;
395 aDelta = theDoc->GetRedos().First();
397 aDelta = theDoc->GetUndos().Last();
398 aDelta->Labels(theDelta);
399 // add also label of the modified attributes
400 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
401 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
402 theDelta.Append(anAttr.Value()->Label());
406 void Model_Document::abortOperation()
408 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
409 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
411 // store undo-delta here as undo actually does in the method later
412 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
413 for(a = 0; a < aNumTransactions; a++) {
414 modifiedLabels(myDoc, aDeltaLabels);
417 for(a = 0; a < aNumTransactions; a++) {
421 undoInternal(false, false);
424 } else { // abort the current
425 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
426 myTransactions.pop_back();
427 if (!myNestedNum.empty())
428 (*myNestedNum.rbegin())--;
429 // roll back the needed number of transactions
430 // make commit/undo to get the modification delta
431 //myDoc->AbortCommand();
432 if (myDoc->CommitCommand()) {
433 modifiedLabels(myDoc, aDeltaLabels);
436 for(int a = 0; a < aNumTransactions; a++) {
437 modifiedLabels(myDoc, aDeltaLabels);
442 // abort for all subs, flushes will be later, in the end of root abort
443 const std::set<std::string> aSubs = subDocuments(true);
444 std::set<std::string>::iterator aSubIter = aSubs.begin();
445 for (; aSubIter != aSubs.end(); aSubIter++)
446 subDoc(*aSubIter)->abortOperation();
447 // references may be changed because they are set in attributes on the fly
448 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
451 bool Model_Document::isOperation() const
453 // operation is opened for all documents: no need to check subs
454 return myDoc->HasOpenCommand() == Standard_True ;
457 bool Model_Document::isModified()
459 // is modified if at least one operation was commited and not undoed
460 return myTransactions.size() != myTransactionSave || isOperation();
463 bool Model_Document::canUndo()
465 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
466 int aCurrentNum = isOperation() ? 1 : 0;
467 if (myDoc->GetAvailableUndos() > 0 &&
468 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
469 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
471 // check other subs contains operation that can be undoed
472 const std::set<std::string> aSubs = subDocuments(true);
473 std::set<std::string>::iterator aSubIter = aSubs.begin();
474 for (; aSubIter != aSubs.end(); aSubIter++) {
475 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
476 if (aSub->myObjs) {// if it was not closed before
485 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
487 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
488 myRedos.push_back(*myTransactions.rbegin());
489 myTransactions.pop_back();
490 if (!myNestedNum.empty())
491 (*myNestedNum.rbegin())--;
492 // roll back the needed number of transactions
493 TDF_LabelList aDeltaLabels;
494 for(int a = 0; a < aNumTransactions; a++) {
496 modifiedLabels(myDoc, aDeltaLabels);
502 const std::set<std::string> aSubs = subDocuments(true);
503 std::set<std::string>::iterator aSubIter = aSubs.begin();
504 for (; aSubIter != aSubs.end(); aSubIter++) {
505 if (!subDoc(*aSubIter)->myObjs)
507 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
510 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
511 if (theSynchronize) {
512 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
513 // update the current features status
514 setCurrentFeature(currentFeature(false), false);
518 void Model_Document::undo()
520 undoInternal(true, true);
523 bool Model_Document::canRedo()
525 if (!myRedos.empty())
527 // check other subs contains operation that can be redoed
528 const std::set<std::string> aSubs = subDocuments(true);
529 std::set<std::string>::iterator aSubIter = aSubs.begin();
530 for (; aSubIter != aSubs.end(); aSubIter++) {
531 if (!subDoc(*aSubIter)->myObjs)
533 if (subDoc(*aSubIter)->canRedo())
539 void Model_Document::redo()
541 if (!myNestedNum.empty())
542 (*myNestedNum.rbegin())++;
543 int aNumRedos = myRedos.rbegin()->myOCAFNum;
544 myTransactions.push_back(*myRedos.rbegin());
546 TDF_LabelList aDeltaLabels;
547 for(int a = 0; a < aNumRedos; a++) {
548 modifiedLabels(myDoc, aDeltaLabels, true);
553 const std::set<std::string> aSubs = subDocuments(true);
554 std::set<std::string>::iterator aSubIter = aSubs.begin();
555 for (; aSubIter != aSubs.end(); aSubIter++)
556 subDoc(*aSubIter)->redo();
558 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
559 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
560 // update the current features status
561 setCurrentFeature(currentFeature(false), false);
564 std::list<std::string> Model_Document::undoList() const
566 std::list<std::string> aResult;
567 // the number of skipped current operations (on undo they will be aborted)
568 int aSkipCurrent = isOperation() ? 1 : 0;
569 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
570 int aNumUndo = myTransactions.size();
571 if (!myNestedNum.empty())
572 aNumUndo = *myNestedNum.rbegin();
573 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
574 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
580 std::list<std::string> Model_Document::redoList() const
582 std::list<std::string> aResult;
583 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
584 for( ; aTrIter != myRedos.crend(); aTrIter++) {
585 aResult.push_back(aTrIter->myId);
590 void Model_Document::operationId(const std::string& theId)
592 myTransactions.rbegin()->myId = theId;
595 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
597 std::shared_ptr<Model_Session> aSession =
598 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
599 FeaturePtr aFeature = aSession->createFeature(theID, this);
602 Model_Document* aDocToAdd;
603 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
604 if (aFeature->documentToAdd() != kind()) { // the root document by default
605 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
609 } else { // if customized is not presented, add to "this" document
613 aDocToAdd->myObjs->addFeature(aFeature, aDocToAdd->currentFeature(false));
614 if (!aFeature->isAction()) { // do not add action to the data model
615 if (theMakeCurrent) // after all this feature stays in the document, so make it current
616 aDocToAdd->setCurrentFeature(aFeature, false);
617 } else { // feature must be executed
618 // no creation event => updater not working, problem with remove part
626 void Model_Document::refsToFeature(FeaturePtr theFeature,
627 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
629 myObjs->refsToFeature(theFeature, theRefs, isSendError);
632 void Model_Document::removeFeature(FeaturePtr theFeature)
634 myObjs->removeFeature(theFeature);
637 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
639 myObjs->moveFeature(theMoved, theAfterThis);
642 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
644 myObjs->updateHistory(theObject);
647 void Model_Document::updateHistory(const std::string theGroup)
649 myObjs->updateHistory(theGroup);
652 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
654 return Model_Application::getApplication()->getDocument(theDocID);
657 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
659 std::set<std::string> aResult;
660 std::list<ResultPtr> aPartResults;
661 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
662 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
663 for(; aPartRes != aPartResults.end(); aPartRes++) {
664 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
665 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
666 aResult.insert(aPart->original()->data()->name());
672 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
674 // just store sub-document identifier here to manage it later
675 return std::dynamic_pointer_cast<Model_Document>(
676 Model_Application::getApplication()->getDocument(theDocID));
679 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
681 return myObjs->object(theGroupID, theIndex);
684 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
685 const std::string& theGroupID, const std::string& theName)
687 return myObjs->objectByName(theGroupID, theName);
690 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
692 return myObjs->index(theObject);
695 int Model_Document::size(const std::string& theGroupID)
697 return myObjs->size(theGroupID);
700 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
702 if (!myObjs) // on close document feature destruction it may call this method
703 return std::shared_ptr<ModelAPI_Feature>();
704 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
705 Handle(TDF_Reference) aRef;
706 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
707 TDF_Label aLab = aRef->Get();
708 FeaturePtr aResult = myObjs->feature(aLab);
709 if (theVisible) { // get nearest visible (in history) going up
710 while(aResult.get() && // sub-composites are never in history
711 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
712 aResult = myObjs->nextFeature(aResult, true);
717 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
720 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
721 const bool theVisible)
723 // blocks the flush signals to avoid each objects visualization in the viewer
724 // they should not be shown once after all modifications are performed
725 Events_Loop* aLoop = Events_Loop::loop();
726 bool isActive = aLoop->activateFlushes(false);
728 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
729 CompositeFeaturePtr aMain; // main feature that may nest the new current
730 if (theCurrent.get()) {
731 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
733 // if feature nests into compisite feature, make the composite feature as current
734 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
735 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
736 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
737 CompositeFeaturePtr aComposite =
738 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
739 if (aComposite.get() && aComposite->isSub(theCurrent)) {
747 if (theVisible) { // make features below which are not in history also enabled: sketch subs
749 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
750 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
751 if (aNext->isInHistory()) {
752 break; // next in history is not needed
753 } else { // next not in history is good for making current
758 if (theCurrent.get()) {
759 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
760 if (!aData.get() || !aData->isValid()) {
761 aLoop->activateFlushes(isActive);
764 TDF_Label aFeatureLabel = aData->label().Father();
766 Handle(TDF_Reference) aRef;
767 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
768 aRef->Set(aFeatureLabel);
770 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
772 } else { // remove reference for the null feature
773 aRefLab.ForgetAttribute(TDF_Reference::GetID());
775 // make all features after this feature disabled in reversed order (to remove results without deps)
776 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
777 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
778 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
780 bool aPassed = false; // flag that the current object is already passed in cycle
781 FeaturePtr anIter = myObjs->lastFeature();
782 bool aWasChanged = false;
783 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
784 // check this before passed become enabled: the current feature is enabled!
785 if (anIter == theCurrent) aPassed = true;
787 bool aDisabledFlag = !aPassed;
788 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
789 aDisabledFlag = false;
790 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
791 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
792 aDisabledFlag = false;
794 if (anIter->setDisabled(aDisabledFlag)) {
795 // state of feature is changed => so feature become updated
796 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
797 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
798 // flush is in the end of this method
799 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
802 // update for everyone the concealment flag immideately: on edit feature in the midle of history
804 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
805 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
806 for(; aRes != aResList.end(); aRes++) {
807 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
808 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
813 // unblock the flush signals and up them after this
814 aLoop->activateFlushes(isActive);
816 aLoop->flush(aCreateEvent);
817 aLoop->flush(aRedispEvent);
818 aLoop->flush(aDeleteEvent);
821 void Model_Document::setCurrentFeatureUp()
823 // on remove just go up for minimum step: highlight external objects in sketch causes
824 // problems if it is true: here and in "setCurrentFeature"
825 FeaturePtr aCurrent = currentFeature(false);
826 if (aCurrent.get()) { // if not, do nothing because null is the upper
827 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
828 setCurrentFeature(aPrev, false);
832 TDF_Label Model_Document::generalLabel() const
834 return myDoc->Main().FindChild(TAG_GENERAL);
837 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
838 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
840 return myObjs->createConstruction(theFeatureData, theIndex);
843 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
844 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
846 return myObjs->createBody(theFeatureData, theIndex);
849 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
850 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
852 return myObjs->createPart(theFeatureData, theIndex);
855 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
856 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
857 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
859 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
862 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
863 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
865 return myObjs->createGroup(theFeatureData, theIndex);
868 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
869 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
871 return myObjs->createParameter(theFeatureData, theIndex);
874 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
875 const std::shared_ptr<ModelAPI_Result>& theResult)
877 return myObjs->feature(theResult);
880 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
882 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
885 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
887 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
890 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
892 myNamingNames[theName] = theLabel;
895 TDF_Label Model_Document::findNamingName(std::string theName)
897 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
898 if (aFind == myNamingNames.end())
899 return TDF_Label(); // not found
900 return aFind->second;
903 ResultPtr Model_Document::findByName(const std::string theName)
905 return myObjs->findByName(theName);
908 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
910 return myObjs->allFeatures();
913 void Model_Document::setActive(const bool theFlag)
915 if (theFlag != myIsActive) {
916 myIsActive = theFlag;
917 // redisplay all the objects of this part
918 static Events_Loop* aLoop = Events_Loop::loop();
919 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
921 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
922 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
923 object(ModelAPI_Feature::group(), a));
924 if (aFeature.get() && aFeature->data()->isValid()) {
925 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
926 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
927 for(; aRes != aResList.end(); aRes++) {
928 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
935 bool Model_Document::isActive() const
940 int Model_Document::transactionID()
942 Handle(TDataStd_Integer) anIndex;
943 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
944 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
945 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
947 return anIndex->Get();
950 void Model_Document::incrementTransactionID()
952 int aNewVal = transactionID() + 1;
953 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
955 void Model_Document::decrementTransactionID()
957 int aNewVal = transactionID() - 1;
958 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
961 bool Model_Document::isOpened()
963 return myObjs && !myDoc.IsNull();
966 int Model_Document::numInternalFeatures()
968 return myObjs->numInternalFeatures();
971 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
973 return myObjs->internalFeature(theIndex);
976 // Feature that is used for selection in the Part document by the external request
977 class Model_SelectionInPartFeature : public ModelAPI_Feature {
979 /// Nothing to do in constructor
980 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
982 /// Returns the unique kind of a feature
983 virtual const std::string& getKind() {
984 static std::string MY_KIND("InternalSelectionInPartFeature");
987 /// Request for initialization of data model of the object: adding all attributes
988 virtual void initAttributes() {
989 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
991 /// Nothing to do in the execution function
992 virtual void execute() {}
996 //! Returns the feature that is used for calculation of selection externally from the document
997 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
999 // return already created, otherwise create
1000 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1002 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1004 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1005 std::shared_ptr<Model_Data> aData(new Model_Data);
1006 aData->setLabel(aFeatureLab.FindChild(1));
1007 aData->setObject(mySelectionFeature);
1008 mySelectionFeature->setDoc(myObjs->owner());
1009 mySelectionFeature->setData(aData);
1010 std::string aName = id() + "_Part";
1011 mySelectionFeature->data()->setName(aName);
1012 mySelectionFeature->setDoc(myObjs->owner());
1013 mySelectionFeature->initAttributes();
1015 return mySelectionFeature->selectionList("selection");
1018 FeaturePtr Model_Document::lastFeature()
1021 return myObjs->lastFeature();
1022 return FeaturePtr();