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