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