Salome HOME
bff02679288cdb7013a859d500930f6b0ebeedb9
[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::selectionFilters(SelectMgr_ListOfFilter& theSelectionFilters)
691 {
692   module()->selectionFilters(theSelectionFilters);
693 }
694
695 //******************************************************
696 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
697 {
698   setGrantedFeatures(theOperation);
699
700   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
701     fillPropertyPanel(theOperation);
702     connectToPropertyPanel(true);
703   }
704   updateCommandStatus();
705
706   myModule->operationResumed(theOperation);
707 }
708
709 //******************************************************
710 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
711 {
712   updateCommandStatus();
713
714   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
715                                                                         (theOperation);
716   if (!aFOperation)
717     return;
718
719   ModuleBase_ISelection* aSel = mySelector->selection();
720   QObjectPtrList aObj = aSel->selectedPresentations();
721   //!< No need for property panel
722   hidePanel(myPropertyPanel);
723   myPropertyPanel->cleanContent();
724
725   connectToPropertyPanel(false);
726   myModule->operationStopped(aFOperation);
727
728   // the deactivated objects of the current operation should be activated back.
729   // They were deactivated on operation start or an object redisplay
730   QObjectPtrList anObjects;
731   FeaturePtr aFeature = aFOperation->feature();
732   if (aFeature.get()) { // feature may be not created (plugin load fail)
733     if (myDisplayer->isVisible(aFeature) && !selectionActivate()->isActive(aFeature))
734       anObjects.append(aFeature);
735     std::list<ResultPtr> aResults;
736     ModelAPI_Tools::allResults(aFeature, aResults);
737     std::list<ResultPtr>::const_iterator aIt;
738     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
739       ResultPtr anObject = *aIt;
740       if (myDisplayer->isVisible(anObject) && !selectionActivate()->isActive(anObject)) {
741         anObjects.append(anObject);
742       }
743     }
744   }
745   activateObjectsSelection(anObjects);
746 }
747
748 //******************************************************
749 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
750 {
751   myModule->operationCommitted(theOperation);
752 }
753
754 //******************************************************
755 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
756 {
757   myModule->operationAborted(theOperation);
758 }
759
760 //******************************************************
761 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
762 {
763   ModuleBase_OperationFeature* aFOperation =
764     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
765   if (!aFOperation)
766     return;
767
768   QStringList aGrantedIds;
769   if (isSalomeMode()) {
770     const std::shared_ptr<Config_FeatureMessage>& anInfo =
771                          mySalomeConnector->featureInfo(theOperation->id());
772     if (anInfo.get())
773       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
774                                    .split(" ", QString::SkipEmptyParts);
775   }
776   else
777     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
778
779   ModuleBase_IModule* aModule = module();
780   if (aModule)
781     aModule->grantedOperationIds(theOperation, aGrantedIds);
782
783   aFOperation->setGrantedOperationIds(aGrantedIds);
784 }
785
786 //******************************************************
787 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
788 {
789   QApplication::restoreOverrideCursor();
790   SessionPtr aMgr = ModelAPI_Session::get();
791
792   std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
793   std::list<DocumentPtr>::const_iterator aIt;
794   for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
795     std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
796     (*aIt)->storeNodesState(aState);
797   }
798
799   aMgr->save(theName.toLatin1().constData(), theFileNames);
800
801   QApplication::restoreOverrideCursor();
802 }
803
804 //******************************************************
805 bool XGUI_Workshop::abortAllOperations()
806 {
807   return myOperationMgr->abortAllOperations();
808 }
809
810 //******************************************************
811 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
812 {
813   setGrantedFeatures(theOperation);
814   if (!theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
815     updateCommandStatus();
816   }
817   else {
818     myModule->operationStarted(theOperation);
819   }
820 }
821
822 //******************************************************
823 void XGUI_Workshop::onOpen()
824 {
825   if(!abortAllOperations())
826     return;
827   //save current file before close if modified
828   SessionPtr aSession = ModelAPI_Session::get();
829   if (aSession->isModified()) {
830     //TODO(sbh): re-launch the app?
831     int anAnswer = QMessageBox::question(
832         desktop(), tr("Save current file"),
833         tr("The document is modified, save before opening another?"),
834         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
835     if (anAnswer == QMessageBox::Save) {
836       onSave();
837     } else if (anAnswer == QMessageBox::Cancel) {
838       return;
839     }
840     myCurrentDir = "";
841   }
842
843   //show file dialog, check if readable and open
844   QString aDirectory = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
845   openDirectory(aDirectory);
846 }
847
848 //******************************************************
849 void XGUI_Workshop::openDirectory(const QString& theDirectory)
850 {
851   myCurrentDir = theDirectory;
852   if (myCurrentDir.isEmpty())
853     return;
854
855   QFileInfo aFileInfo(myCurrentDir);
856   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
857     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
858     myCurrentDir = "";
859     return;
860   }
861
862   QApplication::setOverrideCursor(Qt::WaitCursor);
863   module()->closeDocument();
864   SessionPtr aSession = ModelAPI_Session::get();
865   aSession->closeAll();
866   aSession->load(myCurrentDir.toLatin1().constData());
867   myObjectBrowser->rebuildDataTree();
868
869   // Open first level of data tree
870   DocumentPtr aRootDoc = aSession->moduleDocument();
871   std::list<bool> aStates;
872   aRootDoc->restoreNodesState(aStates);
873   myObjectBrowser->setStateForDoc(aRootDoc, aStates);
874
875   updateCommandStatus();
876 #ifndef HAVE_SALOME
877   myMainWindow->setCurrentDir(myCurrentDir, true);
878 #endif
879
880 #ifdef _DEBUG
881   bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
882   if (aNewPart) {
883
884     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
885     int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
886     if (aSize > 0 ) {
887       ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), 0);
888       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
889       if (aPart.get())
890         aPart->activate();
891     }
892   }
893 #endif
894
895   QApplication::restoreOverrideCursor();
896 }
897
898 //******************************************************
899 void XGUI_Workshop::onNew()
900 {
901   QApplication::setOverrideCursor(Qt::WaitCursor);
902   if (objectBrowser() == 0) {
903     createDockWidgets();
904     mySelector->connectViewers();
905   }
906   myViewerProxy->connectToViewer();
907   showObjectBrowser();
908 #ifndef HAVE_SALOME
909   myMainWindow->showPythonConsole();
910   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
911   aWnd->showMaximized();
912   updateCommandStatus();
913 #endif
914   myContextMenuMgr->connectViewer();
915   QApplication::restoreOverrideCursor();
916 }
917
918 #ifndef HAVE_SALOME
919 //******************************************************
920 void XGUI_Workshop::onExit()
921 {
922   SessionPtr aMgr = ModelAPI_Session::get();
923   if (aMgr->isModified()) {
924     int anAnswer = QMessageBox::question(
925         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
926         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
927     if (anAnswer == QMessageBox::Save) {
928       bool saved = onSave();
929       if (!saved) {
930         return;
931       }
932     } else if (anAnswer == QMessageBox::Cancel) {
933       return;
934     }
935   }
936   qApp->exit();
937 }
938
939 //******************************************************
940 void XGUI_Workshop::onPreferences()
941 {
942   ModuleBase_Prefs aModif;
943   ModuleBase_Preferences::editPreferences(aModif);
944   if (aModif.size() > 0) {
945     QString aSection;
946     foreach (ModuleBase_Pref aPref, aModif)
947     {
948       aSection = aPref.first;
949       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
950         myMainWindow->viewer()->updateFromResources();
951       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
952         myMainWindow->menuObject()->updateFromResources();
953       }
954     }
955     displayer()->redisplayObjects();
956   }
957 }
958 #endif
959
960 //******************************************************
961 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
962 {
963   XGUI_Displayer* aDisplayer = displayer();
964   if (aDisplayer)
965     aDisplayer->displayTrihedron(theState);
966 }
967
968 //******************************************************
969 bool XGUI_Workshop::onSave()
970 {
971   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
972     return false;
973   if (myCurrentDir.isEmpty()) {
974     return onSaveAs();
975   }
976   std::list<std::string> aFiles;
977   saveDocument(myCurrentDir, aFiles);
978   updateCommandStatus();
979 #ifndef HAVE_SALOME
980     myMainWindow->setModifiedState(false);
981 #endif
982   return true;
983 }
984
985 //******************************************************
986 bool XGUI_Workshop::onSaveAs()
987 {
988   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
989     return false;
990   QFileDialog dialog(desktop());
991   dialog.setWindowTitle(tr("Select directory to save files..."));
992   dialog.setFileMode(QFileDialog::Directory);
993   dialog.setFilter(QDir::AllDirs);
994   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
995   dialog.setViewMode(QFileDialog::Detail);
996
997   if (!dialog.exec()) {
998     return false;
999   }
1000
1001   QString aTempDir = dialog.selectedFiles().first();
1002   QDir aDir(aTempDir);
1003   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
1004     int answer = QMessageBox::question(
1005         desktop(),
1006         // Title of the dialog which asks user if he wants to save study
1007         // in existing non-empty folder
1008         tr("Save"),
1009         tr("The directory already contains some files, save anyway?"),
1010         QMessageBox::Save | QMessageBox::Cancel);
1011     if (answer == QMessageBox::Cancel) {
1012       return false;
1013     }
1014   }
1015   myCurrentDir = aTempDir;
1016 #ifndef HAVE_SALOME
1017     myMainWindow->setCurrentDir(myCurrentDir, false);
1018     myMainWindow->setModifiedState(false);
1019 #endif
1020   return onSave();
1021 }
1022
1023 //******************************************************
1024 void XGUI_Workshop::onUndo(int theTimes)
1025 {
1026   processUndoRedo(ActionUndo, theTimes);
1027 }
1028
1029 //******************************************************
1030 void XGUI_Workshop::onRedo(int theTimes)
1031 {
1032   processUndoRedo(ActionRedo, theTimes);
1033 }
1034
1035 //******************************************************
1036 void XGUI_Workshop::processUndoRedo(const ModuleBase_ActionType theActionType, int theTimes)
1037 {
1038   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1039   if (anActiveWidget) {
1040     ActionIntParamPtr aParam(new ModuleBase_ActionIntParameter(theTimes));
1041     if (anActiveWidget->processAction(theActionType, aParam))
1042       return;
1043   }
1044   // the viewer update should be blocked in order to avoid the features blinking. For the created
1045   // feature a results are created, the flush of the created signal caused the viewer redisplay for
1046   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1047   // until redo of all possible objects happens
1048   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1049
1050   SessionPtr aMgr = ModelAPI_Session::get();
1051   if (aMgr->isOperation()) {
1052     XGUI_OperationMgr* aOpMgr = operationMgr();
1053     /// this is important for nested operations
1054     /// when sketch operation is active, this condition is false and
1055     /// the sketch operation is not aborted
1056     if (aOpMgr->canStopOperation(aOpMgr->currentOperation()))
1057       aOpMgr->abortOperation(aOpMgr->currentOperation());
1058     else
1059       return;
1060   }
1061   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1062   std::list<std::string> anActionList = theActionType == ActionUndo ? aMgr->undoList()
1063     : aMgr->redoList();
1064   std::list<std::string>::const_iterator aIt = anActionList.cbegin();
1065   for (int i = 0; (i < theTimes) && (aIt != anActionList.cend()); ++i, ++aIt) {
1066     if (theActionType == ActionUndo)
1067       aMgr->undo();
1068     else
1069       aMgr->redo();
1070
1071     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1072       myObjectBrowser->rebuildDataTree();
1073   }
1074   operationMgr()->updateApplyOfOperations();
1075   facesPanel()->reset(true);
1076   updateCommandStatus();
1077
1078   // unblock the viewer update functionality and make update on purpose
1079   if (theActionType == ActionRedo) {
1080     myDisplayer->enableUpdateViewer(isUpdateEnabled);
1081     myDisplayer->updateViewer();
1082   }
1083 }
1084
1085 //******************************************************
1086 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1087 {
1088   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1089   //ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1090   //if (anOperation) {
1091   //  ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1092   //  if (aPanel)
1093   //    anActiveWidget = aPanel->activeWidget();
1094   //}
1095   if (anActiveWidget)
1096     operationMgr()->onValidateOperation();
1097
1098   myModule->widgetStateChanged(thePreviousState);
1099 }
1100
1101 //******************************************************
1102 void XGUI_Workshop::onValuesChanged()
1103 {
1104   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1105   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1106     return;
1107
1108   ModuleBase_ModelWidget* anActiveWidget = 0;
1109   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1110   if (anOperation) {
1111     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1112     if (aPanel)
1113       anActiveWidget = aPanel->activeWidget();
1114   }
1115   if (anActiveWidget) {
1116     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1117                                                                            (anActiveWidget);
1118     if (aWidgetValidated)
1119       aWidgetValidated->clearValidatedCash();
1120   }
1121 }
1122
1123 //******************************************************
1124 void XGUI_Workshop::onWidgetObjectUpdated()
1125 {
1126   operationMgr()->onValidateOperation();
1127 }
1128
1129 //******************************************************
1130 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1131 {
1132   QString libName = QString::fromStdString(library(theModule.toStdString()));
1133   if (libName.isEmpty()) {
1134     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1135     return 0;
1136   }
1137
1138   QString err;
1139   CREATE_FUNC crtInst = 0;
1140
1141 #ifdef WIN32
1142   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1143   if (!modLib) {
1144     LPVOID lpMsgBuf;
1145     ::FormatMessage(
1146         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1147         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1148     QString aMsg((char*) &lpMsgBuf);
1149     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1150     ::LocalFree(lpMsgBuf);
1151   } else {
1152     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1153     if (!crtInst) {
1154       LPVOID lpMsgBuf;
1155       ::FormatMessage(
1156           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1157               | FORMAT_MESSAGE_IGNORE_INSERTS,
1158           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1159       QString aMsg((char*) &lpMsgBuf);
1160       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1161       ::LocalFree(lpMsgBuf);
1162     }
1163   }
1164 #else
1165   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1166   if ( !modLib ) {
1167     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1168   } else {
1169     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1170     if ( !crtInst ) {
1171       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1172     }
1173   }
1174 #endif
1175
1176   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1177
1178   if (!err.isEmpty()) {
1179     if (desktop()) {
1180       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1181     } else {
1182       qWarning(qPrintable(err));
1183     }
1184   }
1185   return aModule;
1186 }
1187
1188 //******************************************************
1189 bool XGUI_Workshop::createModule()
1190 {
1191   Config_ModuleReader aModuleReader;
1192   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1193   myModule = loadModule(moduleName);
1194   if (!myModule)
1195     return false;
1196
1197   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1198   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1199   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1200   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1201
1202   myModule->createFeatures();
1203 #ifdef HAVE_SALOME
1204   salomeConnector()->createFeatureActions();
1205 #endif
1206   //myActionsMgr->update();
1207   return true;
1208 }
1209
1210 //******************************************************
1211 void XGUI_Workshop::updateCommandStatus()
1212 {
1213   QList<QAction*> aCommands;
1214 #ifdef HAVE_SALOME
1215     aCommands = salomeConnector()->commandList();
1216 #else
1217     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1218     foreach (AppElements_Command* aCmd, aMenuBar->features())
1219       aCommands.append(aCmd);
1220 #endif
1221   SessionPtr aMgr = ModelAPI_Session::get();
1222   if (aMgr->hasModuleDocument()) {
1223     foreach(QAction* aCmd, aCommands) {
1224       QString aId = aCmd->data().toString();
1225       if (aId == "UNDO_CMD") {
1226         bool isActionEnabled = false;
1227         // if ultimate is true -> using result of operation only, or using OR combination
1228         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1229         if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled))
1230           aCmd->setEnabled(isActionEnabled);
1231         else
1232           aCmd->setEnabled(myModule->canUndo());
1233       }
1234       else if (aId == "REDO_CMD") {
1235         bool isActionEnabled = false;
1236         // if ultimate is true -> using result of operation only, or using OR combination
1237         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1238         if (anActiveWidget && anActiveWidget->canProcessAction(ActionRedo, isActionEnabled))
1239           aCmd->setEnabled(isActionEnabled);
1240         else
1241           aCmd->setEnabled(myModule->canRedo());
1242       }
1243       else
1244         // Enable all commands
1245         aCmd->setEnabled(true);
1246     }
1247     updateHistory();
1248   } else {
1249     foreach(QAction* aCmd, aCommands) {
1250       QString aId = aCmd->data().toString();
1251       if (aId == "NEW_CMD")
1252         aCmd->setEnabled(true);
1253       else if (aId == "EXIT_CMD")
1254         aCmd->setEnabled(true);
1255       else
1256         aCmd->setEnabled(false);
1257     }
1258   }
1259   myActionsMgr->updateCommandsStatus();
1260   emit commandStatusUpdated();
1261 }
1262
1263 //******************************************************
1264 void XGUI_Workshop::updateHistory()
1265 {
1266   bool isActionEnabled = false;
1267   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1268   QList<ActionInfo> aUndoRes;
1269   QList<ActionInfo> aRedoRes;
1270   if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled)) {
1271     aUndoRes = anActiveWidget->actionsList(ActionUndo);
1272     aRedoRes = anActiveWidget->actionsList(ActionRedo);
1273   } else {
1274     std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1275     aUndoRes = processHistoryList(aUndoList);
1276
1277     std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1278     aRedoRes = processHistoryList(aRedoList);
1279   }
1280   emit updateUndoHistory(aUndoRes);
1281   emit updateRedoHistory(aRedoRes);
1282 }
1283
1284 //******************************************************
1285 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1286 {
1287   QDockWidget* aObjDock = new QDockWidget(theParent);
1288   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1289                             Qt::RightDockWidgetArea |
1290                             Qt::BottomDockWidgetArea);
1291   aObjDock->setWindowTitle(tr("Object browser"));
1292   aObjDock->setStyleSheet(
1293       "::title { position: relative; padding-left: 5px; text-align: left center }");
1294   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1295   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1296   myModule->customizeObjectBrowser(myObjectBrowser);
1297   aObjDock->setWidget(myObjectBrowser);
1298
1299   myContextMenuMgr->connectObjectBrowser();
1300   return aObjDock;
1301 }
1302
1303 //******************************************************
1304 /*
1305  * Creates dock widgets, places them in corresponding area
1306  * and tabifies if necessary.
1307  */
1308 void XGUI_Workshop::createDockWidgets()
1309 {
1310   QMainWindow* aDesktop = desktop();
1311   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1312   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1313   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1314   myActiveControlMgr->addSelector(new XGUI_PropertyPanelSelector(myPropertyPanel));
1315
1316   myPropertyPanel->setupActions(myActionsMgr);
1317   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1318                                    Qt::RightDockWidgetArea |
1319                                    Qt::BottomDockWidgetArea);
1320   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1321   hidePanel(myPropertyPanel);  ///<! Invisible by default
1322
1323   myFacesPanel = new XGUI_FacesPanel(aDesktop, myModuleConnector);
1324   myActiveControlMgr->addSelector(new XGUI_FacesPanelSelector(myFacesPanel));
1325   myFacesPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1326                                 Qt::RightDockWidgetArea |
1327                                 Qt::BottomDockWidgetArea);
1328   connect(myFacesPanel, SIGNAL(closed()), myFacesPanel, SLOT(onClosed()));
1329
1330   aDesktop->addDockWidget(
1331 #ifdef HAVE_SALOME
1332     Qt::RightDockWidgetArea,
1333 #else
1334     Qt::LeftDockWidgetArea,
1335 #endif
1336     myFacesPanel);
1337   hidePanel(myFacesPanel);  ///<! Invisible by default
1338
1339 #ifdef _DEBUG
1340   bool aShowOnTheRight = Config_PropManager::boolean("Plugins", "show_hide_faces");
1341   if (aShowOnTheRight) {
1342     aDesktop->addDockWidget(Qt::RightDockWidgetArea, myFacesPanel);
1343     showPanel(myFacesPanel);
1344   }
1345 #endif
1346   hideObjectBrowser();
1347
1348 #ifndef HAVE_SALOME
1349 #ifdef _DEBUG
1350   if (!aShowOnTheRight)
1351   {
1352 #endif // _DEBUG
1353   aDesktop->tabifyDockWidget(myFacesPanel, aObjDock);
1354 #ifdef _DEBUG
1355   }
1356 #endif // _DEBUG
1357
1358 #endif // HAVE_SALOME
1359
1360   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1361   myPropertyPanel->installEventFilter(myOperationMgr);
1362
1363   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1364   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1365
1366   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1367   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1368
1369   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1370   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1371
1372   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1373           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1374   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1375           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1376 }
1377
1378 //******************************************************
1379 void XGUI_Workshop::showPanel(QDockWidget* theDockWidget)
1380 {
1381   if (theDockWidget == myPropertyPanel) {
1382     QAction* aViewAct = myPropertyPanel->toggleViewAction();
1383     ///<! Restore ability to close panel from the window's menu
1384     aViewAct->setEnabled(true);
1385   }
1386   theDockWidget->show();
1387   theDockWidget->raise();
1388
1389   // The next code is necessary to made the property panel the active window
1390   // in order to operation manager could process key events of the panel.
1391   // otherwise they are ignored. It happens only if the same(activateWindow) is
1392   // not happened by property panel activation(e.g. resume operation of Sketch)
1393   ModuleBase_Tools::setFocus(theDockWidget, "XGUI_Workshop::showPanel()");
1394 }
1395
1396 //******************************************************
1397 void XGUI_Workshop::hidePanel(QDockWidget* theDockWidget)
1398 {
1399   if (theDockWidget && theDockWidget == myPropertyPanel) {
1400     QAction* aViewAct = theDockWidget->toggleViewAction();
1401     ///<! Do not allow to show empty property panel
1402     aViewAct->setEnabled(false);
1403   }
1404   theDockWidget->hide();
1405
1406   // the property panel is active window of the desktop, when it is
1407   // hidden, it is undefined which window becomes active. By this reason
1408   // it is defined to perform the desktop as the active window.
1409   // in SALOME mode, workstack made the PyConsole the active window,
1410   // set the focus on it. As a result, shortcuts of the application, like
1411   // are processed by this console. For example Undo actions.
1412   // It is possible that this code is to be moved to SHAPER package
1413   QMainWindow* aDesktop = desktop();
1414   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::hidePanel()");
1415 }
1416
1417 //******************************************************
1418 void XGUI_Workshop::showObjectBrowser()
1419 {
1420   if (!isSalomeMode())
1421     myObjectBrowser->parentWidget()->show();
1422 }
1423
1424 //******************************************************
1425 void XGUI_Workshop::hideObjectBrowser()
1426 {
1427   if (!isSalomeMode())
1428     myObjectBrowser->parentWidget()->hide();
1429 }
1430
1431 //******************************************************
1432 void XGUI_Workshop::salomeViewerSelectionChanged()
1433 {
1434   emit salomeViewerSelection();
1435 }
1436
1437 //**************************************************************
1438 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1439 {
1440   return mySalomeConnector->viewer();
1441 }
1442
1443 //**************************************************************
1444 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1445 {
1446   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1447   if (theId == "DELETE_CMD")
1448     deleteObjects();
1449   else if (theId == "CLEAN_HISTORY_CMD")
1450     cleanHistory();
1451   else if (theId == "MOVE_CMD")
1452     moveObjects();
1453   else if (theId == "COLOR_CMD")
1454     changeColor(aObjects);
1455   else if (theId == "DEFLECTION_CMD")
1456     changeDeflection(aObjects);
1457 #ifdef USE_TRANSPARENCY
1458   else if (theId == "TRANSPARENCY_CMD")
1459     changeTransparency(aObjects);
1460 #endif
1461   else if (theId == "SHOW_CMD") {
1462     showObjects(aObjects, true);
1463     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1464     updateCommandStatus();
1465   }
1466   else if (theId == "HIDE_CMD") {
1467     showObjects(aObjects, false);
1468     updateCommandStatus();
1469   }
1470   else if (theId == "SHOW_ONLY_CMD") {
1471     showOnlyObjects(aObjects);
1472     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1473     updateCommandStatus();
1474   }
1475   else if (theId == "SHADING_CMD")
1476     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1477   else if (theId == "WIREFRAME_CMD")
1478     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1479   else if (theId == "HIDEALL_CMD") {
1480     QObjectPtrList aList = myDisplayer->displayedObjects();
1481     foreach (ObjectPtr aObj, aList) {
1482       if (module()->canEraseObject(aObj))
1483         aObj->setDisplayed(false);
1484     }
1485     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1486 #ifdef HAVE_SALOME
1487     //issue #2159 Hide all incomplete behavior
1488     viewer()->eraseAll();
1489 #endif
1490     updateCommandStatus();
1491     // Necessary for update icons in ObjectBrowser on Linux
1492     myObjectBrowser->updateAllIndexes();
1493   } else if (theId == "SELECT_VERTEX_CMD") {
1494     setViewerSelectionMode(TopAbs_VERTEX);
1495   } else if (theId == "SELECT_EDGE_CMD") {
1496     setViewerSelectionMode(TopAbs_EDGE);
1497   } else if (theId == "SELECT_FACE_CMD") {
1498     setViewerSelectionMode(TopAbs_FACE);
1499   } else if (theId == "INSERT_FOLDER_CMD") {
1500     insertFeatureFolder();
1501   } else if (theId == "ADD_TO_FOLDER_BEFORE_CMD") {
1502     insertToFolder(true);
1503   } else if (theId == "ADD_TO_FOLDER_AFTER_CMD") {
1504     insertToFolder(false);
1505   } else if (theId == "ADD_OUT_FOLDER_BEFORE_CMD") {
1506     moveOutFolder(true);
1507   } else if (theId == "ADD_OUT_FOLDER_AFTER_CMD") {
1508     moveOutFolder(false);
1509   } else if (theId == "SELECT_RESULT_CMD") {
1510     //setViewerSelectionMode(-1);
1511     //IMP: an attempt to use result selection with other selection modes
1512     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1513     setViewerSelectionMode(TopAbs_COMPSOLID);
1514   } else if (theId == "SHOW_RESULTS_CMD") {
1515     highlightResults(aObjects);
1516   } else if (theId == "SHOW_FEATURE_CMD") {
1517     highlightFeature(aObjects);
1518   }
1519 #ifdef TINSPECTOR
1520   else if (theId == "TINSPECTOR_VIEW") {
1521     Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1522     if (!anApplication.IsNull())
1523     {
1524       if (!MyTCommunicator)
1525       {
1526         MyTCommunicator = new TInspector_Communicator();
1527
1528         NCollection_List<Handle(Standard_Transient)> aParameters;
1529         aParameters.Append(anApplication);
1530         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1531         if (!aContext.IsNull())
1532           aParameters.Append(aContext);
1533
1534 #ifdef DEBUG_WITH_MESSAGE_REPORT
1535         Handle(Message_Report) aContextReport = aContext->GetReport();
1536         aContext->SetReportActive (Standard_True);
1537         aContextReport->SetLimit (1000);
1538         if (!aContextReport.IsNull())
1539           aParameters.Append(aContextReport);
1540 #endif
1541         MyVCallBack = new VInspector_CallBack();
1542         myDisplayer->setCallBack(MyVCallBack);
1543         #ifndef HAVE_SALOME
1544         AppElements_Viewer* aViewer = mainWindow()->viewer();
1545         if (aViewer)
1546           aViewer->setCallBack(MyVCallBack);
1547         #endif
1548         aParameters.Append(MyVCallBack);
1549
1550         MyTCommunicator->RegisterPlugin("TKDFBrowser");
1551         MyTCommunicator->RegisterPlugin("TKShapeView");
1552         MyTCommunicator->RegisterPlugin("TKVInspector");
1553 #ifdef DEBUG_WITH_MESSAGE_REPORT
1554         MyTCommunicator->RegisterPlugin("TKMessageView");
1555 #endif
1556         MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1557         //MyTCommunicator->RegisterPlugin("TKSMBrowser"); // custom plugin to view ModelAPI
1558
1559         MyTCommunicator->Init(aParameters);
1560         MyTCommunicator->Activate("TKSMBrowser"); // to have button in TInspector
1561 #ifndef DEBUG_WITH_MESSAGE_REPORT
1562         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1563 #endif
1564         MyTCommunicator->Activate("TKDFBrowser");
1565
1566 #ifdef DEBUG_WITH_MESSAGE_REPORT
1567         MyTCommunicator->Activate("TKMessageView"); // temporary
1568         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1569 #endif
1570       }
1571       MyTCommunicator->SetVisible(true);
1572     }
1573   }
1574 #endif
1575 }
1576
1577 //**************************************************************
1578 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1579 {
1580   if (theMode == -1)
1581     myViewerSelMode.clear();
1582   else {
1583     if (myViewerSelMode.contains(theMode))
1584       myViewerSelMode.removeAll(theMode);
1585     else
1586       myViewerSelMode.append(theMode);
1587   }
1588   selectionActivate()->updateSelectionModes();
1589 }
1590
1591 //**************************************************************
1592 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1593 {
1594   QIntList aModes;
1595   module()->activeSelectionModes(aModes);
1596   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1597     aModes.append(myViewerSelMode);
1598   selectionActivate()->activateObjects(aModes, theList);
1599 }
1600
1601 //**************************************************************
1602 bool XGUI_Workshop::prepareForDisplay(const std::set<ObjectPtr>& theObjects) const
1603 {
1604   // generate container of objects taking into account sub elments of compsolid
1605   std::set<ObjectPtr> anAllProcessedObjects;
1606   for (std::set<ObjectPtr>::const_iterator anObjectsIt = theObjects.begin();
1607     anObjectsIt != theObjects.end(); anObjectsIt++) {
1608     ObjectPtr anObject = *anObjectsIt;
1609     ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(anObject);
1610     if (aCompRes.get()) {
1611       if (aCompRes->numberOfSubs(true) == 0)
1612         anAllProcessedObjects.insert(anObject);
1613       else {
1614         for (int i = 0; i < aCompRes->numberOfSubs(true); i++) {
1615           ResultPtr aSubRes = aCompRes->subResult(i, true);
1616           anAllProcessedObjects.insert(aCompRes->subResult(i, true));
1617         }
1618       }
1619     }
1620     else
1621       anAllProcessedObjects.insert(anObject);
1622   }
1623
1624   // find hidden objects in faces panel
1625   std::set<ObjectPtr> aHiddenObjects;
1626   QStringList aHiddenObjectNames;
1627   for (std::set<ObjectPtr>::const_iterator anObjectsIt = anAllProcessedObjects.begin();
1628        anObjectsIt != anAllProcessedObjects.end(); anObjectsIt++) {
1629     if (!facesPanel()->isObjectHiddenByPanel(*anObjectsIt))
1630       continue;
1631     aHiddenObjects.insert(*anObjectsIt);
1632     aHiddenObjectNames.append((*anObjectsIt)->data()->name().c_str());
1633   }
1634   if (aHiddenObjects.empty())
1635     return true;
1636
1637   int anAnswer = QMessageBox::question(
1638         desktop(), tr("Show object"),
1639         tr("'%1'\n are hidden by %2:\nRemove objects from the panel to be displayed?")
1640         .arg(aHiddenObjectNames.join(',')).arg(facesPanel()->windowTitle(),
1641         QMessageBox::Yes | QMessageBox::No, QMessageBox::No));
1642
1643   bool aToBeDisplayed = anAnswer == QMessageBox::Yes;
1644   if (aToBeDisplayed)
1645     facesPanel()->restoreObjects(aHiddenObjects);
1646
1647   return aToBeDisplayed;
1648 }
1649
1650 //**************************************************************
1651 void XGUI_Workshop::deleteObjects()
1652 {
1653   ModuleBase_IModule* aModule = module();
1654   // allow the module to delete objects, do nothing if it has succeed
1655   if (aModule->deleteObjects()) {
1656     updateCommandStatus();
1657     return;
1658   }
1659
1660   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1661   if (!abortAllOperations())
1662     return;
1663
1664   bool hasResult = false;
1665   bool hasFeature = false;
1666   bool hasParameter = false;
1667   bool hasCompositeOwner = false;
1668   bool hasResultInHistory = false;
1669   bool hasFolder = false;
1670   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1671                                  hasResultInHistory, hasFolder);
1672   if (!(hasFeature || hasParameter || hasFolder))
1673     return;
1674
1675   // delete objects
1676   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1677   std::set<FeaturePtr> aFeatures;
1678   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1679   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1680
1681   std::set<FolderPtr> aFolders;
1682   ModuleBase_Tools::convertToFolders(anObjects, aFolders);
1683
1684   bool aDone = false;
1685   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1686   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1687   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1688
1689   operationMgr()->startOperation(anOpAction);
1690
1691   std::set<FeaturePtr> aFeatureRefsToDelete;
1692   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1693     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1694     // It is necessary to clear selection in order to avoid selection changed event during
1695     // deletion and negative consequences connected with processing of already deleted items
1696     mySelector->clearSelection();
1697
1698     if (!aFeatureRefsToDelete.empty())
1699       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1700     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1701   }
1702   if (aFolders.size() > 0) {
1703     std::set<FolderPtr>::const_iterator anIt = aFolders.begin(),
1704                                          aLast = aFolders.end();
1705     for (; anIt != aLast; anIt++) {
1706       FolderPtr aFolder = *anIt;
1707       if (aFolder.get()) {
1708         DocumentPtr aDoc = aFolder->document();
1709         aDoc->removeFolder(aFolder);
1710       }
1711     }
1712   }
1713
1714   if (aDone)
1715     operationMgr()->commitOperation();
1716   else
1717     operationMgr()->abortOperation(operationMgr()->currentOperation());
1718 }
1719
1720 //**************************************************************
1721 void addRefsToFeature(const FeaturePtr& theFeature,
1722                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1723                       std::set<FeaturePtr>& theReferences)
1724 {
1725   //if (theReferences.find(theFeature) != theReferences.end())
1726   //  return;
1727   if (theMainList.find(theFeature) == theMainList.end())
1728     return; // this feature is not in the selection list, so exists without references to it
1729   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1730
1731   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1732                                        aLast = aMainReferences.end();
1733   for (; anIt != aLast; anIt++) {
1734     FeaturePtr aRefFeature = *anIt;
1735     if (theReferences.find(aRefFeature) == theReferences.end())
1736       theReferences.insert(aRefFeature);
1737     addRefsToFeature(aRefFeature, theMainList, theReferences);
1738   }
1739 }
1740
1741 //**************************************************************
1742 void XGUI_Workshop::cleanHistory()
1743 {
1744   if (!abortAllOperations())
1745     return;
1746
1747   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1748   std::set<FeaturePtr> aFeatures;
1749   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1750
1751 #ifdef DEBUG_CLEAN_HISTORY
1752   QStringList anInfo;
1753   std::set<FeaturePtr>::const_iterator aFIt;
1754   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1755     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1756     anInfo.append(aFeature->name().c_str());
1757   }
1758   QString anInfoStr = anInfo.join(";\t");
1759   qDebug(QString("cleanHistory for: [%1] - %2").
1760     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1761 #endif
1762
1763   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1764   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1765   // find for each object whether all reference values are in the map as key, that means that there
1766   // is no other reference in the model to this object, so it might be removed by cleaning history
1767   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - cann't be deleted, dependency to bool_1
1768   // ext_1(bool_1, sk_3)  - cann't be deleted, dependency to bool_1
1769   // vertex_1()
1770   // sk_2(ext_2) + (bool_1)  - cann't be deleted, dependency to bool_1
1771   // ext_2(bool_1)  - cann't be deleted, dependency to bool_1
1772   // sk_3()
1773   // Information: bool_1 is not selected
1774   std::set<FeaturePtr> anUnusedObjects;
1775   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1776                                                               aMainLast = aReferences.end();
1777   for (; aMainIt != aMainLast; aMainIt++) {
1778     FeaturePtr aMainListFeature = aMainIt->first;
1779     std::set<FeaturePtr> aMainRefList = aMainIt->second;
1780     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
1781                                                   aRefLast = aMainRefList.end();
1782     bool aFeatureOutOfTheList = false;
1783     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1784       FeaturePtr aRefFeature = *aRefIt;
1785       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1786     }
1787     if (!aFeatureOutOfTheList)
1788       anUnusedObjects.insert(aMainListFeature);
1789   }
1790
1791 #ifdef DEBUG_CLEAN_HISTORY
1792   anInfo.clear();
1793   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1794     FeaturePtr aFeature = *aFIt;
1795     anInfo.append(aFeature->name().c_str());
1796   }
1797   qDebug(QString("unused objects: [%1] - %2").
1798     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1799 #endif
1800
1801   // warn about the references remove, break the delete operation if the user chose it
1802   if (!anUnusedObjects.empty()) {
1803     QStringList aNames;
1804     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1805       aNames.append(aFeature->name().c_str());
1806     }
1807     aNames.sort();
1808     QString anUnusedNames = aNames.join(", ");
1809
1810     QString anActionId = "CLEAN_HISTORY_CMD";
1811     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1812
1813     QMessageBox aMessageBox(desktop());
1814     aMessageBox.setWindowTitle(aDescription);
1815     aMessageBox.setIcon(QMessageBox::Warning);
1816     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1817     aMessageBox.setDefaultButton(QMessageBox::No);
1818
1819     const char* aKeyStr = "Unused features are the following: "
1820                           "%1.\nThese features will be deleted.\nWould you like to continue?";
1821     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
1822     aMessageBox.setText(aText);
1823     if (aMessageBox.exec() == QMessageBox::No)
1824       return;
1825
1826     // 1. start operation
1827     aDescription += "by deleting of " +
1828       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1829     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1830     operationMgr()->startOperation(anOpAction);
1831
1832     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1833     // It is necessary to clear selection in order to avoid selection changed event during
1834     // deletion and negative consequences connected with processing of already deleted items
1835     mySelector->clearSelection();
1836
1837     std::set<FeaturePtr> anIgnoredFeatures;
1838     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
1839       operationMgr()->commitOperation();
1840     }
1841     else {
1842       operationMgr()->abortOperation(operationMgr()->currentOperation());
1843     }
1844   }
1845   else {
1846     QString anActionId = "CLEAN_HISTORY_CMD";
1847     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1848
1849     QMessageBox aMessageBox(desktop());
1850     aMessageBox.setWindowTitle(aDescription);
1851     aMessageBox.setIcon(QMessageBox::Warning);
1852     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1853     aMessageBox.setDefaultButton(QMessageBox::No);
1854
1855     QString aText;
1856     aMessageBox.setStandardButtons(QMessageBox::Ok);
1857     aMessageBox.setDefaultButton(QMessageBox::Ok);
1858
1859     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1860     aMessageBox.setText(aText);
1861
1862     if (aMessageBox.exec() == QMessageBox::No)
1863       return;
1864   }
1865 }
1866
1867 //**************************************************************
1868 void XGUI_Workshop::moveObjects()
1869 {
1870   if (!abortAllOperations())
1871     return;
1872
1873   SessionPtr aMgr = ModelAPI_Session::get();
1874
1875   QString anActionId = "MOVE_CMD";
1876   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1877   aMgr->startOperation(aDescription.toStdString());
1878
1879   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1880   // It is necessary to clear selection in order to avoid selection changed event during
1881   // moving and negative consequences connected with processing of already moved items
1882   mySelector->clearSelection();
1883   // check whether the object can be moved. There should not be parts which are not loaded
1884   std::set<FeaturePtr> aFeatures;
1885   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1886   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
1887     return;
1888
1889   DocumentPtr anActiveDocument = aMgr->activeDocument();
1890   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1891   std::set<FeaturePtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1892   for (; anIt != aLast; anIt++) {
1893     FeaturePtr aFeature = *anIt;
1894     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
1895       continue;
1896
1897     anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1898     aCurrentFeature = anActiveDocument->currentFeature(true);
1899   }
1900   aMgr->finishOperation();
1901 }
1902
1903 //**************************************************************
1904 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
1905 {
1906   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1907   std::set<FeaturePtr> aFeatures;
1908   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
1909
1910   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
1911 }
1912
1913 //******************************************************
1914 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1915 {
1916   bool isFoundResultType = false;
1917   foreach(ObjectPtr anObj, theObjects)
1918   {
1919     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1920     if (aResult.get() == NULL)
1921       continue;
1922
1923     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1924     if (isFoundResultType)
1925       break;
1926   }
1927   return isFoundResultType;
1928 }
1929
1930 //**************************************************************
1931 // Returns the list of all features for theDocument and all features of
1932 // all nested parts.
1933 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1934 {
1935   std::list<FeaturePtr> aResultList;
1936   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1937   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1938     // The order of appending features of the part and the part itself is important
1939
1940     // Append features from a part feature
1941     std::list<ResultPtr> aResults;
1942     ModelAPI_Tools::allResults(aFeature, aResults);
1943     foreach (const ResultPtr& aResult, aResults) {
1944       ResultPartPtr aResultPart =
1945           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1946       if (aResultPart.get() && aResultPart->partDoc().get()) {
1947         // Recursion
1948         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1949         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1950       }
1951     }
1952
1953     aResultList.push_back(aFeature);
1954   }
1955   return aResultList;
1956 }
1957
1958 //**************************************************************
1959 // Returns the list of features placed between theObject and the current feature
1960 // in the same document. Excludes theObject, includes the current feature.
1961 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1962 {
1963   std::list<FeaturePtr> aResult;
1964   DocumentPtr aDocument = theObject->document();
1965   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1966   // find the object iterator
1967   std::list<FeaturePtr>::iterator aObjectIt =
1968     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1969   if (aObjectIt == anAllFeatures.end())
1970     return aResult;
1971   // find the current feature iterator
1972   std::list<FeaturePtr>::iterator aCurrentIt =
1973     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1974   if (aCurrentIt == anAllFeatures.end())
1975     return aResult;
1976   // check the right order
1977   if (std::distance(aObjectIt, anAllFeatures.end()) <=
1978       std::distance(aCurrentIt, anAllFeatures.end()))
1979     return aResult;
1980   // exclude the object
1981   std::advance(aObjectIt, 1);
1982   // include the current feature
1983   std::advance(aCurrentIt, 1);
1984   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1985 }
1986
1987 //******************************************************
1988 bool XGUI_Workshop::canMoveFeature()
1989 {
1990   QString anActionId = "MOVE_CMD";
1991
1992   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1993   QObjectPtrList aValidatedObjects;
1994   foreach (ObjectPtr aObject, aObjects) {
1995     if (!myModule->canApplyAction(aObject, anActionId))
1996       continue;
1997     // To be moved feature should be in active document
1998     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1999       continue;
2000     aValidatedObjects.append(aObject);
2001   }
2002   if (aValidatedObjects.size() != aObjects.size())
2003     aObjects = aValidatedObjects;
2004
2005   bool aCanMove = !aObjects.empty();
2006
2007   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
2008   for (; anIt != aLast && aCanMove; anIt++) {
2009     ObjectPtr aObject = *anIt;
2010     // 1. Get features placed between selected and current in the document
2011     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
2012     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
2013     if (aFeaturesBetween.empty())
2014       aCanMove = false;
2015     else {
2016       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
2017       // 2. Get all reference features to the selected object in the document
2018       std::set<FeaturePtr> aRefFeatures;
2019       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
2020
2021       if (aRefFeatures.empty())
2022         continue;
2023       else {
2024         // 3. Find any placed features in all reference features
2025         std::set<FeaturePtr> aIntersectionFeatures;
2026         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
2027                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
2028                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
2029         // 4. Return false if any reference feature is placed before current feature
2030         if (!aIntersectionFeatures.empty())
2031           aCanMove = false;
2032       }
2033     }
2034   }
2035   return aCanMove;
2036 }
2037
2038 //**************************************************************
2039 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
2040 {
2041   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
2042   if (!aCanBeShaded) {
2043     ResultCompSolidPtr aCompsolidResult =
2044                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
2045     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2046       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
2047         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
2048     }
2049   }
2050   return aCanBeShaded;
2051 }
2052
2053 //**************************************************************
2054 bool XGUI_Workshop::canChangeProperty(const QString& theActionName) const
2055 {
2056   if (theActionName == "COLOR_CMD" ||
2057       theActionName == "DEFLECTION_CMD"
2058 #ifdef USE_TRANSPARENCY
2059       || theActionName == "TRANSPARENCY_CMD"
2060 #endif
2061       ) {
2062     QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2063
2064     std::set<std::string> aTypes;
2065     aTypes.insert(ModelAPI_ResultGroup::group());
2066     aTypes.insert(ModelAPI_ResultConstruction::group());
2067     aTypes.insert(ModelAPI_ResultBody::group());
2068     aTypes.insert(ModelAPI_ResultPart::group());
2069
2070     return hasResults(aObjects, aTypes);
2071   }
2072   return false;
2073 }
2074
2075 //******************************************************
2076 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
2077 {
2078   if (!theResult.get())
2079     return;
2080
2081   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
2082   if (aColorAttr.get() != NULL) {
2083     if (!aColorAttr->size()) {
2084       aColorAttr->setSize(3);
2085     }
2086     aColorAttr->setValue(0, theColor[0]);
2087     aColorAttr->setValue(1, theColor[1]);
2088     aColorAttr->setValue(2, theColor[2]);
2089   }
2090 }
2091
2092 //**************************************************************
2093 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
2094 {
2095
2096   AttributeIntArrayPtr aColorAttr;
2097   // 1. find the current color of the object. This is a color of AIS presentation
2098   // The objects are iterated until a first valid color is found
2099   std::vector<int> aColor;
2100   foreach(ObjectPtr anObject, theObjects) {
2101     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2102     if (aResult.get()) {
2103       XGUI_CustomPrs::getResultColor(aResult, aColor);
2104     }
2105     else {
2106       // TODO: remove the obtaining a color from the AIS object
2107       // this does not happen never because:
2108       // 1. The color can be changed only on results
2109       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2110       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2111       if (anAISObj.get()) {
2112         aColor.resize(3);
2113         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
2114       }
2115     }
2116     if (!aColor.empty())
2117       break;
2118   }
2119   if (aColor.size() != 3)
2120     return;
2121
2122   if (!abortAllOperations())
2123   return;
2124   // 2. show the dialog to change the value
2125   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
2126   aDlg->setColor(aColor);
2127   aDlg->move(QCursor::pos());
2128   bool isDone = aDlg->exec() == QDialog::Accepted;
2129   if (!isDone)
2130     return;
2131
2132   bool isRandomColor = aDlg->isRandomColor();
2133
2134   // 3. abort the previous operation and start a new one
2135   SessionPtr aMgr = ModelAPI_Session::get();
2136   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
2137   aMgr->startOperation(aDescription.toStdString());
2138
2139   // 4. set the value to all results
2140   std::vector<int> aColorResult = aDlg->getColor();
2141   foreach(ObjectPtr anObj, theObjects) {
2142     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2143     if (aResult.get() != NULL) {
2144       ResultCompSolidPtr aCompsolidResult =
2145         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
2146       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2147         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2148           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult :
2149                                                                     aDlg->getRandomColor());
2150         }
2151       }
2152       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2153     }
2154   }
2155   aMgr->finishOperation();
2156   updateCommandStatus();
2157 }
2158
2159 //**************************************************************
2160 void setDeflection(ResultPtr theResult, const double theDeflection)
2161 {
2162   if (!theResult.get())
2163     return;
2164
2165   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
2166   if (aDeflectionAttr.get() != NULL)
2167     aDeflectionAttr->setValue(theDeflection);
2168 }
2169
2170 //**************************************************************
2171 void setTransparency(ResultPtr theResult, double theTransparency)
2172 {
2173   if (!theResult.get())
2174     return;
2175
2176   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
2177   if (anAttribute.get() != NULL)
2178     anAttribute->setValue(theTransparency);
2179 }
2180
2181 //**************************************************************
2182 void setTransparency(double theTransparency, const QObjectPtrList& theObjects)
2183 {
2184   foreach(ObjectPtr anObj, theObjects) {
2185     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2186     if (aResult.get() != NULL) {
2187       ResultCompSolidPtr aCompsolidResult =
2188         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
2189       if (aCompsolidResult.get() != NULL) { // change property for all sub-solids
2190         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2191           setTransparency(aCompsolidResult->subResult(i), theTransparency);
2192         }
2193       }
2194       setTransparency(aResult, theTransparency);
2195     }
2196   }
2197 }
2198
2199 //**************************************************************
2200 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
2201 {
2202   AttributeDoublePtr aDoubleAttr;
2203   // 1. find the current property of the object. This is a property of AIS presentation
2204   // The objects are iterated until a first valid property is found
2205   double aDeflection = -1;
2206   foreach(ObjectPtr anObject, theObjects) {
2207     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2208     if (aResult.get()) {
2209       aDeflection = XGUI_CustomPrs::getResultDeflection(aResult);
2210     }
2211     else {
2212       // TODO: remove the obtaining a property from the AIS object
2213       // this does not happen never because:
2214       // 1. The property can be changed only on results
2215       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2216       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2217       if (anAISObj.get()) {
2218         aDeflection = anAISObj->getDeflection();
2219       }
2220     }
2221     if (aDeflection > 0)
2222       break;
2223   }
2224   if (aDeflection < 0)
2225     return;
2226
2227   if (!abortAllOperations())
2228   return;
2229   // 2. show the dialog to change the value
2230   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
2231   aDlg->setDeflection(aDeflection);
2232   aDlg->move(QCursor::pos());
2233   bool isDone = aDlg->exec() == QDialog::Accepted;
2234   if (!isDone)
2235     return;
2236
2237   // 3. abort the previous operation and start a new one
2238   SessionPtr aMgr = ModelAPI_Session::get();
2239   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2240   aMgr->startOperation(aDescription.toStdString());
2241
2242   // 4. set the value to all results
2243   aDeflection = aDlg->getDeflection();
2244   foreach(ObjectPtr anObj, theObjects) {
2245     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2246     if (aResult.get() != NULL) {
2247       ResultCompSolidPtr aCompsolidResult =
2248         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
2249       if (aCompsolidResult.get() != NULL) { // change property for all sub-solids
2250         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2251           setDeflection(aCompsolidResult->subResult(i), aDeflection);
2252         }
2253       }
2254       setDeflection(aResult, aDeflection);
2255     }
2256   }
2257   aMgr->finishOperation();
2258   updateCommandStatus();
2259 }
2260
2261 //**************************************************************
2262 void XGUI_Workshop::changeTransparency(const QObjectPtrList& theObjects)
2263 {
2264   AttributeDoublePtr aDoubleAttr;
2265   // 1. find the current property of the object. This is a property of AIS presentation
2266   // The objects are iterated until a first valid property is found
2267   double aCurrentValue = -1;
2268   foreach(ObjectPtr anObject, theObjects) {
2269     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2270     if (aResult.get()) {
2271       aCurrentValue = XGUI_CustomPrs::getResultTransparency(aResult);
2272     }
2273     else {
2274       // TODO: remove the obtaining a property from the AIS object
2275       // this does not happen never because:
2276       // 1. The property can be changed only on results
2277       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2278       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2279       if (anAISObj.get()) {
2280         aCurrentValue = anAISObj->getDeflection();
2281       }
2282     }
2283     if (aCurrentValue > 0)
2284       break;
2285   }
2286   if (aCurrentValue < 0)
2287     return;
2288
2289   if (!abortAllOperations())
2290   return;
2291
2292   // 2. show the dialog to change the value
2293   XGUI_PropertyDialog* aDlg = new XGUI_PropertyDialog(desktop());
2294   aDlg->setWindowTitle("Transparency");
2295   XGUI_TransparencyWidget* aTransparencyWidget = new XGUI_TransparencyWidget(aDlg);
2296   connect(aTransparencyWidget, SIGNAL(transparencyValueChanged()),
2297           this, SLOT(onTransparencyValueChanged()));
2298   connect(aTransparencyWidget, SIGNAL(previewStateChanged()),
2299           this, SLOT(onPreviewStateChanged()));
2300   aDlg->setContent(aTransparencyWidget);
2301   aTransparencyWidget->setValue(aCurrentValue);
2302
2303   // 3. abort the previous operation and start a new one
2304   SessionPtr aMgr = ModelAPI_Session::get();
2305   QString aDescription = contextMenuMgr()->action("TRANSPARENCY_CMD")->text();
2306   aMgr->startOperation(aDescription.toStdString());
2307
2308   aDlg->move(QCursor::pos());
2309   bool isDone = aDlg->exec() == QDialog::Accepted;
2310   if (!isDone)
2311     return;
2312
2313   // 4. set the value to all results
2314   aCurrentValue = aTransparencyWidget->getValue();
2315   setTransparency(aCurrentValue, theObjects);
2316
2317   aMgr->finishOperation();
2318   updateCommandStatus();
2319 }
2320
2321 //**************************************************************
2322 void XGUI_Workshop::onTransparencyValueChanged()
2323 {
2324   XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2325   if (!aTransparencyWidget || !aTransparencyWidget->isPreviewNeeded())
2326     return;
2327
2328   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2329   setTransparency(aTransparencyWidget->getValue(), anObjects);
2330   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2331 }
2332
2333 //**************************************************************
2334 void XGUI_Workshop::onPreviewStateChanged()
2335 {
2336   XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2337   if (!aTransparencyWidget || !aTransparencyWidget->isPreviewNeeded())
2338     return;
2339
2340   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2341   setTransparency(aTransparencyWidget->getValue(), anObjects);
2342   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2343 }
2344
2345 //**************************************************************
2346 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
2347 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
2348   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
2349 }
2350
2351 //******************************************************
2352 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2353 {
2354   if (isVisible) {
2355     std::set<ObjectPtr> anObjects;
2356     foreach (ObjectPtr aObj, theList) {
2357       anObjects.insert(aObj);
2358     }
2359     if (!prepareForDisplay(anObjects))
2360       return;
2361   }
2362
2363   foreach (ObjectPtr aObj, theList) {
2364     aObj->setDisplayed(isVisible);
2365   }
2366   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2367   myObjectBrowser->updateAllIndexes();
2368 }
2369
2370 //**************************************************************
2371 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2372 {
2373   // Hide all displayed objects
2374   QObjectPtrList aList = myDisplayer->displayedObjects();
2375   foreach (ObjectPtr aObj, aList) {
2376     if (module()->canEraseObject(aObj))
2377       aObj->setDisplayed(false);
2378   }
2379   //Do not use eraseAll if you didn't send Redisplay event:
2380   //all objects are erased from viewer, but considered as displayed in displayer
2381   // Problem in bug 2218
2382   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2383 #ifdef HAVE_SALOME
2384     //issue #2159 Hide all incomplete behavior
2385     viewer()->eraseAll();
2386 #endif
2387
2388   std::set<ObjectPtr> anObjects;
2389   foreach (ObjectPtr aObj, theList) {
2390     anObjects.insert(aObj);
2391   }
2392
2393   if (!prepareForDisplay(anObjects))
2394     return;
2395
2396   // Show only objects from the list
2397   foreach (ObjectPtr aObj, theList) {
2398     aObj->setDisplayed(true);
2399   }
2400   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2401
2402   // Necessary for update icons in ObjectBrowser on Linux
2403   myObjectBrowser->updateAllIndexes();
2404 }
2405
2406 //**************************************************************
2407 void XGUI_Workshop::registerValidators() const
2408 {
2409   SessionPtr aMgr = ModelAPI_Session::get();
2410   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2411 }
2412
2413 //**************************************************************
2414 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2415 {
2416   if (!theDoc)
2417     return;
2418   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2419   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2420 }
2421
2422 //**************************************************************
2423 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2424 {
2425   for (int i = 0; i < theDoc->size(theGroup); i++)
2426     theDoc->object(theGroup, i)->setDisplayed(true);
2427     //displayObject(theDoc->object(theGroup, i));
2428   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2429 }
2430
2431 //**************************************************************
2432 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2433 {
2434   foreach(ObjectPtr aObj, theList) {
2435     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
2436
2437     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
2438     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2439       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2440           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
2441                                       (XGUI_Displayer::DisplayMode)theMode, false);
2442       }
2443     }
2444   }
2445   if (theList.size() > 0)
2446     myDisplayer->updateViewer();
2447 }
2448
2449 //**************************************************************
2450 void XGUI_Workshop::closeDocument()
2451 {
2452   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2453   while (anOperation) {
2454     anOperation->abort();
2455     anOperation = operationMgr()->currentOperation();
2456   }
2457   //myDisplayer->closeLocalContexts();
2458   myDisplayer->eraseAll();
2459   objectBrowser()->clearContent();
2460
2461   module()->closeDocument();
2462   // we need to clear viewer (with created filters) to do not have problems in 2nd SALOME study
2463   module()->clearViewer();
2464
2465
2466   // data model need not process the document's signals about objects modifications as
2467   // the document is closed
2468   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2469
2470   SessionPtr aMgr = ModelAPI_Session::get();
2471   aMgr->closeAll();
2472
2473   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2474 }
2475
2476 //******************************************************
2477 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2478 {
2479   XGUI_HistoryMenu* aMenu = NULL;
2480   if (isSalomeMode()) {
2481     QAction* anAction = qobject_cast<QAction*>(theObject);
2482     if (!anAction)
2483       return;
2484     aMenu = new XGUI_HistoryMenu(anAction);
2485   } else {
2486     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2487     aMenu = new XGUI_HistoryMenu(aButton);
2488   }
2489   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2490   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2491 }
2492
2493 //******************************************************
2494 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2495 {
2496   QList<ActionInfo> aResult;
2497   std::list<std::string>::const_iterator it = theList.cbegin();
2498   for (; it != theList.cend(); it++) {
2499     QString anId = QString::fromStdString(*it);
2500     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2501     if (isEditing) {
2502       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2503     }
2504     ActionInfo anInfo;
2505     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2506     if (aContextMenuAct) {
2507       anInfo.initFrom(aContextMenuAct);
2508     } else {
2509       anInfo = myActionsMgr->actionInfoById(anId);
2510     }
2511     if (isEditing) {
2512       anInfo.text = anInfo.text.prepend("Modify ");
2513     }
2514     aResult << anInfo;
2515   }
2516   return aResult;
2517 }
2518
2519 //******************************************************
2520 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2521 {
2522 #ifdef HAVE_SALOME
2523   salomeConnector()->putInfo(theMessage, -1);
2524 #else
2525   myMainWindow->putInfo(theMessage, -1);
2526 #endif
2527 }
2528
2529 #ifdef HAVE_SALOME
2530 //******************************************************
2531 void XGUI_Workshop::synchronizeViewer()
2532 {
2533   SessionPtr aMgr = ModelAPI_Session::get();
2534   QList<DocumentPtr> aDocs;
2535   aDocs.append(aMgr->activeDocument());
2536   aDocs.append(aMgr->moduleDocument());
2537
2538   foreach(DocumentPtr aDoc, aDocs) {
2539     synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2540     synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2541     synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2542     synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2543   }
2544 }
2545
2546 //******************************************************
2547 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2548                                              const std::string& theGroup,
2549                                              bool theUpdateViewer)
2550 {
2551   ObjectPtr aObj;
2552   int aSize = theDoc->size(theGroup);
2553   for (int i = 0; i < aSize; i++) {
2554     aObj = theDoc->object(theGroup, i);
2555     if (aObj->isDisplayed()) {
2556       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2557       // be changed to the object becomes visible when the shape becomes not empty
2558       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2559       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2560         continue;
2561       myDisplayer->display(aObj, false);
2562     }
2563   }
2564   if (theUpdateViewer)
2565     myDisplayer->updateViewer();
2566 }
2567 #endif
2568
2569 //******************************************************
2570 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2571 {
2572   FeaturePtr aFeature;
2573   QObjectPtrList aSelList = theObjects;
2574   bool aHasHidden = false;
2575   foreach(ObjectPtr aObj, theObjects) {
2576     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2577     if (aFeature.get()) {
2578       std::list<ResultPtr> aResults;
2579       ModelAPI_Tools::allResults(aFeature, aResults);
2580       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2581       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2582         aHasHidden |= (*aIt)->isConcealed();
2583         aSelList.append(*aIt);
2584       }
2585     }
2586   }
2587   if (aSelList.count() > theObjects.count()) {
2588     // if something was found
2589     bool aBlocked = objectBrowser()->blockSignals(true);
2590     objectBrowser()->setObjectsSelected(aSelList);
2591     objectBrowser()->blockSignals(aBlocked);
2592   }
2593   if (aHasHidden)
2594     QMessageBox::information(desktop(), tr("Find results"),
2595                              tr("Results not found"), QMessageBox::Ok);
2596 }
2597
2598 //******************************************************
2599 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2600 {
2601   ResultPtr aResult;
2602   QObjectPtrList aSelList = theObjects;
2603   FeaturePtr aFeature;
2604   foreach(ObjectPtr aObj, theObjects) {
2605     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2606     if (aResult.get()) {
2607       aFeature = ModelAPI_Feature::feature(aResult);
2608       if (aFeature.get()) {
2609         aSelList.append(aFeature);
2610       }
2611     }
2612   }
2613   if (aSelList.count() > theObjects.count()) {
2614     // if something was found
2615     bool aBlocked = objectBrowser()->blockSignals(true);
2616     objectBrowser()->setObjectsSelected(aSelList);
2617     objectBrowser()->blockSignals(aBlocked);
2618   }
2619 }
2620
2621 void XGUI_Workshop::insertFeatureFolder()
2622 {
2623   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2624   if (aObjects.isEmpty())
2625     return;
2626   ObjectPtr aObj = aObjects.first();
2627   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2628   if (aFeature.get() == NULL)
2629     return;
2630   SessionPtr aMgr = ModelAPI_Session::get();
2631   DocumentPtr aDoc = aMgr->activeDocument();
2632
2633   aMgr->startOperation();
2634   aDoc->addFolder(aFeature);
2635   aMgr->finishOperation();
2636 }
2637
2638
2639 void XGUI_Workshop::insertToFolder(bool isBefore)
2640 {
2641   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2642   if (aFeatures.empty())
2643     return;
2644
2645   SessionPtr aMgr = ModelAPI_Session::get();
2646   DocumentPtr aDoc = aMgr->activeDocument();
2647
2648   FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
2649                                 aDoc->findFolderBelow(aFeatures);
2650   if (!aFolder.get())
2651     return;
2652
2653   aMgr->startOperation();
2654   aDoc->moveToFolder(aFeatures, aFolder);
2655   aMgr->finishOperation();
2656 }
2657
2658 void XGUI_Workshop::moveOutFolder(bool isBefore)
2659 {
2660   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2661   if (aFeatures.empty())
2662     return;
2663
2664   SessionPtr aMgr = ModelAPI_Session::get();
2665   DocumentPtr aDoc = aMgr->activeDocument();
2666
2667   aMgr->startOperation();
2668   aDoc->removeFromFolder(aFeatures, isBefore);
2669   aMgr->finishOperation();
2670 }