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