]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
a657f75ef8680bbfdd118eaa418ae15fb3e71cad
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Document.cxx
4 // Created:     28 Feb 2014
5 // Author:      Mikhail PONIKAROV
6
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>
18
19 #include <Events_Loop.h>
20 #include <Events_Error.h>
21
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>
37 #include <TDF_ListIteratorOfLabelList.hxx>
38
39 #include <climits>
40 #ifndef WIN32
41 #include <sys/stat.h>
42 #endif
43
44 #ifdef WIN32
45 # define _separator_ '\\'
46 #else
47 # define _separator_ '/'
48 #endif
49
50 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
51
52 static const int TAG_GENERAL = 1;  // general properties tag
53
54 // general sub-labels
55 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
56 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
57 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
58
59 Model_Document::Model_Document(const std::string theID, const std::string theKind)
60     : myID(theID), myKind(theKind), myIsActive(false),
61       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
62 {
63   myObjs = new Model_Objects(myDoc->Main());
64   myDoc->SetUndoLimit(UNDO_LIMIT);  
65   myTransactionSave = 0;
66   myExecuteFeatures = true;
67   // to have something in the document and avoid empty doc open/save problem
68   // in transaction for nesting correct working
69   myDoc->NewCommand();
70   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
71   // this to avoid creation of integer attribute outside the transaction after undo
72   transactionID();
73   myDoc->CommitCommand();
74 }
75
76 void Model_Document::setThis(DocumentPtr theDoc)
77 {
78   myObjs->setOwner(theDoc);
79 }
80
81 /// Returns the file name of this document by the nameof directory and identifuer of a document
82 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
83 {
84   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
85   // remove end-separators
86   while(aPath.Length() && 
87         (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
88     aPath.Remove(aPath.Length());
89   aPath += _separator_;
90   aPath += theID.c_str();
91   aPath += ".cbf";  // standard binary file extension
92   return aPath;
93 }
94
95 bool Model_Document::isRoot() const
96 {
97   return this == Model_Session::get()->moduleDocument().get();
98 }
99
100 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
101 {
102   Handle(Model_Application) anApp = Model_Application::getApplication();
103   if (isRoot()) {
104     anApp->setLoadPath(theFileName);
105   }
106   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
107   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
108   try {
109     aStatus = anApp->Open(aPath, myDoc);
110   } catch (Standard_Failure) {
111     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
112     Events_Error::send(
113         std::string("Exception in opening of document: ") + aFail->GetMessageString());
114     return false;
115   }
116   bool isError = aStatus != PCDM_RS_OK;
117   if (isError) {
118     switch (aStatus) {
119       case PCDM_RS_UnknownDocument:
120         Events_Error::send(std::string("Can not open document"));
121         break;
122       case PCDM_RS_AlreadyRetrieved:
123         Events_Error::send(std::string("Can not open document: already opened"));
124         break;
125       case PCDM_RS_AlreadyRetrievedAndModified:
126         Events_Error::send(
127             std::string("Can not open document: already opened and modified"));
128         break;
129       case PCDM_RS_NoDriver:
130         Events_Error::send(std::string("Can not open document: driver library is not found"));
131         break;
132       case PCDM_RS_UnknownFileDriver:
133         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
134         break;
135       case PCDM_RS_OpenError:
136         Events_Error::send(std::string("Can not open document: file open error"));
137         break;
138       case PCDM_RS_NoVersion:
139         Events_Error::send(std::string("Can not open document: invalid version"));
140         break;
141       case PCDM_RS_NoModel:
142         Events_Error::send(std::string("Can not open document: no data model"));
143         break;
144       case PCDM_RS_NoDocument:
145         Events_Error::send(std::string("Can not open document: no document inside"));
146         break;
147       case PCDM_RS_FormatFailure:
148         Events_Error::send(std::string("Can not open document: format failure"));
149         break;
150       case PCDM_RS_TypeNotFoundInSchema:
151         Events_Error::send(std::string("Can not open document: invalid object"));
152         break;
153       case PCDM_RS_UnrecognizedFileFormat:
154         Events_Error::send(std::string("Can not open document: unrecognized file format"));
155         break;
156       case PCDM_RS_MakeFailure:
157         Events_Error::send(std::string("Can not open document: make failure"));
158         break;
159       case PCDM_RS_PermissionDenied:
160         Events_Error::send(std::string("Can not open document: permission denied"));
161         break;
162       case PCDM_RS_DriverFailure:
163         Events_Error::send(std::string("Can not open document: driver failure"));
164         break;
165       default:
166         Events_Error::send(std::string("Can not open document: unknown error"));
167         break;
168     }
169   }
170   if (!isError) {
171     myDoc->SetUndoLimit(UNDO_LIMIT);
172     // to avoid the problem that feature is created in the current, not this, document
173     std::shared_ptr<Model_Session> aSession = 
174       std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
175     aSession->setActiveDocument(anApp->getDocument(myID), false);
176     aSession->setCheckTransactions(false);
177     if (myObjs)
178       delete myObjs;
179     myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
180     myObjs->setOwner(theThis);
181     // update the current features status
182     setCurrentFeature(currentFeature(false), false);
183     aSession->setCheckTransactions(true);
184     aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
185     // this is done in Part result "activate", so no needed here. Causes not-blue active part.
186     // aSession->setActiveDocument(anApp->getDocument(myID), true);
187   }
188   return !isError;
189 }
190
191 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
192 {
193   // create a directory in the root document if it is not yet exist
194   Handle(Model_Application) anApp = Model_Application::getApplication();
195   if (isRoot()) {
196 #ifdef WIN32
197     CreateDirectory(theFileName, NULL);
198 #else
199     mkdir(theFileName, 0x1ff);
200 #endif
201   }
202   // filename in the dir is id of document inside of the given directory
203   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
204   PCDM_StoreStatus aStatus;
205   try {
206     aStatus = anApp->SaveAs(myDoc, aPath);
207   } catch (Standard_Failure) {
208     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
209     Events_Error::send(
210         std::string("Exception in saving of document: ") + aFail->GetMessageString());
211     return false;
212   }
213   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
214   if (!isDone) {
215     switch (aStatus) {
216       case PCDM_SS_DriverFailure:
217         Events_Error::send(std::string("Can not save document: save driver-library failure"));
218         break;
219       case PCDM_SS_WriteFailure:
220         Events_Error::send(std::string("Can not save document: file writing failure"));
221         break;
222       case PCDM_SS_Failure:
223       default:
224         Events_Error::send(std::string("Can not save document"));
225         break;
226     }
227   }
228   myTransactionSave = myTransactions.size();
229   if (isDone) {  // save also sub-documents if any
230     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
231     const std::set<std::string> aSubs = subDocuments(false);
232     std::set<std::string>::iterator aSubIter = aSubs.begin();
233     for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
234       if (anApp->isLoadByDemand(*aSubIter)) { 
235         // copy not-activated document that is not in the memory
236         std::string aDocName = *aSubIter;
237         if (!aDocName.empty()) {
238           // just copy file
239           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
240           OSD_Path aPath(aSubPath);
241           OSD_File aFile(aPath);
242           if (aFile.Exists()) {
243             TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
244             OSD_Path aDestination(aDestinationDir);
245             aFile.Copy(aDestination);
246             theResults.push_back(aDestinationDir.ToCString());
247           } else {
248             Events_Error::send(
249               std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
250           }
251         }
252       } else { // simply save opened document
253         isDone = subDoc(*aSubIter)->save(theFileName, theResults);
254       }
255     }
256   }
257   return isDone;
258 }
259
260 void Model_Document::close(const bool theForever)
261 {
262   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
263   if (!isRoot() && this == aPM->activeDocument().get()) {
264     aPM->setActiveDocument(aPM->moduleDocument());
265   } else if (isRoot()) {
266     // erase the active document if root is closed
267     aPM->setActiveDocument(DocumentPtr());
268   }
269   // close all subs
270   const std::set<std::string> aSubs = subDocuments(true);
271   std::set<std::string>::iterator aSubIter = aSubs.begin();
272   for (; aSubIter != aSubs.end(); aSubIter++) {
273     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
274     if (aSub->myObjs) // if it was not closed before
275       aSub->close(theForever);
276   }
277
278   // close for thid document needs no transaction in this document
279   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
280
281   // close all only if it is really asked, otherwise it can be undoed/redoed
282   if (theForever) {
283     // flush everything to avoid messages with bad objects
284     delete myObjs;
285     myObjs = 0;
286     if (myDoc->CanClose() == CDM_CCS_OK)
287       myDoc->Close();
288     mySelectionFeature.reset();
289   } else {
290     setCurrentFeature(FeaturePtr(), false); // disables all features
291   }
292
293   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
294 }
295
296 void Model_Document::startOperation()
297 {
298   if (myDoc->HasOpenCommand()) {  // start of nested command
299     if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
300       myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
301     }
302     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
303     myDoc->OpenCommand();
304   } else {  // start the simple command
305     myDoc->NewCommand();
306   }
307   // starts a new operation
308   incrementTransactionID();
309   myTransactions.push_back(Transaction());
310   if (!myNestedNum.empty())
311     (*myNestedNum.rbegin())++;
312   myRedos.clear();
313   // new command for all subs
314   const std::set<std::string> aSubs = subDocuments(true);
315   std::set<std::string>::iterator aSubIter = aSubs.begin();
316   for (; aSubIter != aSubs.end(); aSubIter++)
317     subDoc(*aSubIter)->startOperation();
318 }
319
320 void Model_Document::compactNested()
321 {
322   if (!myNestedNum.empty()) {
323     int aNumToCompact = *(myNestedNum.rbegin());
324     int aSumOfTransaction = 0;
325     for(int a = 0; a < aNumToCompact; a++) {
326       aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
327       myTransactions.pop_back();
328     }
329     // the latest transaction is the start of lower-level operation which startes the nested
330     myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
331     myNestedNum.pop_back();
332   }
333 }
334
335 bool Model_Document::finishOperation()
336 {
337   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
338   static std::shared_ptr<Model_Session> aSession = 
339     std::static_pointer_cast<Model_Session>(Model_Session::get());
340   myObjs->synchronizeBackRefs();
341   Events_Loop* aLoop = Events_Loop::loop();
342   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
343   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
344   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
345   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
346   // this must be here just after everything is finished but before real transaction stop
347   // to avoid messages about modifications outside of the transaction
348   // and to rebuild everything after all updates and creates
349   if (isRoot()) { // once for root document
350     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
351     static std::shared_ptr<Events_Message> aFinishMsg
352       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
353     Events_Loop::loop()->send(aFinishMsg);
354     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
355   }
356   // to avoid "updated" message appearance by updater
357   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
358
359   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
360   bool aResult = false;
361   const std::set<std::string> aSubs = subDocuments(true);
362   std::set<std::string>::iterator aSubIter = aSubs.begin();
363   for (; aSubIter != aSubs.end(); aSubIter++)
364     if (subDoc(*aSubIter)->finishOperation())
365       aResult = true;
366
367   // transaction may be empty if this document was created during this transaction (create part)
368   if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
369     myTransactions.rbegin()->myOCAFNum++;
370     aResult = true;
371   }
372
373   if (isNestedClosed) {
374     compactNested();
375   }
376   if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
377     aResult = myTransactions.rbegin()->myOCAFNum != 0;
378
379   if (!aResult && isRoot()) {
380     // nothing inside in all documents, so remove this transaction from the transactions list
381     undoInternal(true, false);
382   }
383   // on finish clear redos in any case (issue 446) and for all subs (issue 408)
384   myDoc->ClearRedos();
385   myRedos.clear();
386   for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
387     subDoc(*aSubIter)->myDoc->ClearRedos();
388     subDoc(*aSubIter)->myRedos.clear();
389   }
390
391   return aResult;
392 }
393
394 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
395 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
396   const bool isRedo = false) {
397   Handle(TDF_Delta) aDelta;
398   if (isRedo)
399     aDelta = theDoc->GetRedos().First();
400   else 
401     aDelta = theDoc->GetUndos().Last();
402   TDF_LabelList aDeltaList;
403   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
404   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
405     theDelta.Append(aListIter.Value());
406   }
407   // add also label of the modified attributes
408   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
409   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
410     theDelta.Append(anAttr.Value()->Label());
411   }
412 }
413
414 void Model_Document::abortOperation()
415 {
416   TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
417   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
418     compactNested();
419     // store undo-delta here as undo actually does in the method later
420     int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
421     for(a = 0; a < aNumTransactions; a++) {
422       modifiedLabels(myDoc, aDeltaLabels);
423       myDoc->Undo();
424     }
425     for(a = 0; a < aNumTransactions; a++) {
426       myDoc->Redo();
427     }
428
429     undoInternal(false, false);
430     myDoc->ClearRedos();
431     myRedos.clear();
432   } else { // abort the current
433     int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
434     myTransactions.pop_back();
435     if (!myNestedNum.empty())
436       (*myNestedNum.rbegin())--;
437     // roll back the needed number of transactions
438     // make commit/undo to get the modification delta
439     //myDoc->AbortCommand();
440     if (myDoc->CommitCommand()) {
441       modifiedLabels(myDoc, aDeltaLabels);
442       myDoc->Undo();
443     }
444     for(int a = 0; a < aNumTransactions; a++) {
445       modifiedLabels(myDoc, aDeltaLabels);
446       myDoc->Undo();
447     }
448     myDoc->ClearRedos();
449   }
450   // abort for all subs, flushes will be later, in the end of root abort
451   const std::set<std::string> aSubs = subDocuments(true);
452   std::set<std::string>::iterator aSubIter = aSubs.begin();
453   for (; aSubIter != aSubs.end(); aSubIter++)
454     subDoc(*aSubIter)->abortOperation();
455   // references may be changed because they are set in attributes on the fly
456   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
457 }
458
459 bool Model_Document::isOperation() const
460 {
461   // operation is opened for all documents: no need to check subs
462   return myDoc->HasOpenCommand() == Standard_True ;
463 }
464
465 bool Model_Document::isModified()
466 {
467   // is modified if at least one operation was commited and not undoed
468   return myTransactions.size() != myTransactionSave || isOperation();
469 }
470
471 bool Model_Document::canUndo()
472 {
473   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
474   int aCurrentNum = isOperation() ? 1 : 0;
475   if (myDoc->GetAvailableUndos() > 0 && 
476       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
477       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
478     return true;
479   // check other subs contains operation that can be undoed
480   const std::set<std::string> aSubs = subDocuments(true);
481   std::set<std::string>::iterator aSubIter = aSubs.begin();
482   for (; aSubIter != aSubs.end(); aSubIter++) {
483     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
484     if (aSub->myObjs) {// if it was not closed before
485       if (aSub->canUndo())
486         return true;
487     }
488   }
489
490   return false;
491 }
492
493 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
494 {
495   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
496   myRedos.push_back(*myTransactions.rbegin());
497   myTransactions.pop_back();
498   if (!myNestedNum.empty())
499     (*myNestedNum.rbegin())--;
500   // roll back the needed number of transactions
501   TDF_LabelList aDeltaLabels;
502   for(int a = 0; a < aNumTransactions; a++) {
503     if (theSynchronize)
504       modifiedLabels(myDoc, aDeltaLabels);
505     myDoc->Undo();
506   }
507
508   if (theWithSubs) {
509     // undo for all subs
510     const std::set<std::string> aSubs = subDocuments(true);
511     std::set<std::string>::iterator aSubIter = aSubs.begin();
512     for (; aSubIter != aSubs.end(); aSubIter++) {
513       if (!subDoc(*aSubIter)->myObjs)
514         continue;
515       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
516     }
517   }
518   // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
519   if (theSynchronize) {
520     myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
521     // update the current features status
522     setCurrentFeature(currentFeature(false), false);
523   }
524 }
525
526 void Model_Document::undo()
527 {
528   undoInternal(true, true);
529 }
530
531 bool Model_Document::canRedo()
532 {
533   if (!myRedos.empty())
534     return true;
535   // check other subs contains operation that can be redoed
536   const std::set<std::string> aSubs = subDocuments(true);
537   std::set<std::string>::iterator aSubIter = aSubs.begin();
538   for (; aSubIter != aSubs.end(); aSubIter++) {
539     if (!subDoc(*aSubIter)->myObjs)
540       continue;
541     if (subDoc(*aSubIter)->canRedo())
542       return true;
543   }
544   return false;
545 }
546
547 void Model_Document::redo()
548 {
549   if (!myNestedNum.empty())
550     (*myNestedNum.rbegin())++;
551   int aNumRedos = myRedos.rbegin()->myOCAFNum;
552   myTransactions.push_back(*myRedos.rbegin());
553   myRedos.pop_back();
554   TDF_LabelList aDeltaLabels;
555   for(int a = 0; a < aNumRedos; a++) {
556     modifiedLabels(myDoc, aDeltaLabels, true);
557     myDoc->Redo();
558   }
559
560   // redo for all subs
561   const std::set<std::string> aSubs = subDocuments(true);
562   std::set<std::string>::iterator aSubIter = aSubs.begin();
563   for (; aSubIter != aSubs.end(); aSubIter++)
564     subDoc(*aSubIter)->redo();
565
566   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
567   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
568   // update the current features status
569   setCurrentFeature(currentFeature(false), false);
570 }
571
572 std::list<std::string> Model_Document::undoList() const
573 {
574   std::list<std::string> aResult;
575   // the number of skipped current operations (on undo they will be aborted)
576   int aSkipCurrent = isOperation() ? 1 : 0;
577   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
578   int aNumUndo = myTransactions.size();
579   if (!myNestedNum.empty())
580     aNumUndo = *myNestedNum.rbegin();
581   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
582     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
583     else aSkipCurrent--;
584   }
585   return aResult;
586 }
587
588 std::list<std::string> Model_Document::redoList() const
589 {
590   std::list<std::string> aResult;
591   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
592   for( ; aTrIter != myRedos.crend(); aTrIter++) {
593     aResult.push_back(aTrIter->myId);
594   }
595   return aResult;
596 }
597
598 void Model_Document::operationId(const std::string& theId)
599 {
600   myTransactions.rbegin()->myId = theId;
601 }
602
603 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
604 {
605   std::shared_ptr<Model_Session> aSession = 
606     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
607   FeaturePtr aFeature = aSession->createFeature(theID, this);
608   if (!aFeature)
609     return aFeature;
610   aFeature->init();
611   Model_Document* aDocToAdd;
612   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
613     if (aFeature->documentToAdd() != kind()) { // the root document by default
614       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
615     } else {
616       aDocToAdd = this;
617     }
618   } else { // if customized is not presented, add to "this" document
619     aDocToAdd = this;
620   }
621   if (aFeature) {
622     // searching for feature after which must be added the next feature: this is the current feature
623     // but also all sub-features of this feature
624     FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
625     bool isModified = true;
626     for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
627         aComp.get() && isModified; 
628         aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
629       isModified =  false;
630       int aSubs = aComp->numberOfSubs(false);
631       for(int a = 0; a < aSubs; a++) {
632         FeaturePtr aSub = aComp->subFeature(a, false);
633         if (myObjs->isLater(aSub, aCurrent)) {
634           isModified =  true;
635           aCurrent = aSub;
636         }
637       }
638     }
639     aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
640     if (!aFeature->isAction()) {  // do not add action to the data model
641       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
642         aDocToAdd->setCurrentFeature(aFeature, false);
643     } else { // feature must be executed
644        // no creation event => updater not working, problem with remove part
645       aFeature->execute();
646     }
647   }
648   return aFeature;
649 }
650
651
652 void Model_Document::refsToFeature(FeaturePtr theFeature,
653   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
654 {
655   myObjs->refsToFeature(theFeature, theRefs, isSendError);
656 }
657
658 void Model_Document::removeFeature(FeaturePtr theFeature)
659 {
660   myObjs->removeFeature(theFeature);
661 }
662
663 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
664 {
665   myObjs->moveFeature(theMoved, theAfterThis);
666   if (theAfterThis == currentFeature(true))
667     setCurrentFeature(theMoved, true);
668 }
669
670 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
671 {
672   myObjs->updateHistory(theObject);
673 }
674
675 void Model_Document::updateHistory(const std::string theGroup)
676 {
677   myObjs->updateHistory(theGroup);
678 }
679
680 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
681 {
682   return Model_Application::getApplication()->getDocument(theDocID);
683 }
684
685 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
686 {
687   std::set<std::string> aResult;
688   std::list<ResultPtr> aPartResults;
689   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
690   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
691   for(; aPartRes != aPartResults.end(); aPartRes++) {
692     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
693     if (aPart && (!theActivatedOnly || aPart->isActivated())) {
694       aResult.insert(aPart->original()->data()->name());
695     }
696   }
697   return aResult;
698 }
699
700 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
701 {
702   // just store sub-document identifier here to manage it later
703   return std::dynamic_pointer_cast<Model_Document>(
704     Model_Application::getApplication()->getDocument(theDocID));
705 }
706
707 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
708 {
709   return myObjs->object(theGroupID, theIndex);
710 }
711
712 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
713     const std::string& theGroupID, const std::string& theName)
714 {
715   return myObjs->objectByName(theGroupID, theName);
716 }
717
718 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
719 {
720   return myObjs->index(theObject);
721 }
722
723 int Model_Document::size(const std::string& theGroupID)
724 {
725   return myObjs->size(theGroupID);
726 }
727
728 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
729 {
730   if (!myObjs) // on close document feature destruction it may call this method
731     return std::shared_ptr<ModelAPI_Feature>();
732   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
733   Handle(TDF_Reference) aRef;
734   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
735     TDF_Label aLab = aRef->Get();
736     FeaturePtr aResult = myObjs->feature(aLab);
737     if (theVisible) { // get nearest visible (in history) going up
738       while(aResult.get() &&  // sub-composites are never in history
739              (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
740         aResult = myObjs->nextFeature(aResult, true);
741       }
742     }
743     return aResult;
744   }
745   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
746 }
747
748 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
749   const bool theVisible)
750 {
751   // blocks the flush signals to avoid each objects visualization in the viewer
752   // they should not be shown once after all modifications are performed
753   Events_Loop* aLoop = Events_Loop::loop();
754   bool isActive = aLoop->activateFlushes(false);
755
756   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
757   CompositeFeaturePtr aMain; // main feature that may nest the new current
758   if (theCurrent.get()) {
759     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
760     if (!aMain.get()) {
761       // if feature nests into compisite feature, make the composite feature as current
762       const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
763       std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
764       for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
765         CompositeFeaturePtr aComposite = 
766           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
767         if (aComposite.get() && aComposite->isSub(theCurrent)) {
768           aMain = aComposite;
769           break;
770         }
771       }
772     }
773   }
774
775   if (theVisible) { // make features below which are not in history also enabled: sketch subs
776     FeaturePtr aNext = 
777       theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
778     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
779       if (aNext->isInHistory()) {
780         break; // next in history is not needed
781       } else { // next not in history is good for making current
782         theCurrent = aNext;
783       }
784     }
785   }
786   if (theCurrent.get()) {
787     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
788     if (!aData.get() || !aData->isValid()) {
789       aLoop->activateFlushes(isActive);
790       return;
791     }
792     TDF_Label aFeatureLabel = aData->label().Father();
793
794     Handle(TDF_Reference) aRef;
795     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
796       aRef->Set(aFeatureLabel);
797     } else {
798       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
799     }
800   } else { // remove reference for the null feature
801     aRefLab.ForgetAttribute(TDF_Reference::GetID());
802   }
803   // make all features after this feature disabled in reversed order (to remove results without deps)
804   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
805   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
806   static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
807
808   bool aPassed = false; // flag that the current object is already passed in cycle
809   FeaturePtr anIter = myObjs->lastFeature();
810   bool aWasChanged = false;
811   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
812     // check this before passed become enabled: the current feature is enabled!
813     if (anIter == theCurrent) aPassed = true;
814
815     bool aDisabledFlag = !aPassed;
816     if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
817       aDisabledFlag = false;
818     if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
819       if (theCurrent.get() && theCurrent->getKind() != "Parameter")
820         aDisabledFlag = false;
821     }
822     if (anIter->setDisabled(aDisabledFlag)) {
823       // state of feature is changed => so feature become updated
824       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
825       ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
826       // flush is in the end of this method
827       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
828       aWasChanged = true;
829     }
830     // update for everyone the concealment flag immideately: on edit feature in the midle of history
831     if (aWasChanged) {
832       const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
833       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
834       for(; aRes != aResList.end(); aRes++) {
835         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
836           std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
837       }
838
839     }
840   }
841   // unblock  the flush signals and up them after this
842   aLoop->activateFlushes(isActive);
843
844   aLoop->flush(aCreateEvent);
845   aLoop->flush(aRedispEvent);
846   aLoop->flush(aDeleteEvent);
847 }
848
849 void Model_Document::setCurrentFeatureUp()
850 {
851   // on remove just go up for minimum step: highlight external objects in sketch causes 
852   // problems if it is true: here and in "setCurrentFeature"
853   FeaturePtr aCurrent = currentFeature(false);
854   if (aCurrent.get()) { // if not, do nothing because null is the upper
855     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
856     setCurrentFeature(aPrev, false);
857   }
858 }
859
860 TDF_Label Model_Document::generalLabel() const
861 {
862   return myDoc->Main().FindChild(TAG_GENERAL);
863 }
864
865 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
866     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
867 {
868   return myObjs->createConstruction(theFeatureData, theIndex);
869 }
870
871 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
872     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
873 {
874   return myObjs->createBody(theFeatureData, theIndex);
875 }
876
877 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
878     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
879 {
880   return myObjs->createPart(theFeatureData, theIndex);
881 }
882
883 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
884       const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
885       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
886 {
887   return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
888 }
889
890 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
891     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
892 {
893   return myObjs->createGroup(theFeatureData, theIndex);
894 }
895
896 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
897       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
898 {
899   return myObjs->createParameter(theFeatureData, theIndex);
900 }
901
902 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
903     const std::shared_ptr<ModelAPI_Result>& theResult)
904 {
905   return myObjs->feature(theResult);
906 }
907
908 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
909 {
910   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
911
912 }
913 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
914 {
915   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
916 }
917
918 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
919 {
920   myNamingNames[theName] = theLabel;
921 }
922
923 TDF_Label Model_Document::findNamingName(std::string theName)
924 {
925   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
926   if (aFind == myNamingNames.end())
927     return TDF_Label(); // not found
928   return aFind->second;
929 }
930
931 ResultPtr Model_Document::findByName(const std::string theName)
932 {
933   return myObjs->findByName(theName);
934 }
935
936 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
937 {
938   return myObjs->allFeatures();
939 }
940
941 void Model_Document::setActive(const bool theFlag)
942 {
943   if (theFlag != myIsActive) {
944     myIsActive = theFlag;
945     // redisplay all the objects of this part
946     static Events_Loop* aLoop = Events_Loop::loop();
947     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
948
949     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
950       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
951         object(ModelAPI_Feature::group(), a));
952       if (aFeature.get() && aFeature->data()->isValid()) {
953         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
954         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
955         for(; aRes != aResList.end(); aRes++) {
956           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
957         }
958       }
959     }
960   }
961 }
962
963 bool Model_Document::isActive() const
964 {
965   return myIsActive;
966 }
967
968 int Model_Document::transactionID()
969 {
970   Handle(TDataStd_Integer) anIndex;
971   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
972       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
973     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
974   }
975   return anIndex->Get();
976 }
977
978 void Model_Document::incrementTransactionID()
979 {
980   int aNewVal = transactionID() + 1;
981   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
982 }
983 void Model_Document::decrementTransactionID()
984 {
985   int aNewVal = transactionID() - 1;
986   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
987 }
988
989 bool Model_Document::isOpened()
990 {
991   return myObjs && !myDoc.IsNull();
992 }
993
994 int Model_Document::numInternalFeatures()
995 {
996   return myObjs->numInternalFeatures();
997 }
998
999 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1000 {
1001   return myObjs->internalFeature(theIndex);
1002 }
1003
1004 void Model_Document::synchronizeTransactions()
1005 {
1006   Model_Document* aRoot = 
1007     std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1008   if (aRoot == this)
1009     return; // don't need to synchronise root with root
1010
1011   std::shared_ptr<Model_Session> aSession = 
1012     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1013   while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1014     aSession->setCheckTransactions(false);
1015     redo();
1016     aSession->setCheckTransactions(true);
1017   }
1018   /* this case can not be reproduced in any known case for the current moment, so, just comment
1019   while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1020     undoInternal(false, true);
1021   }*/
1022 }
1023
1024 // Feature that is used for selection in the Part document by the external request
1025 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1026 public:
1027   /// Nothing to do in constructor
1028   Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1029
1030   /// Returns the unique kind of a feature
1031   virtual const std::string& getKind() {
1032     static std::string MY_KIND("InternalSelectionInPartFeature");
1033     return MY_KIND;
1034   }
1035   /// Request for initialization of data model of the object: adding all attributes
1036   virtual void initAttributes() {
1037     data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1038   }
1039   /// Nothing to do in the execution function
1040   virtual void execute() {}
1041
1042 };
1043
1044 //! Returns the feature that is used for calculation of selection externally from the document
1045 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1046 {
1047   // return already created, otherwise create
1048   if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1049     // create a new one
1050     mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1051   
1052     TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1053     std::shared_ptr<Model_Data> aData(new Model_Data);
1054     aData->setLabel(aFeatureLab.FindChild(1));
1055     aData->setObject(mySelectionFeature);
1056     mySelectionFeature->setDoc(myObjs->owner());
1057     mySelectionFeature->setData(aData);
1058     std::string aName = id() + "_Part";
1059     mySelectionFeature->data()->setName(aName);
1060     mySelectionFeature->setDoc(myObjs->owner());
1061     mySelectionFeature->initAttributes();
1062   }
1063   return mySelectionFeature->selectionList("selection");
1064 }
1065
1066 FeaturePtr Model_Document::lastFeature()
1067 {
1068   if (myObjs)
1069     return myObjs->lastFeature();
1070   return FeaturePtr();
1071 }