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