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