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