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