Salome HOME
Issue #3145: provide help pages for Import/Export operations
[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     anImportPartOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1315       "importFeature.html");
1316     myPropertyPanel->updateApplyPlusButton(anImportPartOp->feature());
1317     operationMgr()->startOperation(anImportPartOp);
1318   }
1319 }
1320
1321 //******************************************************
1322 void XGUI_Workshop::onImportShape()
1323 {
1324   if (abortAllOperations()) {
1325     ModuleBase_OperationFeature* anImportOp = dynamic_cast<ModuleBase_OperationFeature*>(
1326         module()->createOperation(ExchangePlugin_Import::ID()));
1327     anImportOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1328       "importFeature.html");
1329     myPropertyPanel->updateApplyPlusButton(anImportOp->feature());
1330     operationMgr()->startOperation(anImportOp);
1331   }
1332 }
1333
1334 //******************************************************
1335 void XGUI_Workshop::onExportShape()
1336 {
1337   if (abortAllOperations()) {
1338     ModuleBase_OperationFeature* anExportOp = dynamic_cast<ModuleBase_OperationFeature*>(
1339         module()->createOperation(ExchangePlugin_ExportFeature::ID()));
1340     anExportOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1341       "exportFeature.html");
1342     myPropertyPanel->updateApplyPlusButton(anExportOp->feature());
1343     operationMgr()->startOperation(anExportOp);
1344   }
1345 }
1346
1347 //******************************************************
1348 void XGUI_Workshop::onExportPart()
1349 {
1350   if (abortAllOperations()) {
1351     ModuleBase_OperationFeature* anExportPartOp = dynamic_cast<ModuleBase_OperationFeature*>(
1352         module()->createOperation(ExchangePlugin_ExportPart::ID()));
1353     anExportPartOp->setHelpFileName(QString("ExchangePlugin") + QDir::separator() +
1354       "exportFeature.html");
1355     myPropertyPanel->updateApplyPlusButton(anExportPartOp->feature());
1356     operationMgr()->startOperation(anExportPartOp);
1357   }
1358 }
1359
1360 //******************************************************
1361 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1362 {
1363   QString libName = QString::fromStdString(library(theModule.toStdString()));
1364   if (libName.isEmpty()) {
1365     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1366     return 0;
1367   }
1368
1369   QString err;
1370   CREATE_FUNC crtInst = 0;
1371
1372 #ifdef WIN32
1373   HINSTANCE modLib = ::LoadLibraryA(qPrintable(libName));
1374   if (!modLib) {
1375     LPVOID lpMsgBuf;
1376     ::FormatMessage(
1377         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1378         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1379     QString aMsg((char*) &lpMsgBuf);
1380     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1381     ::LocalFree(lpMsgBuf);
1382   } else {
1383     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1384     if (!crtInst) {
1385       LPVOID lpMsgBuf;
1386       ::FormatMessage(
1387           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1388               | FORMAT_MESSAGE_IGNORE_INSERTS,
1389           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1390       QString aMsg((char*) &lpMsgBuf);
1391       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1392       ::LocalFree(lpMsgBuf);
1393     }
1394   }
1395 #else
1396   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1397   if ( !modLib ) {
1398     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1399   } else {
1400     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1401     if ( !crtInst ) {
1402       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1403     }
1404   }
1405 #endif
1406
1407   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1408
1409   if (!err.isEmpty()) {
1410     if (desktop()) {
1411       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1412     } else {
1413       qWarning(qPrintable(err));
1414     }
1415   }
1416   return aModule;
1417 }
1418
1419 //******************************************************
1420 bool XGUI_Workshop::createModule()
1421 {
1422   Config_ModuleReader aModuleReader;
1423   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1424   myModule = loadModule(moduleName);
1425   if (!myModule)
1426     return false;
1427
1428   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1429   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1430   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1431   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1432
1433   myModule->createFeatures();
1434 #ifdef HAVE_SALOME
1435   salomeConnector()->createFeatureActions();
1436 #endif
1437   //myActionsMgr->update();
1438   return true;
1439 }
1440
1441 //******************************************************
1442 void XGUI_Workshop::updateCommandStatus()
1443 {
1444   QList<QAction*> aCommands;
1445 #ifdef HAVE_SALOME
1446     aCommands = salomeConnector()->commandList();
1447 #else
1448     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1449     foreach (AppElements_Command* aCmd, aMenuBar->features())
1450       aCommands.append(aCmd);
1451 #endif
1452   SessionPtr aMgr = ModelAPI_Session::get();
1453   if (aMgr->hasModuleDocument()) {
1454     foreach(QAction* aCmd, aCommands) {
1455       QString aId = aCmd->data().toString();
1456       if (aId == "UNDO_CMD") {
1457         bool isActionEnabled = false;
1458         // if ultimate is true -> using result of operation only, or using OR combination
1459         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1460         if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled))
1461           aCmd->setEnabled(isActionEnabled);
1462         else
1463           aCmd->setEnabled(myModule->canUndo());
1464       }
1465       else if (aId == "REDO_CMD") {
1466         bool isActionEnabled = false;
1467         // if ultimate is true -> using result of operation only, or using OR combination
1468         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1469         if (anActiveWidget && anActiveWidget->canProcessAction(ActionRedo, isActionEnabled))
1470           aCmd->setEnabled(isActionEnabled);
1471         else
1472           aCmd->setEnabled(myModule->canRedo());
1473       }
1474       else if (aId == "AUTOCOMPUTE_CMD") {
1475         aCmd->setIcon(aMgr->isAutoUpdateBlocked() ?
1476           QIcon(":pictures/autoapply_stop.png") :
1477           QIcon(":pictures/autoapply_start.png"));
1478       }
1479       else
1480         // Enable all commands
1481         aCmd->setEnabled(true);
1482     }
1483     updateHistory();
1484   } else {
1485     foreach(QAction* aCmd, aCommands) {
1486       QString aId = aCmd->data().toString();
1487       if (aId == "NEW_CMD")
1488         aCmd->setEnabled(true);
1489       else if (aId == "EXIT_CMD")
1490         aCmd->setEnabled(true);
1491       else
1492         aCmd->setEnabled(false);
1493     }
1494   }
1495   myActionsMgr->updateCommandsStatus();
1496   emit commandStatusUpdated();
1497 }
1498
1499 //******************************************************
1500 void XGUI_Workshop::updateHistory()
1501 {
1502   bool isActionEnabled = false;
1503   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1504   QList<ActionInfo> aUndoRes;
1505   QList<ActionInfo> aRedoRes;
1506   if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled)) {
1507     aUndoRes = anActiveWidget->actionsList(ActionUndo);
1508     aRedoRes = anActiveWidget->actionsList(ActionRedo);
1509   } else {
1510     std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1511     aUndoRes = processHistoryList(aUndoList);
1512
1513     std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1514     aRedoRes = processHistoryList(aRedoList);
1515   }
1516   emit updateUndoHistory(aUndoRes);
1517   emit updateRedoHistory(aRedoRes);
1518 }
1519
1520 //******************************************************
1521 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1522 {
1523   QDockWidget* aObjDock = new QDockWidget(theParent);
1524   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1525                             Qt::RightDockWidgetArea);
1526   aObjDock->setWindowTitle(tr("Object browser"));
1527   aObjDock->setStyleSheet(
1528       "::title { position: relative; padding-left: 5px; text-align: left center }");
1529   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1530   myObjectBrowser->initialize(myModule->rootNode());
1531   myModule->customizeObjectBrowser(myObjectBrowser);
1532   aObjDock->setWidget(myObjectBrowser);
1533   aObjDock->setObjectName("Object browser");
1534
1535   connect(myObjectBrowser, SIGNAL(sizeChanged()), SLOT(onDockSizeChanged()));
1536
1537   myContextMenuMgr->connectObjectBrowser();
1538   return aObjDock;
1539 }
1540
1541 //******************************************************
1542 /*
1543  * Creates dock widgets, places them in corresponding area
1544  * and tabifies if necessary.
1545  */
1546 void XGUI_Workshop::createDockWidgets()
1547 {
1548   QMainWindow* aDesktop = desktop();
1549   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1550   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1551   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1552   myActiveControlMgr->addSelector(new XGUI_PropertyPanelSelector(myPropertyPanel));
1553
1554   myPropertyPanel->setupActions(myActionsMgr);
1555   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1556                                    Qt::RightDockWidgetArea);
1557   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1558
1559   hidePanel(myPropertyPanel);  ///<! Invisible by default
1560
1561   myFacesPanel = new XGUI_FacesPanel(aDesktop, this);
1562   myActiveControlMgr->addSelector(new XGUI_FacesPanelSelector(myFacesPanel));
1563   myFacesPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1564                                 Qt::RightDockWidgetArea |
1565                                 Qt::BottomDockWidgetArea);
1566   connect(myFacesPanel, SIGNAL(closed()), myFacesPanel, SLOT(onClosed()));
1567
1568   myInspectionPanel = new XGUI_InspectionPanel(aDesktop, this);
1569   myInspectionPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1570     Qt::RightDockWidgetArea);
1571   aDesktop->addDockWidget(Qt::RightDockWidgetArea, myInspectionPanel);
1572
1573   myInspectionPanel->hide();
1574
1575   aDesktop->addDockWidget(
1576 #ifdef HAVE_SALOME
1577     Qt::RightDockWidgetArea,
1578 #else
1579     Qt::LeftDockWidgetArea,
1580 #endif
1581     myFacesPanel);
1582   hidePanel(myFacesPanel);  ///<! Invisible by default
1583
1584 #ifdef _DEBUG
1585   bool aShowOnTheRight = Config_PropManager::boolean("Plugins", "show_hide_faces");
1586   if (aShowOnTheRight) {
1587     aDesktop->addDockWidget(Qt::RightDockWidgetArea, myFacesPanel);
1588     showPanel(myFacesPanel);
1589   }
1590 #endif
1591   hideObjectBrowser();
1592
1593 #ifndef HAVE_SALOME
1594 #ifdef _DEBUG
1595   if (!aShowOnTheRight)
1596   {
1597 #endif // _DEBUG
1598   aDesktop->tabifyDockWidget(myFacesPanel, aObjDock);
1599 #ifdef _DEBUG
1600   }
1601 #endif // _DEBUG
1602
1603 #endif // HAVE_SALOME
1604
1605   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1606   myPropertyPanel->installEventFilter(myOperationMgr);
1607
1608   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1609   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1610
1611   QAction* aOkContAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptPlus);
1612   connect(aOkContAct, SIGNAL(triggered()), this, SLOT(onAcceptPlusActionClicked()));
1613
1614   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1615   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1616
1617   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1618   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1619
1620   QAction* aHelpAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Help);
1621   connect(aHelpAct, SIGNAL(triggered()), this, SLOT(onHelpActionClicked()));
1622
1623   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1624           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1625   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1626           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1627 }
1628
1629 //******************************************************
1630 void XGUI_Workshop::showPanel(QDockWidget* theDockWidget)
1631 {
1632   if (theDockWidget == myPropertyPanel) {
1633     QAction* aViewAct = myPropertyPanel->toggleViewAction();
1634     ///<! Restore ability to close panel from the window's menu
1635     aViewAct->setEnabled(true);
1636   }
1637   theDockWidget->show();
1638   theDockWidget->raise();
1639
1640   // The next code is necessary to made the property panel the active window
1641   // in order to operation manager could process key events of the panel.
1642   // otherwise they are ignored. It happens only if the same(activateWindow) is
1643   // not happened by property panel activation(e.g. resume operation of Sketch)
1644   //ModuleBase_Tools::setFocus(theDockWidget, "XGUI_Workshop::showPanel()");
1645 }
1646
1647 //******************************************************
1648 void XGUI_Workshop::hidePanel(QDockWidget* theDockWidget)
1649 {
1650   if (theDockWidget && theDockWidget == myPropertyPanel) {
1651     QAction* aViewAct = theDockWidget->toggleViewAction();
1652     ///<! Do not allow to show empty property panel
1653     aViewAct->setEnabled(false);
1654   }
1655   theDockWidget->hide();
1656
1657   // the property panel is active window of the desktop, when it is
1658   // hidden, it is undefined which window becomes active. By this reason
1659   // it is defined to perform the desktop as the active window.
1660   // in SALOME mode, work-stack made the PyConsole the active window,
1661   // set the focus on it. As a result, shortcuts of the application, like
1662   // are processed by this console. For example Undo actions.
1663   // It is possible that this code is to be moved to SHAPER package
1664   QMainWindow* aDesktop = desktop();
1665   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::hidePanel()");
1666 }
1667
1668 //******************************************************
1669 void XGUI_Workshop::showObjectBrowser()
1670 {
1671   if (!isSalomeMode()) {
1672     myObjectBrowser->parentWidget()->show();
1673   }
1674 }
1675
1676 //******************************************************
1677 void XGUI_Workshop::hideObjectBrowser()
1678 {
1679   if (!isSalomeMode())
1680     myObjectBrowser->parentWidget()->hide();
1681 }
1682
1683 //******************************************************
1684 void XGUI_Workshop::salomeViewerSelectionChanged()
1685 {
1686   emit salomeViewerSelection();
1687 }
1688
1689 //**************************************************************
1690 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1691 {
1692   return mySalomeConnector->viewer();
1693 }
1694
1695 //**************************************************************
1696 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1697 {
1698   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1699   if (theId == "DELETE_CMD")
1700     deleteObjects();
1701   else if (theId == "CLEAN_HISTORY_CMD")
1702     cleanHistory();
1703   else if (theId == "MOVE_CMD" || theId == "MOVE_SPLIT_CMD")
1704     moveObjects(theId == "MOVE_SPLIT_CMD");
1705   else if (theId == "COLOR_CMD")
1706     changeColor(aObjects);
1707   else if (theId == "ISOLINES_CMD")
1708     changeIsoLines(aObjects);
1709   else if (theId == "SHOW_ISOLINES_CMD") {
1710     foreach(ObjectPtr aObj, aObjects) {
1711       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1712       if (aResult.get())
1713         ModelAPI_Tools::showIsoLines(aResult, !ModelAPI_Tools::isShownIsoLines(aResult));
1714     }
1715     mySelector->clearSelection();
1716     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1717   }
1718   else if (theId == "DEFLECTION_CMD")
1719     changeDeflection(aObjects);
1720   else if (theId == "TRANSPARENCY_CMD")
1721     changeTransparency(aObjects);
1722   else if (theId == "SHOW_CMD") {
1723     showObjects(aObjects, true);
1724     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1725     updateCommandStatus();
1726   }
1727   else if (theId == "HIDE_CMD") {
1728     showObjects(aObjects, false);
1729     updateCommandStatus();
1730   }
1731   else if (theId == "SHOW_ONLY_CMD") {
1732     showOnlyObjects(aObjects);
1733     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1734     updateCommandStatus();
1735   }
1736   else if (theId == "SHADING_CMD")
1737     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1738   else if (theId == "WIREFRAME_CMD")
1739     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1740   else if (theId == "HIDEALL_CMD") {
1741     QObjectPtrList aList = myDisplayer->displayedObjects();
1742     foreach (ObjectPtr aObj, aList) {
1743       if (module()->canEraseObject(aObj))
1744         aObj->setDisplayed(false);
1745     }
1746     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1747 #ifdef HAVE_SALOME
1748     //issue #2159 Hide all incomplete behavior
1749     viewer()->eraseAll();
1750 #endif
1751     updateCommandStatus();
1752     // Necessary for update icons in ObjectBrowser on Linux
1753     myObjectBrowser->updateAllIndexes();
1754   } else if (theId == "SELECT_VERTEX_CMD") {
1755     setViewerSelectionMode(TopAbs_VERTEX);
1756   } else if (theId == "SELECT_EDGE_CMD") {
1757     setViewerSelectionMode(TopAbs_EDGE);
1758   } else if (theId == "SELECT_FACE_CMD") {
1759     setViewerSelectionMode(TopAbs_FACE);
1760   } else if (theId == "INSERT_FOLDER_CMD") {
1761     insertFeatureFolder();
1762   } else if (theId == "ADD_TO_FOLDER_BEFORE_CMD") {
1763     insertToFolder(true);
1764   } else if (theId == "ADD_TO_FOLDER_AFTER_CMD") {
1765     insertToFolder(false);
1766   } else if (theId == "ADD_OUT_FOLDER_BEFORE_CMD") {
1767     moveOutFolder(true);
1768   } else if (theId == "ADD_OUT_FOLDER_AFTER_CMD") {
1769     moveOutFolder(false);
1770   } else if (theId == "SELECT_RESULT_CMD") {
1771     //setViewerSelectionMode(-1);
1772     //IMP: an attempt to use result selection with other selection modes
1773     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1774     setViewerSelectionMode(TopAbs_COMPSOLID);
1775   } else if (theId == "SHOW_RESULTS_CMD") {
1776     highlightResults(aObjects);
1777   } else if (theId == "SHOW_FEATURE_CMD") {
1778     highlightFeature(aObjects);
1779   } else if (theId == "SET_VIEW_NORMAL_CMD") {
1780     setNormalView();
1781   } else if (theId == "SET_VIEW_INVERTEDNORMAL_CMD") {
1782     setNormalView(true);
1783   }
1784 #ifdef TINSPECTOR
1785   else if (theId == "TINSPECTOR_VIEW") {
1786     Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1787     if (!anApplication.IsNull())
1788     {
1789       if (!MyTCommunicator)
1790       {
1791         MyTCommunicator = new TInspector_Communicator();
1792
1793         NCollection_List<Handle(Standard_Transient)> aParameters;
1794         aParameters.Append(anApplication);
1795         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1796         if (!aContext.IsNull())
1797           aParameters.Append(aContext);
1798
1799 #ifdef DEBUG_WITH_MESSAGE_REPORT
1800         Handle(Message_Report) aContextReport = aContext->GetReport();
1801         aContext->SetReportActive (Standard_True);
1802         aContextReport->SetLimit (1000);
1803         if (!aContextReport.IsNull())
1804           aParameters.Append(aContextReport);
1805 #endif
1806         MyVCallBack = new VInspector_CallBack();
1807         myDisplayer->setCallBack(MyVCallBack);
1808         #ifndef HAVE_SALOME
1809         AppElements_Viewer* aViewer = mainWindow()->viewer();
1810         if (aViewer)
1811           aViewer->setCallBack(MyVCallBack);
1812         #endif
1813         aParameters.Append(MyVCallBack);
1814
1815         MyTCommunicator->RegisterPlugin("TKDFBrowser");
1816         MyTCommunicator->RegisterPlugin("TKShapeView");
1817         MyTCommunicator->RegisterPlugin("TKVInspector");
1818 #ifdef DEBUG_WITH_MESSAGE_REPORT
1819         MyTCommunicator->RegisterPlugin("TKMessageView");
1820 #endif
1821         //MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1822         //MyTCommunicator->RegisterPlugin("TKSMBrowser"); // custom plugin to view ModelAPI
1823
1824         MyTCommunicator->Init(aParameters);
1825         MyTCommunicator->Activate("TKSMBrowser"); // to have button in TInspector
1826 #ifndef DEBUG_WITH_MESSAGE_REPORT
1827         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1828 #endif
1829         MyTCommunicator->Activate("TKDFBrowser");
1830
1831 #ifdef DEBUG_WITH_MESSAGE_REPORT
1832         MyTCommunicator->Activate("TKMessageView"); // temporary
1833         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1834 #endif
1835       }
1836       MyTCommunicator->SetVisible(true);
1837     }
1838   }
1839 #endif
1840 }
1841
1842 //**************************************************************
1843 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1844 {
1845   if (theMode == -1)
1846     myViewerSelMode.clear();
1847   else {
1848     if (myViewerSelMode.contains(theMode))
1849       myViewerSelMode.removeAll(theMode);
1850     else
1851       myViewerSelMode.append(theMode);
1852   }
1853   selectionActivate()->updateSelectionModes();
1854 }
1855
1856 //**************************************************************
1857 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1858 {
1859   QIntList aModes;
1860   module()->activeSelectionModes(aModes);
1861   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1862     aModes.append(myViewerSelMode);
1863   selectionActivate()->activateObjects(aModes, theList);
1864 }
1865
1866 //**************************************************************
1867 bool XGUI_Workshop::prepareForDisplay(const std::set<ObjectPtr>& theObjects) const
1868 {
1869   if (facesPanel()->isEmpty())
1870     return true;
1871
1872   // generate container of objects taking into account sub elments of compsolid
1873   std::set<ObjectPtr> anAllProcessedObjects;
1874   for (std::set<ObjectPtr>::const_iterator anObjectsIt = theObjects.begin();
1875     anObjectsIt != theObjects.end(); anObjectsIt++) {
1876     ObjectPtr anObject = *anObjectsIt;
1877     ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
1878     if (aCompRes.get()) {
1879       std::list<ResultPtr> allRes;
1880       ModelAPI_Tools::allSubs(aCompRes, allRes);
1881       if (allRes.empty()) {
1882         anAllProcessedObjects.insert(anObject);
1883       } else {
1884         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1885           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1886           if (aBody.get() && aBody->numberOfSubs() == 0)
1887             anAllProcessedObjects.insert(aBody);
1888         }
1889       }
1890     } else
1891       anAllProcessedObjects.insert(anObject);
1892   }
1893
1894   // find hidden objects in faces panel
1895   std::set<ObjectPtr> aHiddenObjects;
1896   QStringList aHiddenObjectNames;
1897   for (std::set<ObjectPtr>::const_iterator anObjectsIt = anAllProcessedObjects.begin();
1898        anObjectsIt != anAllProcessedObjects.end(); anObjectsIt++) {
1899     if (!facesPanel()->isObjectHiddenByPanel(*anObjectsIt))
1900       continue;
1901     aHiddenObjects.insert(*anObjectsIt);
1902     aHiddenObjectNames.append((*anObjectsIt)->data()->name().c_str());
1903   }
1904   if (aHiddenObjects.empty()) // in parameter objects there are no hidden objects in hide face
1905     return true;
1906
1907   int anAnswer = QMessageBox::question(
1908         desktop(), tr("Show object"),
1909         tr("'%1'\n are hidden by %2:\nRemove objects from the panel to be displayed?")
1910         .arg(aHiddenObjectNames.join(", ")).arg(facesPanel()->windowTitle()),
1911         QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
1912
1913   bool aToBeDisplayed = anAnswer == QMessageBox::Yes;
1914   if (aToBeDisplayed)
1915     facesPanel()->restoreObjects(aHiddenObjects);
1916
1917   return aToBeDisplayed;
1918 }
1919
1920 //**************************************************************
1921 void XGUI_Workshop::deleteObjects()
1922 {
1923   ModuleBase_IModule* aModule = module();
1924   // allow the module to delete objects, do nothing if it has succeed
1925   if (aModule->deleteObjects()) {
1926     updateCommandStatus();
1927     myDisplayer->updateViewer();
1928     return;
1929   }
1930
1931   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1932   if (anObjects.isEmpty())
1933     return;
1934
1935   if (!abortAllOperations())
1936     return;
1937
1938   bool hasResult = false;
1939   bool hasFeature = false;
1940   bool hasParameter = false;
1941   bool hasCompositeOwner = false;
1942   bool hasResultInHistory = false;
1943   bool hasFolder = false;
1944   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1945                                  hasResultInHistory, hasFolder);
1946   if (!(hasResult || hasFeature || hasParameter || hasFolder))
1947     return;
1948
1949   // Remove from the list non-deletable objects: infinite constructions which are not in history
1950   bool notDelete = true;
1951   QObjectPtrList::iterator aIt;
1952   for (aIt = anObjects.begin(); aIt != anObjects.end(); aIt++) {
1953     ObjectPtr aObj = (*aIt);
1954     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
1955     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1956     if (aFeature) {
1957       notDelete = (!aFeature->isInHistory()) && aConstr->isInfinite();
1958       if (notDelete) {
1959         anObjects.removeAll(aObj);
1960         aIt--;
1961       }
1962     }
1963   }
1964   // delete objects
1965   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1966   std::set<FeaturePtr> aFeatures;
1967   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1968   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1969
1970   std::set<FolderPtr> aFolders;
1971   ModuleBase_Tools::convertToFolders(anObjects, aFolders);
1972
1973   bool aDone = false;
1974   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1975   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1976   ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, module());
1977
1978   operationMgr()->startOperation(anOpAction);
1979
1980   std::set<FeaturePtr> aFeatureRefsToDelete;
1981   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1982     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1983     // It is necessary to clear selection in order to avoid selection changed event during
1984     // deletion and negative consequences connected with processing of already deleted items
1985     mySelector->clearSelection();
1986
1987     if (!aFeatureRefsToDelete.empty())
1988       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1989     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1990   }
1991   if (aFolders.size() > 0) {
1992     std::set<FolderPtr>::const_iterator anIt = aFolders.begin(),
1993                                          aLast = aFolders.end();
1994     for (; anIt != aLast; anIt++) {
1995       FolderPtr aFolder = *anIt;
1996       if (aFolder.get()) {
1997         DocumentPtr aDoc = aFolder->document();
1998         aDoc->removeFolder(aFolder);
1999       }
2000     }
2001   }
2002   // remove results selected
2003   std::list<ResultPtr> aResults;
2004   for(QObjectPtrList::const_iterator anIt = anObjects.begin(); anIt != anObjects.end(); anIt++) {
2005     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anIt);
2006     if (aRes.get() && aRes->data()->isValid() && !aRes->data()->isDeleted() &&
2007         aRes->groupName() != ModelAPI_ResultGroup::group() && // don't remove groups and fields
2008         aRes->groupName() != ModelAPI_ResultField::group()) // because they are badly selected
2009       aResults.push_back(aRes);
2010   }
2011   if (!aResults.empty()) {
2012     ModelAPI_Tools::removeResults(aResults);
2013   }
2014
2015   if (aDone)
2016     operationMgr()->commitOperation();
2017   else
2018     operationMgr()->abortOperation(operationMgr()->currentOperation());
2019
2020   myDisplayer->updateViewer();
2021 }
2022
2023 //**************************************************************
2024 void addRefsToFeature(const FeaturePtr& theFeature,
2025                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
2026                       std::set<FeaturePtr>& theReferences)
2027 {
2028   //if (theReferences.find(theFeature) != theReferences.end())
2029   //  return;
2030   if (theMainList.find(theFeature) == theMainList.end())
2031     return; // this feature is not in the selection list, so exists without references to it
2032   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
2033
2034   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
2035                                        aLast = aMainReferences.end();
2036   for (; anIt != aLast; anIt++) {
2037     FeaturePtr aRefFeature = *anIt;
2038     if (theReferences.find(aRefFeature) == theReferences.end())
2039       theReferences.insert(aRefFeature);
2040     addRefsToFeature(aRefFeature, theMainList, theReferences);
2041   }
2042 }
2043
2044 //**************************************************************
2045 void XGUI_Workshop::cleanHistory()
2046 {
2047   if (!abortAllOperations())
2048     return;
2049
2050   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2051   std::set<FeaturePtr> aFeatures;
2052   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2053
2054 #ifdef DEBUG_CLEAN_HISTORY
2055   QStringList anInfo;
2056   std::set<FeaturePtr>::const_iterator aFIt;
2057   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
2058     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
2059     anInfo.append(aFeature->name().c_str());
2060   }
2061   QString anInfoStr = anInfo.join(";\t");
2062   qDebug(QString("cleanHistory for: [%1] - %2").
2063     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
2064 #endif
2065
2066   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
2067   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
2068   // find for each object whether all reference values are in the map as key, that means that there
2069   // is no other reference in the model to this object, so it might be removed by cleaning history
2070   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - can't be deleted, dependency to bool_1
2071   // ext_1(bool_1, sk_3)  - can't be deleted, dependency to bool_1
2072   // vertex_1()
2073   // sk_2(ext_2) + (bool_1)  - can't be deleted, dependency to bool_1
2074   // ext_2(bool_1)  - can't be deleted, dependency to bool_1
2075   // sk_3()
2076   // Information: bool_1 is not selected
2077   std::set<FeaturePtr> anUnusedObjects;
2078   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
2079                                                               aMainLast = aReferences.end();
2080   for (; aMainIt != aMainLast; aMainIt++) {
2081     FeaturePtr aMainListFeature = aMainIt->first;
2082     std::set<FeaturePtr> aMainRefList = aMainIt->second;
2083     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
2084                                                   aRefLast = aMainRefList.end();
2085     bool aFeatureOutOfTheList = false;
2086     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
2087       FeaturePtr aRefFeature = *aRefIt;
2088       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
2089     }
2090     if (!aFeatureOutOfTheList)
2091       anUnusedObjects.insert(aMainListFeature);
2092   }
2093
2094 #ifdef DEBUG_CLEAN_HISTORY
2095   anInfo.clear();
2096   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
2097     FeaturePtr aFeature = *aFIt;
2098     anInfo.append(aFeature->name().c_str());
2099   }
2100   qDebug(QString("unused objects: [%1] - %2").
2101     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
2102 #endif
2103
2104   // warn about the references remove, break the delete operation if the user chose it
2105   if (!anUnusedObjects.empty()) {
2106     QStringList aNames;
2107     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
2108       aNames.append(aFeature->name().c_str());
2109     }
2110     aNames.sort();
2111     QString anUnusedNames = aNames.join(", ");
2112
2113     QString anActionId = "CLEAN_HISTORY_CMD";
2114     QString aDescription = ModuleBase_Tools::translate("workshop",
2115         contextMenuMgr()->action(anActionId)->text().toStdString());
2116
2117     QMessageBox aMessageBox(desktop());
2118     aMessageBox.setWindowTitle(aDescription);
2119     aMessageBox.setIcon(QMessageBox::Warning);
2120     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2121     aMessageBox.setDefaultButton(QMessageBox::No);
2122
2123     const char* aKeyStr = "Unused features are the following: "
2124                           "%1.\nThese features will be deleted.\nWould you like to continue?";
2125     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
2126     aMessageBox.setText(aText);
2127     if (aMessageBox.exec() == QMessageBox::No)
2128       return;
2129
2130     // 1. start operation
2131     aDescription += "by deleting of " +
2132       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
2133     ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, module());
2134     operationMgr()->startOperation(anOpAction);
2135
2136     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
2137     // It is necessary to clear selection in order to avoid selection changed event during
2138     // deletion and negative consequences connected with processing of already deleted items
2139     mySelector->clearSelection();
2140
2141     std::set<FeaturePtr> anIgnoredFeatures;
2142     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
2143       operationMgr()->commitOperation();
2144     }
2145     else {
2146       operationMgr()->abortOperation(operationMgr()->currentOperation());
2147     }
2148   }
2149   else {
2150     QString anActionId = "CLEAN_HISTORY_CMD";
2151     QString aDescription = contextMenuMgr()->action(anActionId)->text();
2152
2153     QMessageBox aMessageBox(desktop());
2154     aMessageBox.setWindowTitle(aDescription);
2155     aMessageBox.setIcon(QMessageBox::Warning);
2156     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2157     aMessageBox.setDefaultButton(QMessageBox::No);
2158
2159     QString aText;
2160     aMessageBox.setStandardButtons(QMessageBox::Ok);
2161     aMessageBox.setDefaultButton(QMessageBox::Ok);
2162
2163     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
2164     aMessageBox.setText(aText);
2165
2166     if (aMessageBox.exec() == QMessageBox::No)
2167       return;
2168   }
2169 }
2170
2171 //**************************************************************
2172 bool compareFeature(const FeaturePtr& theF1, const FeaturePtr& theF2) {
2173   DocumentPtr aDoc = theF1->document();
2174   return aDoc->index(theF1) < aDoc->index(theF2);
2175 }
2176 void XGUI_Workshop::moveObjects(const bool theSplit)
2177 {
2178   if (!abortAllOperations())
2179     return;
2180
2181   SessionPtr aMgr = ModelAPI_Session::get();
2182
2183   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2184   // It is necessary to clear selection in order to avoid selection changed event during
2185   // moving and negative consequences connected with processing of already moved items
2186   mySelector->clearSelection();
2187   // check whether the object can be moved. There should not be parts which are not loaded
2188   std::set<FeaturePtr> aFeatures;
2189   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2190   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
2191     return;
2192
2193   QString anActionId = theSplit ? "MOVE_CMD" : "MOVE_SPLIT_CMD";
2194   QString aDescription = contextMenuMgr()->action(anActionId)->text();
2195   aMgr->startOperation(aDescription.toStdString());
2196
2197   // Sort features by index in document
2198   std::list<FeaturePtr> aFList(aFeatures.begin(), aFeatures.end());
2199   aFList.sort(compareFeature);
2200
2201   DocumentPtr anActiveDocument = aMgr->activeDocument();
2202   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
2203   std::list<FeaturePtr>::const_iterator anIt = aFList.begin(), aLast = aFList.end();
2204   for (; anIt != aLast; anIt++) {
2205     FeaturePtr aFeature = *anIt;
2206     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
2207       continue;
2208
2209     anActiveDocument->moveFeature(aFeature, aCurrentFeature, theSplit);
2210     aCurrentFeature = anActiveDocument->currentFeature(true);
2211   }
2212   aMgr->finishOperation();
2213   updateCommandStatus();
2214   myViewerProxy->update();
2215 }
2216
2217 //**************************************************************
2218 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
2219 {
2220   std::set<FeaturePtr> aFeatures;
2221   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
2222
2223   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
2224 }
2225
2226 //******************************************************
2227 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
2228 {
2229   bool isFoundResultType = false;
2230   foreach(ObjectPtr anObj, theObjects)
2231   {
2232     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2233     if (aResult.get() == NULL)
2234       continue;
2235
2236     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
2237     if (isFoundResultType)
2238       break;
2239   }
2240   return isFoundResultType;
2241 }
2242
2243 //**************************************************************
2244 // Returns the list of all features for theDocument and all features of
2245 // all nested parts.
2246 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
2247 {
2248   std::list<FeaturePtr> aResultList;
2249   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
2250   foreach (const FeaturePtr& aFeature, anAllFeatures) {
2251     // The order of appending features of the part and the part itself is important
2252
2253     // Append features from a part feature
2254     std::list<ResultPtr> aResults;
2255     ModelAPI_Tools::allResults(aFeature, aResults);
2256     foreach (const ResultPtr& aResult, aResults) {
2257       ResultPartPtr aResultPart =
2258           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
2259       if (aResultPart.get() && aResultPart->partDoc().get()) {
2260         // Recursion
2261         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
2262         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
2263       }
2264     }
2265
2266     aResultList.push_back(aFeature);
2267   }
2268   return aResultList;
2269 }
2270
2271 //**************************************************************
2272 // Returns the list of features placed between theObject and the current feature
2273 // in the same document. Excludes theObject, includes the current feature.
2274 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
2275 {
2276   std::list<FeaturePtr> aResult;
2277   DocumentPtr aDocument = theObject->document();
2278   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
2279   // find the object iterator
2280   std::list<FeaturePtr>::iterator aObjectIt =
2281     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
2282   if (aObjectIt == anAllFeatures.end())
2283     return aResult;
2284   // find the current feature iterator
2285   std::list<FeaturePtr>::iterator aCurrentIt =
2286     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
2287   if (aCurrentIt == anAllFeatures.end())
2288     return aResult;
2289   // check the right order
2290   if (std::distance(aObjectIt, anAllFeatures.end()) <=
2291       std::distance(aCurrentIt, anAllFeatures.end()))
2292     return aResult;
2293   // exclude the object
2294   std::advance(aObjectIt, 1);
2295   // include the current feature
2296   std::advance(aCurrentIt, 1);
2297   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
2298 }
2299
2300 //******************************************************
2301 bool XGUI_Workshop::canMoveFeature()
2302 {
2303   QString anActionId = "MOVE_CMD";
2304
2305   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2306   QObjectPtrList aValidatedObjects;
2307   foreach (ObjectPtr aObject, aObjects) {
2308     if (!myModule->canApplyAction(aObject, anActionId))
2309       continue;
2310     // To be moved feature should be in active document
2311     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
2312       continue;
2313     aValidatedObjects.append(aObject);
2314   }
2315   if (aValidatedObjects.size() != aObjects.size())
2316     aObjects = aValidatedObjects;
2317
2318   bool aCanMove = !aObjects.empty();
2319
2320   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
2321   for (; anIt != aLast && aCanMove; anIt++) {
2322     ObjectPtr aObject = *anIt;
2323     if (!aObject.get() || !aObject->data().get() || !aObject->data()->isValid()) {
2324       aCanMove = false;
2325       break;
2326     }
2327     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
2328     // only groups can be moved to the end for now (#2451)
2329     if (aFeat.get() && aFeat->getKind() != "Group") {
2330       aCanMove = false;
2331       break;
2332     }
2333
2334     // 1. Get features placed between selected and current in the document
2335     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
2336     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
2337     if (aFeaturesBetween.empty())
2338       aCanMove = false;
2339     else {
2340       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
2341       // 2. Get all reference features to the selected object in the document
2342       std::set<FeaturePtr> aRefFeatures;
2343       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
2344
2345       if (aRefFeatures.empty())
2346         continue;
2347       else {
2348         // 3. Find any placed features in all reference features
2349         std::set<FeaturePtr> aIntersectionFeatures;
2350         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
2351                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
2352                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
2353         // 4. Return false if any reference feature is placed before current feature
2354         if (!aIntersectionFeatures.empty())
2355           aCanMove = false;
2356       }
2357     }
2358   }
2359   return aCanMove;
2360 }
2361
2362 //**************************************************************
2363 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
2364 {
2365   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
2366   if (!aCanBeShaded) {
2367     ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
2368     if (aCompRes.get() != NULL) { // change colors for all sub-solids
2369       std::list<ResultPtr> allRes;
2370       ModelAPI_Tools::allSubs(aCompRes, allRes);
2371       std::list<ResultPtr>::iterator aRes = allRes.begin();
2372       for(; aRes != allRes.end() && !aCanBeShaded; aRes++) {
2373         aCanBeShaded = myDisplayer->canBeShaded(*aRes);
2374       }
2375     }
2376   }
2377   return aCanBeShaded;
2378 }
2379
2380 //**************************************************************
2381 bool XGUI_Workshop::canChangeProperty(const QString& theActionName) const
2382 {
2383   if (theActionName == "COLOR_CMD" ||
2384       theActionName == "DEFLECTION_CMD" ||
2385       theActionName == "TRANSPARENCY_CMD") {
2386     QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2387
2388     std::set<std::string> aTypes;
2389     aTypes.insert(ModelAPI_ResultGroup::group());
2390     aTypes.insert(ModelAPI_ResultConstruction::group());
2391     aTypes.insert(ModelAPI_ResultBody::group());
2392     aTypes.insert(ModelAPI_ResultPart::group());
2393
2394     return hasResults(aObjects, aTypes);
2395   }
2396   return false;
2397 }
2398
2399
2400 //**************************************************************
2401 void getDefaultColor(ObjectPtr theObject, const bool isEmptyColorValid,
2402   std::vector<int>& theColor)
2403 {
2404   theColor.clear();
2405   // get default color from the preferences manager for the given result
2406   if (theColor.empty()) {
2407     std::string aSection, aName, aDefault;
2408     theObject->colorConfigInfo(aSection, aName, aDefault);
2409     if (!aSection.empty() && !aName.empty()) {
2410       theColor = Config_PropManager::color(aSection, aName);
2411     }
2412   }
2413   if (!isEmptyColorValid && theColor.empty()) {
2414     // all AIS objects, where the color is not set, are in black.
2415     // The color should be defined in XML or set in the attribute
2416     theColor = Config_PropManager::color("Visualization", "object_default_color");
2417     Events_InfoMessage("XGUI_CustomPrs",
2418       "A default color is not defined in the preferences for this kind of result").send();
2419   }
2420 }
2421
2422 //**************************************************************
2423 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
2424 {
2425
2426   AttributeIntArrayPtr aColorAttr;
2427   // 1. find the current color of the object. This is a color of AIS presentation
2428   // The objects are iterated until a first valid color is found
2429   std::vector<int> aColor;
2430   foreach(ObjectPtr anObject, theObjects) {
2431     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2432     if (aResult.get()) {
2433       ModelAPI_Tools::getColor(aResult, aColor);
2434       if (aColor.empty())
2435         getDefaultColor(aResult, false, aColor);
2436     }
2437     else {
2438       // TODO: remove the obtaining a color from the AIS object
2439       // this does not happen never because:
2440       // 1. The color can be changed only on results
2441       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2442       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2443       if (anAISObj.get()) {
2444         aColor.resize(3);
2445         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
2446       }
2447     }
2448     if (!aColor.empty())
2449       break;
2450   }
2451   if (aColor.size() != 3)
2452     return;
2453
2454   if (!abortAllOperations())
2455   return;
2456   // 2. show the dialog to change the value
2457   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
2458   aDlg->setColor(aColor);
2459   aDlg->move(QCursor::pos());
2460   bool isDone = aDlg->exec() == QDialog::Accepted;
2461   if (!isDone)
2462     return;
2463
2464   bool isRandomColor = aDlg->isRandomColor();
2465
2466   // 3. abort the previous operation and start a new one
2467   SessionPtr aMgr = ModelAPI_Session::get();
2468   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
2469   aMgr->startOperation(aDescription.toStdString());
2470
2471   // 4. set the value to all results
2472   std::vector<int> aColorResult = aDlg->getColor();
2473   foreach(ObjectPtr anObj, theObjects) {
2474     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2475     if (aResult.get() != NULL) {
2476       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2477       if (aBodyResult.get() != NULL) { // change colors for all sub-solids
2478         std::list<ResultPtr> allRes;
2479         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2480         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2481           ModelAPI_Tools::setColor(*aRes, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2482         }
2483       }
2484       ModelAPI_Tools::setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2485     }
2486   }
2487   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2488   aMgr->finishOperation();
2489   updateCommandStatus();
2490   myViewerProxy->update();
2491 }
2492
2493 //**************************************************************
2494 void setTransparency(double theTransparency, const QObjectPtrList& theObjects)
2495 {
2496   foreach(ObjectPtr anObj, theObjects) {
2497     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2498     if (aResult.get() != NULL) {
2499       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2500       if (aBodyResult.get() != NULL) { // change property for all sub-solids
2501         std::list<ResultPtr> allRes;
2502         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2503         std::list<ResultPtr>::iterator aRes;
2504         for(aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2505           ModelAPI_Tools::setTransparency(*aRes, theTransparency);
2506         }
2507       }
2508       ModelAPI_Tools::setTransparency(aResult, theTransparency);
2509     }
2510   }
2511 }
2512
2513 //**************************************************************
2514 double getDefaultDeflection(const ObjectPtr& theObject)
2515 {
2516   double aDeflection = -1;
2517   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
2518   if (aResult.get()) {
2519     bool isConstruction = false;
2520
2521     std::string aResultGroup = aResult->groupName();
2522     if (aResultGroup == ModelAPI_ResultConstruction::group())
2523       isConstruction = true;
2524     else if (aResultGroup == ModelAPI_ResultBody::group()) {
2525       GeomShapePtr aGeomShape = aResult->shape();
2526       if (aGeomShape.get()) {
2527         // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
2528         // correction of deviation for them should not influence to the application performance
2529         GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
2530         isConstruction = !anExp.more();
2531       }
2532     }
2533     if (isConstruction)
2534       aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
2535     else
2536       aDeflection = Config_PropManager::real("Visualization", "body_deflection");
2537   }
2538   return aDeflection;
2539 }
2540
2541 //**************************************************************
2542 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
2543 {
2544   AttributeDoublePtr aDoubleAttr;
2545   // 1. find the current property of the object. This is a property of AIS presentation
2546   // The objects are iterated until a first valid property is found
2547   double aDeflection = -1;
2548   foreach(ObjectPtr anObject, theObjects) {
2549     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2550     if (aResult.get()) {
2551       aDeflection = ModelAPI_Tools::getDeflection(aResult);
2552       if (aDeflection < 0)
2553         aDeflection = getDefaultDeflection(aResult);
2554     }
2555     else {
2556       // TODO: remove the obtaining a property from the AIS object
2557       // this does not happen never because:
2558       // 1. The property can be changed only on results
2559       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2560       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2561       if (anAISObj.get()) {
2562         aDeflection = anAISObj->getDeflection();
2563       }
2564     }
2565     if (aDeflection > 0)
2566       break;
2567   }
2568   if (aDeflection < 0)
2569     return;
2570
2571   if (!abortAllOperations())
2572   return;
2573   // 2. show the dialog to change the value
2574   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
2575   aDlg->setDeflection(aDeflection);
2576   aDlg->move(QCursor::pos());
2577   bool isDone = aDlg->exec() == QDialog::Accepted;
2578   if (!isDone)
2579     return;
2580
2581   // 3. abort the previous operation and start a new one
2582   SessionPtr aMgr = ModelAPI_Session::get();
2583   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2584   aMgr->startOperation(aDescription.toStdString());
2585
2586   // 4. set the value to all results
2587   aDeflection = aDlg->getDeflection();
2588   foreach(ObjectPtr anObj, theObjects) {
2589     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2590     if (aResult.get() != NULL) {
2591       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2592       if (aBodyResult.get() != NULL) { // change property for all sub-solids
2593         std::list<ResultPtr> allRes;
2594         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2595         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2596           ModelAPI_Tools::setDeflection(*aRes, aDeflection);
2597         }
2598       }
2599       ModelAPI_Tools::setDeflection(aResult, aDeflection);
2600     }
2601   }
2602   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2603   aMgr->finishOperation();
2604   updateCommandStatus();
2605 }
2606
2607 //**************************************************************
2608 double getDefaultTransparency(const ResultPtr& theResult)
2609 {
2610   return Config_PropManager::integer("Visualization", "shaper_default_transparency") / 100.;
2611 }
2612
2613 //**************************************************************
2614 void XGUI_Workshop::changeTransparency(const QObjectPtrList& theObjects)
2615 {
2616   AttributeDoublePtr aDoubleAttr;
2617   // 1. find the current property of the object. This is a property of AIS presentation
2618   // The objects are iterated until a first valid property is found
2619   double aCurrentValue = -1;
2620   foreach(ObjectPtr anObject, theObjects) {
2621     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2622     if (aResult.get()) {
2623       aCurrentValue = ModelAPI_Tools::getTransparency(aResult);
2624       if (aCurrentValue < 0)
2625         aCurrentValue = getDefaultTransparency(aResult);
2626     }
2627     if (aCurrentValue > 0)
2628       break;
2629   }
2630   if (aCurrentValue < 0)
2631     return;
2632
2633   if (!abortAllOperations())
2634     return;
2635
2636   // 2. show the dialog to change the value
2637   XGUI_PropertyDialog* aDlg = new XGUI_PropertyDialog(desktop());
2638   aDlg->setWindowTitle(tr("Transparency"));
2639   XGUI_TransparencyWidget* aTransparencyWidget = new XGUI_TransparencyWidget(aDlg);
2640   connect(aTransparencyWidget, SIGNAL(transparencyValueChanged()),
2641           this, SLOT(onTransparencyValueChanged()));
2642   aDlg->setContent(aTransparencyWidget);
2643   aTransparencyWidget->setValue(aCurrentValue);
2644
2645   // 3. abort the previous operation and start a new one
2646   SessionPtr aMgr = ModelAPI_Session::get();
2647   QString aDescription = contextMenuMgr()->action("TRANSPARENCY_CMD")->text();
2648   aMgr->startOperation(aDescription.toStdString());
2649
2650   if (aDlg->exec() == QDialog::Accepted) {
2651     // 4. set the value to all results
2652     aCurrentValue = aTransparencyWidget->getValue();
2653     setTransparency(aCurrentValue, theObjects);
2654     aMgr->finishOperation();
2655   } else {
2656     aMgr->abortOperation();
2657     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2658   }
2659
2660   updateCommandStatus();
2661 }
2662
2663 //**************************************************************
2664 void XGUI_Workshop::onTransparencyValueChanged()
2665 {
2666   XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2667   if (!aTransparencyWidget)
2668     return;
2669
2670   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2671   setTransparency(aTransparencyWidget->getValue(), anObjects);
2672   static const Events_ID kRedisplayEvent =
2673     Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2674   Events_Loop::loop()->flush(kRedisplayEvent);
2675
2676   myViewerProxy->update();
2677 }
2678
2679
2680 //******************************************************
2681 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2682 {
2683   if (isVisible) {
2684     std::set<ObjectPtr> anObjects;
2685     foreach (ObjectPtr aObj, theList) {
2686       anObjects.insert(aObj);
2687     }
2688     if (!prepareForDisplay(anObjects))
2689       return;
2690   }
2691
2692   foreach (ObjectPtr aObj, theList) {
2693     aObj->setDisplayed(isVisible);
2694   }
2695   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2696   myObjectBrowser->updateAllIndexes();
2697
2698   updateColorScaleVisibility();
2699   displayer()->updateViewer();
2700 }
2701
2702 //**************************************************************
2703 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2704 {
2705   QObjectPtrList aSrcList = theList;
2706   // Hide all displayed objects
2707   QObjectPtrList aList = myDisplayer->displayedObjects();
2708   foreach (ObjectPtr aObj, aList) {
2709     if ((!aSrcList.contains(aObj)) && (module()->canEraseObject(aObj)))
2710       aObj->setDisplayed(false);
2711     else
2712       aSrcList.removeAll(aObj);
2713   }
2714   //Do not use eraseAll if you didn't send Redisplay event:
2715   //all objects are erased from viewer, but considered as displayed in displayer
2716   // Problem in bug 2218
2717   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2718 #ifdef HAVE_SALOME
2719     //issue #2159 Hide all incomplete behavior
2720     viewer()->eraseAll();
2721 #endif
2722
2723   std::set<ObjectPtr> anObjects;
2724   foreach (ObjectPtr aObj, aSrcList) {
2725     anObjects.insert(aObj);
2726   }
2727
2728   if (!prepareForDisplay(anObjects))
2729     return;
2730
2731   // Show only objects from the list
2732   foreach (ObjectPtr aObj, aSrcList) {
2733     aObj->setDisplayed(true);
2734   }
2735   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2736
2737   // Necessary for update icons in ObjectBrowser on Linux
2738   myObjectBrowser->updateAllIndexes();
2739   updateColorScaleVisibility();
2740   displayer()->updateViewer();
2741 }
2742
2743
2744 //**************************************************************
2745 void XGUI_Workshop::updateColorScaleVisibility()
2746 {
2747   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2748   viewer()->setColorScaleShown(false);
2749   if (aObjects.size() == 1) {
2750     FieldStepPtr aStep =
2751       std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(aObjects.first());
2752     if (aStep.get() && myDisplayer->isVisible(aStep)) {
2753       AISObjectPtr aAisPtr = myDisplayer->getAISObject(aStep);
2754       Handle(AIS_InteractiveObject) aIO = aAisPtr->impl<Handle(AIS_InteractiveObject)>();
2755       ModuleBase_IStepPrs* aPrs = dynamic_cast<ModuleBase_IStepPrs*>(aIO.get());
2756       if (aPrs) {
2757         ModelAPI_AttributeTables::ValueType aType = aPrs->dataType();
2758         if ((aType == ModelAPI_AttributeTables::DOUBLE) ||
2759           (aType == ModelAPI_AttributeTables::INTEGER) ||
2760           (aType == ModelAPI_AttributeTables::BOOLEAN)) {
2761           myViewerProxy->setupColorScale();
2762           if (aType == ModelAPI_AttributeTables::BOOLEAN) {
2763             myViewerProxy->setColorScaleIntervals(2);
2764             myViewerProxy->setColorScaleRange(0., 1.);
2765           }
2766           else {
2767             double aMin, aMax;
2768             aPrs->dataRange(aMin, aMax);
2769             myViewerProxy->setColorScaleRange(aMin, aMax);
2770           }
2771           myViewerProxy->setColorScaleTitle(aStep->name().c_str());
2772           myViewerProxy->setColorScaleShown(true);
2773         }
2774       }
2775     }
2776   }
2777 }
2778
2779
2780 //**************************************************************
2781 void XGUI_Workshop::setNormalView(bool toInvert)
2782 {
2783   QList<ModuleBase_ViewerPrsPtr> aPrsList =
2784     mySelector->selection()->getSelected(ModuleBase_ISelection::Viewer);
2785   GeomShapePtr aPlanarFace;
2786   foreach(ModuleBase_ViewerPrsPtr aPrs, aPrsList) {
2787     GeomShapePtr aShape = aPrs->shape();
2788     if (aShape.get() && aShape->isPlanar()) {
2789       aPlanarFace = aShape;
2790       break;
2791     }
2792   }
2793   if (aPlanarFace.get()) {
2794     GeomFacePtr aFace(new GeomAPI_Face(aPlanarFace));
2795     GeomPlanePtr aPlane = aFace->getPlane();
2796     GeomDirPtr aNormal = aPlane->direction();
2797     if (toInvert)
2798       aNormal->reverse();
2799     GeomPointPtr aPos = aPlane->location();
2800
2801     double aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2802     aFace->computeSize(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2803
2804     Handle(V3d_View) aView = myViewerProxy->activeView();
2805     double aScale = aView->Scale();
2806     aView->SetAt(aPos->x(), aPos->y(), aPos->z());
2807     aView->SetProj(aNormal->x(), aNormal->y(), aNormal->z());
2808     Bnd_Box aBox;
2809     aBox.Update(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2810     aView->FitAll(aBox);
2811   }
2812 }
2813
2814 //**************************************************************
2815 void XGUI_Workshop::registerValidators() const
2816 {
2817   SessionPtr aMgr = ModelAPI_Session::get();
2818   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2819 }
2820
2821 //**************************************************************
2822 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2823 {
2824   if (!theDoc)
2825     return;
2826   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2827   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2828 }
2829
2830 //**************************************************************
2831 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2832 {
2833   for (int i = 0; i < theDoc->size(theGroup); i++)
2834     theDoc->object(theGroup, i)->setDisplayed(true);
2835     //displayObject(theDoc->object(theGroup, i));
2836   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2837 }
2838
2839 //**************************************************************
2840 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2841 {
2842   foreach(ObjectPtr anObj, theList) {
2843     myDisplayer->setDisplayMode(anObj, (XGUI_Displayer::DisplayMode)theMode, false);
2844
2845     ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObj);
2846     if (aBodyResult.get() != NULL) { // change display mode for all sub-solids
2847       std::list<ResultPtr> allRes;
2848       ModelAPI_Tools::allSubs(aBodyResult, allRes);
2849       for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2850         myDisplayer->setDisplayMode(*aRes, (XGUI_Displayer::DisplayMode)theMode, false);
2851       }
2852     }
2853   }
2854   if (theList.size() > 0)
2855     myDisplayer->updateViewer();
2856 }
2857
2858 //**************************************************************
2859 void XGUI_Workshop::closeDocument()
2860 {
2861   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2862   while (anOperation) {
2863     anOperation->abort();
2864     anOperation = operationMgr()->currentOperation();
2865   }
2866   //myDisplayer->closeLocalContexts();
2867   myDisplayer->eraseAll();
2868   objectBrowser()->clearContent();
2869
2870   module()->closeDocument();
2871   // we need to clear viewer (with created filters) to do not have problems in 2nd SALOME study
2872   module()->clearViewer();
2873
2874
2875   // data model need not process the document's signals about objects modifications as
2876   // the document is closed
2877   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2878
2879   SessionPtr aMgr = ModelAPI_Session::get();
2880   aMgr->closeAll();
2881
2882   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2883 }
2884
2885 //******************************************************
2886 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2887 {
2888   XGUI_HistoryMenu* aMenu = NULL;
2889   if (isSalomeMode()) {
2890     QAction* anAction = qobject_cast<QAction*>(theObject);
2891     if (!anAction)
2892       return;
2893     aMenu = new XGUI_HistoryMenu(anAction);
2894   } else {
2895     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2896     aMenu = new XGUI_HistoryMenu(aButton);
2897   }
2898   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2899   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2900 }
2901
2902 //******************************************************
2903 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2904 {
2905   QList<ActionInfo> aResult;
2906   std::list<std::string>::const_iterator it = theList.cbegin();
2907   for (; it != theList.cend(); it++) {
2908     QString anId = QString::fromStdString(*it);
2909     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2910     if (isEditing) {
2911       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2912     }
2913     ActionInfo anInfo;
2914     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2915     if (aContextMenuAct) {
2916       anInfo.initFrom(aContextMenuAct);
2917     } else {
2918       anInfo = myActionsMgr->actionInfoById(anId);
2919     }
2920     if (isEditing) {
2921       anInfo.text = anInfo.text.prepend("Modify ");
2922     }
2923     aResult << anInfo;
2924   }
2925   return aResult;
2926 }
2927
2928 //******************************************************
2929 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2930 {
2931 #ifdef HAVE_SALOME
2932   salomeConnector()->putInfo(theMessage, -1);
2933 #else
2934   myMainWindow->putInfo(theMessage, -1);
2935 #endif
2936 }
2937
2938 #ifdef HAVE_SALOME
2939 //******************************************************
2940 void XGUI_Workshop::synchronizeViewer()
2941 {
2942   SessionPtr aMgr = ModelAPI_Session::get();
2943   QList<DocumentPtr> aDocs;
2944   aDocs.append(aMgr->activeDocument());
2945   aDocs.append(aMgr->moduleDocument());
2946
2947   foreach(DocumentPtr aDoc, aDocs) {
2948     synchronizeGroupInViewer(aDoc, false);
2949   }
2950 }
2951
2952 //******************************************************
2953 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2954                                              bool theUpdateViewer)
2955 {
2956   FeaturePtr aFeature;
2957   ResultPtr aRes;
2958   int aSize = theDoc->numInternalFeatures();
2959   for (int i = 0; i < aSize; i++) {
2960     aFeature = theDoc->internalFeature(i);
2961     if (!aFeature.get())
2962       continue;
2963     const std::list<ResultPtr>& aResults = aFeature->results();
2964     std::list<ResultPtr>::const_iterator aIt;
2965     aFeature->setDisplayed(false);
2966     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2967       aRes = (*aIt);
2968       if (aRes->isDisplayed() && !aRes->isConcealed()) {
2969         // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2970         // be changed to the object becomes visible when the shape becomes not empty
2971         if (!aRes->shape().get() || aRes->shape()->isNull())
2972           continue;
2973         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aRes);
2974         if (aResBody.get())
2975           synchronizeResultTree(aResBody, false);
2976         else {
2977           if (aRes->isInHistory()) {
2978             if (aRes->isDisplayed())
2979               myDisplayer->display(aRes, false);
2980             else
2981               myDisplayer->erase(aRes, false);
2982           }
2983           else
2984             aRes->setDisplayed(false);
2985         }
2986       }
2987     }
2988   }
2989   if (theUpdateViewer)
2990     myDisplayer->updateViewer();
2991 }
2992
2993 void XGUI_Workshop::synchronizeResultTree(const ResultBodyPtr& theRes, bool theUpdateViewer)
2994 {
2995   if (theRes->numberOfSubs() > 0)
2996     for (int i = 0; i < theRes->numberOfSubs(); i++) {
2997       ResultBodyPtr aRes = theRes->subResult(i);
2998       if (aRes.get())
2999         synchronizeResultTree(aRes, theUpdateViewer);
3000     }
3001   else {
3002     if (theRes->isDisplayed())
3003       myDisplayer->display(theRes, theUpdateViewer);
3004     else
3005       myDisplayer->erase(theRes, theUpdateViewer);
3006   }
3007 }
3008 #endif
3009
3010 //******************************************************
3011 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
3012 {
3013   FeaturePtr aFeature;
3014   QObjectPtrList aSelList = theObjects;
3015   QObjectPtrList aNewSel;
3016   bool aHasHidden = false;
3017   foreach(ObjectPtr aObj, theObjects) {
3018     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
3019     if (aFeature.get()) {
3020       std::list<ResultPtr> aResults;
3021       ModelAPI_Tools::allResults(aFeature, aResults);
3022       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
3023       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
3024         aHasHidden |= (*aIt)->isConcealed();
3025         aSelList.append(*aIt);
3026         aNewSel.append(*aIt);
3027       }
3028     }
3029   }
3030   if (aSelList.count() > theObjects.count()) {
3031     // if something was found
3032     objectBrowser()->setObjectsSelected(aSelList);
3033     objectBrowser()->ensureVisible(aNewSel.first());
3034   }
3035   if (aHasHidden)
3036     QMessageBox::information(desktop(), tr("Find results"),
3037                              tr("Results not found"), QMessageBox::Ok);
3038 }
3039
3040 //******************************************************
3041 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
3042 {
3043   ResultPtr aResult;
3044   QObjectPtrList aSelList = theObjects;
3045   QObjectPtrList aNewSel;
3046   FeaturePtr aFeature;
3047   foreach(ObjectPtr aObj, theObjects) {
3048     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
3049     if (aResult.get()) {
3050       aFeature = ModelAPI_Feature::feature(aResult);
3051       if (aFeature.get()) {
3052         aSelList.append(aFeature);
3053         aNewSel.append(aFeature);
3054       }
3055     }
3056   }
3057   if (aSelList.count() > theObjects.count()) {
3058     // if something was found
3059     objectBrowser()->setObjectsSelected(aSelList);
3060     objectBrowser()->ensureVisible(aNewSel.first());
3061   }
3062 }
3063
3064 void XGUI_Workshop::insertFeatureFolder()
3065 {
3066   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
3067   if (aObjects.isEmpty())
3068     return;
3069   ObjectPtr aObj = aObjects.first();
3070   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
3071   if (aFeature.get() == NULL)
3072     return;
3073   SessionPtr aMgr = ModelAPI_Session::get();
3074   DocumentPtr aDoc = aMgr->activeDocument();
3075
3076   QString aDescription = contextMenuMgr()->action("INSERT_FOLDER_CMD")->text();
3077
3078   aMgr->startOperation(aDescription.toStdString());
3079   aDoc->addFolder(aFeature);
3080   aMgr->finishOperation();
3081
3082   updateCommandStatus();
3083 }
3084
3085
3086 void XGUI_Workshop::insertToFolder(bool isBefore)
3087 {
3088   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
3089   if (aFeatures.empty())
3090     return;
3091
3092   SessionPtr aMgr = ModelAPI_Session::get();
3093   DocumentPtr aDoc = aMgr->activeDocument();
3094
3095   FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
3096                                 aDoc->findFolderBelow(aFeatures);
3097   if (!aFolder.get())
3098     return;
3099
3100   QString aDescription = contextMenuMgr()->action(
3101     isBefore ? "ADD_TO_FOLDER_BEFORE_CMD" : "ADD_TO_FOLDER_AFTER_CMD")->text();
3102
3103   QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
3104
3105   aMgr->startOperation(aDescription.toStdString());
3106   aDoc->moveToFolder(aFeatures, aFolder);
3107   aMgr->finishOperation();
3108
3109   myObjectBrowser->setFoldersState(aStates);
3110
3111   updateCommandStatus();
3112 }
3113
3114 void XGUI_Workshop::moveOutFolder(bool isBefore)
3115 {
3116   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
3117   if (aFeatures.empty())
3118     return;
3119
3120   SessionPtr aMgr = ModelAPI_Session::get();
3121   DocumentPtr aDoc = aMgr->activeDocument();
3122
3123   QString aDescription = contextMenuMgr()->action(
3124     isBefore ? "ADD_OUT_FOLDER_BEFORE_CMD" : "ADD_OUT_FOLDER_AFTER_CMD")->text();
3125
3126   QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
3127
3128   aMgr->startOperation(aDescription.toStdString());
3129   aDoc->removeFromFolder(aFeatures, isBefore);
3130   aMgr->finishOperation();
3131
3132   myObjectBrowser->setFoldersState(aStates);
3133
3134   updateCommandStatus();
3135 }
3136
3137 void XGUI_Workshop::onAutoApply()
3138 {
3139   SessionPtr aMgr = ModelAPI_Session::get();
3140   bool isBlocked = aMgr->isAutoUpdateBlocked();
3141   aMgr->blockAutoUpdate(!isBlocked);
3142 }
3143
3144 void XGUI_Workshop::updateAutoComputeState()
3145 {
3146   SessionPtr aMgr = ModelAPI_Session::get();
3147   bool isComputeBlocked = aMgr->isAutoUpdateBlocked();
3148 #ifdef HAVE_SALOME
3149 //  QAction* aUpdateCmd;
3150 //  QList<QAction*> aCommands = mySalomeConnector->commandList();
3151 //  foreach(QAction* aCmd, aCommands) {
3152 //    if (aCmd->data().toString() == "AUTOCOMPUTE_CMD") {
3153 //      aUpdateCmd = aCmd;
3154 //      break;
3155 //    }
3156 //  }
3157 //  aUpdateCmd->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
3158 //    QIcon(":pictures/autoapply_start.png"));
3159 #else
3160   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
3161   AppElements_Command* aUpdateCmd = aMenuBar->feature("AUTOCOMPUTE_CMD");
3162   aUpdateCmd->button()->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
3163     QIcon(":pictures/autoapply_start.png"));
3164 #endif
3165 }
3166
3167
3168 void XGUI_Workshop::clearTemporaryDir()
3169 {
3170   QDir aDir(myTmpDir.path());
3171   if (!aDir.isEmpty()) {
3172     QStringList aEntries;
3173     aDir.entryList(aEntries);
3174     foreach(QString aFile, aEntries) {
3175       aDir.remove(aFile);
3176     }
3177   }
3178 }
3179
3180
3181 void XGUI_Workshop::onDockSizeChanged()
3182 {
3183   QDockWidget* aDockWgt = dynamic_cast<QDockWidget*>(myObjectBrowser->parentWidget());
3184   int aObWidth = aDockWgt->size().width();
3185   if (myPropertyPanel->width() != aObWidth) {
3186     QList<QDockWidget*> aWgtList;
3187     aWgtList << myPropertyPanel << aDockWgt;
3188     QList<int> aSizeList;
3189     aSizeList << aObWidth << aObWidth;
3190     desktop()->resizeDocks(aWgtList, aSizeList, Qt::Horizontal);
3191     disconnect(myObjectBrowser, SIGNAL(sizeChanged()), this, SLOT(onDockSizeChanged()));
3192   }
3193 }
3194
3195 void XGUI_Workshop::deactivateCurrentSelector()
3196 {
3197   myActiveControlMgr->deactivateSelector(myActiveControlMgr->activeSelector());
3198 }
3199
3200 void XGUI_Workshop::changeIsoLines(const QObjectPtrList& theObjects)
3201 {
3202   if (theObjects.isEmpty())
3203     return;
3204
3205   QList<ResultPtr> aResultList;
3206   ResultPtr aRes;
3207   foreach(ObjectPtr aObj, theObjects) {
3208     aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
3209     if (aRes.get())
3210       aResultList.append(aRes);
3211   }
3212
3213   std::vector<int> aValues;
3214   bool isVisible;
3215   if (aResultList.size() == 1) {
3216     ResultPtr aRes = aResultList.first();
3217     if (aRes.get())
3218       ModelAPI_Tools::getIsoLines(aRes, isVisible, aValues);
3219     else
3220       return;
3221   }
3222   if (aValues.size() == 0) {
3223     aValues.push_back(1);
3224     aValues.push_back(1);
3225   }
3226
3227   if (!abortAllOperations())
3228     return;
3229
3230   XGUI_PropertyDialog aDlg(desktop());
3231   aDlg.setWindowTitle(tr("Number of Iso-lines"));
3232
3233   QWidget* aIsosWgt = new QWidget(&aDlg);
3234   QFormLayout* aLayout = new QFormLayout(aIsosWgt);
3235   ModuleBase_Tools::adjustMargins(aLayout);
3236   aDlg.setContent(aIsosWgt);
3237
3238   QSpinBox* aUNb = new QSpinBox(&aDlg);
3239   aUNb->setValue(aValues[0]);
3240   aLayout->addRow("U:", aUNb);
3241
3242   QSpinBox* aVNb = new QSpinBox(&aDlg);
3243   aVNb->setValue(aValues[1]);
3244   aLayout->addRow("V:", aVNb);
3245
3246   if (aDlg.exec() == QDialog::Accepted) {
3247     SessionPtr aMgr = ModelAPI_Session::get();
3248     QString aDescription = contextMenuMgr()->action("ISOLINES_CMD")->text();
3249     aMgr->startOperation(aDescription.toStdString());
3250
3251     aValues[0] = aUNb->value();
3252     aValues[1] = aVNb->value();
3253     foreach(ResultPtr aRes, aResultList) {
3254       ModelAPI_Tools::setIsoLines(aRes, aValues);
3255     }
3256     mySelector->clearSelection();
3257     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
3258     aMgr->finishOperation();
3259     updateCommandStatus();
3260   }
3261 }