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