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