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