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