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