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