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