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