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