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