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