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