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