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