]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Correct compilation on Linux
[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_WITH_MESSAGE_REPORT
162
163 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
164
165 //#define DEBUG_DELETE
166 //#define DEBUG_FEATURE_NAME
167 //#define DEBUG_CLEAN_HISTORY
168
169 //******************************************************
170 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
171     : QObject(),
172       myCurrentDir(QString()),
173       myModule(NULL),
174       mySalomeConnector(theConnector),
175       myPropertyPanel(0),
176       myFacesPanel(0),
177       myObjectBrowser(0),
178       myDisplayer(0)
179       //myViewerSelMode(TopAbs_FACE)
180 {
181   mySelector = new XGUI_SelectionMgr(this);
182   myModuleConnector = new XGUI_ModuleConnector(this);
183   myOperationMgr = new XGUI_OperationMgr(this, 0);
184   ModuleBase_IWorkshop* aWorkshop = moduleConnector();
185   // Has to be defined first in order to get errors and messages from other components
186   myEventsListener = new XGUI_WorkshopListener(aWorkshop);
187
188   SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
189 #ifndef HAVE_SALOME
190   myMainWindow = new AppElements_MainWindow();
191
192   bool aCloc = aResMgr->booleanValue("language", "locale", true);
193   if (aCloc)
194     QLocale::setDefault( QLocale::c() );
195   else
196     QLocale::setDefault( QLocale::system() );
197 #endif
198   QString aPath = Config_XMLReader::pluginConfigFile().c_str();
199   QDir aDir(aPath);
200
201   // Load translations
202   QStringList aLangs;
203   aLangs << "*_en.ts"; // load by default eng translations
204   QString aCurrLang = aResMgr->stringValue("language", "language", "en");
205   if(aCurrLang != "en") {
206     aLangs << "*_" + aCurrLang + ".ts"; // then replace with translated files
207   }
208
209   foreach(QString aLang, aLangs) {
210     QStringList aFilters;
211     aFilters << aLang;
212     QStringList aTsFiles = aDir.entryList(aFilters, QDir::Files);
213     foreach(QString aFileName, aTsFiles) {
214       Config_Translator::load(aFileName.toStdString());
215     }
216   }
217
218   myDataModelXMLReader = new Config_DataModelReader();
219   //myDataModelXMLReader->readAll();
220
221   myDisplayer = new XGUI_Displayer(this);
222
223   connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
224
225   myActionsMgr = new XGUI_ActionsMgr(this);
226   myActiveControlMgr = new XGUI_ActiveControlMgr(myModuleConnector);
227   myMenuMgr = new XGUI_MenuMgr(this);
228   myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
229   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
230   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
231           SLOT(onContextMenuCommand(const QString&, bool)));
232
233   myViewerProxy = new XGUI_ViewerProxy(this);
234   //connect(myViewerProxy, SIGNAL(selectionChanged()),
235   //        myActionsMgr,  SLOT(updateOnViewSelection()));
236
237   myOperationMgr->setWorkshop(aWorkshop);
238
239   myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
240
241   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
242           SLOT(onOperationResumed(ModuleBase_Operation*)));
243   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
244           SLOT(onOperationStopped(ModuleBase_Operation*)));
245   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
246           SLOT(onOperationCommitted(ModuleBase_Operation*)));
247   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
248           SLOT(onOperationAborted(ModuleBase_Operation*)));
249
250 #ifndef HAVE_SALOME
251   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
252   onTrihedronVisibilityChanged(true);
253 #endif
254
255   connect(myEventsListener, SIGNAL(errorOccurred(std::shared_ptr<Events_InfoMessage>)),
256           myErrorDlg, SLOT(addError(std::shared_ptr<Events_InfoMessage>)));
257
258   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
259   //                                 Config_Prop::Color, "225,225,225");
260
261   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
262                                    Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
263   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
264                                    Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
265   Config_PropManager::registerProp("Visualization", "result_construction_color",
266                                    "Construction color",
267                                    Config_Prop::Color,
268                                    ModelAPI_ResultConstruction::DEFAULT_COLOR());
269   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
270                                    Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
271   Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
272                                    Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
273
274   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "face-selection", true))
275     myViewerSelMode.append(TopAbs_FACE);
276   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "edge-selection", true))
277     myViewerSelMode.append(TopAbs_EDGE);
278   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "vertex-selection", true))
279     myViewerSelMode.append(TopAbs_VERTEX);
280   //IMP: an attempt to use result selection with other selection modes
281   myViewerSelMode.append(ModuleBase_ResultPrs::Sel_Result);//TopAbs_VERTEX);
282   myViewerSelMode.append(TopAbs_COMPSOLID);
283 }
284
285 //******************************************************
286 XGUI_Workshop::~XGUI_Workshop(void)
287 {
288 #ifdef _DEBUG
289 #ifdef MISSED_TRANSLATION
290   // Save Missed translations
291   Config_Translator::saveMissedTranslations();
292 #endif
293 #endif
294
295   delete myDisplayer;
296   delete myDataModelXMLReader;
297 }
298
299 //******************************************************
300 void XGUI_Workshop::startApplication()
301 {
302   //Initialize event listening
303   myEventsListener->initializeEventListening();
304
305   myDataModelXMLReader->readAll();
306   initMenu();
307
308   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
309                                    Config_Prop::Directory, "");
310
311   std::string aDir = Config_XMLReader::resourcesConfigFile();
312   Config_PropManager::registerProp("Plugins", "import_initial_path", "Import initial directory",
313                                    Config_Prop::Directory, aDir);
314
315 #ifdef _DEBUG
316   Config_PropManager::registerProp("Plugins", "create_part_by_start", "Create Part by Start",
317     Config_Prop::Boolean, "false");
318
319   Config_PropManager::registerProp("Plugins", "show_hide_faces", "Show Hide Faces (on the right)",
320     Config_Prop::Boolean, "false");
321 #endif
322   registerValidators();
323
324   // Calling of  loadCustomProps before activating module is required
325   // by Config_PropManger to restore user-defined path to plugins
326   ModuleBase_Preferences::loadCustomProps();
327   createModule();
328
329 #ifndef HAVE_SALOME
330   myMainWindow->show();
331   updateCommandStatus();
332 #endif
333
334   onNew();
335
336   myViewerProxy->connectViewProxy();
337   connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
338           SLOT(onTrihedronVisibilityChanged(bool)));
339
340   emit applicationStarted();
341
342 #ifdef _DEBUG
343   bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
344   if (aNewPart) {
345       module()->launchOperation("Part", false); // PartSetPlugin_Part::ID()
346   }
347 #endif
348 }
349
350 //******************************************************
351 void XGUI_Workshop::activateModule()
352 {
353   myModule->activateSelectionFilters();
354
355   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
356     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
357   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
358     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
359
360   updateCommandStatus();
361
362   // TODO: get default selection mode
363
364   // activate visualized objects in the viewer
365   activateObjectsSelection(displayer()->displayedObjects());
366   myOperationMgr->activate();
367 }
368
369 //******************************************************
370 void XGUI_Workshop::deactivateModule()
371 {
372   myModule->deactivateSelectionFilters();
373
374   // remove internal displayer filter
375   displayer()->deactivateSelectionFilters();
376
377   disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
378     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
379   disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
380     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
381
382   XGUI_Displayer* aDisplayer = displayer();
383   QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
384   aDisplayer->deactivateObjects(aDisplayed, true);
385   Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
386   Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aDisplayer->getTrihedron());
387   /// deactivate trihedron in selection modes
388   TColStd_ListOfInteger aTColModes;
389   aContext->ActivatedModes(aTrihedron, aTColModes);
390   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
391   for (; itr.More(); itr.Next() ) {
392     Standard_Integer aMode = itr.Value();
393     aContext->Deactivate(aTrihedron, aMode);
394   }
395 #ifdef BEFORE_TRIHEDRON_PATCH
396   /// Trihedron problem: objects stayed in the viewer, should be removed manually
397   /// otherwise in SALOME happens crash by HideAll in the viewer
398   aContext->Remove(aTrihedron->Position(), true);
399   aContext->Remove(aTrihedron->Axis(), true);
400   aContext->Remove(aTrihedron->XAxis(), true);
401   aContext->Remove(aTrihedron->YAxis(), true);
402 #endif
403
404   myOperationMgr->deactivate();
405 }
406
407 //******************************************************
408 void XGUI_Workshop::initMenu()
409 {
410   myContextMenuMgr->createActions();
411
412 #ifdef HAVE_SALOME
413   // Create only Undo, Redo commands
414   QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
415                                                         tr("Undo last command"),
416                                                         QIcon(":pictures/undo.png"),
417                                                         QKeySequence::Undo, false,
418                                                         "MEN_DESK_EDIT");
419   QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
420   salomeConnector()->addActionInToolbar( aAction,aToolBarTitle  );
421
422   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
423   addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
424
425   aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
426                                               QIcon(":pictures/redo.png"), QKeySequence::Redo,
427                                               false, "MEN_DESK_EDIT");
428   salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
429
430   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
431   addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
432
433   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
434
435   aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."),
436                                              tr("Export the current document into a native file"),
437                                               QIcon(), QKeySequence(),
438                                               false, "MEN_DESK_FILE");
439   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
440
441   aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."),
442                                               tr("Import native file"),
443                                               QIcon(), QKeySequence(),
444                                               false, "MEN_DESK_FILE");
445   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
446   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
447
448 #else
449   // File commands group
450   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
451
452   AppElements_Command* aCommand;
453
454   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
455                                 QIcon(":pictures/save.png"), QKeySequence::Save);
456   aCommand->connectTo(this, SLOT(onSave()));
457   //aCommand->disable();
458
459   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
460                                 QIcon(":pictures/save.png"), QKeySequence());
461   aCommand->connectTo(this, SLOT(onSaveAs()));
462
463   QString aUndoId = "UNDO_CMD";
464   aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
465                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
466   aCommand->connectTo(this, SLOT(onUndo()));
467   AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
468   addHistoryMenu(aUndoButton,
469                  SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
470                  SLOT(onUndo(int)));
471
472   QString aRedoId = "REDO_CMD";
473   aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
474                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
475   aCommand->connectTo(this, SLOT(onRedo()));
476   AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
477   addHistoryMenu(aRedoButton,
478                  SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
479                  SLOT(onRedo(int)));
480
481   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
482                                 QIcon(":pictures/open.png"), QKeySequence::Open);
483   aCommand->connectTo(this, SLOT(onOpen()));
484
485   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
486                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
487   aCommand->connectTo(this, SLOT(onPreferences()));
488
489   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
490                                 QIcon(":pictures/close.png"), QKeySequence::Close);
491   aCommand->connectTo(this, SLOT(onExit()));
492 #endif
493 }
494
495 #ifndef HAVE_SALOME
496 //******************************************************
497 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
498 {
499   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
500   return aMenuBar->addWorkbench(theName);
501 }
502 #endif
503
504 //******************************************************
505 QMainWindow* XGUI_Workshop::desktop() const
506 {
507 #ifdef HAVE_SALOME
508   return salomeConnector()->desktop();
509 #else
510   return myMainWindow;
511 #endif
512 }
513
514 //******************************************************
515 void XGUI_Workshop::onStartWaiting()
516 {
517   if (Events_LongOp::isPerformed()) {
518     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
519   }
520 }
521
522 //******************************************************
523 void XGUI_Workshop::onAcceptActionClicked()
524 {
525   QAction* anAction = dynamic_cast<QAction*>(sender());
526   XGUI_OperationMgr* anOperationMgr = operationMgr();
527   if (anOperationMgr) {
528     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
529                                                     (anOperationMgr->currentOperation());
530     if (aFOperation) {
531       //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
532       myOperationMgr->commitOperation();
533     }
534   }
535 }
536
537 //******************************************************
538 void XGUI_Workshop::onPreviewActionClicked()
539 {
540   ModuleBase_IPropertyPanel* aPanel = propertyPanel();
541   if (aPanel) {
542     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
543     if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
544       anActiveWidget->storeValue();
545     }
546   }
547   std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
548                 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
549   Events_Loop::loop()->send(aMsg);
550 }
551
552 //******************************************************
553 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
554 {
555   if (!myModule->canActivateSelection(theObject)) {
556     if (myDisplayer->isActive(theObject)) {
557       QObjectPtrList anObjects;
558       anObjects.append(theObject);
559       myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
560     }
561   }
562 }
563
564 //******************************************************
565 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
566 {
567   bool aHasNested = false;
568   std::string aFeatureKind = theFeature->getKind();
569 #ifdef HAVE_SALOME
570     XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
571     if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
572       aHasNested = true;
573 #else
574     AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
575     AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
576     if (aCommand && aCommand->button()->additionalButtonWidget())
577       aHasNested = true;
578 #endif
579   return aHasNested;
580 }
581
582 //******************************************************
583 void XGUI_Workshop::fillPropertyPanel(ModuleBase_Operation* theOperation)
584 {
585   ModuleBase_OperationFeature* aFOperation =
586     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
587   if (!aFOperation)
588     return;
589
590   showPanel(myPropertyPanel);
591   myPropertyPanel->cleanContent();
592
593   QList<ModuleBase_ModelWidget*> aWidgets;
594   if (!module()->createWidgets(theOperation, aWidgets)) {
595     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
596     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
597     aFactory.createWidget(myPropertyPanel->contentWidget());
598     aWidgets = aFactory.getModelWidgets();
599   }
600
601   // check compatibility of feature and widgets
602   FeaturePtr aFeature = aFOperation->feature();
603   std::string aFeatureKind = aFeature->getKind();
604   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
605     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
606       std::string anErrorMsg = "The feature '%1' has no attribute '%2' used by widget '%3'.";
607       Events_InfoMessage("XGUI_Workshop", anErrorMsg)
608         .arg(aFeatureKind).arg(aWidget->attributeID())
609         .arg(aWidget->metaObject()->className()).send();
610       myPropertyPanel->cleanContent();
611       return;
612     }
613   }
614   // for performance purpose, flush should be done after all controls are filled
615   bool isUpdateFlushed = false;
616   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
617     bool isStoreValue = !aFOperation->isEditOperation() &&
618                         !aWidget->getDefaultValue().empty() &&
619                         !aWidget->isComputedDefault();
620     aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
621     if (!isStoreValue)
622       aWidget->restoreValue();
623     aWidget->enableFocusProcessing();
624   }
625   // update visible state of Preview button
626   std::shared_ptr<Config_FeatureMessage> aFeatureInfo;
627 #ifdef HAVE_SALOME
628   aFeatureInfo = mySalomeConnector->featureInfo(aFeatureKind.c_str());
629 #else
630   AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
631   AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
632   if (aCommand)
633     aFeatureInfo = aCommand->featureMessage();
634 #endif
635   bool anIsAutoPreview = true;
636   if (aFeatureInfo.get())
637     anIsAutoPreview = aFeatureInfo->isAutoPreview();
638   else {
639     std::string aXmlCfg, aDescription;
640     module()->getXMLRepresentation(aFeatureKind, aXmlCfg, aDescription);
641     ModuleBase_WidgetFactory aFactory(aXmlCfg, moduleConnector());
642     anIsAutoPreview = aFactory.widgetAPI()->getBooleanAttribute(FEATURE_AUTO_PREVIEW, true);
643   }
644
645   if (!anIsAutoPreview) {
646     myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
647     // send signal about preview should not be computed automatically, click on preview
648     // button should initiate it
649     std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
650                   new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
651     Events_Loop::loop()->send(aMsg);
652   }
653   // if update happens after preview is blocked, it does nothing when blocked
654   // it improves performance for valid objects on feature start
655   ModuleBase_Tools::flushUpdated(aFeature);
656
657   myPropertyPanel->setModelWidgets(aWidgets);
658   aFOperation->setPropertyPanel(myPropertyPanel);
659
660   myModule->propertyPanelDefined(theOperation);
661
662 #ifndef DEBUG_FEATURE_NAME
663   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
664 #else
665   std::string aFeatureName = aFeature->name();
666   myPropertyPanel->setWindowTitle(QString("%1: %2")
667     .arg(theOperation->getDescription()->description())
668     .arg(aFeatureName.c_str()));
669 #endif
670
671   myErrorMgr->setPropertyPanel(myPropertyPanel);
672 }
673
674 //******************************************************
675 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
676 {
677   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
678   if (aPropertyPanel) {
679     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
680     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
681        myModule->connectToPropertyPanel(aWidget, isToConnect);
682        if (isToConnect) {
683         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
684         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
685         connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
686        }
687       else {
688         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
689         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
690         disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
691       }
692     }
693   }
694 }
695
696 //******************************************************
697 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
698 {
699   setGrantedFeatures(theOperation);
700
701   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
702     fillPropertyPanel(theOperation);
703     connectToPropertyPanel(true);
704   }
705   updateCommandStatus();
706
707   myModule->operationResumed(theOperation);
708 }
709
710
711 //******************************************************
712 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
713 {
714   updateCommandStatus();
715
716   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
717                                                                         (theOperation);
718   if (!aFOperation)
719     return;
720
721   ModuleBase_ISelection* aSel = mySelector->selection();
722   QObjectPtrList aObj = aSel->selectedPresentations();
723   //!< No need for property panel
724   hidePanel(myPropertyPanel);
725   myPropertyPanel->cleanContent();
726
727   connectToPropertyPanel(false);
728   myModule->operationStopped(aFOperation);
729
730   // the deactivated objects of the current operation should be activated back.
731   // They were deactivated on operation start or an object redisplay
732   QObjectPtrList anObjects;
733   FeaturePtr aFeature = aFOperation->feature();
734   if (aFeature.get()) { // feature may be not created (plugin load fail)
735     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
736       anObjects.append(aFeature);
737     std::list<ResultPtr> aResults;
738     ModelAPI_Tools::allResults(aFeature, aResults);
739     std::list<ResultPtr>::const_iterator aIt;
740     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
741       ResultPtr anObject = *aIt;
742       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
743         anObjects.append(anObject);
744       }
745     }
746   }
747   activateObjectsSelection(anObjects);
748 }
749
750 //******************************************************
751 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
752 {
753   myModule->operationCommitted(theOperation);
754 }
755
756 //******************************************************
757 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
758 {
759   myModule->operationAborted(theOperation);
760 }
761
762 //******************************************************
763 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
764 {
765   ModuleBase_OperationFeature* aFOperation =
766     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
767   if (!aFOperation)
768     return;
769
770   QStringList aGrantedIds;
771   if (isSalomeMode()) {
772     const std::shared_ptr<Config_FeatureMessage>& anInfo =
773                          mySalomeConnector->featureInfo(theOperation->id());
774     if (anInfo.get())
775       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
776                                    .split(" ", QString::SkipEmptyParts);
777   }
778   else
779     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
780
781   ModuleBase_IModule* aModule = module();
782   if (aModule)
783     aModule->grantedOperationIds(theOperation, aGrantedIds);
784
785   aFOperation->setGrantedOperationIds(aGrantedIds);
786 }
787
788 //******************************************************
789 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
790 {
791   QApplication::restoreOverrideCursor();
792   SessionPtr aMgr = ModelAPI_Session::get();
793
794   std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
795   std::list<DocumentPtr>::const_iterator aIt;
796   for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
797     std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
798     (*aIt)->storeNodesState(aState);
799   }
800
801   aMgr->save(theName.toLatin1().constData(), theFileNames);
802
803   QApplication::restoreOverrideCursor();
804 }
805
806 //******************************************************
807 bool XGUI_Workshop::abortAllOperations()
808 {
809   return myOperationMgr->abortAllOperations();
810 }
811
812 //******************************************************
813 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
814 {
815   setGrantedFeatures(theOperation);
816   if (!theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
817     updateCommandStatus();
818   }
819   else {
820     myModule->operationStarted(theOperation);
821   }
822 }
823
824 //******************************************************
825 void XGUI_Workshop::onOpen()
826 {
827   if(!abortAllOperations())
828     return;
829   //save current file before close if modified
830   SessionPtr aSession = ModelAPI_Session::get();
831   if (aSession->isModified()) {
832     //TODO(sbh): re-launch the app?
833     int anAnswer = QMessageBox::question(
834         desktop(), tr("Save current file"),
835         tr("The document is modified, save before opening another?"),
836         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
837     if (anAnswer == QMessageBox::Save) {
838       onSave();
839     } else if (anAnswer == QMessageBox::Cancel) {
840       return;
841     }
842     myCurrentDir = "";
843   }
844
845   //show file dialog, check if readable and open
846   QString aDirectory = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
847   openDirectory(aDirectory);
848 }
849
850 //******************************************************
851 void XGUI_Workshop::openDirectory(const QString& theDirectory)
852 {
853   myCurrentDir = theDirectory;
854   if (myCurrentDir.isEmpty())
855     return;
856
857   QFileInfo aFileInfo(myCurrentDir);
858   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
859     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
860     myCurrentDir = "";
861     return;
862   }
863
864   QApplication::setOverrideCursor(Qt::WaitCursor);
865   module()->closeDocument();
866   SessionPtr aSession = ModelAPI_Session::get();
867   aSession->closeAll();
868   aSession->load(myCurrentDir.toLatin1().constData());
869   myObjectBrowser->rebuildDataTree();
870
871   // Open first level of data tree
872   DocumentPtr aRootDoc = aSession->moduleDocument();
873   std::list<bool> aStates;
874   aRootDoc->restoreNodesState(aStates);
875   myObjectBrowser->setStateForDoc(aRootDoc, aStates);
876
877   updateCommandStatus();
878 #ifndef HAVE_SALOME
879   myMainWindow->setCurrentDir(myCurrentDir, true);
880 #endif
881
882 #ifdef _DEBUG
883   bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
884   if (aNewPart) {
885
886     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
887     int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
888     if (aSize > 0 ) {
889       ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), 0);
890       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
891       if (aPart.get())
892         aPart->activate();
893     }
894   }
895 #endif
896
897   QApplication::restoreOverrideCursor();
898 }
899
900 //******************************************************
901 void XGUI_Workshop::onNew()
902 {
903   QApplication::setOverrideCursor(Qt::WaitCursor);
904   if (objectBrowser() == 0) {
905     createDockWidgets();
906     mySelector->connectViewers();
907   }
908   myViewerProxy->connectToViewer();
909   showObjectBrowser();
910 #ifndef HAVE_SALOME
911   myMainWindow->showPythonConsole();
912   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
913   aWnd->showMaximized();
914   updateCommandStatus();
915 #endif
916   myContextMenuMgr->connectViewer();
917   QApplication::restoreOverrideCursor();
918 }
919
920 #ifndef HAVE_SALOME
921 //******************************************************
922 void XGUI_Workshop::onExit()
923 {
924   SessionPtr aMgr = ModelAPI_Session::get();
925   if (aMgr->isModified()) {
926     int anAnswer = QMessageBox::question(
927         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
928         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
929     if (anAnswer == QMessageBox::Save) {
930       bool saved = onSave();
931       if (!saved) {
932         return;
933       }
934     } else if (anAnswer == QMessageBox::Cancel) {
935       return;
936     }
937   }
938   qApp->exit();
939 }
940
941 //******************************************************
942 void XGUI_Workshop::onPreferences()
943 {
944   ModuleBase_Prefs aModif;
945   ModuleBase_Preferences::editPreferences(aModif);
946   if (aModif.size() > 0) {
947     QString aSection;
948     foreach (ModuleBase_Pref aPref, aModif)
949     {
950       aSection = aPref.first;
951       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
952         myMainWindow->viewer()->updateFromResources();
953       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
954         myMainWindow->menuObject()->updateFromResources();
955       }
956     }
957     displayer()->redisplayObjects();
958   }
959 }
960 #endif
961
962 //******************************************************
963 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
964 {
965   XGUI_Displayer* aDisplayer = displayer();
966   if (aDisplayer)
967     aDisplayer->displayTrihedron(theState);
968 }
969
970 //******************************************************
971 bool XGUI_Workshop::onSave()
972 {
973   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
974     return false;
975   if (myCurrentDir.isEmpty()) {
976     return onSaveAs();
977   }
978   std::list<std::string> aFiles;
979   saveDocument(myCurrentDir, aFiles);
980   updateCommandStatus();
981 #ifndef HAVE_SALOME
982     myMainWindow->setModifiedState(false);
983 #endif
984   return true;
985 }
986
987 //******************************************************
988 bool XGUI_Workshop::onSaveAs()
989 {
990   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
991     return false;
992   QFileDialog dialog(desktop());
993   dialog.setWindowTitle(tr("Select directory to save files..."));
994   dialog.setFileMode(QFileDialog::Directory);
995   dialog.setFilter(QDir::AllDirs);
996   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
997   dialog.setViewMode(QFileDialog::Detail);
998
999   if (!dialog.exec()) {
1000     return false;
1001   }
1002
1003   QString aTempDir = dialog.selectedFiles().first();
1004   QDir aDir(aTempDir);
1005   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
1006     int answer = QMessageBox::question(
1007         desktop(),
1008         // Title of the dialog which asks user if he wants to save study
1009         // in existing non-empty folder
1010         tr("Save"),
1011         tr("The directory already contains some files, save anyway?"),
1012         QMessageBox::Save | QMessageBox::Cancel);
1013     if (answer == QMessageBox::Cancel) {
1014       return false;
1015     }
1016   }
1017   myCurrentDir = aTempDir;
1018 #ifndef HAVE_SALOME
1019     myMainWindow->setCurrentDir(myCurrentDir, false);
1020     myMainWindow->setModifiedState(false);
1021 #endif
1022   return onSave();
1023 }
1024
1025 //******************************************************
1026 void XGUI_Workshop::onUndo(int theTimes)
1027 {
1028   processUndoRedo(ActionUndo, theTimes);
1029 }
1030
1031 //******************************************************
1032 void XGUI_Workshop::onRedo(int theTimes)
1033 {
1034   processUndoRedo(ActionRedo, theTimes);
1035 }
1036
1037 //******************************************************
1038 void XGUI_Workshop::processUndoRedo(const ModuleBase_ActionType theActionType, int theTimes)
1039 {
1040   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1041   if (anActiveWidget) {
1042     ActionIntParamPtr aParam(new ModuleBase_ActionIntParameter(theTimes));
1043     if (anActiveWidget->processAction(theActionType, aParam))
1044       return;
1045   }
1046   // the viewer update should be blocked in order to avoid the features blinking. For the created
1047   // feature a results are created, the flush of the created signal caused the viewer redisplay for
1048   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1049   // until redo of all possible objects happens
1050   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1051
1052   SessionPtr aMgr = ModelAPI_Session::get();
1053   if (aMgr->isOperation()) {
1054     XGUI_OperationMgr* aOpMgr = operationMgr();
1055     /// this is important for nested operations
1056     /// when sketch operation is active, this condition is false and
1057     /// the sketch operation is not aborted
1058     if (aOpMgr->canStopOperation(aOpMgr->currentOperation()))
1059       aOpMgr->abortOperation(aOpMgr->currentOperation());
1060     else
1061       return;
1062   }
1063   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1064   std::list<std::string> anActionList = theActionType == ActionUndo ? aMgr->undoList()
1065     : aMgr->redoList();
1066   std::list<std::string>::const_iterator aIt = anActionList.cbegin();
1067   for (int i = 0; (i < theTimes) && (aIt != anActionList.cend()); ++i, ++aIt) {
1068     if (theActionType == ActionUndo)
1069       aMgr->undo();
1070     else
1071       aMgr->redo();
1072
1073     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1074       myObjectBrowser->rebuildDataTree();
1075   }
1076   operationMgr()->updateApplyOfOperations();
1077   facesPanel()->reset(true);
1078   updateCommandStatus();
1079
1080   // unblock the viewer update functionality and make update on purpose
1081   if (theActionType == ActionRedo) {
1082     myDisplayer->enableUpdateViewer(isUpdateEnabled);
1083     myDisplayer->updateViewer();
1084   }
1085 }
1086
1087 //******************************************************
1088 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1089 {
1090   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1091   //ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1092   //if (anOperation) {
1093   //  ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1094   //  if (aPanel)
1095   //    anActiveWidget = aPanel->activeWidget();
1096   //}
1097   if (anActiveWidget)
1098     operationMgr()->onValidateOperation();
1099
1100   myModule->widgetStateChanged(thePreviousState);
1101 }
1102
1103 //******************************************************
1104 void XGUI_Workshop::onValuesChanged()
1105 {
1106   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1107   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1108     return;
1109
1110   ModuleBase_ModelWidget* anActiveWidget = 0;
1111   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1112   if (anOperation) {
1113     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1114     if (aPanel)
1115       anActiveWidget = aPanel->activeWidget();
1116   }
1117   if (anActiveWidget) {
1118     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1119                                                                            (anActiveWidget);
1120     if (aWidgetValidated)
1121       aWidgetValidated->clearValidatedCash();
1122   }
1123 }
1124
1125 //******************************************************
1126 void XGUI_Workshop::onWidgetObjectUpdated()
1127 {
1128   operationMgr()->onValidateOperation();
1129 }
1130
1131 //******************************************************
1132 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1133 {
1134   QString libName = QString::fromStdString(library(theModule.toStdString()));
1135   if (libName.isEmpty()) {
1136     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1137     return 0;
1138   }
1139
1140   QString err;
1141   CREATE_FUNC crtInst = 0;
1142
1143 #ifdef WIN32
1144   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1145   if (!modLib) {
1146     LPVOID lpMsgBuf;
1147     ::FormatMessage(
1148         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1149         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1150     QString aMsg((char*) &lpMsgBuf);
1151     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1152     ::LocalFree(lpMsgBuf);
1153   } else {
1154     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1155     if (!crtInst) {
1156       LPVOID lpMsgBuf;
1157       ::FormatMessage(
1158           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1159               | FORMAT_MESSAGE_IGNORE_INSERTS,
1160           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1161       QString aMsg((char*) &lpMsgBuf);
1162       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1163       ::LocalFree(lpMsgBuf);
1164     }
1165   }
1166 #else
1167   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1168   if ( !modLib ) {
1169     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1170   } else {
1171     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1172     if ( !crtInst ) {
1173       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1174     }
1175   }
1176 #endif
1177
1178   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1179
1180   if (!err.isEmpty()) {
1181     if (desktop()) {
1182       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1183     } else {
1184       qWarning(qPrintable(err));
1185     }
1186   }
1187   return aModule;
1188 }
1189
1190 //******************************************************
1191 bool XGUI_Workshop::createModule()
1192 {
1193   Config_ModuleReader aModuleReader;
1194   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1195   myModule = loadModule(moduleName);
1196   if (!myModule)
1197     return false;
1198
1199   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1200   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1201   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1202   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1203
1204   myModule->createFeatures();
1205 #ifdef HAVE_SALOME
1206   salomeConnector()->createFeatureActions();
1207 #endif
1208   //myActionsMgr->update();
1209   return true;
1210 }
1211
1212 //******************************************************
1213 void XGUI_Workshop::updateCommandStatus()
1214 {
1215   QList<QAction*> aCommands;
1216 #ifdef HAVE_SALOME
1217     aCommands = salomeConnector()->commandList();
1218 #else
1219     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1220     foreach (AppElements_Command* aCmd, aMenuBar->features())
1221       aCommands.append(aCmd);
1222 #endif
1223   SessionPtr aMgr = ModelAPI_Session::get();
1224   if (aMgr->hasModuleDocument()) {
1225     foreach(QAction* aCmd, aCommands) {
1226       QString aId = aCmd->data().toString();
1227       if (aId == "UNDO_CMD") {
1228         bool isActionEnabled = false;
1229         // if ultimate is true -> using result of operation only, or using OR combination
1230         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1231         if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled))
1232           aCmd->setEnabled(isActionEnabled);
1233         else
1234           aCmd->setEnabled(myModule->canUndo());
1235       }
1236       else if (aId == "REDO_CMD") {
1237         bool isActionEnabled = false;
1238         // if ultimate is true -> using result of operation only, or using OR combination
1239         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1240         if (anActiveWidget && anActiveWidget->canProcessAction(ActionRedo, isActionEnabled))
1241           aCmd->setEnabled(isActionEnabled);
1242         else
1243           aCmd->setEnabled(myModule->canRedo());
1244       }
1245       else
1246         // Enable all commands
1247         aCmd->setEnabled(true);
1248     }
1249     updateHistory();
1250   } else {
1251     foreach(QAction* aCmd, aCommands) {
1252       QString aId = aCmd->data().toString();
1253       if (aId == "NEW_CMD")
1254         aCmd->setEnabled(true);
1255       else if (aId == "EXIT_CMD")
1256         aCmd->setEnabled(true);
1257       else
1258         aCmd->setEnabled(false);
1259     }
1260   }
1261   myActionsMgr->updateCommandsStatus();
1262   emit commandStatusUpdated();
1263 }
1264
1265 //******************************************************
1266 void XGUI_Workshop::updateHistory()
1267 {
1268   bool isActionEnabled = false;
1269   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1270   QList<ActionInfo> aUndoRes;
1271   QList<ActionInfo> aRedoRes;
1272   if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled)) {
1273     aUndoRes = anActiveWidget->actionsList(ActionUndo);
1274     aRedoRes = anActiveWidget->actionsList(ActionRedo);
1275   } else {
1276     std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1277     aUndoRes = processHistoryList(aUndoList);
1278
1279     std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1280     aRedoRes = processHistoryList(aRedoList);
1281   }
1282   emit updateUndoHistory(aUndoRes);
1283   emit updateRedoHistory(aRedoRes);
1284 }
1285
1286 //******************************************************
1287 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1288 {
1289   QDockWidget* aObjDock = new QDockWidget(theParent);
1290   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1291                             Qt::RightDockWidgetArea |
1292                             Qt::BottomDockWidgetArea);
1293   aObjDock->setWindowTitle(tr("Object browser"));
1294   aObjDock->setStyleSheet(
1295       "::title { position: relative; padding-left: 5px; text-align: left center }");
1296   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1297   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1298   myModule->customizeObjectBrowser(myObjectBrowser);
1299   aObjDock->setWidget(myObjectBrowser);
1300
1301   myContextMenuMgr->connectObjectBrowser();
1302   return aObjDock;
1303 }
1304
1305 //******************************************************
1306 /*
1307  * Creates dock widgets, places them in corresponding area
1308  * and tabifies if necessary.
1309  */
1310 void XGUI_Workshop::createDockWidgets()
1311 {
1312   QMainWindow* aDesktop = desktop();
1313   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1314   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1315   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1316   myActiveControlMgr->addSelector(new XGUI_PropertyPanelSelector(myPropertyPanel));
1317
1318   myPropertyPanel->setupActions(myActionsMgr);
1319   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1320                                    Qt::RightDockWidgetArea |
1321                                    Qt::BottomDockWidgetArea);
1322   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1323   hidePanel(myPropertyPanel);  ///<! Invisible by default
1324
1325   myFacesPanel = new XGUI_FacesPanel(aDesktop, myModuleConnector);
1326   myActiveControlMgr->addSelector(new XGUI_FacesPanelSelector(myFacesPanel));
1327   myFacesPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1328                                 Qt::RightDockWidgetArea |
1329                                 Qt::BottomDockWidgetArea);
1330   connect(myFacesPanel, SIGNAL(closed()), myFacesPanel, SLOT(onClosed()));
1331
1332   aDesktop->addDockWidget(
1333 #ifdef HAVE_SALOME
1334     Qt::RightDockWidgetArea,
1335 #else
1336     Qt::LeftDockWidgetArea,
1337 #endif
1338     myFacesPanel);
1339   hidePanel(myFacesPanel);  ///<! Invisible by default
1340
1341 #ifdef _DEBUG
1342   bool aShowOnTheRight = Config_PropManager::boolean("Plugins", "show_hide_faces");
1343   if (aShowOnTheRight) {
1344     aDesktop->addDockWidget(Qt::RightDockWidgetArea, myFacesPanel);
1345     showPanel(myFacesPanel);
1346   }
1347 #endif
1348   hideObjectBrowser();
1349
1350 #ifndef HAVE_SALOME
1351 #ifdef _DEBUG
1352   if (!aShowOnTheRight)
1353   {
1354 #endif // _DEBUG
1355   aDesktop->tabifyDockWidget(myFacesPanel, aObjDock);
1356 #ifdef _DEBUG
1357   }
1358 #endif // _DEBUG
1359
1360 #endif // HAVE_SALOME
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 #ifdef HAVE_SALOME
2536 //******************************************************
2537 void XGUI_Workshop::synchronizeViewer()
2538 {
2539   SessionPtr aMgr = ModelAPI_Session::get();
2540   QList<DocumentPtr> aDocs;
2541   aDocs.append(aMgr->activeDocument());
2542   aDocs.append(aMgr->moduleDocument());
2543
2544   foreach(DocumentPtr aDoc, aDocs) {
2545     synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2546     synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2547     synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2548     synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2549   }
2550 }
2551
2552 //******************************************************
2553 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2554                                              const std::string& theGroup,
2555                                              bool theUpdateViewer)
2556 {
2557   ObjectPtr aObj;
2558   int aSize = theDoc->size(theGroup);
2559   for (int i = 0; i < aSize; i++) {
2560     aObj = theDoc->object(theGroup, i);
2561     if (aObj->isDisplayed()) {
2562       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2563       // be changed to the object becomes visible when the shape becomes not empty
2564       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2565       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2566         continue;
2567       myDisplayer->display(aObj, false);
2568     }
2569   }
2570   if (theUpdateViewer)
2571     myDisplayer->updateViewer();
2572 }
2573 #endif
2574
2575 //******************************************************
2576 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2577 {
2578   FeaturePtr aFeature;
2579   QObjectPtrList aSelList = theObjects;
2580   bool aHasHidden = false;
2581   foreach(ObjectPtr aObj, theObjects) {
2582     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2583     if (aFeature.get()) {
2584       std::list<ResultPtr> aResults;
2585       ModelAPI_Tools::allResults(aFeature, aResults);
2586       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2587       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2588         aHasHidden |= (*aIt)->isConcealed();
2589         aSelList.append(*aIt);
2590       }
2591     }
2592   }
2593   if (aSelList.count() > theObjects.count()) {
2594     // if something was found
2595     bool aBlocked = objectBrowser()->blockSignals(true);
2596     objectBrowser()->setObjectsSelected(aSelList);
2597     objectBrowser()->blockSignals(aBlocked);
2598   }
2599   if (aHasHidden)
2600     QMessageBox::information(desktop(), tr("Find results"),
2601                              tr("Results not found"), QMessageBox::Ok);
2602 }
2603
2604 //******************************************************
2605 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2606 {
2607   ResultPtr aResult;
2608   QObjectPtrList aSelList = theObjects;
2609   FeaturePtr aFeature;
2610   foreach(ObjectPtr aObj, theObjects) {
2611     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2612     if (aResult.get()) {
2613       aFeature = ModelAPI_Feature::feature(aResult);
2614       if (aFeature.get()) {
2615         aSelList.append(aFeature);
2616       }
2617     }
2618   }
2619   if (aSelList.count() > theObjects.count()) {
2620     // if something was found
2621     bool aBlocked = objectBrowser()->blockSignals(true);
2622     objectBrowser()->setObjectsSelected(aSelList);
2623     objectBrowser()->blockSignals(aBlocked);
2624   }
2625 }
2626
2627 void XGUI_Workshop::insertFeatureFolder()
2628 {
2629   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2630   if (aObjects.isEmpty())
2631     return;
2632   ObjectPtr aObj = aObjects.first();
2633   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2634   if (aFeature.get() == NULL)
2635     return;
2636   SessionPtr aMgr = ModelAPI_Session::get();
2637   DocumentPtr aDoc = aMgr->activeDocument();
2638
2639   aMgr->startOperation();
2640   aDoc->addFolder(aFeature);
2641   aMgr->finishOperation();
2642 }
2643
2644
2645 void XGUI_Workshop::insertToFolder(bool isBefore)
2646 {
2647   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2648   if (aFeatures.empty())
2649     return;
2650
2651   SessionPtr aMgr = ModelAPI_Session::get();
2652   DocumentPtr aDoc = aMgr->activeDocument();
2653
2654   FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
2655                                 aDoc->findFolderBelow(aFeatures);
2656   if (!aFolder.get())
2657     return;
2658
2659   aMgr->startOperation();
2660   aDoc->moveToFolder(aFeatures, aFolder);
2661   aMgr->finishOperation();
2662 }
2663
2664 void XGUI_Workshop::moveOutFolder(bool isBefore)
2665 {
2666   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2667   if (aFeatures.empty())
2668     return;
2669
2670   SessionPtr aMgr = ModelAPI_Session::get();
2671   DocumentPtr aDoc = aMgr->activeDocument();
2672
2673   aMgr->startOperation();
2674   aDoc->removeFromFolder(aFeatures, isBefore);
2675   aMgr->finishOperation();
2676 }