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