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