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