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