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