Salome HOME
Merge branch 'nrn/Lot2/AutoColor' into master
[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   QApplication::restoreOverrideCursor();
1071 }
1072
1073 //******************************************************
1074 void XGUI_Workshop::onNew()
1075 {
1076   QApplication::setOverrideCursor(Qt::WaitCursor);
1077   if (objectBrowser() == 0) {
1078     createDockWidgets();
1079     mySelector->connectViewers();
1080   }
1081   myViewerProxy->connectToViewer();
1082   showObjectBrowser();
1083 #ifndef HAVE_SALOME
1084   myMainWindow->showPythonConsole();
1085   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
1086   aWnd->showMaximized();
1087   updateCommandStatus();
1088   PyConsole_Console* aConsole = myMainWindow->pythonConsole();
1089   connect(aConsole, SIGNAL(scriptLoaded()), SLOT(updateCommandStatus()));
1090 #endif
1091   myContextMenuMgr->connectViewer();
1092   QApplication::restoreOverrideCursor();
1093 }
1094
1095 #ifndef HAVE_SALOME
1096 //******************************************************
1097 void XGUI_Workshop::onExit()
1098 {
1099   SessionPtr aMgr = ModelAPI_Session::get();
1100   if (aMgr->isModified()) {
1101     int anAnswer = QMessageBox::question(
1102         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
1103         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
1104     if (anAnswer == QMessageBox::Save) {
1105       bool saved = onSave();
1106       if (!saved) {
1107         return;
1108       }
1109     } else if (anAnswer == QMessageBox::Cancel) {
1110       return;
1111     }
1112   }
1113   qApp->exit();
1114 }
1115
1116 //******************************************************
1117 void XGUI_Workshop::onPreferences()
1118 {
1119   ModuleBase_Prefs aModif;
1120   ModuleBase_Preferences::editPreferences(aModif);
1121   if (aModif.size() > 0) {
1122     QString aSection;
1123     foreach (ModuleBase_Pref aPref, aModif) {
1124       aSection = aPref.first;
1125       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1126         myMainWindow->viewer()->updateFromResources();
1127       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1128         myMainWindow->menuObject()->updateFromResources();
1129       }
1130     }
1131     std::vector<int> aColor;
1132     try {
1133       aColor = Config_PropManager::color("Visualization", "selection_color");
1134     }
1135     catch (...) {
1136     }
1137     if (aColor.size() == 3)
1138       displayer()->setSelectionColor(aColor);
1139
1140     displayer()->redisplayObjects();
1141   }
1142 }
1143 #endif
1144
1145 //******************************************************
1146 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
1147 {
1148   XGUI_Displayer* aDisplayer = displayer();
1149   if (aDisplayer) {
1150     aDisplayer->displayTrihedron(theState);
1151     aDisplayer->updateViewer();
1152   }
1153 }
1154
1155 //******************************************************
1156 bool XGUI_Workshop::onSave()
1157 {
1158   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
1159     return false;
1160   if (myCurrentFile.isEmpty()) {
1161     return onSaveAs();
1162   }
1163   SessionPtr aMgr = ModelAPI_Session::get();
1164   if (aMgr->isAutoUpdateBlocked())
1165     aMgr->blockAutoUpdate(false);
1166
1167   std::list<std::string> aFiles;
1168   // issue #2899: create a temporary directory, save and then remove it
1169 #ifdef HAVE_SALOME
1170   std::string aTmpDir = XGUI_Tools::getTmpDirByEnv("SALOME_TMP_DIR");
1171 #else
1172   std::string aTmpDir = XGUI_Tools::getTmpDirByEnv("");
1173 #endif
1174   saveDocument(QString(aTmpDir.c_str()), aFiles);
1175   bool aResult = XGUI_CompressFiles::compress(myCurrentFile, aFiles);
1176   XGUI_Tools::removeTemporaryFiles(aTmpDir, aFiles);
1177
1178   if (aResult) {
1179     updateCommandStatus();
1180 #ifndef HAVE_SALOME
1181     myMainWindow->setModifiedState(false);
1182 #endif
1183   }
1184   return aResult;
1185 }
1186
1187 //******************************************************
1188 bool XGUI_Workshop::onSaveAs()
1189 {
1190   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
1191     return false;
1192   qreal aRatio = ModuleBase_Tools::currentPixelRatio();
1193   myCurrentFile = QFileDialog::getSaveFileName(desktop(), tr("Select name to save file..."),
1194     QString(), MyFilter2,
1195     Q_NULLPTR, ((aRatio > 1) ? QFileDialog::DontUseNativeDialog : QFileDialog::Options()));
1196   if (!myCurrentFile.isNull()) {
1197     if (!myCurrentFile.endsWith(MyExtension)) {
1198       myCurrentFile += MyExtension;
1199     }
1200   }
1201   else
1202     return false;
1203 #ifndef HAVE_SALOME
1204     myMainWindow->setCurrentDir(myCurrentFile, false);
1205     myMainWindow->setModifiedState(false);
1206 #endif
1207   return onSave();
1208 }
1209
1210 //******************************************************
1211 void XGUI_Workshop::onUndo(int theTimes)
1212 {
1213   processUndoRedo(ActionUndo, theTimes);
1214   myObjectBrowser->updateAllIndexes(1);
1215 }
1216
1217 //******************************************************
1218 void XGUI_Workshop::onRedo(int theTimes)
1219 {
1220   processUndoRedo(ActionRedo, theTimes);
1221   myObjectBrowser->updateAllIndexes(1);
1222 }
1223
1224 //******************************************************
1225 void XGUI_Workshop::processUndoRedo(const ModuleBase_ActionType theActionType, int theTimes)
1226 {
1227   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1228   if (anActiveWidget) {
1229     ActionIntParamPtr aParam(new ModuleBase_ActionIntParameter(theTimes));
1230     if (anActiveWidget->processAction(theActionType, aParam))
1231       return;
1232   }
1233   else
1234   {
1235     XGUI_FacesPanel *  anFacePannel = facesPanel();
1236     if(ActionUndo == theActionType && anFacePannel->isActivePanel())
1237     {
1238       anFacePannel->processUndo();
1239       return;
1240     }
1241   }
1242   // the viewer update should be blocked in order to avoid the features blinking. For the created
1243   // feature a results are created, the flush of the created signal caused the viewer redisplay for
1244   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1245   // until redo of all possible objects happens
1246   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1247
1248   int aTimes = theTimes;
1249   SessionPtr aMgr = ModelAPI_Session::get();
1250   if (aMgr->isOperation()) {
1251     XGUI_OperationMgr* aOpMgr = operationMgr();
1252     /// this is important for nested operations
1253     /// when sketch operation is active, this condition is false and
1254     /// the sketch operation is not aborted
1255     if (aOpMgr->canStopOperation(aOpMgr->currentOperation())) {
1256       aOpMgr->abortOperation(aOpMgr->currentOperation());
1257       aTimes--;
1258     }
1259     else
1260     {
1261       myDisplayer->enableUpdateViewer(isUpdateEnabled);
1262       return;
1263     }
1264   }
1265   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1266   std::list<std::string> anActionList = theActionType == ActionUndo ? aMgr->undoList()
1267     : aMgr->redoList();
1268   std::list<std::string>::const_iterator aIt = anActionList.cbegin();
1269   for (int i = 0; (i < aTimes) && (aIt != anActionList.cend()); ++i, ++aIt) {
1270     if (theActionType == ActionUndo)
1271       aMgr->undo();
1272     else
1273       aMgr->redo();
1274
1275     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND ||
1276         QString((*aIt).c_str()) == MOVE_TO_END_SPLIT_COMMAND)
1277       myObjectBrowser->rebuildDataTree();
1278   }
1279   operationMgr()->updateApplyOfOperations();
1280   facesPanel()->reset(true);
1281   updateCommandStatus();
1282
1283   // unblock the viewer update functionality and make update on purpose
1284   myDisplayer->enableUpdateViewer(isUpdateEnabled);
1285   myDisplayer->updateViewer();
1286   // Clear messages in status bar from previous operations if exists
1287   setStatusBarMessage("");
1288 }
1289
1290 //******************************************************
1291 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1292 {
1293   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1294   //ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1295   //if (anOperation) {
1296   //  ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1297   //  if (aPanel)
1298   //    anActiveWidget = aPanel->activeWidget();
1299   //}
1300   if (anActiveWidget)
1301     operationMgr()->onValidateOperation();
1302
1303   myModule->widgetStateChanged(thePreviousState);
1304 }
1305
1306 //******************************************************
1307 void XGUI_Workshop::onValuesChanged()
1308 {
1309   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1310   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1311     return;
1312
1313   ModuleBase_ModelWidget* anActiveWidget = 0;
1314   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1315   if (anOperation) {
1316     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1317     if (aPanel)
1318       anActiveWidget = aPanel->activeWidget();
1319   }
1320   if (anActiveWidget) {
1321     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1322                                                                            (anActiveWidget);
1323     if (aWidgetValidated)
1324       aWidgetValidated->clearValidatedCash();
1325   }
1326 }
1327
1328 //******************************************************
1329 void XGUI_Workshop::onWidgetObjectUpdated()
1330 {
1331   operationMgr()->onValidateOperation();
1332   myDisplayer->updateViewer();
1333 }
1334
1335 //******************************************************
1336 void XGUI_Workshop::onImportPart()
1337 {
1338   if (abortAllOperations()) {
1339     ModuleBase_OperationFeature* anImportPartOp = dynamic_cast<ModuleBase_OperationFeature*>(
1340         module()->createOperation(ExchangePlugin_ImportPart::ID()));
1341     anImportPartOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1342       "importFeature.html");
1343     myPropertyPanel->updateApplyPlusButton(anImportPartOp->feature());
1344     operationMgr()->startOperation(anImportPartOp);
1345   }
1346 }
1347
1348 //******************************************************
1349 void XGUI_Workshop::onImportShape()
1350 {
1351   if (abortAllOperations()) {
1352     ModuleBase_OperationFeature* anImportOp = dynamic_cast<ModuleBase_OperationFeature*>(
1353         module()->createOperation(ExchangePlugin_Import::ID()));
1354     anImportOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1355       "importFeature.html");
1356     myPropertyPanel->updateApplyPlusButton(anImportOp->feature());
1357     operationMgr()->startOperation(anImportOp);
1358   }
1359 }
1360
1361 //******************************************************
1362 void XGUI_Workshop::onImportImage()
1363 {
1364   if (abortAllOperations()) {
1365     ModuleBase_OperationFeature* anImportOp = dynamic_cast<ModuleBase_OperationFeature*>(
1366         module()->createOperation(ExchangePlugin_Import_Image::ID()));
1367     anImportOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1368       "importFeature.html");
1369     myPropertyPanel->updateApplyPlusButton(anImportOp->feature());
1370     operationMgr()->startOperation(anImportOp);
1371   }
1372 }
1373
1374 //******************************************************
1375 void XGUI_Workshop::onExportShape()
1376 {
1377   if (abortAllOperations()) {
1378     ModuleBase_OperationFeature* anExportOp = dynamic_cast<ModuleBase_OperationFeature*>(
1379         module()->createOperation(ExchangePlugin_ExportFeature::ID()));
1380     anExportOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1381       "exportFeature.html");
1382     myPropertyPanel->updateApplyPlusButton(anExportOp->feature());
1383     operationMgr()->startOperation(anExportOp);
1384   }
1385 }
1386
1387 //******************************************************
1388 void XGUI_Workshop::onExportPart()
1389 {
1390   if (abortAllOperations()) {
1391     ModuleBase_OperationFeature* anExportPartOp = dynamic_cast<ModuleBase_OperationFeature*>(
1392         module()->createOperation(ExchangePlugin_ExportPart::ID()));
1393     anExportPartOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1394       "exportFeature.html");
1395     myPropertyPanel->updateApplyPlusButton(anExportPartOp->feature());
1396     operationMgr()->startOperation(anExportPartOp);
1397   }
1398 }
1399
1400 //******************************************************
1401 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1402 {
1403   QString libName = QString::fromStdString(library(theModule.toStdString()));
1404   if (libName.isEmpty()) {
1405     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1406     return 0;
1407   }
1408
1409   QString err;
1410   CREATE_FUNC crtInst = 0;
1411
1412 #ifdef WIN32
1413   HINSTANCE modLib = ::LoadLibraryA(qPrintable(libName));
1414   if (!modLib) {
1415     LPVOID lpMsgBuf;
1416     ::FormatMessage(
1417         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1418         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1419     QString aMsg((char*) &lpMsgBuf);
1420     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1421     ::LocalFree(lpMsgBuf);
1422   } else {
1423     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1424     if (!crtInst) {
1425       LPVOID lpMsgBuf;
1426       ::FormatMessage(
1427           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1428               | FORMAT_MESSAGE_IGNORE_INSERTS,
1429           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1430       QString aMsg((char*) &lpMsgBuf);
1431       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1432       ::LocalFree(lpMsgBuf);
1433     }
1434   }
1435 #else
1436   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1437   if ( !modLib ) {
1438     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1439   } else {
1440     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1441     if ( !crtInst ) {
1442       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1443     }
1444   }
1445 #endif
1446
1447   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1448
1449   if (!err.isEmpty()) {
1450     if (desktop()) {
1451       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1452     } else {
1453       qWarning(qPrintable(err));
1454     }
1455   }
1456   return aModule;
1457 }
1458
1459 //******************************************************
1460 bool XGUI_Workshop::createModule()
1461 {
1462   Config_ModuleReader aModuleReader;
1463   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1464   myModule = loadModule(moduleName);
1465   if (!myModule)
1466     return false;
1467
1468   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1469   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1470   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1471   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1472
1473   myModule->createFeatures();
1474 #ifdef HAVE_SALOME
1475   salomeConnector()->createFeatureActions();
1476 #endif
1477   //myActionsMgr->update();
1478   return true;
1479 }
1480
1481 //******************************************************
1482 void XGUI_Workshop::updateCommandStatus()
1483 {
1484   QList<QAction*> aCommands;
1485 #ifdef HAVE_SALOME
1486     aCommands = salomeConnector()->commandList();
1487 #else
1488     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1489     foreach (AppElements_Command* aCmd, aMenuBar->features())
1490       aCommands.append(aCmd);
1491 #endif
1492   SessionPtr aMgr = ModelAPI_Session::get();
1493   if (aMgr->hasModuleDocument()) {
1494     foreach(QAction* aCmd, aCommands) {
1495       QString aId = aCmd->data().toString();
1496       if (aId == "UNDO_CMD") {
1497         bool isActionEnabled = false;
1498         // if ultimate is true -> using result of operation only, or using OR combination
1499         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1500         if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled))
1501           aCmd->setEnabled(isActionEnabled);
1502         else
1503           aCmd->setEnabled(myModule->canUndo());
1504       }
1505       else if (aId == "REDO_CMD") {
1506         bool isActionEnabled = false;
1507         // if ultimate is true -> using result of operation only, or using OR combination
1508         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1509         if (anActiveWidget && anActiveWidget->canProcessAction(ActionRedo, isActionEnabled))
1510           aCmd->setEnabled(isActionEnabled);
1511         else
1512           aCmd->setEnabled(myModule->canRedo());
1513       }
1514       else if (aId == "AUTOCOMPUTE_CMD") {
1515         aCmd->setIcon(aMgr->isAutoUpdateBlocked() ?
1516           QIcon(":pictures/autoapply_stop.png") :
1517           QIcon(":pictures/autoapply_start.png"));
1518       }
1519       else
1520         // Enable all commands
1521         aCmd->setEnabled(true);
1522     }
1523     updateHistory();
1524   } else {
1525     foreach(QAction* aCmd, aCommands) {
1526       QString aId = aCmd->data().toString();
1527       if (aId == "NEW_CMD")
1528         aCmd->setEnabled(true);
1529       else if (aId == "EXIT_CMD")
1530         aCmd->setEnabled(true);
1531       else
1532         aCmd->setEnabled(false);
1533     }
1534   }
1535   myActionsMgr->updateCommandsStatus();
1536   emit commandStatusUpdated();
1537 }
1538
1539 //******************************************************
1540 void XGUI_Workshop::updateHistory()
1541 {
1542   bool isActionEnabled = false;
1543   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1544   QList<ActionInfo> aUndoRes;
1545   QList<ActionInfo> aRedoRes;
1546   if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled)) {
1547     aUndoRes = anActiveWidget->actionsList(ActionUndo);
1548     aRedoRes = anActiveWidget->actionsList(ActionRedo);
1549   } else {
1550     std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1551     aUndoRes = processHistoryList(aUndoList);
1552
1553     std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1554     aRedoRes = processHistoryList(aRedoList);
1555   }
1556   emit updateUndoHistory(aUndoRes);
1557   emit updateRedoHistory(aRedoRes);
1558 }
1559
1560 //******************************************************
1561 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1562 {
1563   QDockWidget* aObjDock = new QDockWidget(theParent);
1564   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1565                             Qt::RightDockWidgetArea);
1566   aObjDock->setWindowTitle(tr("Object browser"));
1567   aObjDock->setStyleSheet(
1568       "::title { position: relative; padding-left: 5px; text-align: left center }");
1569   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1570   myObjectBrowser->initialize(myModule->rootNode());
1571   myModule->customizeObjectBrowser(myObjectBrowser);
1572   aObjDock->setWidget(myObjectBrowser);
1573   aObjDock->setObjectName("Object browser");
1574
1575   connect(myObjectBrowser, SIGNAL(sizeChanged()), SLOT(onDockSizeChanged()));
1576
1577   myContextMenuMgr->connectObjectBrowser();
1578   return aObjDock;
1579 }
1580
1581 //******************************************************
1582 /*
1583  * Creates dock widgets, places them in corresponding area
1584  * and tabifies if necessary.
1585  */
1586 void XGUI_Workshop::createDockWidgets()
1587 {
1588   QMainWindow* aDesktop = desktop();
1589   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1590   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1591   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1592   myActiveControlMgr->addSelector(new XGUI_PropertyPanelSelector(myPropertyPanel));
1593
1594   myPropertyPanel->setupActions(myActionsMgr);
1595   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1596                                    Qt::RightDockWidgetArea);
1597   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1598
1599   hidePanel(myPropertyPanel);  ///<! Invisible by default
1600
1601   myFacesPanel = new XGUI_FacesPanel(aDesktop, this);
1602   myActiveControlMgr->addSelector(new XGUI_FacesPanelSelector(myFacesPanel));
1603   myFacesPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1604                                 Qt::RightDockWidgetArea |
1605                                 Qt::BottomDockWidgetArea);
1606   connect(myFacesPanel, SIGNAL(closed()), myFacesPanel, SLOT(onClosed()));
1607
1608   myInspectionPanel = new XGUI_InspectionPanel(aDesktop, this);
1609   myInspectionPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1610     Qt::RightDockWidgetArea);
1611   aDesktop->addDockWidget(Qt::RightDockWidgetArea, myInspectionPanel);
1612
1613   myInspectionPanel->hide();
1614
1615   aDesktop->addDockWidget(
1616 #ifdef HAVE_SALOME
1617     Qt::RightDockWidgetArea,
1618 #else
1619     Qt::LeftDockWidgetArea,
1620 #endif
1621     myFacesPanel);
1622   hidePanel(myFacesPanel);  ///<! Invisible by default
1623
1624 #ifdef _DEBUG
1625   bool aShowOnTheRight = Config_PropManager::boolean("Plugins", "show_hide_faces");
1626   if (aShowOnTheRight) {
1627     aDesktop->addDockWidget(Qt::RightDockWidgetArea, myFacesPanel);
1628     showPanel(myFacesPanel);
1629   }
1630 #endif
1631   hideObjectBrowser();
1632
1633 #ifndef HAVE_SALOME
1634 #ifdef _DEBUG
1635   if (!aShowOnTheRight)
1636   {
1637 #endif // _DEBUG
1638   aDesktop->tabifyDockWidget(myFacesPanel, aObjDock);
1639 #ifdef _DEBUG
1640   }
1641 #endif // _DEBUG
1642
1643 #endif // HAVE_SALOME
1644
1645   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1646   myPropertyPanel->installEventFilter(myOperationMgr);
1647
1648   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1649   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1650
1651   QAction* aOkContAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptPlus);
1652   connect(aOkContAct, SIGNAL(triggered()), this, SLOT(onAcceptPlusActionClicked()));
1653
1654   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1655   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1656
1657   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1658   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1659
1660   QAction* aHelpAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Help);
1661   connect(aHelpAct, SIGNAL(triggered()), this, SLOT(onHelpActionClicked()));
1662
1663   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1664           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1665   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1666           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1667 }
1668
1669 //******************************************************
1670 void XGUI_Workshop::showPanel(QDockWidget* theDockWidget)
1671 {
1672   if (theDockWidget == myPropertyPanel) {
1673     QAction* aViewAct = myPropertyPanel->toggleViewAction();
1674     ///<! Restore ability to close panel from the window's menu
1675     aViewAct->setEnabled(true);
1676   }
1677   theDockWidget->show();
1678   theDockWidget->raise();
1679
1680   // The next code is necessary to made the property panel the active window
1681   // in order to operation manager could process key events of the panel.
1682   // otherwise they are ignored. It happens only if the same(activateWindow) is
1683   // not happened by property panel activation(e.g. resume operation of Sketch)
1684   //ModuleBase_Tools::setFocus(theDockWidget, "XGUI_Workshop::showPanel()");
1685 }
1686
1687 //******************************************************
1688 void XGUI_Workshop::hidePanel(QDockWidget* theDockWidget)
1689 {
1690   if (theDockWidget && theDockWidget == myPropertyPanel) {
1691     QAction* aViewAct = theDockWidget->toggleViewAction();
1692     ///<! Do not allow to show empty property panel
1693     aViewAct->setEnabled(false);
1694   }
1695   theDockWidget->hide();
1696
1697   // the property panel is active window of the desktop, when it is
1698   // hidden, it is undefined which window becomes active. By this reason
1699   // it is defined to perform the desktop as the active window.
1700   // in SALOME mode, work-stack made the PyConsole the active window,
1701   // set the focus on it. As a result, shortcuts of the application, like
1702   // are processed by this console. For example Undo actions.
1703   // It is possible that this code is to be moved to SHAPER package
1704   QMainWindow* aDesktop = desktop();
1705   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::hidePanel()");
1706 }
1707
1708 //******************************************************
1709 void XGUI_Workshop::showObjectBrowser()
1710 {
1711   if (!isSalomeMode()) {
1712     myObjectBrowser->parentWidget()->show();
1713   }
1714 }
1715
1716 //******************************************************
1717 void XGUI_Workshop::hideObjectBrowser()
1718 {
1719   if (!isSalomeMode())
1720     myObjectBrowser->parentWidget()->hide();
1721 }
1722
1723 //******************************************************
1724 void XGUI_Workshop::salomeViewerSelectionChanged()
1725 {
1726   emit salomeViewerSelection();
1727 }
1728
1729 //**************************************************************
1730 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1731 {
1732   return mySalomeConnector->viewer();
1733 }
1734
1735 //**************************************************************
1736 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1737 {
1738   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1739   if (theId == "DELETE_CMD")
1740     deleteObjects();
1741   else if (theId == "CLEAN_HISTORY_CMD")
1742     cleanHistory();
1743   else if (theId == "MOVE_CMD" || theId == "MOVE_SPLIT_CMD")
1744     moveObjects(theId == "MOVE_SPLIT_CMD");
1745   else if (theId == "COLOR_CMD")
1746     changeColor(anObjects);
1747   else if (theId == "AUTOCOLOR_CMD")
1748     changeAutoColor(anObjects);
1749   else if (theId == "ISOLINES_CMD")
1750     changeIsoLines(anObjects);
1751   else if (theId == "SHOW_ISOLINES_CMD") {
1752     foreach(ObjectPtr aObj, anObjects) {
1753       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1754       if (aResult.get())
1755         ModelAPI_Tools::showIsoLines(aResult, !ModelAPI_Tools::isShownIsoLines(aResult));
1756     }
1757     mySelector->clearSelection();
1758     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1759   }
1760   else if (theId == "DEFLECTION_CMD")
1761     changeDeflection(anObjects);
1762   else if (theId == "TRANSPARENCY_CMD")
1763     changeTransparency(anObjects);
1764   else if (theId == "SHOW_CMD") {
1765     showObjects(anObjects, true);
1766     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1767     updateCommandStatus();
1768   }
1769   else if (theId == "HIDE_CMD") {
1770     showObjects(anObjects, false);
1771     updateCommandStatus();
1772   }
1773   else if (theId == "SHOW_ONLY_CMD") {
1774     showOnlyObjects(anObjects);
1775     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1776     updateCommandStatus();
1777   }
1778   else if (theId == "SHADING_CMD")
1779     setDisplayMode(anObjects, XGUI_Displayer::Shading);
1780   else if (theId == "WIREFRAME_CMD")
1781     setDisplayMode(anObjects, XGUI_Displayer::Wireframe);
1782   else if (theId == "HIDEALL_CMD") {
1783     QObjectPtrList aList = myDisplayer->displayedObjects();
1784     foreach (ObjectPtr aObj, aList) {
1785       if (module()->canEraseObject(aObj))
1786         aObj->setDisplayed(false);
1787     }
1788     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1789 #ifdef HAVE_SALOME
1790     //issue #2159 Hide all incomplete behavior
1791     viewer()->eraseAll();
1792 #endif
1793     updateCommandStatus();
1794     // Necessary for update icons in ObjectBrowser on Linux
1795     myObjectBrowser->updateAllIndexes();
1796   } else if (theId == "SELECT_VERTEX_CMD") {
1797     setViewerSelectionMode(TopAbs_VERTEX);
1798   } else if (theId == "SELECT_EDGE_CMD") {
1799     setViewerSelectionMode(TopAbs_EDGE);
1800   } else if (theId == "SELECT_FACE_CMD") {
1801     setViewerSelectionMode(TopAbs_FACE);
1802   } else if (theId == "INSERT_FOLDER_CMD") {
1803     insertFeatureFolder();
1804   } else if (theId == "ADD_TO_FOLDER_BEFORE_CMD") {
1805     insertToFolder(true);
1806   } else if (theId == "ADD_TO_FOLDER_AFTER_CMD") {
1807     insertToFolder(false);
1808   } else if (theId == "ADD_OUT_FOLDER_BEFORE_CMD") {
1809     moveOutFolder(true);
1810   } else if (theId == "ADD_OUT_FOLDER_AFTER_CMD") {
1811     moveOutFolder(false);
1812   } else if (theId == "SELECT_RESULT_CMD") {
1813     //setViewerSelectionMode(-1);
1814     //IMP: an attempt to use result selection with other selection modes
1815     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1816     setViewerSelectionMode(TopAbs_COMPSOLID);
1817   } else if (theId == "SHOW_RESULTS_CMD") {
1818     highlightResults(anObjects);
1819   } else if (theId == "SHOW_FEATURE_CMD") {
1820     highlightFeature(anObjects);
1821   } else if (theId == "SET_VIEW_NORMAL_CMD") {
1822     setNormalView();
1823   } else if (theId == "SET_VIEW_INVERTEDNORMAL_CMD") {
1824     setNormalView(true);
1825   }
1826 #ifdef TINSPECTOR
1827   else if (theId == "TINSPECTOR_VIEW") {
1828     Handle(TDocStd_Application) anApplication = ModelAPI_Session::get()->application();
1829     if (!anApplication.IsNull())
1830     {
1831       if (!MyTCommunicator)
1832       {
1833         MyTCommunicator = new TInspector_Communicator();
1834
1835         NCollection_List<Handle(Standard_Transient)> aParameters;
1836         aParameters.Append(anApplication);
1837         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1838         if (!aContext.IsNull())
1839           aParameters.Append(aContext);
1840
1841 #ifdef DEBUG_WITH_MESSAGE_REPORT
1842         Handle(Message_Report) aContextReport = aContext->GetReport();
1843         aContext->SetReportActive (Standard_True);
1844         aContextReport->SetLimit (1000);
1845         if (!aContextReport.IsNull())
1846           aParameters.Append(aContextReport);
1847 #endif
1848         MyVCallBack = new VInspector_CallBack();
1849         myDisplayer->setCallBack(MyVCallBack);
1850         #ifndef HAVE_SALOME
1851         AppElements_Viewer* aViewer = mainWindow()->viewer();
1852         if (aViewer)
1853           aViewer->setCallBack(MyVCallBack);
1854         #endif
1855         aParameters.Append(MyVCallBack);
1856
1857         MyTCommunicator->RegisterPlugin("TKDFBrowser");
1858         MyTCommunicator->RegisterPlugin("TKShapeView");
1859         MyTCommunicator->RegisterPlugin("TKVInspector");
1860 #ifdef DEBUG_WITH_MESSAGE_REPORT
1861         MyTCommunicator->RegisterPlugin("TKMessageView");
1862 #endif
1863         //MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1864         //MyTCommunicator->RegisterPlugin("TKSMBrowser"); // custom plugin to view ModelAPI
1865
1866         MyTCommunicator->Init(aParameters);
1867         MyTCommunicator->Activate("TKSMBrowser"); // to have button in TInspector
1868 #ifndef DEBUG_WITH_MESSAGE_REPORT
1869         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1870 #endif
1871         MyTCommunicator->Activate("TKDFBrowser");
1872
1873 #ifdef DEBUG_WITH_MESSAGE_REPORT
1874         MyTCommunicator->Activate("TKMessageView"); // temporary
1875         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1876 #endif
1877       }
1878       MyTCommunicator->SetVisible(true);
1879     }
1880   }
1881 #endif
1882 }
1883
1884 //**************************************************************
1885 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1886 {
1887   if (theMode == -1)
1888     myViewerSelMode.clear();
1889   else {
1890     if (myViewerSelMode.contains(theMode))
1891       myViewerSelMode.removeAll(theMode);
1892     else
1893       myViewerSelMode.append(theMode);
1894   }
1895   selectionActivate()->updateSelectionModes();
1896 }
1897
1898 //**************************************************************
1899 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1900 {
1901   QIntList aModes;
1902   module()->activeSelectionModes(aModes);
1903   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1904     aModes.append(myViewerSelMode);
1905   selectionActivate()->activateObjects(aModes, theList);
1906 }
1907
1908 //**************************************************************
1909 bool XGUI_Workshop::prepareForDisplay(const std::set<ObjectPtr>& theObjects) const
1910 {
1911   if (facesPanel()->isEmpty())
1912     return true;
1913
1914   // generate container of objects taking into account sub elments of compsolid
1915   std::set<ObjectPtr> anAllProcessedObjects;
1916   for (std::set<ObjectPtr>::const_iterator anObjectsIt = theObjects.begin();
1917     anObjectsIt != theObjects.end(); anObjectsIt++) {
1918     ObjectPtr anObject = *anObjectsIt;
1919     ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
1920     if (aCompRes.get()) {
1921       std::list<ResultPtr> allRes;
1922       ModelAPI_Tools::allSubs(aCompRes, allRes);
1923       if (allRes.empty()) {
1924         anAllProcessedObjects.insert(anObject);
1925       } else {
1926         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1927           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1928           if (aBody.get() && aBody->numberOfSubs() == 0)
1929             anAllProcessedObjects.insert(aBody);
1930         }
1931       }
1932     } else
1933       anAllProcessedObjects.insert(anObject);
1934   }
1935
1936   // find hidden objects in faces panel
1937   std::set<ObjectPtr> aHiddenObjects;
1938   QStringList aHiddenObjectNames;
1939   for (std::set<ObjectPtr>::const_iterator anObjectsIt = anAllProcessedObjects.begin();
1940        anObjectsIt != anAllProcessedObjects.end(); anObjectsIt++) {
1941     if (!facesPanel()->isObjectHiddenByPanel(*anObjectsIt))
1942       continue;
1943     aHiddenObjects.insert(*anObjectsIt);
1944     aHiddenObjectNames.append(QString::fromStdWString((*anObjectsIt)->data()->name()));
1945   }
1946   if (aHiddenObjects.empty()) // in parameter objects there are no hidden objects in hide face
1947     return true;
1948
1949   int anAnswer = QMessageBox::question(
1950         desktop(), tr("Show object"),
1951         tr("'%1'\n are hidden by %2:\nRemove objects from the panel to be displayed?")
1952         .arg(aHiddenObjectNames.join(", ")).arg(facesPanel()->windowTitle()),
1953         QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
1954
1955   bool aToBeDisplayed = anAnswer == QMessageBox::Yes;
1956   if (aToBeDisplayed)
1957     facesPanel()->restoreObjects(aHiddenObjects);
1958
1959   return aToBeDisplayed;
1960 }
1961
1962 //**************************************************************
1963 void XGUI_Workshop::deleteObjects()
1964 {
1965   ModuleBase_IModule* aModule = module();
1966   // allow the module to delete objects, do nothing if it has succeed
1967   if (aModule->deleteObjects()) {
1968     updateCommandStatus();
1969     myDisplayer->updateViewer();
1970     return;
1971   }
1972
1973   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1974   if (anObjects.isEmpty())
1975     return;
1976
1977   if (!abortAllOperations())
1978     return;
1979
1980   bool hasResult = false;
1981   bool hasFeature = false;
1982   bool hasParameter = false;
1983   bool hasCompositeOwner = false;
1984   bool hasResultInHistory = false;
1985   bool hasFolder = false;
1986   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1987                                  hasResultInHistory, hasFolder);
1988   if (!(hasResult || hasFeature || hasParameter || hasFolder))
1989     return;
1990
1991   // Remove from the list non-deletable objects: infinite constructions which are not in history
1992   bool notDelete = true;
1993   QObjectPtrList::iterator aIt;
1994   for (aIt = anObjects.begin(); aIt != anObjects.end(); aIt++) {
1995     ObjectPtr aObj = (*aIt);
1996     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
1997     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1998     if (aFeature) {
1999       notDelete = (!aFeature->isInHistory()) && (aConstr && aConstr->isInfinite());
2000       if (notDelete) {
2001         anObjects.removeAll(aObj);
2002         aIt--;
2003       }
2004     }
2005   }
2006   // delete objects
2007   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
2008   std::set<FeaturePtr> aFeatures;
2009   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2010   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
2011
2012   std::set<FolderPtr> aFolders;
2013   ModuleBase_Tools::convertToFolders(anObjects, aFolders);
2014
2015   bool aDone = false;
2016   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
2017   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
2018   ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, module());
2019
2020   operationMgr()->startOperation(anOpAction);
2021
2022   std::set<FeaturePtr> aFeatureRefsToDelete;
2023   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
2024     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
2025     // It is necessary to clear selection in order to avoid selection changed event during
2026     // deletion and negative consequences connected with processing of already deleted items
2027     mySelector->clearSelection();
2028
2029     if (!aFeatureRefsToDelete.empty())
2030       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
2031     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
2032   }
2033   if (aFolders.size() > 0) {
2034     std::set<FolderPtr>::const_iterator anIt = aFolders.begin(),
2035                                          aLast = aFolders.end();
2036     for (; anIt != aLast; anIt++) {
2037       FolderPtr aFolder = *anIt;
2038       if (aFolder.get()) {
2039         DocumentPtr aDoc = aFolder->document();
2040         aDoc->removeFolder(aFolder);
2041       }
2042     }
2043   }
2044   // remove results selected
2045   std::list<ResultPtr> aResults;
2046   for(QObjectPtrList::const_iterator anIt = anObjects.begin(); anIt != anObjects.end(); anIt++) {
2047     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anIt);
2048     if (aRes.get() && aRes->data()->isValid() && !aRes->data()->isDeleted() &&
2049         aRes->groupName() != ModelAPI_ResultGroup::group() && // don't remove groups and fields
2050         aRes->groupName() != ModelAPI_ResultField::group()) // because they are badly selected
2051       aResults.push_back(aRes);
2052   }
2053   if (!aResults.empty()) {
2054     ModelAPI_Tools::removeResults(aResults);
2055   }
2056
2057   if (aDone)
2058     operationMgr()->commitOperation();
2059   else
2060     operationMgr()->abortOperation(operationMgr()->currentOperation());
2061
2062   myDisplayer->updateViewer();
2063 }
2064
2065 //**************************************************************
2066 void addRefsToFeature(const FeaturePtr& theFeature,
2067                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
2068                       std::set<FeaturePtr>& theReferences)
2069 {
2070   //if (theReferences.find(theFeature) != theReferences.end())
2071   //  return;
2072   if (theMainList.find(theFeature) == theMainList.end())
2073     return; // this feature is not in the selection list, so exists without references to it
2074   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
2075
2076   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
2077                                        aLast = aMainReferences.end();
2078   for (; anIt != aLast; anIt++) {
2079     FeaturePtr aRefFeature = *anIt;
2080     if (theReferences.find(aRefFeature) == theReferences.end())
2081       theReferences.insert(aRefFeature);
2082     addRefsToFeature(aRefFeature, theMainList, theReferences);
2083   }
2084 }
2085
2086 //**************************************************************
2087 void XGUI_Workshop::cleanHistory()
2088 {
2089   if (!abortAllOperations())
2090     return;
2091
2092   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2093   std::set<FeaturePtr> aFeatures;
2094   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2095
2096 #ifdef DEBUG_CLEAN_HISTORY
2097   QStringList anInfo;
2098   std::set<FeaturePtr>::const_iterator aFIt;
2099   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
2100     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
2101     anInfo.append(aFeature->name().c_str());
2102   }
2103   QString anInfoStr = anInfo.join(";\t");
2104   qDebug(QString("cleanHistory for: [%1] - %2").
2105     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
2106 #endif
2107
2108   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
2109   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
2110   // find for each object whether all reference values are in the map as key, that means that there
2111   // is no other reference in the model to this object, so it might be removed by cleaning history
2112   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - can't be deleted, dependency to bool_1
2113   // ext_1(bool_1, sk_3)  - can't be deleted, dependency to bool_1
2114   // vertex_1()
2115   // sk_2(ext_2) + (bool_1)  - can't be deleted, dependency to bool_1
2116   // ext_2(bool_1)  - can't be deleted, dependency to bool_1
2117   // sk_3()
2118   // Information: bool_1 is not selected
2119   std::set<FeaturePtr> anUnusedObjects;
2120   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
2121                                                               aMainLast = aReferences.end();
2122   for (; aMainIt != aMainLast; aMainIt++) {
2123     FeaturePtr aMainListFeature = aMainIt->first;
2124     std::set<FeaturePtr> aMainRefList = aMainIt->second;
2125     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
2126                                                   aRefLast = aMainRefList.end();
2127     bool aFeatureOutOfTheList = false;
2128     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
2129       FeaturePtr aRefFeature = *aRefIt;
2130       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
2131     }
2132     if (!aFeatureOutOfTheList)
2133       anUnusedObjects.insert(aMainListFeature);
2134   }
2135
2136 #ifdef DEBUG_CLEAN_HISTORY
2137   anInfo.clear();
2138   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
2139     FeaturePtr aFeature = *aFIt;
2140     anInfo.append(aFeature->name().c_str());
2141   }
2142   qDebug(QString("unused objects: [%1] - %2").
2143     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
2144 #endif
2145
2146   // warn about the references remove, break the delete operation if the user chose it
2147   if (!anUnusedObjects.empty()) {
2148     QStringList aNames;
2149     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
2150       aNames.append(QString::fromStdWString(aFeature->name()));
2151     }
2152     aNames.sort();
2153     QString anUnusedNames = aNames.join(", ");
2154
2155     QString anActionId = "CLEAN_HISTORY_CMD";
2156     QString aDescription = ModuleBase_Tools::translate("workshop",
2157         contextMenuMgr()->action(anActionId)->text().toStdString());
2158
2159     QMessageBox aMessageBox(desktop());
2160     aMessageBox.setWindowTitle(aDescription);
2161     aMessageBox.setIcon(QMessageBox::Warning);
2162     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2163     aMessageBox.setDefaultButton(QMessageBox::No);
2164
2165     const char* aKeyStr = "Unused features are the following: "
2166                           "%1.\nThese features will be deleted.\nWould you like to continue?";
2167     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
2168     aMessageBox.setText(aText);
2169     if (aMessageBox.exec() == QMessageBox::No)
2170       return;
2171
2172     // 1. start operation
2173     aDescription += "by deleting of " +
2174       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
2175     ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, module());
2176     operationMgr()->startOperation(anOpAction);
2177
2178     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
2179     // It is necessary to clear selection in order to avoid selection changed event during
2180     // deletion and negative consequences connected with processing of already deleted items
2181     mySelector->clearSelection();
2182
2183     std::set<FeaturePtr> anIgnoredFeatures;
2184     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
2185       operationMgr()->commitOperation();
2186     }
2187     else {
2188       operationMgr()->abortOperation(operationMgr()->currentOperation());
2189     }
2190   }
2191   else {
2192     QString anActionId = "CLEAN_HISTORY_CMD";
2193     QString aDescription = contextMenuMgr()->action(anActionId)->text();
2194
2195     QMessageBox aMessageBox(desktop());
2196     aMessageBox.setWindowTitle(aDescription);
2197     aMessageBox.setIcon(QMessageBox::Warning);
2198     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2199     aMessageBox.setDefaultButton(QMessageBox::No);
2200
2201     QString aText;
2202     aMessageBox.setStandardButtons(QMessageBox::Ok);
2203     aMessageBox.setDefaultButton(QMessageBox::Ok);
2204
2205     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
2206     aMessageBox.setText(aText);
2207
2208     if (aMessageBox.exec() == QMessageBox::No)
2209       return;
2210   }
2211 }
2212
2213 //**************************************************************
2214 bool compareFeature(const FeaturePtr& theF1, const FeaturePtr& theF2) {
2215   DocumentPtr aDoc = theF1->document();
2216   return aDoc->index(theF1) < aDoc->index(theF2);
2217 }
2218 void XGUI_Workshop::moveObjects(const bool theSplit)
2219 {
2220   if (!abortAllOperations())
2221     return;
2222
2223   SessionPtr aMgr = ModelAPI_Session::get();
2224
2225   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2226   // It is necessary to clear selection in order to avoid selection changed event during
2227   // moving and negative consequences connected with processing of already moved items
2228   mySelector->clearSelection();
2229   // check whether the object can be moved. There should not be parts which are not loaded
2230   std::set<FeaturePtr> aFeatures;
2231   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2232   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
2233     return;
2234
2235   QString anActionId = theSplit ? "MOVE_CMD" : "MOVE_SPLIT_CMD";
2236   QString aDescription = contextMenuMgr()->action(anActionId)->text();
2237   aMgr->startOperation(aDescription.toStdString());
2238
2239   // Sort features by index in document
2240   std::list<FeaturePtr> aFList(aFeatures.begin(), aFeatures.end());
2241   aFList.sort(compareFeature);
2242
2243   DocumentPtr anActiveDocument = aMgr->activeDocument();
2244   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
2245   std::list<FeaturePtr>::const_iterator anIt = aFList.begin(), aLast = aFList.end();
2246   for (; anIt != aLast; anIt++) {
2247     FeaturePtr aFeature = *anIt;
2248     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
2249       continue;
2250
2251     anActiveDocument->moveFeature(aFeature, aCurrentFeature, theSplit);
2252     aCurrentFeature = anActiveDocument->currentFeature(true);
2253   }
2254   aMgr->finishOperation();
2255   updateCommandStatus();
2256   myViewerProxy->update();
2257 }
2258
2259 //**************************************************************
2260 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
2261 {
2262   std::set<FeaturePtr> aFeatures;
2263   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
2264
2265   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
2266 }
2267
2268 //******************************************************
2269 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
2270 {
2271   bool isFoundResultType = false;
2272   foreach(ObjectPtr anObj, theObjects)
2273   {
2274     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2275     if (aResult.get() == NULL)
2276       continue;
2277
2278     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
2279     if (isFoundResultType)
2280       break;
2281   }
2282   return isFoundResultType;
2283 }
2284
2285 //**************************************************************
2286 // Returns the list of all features for theDocument and all features of
2287 // all nested parts.
2288 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
2289 {
2290   std::list<FeaturePtr> aResultList;
2291   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
2292   foreach (const FeaturePtr& aFeature, anAllFeatures) {
2293     // The order of appending features of the part and the part itself is important
2294
2295     // Append features from a part feature
2296     std::list<ResultPtr> aResults;
2297     ModelAPI_Tools::allResults(aFeature, aResults);
2298     foreach (const ResultPtr& aResult, aResults) {
2299       ResultPartPtr aResultPart =
2300           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
2301       if (aResultPart.get() && aResultPart->partDoc().get()) {
2302         // Recursion
2303         std::list<FeaturePtr> aPartFeatures = allFeatures(aResultPart->partDoc());
2304         aResultList.insert(aResultList.end(), aPartFeatures.begin(), aPartFeatures.end());
2305       }
2306     }
2307
2308     aResultList.push_back(aFeature);
2309   }
2310   return aResultList;
2311 }
2312
2313 //**************************************************************
2314 // Returns the list of features placed between theObject and the current feature
2315 // in the same document. Excludes theObject, includes the current feature.
2316 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
2317 {
2318   std::list<FeaturePtr> aResult;
2319   DocumentPtr aDocument = theObject->document();
2320   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
2321   // find the object iterator
2322   std::list<FeaturePtr>::iterator anObjectIt =
2323     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
2324   if (anObjectIt == anAllFeatures.end())
2325     return aResult;
2326   // find the current feature iterator
2327   std::list<FeaturePtr>::iterator aCurrentIt =
2328     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
2329   if (aCurrentIt == anAllFeatures.end())
2330     return aResult;
2331   // check the right order
2332   if (std::distance(anObjectIt, anAllFeatures.end()) <=
2333       std::distance(aCurrentIt, anAllFeatures.end()))
2334     return aResult;
2335   // exclude the object
2336   std::advance(anObjectIt, 1);
2337   // include the current feature
2338   std::advance(aCurrentIt, 1);
2339   return std::list<FeaturePtr>(anObjectIt, aCurrentIt);
2340 }
2341
2342 //******************************************************
2343 bool XGUI_Workshop::canMoveFeature()
2344 {
2345   QString anActionId = "MOVE_CMD";
2346
2347   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2348   QObjectPtrList aValidatedObjects;
2349   foreach (ObjectPtr anObject, anObjects) {
2350     if (!myModule->canApplyAction(anObject, anActionId))
2351       continue;
2352     // To be moved feature should be in active document
2353     if (anObject->document() != ModelAPI_Session::get()->activeDocument())
2354       continue;
2355     aValidatedObjects.append(anObject);
2356   }
2357   if (aValidatedObjects.size() != anObjects.size())
2358     anObjects = aValidatedObjects;
2359
2360   bool aCanMove = !anObjects.empty();
2361
2362   QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
2363   for (; anIt != aLast && aCanMove; anIt++) {
2364     ObjectPtr anObject = *anIt;
2365     if (!anObject.get() || !anObject->data().get() || !anObject->data()->isValid()) {
2366       aCanMove = false;
2367       break;
2368     }
2369     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
2370     // only groups can be moved to the end for now (#2451)
2371     if (aFeat.get() && aFeat->getKind() != "Group") {
2372       aCanMove = false;
2373       break;
2374     }
2375
2376     // 1. Get features placed between selected and current in the document
2377     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(anObject);
2378     // if aFeaturesBetween is empty it means wrong order or anObject is the current feature
2379     if (aFeaturesBetween.empty())
2380       aCanMove = false;
2381     else {
2382       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
2383       // 2. Get all reference features to the selected object in the document
2384       std::set<FeaturePtr> aRefFeatures;
2385       ModuleBase_Tools::refsToFeatureInFeatureDocument(anObject, aRefFeatures);
2386
2387       if (aRefFeatures.empty())
2388         continue;
2389       else {
2390         // 3. Find any placed features in all reference features
2391         std::set<FeaturePtr> aIntersectionFeatures;
2392         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
2393                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
2394                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
2395         // 4. Return false if any reference feature is placed before current feature
2396         if (!aIntersectionFeatures.empty())
2397           aCanMove = false;
2398       }
2399     }
2400   }
2401   return aCanMove;
2402 }
2403
2404 //**************************************************************
2405 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
2406 {
2407   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
2408   if (!aCanBeShaded) {
2409     ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
2410     if (aCompRes.get() != NULL) { // change colors for all sub-solids
2411       std::list<ResultPtr> allRes;
2412       ModelAPI_Tools::allSubs(aCompRes, allRes);
2413       std::list<ResultPtr>::iterator aRes = allRes.begin();
2414       for(; aRes != allRes.end() && !aCanBeShaded; aRes++) {
2415         aCanBeShaded = myDisplayer->canBeShaded(*aRes);
2416       }
2417     }
2418   }
2419   return aCanBeShaded;
2420 }
2421
2422 //**************************************************************
2423 bool XGUI_Workshop::canChangeProperty(const QString& theActionName) const
2424 {
2425   if (theActionName == "COLOR_CMD" ||
2426       theActionName == "DEFLECTION_CMD" ||
2427       theActionName == "TRANSPARENCY_CMD") {
2428     QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2429
2430     std::set<std::string> aTypes;
2431     aTypes.insert(ModelAPI_ResultGroup::group());
2432     aTypes.insert(ModelAPI_ResultConstruction::group());
2433     aTypes.insert(ModelAPI_ResultBody::group());
2434     aTypes.insert(ModelAPI_ResultPart::group());
2435
2436     return hasResults(anObjects, aTypes);
2437   }
2438   if (theActionName == "AUTOCOLOR_CMD") {
2439
2440     QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2441
2442     std::set<std::string> aTypes;
2443     aTypes.insert(ModelAPI_ResultGroup::group());
2444
2445     return hasResults(anObjects, aTypes);
2446   }
2447   return false;
2448 }
2449
2450
2451 //**************************************************************
2452 void getDefaultColor(ObjectPtr theObject, const bool isEmptyColorValid,
2453   std::vector<int>& theColor)
2454 {
2455   theColor.clear();
2456   // get default color from the preferences manager for the given result
2457   if (theColor.empty()) {
2458     std::string aSection, aName, aDefault;
2459     theObject->colorConfigInfo(aSection, aName, aDefault);
2460     if (!aSection.empty() && !aName.empty()) {
2461       theColor = Config_PropManager::color(aSection, aName);
2462     }
2463   }
2464   if (!isEmptyColorValid && theColor.empty()) {
2465     // all AIS objects, where the color is not set, are in black.
2466     // The color should be defined in XML or set in the attribute
2467     theColor = Config_PropManager::color("Visualization", "object_default_color");
2468     Events_InfoMessage("XGUI_CustomPrs",
2469       "A default color is not defined in the preferences for this kind of result").send();
2470   }
2471 }
2472
2473 //**************************************************************
2474 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
2475 {
2476
2477   AttributeIntArrayPtr aColorAttr;
2478   // 1. find the current color of the object. This is a color of AIS presentation
2479   // The objects are iterated until a first valid color is found
2480   std::vector<int> aColor;
2481   foreach(ObjectPtr anObject, theObjects) {
2482     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2483     if (aResult.get()) {
2484       ModelAPI_Tools::getColor(aResult, aColor);
2485       if (aColor.empty()) {
2486         AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2487         if (anAISObj.get()) {
2488           aColor.resize(3);
2489           anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
2490         }
2491       }
2492       if (aColor.empty()) {
2493         getDefaultColor(aResult, false, aColor);
2494       }
2495     }
2496   }
2497   if (aColor.size() != 3)
2498     return;
2499
2500   if (!abortAllOperations())
2501   return;
2502   // 2. show the dialog to change the value
2503   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
2504   aDlg->setColor(aColor);
2505   aDlg->move(QCursor::pos());
2506   bool isDone = aDlg->exec() == QDialog::Accepted;
2507   if (!isDone)
2508     return;
2509
2510   bool isRandomColor = aDlg->isRandomColor();
2511
2512   // 3. abort the previous operation and start a new one
2513   SessionPtr aMgr = ModelAPI_Session::get();
2514   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
2515
2516   aMgr->startOperation(aDescription.toStdString());
2517
2518   // 4. set the value to all results
2519   std::vector<int> aColorResult = aDlg->getColor();
2520   foreach(ObjectPtr anObj, theObjects) {
2521     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2522     if (aResult.get() != NULL) {
2523       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2524       if (aBodyResult.get() != NULL) { // change colors for all sub-solids
2525         std::list<ResultPtr> allRes;
2526         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2527         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2528           ModelAPI_Tools::setColor(*aRes, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2529         }
2530       }
2531       ModelAPI_Tools::setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2532     }
2533   }
2534   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2535   aMgr->finishOperation();
2536   updateCommandStatus();
2537   myViewerProxy->update();
2538 }
2539
2540 //**************************************************************
2541 void XGUI_Workshop::changeAutoColor(const QObjectPtrList& theObjects)
2542 {
2543   if (!abortAllOperations())
2544   return;
2545
2546   std::vector<int> aColor;
2547
2548   // abort the previous operation and start a new one
2549   SessionPtr aMgr = ModelAPI_Session::get();
2550   QString aDescription = contextMenuMgr()->action("AUTOCOLOR_CMD")->text();
2551   aMgr->startOperation(aDescription.toStdString());
2552
2553     if (Config_PropManager::getAutoColorStatus()) {
2554       contextMenuMgr()->action("AUTOCOLOR_CMD")->setText(tr("Auto color"));
2555       Config_PropManager::setAutoColorStatus(false);
2556       ModelAPI_Tools::findRandomColor(aColor, true);
2557     } else {
2558       // set the value to all results
2559       foreach (ObjectPtr anObj, theObjects) {
2560         DocumentPtr aDocument = anObj->document();
2561         std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
2562         // find the object iterator
2563         std::list<FeaturePtr>::iterator anObjectIt = anAllFeatures.begin();
2564         for (; anObjectIt !=  anAllFeatures.end(); ++ anObjectIt) {
2565           FeaturePtr aFeature = *anObjectIt;
2566           if (aFeature.get()) {
2567             std::list<ResultPtr> aResults;
2568             ModelAPI_Tools::allResults(aFeature, aResults);
2569             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2570             for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2571               ResultPtr aGroupResult = *aIt;
2572               if (aGroupResult.get() &&
2573                   aGroupResult->groupName() == ModelAPI_ResultGroup::group()) {
2574                 ModelAPI_Tools::findRandomColor(aColor);
2575                 ModelAPI_Tools::setColor(aGroupResult, aColor);
2576               }
2577             }
2578           }
2579         }
2580       }
2581       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2582       aMgr->finishOperation();
2583       updateCommandStatus();
2584       myViewerProxy->update();
2585       contextMenuMgr()->action("AUTOCOLOR_CMD")->setText(tr("Disable auto color"));
2586       Config_PropManager::setAutoColorStatus(true);
2587     }
2588 }
2589
2590 //**************************************************************
2591 void setTransparency(double theTransparency, const QObjectPtrList& theObjects)
2592 {
2593   foreach(ObjectPtr anObj, theObjects) {
2594     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2595     if (aResult.get() != NULL) {
2596       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2597       if (aBodyResult.get() != NULL) { // change property for all sub-solids
2598         std::list<ResultPtr> allRes;
2599         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2600         std::list<ResultPtr>::iterator aRes;
2601         for(aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2602           ModelAPI_Tools::setTransparency(*aRes, theTransparency);
2603         }
2604       }
2605       ModelAPI_Tools::setTransparency(aResult, theTransparency);
2606     }
2607   }
2608 }
2609
2610 //**************************************************************
2611 double getDefaultDeflection(const ObjectPtr& theObject)
2612 {
2613   double aDeflection = -1;
2614   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
2615   if (aResult.get()) {
2616     bool isConstruction = false;
2617
2618     std::string aResultGroup = aResult->groupName();
2619     if (aResultGroup == ModelAPI_ResultConstruction::group())
2620       isConstruction = true;
2621     else if (aResultGroup == ModelAPI_ResultBody::group()) {
2622       GeomShapePtr aGeomShape = aResult->shape();
2623       if (aGeomShape.get()) {
2624         // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
2625         // correction of deviation for them should not influence to the application performance
2626         GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
2627         isConstruction = !anExp.more();
2628       }
2629     }
2630     if (isConstruction)
2631       aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
2632     else
2633       aDeflection = Config_PropManager::real("Visualization", "body_deflection");
2634   }
2635   return aDeflection;
2636 }
2637
2638 //**************************************************************
2639 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
2640 {
2641   AttributeDoublePtr aDoubleAttr;
2642   // 1. find the current property of the object. This is a property of AIS presentation
2643   // The objects are iterated until a first valid property is found
2644   double aDeflection = -1;
2645   foreach(ObjectPtr anObject, theObjects) {
2646     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2647     if (aResult.get()) {
2648       aDeflection = ModelAPI_Tools::getDeflection(aResult);
2649       if (aDeflection < 0)
2650         aDeflection = getDefaultDeflection(aResult);
2651     }
2652     else {
2653       // TODO: remove the obtaining a property from the AIS object
2654       // this does not happen never because:
2655       // 1. The property can be changed only on results
2656       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2657       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2658       if (anAISObj.get()) {
2659         aDeflection = anAISObj->getDeflection();
2660       }
2661     }
2662     if (aDeflection > 0)
2663       break;
2664   }
2665   if (aDeflection < 0)
2666     return;
2667
2668   if (!abortAllOperations())
2669   return;
2670   // 2. show the dialog to change the value
2671   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
2672   aDlg->setDeflection(aDeflection);
2673   aDlg->move(QCursor::pos());
2674   bool isDone = aDlg->exec() == QDialog::Accepted;
2675   if (!isDone)
2676     return;
2677
2678   // 3. abort the previous operation and start a new one
2679   SessionPtr aMgr = ModelAPI_Session::get();
2680   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2681   aMgr->startOperation(aDescription.toStdString());
2682
2683   // 4. set the value to all results
2684   aDeflection = aDlg->getDeflection();
2685   foreach(ObjectPtr anObj, theObjects) {
2686     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2687     if (aResult.get() != NULL) {
2688       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2689       if (aBodyResult.get() != NULL) { // change property for all sub-solids
2690         std::list<ResultPtr> allRes;
2691         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2692         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2693           ModelAPI_Tools::setDeflection(*aRes, aDeflection);
2694         }
2695       }
2696       ModelAPI_Tools::setDeflection(aResult, aDeflection);
2697     }
2698   }
2699   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2700   aMgr->finishOperation();
2701   updateCommandStatus();
2702 }
2703
2704 //**************************************************************
2705 double getDefaultTransparency(const ResultPtr& theResult)
2706 {
2707   return Config_PropManager::integer("Visualization", "shaper_default_transparency") / 100.;
2708 }
2709
2710 //**************************************************************
2711 void XGUI_Workshop::changeTransparency(const QObjectPtrList& theObjects)
2712 {
2713   AttributeDoublePtr aDoubleAttr;
2714   // 1. find the current property of the object. This is a property of AIS presentation
2715   // The objects are iterated until a first valid property is found
2716   double aCurrentValue = -1;
2717   foreach(ObjectPtr anObject, theObjects) {
2718     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2719     if (aResult.get()) {
2720       aCurrentValue = ModelAPI_Tools::getTransparency(aResult);
2721       if (aCurrentValue < 0)
2722         aCurrentValue = getDefaultTransparency(aResult);
2723     }
2724     if (aCurrentValue > 0)
2725       break;
2726   }
2727   if (aCurrentValue < 0)
2728     return;
2729
2730   if (!abortAllOperations())
2731     return;
2732
2733   // 2. show the dialog to change the value
2734   XGUI_PropertyDialog* aDlg = new XGUI_PropertyDialog(desktop());
2735   aDlg->setWindowTitle(tr("Transparency"));
2736   XGUI_TransparencyWidget* aTransparencyWidget = new XGUI_TransparencyWidget(aDlg);
2737   connect(aTransparencyWidget, SIGNAL(transparencyValueChanged()),
2738           this, SLOT(onTransparencyValueChanged()));
2739   aDlg->setContent(aTransparencyWidget);
2740   aTransparencyWidget->setValue(aCurrentValue);
2741
2742   // 3. abort the previous operation and start a new one
2743   SessionPtr aMgr = ModelAPI_Session::get();
2744   QString aDescription = contextMenuMgr()->action("TRANSPARENCY_CMD")->text();
2745   aMgr->startOperation(aDescription.toStdString());
2746
2747   if (aDlg->exec() == QDialog::Accepted) {
2748     // 4. set the value to all results
2749     aCurrentValue = aTransparencyWidget->getValue();
2750     setTransparency(aCurrentValue, theObjects);
2751     aMgr->finishOperation();
2752   } else {
2753     aMgr->abortOperation();
2754     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2755   }
2756
2757   updateCommandStatus();
2758 }
2759
2760 //**************************************************************
2761 void XGUI_Workshop::onTransparencyValueChanged()
2762 {
2763   XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2764   if (!aTransparencyWidget)
2765     return;
2766
2767   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2768   setTransparency(aTransparencyWidget->getValue(), anObjects);
2769   static const Events_ID kRedisplayEvent =
2770     Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2771   Events_Loop::loop()->flush(kRedisplayEvent);
2772
2773   myViewerProxy->update();
2774 }
2775
2776
2777 //******************************************************
2778 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2779 {
2780   if (isVisible) {
2781     std::set<ObjectPtr> anObjects;
2782     foreach (ObjectPtr aObj, theList) {
2783       anObjects.insert(aObj);
2784     }
2785     if (!prepareForDisplay(anObjects))
2786       return;
2787   }
2788
2789   foreach (ObjectPtr aObj, theList) {
2790     aObj->setDisplayed(isVisible);
2791   }
2792   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2793   myObjectBrowser->updateAllIndexes();
2794
2795   updateColorScaleVisibility();
2796   displayer()->updateViewer();
2797 }
2798
2799 //**************************************************************
2800 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2801 {
2802   QObjectPtrList aSrcList = theList;
2803   // Hide all displayed objects
2804   QObjectPtrList aList = myDisplayer->displayedObjects();
2805   foreach (ObjectPtr aObj, aList) {
2806     if ((!aSrcList.contains(aObj)) && (module()->canEraseObject(aObj)))
2807       aObj->setDisplayed(false);
2808     else
2809       aSrcList.removeAll(aObj);
2810   }
2811   //Do not use eraseAll if you didn't send Redisplay event:
2812   //all objects are erased from viewer, but considered as displayed in displayer
2813   // Problem in bug 2218
2814   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2815 #ifdef HAVE_SALOME
2816     //issue #2159 Hide all incomplete behavior
2817     viewer()->eraseAll();
2818 #endif
2819
2820   std::set<ObjectPtr> anObjects;
2821   foreach (ObjectPtr aObj, aSrcList) {
2822     anObjects.insert(aObj);
2823   }
2824
2825   if (!prepareForDisplay(anObjects))
2826     return;
2827
2828   // Show only objects from the list
2829   foreach (ObjectPtr aObj, aSrcList) {
2830     aObj->setDisplayed(true);
2831   }
2832   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2833
2834   // Necessary for update icons in ObjectBrowser on Linux
2835   myObjectBrowser->updateAllIndexes();
2836   updateColorScaleVisibility();
2837   displayer()->updateViewer();
2838 }
2839
2840
2841 //**************************************************************
2842 void XGUI_Workshop::updateColorScaleVisibility()
2843 {
2844   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2845   viewer()->setColorScaleShown(false);
2846   if (anObjects.size() == 1) {
2847     FieldStepPtr aStep =
2848       std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(anObjects.first());
2849     if (aStep.get() && myDisplayer->isVisible(aStep)) {
2850       AISObjectPtr aAisPtr = myDisplayer->getAISObject(aStep);
2851       Handle(AIS_InteractiveObject) aIO = aAisPtr->impl<Handle(AIS_InteractiveObject)>();
2852       ModuleBase_IStepPrs* aPrs = dynamic_cast<ModuleBase_IStepPrs*>(aIO.get());
2853       if (aPrs) {
2854         ModelAPI_AttributeTables::ValueType aType = aPrs->dataType();
2855         if ((aType == ModelAPI_AttributeTables::DOUBLE) ||
2856           (aType == ModelAPI_AttributeTables::INTEGER) ||
2857           (aType == ModelAPI_AttributeTables::BOOLEAN)) {
2858           myViewerProxy->setupColorScale();
2859           if (aType == ModelAPI_AttributeTables::BOOLEAN) {
2860             myViewerProxy->setColorScaleIntervals(2);
2861             myViewerProxy->setColorScaleRange(0., 1.);
2862           }
2863           else {
2864             double aMin, aMax;
2865             aPrs->dataRange(aMin, aMax);
2866             myViewerProxy->setColorScaleRange(aMin, aMax);
2867           }
2868           myViewerProxy->setColorScaleTitle(QString::fromStdWString(aStep->name()));
2869           myViewerProxy->setColorScaleShown(true);
2870         }
2871       }
2872     }
2873   }
2874 }
2875
2876
2877 //**************************************************************
2878 void XGUI_Workshop::setNormalView(bool toInvert)
2879 {
2880   QList<ModuleBase_ViewerPrsPtr> aPrsList =
2881     mySelector->selection()->getSelected(ModuleBase_ISelection::Viewer);
2882   GeomShapePtr aPlanarFace;
2883   foreach(ModuleBase_ViewerPrsPtr aPrs, aPrsList) {
2884     GeomShapePtr aShape = aPrs->shape();
2885     if (aShape.get() && aShape->isFace() && aShape->isPlanar()) {
2886       aPlanarFace = aShape;
2887       break;
2888     }
2889   }
2890   if (aPlanarFace.get()) {
2891     GeomFacePtr aFace(new GeomAPI_Face(aPlanarFace));
2892     GeomPlanePtr aPlane = aFace->getPlane();
2893     GeomDirPtr aNormal = aPlane->direction();
2894     if (toInvert)
2895       aNormal->reverse();
2896     GeomPointPtr aPos = aPlane->location();
2897
2898     double aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2899     aFace->computeSize(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2900
2901     Handle(V3d_View) aView = myViewerProxy->activeView();
2902     aView->SetAt(aPos->x(), aPos->y(), aPos->z());
2903     aView->SetProj(aNormal->x(), aNormal->y(), aNormal->z());
2904     Bnd_Box aBox;
2905     aBox.Update(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2906     aView->FitAll(aBox);
2907   }
2908 }
2909
2910 //**************************************************************
2911 void XGUI_Workshop::registerValidators() const
2912 {
2913   SessionPtr aMgr = ModelAPI_Session::get();
2914   MAYBE_UNUSED ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2915 }
2916
2917 //**************************************************************
2918 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2919 {
2920   if (!theDoc)
2921     return;
2922   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2923   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2924 }
2925
2926 //**************************************************************
2927 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2928 {
2929   for (int i = 0; i < theDoc->size(theGroup); i++)
2930     theDoc->object(theGroup, i)->setDisplayed(true);
2931     //displayObject(theDoc->object(theGroup, i));
2932   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2933 }
2934
2935 //**************************************************************
2936 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2937 {
2938   foreach(ObjectPtr anObj, theList) {
2939     myDisplayer->setDisplayMode(anObj, (XGUI_Displayer::DisplayMode)theMode, false);
2940
2941     ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObj);
2942     if (aBodyResult.get() != NULL) { // change display mode for all sub-solids
2943       std::list<ResultPtr> allRes;
2944       ModelAPI_Tools::allSubs(aBodyResult, allRes);
2945       for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2946         myDisplayer->setDisplayMode(*aRes, (XGUI_Displayer::DisplayMode)theMode, false);
2947       }
2948     }
2949   }
2950   if (theList.size() > 0)
2951     myDisplayer->updateViewer();
2952 }
2953
2954 //**************************************************************
2955 void XGUI_Workshop::closeDocument()
2956 {
2957   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2958   while (anOperation) {
2959     anOperation->abort();
2960     anOperation = operationMgr()->currentOperation();
2961   }
2962   //myDisplayer->closeLocalContexts();
2963   myDisplayer->eraseAll();
2964   objectBrowser()->clearContent();
2965
2966   module()->closeDocument();
2967   // we need to clear viewer (with created filters) to do not have problems in 2nd SALOME study
2968   module()->clearViewer();
2969
2970
2971   // data model need not process the document's signals about objects modifications as
2972   // the document is closed
2973   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2974
2975   SessionPtr aMgr = ModelAPI_Session::get();
2976   aMgr->closeAll();
2977
2978   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2979 }
2980
2981 //******************************************************
2982 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2983 {
2984   XGUI_HistoryMenu* aMenu = NULL;
2985   if (isSalomeMode()) {
2986     QAction* anAction = qobject_cast<QAction*>(theObject);
2987     if (!anAction)
2988       return;
2989     aMenu = new XGUI_HistoryMenu(anAction);
2990   } else {
2991     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2992     aMenu = new XGUI_HistoryMenu(aButton);
2993   }
2994   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2995   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2996 }
2997
2998 //******************************************************
2999 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
3000 {
3001   QList<ActionInfo> aResult;
3002   std::list<std::string>::const_iterator it = theList.cbegin();
3003   for (; it != theList.cend(); it++) {
3004     QString anId = QString::fromStdString(*it);
3005     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
3006     if (isEditing) {
3007       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
3008     }
3009     ActionInfo anInfo;
3010     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
3011     if (aContextMenuAct) {
3012       anInfo.initFrom(aContextMenuAct);
3013     } else {
3014       anInfo = myActionsMgr->actionInfoById(anId);
3015     }
3016     if (isEditing) {
3017       anInfo.text = anInfo.text.prepend("Modify ");
3018     }
3019     aResult << anInfo;
3020   }
3021   return aResult;
3022 }
3023
3024 //******************************************************
3025 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
3026 {
3027 #ifdef HAVE_SALOME
3028   salomeConnector()->putInfo(theMessage, -1);
3029 #else
3030   myMainWindow->putInfo(theMessage, -1);
3031 #endif
3032 }
3033
3034 #ifdef HAVE_SALOME
3035 //******************************************************
3036 void XGUI_Workshop::synchronizeViewer()
3037 {
3038   SessionPtr aMgr = ModelAPI_Session::get();
3039   QList<DocumentPtr> aDocs;
3040   aDocs.append(aMgr->activeDocument());
3041   aDocs.append(aMgr->moduleDocument());
3042
3043   foreach(DocumentPtr aDoc, aDocs) {
3044     synchronizeGroupInViewer(aDoc, false);
3045   }
3046 }
3047
3048 //******************************************************
3049 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
3050                                              bool theUpdateViewer)
3051 {
3052   FeaturePtr aFeature;
3053   ResultPtr aRes;
3054   int aSize = theDoc->numInternalFeatures();
3055   for (int i = 0; i < aSize; i++) {
3056     aFeature = theDoc->internalFeature(i);
3057     if (!aFeature.get())
3058       continue;
3059     const std::list<ResultPtr>& aResults = aFeature->results();
3060     std::list<ResultPtr>::const_iterator aIt;
3061     aFeature->setDisplayed(false);
3062     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
3063       aRes = (*aIt);
3064       if (aRes->isDisplayed() && !aRes->isConcealed()) {
3065         // Hide the presentation with an empty shape. But isDisplayed state of the object should not
3066         // be changed to the object becomes visible when the shape becomes not empty
3067         if (!aRes->shape().get() || aRes->shape()->isNull())
3068           continue;
3069         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aRes);
3070         if (aResBody.get())
3071           synchronizeResultTree(aResBody, false);
3072         else {
3073           if (aRes->isInHistory()) {
3074             if (aRes->isDisplayed())
3075               myDisplayer->display(aRes, false);
3076             else
3077               myDisplayer->erase(aRes, false);
3078           }
3079           else
3080             aRes->setDisplayed(false);
3081         }
3082       }
3083     }
3084   }
3085   if (theUpdateViewer)
3086     myDisplayer->updateViewer();
3087 }
3088
3089 void XGUI_Workshop::synchronizeResultTree(const ResultBodyPtr& theRes, bool theUpdateViewer)
3090 {
3091   if (theRes->numberOfSubs() > 0)
3092     for (int i = 0; i < theRes->numberOfSubs(); i++) {
3093       ResultBodyPtr aRes = theRes->subResult(i);
3094       if (aRes.get())
3095         synchronizeResultTree(aRes, theUpdateViewer);
3096     }
3097   else {
3098     if (theRes->isDisplayed())
3099       myDisplayer->display(theRes, theUpdateViewer);
3100     else
3101       myDisplayer->erase(theRes, theUpdateViewer);
3102   }
3103 }
3104 #endif
3105
3106 //******************************************************
3107 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
3108 {
3109   FeaturePtr aFeature;
3110   QObjectPtrList aSelList = theObjects;
3111   QObjectPtrList aNewSel;
3112   bool aHasHidden = false;
3113   foreach(ObjectPtr aObj, theObjects) {
3114     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
3115     if (aFeature.get()) {
3116       std::list<ResultPtr> aResults;
3117       ModelAPI_Tools::allResults(aFeature, aResults);
3118       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
3119       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
3120         aHasHidden |= (*aIt)->isConcealed();
3121         aSelList.append(*aIt);
3122         aNewSel.append(*aIt);
3123       }
3124     }
3125   }
3126   if (aSelList.count() > theObjects.count()) {
3127     // if something was found
3128     objectBrowser()->setObjectsSelected(aSelList);
3129     objectBrowser()->ensureVisible(aNewSel.first());
3130   }
3131   if (aHasHidden)
3132     QMessageBox::information(desktop(), tr("Find results"),
3133                              tr("Results not found"), QMessageBox::Ok);
3134 }
3135
3136 //******************************************************
3137 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
3138 {
3139   ResultPtr aResult;
3140   QObjectPtrList aSelList = theObjects;
3141   QObjectPtrList aNewSel;
3142   FeaturePtr aFeature;
3143   foreach(ObjectPtr aObj, theObjects) {
3144     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
3145     if (aResult.get()) {
3146       aFeature = ModelAPI_Feature::feature(aResult);
3147       if (aFeature.get()) {
3148         aSelList.append(aFeature);
3149         aNewSel.append(aFeature);
3150       }
3151     }
3152   }
3153   if (aSelList.count() > theObjects.count()) {
3154     // if something was found
3155     objectBrowser()->setObjectsSelected(aSelList);
3156     objectBrowser()->ensureVisible(aNewSel.first());
3157   }
3158 }
3159
3160 void XGUI_Workshop::insertFeatureFolder()
3161 {
3162   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
3163   if (anObjects.isEmpty())
3164     return;
3165   ObjectPtr aObj = anObjects.first();
3166   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
3167   if (aFeature.get() == NULL)
3168     return;
3169   SessionPtr aMgr = ModelAPI_Session::get();
3170   DocumentPtr aDoc = aMgr->activeDocument();
3171
3172   QString aDescription = contextMenuMgr()->action("INSERT_FOLDER_CMD")->text();
3173
3174   aMgr->startOperation(aDescription.toStdString());
3175   aDoc->addFolder(aFeature);
3176   aMgr->finishOperation();
3177
3178   updateCommandStatus();
3179 }
3180
3181
3182 void XGUI_Workshop::insertToFolder(bool isBefore)
3183 {
3184   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
3185   if (aFeatures.empty())
3186     return;
3187
3188   SessionPtr aMgr = ModelAPI_Session::get();
3189   DocumentPtr aDoc = aMgr->activeDocument();
3190
3191   FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
3192                                 aDoc->findFolderBelow(aFeatures);
3193   if (!aFolder.get())
3194     return;
3195
3196   QString aDescription = contextMenuMgr()->action(
3197     isBefore ? "ADD_TO_FOLDER_BEFORE_CMD" : "ADD_TO_FOLDER_AFTER_CMD")->text();
3198
3199   QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
3200
3201   aMgr->startOperation(aDescription.toStdString());
3202   aDoc->moveToFolder(aFeatures, aFolder);
3203   aMgr->finishOperation();
3204
3205   myObjectBrowser->setFoldersState(aStates);
3206
3207   updateCommandStatus();
3208 }
3209
3210 void XGUI_Workshop::moveOutFolder(bool isBefore)
3211 {
3212   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
3213   if (aFeatures.empty())
3214     return;
3215
3216   SessionPtr aMgr = ModelAPI_Session::get();
3217   DocumentPtr aDoc = aMgr->activeDocument();
3218
3219   QString aDescription = contextMenuMgr()->action(
3220     isBefore ? "ADD_OUT_FOLDER_BEFORE_CMD" : "ADD_OUT_FOLDER_AFTER_CMD")->text();
3221
3222   QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
3223
3224   aMgr->startOperation(aDescription.toStdString());
3225   aDoc->removeFromFolder(aFeatures, isBefore);
3226   aMgr->finishOperation();
3227
3228   myObjectBrowser->setFoldersState(aStates);
3229
3230   updateCommandStatus();
3231 }
3232
3233 void XGUI_Workshop::onAutoApply()
3234 {
3235   SessionPtr aMgr = ModelAPI_Session::get();
3236   bool isBlocked = aMgr->isAutoUpdateBlocked();
3237   aMgr->blockAutoUpdate(!isBlocked);
3238   myDisplayer->updateViewer();
3239 }
3240
3241 void XGUI_Workshop::updateAutoComputeState()
3242 {
3243   SessionPtr aMgr = ModelAPI_Session::get();
3244 #ifdef HAVE_SALOME
3245 //  QAction* aUpdateCmd;
3246 //  QList<QAction*> aCommands = mySalomeConnector->commandList();
3247 //  foreach(QAction* aCmd, aCommands) {
3248 //    if (aCmd->data().toString() == "AUTOCOMPUTE_CMD") {
3249 //      aUpdateCmd = aCmd;
3250 //      break;
3251 //    }
3252 //  }
3253 //  aUpdateCmd->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
3254 //    QIcon(":pictures/autoapply_start.png"));
3255 #else
3256   bool isComputeBlocked = aMgr->isAutoUpdateBlocked();
3257   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
3258   AppElements_Command* aUpdateCmd = aMenuBar->feature("AUTOCOMPUTE_CMD");
3259   aUpdateCmd->button()->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
3260     QIcon(":pictures/autoapply_start.png"));
3261 #endif
3262 }
3263
3264
3265 void XGUI_Workshop::clearTemporaryDir()
3266 {
3267   QDir aDir(myTmpDir.path());
3268   if (!aDir.isEmpty()) {
3269     QStringList aEntries;
3270     aDir.entryList(aEntries);
3271     foreach(QString aFile, aEntries) {
3272       aDir.remove(aFile);
3273     }
3274   }
3275 }
3276
3277
3278 void XGUI_Workshop::onDockSizeChanged()
3279 {
3280   QDockWidget* aDockWgt = dynamic_cast<QDockWidget*>(myObjectBrowser->parentWidget());
3281   int aObWidth = aDockWgt->size().width();
3282   if (myPropertyPanel->width() != aObWidth) {
3283     QList<QDockWidget*> aWgtList;
3284     aWgtList << myPropertyPanel << aDockWgt;
3285     QList<int> aSizeList;
3286     aSizeList << aObWidth << aObWidth;
3287     desktop()->resizeDocks(aWgtList, aSizeList, Qt::Horizontal);
3288     disconnect(myObjectBrowser, SIGNAL(sizeChanged()), this, SLOT(onDockSizeChanged()));
3289   }
3290 }
3291
3292 void XGUI_Workshop::deactivateCurrentSelector()
3293 {
3294   myActiveControlMgr->deactivateSelector(myActiveControlMgr->activeSelector());
3295 }
3296
3297 void XGUI_Workshop::changeIsoLines(const QObjectPtrList& theObjects)
3298 {
3299   if (theObjects.isEmpty())
3300     return;
3301
3302   QList<ResultPtr> aResultList;
3303   ResultPtr aRes;
3304   foreach(ObjectPtr aObj, theObjects) {
3305     aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
3306     if (aRes.get())
3307       aResultList.append(aRes);
3308   }
3309
3310   std::vector<int> aValues;
3311   bool isVisible;
3312   if (aResultList.size() == 1) {
3313     ResultPtr aResult = aResultList.first();
3314     if (aResult.get())
3315       ModelAPI_Tools::getIsoLines(aResult, isVisible, aValues);
3316     else
3317       return;
3318   }
3319   if (aValues.size() == 0) {
3320     aValues.push_back(1);
3321     aValues.push_back(1);
3322   }
3323
3324   if (!abortAllOperations())
3325     return;
3326
3327   XGUI_PropertyDialog aDlg(desktop());
3328   aDlg.setWindowTitle(tr("Number of Iso-lines"));
3329
3330   QWidget* aIsosWgt = new QWidget(&aDlg);
3331   QFormLayout* aLayout = new QFormLayout(aIsosWgt);
3332   ModuleBase_Tools::adjustMargins(aLayout);
3333   aDlg.setContent(aIsosWgt);
3334
3335   QSpinBox* aUNb = new QSpinBox(&aDlg);
3336   aUNb->setValue(aValues[0]);
3337   aLayout->addRow("U:", aUNb);
3338
3339   QSpinBox* aVNb = new QSpinBox(&aDlg);
3340   aVNb->setValue(aValues[1]);
3341   aLayout->addRow("V:", aVNb);
3342
3343   if (aDlg.exec() == QDialog::Accepted) {
3344     SessionPtr aMgr = ModelAPI_Session::get();
3345     QString aDescription = contextMenuMgr()->action("ISOLINES_CMD")->text();
3346     aMgr->startOperation(aDescription.toStdString());
3347
3348     aValues[0] = aUNb->value();
3349     aValues[1] = aVNb->value();
3350     foreach(ResultPtr aResult, aResultList) {
3351       ModelAPI_Tools::setIsoLines(aResult, aValues);
3352     }
3353     mySelector->clearSelection();
3354     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
3355     aMgr->finishOperation();
3356     updateCommandStatus();
3357   }
3358 }