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