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