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