Salome HOME
3a2cb0d2c77fb9c4770fb0ca1dfb687cedf12a72
[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     myDoc->AbortCommand();
431     for(int a = 0; a < aNumTransactions; a++) {
432       modifiedLabels(myDoc, aDeltaLabels);
433       myDoc->Undo();
434     }
435     myDoc->ClearRedos();
436   }
437   // abort for all subs, flushes will be later, in the end of root abort
438   const std::set<std::string> aSubs = subDocuments(true);
439   std::set<std::string>::iterator aSubIter = aSubs.begin();
440   for (; aSubIter != aSubs.end(); aSubIter++)
441     subDoc(*aSubIter)->abortOperation();
442   // references may be changed because they are set in attributes on the fly
443   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
444 }
445
446 bool Model_Document::isOperation() const
447 {
448   // operation is opened for all documents: no need to check subs
449   return myDoc->HasOpenCommand() == Standard_True ;
450 }
451
452 bool Model_Document::isModified()
453 {
454   // is modified if at least one operation was commited and not undoed
455   return myTransactions.size() != myTransactionSave || isOperation();
456 }
457
458 bool Model_Document::canUndo()
459 {
460   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
461   int aCurrentNum = isOperation() ? 1 : 0;
462   if (myDoc->GetAvailableUndos() > 0 && 
463       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
464       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
465     return true;
466   // check other subs contains operation that can be undoed
467   const std::set<std::string> aSubs = subDocuments(true);
468   std::set<std::string>::iterator aSubIter = aSubs.begin();
469   for (; aSubIter != aSubs.end(); aSubIter++) {
470     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
471     if (aSub->myObjs) {// if it was not closed before
472       if (aSub->canUndo())
473         return true;
474     }
475   }
476
477   return false;
478 }
479
480 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
481 {
482   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
483   myRedos.push_back(*myTransactions.rbegin());
484   myTransactions.pop_back();
485   if (!myNestedNum.empty())
486     (*myNestedNum.rbegin())--;
487   // roll back the needed number of transactions
488   TDF_LabelList aDeltaLabels;
489   for(int a = 0; a < aNumTransactions; a++) {
490     if (theSynchronize)
491       modifiedLabels(myDoc, aDeltaLabels);
492     myDoc->Undo();
493   }
494
495   if (theWithSubs) {
496     // undo for all subs
497     const std::set<std::string> aSubs = subDocuments(true);
498     std::set<std::string>::iterator aSubIter = aSubs.begin();
499     for (; aSubIter != aSubs.end(); aSubIter++) {
500       if (!subDoc(*aSubIter)->myObjs)
501         continue;
502       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
503     }
504   }
505   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
506   if (theSynchronize) {
507     myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
508     // update the current features status
509     setCurrentFeature(currentFeature(false), false);
510   }
511 }
512
513 void Model_Document::undo()
514 {
515   undoInternal(true, true);
516 }
517
518 bool Model_Document::canRedo()
519 {
520   if (!myRedos.empty())
521     return true;
522   // check other subs contains operation that can be redoed
523   const std::set<std::string> aSubs = subDocuments(true);
524   std::set<std::string>::iterator aSubIter = aSubs.begin();
525   for (; aSubIter != aSubs.end(); aSubIter++) {
526     if (!subDoc(*aSubIter)->myObjs)
527       continue;
528     if (subDoc(*aSubIter)->canRedo())
529       return true;
530   }
531   return false;
532 }
533
534 void Model_Document::redo()
535 {
536   if (!myNestedNum.empty())
537     (*myNestedNum.rbegin())++;
538   int aNumRedos = myRedos.rbegin()->myOCAFNum;
539   myTransactions.push_back(*myRedos.rbegin());
540   myRedos.pop_back();
541   TDF_LabelList aDeltaLabels;
542   for(int a = 0; a < aNumRedos; a++) {
543     modifiedLabels(myDoc, aDeltaLabels, true);
544     myDoc->Redo();
545   }
546
547   // redo for all subs
548   const std::set<std::string> aSubs = subDocuments(true);
549   std::set<std::string>::iterator aSubIter = aSubs.begin();
550   for (; aSubIter != aSubs.end(); aSubIter++)
551     subDoc(*aSubIter)->redo();
552
553   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
554   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
555   // update the current features status
556   setCurrentFeature(currentFeature(false), false);
557 }
558
559 std::list<std::string> Model_Document::undoList() const
560 {
561   std::list<std::string> aResult;
562   // the number of skipped current operations (on undo they will be aborted)
563   int aSkipCurrent = isOperation() ? 1 : 0;
564   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
565   int aNumUndo = myTransactions.size();
566   if (!myNestedNum.empty())
567     aNumUndo = *myNestedNum.rbegin();
568   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
569     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
570     else aSkipCurrent--;
571   }
572   return aResult;
573 }
574
575 std::list<std::string> Model_Document::redoList() const
576 {
577   std::list<std::string> aResult;
578   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
579   for( ; aTrIter != myRedos.crend(); aTrIter++) {
580     aResult.push_back(aTrIter->myId);
581   }
582   return aResult;
583 }
584
585 void Model_Document::operationId(const std::string& theId)
586 {
587   myTransactions.rbegin()->myId = theId;
588 }
589
590 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
591 {
592   std::shared_ptr<Model_Session> aSession = 
593     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
594   FeaturePtr aFeature = aSession->createFeature(theID, this);
595   if (!aFeature)
596     return aFeature;
597   Model_Document* aDocToAdd;
598   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
599     if (aFeature->documentToAdd() != kind()) { // the root document by default
600       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
601     } else {
602       aDocToAdd = this;
603     }
604   } else { // if customized is not presented, add to "this" document
605     aDocToAdd = this;
606   }
607   if (aFeature) {
608     aDocToAdd->myObjs->addFeature(aFeature, aDocToAdd->currentFeature(false));
609     if (!aFeature->isAction()) {  // do not add action to the data model
610       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
611         aDocToAdd->setCurrentFeature(aFeature, false);
612     } else { // feature must be executed
613        // no creation event => updater not working, problem with remove part
614       aFeature->execute();
615     }
616   }
617   return aFeature;
618 }
619
620
621 void Model_Document::refsToFeature(FeaturePtr theFeature,
622   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
623 {
624   myObjs->refsToFeature(theFeature, theRefs, isSendError);
625 }
626
627 void Model_Document::removeFeature(FeaturePtr theFeature)
628 {
629   myObjs->removeFeature(theFeature);
630 }
631
632 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
633 {
634   myObjs->moveFeature(theMoved, theAfterThis);
635 }
636
637 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
638 {
639   myObjs->updateHistory(theObject);
640 }
641
642 void Model_Document::updateHistory(const std::string theGroup)
643 {
644   myObjs->updateHistory(theGroup);
645 }
646
647 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
648 {
649   return Model_Application::getApplication()->getDocument(theDocID);
650 }
651
652 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
653 {
654   std::set<std::string> aResult;
655   std::list<ResultPtr> aPartResults;
656   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
657   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
658   for(; aPartRes != aPartResults.end(); aPartRes++) {
659     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
660     if (aPart && (!theActivatedOnly || aPart->isActivated())) {
661       aResult.insert(aPart->original()->data()->name());
662     }
663   }
664   return aResult;
665 }
666
667 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
668 {
669   // just store sub-document identifier here to manage it later
670   return std::dynamic_pointer_cast<Model_Document>(
671     Model_Application::getApplication()->getDocument(theDocID));
672 }
673
674 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
675 {
676   return myObjs->object(theGroupID, theIndex);
677 }
678
679 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
680     const std::string& theGroupID, const std::string& theName)
681 {
682   return myObjs->objectByName(theGroupID, theName);
683 }
684
685 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
686 {
687   return myObjs->index(theObject);
688 }
689
690 int Model_Document::size(const std::string& theGroupID)
691 {
692   return myObjs->size(theGroupID);
693 }
694
695 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
696 {
697   if (!myObjs) // on close document feature destruction it may call this method
698     return std::shared_ptr<ModelAPI_Feature>();
699   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
700   Handle(TDF_Reference) aRef;
701   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
702     TDF_Label aLab = aRef->Get();
703     FeaturePtr aResult = myObjs->feature(aLab);
704     if (theVisible) { // get nearest visible (in history) going up
705       while(aResult.get() &&  // sub-composites are never in history
706              (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
707         aResult = myObjs->nextFeature(aResult, true);
708       }
709     }
710     return aResult;
711   }
712   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
713 }
714
715 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
716   const bool theVisible)
717 {
718   // blocks the flush signals to avoid each objects visualization in the viewer
719   // they should not be shown once after all modifications are performed
720   Events_Loop* aLoop = Events_Loop::loop();
721   bool isActive = aLoop->activateFlushes(false);
722
723   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
724   CompositeFeaturePtr aMain; // main feature that may nest the new current
725   if (theCurrent.get()) {
726     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
727     if (!aMain.get()) {
728       // if feature nests into compisite feature, make the composite feature as current
729       const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
730       std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
731       for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
732         CompositeFeaturePtr aComposite = 
733           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
734         if (aComposite.get() && aComposite->isSub(theCurrent)) {
735           aMain = aComposite;
736           break;
737         }
738       }
739     }
740   }
741
742   if (theVisible) { // make features below which are not in history also enabled: sketch subs
743     FeaturePtr aNext = 
744       theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
745     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
746       if (aNext->isInHistory()) {
747         break; // next in history is not needed
748       } else { // next not in history is good for making current
749         theCurrent = aNext;
750       }
751     }
752   }
753   if (theCurrent.get()) {
754     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
755     if (!aData.get() || !aData->isValid()) {
756       aLoop->activateFlushes(isActive);
757       return;
758     }
759     TDF_Label aFeatureLabel = aData->label().Father();
760
761     Handle(TDF_Reference) aRef;
762     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
763       aRef->Set(aFeatureLabel);
764     } else {
765       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
766     }
767   } else { // remove reference for the null feature
768     aRefLab.ForgetAttribute(TDF_Reference::GetID());
769   }
770   // make all features after this feature disabled in reversed order (to remove results without deps)
771   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
772   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
773   static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
774
775   bool aPassed = false; // flag that the current object is already passed in cycle
776   FeaturePtr anIter = myObjs->lastFeature();
777   bool aWasChanged = false;
778   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
779     // check this before passed become enabled: the current feature is enabled!
780     if (anIter == theCurrent) aPassed = true;
781
782     bool aDisabledFlag = !aPassed;
783     if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
784       aDisabledFlag = false;
785     if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
786       if (theCurrent.get() && theCurrent->getKind() != "Parameter")
787         aDisabledFlag = false;
788     }
789     if (anIter->setDisabled(aDisabledFlag)) {
790       // state of feature is changed => so feature become updated
791       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
792       ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
793       // flush is in the end of this method
794       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
795       aWasChanged = true;
796     }
797     // update for everyone the concealment flag immideately: on edit feature in the midle of history
798     if (aWasChanged) {
799       const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
800       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
801       for(; aRes != aResList.end(); aRes++) {
802         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
803           std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
804       }
805
806     }
807   }
808   // unblock  the flush signals and up them after this
809   aLoop->activateFlushes(isActive);
810
811   aLoop->flush(aCreateEvent);
812   aLoop->flush(aRedispEvent);
813   aLoop->flush(aDeleteEvent);
814 }
815
816 void Model_Document::setCurrentFeatureUp()
817 {
818   // on remove just go up for minimum step: highlight external objects in sketch causes 
819   // problems if it is true: here and in "setCurrentFeature"
820   FeaturePtr aCurrent = currentFeature(false);
821   if (aCurrent.get()) { // if not, do nothing because null is the upper
822     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
823     setCurrentFeature(aPrev, false);
824   }
825 }
826
827 TDF_Label Model_Document::generalLabel() const
828 {
829   return myDoc->Main().FindChild(TAG_GENERAL);
830 }
831
832 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
833     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
834 {
835   return myObjs->createConstruction(theFeatureData, theIndex);
836 }
837
838 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
839     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
840 {
841   return myObjs->createBody(theFeatureData, theIndex);
842 }
843
844 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
845     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
846 {
847   return myObjs->createPart(theFeatureData, theIndex);
848 }
849
850 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
851       const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
852       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
853 {
854   return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
855 }
856
857 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
858     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
859 {
860   return myObjs->createGroup(theFeatureData, theIndex);
861 }
862
863 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
864       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
865 {
866   return myObjs->createParameter(theFeatureData, theIndex);
867 }
868
869 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
870     const std::shared_ptr<ModelAPI_Result>& theResult)
871 {
872   return myObjs->feature(theResult);
873 }
874
875 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
876 {
877   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
878
879 }
880 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
881 {
882   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
883 }
884
885 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
886 {
887   myNamingNames[theName] = theLabel;
888 }
889
890 TDF_Label Model_Document::findNamingName(std::string theName)
891 {
892   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
893   if (aFind == myNamingNames.end())
894     return TDF_Label(); // not found
895   return aFind->second;
896 }
897
898 ResultPtr Model_Document::findByName(const std::string theName)
899 {
900   return myObjs->findByName(theName);
901 }
902
903 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
904 {
905   return myObjs->allFeatures();
906 }
907
908 void Model_Document::setActive(const bool theFlag)
909 {
910   if (theFlag != myIsActive) {
911     myIsActive = theFlag;
912     // redisplay all the objects of this part
913     static Events_Loop* aLoop = Events_Loop::loop();
914     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
915
916     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
917       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
918         object(ModelAPI_Feature::group(), a));
919       if (aFeature.get() && aFeature->data()->isValid()) {
920         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
921         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
922         for(; aRes != aResList.end(); aRes++) {
923           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
924         }
925       }
926     }
927   }
928 }
929
930 bool Model_Document::isActive() const
931 {
932   return myIsActive;
933 }
934
935 int Model_Document::transactionID()
936 {
937   Handle(TDataStd_Integer) anIndex;
938   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
939       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
940     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
941   }
942   return anIndex->Get();
943 }
944
945 void Model_Document::incrementTransactionID()
946 {
947   int aNewVal = transactionID() + 1;
948   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
949 }
950 void Model_Document::decrementTransactionID()
951 {
952   int aNewVal = transactionID() - 1;
953   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
954 }
955
956 bool Model_Document::isOpened()
957 {
958   return myObjs && !myDoc.IsNull();
959 }
960
961 int Model_Document::numInternalFeatures()
962 {
963   return myObjs->numInternalFeatures();
964 }
965
966 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
967 {
968   return myObjs->internalFeature(theIndex);
969 }
970
971 // Feature that is used for selection in the Part document by the external request
972 class Model_SelectionInPartFeature : public ModelAPI_Feature {
973 public:
974   /// Nothing to do in constructor
975   Model_SelectionInPartFeature() : ModelAPI_Feature() {}
976
977   /// Returns the unique kind of a feature
978   virtual const std::string& getKind() {
979     static std::string MY_KIND("InternalSelectionInPartFeature");
980     return MY_KIND;
981   }
982   /// Request for initialization of data model of the object: adding all attributes
983   virtual void initAttributes() {
984     data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
985   }
986   /// Nothing to do in the execution function
987   virtual void execute() {}
988
989 };
990
991 //! Returns the feature that is used for calculation of selection externally from the document
992 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
993 {
994   // return already created, otherwise create
995   if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
996     // create a new one
997     mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
998   
999     TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1000     std::shared_ptr<Model_Data> aData(new Model_Data);
1001     aData->setLabel(aFeatureLab.FindChild(1));
1002     aData->setObject(mySelectionFeature);
1003     mySelectionFeature->setDoc(myObjs->owner());
1004     mySelectionFeature->setData(aData);
1005     std::string aName = id() + "_Part";
1006     mySelectionFeature->data()->setName(aName);
1007     mySelectionFeature->setDoc(myObjs->owner());
1008     mySelectionFeature->initAttributes();
1009   }
1010   return mySelectionFeature->selectionList("selection");
1011 }
1012
1013 FeaturePtr Model_Document::lastFeature()
1014 {
1015   if (myObjs)
1016     return myObjs->lastFeature();
1017   return FeaturePtr();
1018 }