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