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