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