Salome HOME
Delete folder operation
[modules/shaper.git] / src / XGUI / XGUI_DataModel.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "XGUI_DataModel.h"
22 #include "XGUI_Workshop.h"
23 #include "XGUI_ObjectsBrowser.h"
24 #include "XGUI_Displayer.h"
25
26 #include <ModuleBase_IconFactory.h>
27
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_Events.h>
30 #include <ModelAPI_ResultParameter.h>
31 #include <ModelAPI_AttributeDouble.h>
32 #include <ModelAPI_ResultPart.h>
33 #include <ModelAPI_Feature.h>
34 #include <ModelAPI_CompositeFeature.h>
35 #include <ModelAPI_ResultCompSolid.h>
36 #include <ModelAPI_ResultField.h>
37 #include <ModelAPI_Tools.h>
38 #include <ModelAPI_Folder.h>
39
40 #include <Config_FeatureMessage.h>
41 #include <Config_DataModelReader.h>
42
43 #include <Events_Loop.h>
44
45 #include <QIcon>
46 #include <QBrush>
47
48 #define ACTIVE_COLOR QColor(Qt::black)
49 //#define ACTIVE_COLOR QColor(0,72,140)
50 //#define PASSIVE_COLOR Qt::black
51
52 /// Returns ResultPart object if the given object is a Part feature
53 /// Otherwise returns NULL
54
55 #define SELECTABLE_COLOR QColor(80, 80, 80)
56 #define DISABLED_COLOR QColor(200, 200, 200)
57
58
59 ResultPartPtr getPartResult(ModelAPI_Object* theObj)
60 {
61   ModelAPI_Feature* aFeature = dynamic_cast<ModelAPI_Feature*>(theObj);
62   if (aFeature) {
63     ResultPtr aRes = aFeature->firstResult();
64     if (aRes.get() && (aRes->groupName() == ModelAPI_ResultPart::group())) {
65       ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aRes);
66       // Use only original parts, not a placement results
67       if (aPartRes == aPartRes->original())
68       return aPartRes;
69     }
70   }
71   return ResultPartPtr();
72 }
73
74 /// Returns pointer on document if the given object is document object
75 ModelAPI_Document* getSubDocument(void* theObj)
76 {
77   ModelAPI_Document* aDoc = dynamic_cast<ModelAPI_Document*>((ModelAPI_Entity*)theObj);
78   return aDoc;
79 }
80
81
82
83
84 // Constructor *************************************************
85 XGUI_DataModel::XGUI_DataModel(QObject* theParent) : QAbstractItemModel(theParent)//,
86   //myIsEventsProcessingBlocked(false)
87 {
88   XGUI_ObjectsBrowser* aOB = qobject_cast<XGUI_ObjectsBrowser*>(theParent);
89   myWorkshop = aOB->workshop();
90
91   Events_Loop* aLoop = Events_Loop::loop();
92   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
93   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
94   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
95   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_ORDER_UPDATED));
96   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
97 }
98
99 XGUI_DataModel::~XGUI_DataModel()
100 {
101   clear();
102 }
103
104 //******************************************************
105 void XGUI_DataModel::processEvent(const std::shared_ptr<Events_Message>& theMessage)
106 {
107   //if (myIsEventsProcessingBlocked)
108   //  return;
109   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
110   std::string aRootType = myXMLReader->rootType();
111   std::string aSubType = myXMLReader->subType();
112   int aNbFolders = foldersCount();
113
114   // Created object event *******************
115   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
116     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
117         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
118     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
119
120     std::set<ObjectPtr>::const_iterator aIt;
121     std::string aObjType;
122     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
123       ObjectPtr aObject = (*aIt);
124       // We do not show objects which does not need to be shown in object browser
125       if (!aObject->isInHistory())
126         continue;
127
128       aObjType = aObject->groupName();
129       DocumentPtr aDoc = aObject->document();
130       if (aDoc == aRootDoc) {
131         // Check that new folders could appear
132         QStringList aNotEmptyFolders = listOfShowNotEmptyFolders();
133         foreach (QString aNotEmptyFolder, aNotEmptyFolders) {
134           if ((aNotEmptyFolder.toStdString() == aObjType) && (aRootDoc->size(aObjType) > 0)) {
135             // Appears first object in folder which can not be shown empty
136             if (!hasShownFolder(aRootDoc, aNotEmptyFolder)) {
137               insertRow(myXMLReader->rootFolderId(aObjType));
138               addShownFolder(aRootDoc, aNotEmptyFolder);
139             }
140           }
141         }
142         // Insert new object
143         int aRow = aRootDoc->size(aObjType) - 1;
144         if (aRow != -1) {
145           if ((aObjType == aRootType) || (aObjType == ModelAPI_Folder::group())) {
146             insertRow(aRow + aNbFolders + 1);
147           } else {
148             int aFolderId = myXMLReader->rootFolderId(aObjType);
149             if (aFolderId != -1) {
150               insertRow(aRow, createIndex(aFolderId, 0, (void*)Q_NULLPTR));
151             }
152           }
153         }
154       } else {
155         // Object created in sub-document
156         QModelIndex aDocRoot = findDocumentRootIndex(aDoc.get(), 0);
157         if (aDocRoot.isValid()) {
158           // Check that new folders could appear
159           QStringList aNotEmptyFolders = listOfShowNotEmptyFolders(false);
160           foreach (QString aNotEmptyFolder, aNotEmptyFolders) {
161             if ((aNotEmptyFolder.toStdString() == aObjType) && (aDoc->size(aObjType) > 0)) {
162               // Appears first object in folder which can not be shown empty
163               if (!hasShownFolder(aDoc, aNotEmptyFolder)) {
164                 insertRow(myXMLReader->subFolderId(aObjType), aDocRoot);
165                 addShownFolder(aDoc, aNotEmptyFolder);
166               }
167             }
168          }
169           int aRow = aDoc->index(aObject, true);
170           if (aRow != -1) {
171             int aNbSubFolders = foldersCount(aDoc.get());
172             if ((aObjType == aSubType) || (aObjType == ModelAPI_Folder::group())) {
173               // List of objects under document root
174               insertRow(aRow + aNbSubFolders, aDocRoot);
175             } else {
176               // List of objects under a folder
177               if (aRow != -1) {
178                 int aFolderId = folderId(aObjType, aDoc.get());
179                 if (aFolderId != -1) {
180                   QModelIndex aParentFolder = createIndex(aFolderId, 0, aDoc.get());
181                   insertRow(aRow, aParentFolder);
182                   emit dataChanged(aParentFolder, aParentFolder);
183                 }
184               }
185             }
186           } else {
187             rebuildDataTree();
188             break;
189           }
190         } else {
191           rebuildDataTree();
192           break;
193         }
194       }
195     }
196     // Deleted object event ***********************
197   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
198     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aUpdMsg =
199         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
200     DocumentPtr aDoc = aUpdMsg->document();
201     std::set<std::string> aMsgGroups = aUpdMsg->groups();
202
203     /// Sort groups because RootType deletion has to be done after others
204     std::string aType = (aDoc == aRootDoc)? aRootType : aSubType;
205     std::list<std::string> aGroups;
206     std::set<std::string>::const_iterator aSetIt;
207     for (aSetIt = aMsgGroups.begin(); aSetIt != aMsgGroups.end(); ++aSetIt) {
208       std::string aGroup = (*aSetIt);
209       if (aGroup == aType)
210         aGroups.push_back(aGroup);
211       else
212         aGroups.push_front(aGroup);
213     }
214
215     std::list<std::string>::const_iterator aIt;
216     for (aIt = aGroups.begin(); aIt != aGroups.end(); ++aIt) {
217       std::string aGroup = (*aIt);
218       if (aDoc == aRootDoc) {  // If root objects
219         int aRow = aRootDoc->size(aGroup, true);
220         if ((aGroup == aRootType) || (aGroup == ModelAPI_Folder::group())) {
221           // Process root folder
222           removeRow(aRow + aNbFolders);
223           rebuildBranch(aNbFolders, aRow);
224         } else {
225           // Process root sub-folder
226           int aFolderId = myXMLReader->rootFolderId(aGroup);
227           if (aFolderId != -1) {
228             QModelIndex aFolderIndex = createIndex(aFolderId, 0, (void*)Q_NULLPTR);
229             removeRow(aRow, aFolderIndex);
230             //rebuildBranch(0, aRow);
231           }
232         }
233         // Check that some folders could erased
234         QStringList aNotEmptyFolders = listOfShowNotEmptyFolders();
235         foreach (QString aNotEmptyFolder, aNotEmptyFolders) {
236           if ((aNotEmptyFolder.toStdString() == aGroup) && (aRootDoc->size(aGroup, true) == 0)) {
237             // Appears first object in folder which can not be shown empty
238             removeRow(myXMLReader->rootFolderId(aGroup));
239             removeShownFolder(aRootDoc, aNotEmptyFolder);
240             //rebuildBranch(0, aNbFolders + aDoc->size(myXMLReader->rootType()));
241             break;
242           }
243         }
244       } else {
245         // Remove row for sub-document
246         QModelIndex aDocRoot = findDocumentRootIndex(aDoc.get(), 0);
247         if (aDocRoot.isValid()) {
248           int aRow = aDoc->size(aGroup, true);
249           int aNbSubFolders = foldersCount(aDoc.get());
250           if ((aGroup == aSubType) || (aGroup == ModelAPI_Folder::group())) {
251             // List of objects under document root
252             removeRow(aRow + aNbSubFolders, aDocRoot);
253             rebuildBranch(aNbSubFolders, aRow, aDocRoot);
254           } else {
255             // List of objects under a folder
256             int aFolderId = folderId(aGroup, aDoc.get());
257             if (aFolderId != -1) {
258               QModelIndex aFolderRoot = createIndex(aFolderId, 0, aDoc.get());
259               removeRow(aRow, aFolderRoot);
260               //rebuildBranch(0, aRow, aFolderRoot);
261             }
262           }
263           // Check that some folders could disappear
264           QStringList aNotEmptyFolders = listOfShowNotEmptyFolders(false);
265           int aSize = aDoc->size(aGroup, true);
266           foreach (QString aNotEmptyFolder, aNotEmptyFolders) {
267             if ((aNotEmptyFolder.toStdString() == aGroup) && (aSize == 0)) {
268               // Appears first object in folder which can not be shown empty
269               removeRow(myXMLReader->subFolderId(aGroup), aDocRoot);
270               removeShownFolder(aDoc, aNotEmptyFolder);
271               //rebuildBranch(0, aNbSubFolders + aDoc->size(myXMLReader->subType()), aDocRoot);
272               break;
273             }
274           }
275         } else {
276           rebuildDataTree();
277           break;
278         }
279       }
280     }
281   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
282     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
283         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
284     std::set<ObjectPtr> aObjects = aUpdMsg->objects();
285
286     std::set<ObjectPtr>::const_iterator aIt;
287     std::string aObjType;
288     for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
289       ObjectPtr aObject = (*aIt);
290       if (aObject->data()->isValid()) {
291         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
292         if (aFeature.get() && aFeature->firstResult().get()
293           && (aFeature->firstResult()->groupName() == ModelAPI_ResultField::group())) {
294             ResultFieldPtr aResult =
295               std::dynamic_pointer_cast<ModelAPI_ResultField>(aFeature->firstResult());
296             QModelIndex aIndex = objectIndex(aResult, 0);
297             removeRows(0, aResult->stepsSize(), aIndex);
298         } else {
299           QModelIndex aIndex = objectIndex(aObject, 0);
300           if (aIndex.isValid()) {
301             emit dataChanged(aIndex, aIndex);
302           }
303         }
304       } else {
305         rebuildDataTree();
306         break;
307       }
308     }
309   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_ORDER_UPDATED)) {
310     std::shared_ptr<ModelAPI_OrderUpdatedMessage> aUpdMsg =
311         std::dynamic_pointer_cast<ModelAPI_OrderUpdatedMessage>(theMessage);
312     if (aUpdMsg->reordered().get()) {
313       DocumentPtr aDoc = aUpdMsg->reordered()->document();
314       std::string aGroup = aUpdMsg->reordered()->group();
315
316       QModelIndex aParent;
317       int aStartId = 0;
318       if (aDoc == aRootDoc) {
319         // Update a group under root
320         if (aGroup == myXMLReader->rootType()) // Update objects under root
321           aStartId = foldersCount();
322         else // Update objects in folder under root
323           aParent = createIndex(folderId(aGroup), 0, (void*)Q_NULLPTR);
324       } else {
325         // Update a sub-document
326         if (aGroup == myXMLReader->subType()) {
327           // Update sub-document root
328           aParent = findDocumentRootIndex(aDoc.get(), 0);
329           aStartId = foldersCount(aDoc.get());
330         } else
331           // update folder in sub-document
332           aParent = createIndex(folderId(aGroup, aDoc.get()), 0, aDoc.get());
333       }
334       int aChildNb = rowCount(aParent);
335       rebuildBranch(aStartId, aChildNb - aStartId, aParent);
336     } else {
337       rebuildDataTree();
338     }
339   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
340     DocumentPtr aDoc = ModelAPI_Session::get()->activeDocument();
341     if (aDoc != aRootDoc) {
342       QModelIndex aDocRoot = findDocumentRootIndex(aDoc.get(), 0);
343       if (aDocRoot.isValid())
344         emit dataChanged(aDocRoot, aDocRoot);
345       else
346         // We have got a new document
347         rebuildDataTree();
348     }
349   }
350 }
351
352 //******************************************************
353 void XGUI_DataModel::clear()
354 {
355   beginResetModel();
356   endResetModel();
357 }
358
359 //******************************************************
360 void XGUI_DataModel::rebuildDataTree()
361 {
362   beginResetModel();
363   endResetModel();
364   emit treeRebuilt();
365 }
366
367 //******************************************************
368 ObjectPtr XGUI_DataModel::object(const QModelIndex& theIndex) const
369 {
370   if (theIndex.internalId() == 0) // this is a folder
371     return ObjectPtr();
372   ModelAPI_Object* aObj =
373     dynamic_cast<ModelAPI_Object*>((ModelAPI_Entity*)theIndex.internalPointer());
374   if (!aObj)
375     return ObjectPtr();
376   if (getSubDocument(aObj)) // the selected index is a folder of sub-document
377     return ObjectPtr();
378
379   return aObj->data()->owner();
380 }
381
382 //******************************************************
383 QModelIndex XGUI_DataModel::objectIndex(const ObjectPtr theObject, int theColumn) const
384 {
385   std::string aType = theObject->groupName();
386   DocumentPtr aDoc = theObject->document();
387   int aRow = aDoc->index(theObject, true);
388   if (aRow == -1) {
389     // it could be a part of complex object
390     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
391     if (aFeature.get()) {
392       CompositeFeaturePtr aCompFea = ModelAPI_Tools::compositeOwner(aFeature);
393       if (aCompFea.get()) {
394         for (int i = 0; i < aCompFea->numberOfSubs(true); i++) {
395           if (aCompFea->subFeature(i, true) == theObject) {
396             aRow = i;
397             break;
398           }
399         }
400       }
401     } else {
402       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
403       if (aResult.get()) {
404         ResultCompSolidPtr aCompRes = ModelAPI_Tools::compSolidOwner(aResult);
405         if (aCompRes.get()) {
406           aRow = ModelAPI_Tools::compSolidIndex(aResult);
407         }
408       }
409     }
410     if (aRow == -1)
411       return QModelIndex();
412     else
413       return createIndex(aRow, theColumn, theObject.get());
414   }
415   SessionPtr aSession = ModelAPI_Session::get();
416   DocumentPtr aRootDoc = aSession->moduleDocument();
417   if (aDoc == aRootDoc &&
418     ((myXMLReader->rootType() == aType) || (aType == ModelAPI_Folder::group()))) {
419     // The object from root document
420     aRow += foldersCount();
421   } else if ((myXMLReader->subType() == aType) || (aType == ModelAPI_Folder::group())) {
422     // The object from sub document
423     aRow += foldersCount(aDoc.get());
424   }
425   return createIndex(aRow, theColumn, theObject.get());
426 }
427
428 //******************************************************
429 QVariant XGUI_DataModel::data(const QModelIndex& theIndex, int theRole) const
430 {
431   SessionPtr aSession = ModelAPI_Session::get();
432   DocumentPtr aRootDoc = aSession->moduleDocument();
433   int aNbFolders = foldersCount();
434   int theIndexRow = theIndex.row();
435
436   if (theRole == Qt::DecorationRole) {
437     if (theIndex == lastHistoryIndex())
438       return QIcon(":pictures/arrow.png");
439     else if (theIndex.column() == 0) {
440       VisibilityState aState = getVisibilityState(theIndex);
441       switch (aState) {
442       case NoneState:
443         return QIcon();
444       case Visible:
445         return QIcon(":pictures/eyeopen.png");
446       case SemiVisible:
447         return QIcon(":pictures/eyemiclosed.png");
448       case Hidden:
449         return QIcon(":pictures/eyeclosed.png");
450       }
451     }
452   }
453
454   //if (theIndex.column() == 1)
455   if (theIndex.column() != 1)
456     return QVariant();
457
458   quintptr aParentId = theIndex.internalId();
459   if (aParentId == 0) { // root folders
460     switch (theRole) {
461       case Qt::DisplayRole:
462         return QString(myXMLReader->rootFolderName(theIndexRow).c_str()) +
463           QString(" (%1)").arg(rowCount(theIndex));
464       case Qt::DecorationRole:
465         return QIcon(myXMLReader->rootFolderIcon(theIndexRow).c_str());
466       case Qt::ForegroundRole:
467         {
468           Qt::ItemFlags aFlags = theIndex.flags();
469           if (aFlags == Qt::ItemFlags())
470             return QBrush(DISABLED_COLOR);
471           if (!aFlags.testFlag(Qt::ItemIsEditable))
472             return QBrush(SELECTABLE_COLOR);
473         }
474         return ACTIVE_COLOR;
475     }
476   } else { // an object or sub-document
477     if (theRole == Qt::ForegroundRole) {
478       Qt::ItemFlags aFlags = theIndex.flags();
479       if (aFlags == Qt::ItemFlags())
480         return QBrush(DISABLED_COLOR);
481       if (!aFlags.testFlag(Qt::ItemIsEditable))
482         return QBrush(SELECTABLE_COLOR);
483       return ACTIVE_COLOR;
484     }
485
486     ModelAPI_Document* aSubDoc = getSubDocument(theIndex.internalPointer());
487     if (aSubDoc) { // this is a folder of sub document
488       QIntList aMissedIdx = missedFolderIndexes(aSubDoc);
489       int aRow = theIndexRow;
490       while (aMissedIdx.contains(aRow))
491         aRow++;
492       if (aRow < myXMLReader->subFoldersNumber()) {
493         switch (theRole) {
494           case Qt::DisplayRole:
495             return QString(myXMLReader->subFolderName(aRow).c_str()) +
496               QString(" (%1)").arg(rowCount(theIndex));
497           case Qt::DecorationRole:
498             return QIcon(myXMLReader->subFolderIcon(aRow).c_str());
499         }
500       }
501     } else {
502       ObjectPtr aObj = object(theIndex);
503       if (aObj) {
504         switch (theRole) {
505         case Qt::DisplayRole:
506           {
507             if (aObj->groupName() == ModelAPI_ResultParameter::group()) {
508               ResultParameterPtr aParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aObj);
509               AttributeDoublePtr aValueAttribute =
510                 aParam->data()->real(ModelAPI_ResultParameter::VALUE());
511               QString aVal = QString::number(aValueAttribute->value());
512               QString aTitle = QString(aObj->data()->name().c_str());
513               return aTitle + " = " + aVal;
514             }
515             QString aSuffix;
516             if (aObj->groupName() == myXMLReader->subType()) {
517               ResultPartPtr aPartRes = getPartResult(aObj.get());
518               if (aPartRes.get()) {
519                 if (aPartRes->partDoc().get() == NULL)
520                   aSuffix = " (Not loaded)";
521               }
522             }
523             return aObj->data()->name().c_str() + aSuffix;
524           }
525         case Qt::DecorationRole:
526           {
527             if (aObj->groupName() == ModelAPI_Folder::group())
528               return QIcon(":pictures/features_folder.png");
529             else
530               return ModuleBase_IconFactory::get()->getIcon(aObj);
531           }
532         }
533       } else {
534         switch (theRole) {
535         case Qt::DisplayRole:
536           {
537             ModelAPI_ResultField::ModelAPI_FieldStep* aStep =
538               dynamic_cast<ModelAPI_ResultField::ModelAPI_FieldStep*>
539               ((ModelAPI_Entity*)theIndex.internalPointer());
540             if (aStep) {
541               return "Step " + QString::number(aStep->id() + 1) + " " +
542                 aStep->field()->textLine(aStep->id()).c_str();
543             }
544           }
545           break;
546         }
547       }
548     }
549   }
550   return QVariant();
551 }
552
553 //******************************************************
554 QVariant XGUI_DataModel::headerData(int theSection, Qt::Orientation theOrient, int theRole) const
555 {
556   return QVariant();
557 }
558
559 //******************************************************
560 int XGUI_DataModel::rowCount(const QModelIndex& theParent) const
561 {
562   SessionPtr aSession = ModelAPI_Session::get();
563   if (!aSession->hasModuleDocument())
564     return 0;
565   DocumentPtr aRootDoc = aSession->moduleDocument();
566
567   if (!theParent.isValid()) {
568     // Return number of items in root
569     int aNbFolders = foldersCount();
570     int aNbItems = 0;
571     std::string aType = myXMLReader->rootType();
572     if (!aType.empty())
573       aNbItems = aRootDoc->size(aType, true);
574     return aNbFolders + aNbItems;
575   }
576
577   quintptr aId = theParent.internalId();
578   if (aId == 0) {
579     // this is a folder under root
580     int aParentPos = theParent.row();
581     std::string aType = myXMLReader->rootFolderType(aParentPos);
582     return aRootDoc->size(aType);
583   } else {
584     // It is an object which could have children
585     ModelAPI_Document* aDoc = getSubDocument(theParent.internalPointer());
586     if (aDoc) {
587       // a folder of sub-document
588       QIntList aMissedIdx = missedFolderIndexes(aDoc);
589       int aRow = theParent.row();
590       while (aMissedIdx.contains(aRow))
591         aRow++;
592       if (aRow < myXMLReader->subFoldersNumber()) {
593         std::string aType = myXMLReader->subFolderType(aRow);
594         return aDoc->size(aType);
595       }
596     } else {
597       ModelAPI_Object* aObj =
598         dynamic_cast<ModelAPI_Object*>((ModelAPI_Entity*)theParent.internalPointer());
599       // Check for Part feature
600       ResultPartPtr aPartRes = getPartResult(aObj);
601       if (aPartRes.get()) {
602         DocumentPtr aSubDoc = aPartRes->partDoc();
603         if (!aSubDoc.get())
604           return 0;
605
606         int aNbSubFolders = foldersCount(aSubDoc.get());
607         int aNbSubItems = 0;
608         std::string aSubType = myXMLReader->subType();
609         if (!aSubType.empty())
610           aNbSubItems = aSubDoc->size(aSubType, true);
611         return aNbSubItems + aNbSubFolders;
612       } else {
613         // Check for composite object
614         ModelAPI_CompositeFeature* aCompFeature = dynamic_cast<ModelAPI_CompositeFeature*>(aObj);
615         if (aCompFeature)
616           return aCompFeature->numberOfSubs(true);
617         ModelAPI_ResultCompSolid* aCompRes = dynamic_cast<ModelAPI_ResultCompSolid*>(aObj);
618         if (aCompRes)
619           return aCompRes->numberOfSubs(true);
620         ModelAPI_ResultField* aFieldRes = dynamic_cast<ModelAPI_ResultField*>(aObj);
621         if (aFieldRes)
622           return aFieldRes->stepsSize();
623       }
624     }
625   }
626   return 0;
627 }
628
629 //******************************************************
630 int XGUI_DataModel::columnCount(const QModelIndex& theParent) const
631 {
632   return 3;
633 }
634
635 //******************************************************
636 QModelIndex XGUI_DataModel::index(int theRow, int theColumn, const QModelIndex &theParent) const
637 {
638   SessionPtr aSession = ModelAPI_Session::get();
639   DocumentPtr aRootDoc = aSession->moduleDocument();
640   int aNbFolders = foldersCount();
641
642   QModelIndex aIndex;
643
644   if (!theParent.isValid()) {
645     if (theRow < aNbFolders) // Return first level folder index
646       return createIndex(theRow, theColumn, (void*)Q_NULLPTR);
647     else { // return object under root index
648       std::string aType = myXMLReader->rootType();
649       int aObjId = theRow - aNbFolders;
650       if (aObjId < aRootDoc->size(aType, true)) {
651         ObjectPtr aObj = aRootDoc->object(aType, aObjId, true);
652         aIndex = objectIndex(aObj, theColumn);
653       }
654     }
655   } else {
656     quintptr aId = theParent.internalId();
657     int aParentPos = theParent.row();
658     if (aId == 0) { // return object index inside of first level of folders
659       std::string aType = myXMLReader->rootFolderType(aParentPos);
660       if (theRow < aRootDoc->size(aType)) {
661         ObjectPtr aObj = aRootDoc->object(aType, theRow, true);
662         aIndex = objectIndex(aObj, theColumn);
663       }
664     } else {
665       // It is an object which could have children
666       ModelAPI_Document* aDoc = getSubDocument(theParent.internalPointer());
667       if (aDoc) {
668         // It is a folder of sub-document
669         int aParentRow = aParentPos;
670         QIntList aMissedIdx = missedFolderIndexes(aDoc);
671         while (aMissedIdx.contains(aParentRow))
672           aParentRow++;
673         if (aParentRow < myXMLReader->subFoldersNumber()) {
674           std::string aType = myXMLReader->subFolderType(aParentRow);
675           if (theRow < aDoc->size(aType)) {
676             ObjectPtr aObj = aDoc->object(aType, theRow);
677             aIndex = objectIndex(aObj, theColumn);
678           }
679         }
680       } else {
681         ModelAPI_Object* aParentObj =
682           dynamic_cast<ModelAPI_Object*>((ModelAPI_Entity*)theParent.internalPointer());
683
684         // Check for Part feature
685         ResultPartPtr aPartRes = getPartResult(aParentObj);
686         if (aPartRes.get()) {
687           DocumentPtr aSubDoc = aPartRes->partDoc();
688           int aNbSubFolders = foldersCount(aSubDoc.get());
689           if (theRow < aNbSubFolders) { // Create a Folder of sub-document
690             aIndex = createIndex(theRow, theColumn, aSubDoc.get());
691           } else {
692             // this is an object under sub document root
693             std::string aType = myXMLReader->subType();
694             ObjectPtr aObj = aSubDoc->object(aType, theRow - aNbSubFolders, true);
695             aIndex = objectIndex(aObj, theColumn);
696           }
697         } else {
698           // Check for composite object
699           ModelAPI_CompositeFeature* aCompFeature =
700             dynamic_cast<ModelAPI_CompositeFeature*>(aParentObj);
701           if (aCompFeature) {
702             aIndex = objectIndex(aCompFeature->subFeature(theRow), theColumn);
703           } else {
704             ModelAPI_ResultCompSolid* aCompRes =
705               dynamic_cast<ModelAPI_ResultCompSolid*>(aParentObj);
706             if (aCompRes)
707               aIndex = objectIndex(aCompRes->subResult(theRow), theColumn);
708             else {
709               ModelAPI_ResultField* aFieldRes =
710                 dynamic_cast<ModelAPI_ResultField*>(aParentObj);
711               if (aFieldRes) {
712                 aIndex = createIndex(theRow, theColumn, aFieldRes->step(theRow));
713               }
714             }
715           }
716         }
717       }
718     }
719   }
720   return aIndex;
721 }
722
723 //******************************************************
724 static QModelIndex MYLastDeleted;
725 QModelIndex XGUI_DataModel::parent(const QModelIndex& theIndex) const
726 {
727   if (!theIndex.isValid())
728     return QModelIndex();
729   // To avoid additional request about index which was already deleted
730   if (theIndex == MYLastDeleted)
731     return QModelIndex();
732
733   SessionPtr aSession = ModelAPI_Session::get();
734   quintptr aId = theIndex.internalId();
735   if (aId != 0) { // The object is not a root folder
736     ModelAPI_Document* aDoc = getSubDocument(theIndex.internalPointer());
737     if (aDoc) {
738       // It is a folder of sub-document
739       return findDocumentRootIndex(aDoc);
740     }
741     ObjectPtr aObj = object(theIndex);
742     if (!aObj.get()) {
743       // It can b e a step of a field
744       ModelAPI_ResultField::ModelAPI_FieldStep* aStep =
745         dynamic_cast<ModelAPI_ResultField::ModelAPI_FieldStep*>
746         ((ModelAPI_Entity*)theIndex.internalPointer());
747       if (aStep) {
748         ModelAPI_ResultField* aField = aStep->field();
749         DocumentPtr aDoc = aSession->activeDocument();
750         ObjectPtr aFld;
751         for(int i = 0; i < aDoc->size(ModelAPI_ResultField::group()); i++) {
752           aFld = aDoc->object(ModelAPI_ResultField::group(), i);
753           if (aFld.get() == aField)
754             return objectIndex(aFld);
755         }
756       }
757       // To avoid additional request about index which was already deleted
758       // If deleted it causes a crash on delete object from Part
759       MYLastDeleted = theIndex;
760       return QModelIndex();
761     }
762     // Check is it object a sub-object of a complex object
763     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
764     if (aFeature.get()) {
765       CompositeFeaturePtr aCompFea = ModelAPI_Tools::compositeOwner(aFeature);
766       if (aCompFea.get()) {
767         return objectIndex(aCompFea);
768       }
769     }
770     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
771     if (aResult.get()) {
772       ResultCompSolidPtr aCompRes = ModelAPI_Tools::compSolidOwner(aResult);
773       if (aCompRes.get()) {
774         return objectIndex(aCompRes);
775       }
776     }
777     // Use as ordinary object
778     std::string aType = aObj->groupName();
779     DocumentPtr aRootDoc = aSession->moduleDocument();
780     DocumentPtr aSubDoc = aObj->document();
781     if (aSubDoc == aRootDoc) {
782       if ((aType == myXMLReader->rootType()) || (aType == ModelAPI_Folder::group()))
783         return QModelIndex();
784       else {
785         // return first level of folder index
786         int aFolderId = myXMLReader->rootFolderId(aType);
787         // Items in a one row must have the same parent
788         return createIndex(aFolderId, 1, (void*)Q_NULLPTR);
789       }
790     } else {
791       if ((aType == myXMLReader->subType()) || (aType == ModelAPI_Folder::group()))
792         return findDocumentRootIndex(aSubDoc.get());
793       else {
794         // return first level of folder index
795         int aFolderId = folderId(aType, aSubDoc.get());
796         // Items in a one row must have the same parent
797         return createIndex(aFolderId, 1, aSubDoc.get());
798       }
799     }
800   }
801   return QModelIndex();
802 }
803
804 //******************************************************
805 bool XGUI_DataModel::hasChildren(const QModelIndex& theParent) const
806 {
807   return rowCount(theParent) > 0;
808 }
809
810 //******************************************************
811 bool XGUI_DataModel::insertRows(int theRow, int theCount, const QModelIndex& theParent)
812 {
813   beginInsertRows(theParent, theRow, theRow + theCount - 1);
814   endInsertRows();
815
816   return true;
817 }
818
819 //******************************************************
820 bool XGUI_DataModel::removeRows(int theRow, int theCount, const QModelIndex& theParent)
821 {
822   beginRemoveRows(theParent, theRow, theRow + theCount - 1);
823   endRemoveRows();
824   return true;
825 }
826
827 //******************************************************
828 Qt::ItemFlags XGUI_DataModel::flags(const QModelIndex& theIndex) const
829 {
830   quintptr aIt = theIndex.internalId();
831   ModelAPI_Object* aObj = 0;
832   ModelAPI_Document* aDoc = 0;
833   SessionPtr aSession = ModelAPI_Session::get();
834   DocumentPtr aActiveDoc = aSession->activeDocument();
835
836   Qt::ItemFlags aNullFlag;
837   Qt::ItemFlags aDefaultFlag = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
838   Qt::ItemFlags aEditingFlag = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
839
840
841   if (aIt == 0) {
842     // Folders under root
843     DocumentPtr aRootDoc = aSession->moduleDocument();
844     if (aRootDoc != aActiveDoc)
845       return aDefaultFlag;
846   } else {
847     aDoc = getSubDocument(theIndex.internalPointer());
848     if (!aDoc)
849       aObj = dynamic_cast<ModelAPI_Object*>((ModelAPI_Entity*)theIndex.internalPointer());
850   }
851
852   if (aObj) {
853     // An object
854     if (aObj->isDisabled())
855       return theIndex.column() == 2? Qt::ItemIsSelectable : aNullFlag;
856
857     if (aSession->moduleDocument() != aObj->document())
858       if (aActiveDoc != aObj->document())
859         return theIndex.column() == 2? Qt::ItemIsSelectable : aNullFlag;
860
861     bool isCompositeSub = false;
862     // An object which is sub-object of a composite object can not be accessible in column 2
863     if (theIndex.column() == 2) {
864       ObjectPtr aObjPtr = aObj->data()->owner();
865       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjPtr);
866       if (aFeature.get()) {
867         CompositeFeaturePtr aCompFea = ModelAPI_Tools::compositeOwner(aFeature);
868         if (aCompFea.get())
869           isCompositeSub = true;
870       } else {
871         ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObjPtr);
872         if (aResult.get()) {
873           ResultCompSolidPtr aCompRes = ModelAPI_Tools::compSolidOwner(aResult);
874           if (aCompRes.get())
875             isCompositeSub = true;
876         }
877       }
878     }
879     if (isCompositeSub)
880       return Qt::ItemIsSelectable;
881
882     if (aObj->document() != aActiveDoc) {
883       // The object could be a root of sub-tree
884       ResultPartPtr aPartRes = getPartResult(aObj);
885       if (aPartRes.get()) {
886         if (aPartRes->partDoc() == aActiveDoc)
887           return aEditingFlag;
888       }
889       return aDefaultFlag;
890     }
891   } else if (aDoc) {
892     // A folder under sub-document
893     if (aActiveDoc.get() != aDoc)
894       return aNullFlag;
895   }
896   return aEditingFlag;
897 }
898
899 //******************************************************
900 QModelIndex
901   XGUI_DataModel::findDocumentRootIndex(const ModelAPI_Document* theDoc, int aColumn) const
902 {
903   SessionPtr aSession = ModelAPI_Session::get();
904   DocumentPtr aRootDoc = aSession->moduleDocument();
905   if (myXMLReader->isAttachToResult()) { // If document is attached to result
906     int aNb = aRootDoc->size(ModelAPI_ResultPart::group());
907     ObjectPtr aObj;
908     ResultPartPtr aPartRes;
909     for (int i = 0; i < aNb; i++) {
910       aObj = aRootDoc->object(ModelAPI_ResultPart::group(), i);
911       aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
912       if (aPartRes.get() && (aPartRes->partDoc().get() == theDoc)) {
913         int aRow = i;
914         if (myXMLReader->rootType() == ModelAPI_Feature::group()) {
915           aRow += foldersCount();
916         }
917         return createIndex(aRow, aColumn, aObj.get());
918       }
919     }
920   } else { // If document is attached to feature
921     int aNb = aRootDoc->size(ModelAPI_Feature::group(), true);
922     ObjectPtr aObj;
923     ResultPartPtr aPartRes;
924     for (int i = 0; i < aNb; i++) {
925       aObj = aRootDoc->object(ModelAPI_Feature::group(), i, true);
926       aPartRes = getPartResult(aObj.get());
927       if (aPartRes.get() && (aPartRes->partDoc().get() == theDoc)) {
928         int aRow = i;
929         if (myXMLReader->rootType() == ModelAPI_Feature::group())
930           aRow += foldersCount();
931         return createIndex(aRow, aColumn, aObj.get());
932       }
933     }
934   }
935   return QModelIndex();
936 }
937
938 //******************************************************
939 QModelIndex XGUI_DataModel::documentRootIndex(DocumentPtr theDoc, int theColumn) const
940 {
941   SessionPtr aSession = ModelAPI_Session::get();
942   DocumentPtr aRootDoc = aSession->moduleDocument();
943   if (theDoc == aRootDoc)
944     return QModelIndex();
945   else
946     return findDocumentRootIndex(theDoc.get(), theColumn);
947 }
948
949 //******************************************************
950 int XGUI_DataModel::foldersCount(ModelAPI_Document* theDoc) const
951 {
952   int aNb = 0;
953   SessionPtr aSession = ModelAPI_Session::get();
954   DocumentPtr aRootDoc = aSession->moduleDocument();
955   if ((theDoc == 0) || (theDoc == aRootDoc.get())) {
956     for (int i = 0; i < myXMLReader->rootFoldersNumber(); i++) {
957       if (myXMLReader->rootShowEmpty(i))
958         aNb++;
959       else {
960         if (aRootDoc->size(myXMLReader->rootFolderType(i)) > 0)
961           aNb++;
962       }
963     }
964   } else {
965     for (int i = 0; i < myXMLReader->subFoldersNumber(); i++) {
966       if (myXMLReader->subShowEmpty(i))
967         aNb++;
968       else {
969         if (theDoc->size(myXMLReader->subFolderType(i)) > 0)
970           aNb++;
971       }
972     }
973   }
974   return aNb;
975 }
976
977
978 //******************************************************
979 QIntList XGUI_DataModel::missedFolderIndexes(ModelAPI_Document* theDoc) const
980 {
981   QIntList aList;
982   SessionPtr aSession = ModelAPI_Session::get();
983   DocumentPtr aRootDoc = aSession->moduleDocument();
984   if ((theDoc == 0) || (theDoc == aRootDoc.get())) {
985     for (int i = 0; i < myXMLReader->rootFoldersNumber(); i++) {
986       if (!myXMLReader->rootShowEmpty(i)) {
987         if (aRootDoc->size(myXMLReader->rootFolderType(i)) == 0)
988           aList.append(i);
989       }
990     }
991   } else {
992     for (int i = 0; i < myXMLReader->subFoldersNumber(); i++) {
993       if (!myXMLReader->subShowEmpty(i)) {
994         if (theDoc->size(myXMLReader->subFolderType(i)) == 0)
995           aList.append(i);
996       }
997     }
998   }
999   return aList;
1000 }
1001
1002
1003 //******************************************************
1004 QStringList XGUI_DataModel::listOfShowNotEmptyFolders(bool fromRoot) const
1005 {
1006   QStringList aResult;
1007   if (fromRoot) {
1008     for (int i = 0; i < myXMLReader->rootFoldersNumber(); i++) {
1009       if (!myXMLReader->rootShowEmpty(i))
1010         aResult << myXMLReader->rootFolderType(i).c_str();
1011     }
1012   } else {
1013     for (int i = 0; i < myXMLReader->subFoldersNumber(); i++) {
1014       if (!myXMLReader->subShowEmpty(i))
1015         aResult << myXMLReader->subFolderType(i).c_str();
1016     }
1017   }
1018   return aResult;
1019 }
1020
1021 //******************************************************
1022 QModelIndex XGUI_DataModel::lastHistoryIndex() const
1023 {
1024   SessionPtr aSession = ModelAPI_Session::get();
1025   DocumentPtr aCurDoc = aSession->activeDocument();
1026   FeaturePtr aFeature = aCurDoc->currentFeature(true);
1027   if (aFeature.get()) {
1028     QModelIndex aInd = objectIndex(aFeature);
1029     return createIndex(aInd.row(), 2, aInd.internalPointer());
1030   } else {
1031     if (aCurDoc == aSession->moduleDocument())
1032       return createIndex(foldersCount() - 1, 2, -1);
1033     else
1034       return createIndex(foldersCount(aCurDoc.get()) - 1, 2, aCurDoc.get());
1035   }
1036 }
1037
1038 //******************************************************
1039 int XGUI_DataModel::folderId(std::string theType, ModelAPI_Document* theDoc) const
1040 {
1041   SessionPtr aSession = ModelAPI_Session::get();
1042   ModelAPI_Document* aDoc = theDoc;
1043   if (aDoc == 0)
1044     aDoc = aSession->moduleDocument().get();
1045
1046   bool aUseSubDoc = (aDoc != aSession->moduleDocument().get());
1047
1048   int aRes = -1;
1049   if (aUseSubDoc) {
1050     int aId = myXMLReader->subFolderId(theType);
1051     aRes = aId;
1052     for (int i = 0; i < aId; i++) {
1053       if (!myXMLReader->subShowEmpty(i)) {
1054         if (aDoc->size(myXMLReader->subFolderType(i)) == 0)
1055           aRes--;
1056       }
1057     }
1058   } else {
1059     int aId = myXMLReader->rootFolderId(theType);
1060     aRes = aId;
1061     for (int i = 0; i < aId; i++) {
1062       if (!myXMLReader->rootShowEmpty(i)) {
1063         if (aDoc->size(myXMLReader->rootFolderType(i)) == 0)
1064           aRes--;
1065       }
1066     }
1067   }
1068   return aRes;
1069 }
1070
1071 //******************************************************
1072 void XGUI_DataModel::rebuildBranch(int theRow, int theCount, const QModelIndex& theParent)
1073 {
1074   if (theCount > 0) {
1075     removeRows(theRow, theCount, theParent);
1076     insertRows(theRow, theCount, theParent);
1077   }
1078 }
1079
1080 //******************************************************
1081 //bool XGUI_DataModel::blockEventsProcessing(const bool theState)
1082 //{
1083 //  bool aPreviousState = myIsEventsProcessingBlocked;
1084 //  myIsEventsProcessingBlocked = theState;
1085 //  return aPreviousState;
1086 //}
1087
1088 //******************************************************
1089 XGUI_DataModel::VisibilityState
1090   XGUI_DataModel::getVisibilityState(const QModelIndex& theIndex) const
1091 {
1092   Qt::ItemFlags aFlags = theIndex.flags();
1093   if (aFlags == Qt::ItemFlags())
1094     return NoneState;
1095
1096   ObjectPtr aObj = object(theIndex);
1097   if (aObj.get()) {
1098     ResultPtr aResObj = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1099     if (aResObj.get()) {
1100       XGUI_Displayer* aDisplayer = myWorkshop->displayer();
1101       ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResObj);
1102       if (aCompRes.get()) {
1103         VisibilityState aState = aCompRes->numberOfSubs(true) == 0 ?
1104           (aDisplayer->isVisible(aCompRes)? Visible : Hidden) : NoneState;
1105         for (int i = 0; i < aCompRes->numberOfSubs(true); i++) {
1106           ResultPtr aSubRes = aCompRes->subResult(i, true);
1107           VisibilityState aS = aDisplayer->isVisible(aSubRes)? Visible : Hidden;
1108           if (aState == NoneState)
1109             aState = aS;
1110           else if (aState != aS) {
1111             aState = SemiVisible;
1112             break;
1113           }
1114         }
1115         return aState;
1116       } else {
1117         if (aDisplayer->isVisible(aResObj))
1118           return Visible;
1119         else
1120           return Hidden;
1121       }
1122     }
1123   }
1124   return NoneState;
1125 }