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