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