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