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