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