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