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