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