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