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