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