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