Salome HOME
Speed up the redraw of sketch with constraints moved by the point of the line
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // File:        Model_Document.cxx
2 // Created:     28 Feb 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include <Model_Document.h>
6 #include <Model_Data.h>
7 #include <Model_Application.h>
8 #include <Model_Session.h>
9 #include <Model_Events.h>
10 #include <Model_ResultPart.h>
11 #include <Model_ResultConstruction.h>
12 #include <Model_ResultBody.h>
13 #include <Model_ResultGroup.h>
14 #include <ModelAPI_Validator.h>
15 #include <Events_Loop.h>
16 #include <Events_Error.h>
17
18 #include <TDataStd_Integer.hxx>
19 #include <TDataStd_Comment.hxx>
20 #include <TDF_ChildIDIterator.hxx>
21 #include <TDataStd_ReferenceArray.hxx>
22 #include <TDataStd_HLabelArray1.hxx>
23 #include <TDataStd_Name.hxx>
24 #include <TDF_Reference.hxx>
25 #include <TDF_ChildIDIterator.hxx>
26 #include <TDF_LabelMapHasher.hxx>
27
28 #include <climits>
29 #ifndef WIN32
30 #include <sys/stat.h>
31 #endif
32
33 #ifdef WIN32
34 # define _separator_ '\\'
35 #else
36 # define _separator_ '/'
37 #endif
38
39 static const int UNDO_LIMIT = 10;  // number of possible undo operations
40
41 static const int TAG_GENERAL = 1;  // general properties tag
42 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
43 static const int TAG_HISTORY = 3;  // tag of the history sub-tree (python dump)
44
45 // feature sub-labels
46 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
47 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
48
49 Model_Document::Model_Document(const std::string theID, const std::string theKind)
50     : myID(theID), myKind(theKind),
51       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
52 {
53   myDoc->SetUndoLimit(UNDO_LIMIT);  
54   myTransactionsCounter = 0;
55   myTransactionSave = 0;
56   myNestedNum = -1;
57   myExecuteFeatures = true;
58   // to have something in the document and avoid empty doc open/save problem
59   // in transaction for nesting correct working
60   myDoc->NewCommand();
61   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
62   myDoc->CommitCommand();
63 }
64
65 /// Returns the file name of this document by the nameof directory and identifuer of a document
66 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
67 {
68   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
69   // remove end-separators
70   while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
71     aPath.Remove(aPath.Length());
72   aPath += _separator_;
73   aPath += theID.c_str();
74   aPath += ".cbf";  // standard binary file extension
75   return aPath;
76 }
77
78 bool Model_Document::load(const char* theFileName)
79 {
80   Handle(Model_Application) anApp = Model_Application::getApplication();
81   if (this == Model_Session::get()->moduleDocument().get()) {
82     anApp->setLoadPath(theFileName);
83   }
84   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
85   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
86   try {
87     aStatus = anApp->Open(aPath, myDoc);
88   } catch (Standard_Failure) {
89     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
90     Events_Error::send(
91         std::string("Exception in opening of document: ") + aFail->GetMessageString());
92     return false;
93   }
94   bool isError = aStatus != PCDM_RS_OK;
95   if (isError) {
96     switch (aStatus) {
97       case PCDM_RS_UnknownDocument:
98         Events_Error::send(std::string("Can not open document: unknown format"));
99         break;
100       case PCDM_RS_AlreadyRetrieved:
101         Events_Error::send(std::string("Can not open document: already opened"));
102         break;
103       case PCDM_RS_AlreadyRetrievedAndModified:
104         Events_Error::send(
105             std::string("Can not open document: already opened and modified"));
106         break;
107       case PCDM_RS_NoDriver:
108         Events_Error::send(std::string("Can not open document: driver library is not found"));
109         break;
110       case PCDM_RS_UnknownFileDriver:
111         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
112         break;
113       case PCDM_RS_OpenError:
114         Events_Error::send(std::string("Can not open document: file open error"));
115         break;
116       case PCDM_RS_NoVersion:
117         Events_Error::send(std::string("Can not open document: invalid version"));
118         break;
119       case PCDM_RS_NoModel:
120         Events_Error::send(std::string("Can not open document: no data model"));
121         break;
122       case PCDM_RS_NoDocument:
123         Events_Error::send(std::string("Can not open document: no document inside"));
124         break;
125       case PCDM_RS_FormatFailure:
126         Events_Error::send(std::string("Can not open document: format failure"));
127         break;
128       case PCDM_RS_TypeNotFoundInSchema:
129         Events_Error::send(std::string("Can not open document: invalid object"));
130         break;
131       case PCDM_RS_UnrecognizedFileFormat:
132         Events_Error::send(std::string("Can not open document: unrecognized file format"));
133         break;
134       case PCDM_RS_MakeFailure:
135         Events_Error::send(std::string("Can not open document: make failure"));
136         break;
137       case PCDM_RS_PermissionDenied:
138         Events_Error::send(std::string("Can not open document: permission denied"));
139         break;
140       case PCDM_RS_DriverFailure:
141         Events_Error::send(std::string("Can not open document: driver failure"));
142         break;
143       default:
144         Events_Error::send(std::string("Can not open document: unknown error"));
145         break;
146     }
147   }
148   if (!isError) {
149     myDoc->SetUndoLimit(UNDO_LIMIT);
150     // to avoid the problem that feature is created in the current, not this, document
151     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
152     synchronizeFeatures(false, true);
153     Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
154     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
155   }
156   return !isError;
157 }
158
159 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
160 {
161   // create a directory in the root document if it is not yet exist
162   if (this == Model_Session::get()->moduleDocument().get()) {
163 #ifdef WIN32
164     CreateDirectory(theFileName, NULL);
165 #else
166     mkdir(theFileName, 0x1ff);
167 #endif
168   }
169   // filename in the dir is id of document inside of the given directory
170   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
171   PCDM_StoreStatus aStatus;
172   try {
173     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
174   } catch (Standard_Failure) {
175     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
176     Events_Error::send(
177         std::string("Exception in saving of document: ") + aFail->GetMessageString());
178     return false;
179   }
180   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
181   if (!isDone) {
182     switch (aStatus) {
183       case PCDM_SS_DriverFailure:
184         Events_Error::send(std::string("Can not save document: save driver-library failure"));
185         break;
186       case PCDM_SS_WriteFailure:
187         Events_Error::send(std::string("Can not save document: file writing failure"));
188         break;
189       case PCDM_SS_Failure:
190       default:
191         Events_Error::send(std::string("Can not save document"));
192         break;
193     }
194   }
195   myTransactionSave = myTransactionsCounter;
196   if (isDone) {  // save also sub-documents if any
197     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
198     std::set<std::string>::iterator aSubIter = mySubs.begin();
199     for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
200       isDone = subDoc(*aSubIter)->save(theFileName, theResults);
201     }
202   }
203   return isDone;
204 }
205
206 void Model_Document::close(const bool theForever)
207 {
208   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
209   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
210     aPM->setActiveDocument(aPM->moduleDocument());
211   }
212   // close all subs
213   std::set<std::string>::iterator aSubIter = mySubs.begin();
214   for (; aSubIter != mySubs.end(); aSubIter++)
215     subDoc(*aSubIter)->close(theForever);
216   mySubs.clear();
217
218   // close for thid document needs no transaction in this document
219   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
220
221   // delete all features of this document
222   std::shared_ptr<ModelAPI_Document> aThis = 
223     Model_Application::getApplication()->getDocument(myID);
224   Events_Loop* aLoop = Events_Loop::loop();
225   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
226   for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
227     FeaturePtr aFeature = aFeaturesIter.Value();
228     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
229     ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
230     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
231     aFeature->eraseResults();
232     aFeature->erase();
233   }
234   myObjs.Clear();
235   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
236   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
237
238   // close all only if it is really asked, otherwise it can be undoed/redoed
239   if (theForever) {
240     if (myDoc->CanClose() == CDM_CCS_OK)
241       myDoc->Close();
242   }
243
244   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
245 }
246
247 void Model_Document::startOperation()
248 {
249   if (myDoc->HasOpenCommand()) {  // start of nested command
250     if (myNestedNum == -1) {
251       myNestedNum = 0;
252       myDoc->InitDeltaCompaction();
253     }
254     myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();
255     myTransactionsCounter++;
256     myDoc->OpenCommand();
257   } else {  // start the simple command
258     myDoc->NewCommand();
259   }
260   // new command for all subs
261   std::set<std::string>::iterator aSubIter = mySubs.begin();
262   for (; aSubIter != mySubs.end(); aSubIter++)
263     subDoc(*aSubIter)->startOperation();
264 }
265
266 bool Model_Document::compactNested()
267 {
268   bool allWasEmpty = true;
269   while (myNestedNum != -1) {
270     myTransactionsCounter--;
271     if (!myIsEmptyTr[myTransactionsCounter]) {
272       allWasEmpty = false;
273     }
274     myIsEmptyTr.erase(myTransactionsCounter);
275     myNestedNum--;
276   }
277   myIsEmptyTr[myTransactionsCounter] = allWasEmpty;
278   myTransactionsCounter++;
279   if (allWasEmpty) {
280     // Issue 151: if everything is empty, it is a problem for OCCT to work with it, 
281     // just commit the empty that returns nothing
282     myDoc->CommitCommand();
283   } else {
284     myDoc->PerformDeltaCompaction();
285   }
286   return !allWasEmpty;
287 }
288
289 void Model_Document::finishOperation()
290 {
291   // just to be sure that everybody knows that changes were performed
292   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
293     std::static_pointer_cast<Model_Session>(Model_Session::get())
294         ->setCheckTransactions(false);  // for nested transaction commit
295   synchronizeBackRefs();
296   Events_Loop* aLoop = Events_Loop::loop();
297   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
298   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
299   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
300   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
301   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
302   // this must be here just after everything is finished but before real transaction stop
303   // to avoid messages about modifications outside of the transaction
304   // and to rebuild everything after all updates and creates
305   if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
306     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
307     static std::shared_ptr<Events_Message> aFinishMsg
308       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
309     Events_Loop::loop()->send(aFinishMsg);
310     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
311   }
312   // to avoid "updated" message appearance by updater
313   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
314
315   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
316     std::static_pointer_cast<Model_Session>(Model_Session::get())
317         ->setCheckTransactions(true);  // for nested transaction commit
318
319   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
320   std::set<std::string>::iterator aSubIter = mySubs.begin();
321   for (; aSubIter != mySubs.end(); aSubIter++)
322     subDoc(*aSubIter)->finishOperation();
323
324   if (myNestedNum != -1)  // this nested transaction is owervritten
325     myNestedNum++;
326   if (!myDoc->HasOpenCommand()) {
327     if (myNestedNum != -1) {
328       myNestedNum--;
329       compactNested();
330     }
331   } else {
332     // returns false if delta is empty and no transaction was made
333     myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
334     myTransactionsCounter++;
335   }
336 }
337
338 void Model_Document::abortOperation()
339 {
340   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
341       // first compact all nested
342     if (compactNested()) {
343       myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
344     }
345     myDoc->ClearRedos();
346     myTransactionsCounter--;
347     myIsEmptyTr.erase(myTransactionsCounter);
348   } else {
349     if (myNestedNum == 0)  // abort only high-level
350       myNestedNum = -1;
351     myDoc->AbortCommand();
352   }
353   synchronizeFeatures(true, false); // references were not changed since transaction start
354   // abort for all subs
355   std::set<std::string>::iterator aSubIter = mySubs.begin();
356   for (; aSubIter != mySubs.end(); aSubIter++)
357     subDoc(*aSubIter)->abortOperation();
358 }
359
360 bool Model_Document::isOperation()
361 {
362   // operation is opened for all documents: no need to check subs
363   return myDoc->HasOpenCommand() == Standard_True ;
364 }
365
366 bool Model_Document::isModified()
367 {
368   // is modified if at least one operation was commited and not undoed
369   return myTransactionsCounter != myTransactionSave || isOperation();
370 }
371
372 bool Model_Document::canUndo()
373 {
374   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
375       && myTransactionsCounter != 0 /* for omitting the first useless transaction */)
376     return true;
377   // check other subs contains operation that can be undoed
378   std::set<std::string>::iterator aSubIter = mySubs.begin();
379   for (; aSubIter != mySubs.end(); aSubIter++)
380     if (subDoc(*aSubIter)->canUndo())
381       return true;
382   return false;
383 }
384
385 void Model_Document::undo()
386 {
387   myTransactionsCounter--;
388   if (myNestedNum > 0)
389     myNestedNum--;
390   if (!myIsEmptyTr[myTransactionsCounter])
391     myDoc->Undo();
392   synchronizeFeatures(true, true);
393   // undo for all subs
394   std::set<std::string>::iterator aSubIter = mySubs.begin();
395   for (; aSubIter != mySubs.end(); aSubIter++)
396     subDoc(*aSubIter)->undo();
397 }
398
399 bool Model_Document::canRedo()
400 {
401   if (myDoc->GetAvailableRedos() > 0)
402     return true;
403   // check other subs contains operation that can be redoed
404   std::set<std::string>::iterator aSubIter = mySubs.begin();
405   for (; aSubIter != mySubs.end(); aSubIter++)
406     if (subDoc(*aSubIter)->canRedo())
407       return true;
408   return false;
409 }
410
411 void Model_Document::redo()
412 {
413   if (myNestedNum != -1)
414     myNestedNum++;
415   if (!myIsEmptyTr[myTransactionsCounter])
416     myDoc->Redo();
417   myTransactionsCounter++;
418   synchronizeFeatures(true, true);
419   // redo for all subs
420   std::set<std::string>::iterator aSubIter = mySubs.begin();
421   for (; aSubIter != mySubs.end(); aSubIter++)
422     subDoc(*aSubIter)->redo();
423 }
424
425 /// Appenad to the array of references a new referenced label
426 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
427 {
428   Handle(TDataStd_ReferenceArray) aRefs;
429   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
430     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
431     aRefs->SetValue(0, theReferenced);
432   } else {  // extend array by one more element
433     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
434                                                                         aRefs->Upper() + 1);
435     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
436       aNewArray->SetValue(a, aRefs->Value(a));
437     }
438     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
439     aRefs->SetInternalArray(aNewArray);
440   }
441 }
442
443 FeaturePtr Model_Document::addFeature(std::string theID)
444 {
445   TDF_Label anEmptyLab;
446   FeaturePtr anEmptyFeature;
447   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
448   if (!aFeature)
449     return aFeature;
450   std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
451       aFeature->documentToAdd());
452   if (aFeature) {
453     TDF_Label aFeatureLab;
454     if (!aFeature->isAction()) {  // do not add action to the data model
455       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
456       aFeatureLab = aFeaturesLab.NewChild();
457       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
458       // keep the feature ID to restore document later correctly
459       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
460       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
461       // store feature in the history of features array
462       if (aFeature->isInHistory()) {
463         AddToRefArray(aFeaturesLab, aFeatureLab);
464       }
465     }
466     if (!aFeature->isAction()) {  // do not add action to the data model
467       // event: feature is added
468       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
469       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
470     } else { // feature must be executed
471        // no creation event => updater not working, problem with remove part
472       aFeature->execute();
473     }
474   }
475   return aFeature;
476 }
477
478 /// Appenad to the array of references a new referenced label.
479 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
480 /// \returns the index of removed element
481 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
482                                   -1)
483 {
484   int aResult = -1;  // no returned
485   Handle(TDataStd_ReferenceArray) aRefs;
486   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
487     if (aRefs->Length() == 1) {  // just erase an array
488       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
489         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
490       }
491       aResult = 0;
492     } else {  // reduce the array
493       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
494                                                                           aRefs->Upper() - 1);
495       int aCount = aRefs->Lower();
496       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
497         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
498           aCount--;
499           aResult = a;
500         } else {
501           aNewArray->SetValue(aCount, aRefs->Value(a));
502         }
503       }
504       aRefs->SetInternalArray(aNewArray);
505     }
506   }
507   return aResult;
508 }
509
510 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
511 {
512   if (theCheck) {
513     // check the feature: it must have no depended objects on it
514     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
515     for(; aResIter != theFeature->results().cend(); aResIter++) {
516       std::shared_ptr<Model_Data> aData = 
517         std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
518       if (aData && !aData->refsToMe().empty()) {
519         Events_Error::send(
520           "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
521         return;
522       }
523     }
524   }
525
526   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
527   if (aData) {
528     TDF_Label aFeatureLabel = aData->label().Father();
529     if (myObjs.IsBound(aFeatureLabel))
530       myObjs.UnBind(aFeatureLabel);
531     else
532       return;  // not found feature => do not remove
533     // erase fields
534     theFeature->erase();
535     // erase all attributes under the label of feature
536     aFeatureLabel.ForgetAllAttributes();
537     // remove it from the references array
538     if (theFeature->isInHistory()) {
539       RemoveFromRefArray(featuresLabel(), aFeatureLabel);
540     }
541   }
542   // event: feature is deleted
543   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
544 }
545
546 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
547 {
548   if (myObjs.IsBound(theLabel))
549     return myObjs.Find(theLabel);
550   return FeaturePtr();  // not found
551 }
552
553 ObjectPtr Model_Document::object(TDF_Label theLabel)
554 {
555   // try feature by label
556   FeaturePtr aFeature = feature(theLabel);
557   if (aFeature)
558     return feature(theLabel);
559   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
560   aFeature = feature(aFeatureLabel);
561   if (aFeature) {
562     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
563     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
564     for (; aRIter != aResults.cend(); aRIter++) {
565       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
566           (*aRIter)->data());
567       if (aResData->label().Father().IsEqual(theLabel))
568         return *aRIter;
569     }
570   }
571   return FeaturePtr();  // not found
572 }
573
574 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
575 {
576   // just store sub-document identifier here to manage it later
577   if (mySubs.find(theDocID) == mySubs.end())
578     mySubs.insert(theDocID);
579   return Model_Application::getApplication()->getDocument(theDocID);
580 }
581
582 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
583 {
584   // just store sub-document identifier here to manage it later
585   if (mySubs.find(theDocID) == mySubs.end())
586     mySubs.insert(theDocID);
587   return std::dynamic_pointer_cast<Model_Document>(
588     Model_Application::getApplication()->getDocument(theDocID));
589 }
590
591 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
592                                  const bool theHidden)
593 {
594   if (theGroupID == ModelAPI_Feature::group()) {
595     if (theHidden) {
596       int anIndex = 0;
597       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
598       for (; aLabIter.More(); aLabIter.Next()) {
599         if (theIndex == anIndex) {
600           TDF_Label aFLabel = aLabIter.Value()->Label();
601           return feature(aFLabel);
602         }
603         anIndex++;
604       }
605     } else {
606       Handle(TDataStd_ReferenceArray) aRefs;
607       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
608         return ObjectPtr();
609       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
610         return ObjectPtr();
611       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
612       return feature(aFeatureLabel);
613     }
614   } else {
615     // comment must be in any feature: it is kind
616     int anIndex = 0;
617     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
618     for (; aLabIter.More(); aLabIter.Next()) {
619       TDF_Label aFLabel = aLabIter.Value()->Label();
620       FeaturePtr aFeature = feature(aFLabel);
621       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
622       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
623       for (; aRIter != aResults.cend(); aRIter++) {
624         if ((*aRIter)->groupName() != theGroupID) continue;
625         bool isIn = theHidden && (*aRIter)->isInHistory();
626         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
627           isIn = !(*aRIter)->isConcealed();
628         }
629         if (isIn) {
630           if (anIndex == theIndex)
631             return *aRIter;
632           anIndex++;
633         }
634       }
635     }
636   }
637   // not found
638   return ObjectPtr();
639 }
640
641 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
642 {
643   int aResult = 0;
644   if (theGroupID == ModelAPI_Feature::group()) {
645     if (theHidden) {
646       return myObjs.Size();
647     } else {
648       Handle(TDataStd_ReferenceArray) aRefs;
649       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
650         return aRefs->Length();
651     }
652   } else {
653     // comment must be in any feature: it is kind
654     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
655     for (; aLabIter.More(); aLabIter.Next()) {
656       TDF_Label aFLabel = aLabIter.Value()->Label();
657       FeaturePtr aFeature = feature(aFLabel);
658       if (!aFeature) // may be on close
659         continue;
660       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
661       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
662       for (; aRIter != aResults.cend(); aRIter++) {
663         if ((*aRIter)->groupName() != theGroupID) continue;
664         bool isIn = theHidden;
665         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
666           isIn = !(*aRIter)->isConcealed();
667         }
668         if (isIn)
669           aResult++;
670       }
671     }
672   }
673   // group is not found
674   return aResult;
675 }
676
677 TDF_Label Model_Document::featuresLabel()
678 {
679   return myDoc->Main().FindChild(TAG_OBJECTS);
680 }
681
682 void Model_Document::setUniqueName(FeaturePtr theFeature)
683 {
684   if (!theFeature->data()->name().empty())
685     return;  // not needed, name is already defined
686   std::string aName;  // result
687   // first count all objects of such kind to start with index = count + 1
688   int aNumObjects = 0;
689   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
690   for (; aFIter.More(); aFIter.Next()) {
691     if (aFIter.Value()->getKind() == theFeature->getKind())
692       aNumObjects++;
693   }
694   // generate candidate name
695   std::stringstream aNameStream;
696   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
697   aName = aNameStream.str();
698   // check this is unique, if not, increase index by 1
699   for (aFIter.Initialize(myObjs); aFIter.More();) {
700     FeaturePtr aFeature = aFIter.Value();
701     bool isSameName = aFeature->data()->name() == aName;
702     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
703       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
704       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
705       for (; aRIter != aResults.cend(); aRIter++) {
706         isSameName = (*aRIter)->data()->name() == aName;
707       }
708     }
709     if (isSameName) {
710       aNumObjects++;
711       std::stringstream aNameStream;
712       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
713       aName = aNameStream.str();
714       // reinitialize iterator to make sure a new name is unique
715       aFIter.Initialize(myObjs);
716     } else
717       aFIter.Next();
718   }
719   theFeature->data()->setName(aName);
720 }
721
722 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
723 {
724   std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
725       myID);
726   std::shared_ptr<Model_Data> aData(new Model_Data);
727   aData->setLabel(theLab.FindChild(theTag));
728   aData->setObject(theObj);
729   theObj->setDoc(aThis);
730   theObj->setData(aData);
731   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
732   if (aFeature) {
733     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
734     aFeature->initAttributes();
735   }
736 }
737
738 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
739 {
740   std::shared_ptr<ModelAPI_Document> aThis = 
741     Model_Application::getApplication()->getDocument(myID);
742   // after all updates, sends a message that groups of features were created or updated
743   std::static_pointer_cast<Model_Session>(Model_Session::get())
744     ->setCheckTransactions(false);
745   Events_Loop* aLoop = Events_Loop::loop();
746   aLoop->activateFlushes(false);
747
748   // update all objects by checking are they of labels or not
749   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
750   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
751   for (; aLabIter.More(); aLabIter.Next()) {
752     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
753     FeaturePtr aFeature;
754     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
755       // create a feature
756       aFeature = ModelAPI_Session::get()->createFeature(
757           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
758               .ToCString());
759       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
760         Events_Error::send("Invalid type of object in the document");
761         aLabIter.Value()->Label().ForgetAllAttributes();
762         continue;
763       }
764       // this must be before "setData" to redo the sketch line correctly
765       myObjs.Bind(aFeatureLabel, aFeature);
766       aNewFeatures.insert(aFeature);
767       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
768
769       // event: model is updated
770       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
771       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
772     } else {  // nothing is changed, both iterators are incremented
773       aFeature = myObjs.Find(aFeatureLabel);
774       aKeptFeatures.insert(aFeature);
775       if (theMarkUpdated) {
776         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
777         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
778       }
779     }
780   }
781   // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
782   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
783   for (; aLabIter2.More(); aLabIter2.Next()) {
784     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
785     if (myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
786       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
787       updateResults(aFeature);
788     }
789   }
790
791   // check all features are checked: if not => it was removed
792   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
793   while (aFIter.More()) {
794     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
795         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
796       FeaturePtr aFeature = aFIter.Value();
797       // event: model is updated
798       //if (aFeature->isInHistory()) {
799         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
800       //}
801       // results of this feature must be redisplayed (hided)
802       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
803       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
804       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
805       // redisplay also removed feature (used for sketch and AISObject)
806       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
807       aFeature->erase();
808       // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
809       TDF_Label aLab = aFIter.Key();
810       aFIter.Next();
811       myObjs.UnBind(aLab);
812     } else
813       aFIter.Next();
814   }
815
816   if (theUpdateReferences) {
817     synchronizeBackRefs();
818   }
819
820   myExecuteFeatures = false;
821   aLoop->activateFlushes(true);
822
823   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
824   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
825   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
826   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
827   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
828   std::static_pointer_cast<Model_Session>(Model_Session::get())
829     ->setCheckTransactions(true);
830   myExecuteFeatures = true;
831 }
832
833 void Model_Document::synchronizeBackRefs()
834 {
835   std::shared_ptr<ModelAPI_Document> aThis = 
836     Model_Application::getApplication()->getDocument(myID);
837   // keeps the concealed flags of result to catch the change and create created/deleted events
838   std::list<std::pair<ResultPtr, bool> > aConcealed;
839   // first cycle: erase all data about back-references
840   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
841   for(; aFeatures.More(); aFeatures.Next()) {
842     FeaturePtr aFeature = aFeatures.Value();
843     std::shared_ptr<Model_Data> aFData = 
844       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
845     if (aFData) {
846       aFData->eraseBackReferences();
847     }
848     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
849     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
850     for (; aRIter != aResults.cend(); aRIter++) {
851       std::shared_ptr<Model_Data> aResData = 
852         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
853       if (aResData) {
854         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
855         aResData->eraseBackReferences();
856       }
857     }
858   }
859
860   // second cycle: set new back-references: only features may have reference, iterate only them
861   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
862   for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
863     FeaturePtr aFeature = aFeatures.Value();
864     std::shared_ptr<Model_Data> aFData = 
865       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
866     if (aFData) {
867       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
868       aFData->referencesToObjects(aRefs);
869       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
870       for(; aRefsIter != aRefs.end(); aRefsIter++) {
871         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
872         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
873           if (*aRefTo) {
874             std::shared_ptr<Model_Data> aRefData = 
875               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
876             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
877           }
878         }
879       }
880     }
881   }
882   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
883   for(; aCIter != aConcealed.end(); aCIter++) {
884     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
885       if (aCIter->second) { // was concealed become not => creation event
886         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
887         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
888       } else { // was not concealed become concealed => delete event
889         ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
890         // redisplay for the viewer (it must be disappeared also)
891         static Events_ID EVENT_DISP = 
892           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
893         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
894       }
895     }
896   }
897 }
898
899 TDF_Label Model_Document::resultLabel(
900   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
901 {
902   const std::shared_ptr<Model_Data>& aData = 
903     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
904   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
905 }
906
907 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
908                                  std::shared_ptr<ModelAPI_Result> theResult,
909                                  const int theResultIndex)
910 {
911   std::shared_ptr<ModelAPI_Document> aThis = 
912     Model_Application::getApplication()->getDocument(myID);
913   theResult->setDoc(aThis);
914   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
915   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
916     theResult->data()->setName(theFeatureData->name());
917   }
918 }
919
920 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
921     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
922 {
923   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
924   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
925   ObjectPtr anOldObject = object(aLab);
926   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
927   if (anOldObject) {
928     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
929   }
930   if (!aResult) {
931     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
932     storeResult(theFeatureData, aResult, theIndex);
933   }
934   return aResult;
935 }
936
937 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
938     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
939 {
940   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
941   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
942   ObjectPtr anOldObject = object(aLab);
943   std::shared_ptr<ModelAPI_ResultBody> aResult;
944   if (anOldObject) {
945     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
946   }
947   if (!aResult) {
948     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
949     storeResult(theFeatureData, aResult, theIndex);
950   }
951   return aResult;
952 }
953
954 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
955     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
956 {
957   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
958   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
959   ObjectPtr anOldObject = object(aLab);
960   std::shared_ptr<ModelAPI_ResultPart> aResult;
961   if (anOldObject) {
962     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
963   }
964   if (!aResult) {
965     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
966     storeResult(theFeatureData, aResult, theIndex);
967   }
968   return aResult;
969 }
970
971 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
972     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
973 {
974   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
975   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
976   ObjectPtr anOldObject = object(aLab);
977   std::shared_ptr<ModelAPI_ResultGroup> aResult;
978   if (anOldObject) {
979     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
980   }
981   if (!aResult) {
982     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
983     storeResult(theFeatureData, aResult, theIndex);
984   }
985   return aResult;
986 }
987
988 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
989     const std::shared_ptr<ModelAPI_Result>& theResult)
990 {
991   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
992   if (aData) {
993     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
994     return feature(aFeatureLab);
995   }
996   return FeaturePtr();
997 }
998
999 void Model_Document::updateResults(FeaturePtr theFeature)
1000 {
1001   // for not persistent is will be done by parametric updater automatically
1002   //if (!theFeature->isPersistentResult()) return;
1003   // check the existing results and remove them if there is nothing on the label
1004   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1005   while(aResIter != theFeature->results().cend()) {
1006     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1007     if (aBody) {
1008       if (!aBody->data()->isValid()) { 
1009         // found a disappeared result => remove it
1010         theFeature->removeResult(aBody);
1011         // start iterate from beginning because iterator is corrupted by removing
1012         aResIter = theFeature->results().cbegin();
1013         continue;
1014       }
1015     }
1016     aResIter++;
1017   }
1018   // it may be on undo
1019   if (!theFeature->data() || !theFeature->data()->isValid())
1020     return;
1021   // check that results are presented on all labels
1022   int aResSize = theFeature->results().size();
1023   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1024   for(; aLabIter.More(); aLabIter.Next()) {
1025     // here must be GUID of the feature
1026     int aResIndex = aLabIter.Value().Tag() - 1;
1027     ResultPtr aNewBody;
1028     if (aResSize <= aResIndex) {
1029       TDF_Label anArgLab = aLabIter.Value();
1030       Handle(TDataStd_Comment) aGroup;
1031       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1032         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1033           aNewBody = createBody(theFeature->data(), aResIndex);
1034         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1035           aNewBody = createPart(theFeature->data(), aResIndex);
1036         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1037           theFeature->execute(); // construction shapes are needed for sketch solver
1038           break;
1039         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1040           aNewBody = createGroup(theFeature->data(), aResIndex);
1041         } else {
1042           Events_Error::send(std::string("Unknown type of result is found in the document:") +
1043             TCollection_AsciiString(aGroup->Get()).ToCString());
1044         }
1045       }
1046       if (aNewBody) {
1047         theFeature->setResult(aNewBody, aResIndex);
1048       }
1049     }
1050   }
1051 }
1052
1053 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1054 {
1055   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1056
1057 }
1058 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1059 {
1060   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1061 }