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