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