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