Salome HOME
Porting to the current version of TInspector.
[modules/shaper.git] / src / XGUI / XGUI_Workshop.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_Workshop.h"
22
23 #include "XGUI_ActionsMgr.h"
24 #include "XGUI_MenuMgr.h"
25 #include "XGUI_ColorDialog.h"
26 #include "XGUI_DeflectionDialog.h"
27 #include "XGUI_ContextMenuMgr.h"
28 #include "XGUI_Displayer.h"
29 #include "XGUI_ErrorDialog.h"
30 #include "XGUI_ErrorMgr.h"
31 #include "XGUI_ModuleConnector.h"
32 #include "XGUI_ObjectsBrowser.h"
33 #include "XGUI_OperationMgr.h"
34 #include "XGUI_PropertyPanel.h"
35 #include "XGUI_SalomeConnector.h"
36 #include "XGUI_Selection.h"
37 #include "XGUI_SelectionMgr.h"
38 #include "XGUI_Tools.h"
39 #include "XGUI_ViewerProxy.h"
40 #include "XGUI_WorkshopListener.h"
41 #include <XGUI_CustomPrs.h>
42 #include <XGUI_HistoryMenu.h>
43 #include <XGUI_QtEvents.h>
44 #include <XGUI_DataModel.h>
45
46 #ifndef HAVE_SALOME
47 #include <AppElements_Button.h>
48 #include <AppElements_Command.h>
49 #include <AppElements_MainMenu.h>
50 #include <AppElements_MainWindow.h>
51 #include <AppElements_MenuGroupPanel.h>
52 #include <AppElements_Viewer.h>
53 #include <AppElements_Workbench.h>
54 #endif
55
56 #include <ModelAPI_AttributeDocRef.h>
57 #include <ModelAPI_AttributeIntArray.h>
58 #include <ModelAPI_AttributeDouble.h>
59 #include <ModelAPI_Data.h>
60 #include <ModelAPI_Events.h>
61 #include <ModelAPI_Feature.h>
62 #include <ModelAPI_Object.h>
63 #include <ModelAPI_ResultBody.h>
64 #include <ModelAPI_ResultConstruction.h>
65 #include <ModelAPI_ResultGroup.h>
66 #include <ModelAPI_ResultParameter.h>
67 #include <ModelAPI_ResultField.h>
68 #include <ModelAPI_Session.h>
69 #include <ModelAPI_Validator.h>
70 #include <ModelAPI_ResultCompSolid.h>
71 #include <ModelAPI_Tools.h>
72
73 //#include <PartSetPlugin_Part.h>
74
75 #include <Events_Loop.h>
76 #include <Events_InfoMessage.h>
77 #include <Events_LongOp.h>
78
79 #include <ModuleBase_IModule.h>
80 #include <ModuleBase_IViewer.h>
81 #include <ModuleBase_Operation.h>
82 #include <ModuleBase_OperationDescription.h>
83 #include <ModuleBase_PageBase.h>
84 #include <ModuleBase_Preferences.h>
85 #include <ModuleBase_SelectionValidator.h>
86 #include <ModuleBase_Tools.h>
87 #include <ModuleBase_WidgetFactory.h>
88 #include <ModuleBase_OperationFeature.h>
89 #include <ModuleBase_OperationAction.h>
90 #include <ModuleBase_PagedContainer.h>
91 #include <ModuleBase_WidgetValidated.h>
92 #include <ModuleBase_ModelWidget.h>
93 #include <ModuleBase_ResultPrs.h>
94
95 #include <Config_Common.h>
96 #include <Config_FeatureMessage.h>
97 #include <Config_ModuleReader.h>
98 #include <Config_PointerMessage.h>
99 #include <Config_PropManager.h>
100 #include <Config_DataModelReader.h>
101 #include <Config_Translator.h>
102 #include <Config_WidgetAPI.h>
103 #include <Config_Keywords.h>
104
105 #include <SUIT_ResourceMgr.h>
106
107 #include <AIS_Trihedron.hxx>
108 #ifdef BEFORE_TRIHEDRON_PATCH
109 #include <AIS_Point.hxx>
110 #include <AIS_Axis.hxx>
111 #endif
112
113 #include <QApplication>
114 #include <QFileDialog>
115 #include <QMessageBox>
116 #include <QMdiSubWindow>
117 #include <QMainWindow>
118 #include <QPushButton>
119 #include <QDockWidget>
120 #include <QLayout>
121 #include <QThread>
122 #include <QObject>
123 #include <QMenu>
124 #include <QToolButton>
125 #include <QAction>
126 #include <QDesktopWidget>
127
128 #include <iterator>
129
130 #ifdef TINSPECTOR
131 #include <CDF_Session.hxx>
132 #include <CDF_Application.hxx>
133 #include <TInspector_Communicator.hxx>
134 #include <VInspector_CallBack.hxx>
135 static TInspector_Communicator* MyTCommunicator;
136 static Handle(VInspector_CallBack) MyVCallBack;
137
138 #endif
139
140 #ifdef _DEBUG
141 #include <QDebug>
142 #include <iostream>
143 #endif
144
145 #ifdef WIN32
146 #include <windows.h>
147 #else
148 #include <dlfcn.h>
149 #endif
150
151 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
152
153 //#define DEBUG_DELETE
154 //#define DEBUG_FEATURE_NAME
155 //#define DEBUG_CLEAN_HISTORY
156
157 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
158     : QObject(),
159       myCurrentDir(QString()),
160       myModule(NULL),
161       mySalomeConnector(theConnector),
162       myPropertyPanel(0),
163       myObjectBrowser(0),
164       myDisplayer(0)
165       //myViewerSelMode(TopAbs_FACE)
166 {
167   mySelector = new XGUI_SelectionMgr(this);
168   myModuleConnector = new XGUI_ModuleConnector(this);
169   myOperationMgr = new XGUI_OperationMgr(this, 0);
170   ModuleBase_IWorkshop* aWorkshop = moduleConnector();
171   // Has to be defined first in order to get errors and messages from other components
172   myEventsListener = new XGUI_WorkshopListener(aWorkshop);
173
174   SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
175 #ifndef HAVE_SALOME
176   myMainWindow = new AppElements_MainWindow();
177
178   bool aCloc = aResMgr->booleanValue("language", "locale", true);
179   if (aCloc)
180     QLocale::setDefault( QLocale::c() );
181   else
182     QLocale::setDefault( QLocale::system() );
183 #endif
184   QString aPath = Config_XMLReader::pluginConfigFile().c_str();
185   QDir aDir(aPath);
186
187   // Load translations
188   QStringList aLangs;
189   aLangs << "*_en.ts"; // load by default eng translations
190   QString aCurrLang = aResMgr->stringValue("language", "language", "en");
191   if(aCurrLang != "en") {
192     aLangs << "*_" + aCurrLang + ".ts"; // then replace with translated files
193   }
194
195   foreach(QString aLang, aLangs) {
196     QStringList aFilters;
197     aFilters << aLang;
198     QStringList aTsFiles = aDir.entryList(aFilters, QDir::Files);
199     foreach(QString aFileName, aTsFiles) {
200       Config_Translator::load(aFileName.toStdString());
201     }
202   }
203
204   myDataModelXMLReader = new Config_DataModelReader();
205   //myDataModelXMLReader->readAll();
206
207   myDisplayer = new XGUI_Displayer(this);
208
209   connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
210
211   myActionsMgr = new XGUI_ActionsMgr(this);
212   myMenuMgr = new XGUI_MenuMgr(this);
213   myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
214   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
215   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
216           SLOT(onContextMenuCommand(const QString&, bool)));
217
218   myViewerProxy = new XGUI_ViewerProxy(this);
219   //connect(myViewerProxy, SIGNAL(selectionChanged()),
220   //        myActionsMgr,  SLOT(updateOnViewSelection()));
221
222   myOperationMgr->setWorkshop(aWorkshop);
223
224   myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
225
226   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
227           SLOT(onOperationResumed(ModuleBase_Operation*)));
228   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
229           SLOT(onOperationStopped(ModuleBase_Operation*)));
230   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
231           SLOT(onOperationCommitted(ModuleBase_Operation*)));
232   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
233           SLOT(onOperationAborted(ModuleBase_Operation*)));
234
235 #ifndef HAVE_SALOME
236   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
237   onTrihedronVisibilityChanged(true);
238 #endif
239
240   connect(myEventsListener, SIGNAL(errorOccurred(std::shared_ptr<Events_InfoMessage>)),
241           myErrorDlg, SLOT(addError(std::shared_ptr<Events_InfoMessage>)));
242
243   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
244   //                                 Config_Prop::Color, "225,225,225");
245
246   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
247                                    Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
248   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
249                                    Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
250   Config_PropManager::registerProp("Visualization", "result_construction_color",
251                                    "Construction color",
252                                    Config_Prop::Color,
253                                    ModelAPI_ResultConstruction::DEFAULT_COLOR());
254   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
255                                    Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
256   Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
257                                    Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
258
259   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "face-selection", true))
260     myViewerSelMode.append(TopAbs_FACE);
261   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "edge-selection", true))
262     myViewerSelMode.append(TopAbs_EDGE);
263   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "vertex-selection", true))
264     myViewerSelMode.append(TopAbs_VERTEX);
265   //IMP: an attempt to use result selection with other selection modes
266   myViewerSelMode.append(ModuleBase_ResultPrs::Sel_Result);//TopAbs_VERTEX);
267   myViewerSelMode.append(TopAbs_COMPSOLID);
268 }
269
270 //******************************************************
271 XGUI_Workshop::~XGUI_Workshop(void)
272 {
273 #ifdef _DEBUG
274 #ifdef MISSED_TRANSLATION
275   // Save Missed translations
276   Config_Translator::saveMissedTranslations();
277 #endif
278 #endif
279
280   delete myDisplayer;
281   delete myDataModelXMLReader;
282 }
283
284 //******************************************************
285 void XGUI_Workshop::startApplication()
286 {
287   //Initialize event listening
288   myEventsListener->initializeEventListening();
289
290   myDataModelXMLReader->readAll();
291   initMenu();
292
293   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
294                                    Config_Prop::Directory, "");
295
296
297   registerValidators();
298
299   // Calling of  loadCustomProps before activating module is required
300   // by Config_PropManger to restore user-defined path to plugins
301   ModuleBase_Preferences::loadCustomProps();
302   createModule();
303
304 #ifndef HAVE_SALOME
305   myMainWindow->show();
306   updateCommandStatus();
307 #endif
308
309   onNew();
310
311   myViewerProxy->connectViewProxy();
312   connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
313           SLOT(onTrihedronVisibilityChanged(bool)));
314
315   emit applicationStarted();
316 }
317
318 void XGUI_Workshop::activateModule()
319 {
320   myModule->activateSelectionFilters();
321
322   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
323     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
324   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
325     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
326
327   updateCommandStatus();
328
329   // TODO: get default selection mode
330
331   // activate visualized objects in the viewer
332   activateObjectsSelection(displayer()->displayedObjects());
333   myOperationMgr->activate();
334 }
335
336 void XGUI_Workshop::deactivateModule()
337 {
338   myModule->deactivateSelectionFilters();
339
340   // remove internal displayer filter
341   displayer()->deactivateSelectionFilters();
342
343   disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
344     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
345   disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
346     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
347
348   XGUI_Displayer* aDisplayer = displayer();
349   QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
350   aDisplayer->deactivateObjects(aDisplayed, true);
351   Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
352   Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aDisplayer->getTrihedron());
353   /// deactivate trihedron in selection modes
354   TColStd_ListOfInteger aTColModes;
355   aContext->ActivatedModes(aTrihedron, aTColModes);
356   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
357   for (; itr.More(); itr.Next() ) {
358     Standard_Integer aMode = itr.Value();
359     aContext->Deactivate(aTrihedron, aMode);
360   }
361 #ifdef BEFORE_TRIHEDRON_PATCH
362   /// Trihedron problem: objects stayed in the viewer, should be removed manually
363   /// otherwise in SALOME happens crash by HideAll in the viewer
364   aContext->Remove(aTrihedron->Position(), true);
365   aContext->Remove(aTrihedron->Axis(), true);
366   aContext->Remove(aTrihedron->XAxis(), true);
367   aContext->Remove(aTrihedron->YAxis(), true);
368 #endif
369
370   myOperationMgr->deactivate();
371 }
372
373 //******************************************************
374 void XGUI_Workshop::initMenu()
375 {
376   myContextMenuMgr->createActions();
377
378 #ifdef HAVE_SALOME
379   // Create only Undo, Redo commands
380   QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
381                                                         tr("Undo last command"),
382                                                         QIcon(":pictures/undo.png"),
383                                                         QKeySequence::Undo, false,
384                                                         "MEN_DESK_EDIT");
385   QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
386   salomeConnector()->addActionInToolbar( aAction,aToolBarTitle  );
387
388   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
389   addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
390
391   aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
392                                               QIcon(":pictures/redo.png"), QKeySequence::Redo,
393                                               false, "MEN_DESK_EDIT");
394   salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
395
396   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
397   addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
398
399   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
400   //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"),
401   //                                            tr("Rebuild data objects"),
402   //                                            QIcon(":pictures/rebuild.png"), QKeySequence(),
403   //                                            false, "MEN_DESK_EDIT");
404   //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
405
406   //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
407   //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
408
409   aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."),
410                                              tr("Export the current document into a native file"),
411                                               QIcon(), QKeySequence(),
412                                               false, "MEN_DESK_FILE");
413   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
414
415   aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."),
416                                               tr("Import native file"),
417                                               QIcon(), QKeySequence(),
418                                               false, "MEN_DESK_FILE");
419   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
420   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
421
422 #else
423   // File commands group
424   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
425
426   AppElements_Command* aCommand;
427
428   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
429                                 QIcon(":pictures/save.png"), QKeySequence::Save);
430   aCommand->connectTo(this, SLOT(onSave()));
431   //aCommand->disable();
432
433   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
434                                 QIcon(":pictures/save.png"), QKeySequence());
435   aCommand->connectTo(this, SLOT(onSaveAs()));
436
437   QString aUndoId = "UNDO_CMD";
438   aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
439                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
440   aCommand->connectTo(this, SLOT(onUndo()));
441   AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
442   addHistoryMenu(aUndoButton,
443                  SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
444                  SLOT(onUndo(int)));
445
446   QString aRedoId = "REDO_CMD";
447   aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
448                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
449   aCommand->connectTo(this, SLOT(onRedo()));
450   AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
451   addHistoryMenu(aRedoButton,
452                  SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
453                  SLOT(onRedo(int)));
454
455   //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
456   //  QIcon(":pictures/rebuild.png"), QKeySequence());
457   //aCommand->connectTo(this, SLOT(onRebuild()));
458
459   //aCommand->disable();
460
461   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
462                                 QIcon(":pictures/open.png"), QKeySequence::Open);
463   aCommand->connectTo(this, SLOT(onOpen()));
464
465   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
466                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
467   aCommand->connectTo(this, SLOT(onPreferences()));
468
469   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
470                                 QIcon(":pictures/close.png"), QKeySequence::Close);
471   aCommand->connectTo(this, SLOT(onExit()));
472 #endif
473 }
474
475 #ifndef HAVE_SALOME
476 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
477 {
478   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
479   return aMenuBar->addWorkbench(theName);
480 }
481 #endif
482
483 //******************************************************
484 QMainWindow* XGUI_Workshop::desktop() const
485 {
486 #ifdef HAVE_SALOME
487   return salomeConnector()->desktop();
488 #else
489   return myMainWindow;
490 #endif
491 }
492
493 //******************************************************
494 void XGUI_Workshop::onStartWaiting()
495 {
496   if (Events_LongOp::isPerformed()) {
497     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
498   }
499 }
500
501 //******************************************************
502 void XGUI_Workshop::onAcceptActionClicked()
503 {
504   QAction* anAction = dynamic_cast<QAction*>(sender());
505   XGUI_OperationMgr* anOperationMgr = operationMgr();
506   if (anOperationMgr) {
507     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
508                                                     (anOperationMgr->currentOperation());
509     if (aFOperation) {
510       //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
511       myOperationMgr->commitOperation();
512     }
513   }
514 }
515
516 //******************************************************
517 void XGUI_Workshop::onPreviewActionClicked()
518 {
519   ModuleBase_IPropertyPanel* aPanel = propertyPanel();
520   if (aPanel) {
521     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
522     if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
523       anActiveWidget->storeValue();
524     }
525   }
526   std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
527                 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
528   Events_Loop::loop()->send(aMsg);
529 }
530
531 //******************************************************
532 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
533 {
534   if (!myModule->canActivateSelection(theObject)) {
535     if (myDisplayer->isActive(theObject)) {
536       QObjectPtrList anObjects;
537       anObjects.append(theObject);
538       myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
539     }
540   }
541 }
542
543 //******************************************************
544 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
545 {
546   bool aHasNested = false;
547   std::string aFeatureKind = theFeature->getKind();
548 #ifdef HAVE_SALOME
549     XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
550     if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
551       aHasNested = true;
552 #else
553     AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
554     AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
555     if (aCommand && aCommand->button()->additionalButtonWidget())
556       aHasNested = true;
557 #endif
558   return aHasNested;
559 }
560
561 void XGUI_Workshop::fillPropertyPanel(ModuleBase_Operation* theOperation)
562 {
563   ModuleBase_OperationFeature* aFOperation =
564     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
565   if (!aFOperation)
566     return;
567
568   showPropertyPanel();
569   myPropertyPanel->cleanContent();
570
571   QList<ModuleBase_ModelWidget*> aWidgets;
572   if (!module()->createWidgets(theOperation, aWidgets)) {
573     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
574     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
575     aFactory.createWidget(myPropertyPanel->contentWidget());
576     aWidgets = aFactory.getModelWidgets();
577   }
578
579   // check compatibility of feature and widgets
580   FeaturePtr aFeature = aFOperation->feature();
581   std::string aFeatureKind = aFeature->getKind();
582   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
583     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
584       std::string anErrorMsg = "The feature '%1' has no attribute '%2' used by widget '%3'.";
585       Events_InfoMessage("XGUI_Workshop", anErrorMsg)
586         .arg(aFeatureKind).arg(aWidget->attributeID())
587         .arg(aWidget->metaObject()->className()).send();
588       myPropertyPanel->cleanContent();
589       return;
590     }
591   }
592   // for performance purpose, flush should be done after all controls are filled
593   bool isUpdateFlushed = false;
594   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
595     bool isStoreValue = !aFOperation->isEditOperation() &&
596                         !aWidget->getDefaultValue().empty() &&
597                         !aWidget->isComputedDefault();
598     aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
599     if (!isStoreValue)
600       aWidget->restoreValue();
601     aWidget->enableFocusProcessing();
602   }
603   ModuleBase_Tools::flushUpdated(aFeature);
604
605   // update visible state of Preview button
606   std::shared_ptr<Config_FeatureMessage> aFeatureInfo;
607 #ifdef HAVE_SALOME
608   aFeatureInfo = mySalomeConnector->featureInfo(aFeatureKind.c_str());
609 #else
610   AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
611   AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
612   if (aCommand)
613     aFeatureInfo = aCommand->featureMessage();
614 #endif
615   bool anIsAutoPreview = true;
616   if (aFeatureInfo.get())
617     anIsAutoPreview = aFeatureInfo->isAutoPreview();
618   else {
619     std::string aXmlCfg, aDescription;
620     module()->getXMLRepresentation(aFeatureKind, aXmlCfg, aDescription);
621     ModuleBase_WidgetFactory aFactory(aXmlCfg, moduleConnector());
622     anIsAutoPreview = aFactory.widgetAPI()->getBooleanAttribute(FEATURE_AUTO_PREVIEW, true);
623   }
624
625   if (!anIsAutoPreview) {
626     myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
627     // send signal about preview should not be computed automatically, click on preview
628     // button should initiate it
629     std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
630                   new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
631     Events_Loop::loop()->send(aMsg);
632   }
633   myPropertyPanel->setModelWidgets(aWidgets);
634   aFOperation->setPropertyPanel(myPropertyPanel);
635
636   myModule->propertyPanelDefined(theOperation);
637
638 #ifndef DEBUG_FEATURE_NAME
639   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
640 #else
641   std::string aFeatureName = aFeature->name();
642   myPropertyPanel->setWindowTitle(QString("%1: %2")
643     .arg(theOperation->getDescription()->description())
644     .arg(aFeatureName.c_str()));
645 #endif
646
647   myErrorMgr->setPropertyPanel(myPropertyPanel);
648 }
649
650 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
651 {
652   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
653   if (aPropertyPanel) {
654     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
655     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
656        myModule->connectToPropertyPanel(aWidget, isToConnect);
657        if (isToConnect) {
658         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
659         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
660         connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
661        }
662       else {
663         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
664         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
665         disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
666       }
667     }
668   }
669 }
670
671 //******************************************************
672 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
673 {
674   setGrantedFeatures(theOperation);
675
676   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
677     fillPropertyPanel(theOperation);
678     connectToPropertyPanel(true);
679   }
680   updateCommandStatus();
681
682   myModule->operationResumed(theOperation);
683 }
684
685
686 //******************************************************
687 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
688 {
689   updateCommandStatus();
690
691   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
692                                                                         (theOperation);
693   if (!aFOperation)
694     return;
695
696   ModuleBase_ISelection* aSel = mySelector->selection();
697   QObjectPtrList aObj = aSel->selectedPresentations();
698   //!< No need for property panel
699   hidePropertyPanel();
700   myPropertyPanel->cleanContent();
701
702   connectToPropertyPanel(false);
703   myModule->operationStopped(aFOperation);
704
705   // the deactivated objects of the current operation should be activated back.
706   // They were deactivated on operation start or an object redisplay
707   QObjectPtrList anObjects;
708   FeaturePtr aFeature = aFOperation->feature();
709   if (aFeature.get()) { // feature may be not created (plugin load fail)
710     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
711       anObjects.append(aFeature);
712     std::list<ResultPtr> aResults;
713     ModelAPI_Tools::allResults(aFeature, aResults);
714     std::list<ResultPtr>::const_iterator aIt;
715     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
716       ResultPtr anObject = *aIt;
717       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
718         anObjects.append(anObject);
719       }
720     }
721   }
722   activateObjectsSelection(anObjects);
723 }
724
725
726 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
727 {
728   myModule->operationCommitted(theOperation);
729 }
730
731 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
732 {
733   myModule->operationAborted(theOperation);
734 }
735
736 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
737 {
738   ModuleBase_OperationFeature* aFOperation =
739     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
740   if (!aFOperation)
741     return;
742
743   QStringList aGrantedIds;
744   if (isSalomeMode()) {
745     const std::shared_ptr<Config_FeatureMessage>& anInfo =
746                          mySalomeConnector->featureInfo(theOperation->id());
747     if (anInfo.get())
748       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
749                                    .split(" ", QString::SkipEmptyParts);
750   }
751   else
752     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
753
754   ModuleBase_IModule* aModule = module();
755   if (aModule)
756     aModule->grantedOperationIds(theOperation, aGrantedIds);
757
758   aFOperation->setGrantedOperationIds(aGrantedIds);
759 }
760
761 //******************************************************
762 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
763 {
764   QApplication::restoreOverrideCursor();
765   SessionPtr aMgr = ModelAPI_Session::get();
766
767   std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
768   std::list<DocumentPtr>::const_iterator aIt;
769   for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
770     std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
771     (*aIt)->storeNodesState(aState);
772   }
773
774   aMgr->save(theName.toLatin1().constData(), theFileNames);
775
776   QApplication::restoreOverrideCursor();
777 }
778
779 //******************************************************
780 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
781 {
782   setGrantedFeatures(theOperation);
783   if (!theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
784     updateCommandStatus();
785   }
786   else {
787     myModule->operationStarted(theOperation);
788   }
789 }
790
791 //******************************************************
792 void XGUI_Workshop::onOpen()
793 {
794   if(!myOperationMgr->abortAllOperations())
795     return;
796   //save current file before close if modified
797   SessionPtr aSession = ModelAPI_Session::get();
798   if (aSession->isModified()) {
799     //TODO(sbh): re-launch the app?
800     int anAnswer = QMessageBox::question(
801         desktop(), tr("Save current file"),
802         tr("The document is modified, save before opening another?"),
803         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
804     if (anAnswer == QMessageBox::Save) {
805       onSave();
806     } else if (anAnswer == QMessageBox::Cancel) {
807       return;
808     }
809     myCurrentDir = "";
810   }
811
812   //show file dialog, check if readable and open
813   QString aDirectory = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
814   openDirectory(aDirectory);
815 }
816
817 //******************************************************
818 void XGUI_Workshop::openDirectory(const QString& theDirectory)
819 {
820   myCurrentDir = theDirectory;
821   if (myCurrentDir.isEmpty())
822     return;
823
824   QFileInfo aFileInfo(myCurrentDir);
825   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
826     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
827     myCurrentDir = "";
828     return;
829   }
830
831   QApplication::setOverrideCursor(Qt::WaitCursor);
832   module()->closeDocument();
833   SessionPtr aSession = ModelAPI_Session::get();
834   aSession->closeAll();
835   aSession->load(myCurrentDir.toLatin1().constData());
836   myObjectBrowser->rebuildDataTree();
837
838   // Open first level of data tree
839   DocumentPtr aRootDoc = aSession->moduleDocument();
840   std::list<bool> aStates;
841   aRootDoc->restoreNodesState(aStates);
842   myObjectBrowser->setStateForDoc(aRootDoc, aStates);
843
844   updateCommandStatus();
845 #ifndef HAVE_SALOME
846   myMainWindow->setCurrentDir(myCurrentDir, true);
847 #endif
848   QApplication::restoreOverrideCursor();
849 }
850
851 //******************************************************
852 void XGUI_Workshop::onNew()
853 {
854   QApplication::setOverrideCursor(Qt::WaitCursor);
855   if (objectBrowser() == 0) {
856     createDockWidgets();
857     mySelector->connectViewers();
858   }
859   myViewerProxy->connectToViewer();
860   showObjectBrowser();
861 #ifndef HAVE_SALOME
862   myMainWindow->showPythonConsole();
863   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
864   aWnd->showMaximized();
865   updateCommandStatus();
866 #endif
867   myContextMenuMgr->connectViewer();
868   QApplication::restoreOverrideCursor();
869 }
870
871 #ifndef HAVE_SALOME
872 //******************************************************
873 void XGUI_Workshop::onExit()
874 {
875   SessionPtr aMgr = ModelAPI_Session::get();
876   if (aMgr->isModified()) {
877     int anAnswer = QMessageBox::question(
878         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
879         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
880     if (anAnswer == QMessageBox::Save) {
881       bool saved = onSave();
882       if (!saved) {
883         return;
884       }
885     } else if (anAnswer == QMessageBox::Cancel) {
886       return;
887     }
888   }
889   qApp->exit();
890 }
891
892 //******************************************************
893 void XGUI_Workshop::onPreferences()
894 {
895   ModuleBase_Prefs aModif;
896   ModuleBase_Preferences::editPreferences(aModif);
897   if (aModif.size() > 0) {
898     QString aSection;
899     foreach (ModuleBase_Pref aPref, aModif)
900     {
901       aSection = aPref.first;
902       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
903         myMainWindow->viewer()->updateFromResources();
904       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
905         myMainWindow->menuObject()->updateFromResources();
906       }
907     }
908     displayer()->redisplayObjects();
909   }
910 }
911 #endif
912
913 //******************************************************
914 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
915 {
916   XGUI_Displayer* aDisplayer = displayer();
917   if (aDisplayer)
918     aDisplayer->displayTrihedron(theState);
919 }
920
921 //******************************************************
922 bool XGUI_Workshop::onSave()
923 {
924   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
925     return false;
926   if (myCurrentDir.isEmpty()) {
927     return onSaveAs();
928   }
929   std::list<std::string> aFiles;
930   saveDocument(myCurrentDir, aFiles);
931   updateCommandStatus();
932 #ifndef HAVE_SALOME
933     myMainWindow->setModifiedState(false);
934 #endif
935   return true;
936 }
937
938 //******************************************************
939 bool XGUI_Workshop::onSaveAs()
940 {
941   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
942     return false;
943   QFileDialog dialog(desktop());
944   dialog.setWindowTitle(tr("Select directory to save files..."));
945   dialog.setFileMode(QFileDialog::Directory);
946   dialog.setFilter(QDir::AllDirs);
947   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
948   dialog.setViewMode(QFileDialog::Detail);
949
950   if (!dialog.exec()) {
951     return false;
952   }
953
954   QString aTempDir = dialog.selectedFiles().first();
955   QDir aDir(aTempDir);
956   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
957     int answer = QMessageBox::question(
958         desktop(),
959         // Title of the dialog which asks user if he wants to save study
960         // in existing non-empty folder
961         tr("Save"),
962         tr("The directory already contains some files, save anyway?"),
963         QMessageBox::Save | QMessageBox::Cancel);
964     if (answer == QMessageBox::Cancel) {
965       return false;
966     }
967   }
968   myCurrentDir = aTempDir;
969 #ifndef HAVE_SALOME
970     myMainWindow->setCurrentDir(myCurrentDir, false);
971     myMainWindow->setModifiedState(false);
972 #endif
973   return onSave();
974 }
975
976 //******************************************************
977 void XGUI_Workshop::onUndo(int theTimes)
978 {
979   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
980   SessionPtr aMgr = ModelAPI_Session::get();
981   std::list<std::string> aUndoList = aMgr->undoList();
982   if (aMgr->isOperation()) {
983     /// this is important for nested operations
984     /// when sketch operation is active, this condition is false and
985     /// the sketch operation is not aborted
986     operationMgr()->onAbortOperation();
987   }
988   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
989   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
990     aMgr->undo();
991     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
992       myObjectBrowser->rebuildDataTree();
993   }
994
995   operationMgr()->updateApplyOfOperations();
996   updateCommandStatus();
997 }
998
999 //******************************************************
1000 void XGUI_Workshop::onRedo(int theTimes)
1001 {
1002   // the viewer update should be blocked in order to avoid the features blinking. For the created
1003   // feature a results are created, the flush of the created signal caused the viewer redisplay for
1004   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1005   // until redo of all possible objects happens
1006   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1007
1008   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1009   SessionPtr aMgr = ModelAPI_Session::get();
1010   std::list<std::string> aRedoList = aMgr->redoList();
1011   if (aMgr->isOperation()) {
1012     /// this is important for nested operations
1013     /// when sketch operation is active, this condition is false and
1014     /// the sketch operation is not aborted
1015     operationMgr()->onAbortOperation();
1016   }
1017   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
1018   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
1019     aMgr->redo();
1020     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1021       myObjectBrowser->rebuildDataTree();
1022   }
1023   operationMgr()->updateApplyOfOperations();
1024   updateCommandStatus();
1025
1026   // unblock the viewer update functionality and make update on purpose
1027   myDisplayer->enableUpdateViewer(isUpdateEnabled);
1028   myDisplayer->updateViewer();
1029 }
1030
1031 //******************************************************
1032 //void XGUI_Workshop::onRebuild()
1033 //{
1034 //  SessionPtr aMgr = ModelAPI_Session::get();
1035 //  bool aWasOperation = aMgr->isOperation(); // keep this value
1036 //  if (!aWasOperation) {
1037 //    aMgr->startOperation("Rebuild");
1038 //  }
1039 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1040 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1041 //    new Events_Message(aRebuildEvent, this)));
1042 //  if (!aWasOperation) {
1043 //    aMgr->finishOperation();
1044 //  }
1045 //  updateCommandStatus();
1046 //}
1047
1048 //******************************************************
1049 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1050 {
1051   ModuleBase_ModelWidget* anActiveWidget = 0;
1052   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1053   if (anOperation) {
1054     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1055     if (aPanel)
1056       anActiveWidget = aPanel->activeWidget();
1057   }
1058   if (anActiveWidget)
1059     operationMgr()->onValidateOperation();
1060
1061   myModule->widgetStateChanged(thePreviousState);
1062 }
1063
1064 //******************************************************
1065 void XGUI_Workshop::onValuesChanged()
1066 {
1067   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1068   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1069     return;
1070
1071   ModuleBase_ModelWidget* anActiveWidget = 0;
1072   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1073   if (anOperation) {
1074     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1075     if (aPanel)
1076       anActiveWidget = aPanel->activeWidget();
1077   }
1078   if (anActiveWidget) {
1079     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1080                                                                            (anActiveWidget);
1081     if (aWidgetValidated)
1082       aWidgetValidated->clearValidatedCash();
1083   }
1084 }
1085
1086 void XGUI_Workshop::onWidgetObjectUpdated()
1087 {
1088   operationMgr()->onValidateOperation();
1089 }
1090
1091 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1092 {
1093   QString libName = QString::fromStdString(library(theModule.toStdString()));
1094   if (libName.isEmpty()) {
1095     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1096     return 0;
1097   }
1098
1099   QString err;
1100   CREATE_FUNC crtInst = 0;
1101
1102 #ifdef WIN32
1103   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1104   if (!modLib) {
1105     LPVOID lpMsgBuf;
1106     ::FormatMessage(
1107         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1108         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1109     QString aMsg((char*) &lpMsgBuf);
1110     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1111     ::LocalFree(lpMsgBuf);
1112   } else {
1113     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1114     if (!crtInst) {
1115       LPVOID lpMsgBuf;
1116       ::FormatMessage(
1117           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1118               | FORMAT_MESSAGE_IGNORE_INSERTS,
1119           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1120       QString aMsg((char*) &lpMsgBuf);
1121       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1122       ::LocalFree(lpMsgBuf);
1123     }
1124   }
1125 #else
1126   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1127   if ( !modLib ) {
1128     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1129   } else {
1130     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1131     if ( !crtInst ) {
1132       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1133     }
1134   }
1135 #endif
1136
1137   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1138
1139   if (!err.isEmpty()) {
1140     if (desktop()) {
1141       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1142     } else {
1143       qWarning(qPrintable(err));
1144     }
1145   }
1146   return aModule;
1147 }
1148
1149 //******************************************************
1150 bool XGUI_Workshop::createModule()
1151 {
1152   Config_ModuleReader aModuleReader;
1153   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1154   myModule = loadModule(moduleName);
1155   if (!myModule)
1156     return false;
1157
1158   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1159   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1160   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1161   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1162
1163   myModule->createFeatures();
1164 #ifdef HAVE_SALOME
1165   salomeConnector()->createFeatureActions();
1166 #endif
1167   //myActionsMgr->update();
1168   return true;
1169 }
1170
1171 //******************************************************
1172 void XGUI_Workshop::updateCommandStatus()
1173 {
1174   QList<QAction*> aCommands;
1175 #ifdef HAVE_SALOME
1176     aCommands = salomeConnector()->commandList();
1177 #else
1178     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1179     foreach (AppElements_Command* aCmd, aMenuBar->features())
1180       aCommands.append(aCmd);
1181 #endif
1182   SessionPtr aMgr = ModelAPI_Session::get();
1183   if (aMgr->hasModuleDocument()) {
1184     foreach(QAction* aCmd, aCommands) {
1185       QString aId = aCmd->data().toString();
1186       if (aId == "UNDO_CMD")
1187         aCmd->setEnabled(myModule->canUndo());
1188       else if (aId == "REDO_CMD")
1189         aCmd->setEnabled(myModule->canRedo());
1190       else
1191         // Enable all commands
1192         aCmd->setEnabled(true);
1193     }
1194     updateHistory();
1195   } else {
1196     foreach(QAction* aCmd, aCommands) {
1197       QString aId = aCmd->data().toString();
1198       if (aId == "NEW_CMD")
1199         aCmd->setEnabled(true);
1200       else if (aId == "EXIT_CMD")
1201         aCmd->setEnabled(true);
1202       else
1203         aCmd->setEnabled(false);
1204     }
1205   }
1206   myActionsMgr->updateCommandsStatus();
1207   emit commandStatusUpdated();
1208 }
1209
1210 void XGUI_Workshop::updateHistory()
1211 {
1212   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1213   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1214   emit updateUndoHistory(aUndoRes);
1215
1216   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1217   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1218   emit updateRedoHistory(aRedoRes);
1219 }
1220
1221 //******************************************************
1222 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1223 {
1224   QDockWidget* aObjDock = new QDockWidget(theParent);
1225   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1226                             Qt::RightDockWidgetArea |
1227                             Qt::BottomDockWidgetArea);
1228   aObjDock->setWindowTitle(tr("Object browser"));
1229   aObjDock->setStyleSheet(
1230       "::title { position: relative; padding-left: 5px; text-align: left center }");
1231   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1232   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1233   myModule->customizeObjectBrowser(myObjectBrowser);
1234   aObjDock->setWidget(myObjectBrowser);
1235
1236   myContextMenuMgr->connectObjectBrowser();
1237   return aObjDock;
1238 }
1239
1240 //******************************************************
1241 /*
1242  * Creates dock widgets, places them in corresponding area
1243  * and tabifies if necessary.
1244  */
1245 void XGUI_Workshop::createDockWidgets()
1246 {
1247   QMainWindow* aDesktop = desktop();
1248   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1249   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1250   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1251   myPropertyPanel->setupActions(myActionsMgr);
1252   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1253                                    Qt::RightDockWidgetArea |
1254                                    Qt::BottomDockWidgetArea);
1255   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1256   hidePropertyPanel();  ///<! Invisible by default
1257   hideObjectBrowser();
1258   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1259   myPropertyPanel->installEventFilter(myOperationMgr);
1260
1261   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1262   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1263
1264   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1265   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1266
1267   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1268   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1269
1270   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1271           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1272   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1273           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1274 }
1275
1276 //******************************************************
1277 void XGUI_Workshop::showPropertyPanel()
1278 {
1279   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1280   ///<! Restore ability to close panel from the window's menu
1281   aViewAct->setEnabled(true);
1282   myPropertyPanel->show();
1283   myPropertyPanel->raise();
1284
1285   // The next code is necessary to made the property panel the active window
1286   // in order to operation manager could process key events of the panel.
1287   // otherwise they are ignored. It happens only if the same(activateWindow) is
1288   // not happened by property panel activation(e.g. resume operation of Sketch)
1289   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1290 }
1291
1292 //******************************************************
1293 void XGUI_Workshop::hidePropertyPanel()
1294 {
1295   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1296   ///<! Do not allow to show empty property panel
1297   aViewAct->setEnabled(false);
1298   myPropertyPanel->hide();
1299
1300   // the property panel is active window of the desktop, when it is
1301   // hidden, it is undefined which window becomes active. By this reason
1302   // it is defined to perform the desktop as the active window.
1303   // in SALOME mode, workstack made the PyConsole the active window,
1304   // set the focus on it. As a result, shortcuts of the application, like
1305   // are processed by this console. For example Undo actions.
1306   // It is possible that this code is to be moved to SHAPER package
1307   QMainWindow* aDesktop = desktop();
1308   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1309 }
1310
1311 //******************************************************
1312 void XGUI_Workshop::showObjectBrowser()
1313 {
1314   if (!isSalomeMode())
1315     myObjectBrowser->parentWidget()->show();
1316 }
1317
1318 //******************************************************
1319 void XGUI_Workshop::hideObjectBrowser()
1320 {
1321   if (!isSalomeMode())
1322     myObjectBrowser->parentWidget()->hide();
1323 }
1324
1325 //******************************************************
1326 void XGUI_Workshop::salomeViewerSelectionChanged()
1327 {
1328   emit salomeViewerSelection();
1329 }
1330
1331 //**************************************************************
1332 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1333 {
1334   return mySalomeConnector->viewer();
1335 }
1336
1337 //**************************************************************
1338 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1339 {
1340   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1341   if (theId == "DELETE_CMD")
1342     deleteObjects();
1343   else if (theId == "CLEAN_HISTORY_CMD")
1344     cleanHistory();
1345   else if (theId == "MOVE_CMD")
1346     moveObjects();
1347   else if (theId == "COLOR_CMD")
1348     changeColor(aObjects);
1349   else if (theId == "DEFLECTION_CMD")
1350     changeDeflection(aObjects);
1351   else if (theId == "SHOW_CMD") {
1352     showObjects(aObjects, true);
1353     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1354     updateCommandStatus();
1355   }
1356   else if (theId == "HIDE_CMD") {
1357     showObjects(aObjects, false);
1358     updateCommandStatus();
1359   }
1360   else if (theId == "SHOW_ONLY_CMD") {
1361     showOnlyObjects(aObjects);
1362     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1363     updateCommandStatus();
1364   }
1365   else if (theId == "SHADING_CMD")
1366     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1367   else if (theId == "WIREFRAME_CMD")
1368     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1369   else if (theId == "HIDEALL_CMD") {
1370     QObjectPtrList aList = myDisplayer->displayedObjects();
1371     foreach (ObjectPtr aObj, aList) {
1372       if (module()->canEraseObject(aObj))
1373         aObj->setDisplayed(false);
1374     }
1375     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1376 #ifdef HAVE_SALOME
1377     //issue #2159 Hide all incomplete behavior
1378     viewer()->eraseAll();
1379 #endif
1380     updateCommandStatus();
1381   } else if (theId == "SELECT_VERTEX_CMD") {
1382     setViewerSelectionMode(TopAbs_VERTEX);
1383   } else if (theId == "SELECT_EDGE_CMD") {
1384     setViewerSelectionMode(TopAbs_EDGE);
1385   } else if (theId == "SELECT_FACE_CMD") {
1386     setViewerSelectionMode(TopAbs_FACE);
1387   } else if (theId == "SELECT_RESULT_CMD") {
1388     //setViewerSelectionMode(-1);
1389     //IMP: an attempt to use result selection with other selection modes
1390     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1391     setViewerSelectionMode(TopAbs_COMPSOLID);
1392   } else if (theId == "SHOW_RESULTS_CMD") {
1393     highlightResults(aObjects);
1394   } else if (theId == "SHOW_FEATURE_CMD") {
1395     highlightFeature(aObjects);
1396   }
1397 #ifdef TINSPECTOR
1398   else if (theId == "TINSPECTOR_VIEW") {
1399     Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1400     if (!anApplication.IsNull())
1401     {
1402       if (!MyTCommunicator)
1403       {
1404         MyTCommunicator = new TInspector_Communicator();
1405
1406         NCollection_List<Handle(Standard_Transient)> aParameters;
1407         aParameters.Append(anApplication);
1408         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1409         if (!aContext.IsNull())
1410           aParameters.Append(aContext);
1411
1412         MyVCallBack = new VInspector_CallBack();
1413         myDisplayer->setCallBack(MyVCallBack);
1414         #ifndef HAVE_SALOME
1415         AppElements_Viewer* aViewer = mainWindow()->viewer();
1416         if (aViewer)
1417           aViewer->setCallBack(MyVCallBack);
1418         #endif
1419         aParameters.Append(MyVCallBack);
1420
1421         MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1422
1423         MyTCommunicator->Init(aParameters);
1424         MyTCommunicator->Activate("SMBrowser"); // to have button in TInspector
1425         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1426         MyTCommunicator->Activate("TKDFBrowser");
1427       }
1428       MyTCommunicator->SetVisible(true);
1429     }
1430   }
1431 #endif
1432 }
1433
1434 //**************************************************************
1435 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1436 {
1437   if (theMode == -1)
1438     myViewerSelMode.clear();
1439   else {
1440     if (myViewerSelMode.contains(theMode))
1441       myViewerSelMode.removeAll(theMode);
1442     else
1443       myViewerSelMode.append(theMode);
1444   }
1445   activateObjectsSelection(myDisplayer->displayedObjects());
1446 }
1447
1448 //**************************************************************
1449 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1450 {
1451   QIntList aModes;
1452   module()->activeSelectionModes(aModes);
1453   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1454     aModes.append(myViewerSelMode);
1455   myDisplayer->activateObjects(aModes, theList);
1456 }
1457
1458 //**************************************************************
1459 void XGUI_Workshop::deleteObjects()
1460 {
1461   ModuleBase_IModule* aModule = module();
1462   // allow the module to delete objects, do nothing if it has succeed
1463   if (aModule->deleteObjects()) {
1464     updateCommandStatus();
1465     return;
1466   }
1467
1468   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1469   if (!myOperationMgr->abortAllOperations())
1470     return;
1471
1472   bool hasResult = false;
1473   bool hasFeature = false;
1474   bool hasParameter = false;
1475   bool hasCompositeOwner = false;
1476   bool hasResultInHistory = false;
1477   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1478                                  hasResultInHistory);
1479   if (!(hasFeature || hasParameter))
1480     return;
1481
1482   // delete objects
1483   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1484   std::set<FeaturePtr> aFeatures;
1485   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1486   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1487
1488   bool aDone = false;
1489   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1490   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1491   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1492
1493   operationMgr()->startOperation(anOpAction);
1494
1495   std::set<FeaturePtr> aFeatureRefsToDelete;
1496   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1497     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1498     // It is necessary to clear selection in order to avoid selection changed event during
1499     // deletion and negative consequences connected with processing of already deleted items
1500     mySelector->clearSelection();
1501
1502     if (!aFeatureRefsToDelete.empty())
1503       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1504     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1505   }
1506   if (aDone)
1507     operationMgr()->commitOperation();
1508   else
1509     operationMgr()->abortOperation(operationMgr()->currentOperation());
1510 }
1511
1512 //**************************************************************
1513 void addRefsToFeature(const FeaturePtr& theFeature,
1514                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1515                       std::set<FeaturePtr>& theReferences)
1516 {
1517   //if (theReferences.find(theFeature) != theReferences.end())
1518   //  return;
1519   if (theMainList.find(theFeature) == theMainList.end())
1520     return; // this feature is not in the selection list, so exists without references to it
1521   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1522
1523   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1524                                        aLast = aMainReferences.end();
1525   for (; anIt != aLast; anIt++) {
1526     FeaturePtr aRefFeature = *anIt;
1527     if (theReferences.find(aRefFeature) == theReferences.end())
1528       theReferences.insert(aRefFeature);
1529     addRefsToFeature(aRefFeature, theMainList, theReferences);
1530   }
1531 }
1532
1533 //**************************************************************
1534 void XGUI_Workshop::cleanHistory()
1535 {
1536   if (!myOperationMgr->abortAllOperations())
1537     return;
1538
1539   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1540   std::set<FeaturePtr> aFeatures;
1541   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1542
1543 #ifdef DEBUG_CLEAN_HISTORY
1544   QStringList anInfo;
1545   std::set<FeaturePtr>::const_iterator aFIt;
1546   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1547     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1548     anInfo.append(aFeature->name().c_str());
1549   }
1550   QString anInfoStr = anInfo.join(";\t");
1551   qDebug(QString("cleanHistory for: [%1] - %2").
1552     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1553 #endif
1554
1555   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1556   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1557   // find for each object whether all reference values are in the map as key, that means that there
1558   // is no other reference in the model to this object, so it might be removed by cleaning history
1559   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - cann't be deleted, dependency to bool_1
1560   // ext_1(bool_1, sk_3)  - cann't be deleted, dependency to bool_1
1561   // vertex_1()
1562   // sk_2(ext_2) + (bool_1)  - cann't be deleted, dependency to bool_1
1563   // ext_2(bool_1)  - cann't be deleted, dependency to bool_1
1564   // sk_3()
1565   // Information: bool_1 is not selected
1566   std::set<FeaturePtr> anUnusedObjects;
1567   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1568                                                               aMainLast = aReferences.end();
1569   for (; aMainIt != aMainLast; aMainIt++) {
1570     FeaturePtr aMainListFeature = aMainIt->first;
1571     std::set<FeaturePtr> aMainRefList = aMainIt->second;
1572     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
1573                                                   aRefLast = aMainRefList.end();
1574     bool aFeatureOutOfTheList = false;
1575     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1576       FeaturePtr aRefFeature = *aRefIt;
1577       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1578     }
1579     if (!aFeatureOutOfTheList)
1580       anUnusedObjects.insert(aMainListFeature);
1581   }
1582
1583 #ifdef DEBUG_CLEAN_HISTORY
1584   anInfo.clear();
1585   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1586     FeaturePtr aFeature = *aFIt;
1587     anInfo.append(aFeature->name().c_str());
1588   }
1589   qDebug(QString("unused objects: [%1] - %2").
1590     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1591 #endif
1592
1593   // warn about the references remove, break the delete operation if the user chose it
1594   if (!anUnusedObjects.empty()) {
1595     QStringList aNames;
1596     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1597       aNames.append(aFeature->name().c_str());
1598     }
1599     aNames.sort();
1600     QString anUnusedNames = aNames.join(", ");
1601
1602     QString anActionId = "CLEAN_HISTORY_CMD";
1603     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1604
1605     QMessageBox aMessageBox(desktop());
1606     aMessageBox.setWindowTitle(aDescription);
1607     aMessageBox.setIcon(QMessageBox::Warning);
1608     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1609     aMessageBox.setDefaultButton(QMessageBox::No);
1610
1611     const char* aKeyStr = "Unused features are the following: "
1612                           "%1.\nThese features will be deleted.\nWould you like to continue?";
1613     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
1614     aMessageBox.setText(aText);
1615     if (aMessageBox.exec() == QMessageBox::No)
1616       return;
1617
1618     // 1. start operation
1619     aDescription += "by deleting of " +
1620       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1621     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1622     operationMgr()->startOperation(anOpAction);
1623
1624     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1625     // It is necessary to clear selection in order to avoid selection changed event during
1626     // deletion and negative consequences connected with processing of already deleted items
1627     mySelector->clearSelection();
1628
1629     std::set<FeaturePtr> anIgnoredFeatures;
1630     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
1631       operationMgr()->commitOperation();
1632     }
1633     else {
1634       operationMgr()->abortOperation(operationMgr()->currentOperation());
1635     }
1636   }
1637   else {
1638     QString anActionId = "CLEAN_HISTORY_CMD";
1639     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1640
1641     QMessageBox aMessageBox(desktop());
1642     aMessageBox.setWindowTitle(aDescription);
1643     aMessageBox.setIcon(QMessageBox::Warning);
1644     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1645     aMessageBox.setDefaultButton(QMessageBox::No);
1646
1647     QString aText;
1648     aMessageBox.setStandardButtons(QMessageBox::Ok);
1649     aMessageBox.setDefaultButton(QMessageBox::Ok);
1650
1651     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1652     aMessageBox.setText(aText);
1653
1654     if (aMessageBox.exec() == QMessageBox::No)
1655       return;
1656   }
1657 }
1658
1659 //**************************************************************
1660 void XGUI_Workshop::moveObjects()
1661 {
1662   if (!myOperationMgr->abortAllOperations())
1663     return;
1664
1665   SessionPtr aMgr = ModelAPI_Session::get();
1666
1667   QString anActionId = "MOVE_CMD";
1668   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1669   aMgr->startOperation(aDescription.toStdString());
1670
1671   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1672   // It is necessary to clear selection in order to avoid selection changed event during
1673   // moving and negative consequences connected with processing of already moved items
1674   mySelector->clearSelection();
1675   // check whether the object can be moved. There should not be parts which are not loaded
1676   std::set<FeaturePtr> aFeatures;
1677   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1678   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
1679     return;
1680
1681   DocumentPtr anActiveDocument = aMgr->activeDocument();
1682   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1683   std::set<FeaturePtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1684   for (; anIt != aLast; anIt++) {
1685     FeaturePtr aFeature = *anIt;
1686     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
1687       continue;
1688
1689     anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1690     aCurrentFeature = anActiveDocument->currentFeature(true);
1691   }
1692   aMgr->finishOperation();
1693 }
1694
1695 //**************************************************************
1696 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
1697 {
1698   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1699   std::set<FeaturePtr> aFeatures;
1700   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
1701
1702   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
1703 }
1704
1705 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1706 {
1707   bool isFoundResultType = false;
1708   foreach(ObjectPtr anObj, theObjects)
1709   {
1710     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1711     if (aResult.get() == NULL)
1712       continue;
1713
1714     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1715     if (isFoundResultType)
1716       break;
1717   }
1718   return isFoundResultType;
1719 }
1720
1721 //**************************************************************
1722 // Returns the list of all features for theDocument and all features of
1723 // all nested parts.
1724 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1725 {
1726   std::list<FeaturePtr> aResultList;
1727   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1728   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1729     // The order of appending features of the part and the part itself is important
1730
1731     // Append features from a part feature
1732     std::list<ResultPtr> aResults;
1733     ModelAPI_Tools::allResults(aFeature, aResults);
1734     foreach (const ResultPtr& aResult, aResults) {
1735       ResultPartPtr aResultPart =
1736           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1737       if (aResultPart.get() && aResultPart->partDoc().get()) {
1738         // Recursion
1739         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1740         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1741       }
1742     }
1743
1744     aResultList.push_back(aFeature);
1745   }
1746   return aResultList;
1747 }
1748
1749 //**************************************************************
1750 // Returns the list of features placed between theObject and the current feature
1751 // in the same document. Excludes theObject, includes the current feature.
1752 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1753 {
1754   std::list<FeaturePtr> aResult;
1755   DocumentPtr aDocument = theObject->document();
1756   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1757   // find the object iterator
1758   std::list<FeaturePtr>::iterator aObjectIt =
1759     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1760   if (aObjectIt == anAllFeatures.end())
1761     return aResult;
1762   // find the current feature iterator
1763   std::list<FeaturePtr>::iterator aCurrentIt =
1764     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1765   if (aCurrentIt == anAllFeatures.end())
1766     return aResult;
1767   // check the right order
1768   if (std::distance(aObjectIt, anAllFeatures.end()) <=
1769       std::distance(aCurrentIt, anAllFeatures.end()))
1770     return aResult;
1771   // exclude the object
1772   std::advance(aObjectIt, 1);
1773   // include the current feature
1774   std::advance(aCurrentIt, 1);
1775   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1776 }
1777
1778 bool XGUI_Workshop::canMoveFeature()
1779 {
1780   QString anActionId = "MOVE_CMD";
1781
1782   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1783   QObjectPtrList aValidatedObjects;
1784   foreach (ObjectPtr aObject, aObjects) {
1785     if (!myModule->canApplyAction(aObject, anActionId))
1786       continue;
1787     // To be moved feature should be in active document
1788     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1789       continue;
1790     aValidatedObjects.append(aObject);
1791   }
1792   if (aValidatedObjects.size() != aObjects.size())
1793     aObjects = aValidatedObjects;
1794
1795   bool aCanMove = !aObjects.empty();
1796
1797   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1798   for (; anIt != aLast && aCanMove; anIt++) {
1799     ObjectPtr aObject = *anIt;
1800     // 1. Get features placed between selected and current in the document
1801     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1802     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1803     if (aFeaturesBetween.empty())
1804       aCanMove = false;
1805     else {
1806       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1807       // 2. Get all reference features to the selected object in the document
1808       std::set<FeaturePtr> aRefFeatures;
1809       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1810
1811       if (aRefFeatures.empty())
1812         continue;
1813       else {
1814         // 3. Find any placed features in all reference features
1815         std::set<FeaturePtr> aIntersectionFeatures;
1816         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1817                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1818                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1819         // 4. Return false if any reference feature is placed before current feature
1820         if (!aIntersectionFeatures.empty())
1821           aCanMove = false;
1822       }
1823     }
1824   }
1825   return aCanMove;
1826 }
1827
1828 //**************************************************************
1829 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1830 {
1831   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1832   if (!aCanBeShaded) {
1833     ResultCompSolidPtr aCompsolidResult =
1834                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1835     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1836       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1837         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1838     }
1839   }
1840   return aCanBeShaded;
1841 }
1842
1843 //**************************************************************
1844 bool XGUI_Workshop::canChangeColor() const
1845 {
1846   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1847
1848   std::set<std::string> aTypes;
1849   aTypes.insert(ModelAPI_ResultGroup::group());
1850   aTypes.insert(ModelAPI_ResultConstruction::group());
1851   aTypes.insert(ModelAPI_ResultBody::group());
1852   aTypes.insert(ModelAPI_ResultPart::group());
1853
1854   return hasResults(aObjects, aTypes);
1855 }
1856
1857 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1858 {
1859   if (!theResult.get())
1860     return;
1861
1862   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1863   if (aColorAttr.get() != NULL) {
1864     if (!aColorAttr->size()) {
1865       aColorAttr->setSize(3);
1866     }
1867     aColorAttr->setValue(0, theColor[0]);
1868     aColorAttr->setValue(1, theColor[1]);
1869     aColorAttr->setValue(2, theColor[2]);
1870   }
1871 }
1872
1873 //**************************************************************
1874 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1875 {
1876
1877   AttributeIntArrayPtr aColorAttr;
1878   // 1. find the current color of the object. This is a color of AIS presentation
1879   // The objects are iterated until a first valid color is found
1880   std::vector<int> aColor;
1881   foreach(ObjectPtr anObject, theObjects) {
1882     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1883     if (aResult.get()) {
1884       XGUI_CustomPrs::getResultColor(aResult, aColor);
1885     }
1886     else {
1887       // TODO: remove the obtaining a color from the AIS object
1888       // this does not happen never because:
1889       // 1. The color can be changed only on results
1890       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1891       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1892       if (anAISObj.get()) {
1893         aColor.resize(3);
1894         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1895       }
1896     }
1897     if (!aColor.empty())
1898       break;
1899   }
1900   if (aColor.size() != 3)
1901     return;
1902
1903   if (!myOperationMgr->abortAllOperations())
1904   return;
1905   // 2. show the dialog to change the value
1906   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1907   aDlg->setColor(aColor);
1908   aDlg->move(QCursor::pos());
1909   bool isDone = aDlg->exec() == QDialog::Accepted;
1910   if (!isDone)
1911     return;
1912
1913   bool isRandomColor = aDlg->isRandomColor();
1914
1915   // 3. abort the previous operation and start a new one
1916   SessionPtr aMgr = ModelAPI_Session::get();
1917   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1918   aMgr->startOperation(aDescription.toStdString());
1919
1920   // 4. set the value to all results
1921   std::vector<int> aColorResult = aDlg->getColor();
1922   foreach(ObjectPtr anObj, theObjects) {
1923     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1924     if (aResult.get() != NULL) {
1925       ResultCompSolidPtr aCompsolidResult =
1926         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1927       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1928         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1929           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult :
1930                                                                     aDlg->getRandomColor());
1931         }
1932       }
1933       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1934     }
1935   }
1936   aMgr->finishOperation();
1937   updateCommandStatus();
1938 }
1939
1940 //**************************************************************
1941 bool XGUI_Workshop::canChangeDeflection() const
1942 {
1943   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1944
1945   std::set<std::string> aTypes;
1946   aTypes.insert(ModelAPI_ResultGroup::group());
1947   aTypes.insert(ModelAPI_ResultConstruction::group());
1948   aTypes.insert(ModelAPI_ResultBody::group());
1949   aTypes.insert(ModelAPI_ResultPart::group());
1950
1951   return hasResults(aObjects, aTypes);
1952 }
1953
1954 void setDeflection(ResultPtr theResult, const double theDeflection)
1955 {
1956   if (!theResult.get())
1957     return;
1958
1959   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1960   if (aDeflectionAttr.get() != NULL)
1961     aDeflectionAttr->setValue(theDeflection);
1962 }
1963
1964
1965 //**************************************************************
1966 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
1967 {
1968   AttributeDoublePtr aDoubleAttr;
1969   // 1. find the current color of the object. This is a color of AIS presentation
1970   // The objects are iterated until a first valid color is found
1971   double aDeflection = -1;
1972   foreach(ObjectPtr anObject, theObjects) {
1973     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1974     if (aResult.get()) {
1975       aDeflection = XGUI_CustomPrs::getResultDeflection(aResult);
1976     }
1977     else {
1978       // TODO: remove the obtaining a color from the AIS object
1979       // this does not happen never because:
1980       // 1. The color can be changed only on results
1981       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1982       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1983       if (anAISObj.get()) {
1984         aDeflection = anAISObj->getDeflection();
1985       }
1986     }
1987     if (aDeflection > 0)
1988       break;
1989   }
1990   if (aDeflection < 0)
1991     return;
1992
1993   if (!myOperationMgr->abortAllOperations())
1994   return;
1995   // 2. show the dialog to change the value
1996   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
1997   aDlg->setDeflection(aDeflection);
1998   aDlg->move(QCursor::pos());
1999   bool isDone = aDlg->exec() == QDialog::Accepted;
2000   if (!isDone)
2001     return;
2002
2003   // 3. abort the previous operation and start a new one
2004   SessionPtr aMgr = ModelAPI_Session::get();
2005   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2006   aMgr->startOperation(aDescription.toStdString());
2007
2008   // 4. set the value to all results
2009   aDeflection = aDlg->getDeflection();
2010   foreach(ObjectPtr anObj, theObjects) {
2011     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2012     if (aResult.get() != NULL) {
2013       ResultCompSolidPtr aCompsolidResult =
2014         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
2015       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2016         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2017           setDeflection(aCompsolidResult->subResult(i), aDeflection);
2018         }
2019       }
2020       setDeflection(aResult, aDeflection);
2021     }
2022   }
2023   aMgr->finishOperation();
2024   updateCommandStatus();
2025 }
2026
2027 //**************************************************************
2028 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
2029 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
2030   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
2031 }
2032 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2033 {
2034   foreach (ObjectPtr aObj, theList) {
2035     aObj->setDisplayed(isVisible);
2036   }
2037   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2038 }
2039
2040 //**************************************************************
2041 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2042 {
2043   // Hide all displayed objects
2044   QObjectPtrList aList = myDisplayer->displayedObjects();
2045   foreach (ObjectPtr aObj, aList) {
2046     if (module()->canEraseObject(aObj))
2047       aObj->setDisplayed(false);
2048   }
2049   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2050 #ifdef HAVE_SALOME
2051     //issue #2159 Hide all incomplete behavior
2052     viewer()->eraseAll();
2053 #endif
2054
2055   // Show only objects from the list
2056   foreach (ObjectPtr aObj, theList) {
2057     aObj->setDisplayed(true);
2058   }
2059   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2060 }
2061
2062
2063 //**************************************************************
2064 void XGUI_Workshop::registerValidators() const
2065 {
2066   SessionPtr aMgr = ModelAPI_Session::get();
2067   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2068 }
2069
2070 //**************************************************************
2071 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2072 {
2073   if (!theDoc)
2074     return;
2075   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2076   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2077 }
2078
2079 //**************************************************************
2080 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2081 {
2082   for (int i = 0; i < theDoc->size(theGroup); i++)
2083     theDoc->object(theGroup, i)->setDisplayed(true);
2084     //displayObject(theDoc->object(theGroup, i));
2085   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2086 }
2087
2088 //**************************************************************
2089 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2090 {
2091   foreach(ObjectPtr aObj, theList) {
2092     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
2093
2094     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
2095     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2096       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2097           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
2098                                       (XGUI_Displayer::DisplayMode)theMode, false);
2099       }
2100     }
2101   }
2102   if (theList.size() > 0)
2103     myDisplayer->updateViewer();
2104 }
2105
2106 //**************************************************************
2107 void XGUI_Workshop::closeDocument()
2108 {
2109   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2110   while (anOperation) {
2111     anOperation->abort();
2112     anOperation = operationMgr()->currentOperation();
2113   }
2114   //myDisplayer->closeLocalContexts();
2115   myDisplayer->eraseAll();
2116   objectBrowser()->clearContent();
2117
2118   module()->closeDocument();
2119
2120   // data model need not process the document's signals about objects modifications as
2121   // the document is closed
2122   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2123
2124   SessionPtr aMgr = ModelAPI_Session::get();
2125   aMgr->closeAll();
2126
2127   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2128 }
2129
2130 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2131 {
2132   XGUI_HistoryMenu* aMenu = NULL;
2133   if (isSalomeMode()) {
2134     QAction* anAction = qobject_cast<QAction*>(theObject);
2135     if (!anAction)
2136       return;
2137     aMenu = new XGUI_HistoryMenu(anAction);
2138   } else {
2139     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2140     aMenu = new XGUI_HistoryMenu(aButton);
2141   }
2142   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2143   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2144 }
2145
2146 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2147 {
2148   QList<ActionInfo> aResult;
2149   std::list<std::string>::const_iterator it = theList.cbegin();
2150   for (; it != theList.cend(); it++) {
2151     QString anId = QString::fromStdString(*it);
2152     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2153     if (isEditing) {
2154       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2155     }
2156     ActionInfo anInfo;
2157     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2158     if (aContextMenuAct) {
2159       anInfo.initFrom(aContextMenuAct);
2160     } else {
2161       anInfo = myActionsMgr->actionInfoById(anId);
2162     }
2163     if (isEditing) {
2164       anInfo.text = anInfo.text.prepend("Modify ");
2165     }
2166     aResult << anInfo;
2167   }
2168   return aResult;
2169 }
2170
2171 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2172 {
2173 #ifdef HAVE_SALOME
2174   salomeConnector()->putInfo(theMessage, -1);
2175 #else
2176   myMainWindow->putInfo(theMessage, -1);
2177 #endif
2178 }
2179
2180 void XGUI_Workshop::synchronizeViewer()
2181 {
2182   SessionPtr aMgr = ModelAPI_Session::get();
2183   QList<DocumentPtr> aDocs;
2184   aDocs.append(aMgr->activeDocument());
2185   aDocs.append(aMgr->moduleDocument());
2186
2187   foreach(DocumentPtr aDoc, aDocs) {
2188     synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2189     synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2190     synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2191     synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2192   }
2193 }
2194
2195 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2196                                              const std::string& theGroup,
2197                                              bool theUpdateViewer)
2198 {
2199   ObjectPtr aObj;
2200   int aSize = theDoc->size(theGroup);
2201   for (int i = 0; i < aSize; i++) {
2202     aObj = theDoc->object(theGroup, i);
2203     if (aObj->isDisplayed()) {
2204       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2205       // be changed to the object becomes visible when the shape becomes not empty
2206       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2207       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2208         continue;
2209       myDisplayer->display(aObj, false);
2210     }
2211   }
2212   if (theUpdateViewer)
2213     myDisplayer->updateViewer();
2214 }
2215
2216 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2217 {
2218   FeaturePtr aFeature;
2219   QObjectPtrList aSelList = theObjects;
2220   bool aHasHidden = false;
2221   foreach(ObjectPtr aObj, theObjects) {
2222     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2223     if (aFeature.get()) {
2224       std::list<ResultPtr> aResults;
2225       ModelAPI_Tools::allResults(aFeature, aResults);
2226       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2227       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2228         aHasHidden |= (*aIt)->isConcealed();
2229         aSelList.append(*aIt);
2230       }
2231     }
2232   }
2233   if (aSelList.count() > theObjects.count()) {
2234     // if something was found
2235     bool aBlocked = objectBrowser()->blockSignals(true);
2236     objectBrowser()->setObjectsSelected(aSelList);
2237     objectBrowser()->blockSignals(aBlocked);
2238   }
2239   if (aHasHidden)
2240     QMessageBox::information(desktop(), tr("Find results"),
2241                              tr("Results not found"), QMessageBox::Ok);
2242 }
2243
2244 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2245 {
2246   ResultPtr aResult;
2247   QObjectPtrList aSelList = theObjects;
2248   FeaturePtr aFeature;
2249   foreach(ObjectPtr aObj, theObjects) {
2250     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2251     if (aResult.get()) {
2252       aFeature = ModelAPI_Feature::feature(aResult);
2253       if (aFeature.get()) {
2254         aSelList.append(aFeature);
2255       }
2256     }
2257   }
2258   if (aSelList.count() > theObjects.count()) {
2259     // if something was found
2260     bool aBlocked = objectBrowser()->blockSignals(true);
2261     objectBrowser()->setObjectsSelected(aSelList);
2262     objectBrowser()->blockSignals(aBlocked);
2263   }
2264 }