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