Salome HOME
Correction according to coding standards
[modules/shaper.git] / src / XGUI / XGUI_ObjectsBrowser.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_ObjectsBrowser.h"
22 #include "XGUI_Tools.h"
23 #include "XGUI_DataModel.h"
24
25 #include <ModelAPI_Data.h>
26 #include <ModelAPI_Session.h>
27 #include <ModelAPI_Document.h>
28 #include <ModelAPI_Tools.h>
29
30 #include <ModuleBase_Tools.h>
31
32 #include <QLayout>
33 #include <QLineEdit>
34 #include <QPixmap>
35 #include <QEvent>
36 #include <QMouseEvent>
37 #include <QAction>
38 #include <QStyledItemDelegate>
39 #include <QMessageBox>
40
41 #ifdef DEBUG_INDXES
42 #include <QToolTip>
43 #endif
44
45 /// Width of second column (minimum acceptable = 27)
46 #define FIRST_COL_WIDTH 30
47 #define SECOND_COL_WIDTH 30
48
49
50 /**
51 * \ingroup GUI
52 * Tree item delegate for definition of data in column items editor
53 */
54 class XGUI_TreeViewItemDelegate: public QStyledItemDelegate
55 {
56 public:
57   /// Constructor
58   /// \param theParent a parent of the delegate
59   XGUI_TreeViewItemDelegate(XGUI_DataTree* theParent):QStyledItemDelegate(theParent),
60     myTreedView(theParent) {}
61
62   /// Set data for item editor (name of the item)
63   /// \param editor a widget of editor
64   /// \param index the tree item index
65   virtual void  setEditorData ( QWidget* editor, const QModelIndex& index ) const
66   {
67     QLineEdit* aEditor = dynamic_cast<QLineEdit*>(editor);
68     if (aEditor) {
69       XGUI_DataModel* aModel = myTreedView->dataModel();
70       ObjectPtr aObj = aModel->object(index);
71       if (aObj.get() != NULL) {
72         aEditor->setText(aObj->data()->name().c_str());
73         return;
74       }
75     }
76     QStyledItemDelegate::setEditorData(editor, index);
77   }
78
79 private:
80   XGUI_DataTree* myTreedView;
81 };
82
83
84 XGUI_DataTree::XGUI_DataTree(QWidget* theParent)
85     : QTreeView(theParent)
86 {
87   setHeaderHidden(true);
88   setTreePosition(1);
89   setEditTriggers(QAbstractItemView::NoEditTriggers);
90   setSelectionBehavior(QAbstractItemView::SelectRows);
91   setSelectionMode(QAbstractItemView::ExtendedSelection);
92
93   setItemDelegateForColumn(1, new XGUI_TreeViewItemDelegate(this));
94
95   connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
96     SLOT(onDoubleClick(const QModelIndex&)));
97 }
98
99 XGUI_DataTree::~XGUI_DataTree()
100 {
101 }
102
103 XGUI_DataModel* XGUI_DataTree::dataModel() const
104 {
105   return static_cast<XGUI_DataModel*>(model());
106 }
107
108 void XGUI_DataTree::contextMenuEvent(QContextMenuEvent* theEvent)
109 {
110   emit contextMenuRequested(theEvent);
111 }
112
113 void XGUI_DataTree::commitData(QWidget* theEditor)
114 {
115   static int aEntrance = 0;
116   if (aEntrance == 0) {
117     // We have to check number of enter and exit of this function because it can be called
118     // recursively by Qt in order to avoid double modifying of a data
119     aEntrance = 1;
120     QLineEdit* aEditor = dynamic_cast<QLineEdit*>(theEditor);
121     if (aEditor) {
122       QString aName = aEditor->text();
123       QModelIndexList aIndexList = selectionModel()->selectedIndexes();
124       XGUI_DataModel* aModel = dataModel();
125       ObjectPtr aObj = aModel->object(aIndexList.first());
126
127       if (XGUI_Tools::canRename(aObj, aName)) {
128         SessionPtr aMgr = ModelAPI_Session::get();
129         aMgr->startOperation("Rename");
130         aObj->data()->setName(qPrintable(aName));
131         aMgr->finishOperation();
132       }
133     }
134   }
135   aEntrance = 0;
136 }
137
138 void XGUI_DataTree::clear()
139 {
140   dataModel()->clear();
141   reset();
142 }
143
144 void XGUI_DataTree::resizeEvent(QResizeEvent* theEvent)
145 {
146   QTreeView::resizeEvent(theEvent);
147   QSize aSize = theEvent->size();
148   if (aSize.isValid()) {
149     setColumnWidth(0, FIRST_COL_WIDTH);
150     setColumnWidth(1, aSize.width() - SECOND_COL_WIDTH - FIRST_COL_WIDTH - 12);
151     setColumnWidth(2, SECOND_COL_WIDTH);
152   }
153 }
154
155 #ifdef DEBUG_INDXES
156 void XGUI_DataTree::mousePressEvent(QMouseEvent* theEvent)
157 {
158   QTreeView::mousePressEvent(theEvent);
159   if (theEvent->button() != Qt::MidButton)
160     return;
161   QModelIndex aInd = indexAt(theEvent->pos());
162   QString aTxt =
163     QString("r=%1 c=%2 p=%3").arg(aInd.row()).arg(aInd.column()).arg((long)aInd.internalPointer());
164
165   QModelIndex aPar = aInd.parent();
166   QString aTxt1 =
167     QString("r=%1 c=%2 p=%3").arg(aPar.row()).arg(aPar.column()).arg((long)aPar.internalPointer());
168   QToolTip::showText(theEvent->globalPos(), aTxt + '\n' + aTxt1);
169 }
170 #endif
171
172 void XGUI_DataTree::mouseReleaseEvent(QMouseEvent* theEvent)
173 {
174   QTreeView::mouseReleaseEvent(theEvent);
175 #ifdef DEBUG_INDXES
176   if (theEvent->button() != Qt::MidButton)
177     return;
178   QToolTip::hideText();
179 #endif
180   if (theEvent->button() == Qt::LeftButton) {
181     QModelIndex aInd = indexAt(theEvent->pos());
182     if (aInd.column() == 0)
183       processEyeClick(aInd);
184   }
185 }
186
187 void XGUI_DataTree::processHistoryChange(const QModelIndex& theIndex)
188 {
189   SessionPtr aMgr = ModelAPI_Session::get();
190   // When operation is opened then we can not change history
191   if (aMgr->isOperation())
192     return;
193   XGUI_DataModel* aModel = dataModel();
194   if (aModel->flags(theIndex) == 0)
195     return;
196   ObjectPtr aObj = aModel->object(theIndex);
197
198   DocumentPtr aDoc = aMgr->activeDocument();
199
200   std::string aOpName = tr("History change").toStdString();
201   if (aObj.get()) {
202     if (aObj->document() != aDoc)
203       return;
204     aMgr->startOperation(aOpName);
205     aDoc->setCurrentFeature(std::dynamic_pointer_cast<ModelAPI_Feature>(aObj), true);
206     aMgr->finishOperation();
207   } else {
208     // Ignore clicks on folders outside current document
209     if ((theIndex.internalId() == 0) && (aDoc != aMgr->moduleDocument()))
210       // Clicked folder under root but active document is another
211       return;
212     if ((theIndex.internalId() != 0) && (aDoc.get() != theIndex.internalPointer()))
213       // Cliced not on active document folder
214       return;
215
216     aMgr->startOperation(aOpName);
217     aDoc->setCurrentFeature(FeaturePtr(), true);
218     aMgr->finishOperation();
219   }
220   QModelIndex aNewIndex = aModel->lastHistoryIndex();
221   QModelIndex aParent = theIndex.parent();
222   int aSize = aModel->rowCount(aParent);
223   for (int i = 0; i < aSize; i++) {
224     update(aModel->index(i, 0, aParent));
225     update(aModel->index(i, 1, aParent));
226     update(aModel->index(i, 2, aParent));
227   }
228 }
229
230 void XGUI_DataTree::processEyeClick(const QModelIndex& theIndex)
231 {
232   XGUI_DataModel* aModel = dataModel();
233   ObjectPtr aObj = aModel->object(theIndex);
234   if (aObj.get()) {
235     ResultPtr aResObj = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
236     if (aResObj.get()) {
237       aResObj->setDisplayed(!aResObj->isDisplayed());
238       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
239       update(theIndex);
240     }
241     // Update list of selected objects because this event happens after
242     // selection event in object browser
243     XGUI_ObjectsBrowser* aObjBrowser = qobject_cast<XGUI_ObjectsBrowser*>(parent());
244     if (aObjBrowser) {
245       aObjBrowser->onSelectionChanged();
246     }
247   }
248 }
249
250 void XGUI_DataTree::onDoubleClick(const QModelIndex& theIndex)
251 {
252   switch (theIndex.column()) {
253   case 2:
254     processHistoryChange(theIndex);
255     break;
256   }
257 }
258
259
260 //********************************************************************
261 //********************************************************************
262 //********************************************************************
263 XGUI_ActiveDocLbl::XGUI_ActiveDocLbl(const QString& theText, QWidget* theParent )
264   : QLabel(theText, theParent),
265   myPreSelectionStyle(""),
266   myNeutralStyle(""),
267   mySelectionStyle(""),
268   myIsSelected(false)
269 {
270 }
271
272 void XGUI_ActiveDocLbl::setTreeView(QTreeView* theView)
273 {
274   myTreeView = theView;
275   setFont(myTreeView->font());
276
277   QPalette aPalet = myTreeView->palette();
278   QColor aHighlight = aPalet.highlight().color();
279   QColor aHighlightText = aPalet.highlightedText().color();
280
281   myPreSelectionStyle = "QLabel {background-color: ";
282   myPreSelectionStyle += aHighlight.lighter(170).name() + "}";
283   //myPreSelectionStyle += "qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 white, stop:1 " +
284   //  aHighlight.lighter(170).name() + ");";
285   //myPreSelectionStyle += "border: 1px solid lightblue; border-radius: 2px }";
286
287   QString aName = aPalet.color(QPalette::Base).name();
288   myNeutralStyle = "QLabel { border: 1px solid " + aName + " }";
289
290
291 #if (!defined HAVE_SALOME) && (defined WIN32)
292   mySelectionStyle = "QLabel {background-color: ";
293   mySelectionStyle += "rgb(205, 232, 255); ";
294   //mySelectionStyle += "qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(236, 245, 255)";
295   //mySelectionStyle += ", stop:1 rgb(208, 229, 255));";
296   //mySelectionStyle += "border: 1px solid rgb(132, 172, 221); border-radius: 2px }";
297   mySelectionStyle += "border: 1px solid rgb(153, 209, 255) }";
298 #else
299   mySelectionStyle = "QLabel {background-color: " + aHighlight.name();
300   mySelectionStyle += "; color : " + aHighlightText.name() + "}";
301 #endif
302
303   myTreeView->viewport()->installEventFilter(this);
304 }
305
306
307 #if (!defined HAVE_SALOME) && (defined WIN32)
308 bool XGUI_ActiveDocLbl::event(QEvent* theEvent)
309 {
310   switch (theEvent->type()) {
311     case QEvent::Enter:
312       if (!myIsSelected)
313         setStyleSheet(myPreSelectionStyle);
314       break;
315     case QEvent::Leave:
316       if (!myIsSelected)
317         setStyleSheet(myNeutralStyle);
318       break;
319   }
320   return QLabel::event(theEvent);
321 }
322 #endif
323
324 bool XGUI_ActiveDocLbl::eventFilter(QObject* theObj, QEvent* theEvent)
325 {
326   if (theObj == myTreeView->viewport()) {
327     if (theEvent->type() == QEvent::MouseButtonRelease)
328       unselect();
329   }
330   return QLabel::eventFilter(theObj, theEvent);
331 }
332
333 static bool MYClearing = false;
334 void XGUI_ActiveDocLbl::mouseReleaseEvent( QMouseEvent* e)
335 {
336   MYClearing = true;
337   myIsSelected = true;
338   setStyleSheet(mySelectionStyle);
339   // We can not block signals because on
340   // clear selection the View state will not be updated
341   myTreeView->clearSelection();
342   QLabel::mouseReleaseEvent(e);
343   MYClearing = false;
344 }
345
346 void XGUI_ActiveDocLbl::unselect()
347 {
348   if (!MYClearing) {
349     myIsSelected = false;
350     setStyleSheet(myNeutralStyle);
351   }
352 }
353
354
355 //********************************************************************
356 //********************************************************************
357 //********************************************************************
358 XGUI_ObjectsBrowser::XGUI_ObjectsBrowser(QWidget* theParent, XGUI_Workshop* theWorkshop)
359     : QWidget(theParent), myDocModel(0), myWorkshop(theWorkshop)
360 {
361   QVBoxLayout* aLayout = new QVBoxLayout(this);
362   ModuleBase_Tools::zeroMargins(aLayout);
363   aLayout->setSpacing(0);
364
365   QWidget* aLabelWgt = new QWidget(this);
366   aLabelWgt->setAutoFillBackground(true);
367
368   aLayout->addWidget(aLabelWgt);
369   QHBoxLayout* aLabelLay = new QHBoxLayout(aLabelWgt);
370   ModuleBase_Tools::zeroMargins(aLabelLay);
371   aLabelLay->setSpacing(0);
372
373   QLabel* aLbl = new QLabel(aLabelWgt);
374   aLbl->setPixmap(QPixmap(":pictures/assembly.png"));
375   aLbl->setMargin(2);
376   // Do not paint background of the label (in order to show icon)
377   aLbl->setAutoFillBackground(false);
378
379   aLabelLay->addWidget(aLbl);
380
381   SessionPtr aMgr = ModelAPI_Session::get();
382   DocumentPtr aDoc = aMgr->moduleDocument();
383
384   myActiveDocLbl = new XGUI_ActiveDocLbl(tr("Part set"), aLabelWgt);
385 //  myActiveDocLbl->setReadOnly(true);
386 //  myActiveDocLbl->setFrame(false);
387   myActiveDocLbl->setContextMenuPolicy(Qt::CustomContextMenu);
388
389   aLabelLay->addWidget(myActiveDocLbl);
390   aLabelLay->setStretch(1, 1);
391
392   myTreeView = new XGUI_DataTree(this);
393   myTreeView->setFrameShape(QFrame::NoFrame);
394   aLayout->addWidget(myTreeView);
395
396   QPalette aTreePalet = myTreeView->palette();
397   QColor aTreeBack = aTreePalet.color(QPalette::Base);
398
399   QPalette aPalet;
400   aPalet.setColor(QPalette::Base, aTreeBack);
401   aPalet.setColor(QPalette::Window, aTreeBack);
402   aLabelWgt->setPalette(aPalet);
403
404   myDocModel = new XGUI_DataModel(this);
405   connect(myDocModel, SIGNAL(modelAboutToBeReset()), SLOT(onBeforeReset()));
406   connect(myDocModel, SIGNAL(treeRebuilt()), SLOT(onAfterModelReset()));
407
408   connect(myTreeView, SIGNAL(contextMenuRequested(QContextMenuEvent*)), this,
409           SLOT(onContextMenuRequested(QContextMenuEvent*)));
410 }
411
412 //***************************************************
413 XGUI_ObjectsBrowser::~XGUI_ObjectsBrowser()
414 {
415 }
416
417 void XGUI_ObjectsBrowser::setXMLReader(Config_DataModelReader* theReader)
418 {
419   myDocModel->setXMLReader(theReader);
420   myTreeView->setModel(myDocModel);
421
422   // It has to be done after setting of model
423   myActiveDocLbl->setTreeView(myTreeView);
424
425   QItemSelectionModel* aSelMod = myTreeView->selectionModel();
426   connect(aSelMod, SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
427           this, SLOT(onSelectionChanged(const QItemSelection&, const QItemSelection&)));
428 }
429
430 //***************************************************
431 void XGUI_ObjectsBrowser::onContextMenuRequested(QContextMenuEvent* theEvent)
432 {
433   QModelIndexList aIndexes;
434   QObjectPtrList aSelectedData = selectedObjects(&aIndexes);
435   bool toEnable = false;
436
437   if (aSelectedData.size() == 1) {
438     QModelIndex aSelected = myTreeView->indexAt(theEvent->pos());
439     if (!aIndexes.contains(aSelected))
440       return; // menu is called on non selected item
441
442     Qt::ItemFlags aFlags = dataModel()->flags(aIndexes.first());
443     toEnable = ((aFlags & Qt::ItemIsEditable) != 0);
444   }
445   foreach(QAction* aCmd, actions()) {
446     aCmd->setEnabled(toEnable);
447   }
448   emit contextMenuRequested(theEvent);
449 }
450
451 //***************************************************
452 void XGUI_ObjectsBrowser::onLabelContextMenuRequested(const QPoint& thePnt)
453 {
454   myTreeView->selectionModel()->clearSelection();
455   //Empty feature pointer means that selected root document
456   foreach(QAction* aCmd, actions()) {
457     aCmd->setEnabled(true);
458   }
459   QContextMenuEvent aEvent(QContextMenuEvent::Mouse, thePnt, myActiveDocLbl->mapToGlobal(thePnt));
460   emit contextMenuRequested(&aEvent);
461 }
462
463 //***************************************************
464 void XGUI_ObjectsBrowser::onEditItem()
465 {
466   QObjectPtrList aSelectedData = selectedObjects();
467   if (aSelectedData.size() > 0) {
468     ObjectPtr anObject = aSelectedData.first();
469     if (anObject.get()) {  // Selection happens in TreeView
470       // check whether the object can be renamed. There should not be parts which are not loaded
471       std::set<FeaturePtr> aFeatures;
472       aFeatures.insert(ModelAPI_Feature::feature(anObject));
473       if (!XGUI_Tools::canRemoveOrRename((QWidget*)parent(), aFeatures))
474         return;
475
476       // Find index which corresponds the feature
477       QModelIndex aIndex;
478       foreach(QModelIndex aIdx, selectedIndexes()) {
479         ObjectPtr aFea = dataModel()->object(aIdx);
480         if (dataModel()->object(aIdx)->isSame(anObject)) {
481           aIndex = aIdx;
482           break;
483         }
484       }
485       if (aIndex.isValid()) {
486         myTreeView->setCurrentIndex(aIndex);
487         myTreeView->edit(aIndex);
488       }
489       return;
490     }
491   }
492 }
493
494 //***************************************************
495 QModelIndexList XGUI_ObjectsBrowser::expandedItems(const QModelIndex& theParent) const
496 {
497   QModelIndexList aIndexes;
498   QModelIndex aIndex;
499   for (int i = 0; i < myDocModel->rowCount(theParent); i++) {
500     aIndex = myDocModel->index(i, 0, theParent);
501     if (myDocModel->hasChildren(aIndex)) {
502       if (myTreeView->isExpanded(aIndex)) {
503         aIndexes.append(aIndex);
504         QModelIndexList aSubIndexes = expandedItems(aIndex);
505         if (!aSubIndexes.isEmpty())
506           aIndexes.append(aSubIndexes);
507       }
508     }
509   }
510   return aIndexes;
511 }
512
513 //***************************************************
514 void XGUI_ObjectsBrowser::rebuildDataTree()
515 {
516   myDocModel->rebuildDataTree();
517   update();
518 }
519
520 //***************************************************
521 void XGUI_ObjectsBrowser::setObjectsSelected(const QObjectPtrList& theObjects)
522 {
523   QList<QModelIndex> theIndexes;
524   QItemSelectionModel* aSelectModel = myTreeView->selectionModel();
525   aSelectModel->clear();
526
527   foreach(ObjectPtr aFeature, theObjects)
528   {
529     QModelIndex aIndex = myDocModel->objectIndex(aFeature);
530     if (aIndex.isValid()) {
531       aSelectModel->select(aIndex, QItemSelectionModel::Select);
532     }
533   }
534 }
535
536 //***************************************************
537 void XGUI_ObjectsBrowser::clearContent()
538 {
539   myTreeView->clear();
540 }
541
542 //***************************************************
543 void XGUI_ObjectsBrowser::onSelectionChanged(const QItemSelection& theSelected,
544                                        const QItemSelection& theDeselected)
545 {
546   onSelectionChanged();
547 }
548
549 //***************************************************
550 void XGUI_ObjectsBrowser::onSelectionChanged()
551 {
552   emit selectionChanged();
553 }
554
555 //***************************************************
556 QObjectPtrList XGUI_ObjectsBrowser::selectedObjects(QModelIndexList* theIndexes) const
557 {
558   QObjectPtrList aList;
559   QModelIndexList aIndexes = selectedIndexes();
560   XGUI_DataModel* aModel = dataModel();
561   QModelIndexList::const_iterator aIt;
562   for (aIt = aIndexes.constBegin(); aIt != aIndexes.constEnd(); ++aIt) {
563     if ((*aIt).column() == 1) {
564       ObjectPtr aObject = aModel->object(*aIt);
565       if (aObject) {
566         aList.append(aObject);
567         if (theIndexes)
568           theIndexes->append(*aIt);
569       }
570     }
571   }
572   return aList;
573 }
574
575 void XGUI_ObjectsBrowser::onBeforeReset()
576 {
577   myExpandedItems = expandedItems();
578 }
579
580 void XGUI_ObjectsBrowser::onAfterModelReset()
581 {
582   foreach(QModelIndex aIndex, myExpandedItems) {
583     myTreeView->setExpanded(aIndex, true);
584   }
585 }
586
587 std::list<bool> XGUI_ObjectsBrowser::getStateForDoc(DocumentPtr theDoc) const
588 {
589   std::list<bool> aStates;
590   XGUI_DataModel* aModel = dataModel();
591   QModelIndex aRootIdx = aModel->documentRootIndex(theDoc);
592   int aNbChild = aModel->rowCount(aRootIdx);
593   for (int i = 0; i < aNbChild; i++) {
594     QModelIndex aIdx = aModel->index(i, 1, aRootIdx);
595     aStates.push_back(myTreeView->isExpanded(aIdx));
596   }
597   return aStates;
598 }
599
600 void XGUI_ObjectsBrowser::setStateForDoc(DocumentPtr theDoc, const std::list<bool>& theStates)
601 {
602   if (theStates.size() == 0)
603     return;
604   XGUI_DataModel* aModel = dataModel();
605   QModelIndex aRootIdx = aModel->documentRootIndex(theDoc);
606   int aNbChild = aModel->rowCount(aRootIdx);
607
608   std::list<bool>::const_iterator aIt;
609   int i = 0;
610   for (aIt = theStates.cbegin(); aIt != theStates.cend(); aIt++, i++) {
611     if (i >= aNbChild )
612       break;
613     QModelIndex aIdx = aModel->index(i, 0, aRootIdx);
614     myTreeView->setExpanded(aIdx, (*aIt));
615   }
616 }