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