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