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