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