]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Parameters manager implementation
[modules/shaper.git] / src / XGUI / XGUI_Workshop.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Workshop.h"
5
6 #include "XGUI_ActionsMgr.h"
7 #include "XGUI_MenuMgr.h"
8 #include "XGUI_ColorDialog.h"
9 #include "XGUI_ContextMenuMgr.h"
10 #include "XGUI_Displayer.h"
11 #include "XGUI_ErrorDialog.h"
12 #include "XGUI_ErrorMgr.h"
13 #include "XGUI_ModuleConnector.h"
14 #include "XGUI_ObjectsBrowser.h"
15 #include "XGUI_OperationMgr.h"
16 #include "XGUI_PropertyPanel.h"
17 #include "XGUI_SalomeConnector.h"
18 #include "XGUI_Selection.h"
19 #include "XGUI_SelectionMgr.h"
20 #include "XGUI_Tools.h"
21 #include "XGUI_ViewerProxy.h"
22 #include "XGUI_WorkshopListener.h"
23 #include <XGUI_CustomPrs.h>
24 #include <XGUI_HistoryMenu.h>
25 #include <XGUI_QtEvents.h>
26
27 #ifndef HAVE_SALOME
28 #include <AppElements_Button.h>
29 #include <AppElements_Command.h>
30 #include <AppElements_MainMenu.h>
31 #include <AppElements_MainWindow.h>
32 #include <AppElements_MenuGroupPanel.h>
33 #include <AppElements_Viewer.h>
34 #include <AppElements_Workbench.h>
35 #endif
36
37 #include <ModelAPI_AttributeDocRef.h>
38 #include <ModelAPI_AttributeIntArray.h>
39 #include <ModelAPI_Data.h>
40 #include <ModelAPI_Events.h>
41 #include <ModelAPI_Feature.h>
42 #include <ModelAPI_Object.h>
43 #include <ModelAPI_ResultBody.h>
44 #include <ModelAPI_ResultConstruction.h>
45 #include <ModelAPI_ResultGroup.h>
46 #include <ModelAPI_ResultParameter.h>
47 #include <ModelAPI_Session.h>
48 #include <ModelAPI_Validator.h>
49 #include <ModelAPI_ResultCompSolid.h>
50 #include <ModelAPI_Tools.h>
51
52 //#include <PartSetPlugin_Part.h>
53
54 #include <Events_Loop.h>
55 #include <Events_Error.h>
56 #include <Events_LongOp.h>
57
58 #include <ModuleBase_FilterFactory.h>
59 #include <ModuleBase_IModule.h>
60 #include <ModuleBase_IViewer.h>
61 #include <ModuleBase_Operation.h>
62 #include <ModuleBase_OperationDescription.h>
63 #include <ModuleBase_PageBase.h>
64 #include <ModuleBase_Preferences.h>
65 #include <ModuleBase_SelectionValidator.h>
66 #include <ModuleBase_Tools.h>
67 #include <ModuleBase_WidgetFactory.h>
68 #include <ModuleBase_OperationFeature.h>
69 #include <ModuleBase_OperationAction.h>
70 #include <ModuleBase_PagedContainer.h>
71 #include <ModuleBase_WidgetValidated.h>
72 #include <ModuleBase_ModelWidget.h>
73
74 #include <Config_Common.h>
75 #include <Config_FeatureMessage.h>
76 #include <Config_ModuleReader.h>
77 #include <Config_PointerMessage.h>
78 #include <Config_PropManager.h>
79 #include <Config_SelectionFilterMessage.h>
80 #include <Config_DataModelReader.h>
81
82 #include <SUIT_ResourceMgr.h>
83
84 #include <QApplication>
85 #include <QFileDialog>
86 #include <QMessageBox>
87 #include <QMdiSubWindow>
88 #include <QMainWindow>
89 #include <QPushButton>
90 #include <QDockWidget>
91 #include <QLayout>
92 #include <QThread>
93 #include <QObject>
94 #include <QMenu>
95 #include <QToolButton>
96 #include <QAction>
97 #include <QDesktopWidget>
98
99 #include <iterator>
100
101 #ifdef _DEBUG
102 #include <QDebug>
103 #include <iostream>
104 #endif
105
106 #ifdef WIN32
107 #include <windows.h>
108 #else
109 #include <dlfcn.h>
110 #endif
111
112
113 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
114
115 //#define DEBUG_DELETE
116 //#define DEBUG_FEATURE_NAME
117
118 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
119     : QObject(),
120       myCurrentDir(QString()),
121       myModule(NULL),
122       mySalomeConnector(theConnector),
123       myPropertyPanel(0),
124       myObjectBrowser(0),
125       myDisplayer(0),
126       myViewerSelMode(TopAbs_FACE)
127 {
128 #ifndef HAVE_SALOME
129   myMainWindow = new AppElements_MainWindow();
130
131   SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
132   bool aCloc = aResMgr->booleanValue("language", "locale", true);
133   if (aCloc)
134     QLocale::setDefault( QLocale::c() );
135   else 
136     QLocale::setDefault( QLocale::system() );
137 #endif
138
139   myDataModelXMLReader = new Config_DataModelReader();
140   myDataModelXMLReader->readAll();
141
142   myDisplayer = new XGUI_Displayer(this);
143
144   mySelector = new XGUI_SelectionMgr(this);
145   connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
146
147   myOperationMgr = new XGUI_OperationMgr(this, 0);
148   myActionsMgr = new XGUI_ActionsMgr(this);
149   myMenuMgr = new XGUI_MenuMgr(this);
150   myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
151   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
152   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
153           SLOT(onContextMenuCommand(const QString&, bool)));
154
155   myViewerProxy = new XGUI_ViewerProxy(this);
156   connect(myViewerProxy, SIGNAL(selectionChanged()),
157           myActionsMgr,  SLOT(updateOnViewSelection()));
158
159   myModuleConnector = new XGUI_ModuleConnector(this);
160
161   ModuleBase_IWorkshop* aWorkshop = moduleConnector();
162   myOperationMgr->setWorkshop(aWorkshop);
163
164   myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
165   myEventsListener = new XGUI_WorkshopListener(aWorkshop);
166
167   connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)), 
168           SLOT(onOperationStarted(ModuleBase_Operation*)));
169   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
170           SLOT(onOperationResumed(ModuleBase_Operation*)));
171   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
172           SLOT(onOperationStopped(ModuleBase_Operation*)));
173   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)), 
174           SLOT(onOperationCommitted(ModuleBase_Operation*)));
175   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)), 
176           SLOT(onOperationAborted(ModuleBase_Operation*)));
177
178 #ifndef HAVE_SALOME
179   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
180   onTrihedronVisibilityChanged(true);
181 #endif
182
183   connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
184   connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
185           myErrorDlg, SLOT(addError(const QString&)));
186
187   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
188   //                                 Config_Prop::Color, "225,225,225");
189
190   Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
191                                    Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
192   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
193                                    Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
194   Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
195                                    Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
196   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
197                                    Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
198   
199   myViewerSelMode = 
200     ModuleBase_Preferences::resourceMgr()->integerValue("Viewer", "selection", TopAbs_FACE);
201 }
202
203 //******************************************************
204 XGUI_Workshop::~XGUI_Workshop(void)
205 {
206   delete myDisplayer;
207   delete myDataModelXMLReader;
208 }
209
210 //******************************************************
211 void XGUI_Workshop::startApplication()
212 {
213   initMenu();
214
215   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
216                                    Config_Prop::Directory, "");
217
218   //Initialize event listening
219   myEventsListener->initializeEventListening();
220
221   registerValidators();
222
223   // Calling of  loadCustomProps before activating module is required
224   // by Config_PropManger to restore user-defined path to plugins
225   ModuleBase_Preferences::loadCustomProps();
226   createModule();
227
228 #ifndef HAVE_SALOME
229   myMainWindow->show();
230   updateCommandStatus();
231 #endif
232   
233   onNew();
234
235   myViewerProxy->connectViewProxy();
236   connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
237           SLOT(onTrihedronVisibilityChanged(bool)));
238
239   emit applicationStarted();
240 }
241
242 void XGUI_Workshop::activateModule()
243 {
244   myModule->activateSelectionFilters();
245
246   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
247     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
248   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
249     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
250
251   updateCommandStatus();
252
253   // TODO: get default selection mode
254
255   // activate visualized objects in the viewer
256   activateObjectsSelection(displayer()->displayedObjects());
257   myOperationMgr->activate();
258 }
259
260 void XGUI_Workshop::deactivateModule()
261 {
262   myModule->deactivateSelectionFilters();
263
264   // remove internal displayer filter
265   displayer()->deactivateSelectionFilters();
266
267   disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
268     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
269   disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
270     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
271
272   XGUI_Displayer* aDisplayer = displayer();
273   QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
274   aDisplayer->deactivateObjects(aDisplayed, true);
275
276   myOperationMgr->deactivate();
277 }
278
279 //******************************************************
280 void XGUI_Workshop::initMenu()
281 {
282   myContextMenuMgr->createActions();
283
284 #ifdef HAVE_SALOME
285   // Create only Undo, Redo commands
286   QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
287                                                         tr("Undo last command"),
288                                                         QIcon(":pictures/undo.png"),
289                                                         QKeySequence::Undo, false, "MEN_DESK_EDIT");
290   QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
291   salomeConnector()->addActionInToolbar( aAction,aToolBarTitle  );
292
293   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
294   addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
295
296   aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
297                                               QIcon(":pictures/redo.png"), QKeySequence::Redo,
298                                               false, "MEN_DESK_EDIT");
299   salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
300
301   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
302   addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
303
304   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
305   //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
306   //                                            QIcon(":pictures/rebuild.png"), QKeySequence(),
307   //                                            false, "MEN_DESK_EDIT");
308   //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
309
310   //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
311   //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
312
313   aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."), tr("Export the current document into a native file"),
314                                               QIcon(), QKeySequence(),
315                                               false, "MEN_DESK_FILE");
316   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
317
318   aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."), tr("Import native file"),
319                                               QIcon(), QKeySequence(),
320                                               false, "MEN_DESK_FILE");
321   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
322   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
323
324 #else
325   // File commands group
326   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
327
328   AppElements_Command* aCommand;
329
330   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
331                                 QIcon(":pictures/save.png"), QKeySequence::Save);
332   aCommand->connectTo(this, SLOT(onSave()));
333   //aCommand->disable();
334
335   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
336                                 QIcon(":pictures/save.png"), QKeySequence());
337   aCommand->connectTo(this, SLOT(onSaveAs()));
338
339   QString aUndoId = "UNDO_CMD";
340   aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
341                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
342   aCommand->connectTo(this, SLOT(onUndo()));
343   AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
344   addHistoryMenu(aUndoButton,
345                  SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
346                  SLOT(onUndo(int)));
347
348   QString aRedoId = "REDO_CMD";
349   aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
350                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
351   aCommand->connectTo(this, SLOT(onRedo()));
352   AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
353   addHistoryMenu(aRedoButton,
354                  SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
355                  SLOT(onRedo(int)));
356
357   //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
358   //  QIcon(":pictures/rebuild.png"), QKeySequence());
359   //aCommand->connectTo(this, SLOT(onRebuild()));
360
361   //aCommand->disable();
362
363   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
364                                 QIcon(":pictures/open.png"), QKeySequence::Open);
365   aCommand->connectTo(this, SLOT(onOpen()));
366
367   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
368                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
369   aCommand->connectTo(this, SLOT(onPreferences()));
370
371   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
372                                 QIcon(":pictures/close.png"), QKeySequence::Close);
373   aCommand->connectTo(this, SLOT(onExit()));
374 #endif
375 }
376
377 #ifndef HAVE_SALOME
378 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
379 {
380   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
381   return aMenuBar->addWorkbench(theName);
382 }
383 #endif
384
385 //******************************************************
386 QMainWindow* XGUI_Workshop::desktop() const
387 {
388 #ifdef HAVE_SALOME
389   return salomeConnector()->desktop();
390 #else
391   return myMainWindow;
392 #endif
393 }
394
395 //******************************************************
396 void XGUI_Workshop::onStartWaiting()
397 {
398   if (Events_LongOp::isPerformed()) {
399     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
400   }
401 }
402
403 //******************************************************
404 void XGUI_Workshop::onAcceptActionClicked()
405 {
406   QAction* anAction = dynamic_cast<QAction*>(sender());
407   XGUI_OperationMgr* anOperationMgr = operationMgr();
408   if (anOperationMgr) {
409     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
410                                                     (anOperationMgr->currentOperation());
411     if (aFOperation) {
412       //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
413       myOperationMgr->onCommitOperation();
414     }
415   }
416 }
417
418 //******************************************************
419 void XGUI_Workshop::onPreviewActionClicked()
420 {
421   ModuleBase_IPropertyPanel* aPanel = propertyPanel();
422   if (aPanel) {
423     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
424     if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
425       anActiveWidget->storeValue();
426     }
427   }
428   std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
429                 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
430   Events_Loop::loop()->send(aMsg);
431 }
432
433 //******************************************************
434 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
435 {
436   if (!myModule->canActivateSelection(theObject)) {
437     if (myDisplayer->isActive(theObject)) {
438       QObjectPtrList anObjects;
439       anObjects.append(theObject);
440       myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
441     }
442   }
443 }
444
445 //******************************************************
446 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
447 {
448   bool aHasNested = false;
449   std::string aFeatureKind = theFeature->getKind();
450 #ifdef HAVE_SALOME
451     XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
452     if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
453       aHasNested = true;
454 #else 
455     AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
456     AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
457     if (aCommand && aCommand->button()->additionalButtonWidget())
458       aHasNested = true;
459 #endif
460   return aHasNested;
461 }
462
463 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
464 {
465   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
466   if (!aFOperation)
467     return;
468
469   showPropertyPanel();
470   myPropertyPanel->cleanContent();
471
472   QList<ModuleBase_ModelWidget*> aWidgets;
473   if (!module()->createWidgets(theOperation, aWidgets)) {
474     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
475     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
476     aFactory.createWidget(myPropertyPanel->contentWidget());
477     aWidgets = aFactory.getModelWidgets();
478   }
479
480   // check compatibility of feature and widgets
481   FeaturePtr aFeature = aFOperation->feature();
482   std::string aFeatureKind = aFeature->getKind();
483   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
484     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
485       std::string anErrorMsg = "The feature '" + aFeatureKind + "' has no attribute '"
486           + aWidget->attributeID() + "' used by widget '"
487           + aWidget->metaObject()->className() + "'.";
488       Events_Error::send(anErrorMsg);
489       myPropertyPanel->cleanContent();
490       return;
491     }
492   }
493   // for performance purpose, flush should be done after all controls are filled
494   bool isUpdateFlushed = false;
495   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
496     bool isStoreValue = !aFOperation->isEditOperation() &&
497                         !aWidget->getDefaultValue().empty() &&
498                         !aWidget->isComputedDefault();
499     aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
500     aWidget->enableFocusProcessing();
501   }
502   ModuleBase_Tools::flushUpdated(aFeature);
503
504   // update visible state of Preview button
505 #ifdef HAVE_SALOME
506   bool anIsAutoPreview = mySalomeConnector->featureInfo(aFeatureKind.c_str())->isAutoPreview();
507 #else
508   AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
509   AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
510   bool anIsAutoPreview = aCommand && aCommand->featureMessage()->isAutoPreview();
511 #endif
512   if (!anIsAutoPreview) {
513     myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
514     // send signal about preview should not be computed automatically, click on preview
515     // button should initiate it
516     std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
517                   new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
518     Events_Loop::loop()->send(aMsg);
519   }
520   myPropertyPanel->setModelWidgets(aWidgets);
521   aFOperation->setPropertyPanel(myPropertyPanel);
522
523   myModule->propertyPanelDefined(theOperation);
524
525 #ifndef DEBUG_FEATURE_NAME
526   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
527 #else
528   std::string aFeatureName = aFeature->name();
529   myPropertyPanel->setWindowTitle(QString("%1: %2").arg(theOperation->getDescription()->description())
530                                                   .arg(aFeatureName.c_str()));
531 #endif
532
533   myErrorMgr->setPropertyPanel(myPropertyPanel);
534 }
535
536 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
537 {
538   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
539   if (aPropertyPanel) {
540     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
541     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
542        myModule->connectToPropertyPanel(aWidget, isToConnect);
543        if (isToConnect) {
544         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
545         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
546         connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
547        }
548       else {
549         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
550         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
551         disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
552       }
553     }
554   }
555 }
556
557 //******************************************************
558 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
559 {
560   setGrantedFeatures(theOperation);
561   myModule->operationStarted(theOperation);
562 }
563
564 //******************************************************
565 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
566 {
567   setGrantedFeatures(theOperation);
568
569   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
570     setPropertyPanel(theOperation);
571     connectToPropertyPanel(true);
572   }
573   updateCommandStatus();
574
575   myModule->operationResumed(theOperation);
576 }
577
578
579 //******************************************************
580 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
581 {
582   updateCommandStatus();
583
584   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
585                                                                         (theOperation);
586   if (!aFOperation)
587     return;
588
589   ModuleBase_ISelection* aSel = mySelector->selection();
590   QObjectPtrList aObj = aSel->selectedPresentations();
591   //!< No need for property panel
592   hidePropertyPanel();
593   myPropertyPanel->cleanContent();
594
595   connectToPropertyPanel(false);
596   myModule->operationStopped(aFOperation);
597
598   // the deactivated objects of the current operation should be activated back.
599   // They were deactivated on operation start or an object redisplay
600   QObjectPtrList anObjects;
601   FeaturePtr aFeature = aFOperation->feature();
602   if (aFeature.get()) { // feature may be not created (plugin load fail)
603     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
604       anObjects.append(aFeature);
605     std::list<ResultPtr> aResults = aFeature->results();
606     std::list<ResultPtr>::const_iterator aIt;
607     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
608       ResultPtr anObject = *aIt;
609       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
610         anObjects.append(anObject);
611       }
612     }
613   }
614   activateObjectsSelection(anObjects);
615 }
616
617
618 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
619 {
620   myModule->operationCommitted(theOperation);
621 }
622
623 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
624 {
625   myModule->operationAborted(theOperation);
626 }
627
628 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
629 {
630   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
631   if (!aFOperation)
632     return;
633
634   QStringList aGrantedIds;
635   if (isSalomeMode()) {
636     const std::shared_ptr<Config_FeatureMessage>& anInfo =
637                          mySalomeConnector->featureInfo(theOperation->id());
638     if (anInfo.get())
639       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
640                                    .split(" ", QString::SkipEmptyParts);
641   }
642   else
643     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
644
645   ModuleBase_IModule* aModule = module();
646   if (aModule)
647     aModule->grantedOperationIds(theOperation, aGrantedIds);
648
649   aFOperation->setGrantedOperationIds(aGrantedIds);
650 }
651
652
653 /*
654  * Saves document with given name.
655  */
656 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
657 {
658   QApplication::restoreOverrideCursor();
659   SessionPtr aMgr = ModelAPI_Session::get();
660   aMgr->save(theName.toLatin1().constData(), theFileNames);
661   QApplication::restoreOverrideCursor();
662 }
663
664 bool XGUI_Workshop::abortAllOperations()
665 {
666   return myOperationMgr->abortAllOperations();
667 }
668
669 //******************************************************
670 void XGUI_Workshop::onOpen()
671 {
672   if(!abortAllOperations())
673     return;
674   //save current file before close if modified
675   SessionPtr aSession = ModelAPI_Session::get();
676   if (aSession->isModified()) {
677     //TODO(sbh): re-launch the app?
678     int anAnswer = QMessageBox::question(
679         desktop(), tr("Save current file"),
680         tr("The document is modified, save before opening another?"),
681         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
682     if (anAnswer == QMessageBox::Save) {
683       onSave();
684     } else if (anAnswer == QMessageBox::Cancel) {
685       return;
686     }
687     myCurrentDir = "";
688   }
689
690   //show file dialog, check if readable and open
691   myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
692   if (myCurrentDir.isEmpty())
693     return;
694   QFileInfo aFileInfo(myCurrentDir);
695   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
696     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
697     myCurrentDir = "";
698     return;
699   }
700   QApplication::setOverrideCursor(Qt::WaitCursor);
701   aSession->closeAll();
702   aSession->load(myCurrentDir.toLatin1().constData());
703   myObjectBrowser->rebuildDataTree();
704   updateCommandStatus();
705   QApplication::restoreOverrideCursor();
706 }
707
708 //******************************************************
709 void XGUI_Workshop::onNew()
710 {
711   QApplication::setOverrideCursor(Qt::WaitCursor);
712   if (objectBrowser() == 0) {
713     createDockWidgets();
714     mySelector->connectViewers();
715   }
716   myViewerProxy->connectToViewer();
717   showObjectBrowser();
718 #ifndef HAVE_SALOME
719   myMainWindow->showPythonConsole();
720   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
721   aWnd->showMaximized();
722   updateCommandStatus();
723 #endif
724   myContextMenuMgr->connectViewer();
725   QApplication::restoreOverrideCursor();
726 }
727
728 #ifndef HAVE_SALOME
729 //******************************************************
730 void XGUI_Workshop::onExit()
731 {
732   SessionPtr aMgr = ModelAPI_Session::get();
733   if (aMgr->isModified()) {
734     int anAnswer = QMessageBox::question(
735         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
736         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
737     if (anAnswer == QMessageBox::Save) {
738       bool saved = onSave();
739       if (!saved) {
740         return;
741       }
742     } else if (anAnswer == QMessageBox::Cancel) {
743       return;
744     }
745   }
746   qApp->exit();
747 }
748
749 //******************************************************
750 void XGUI_Workshop::onPreferences()
751 {
752   ModuleBase_Prefs aModif;
753   ModuleBase_Preferences::editPreferences(aModif);
754   if (aModif.size() > 0) {
755     QString aSection;
756     foreach (ModuleBase_Pref aPref, aModif)
757     {
758       aSection = aPref.first;
759       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
760         myMainWindow->viewer()->updateFromResources();
761       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
762         myMainWindow->menuObject()->updateFromResources();
763       }
764     }
765     displayer()->redisplayObjects();
766   }
767 }
768 #endif
769
770 //******************************************************
771 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
772 {
773   XGUI_Displayer* aDisplayer = displayer();
774   if (aDisplayer)
775     aDisplayer->displayTrihedron(theState);
776 }
777
778 //******************************************************
779 bool XGUI_Workshop::onSave()
780 {
781   if(!abortAllOperations())
782     return false;
783   if (myCurrentDir.isEmpty()) {
784     return onSaveAs();
785   }
786   std::list<std::string> aFiles;
787   saveDocument(myCurrentDir, aFiles);
788   updateCommandStatus();
789 #ifndef HAVE_SALOME
790     myMainWindow->setModifiedState(false);
791 #endif
792   return true;
793 }
794
795 //******************************************************
796 bool XGUI_Workshop::onSaveAs()
797 {
798   if(!abortAllOperations())
799     return false;
800   QFileDialog dialog(desktop());
801   dialog.setWindowTitle(tr("Select directory to save files..."));
802   dialog.setFileMode(QFileDialog::Directory);
803   dialog.setFilter(tr("Directories (*)"));
804   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
805   dialog.setViewMode(QFileDialog::Detail);
806
807   if (!dialog.exec()) {
808     return false;
809   }
810
811   QString aTempDir = dialog.selectedFiles().first();
812   QDir aDir(aTempDir);
813   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
814     int answer = QMessageBox::question(
815         desktop(),
816         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
817         tr("Save"),
818         tr("The directory already contains some files, save anyway?"),
819         QMessageBox::Save | QMessageBox::Cancel);
820     if (answer == QMessageBox::Cancel) {
821       return false;
822     }
823   }
824   myCurrentDir = aTempDir;
825 #ifndef HAVE_SALOME
826     myMainWindow->setCurrentDir(myCurrentDir, false);
827     myMainWindow->setModifiedState(false);
828 #endif
829   return onSave();
830 }
831
832 //******************************************************
833 void XGUI_Workshop::onUndo(int theTimes)
834 {
835   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
836   SessionPtr aMgr = ModelAPI_Session::get();
837   std::list<std::string> aUndoList = aMgr->undoList();
838   if (aMgr->isOperation()) {
839     /// this is important for nested operations
840     /// when sketch operation is active, this condition is false and
841     /// the sketch operation is not aborted
842     operationMgr()->onAbortOperation();
843   }
844   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
845   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
846     aMgr->undo();
847     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
848       myObjectBrowser->rebuildDataTree();
849   }
850
851   operationMgr()->updateApplyOfOperations();
852   updateCommandStatus();
853 }
854
855 //******************************************************
856 void XGUI_Workshop::onRedo(int theTimes)
857 {
858   // the viewer update should be blocked in order to avoid the features blinking. For the created
859   // feature a results are created, the flush of the created signal caused the viewer redisplay for
860   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
861   // redo of all possible objects happens
862   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
863
864   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
865   SessionPtr aMgr = ModelAPI_Session::get();
866   std::list<std::string> aRedoList = aMgr->redoList();
867   if (aMgr->isOperation()) {
868     /// this is important for nested operations
869     /// when sketch operation is active, this condition is false and
870     /// the sketch operation is not aborted
871     operationMgr()->onAbortOperation();
872   }
873   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
874   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
875     aMgr->redo();
876     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
877       myObjectBrowser->rebuildDataTree();
878   }
879   operationMgr()->updateApplyOfOperations();
880   updateCommandStatus();
881
882   // unblock the viewer update functionality and make update on purpose
883   myDisplayer->enableUpdateViewer(isUpdateEnabled);
884   myDisplayer->updateViewer();
885 }
886
887 //******************************************************
888 //void XGUI_Workshop::onRebuild()
889 //{
890 //  SessionPtr aMgr = ModelAPI_Session::get();
891 //  bool aWasOperation = aMgr->isOperation(); // keep this value
892 //  if (!aWasOperation) {
893 //    aMgr->startOperation("Rebuild");
894 //  }
895 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
896 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
897 //    new Events_Message(aRebuildEvent, this)));
898 //  if (!aWasOperation) {
899 //    aMgr->finishOperation();
900 //  }
901 //  updateCommandStatus();
902 //}
903
904 //******************************************************
905 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
906 {
907   ModuleBase_ModelWidget* anActiveWidget = 0;
908   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
909   if (anOperation) {
910     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
911     if (aPanel)
912       anActiveWidget = aPanel->activeWidget();
913   }
914   if (anActiveWidget)
915     operationMgr()->onValidateOperation();
916
917   myModule->widgetStateChanged(thePreviousState);
918 }
919
920 //******************************************************
921 void XGUI_Workshop::onValuesChanged()
922 {
923   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
924   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
925     return;
926
927   ModuleBase_ModelWidget* anActiveWidget = 0;
928   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
929   if (anOperation) {
930     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
931     if (aPanel)
932       anActiveWidget = aPanel->activeWidget();
933   }
934   if (anActiveWidget) {
935     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
936                                                                            (anActiveWidget);
937     if (aWidgetValidated)
938       aWidgetValidated->clearValidatedCash();
939   }
940 }
941
942 void XGUI_Workshop::onWidgetObjectUpdated()
943 {
944   operationMgr()->onValidateOperation();
945 }
946
947 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
948 {
949   QString libName = QString::fromStdString(library(theModule.toStdString()));
950   if (libName.isEmpty()) {
951     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
952     return 0;
953   }
954
955   QString err;
956   CREATE_FUNC crtInst = 0;
957
958 #ifdef WIN32
959   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
960   if (!modLib) {
961     LPVOID lpMsgBuf;
962     ::FormatMessage(
963         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
964         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
965     QString aMsg((char*) &lpMsgBuf);
966     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
967     ::LocalFree(lpMsgBuf);
968   } else {
969     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
970     if (!crtInst) {
971       LPVOID lpMsgBuf;
972       ::FormatMessage(
973           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
974               | FORMAT_MESSAGE_IGNORE_INSERTS,
975           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
976       QString aMsg((char*) &lpMsgBuf);
977       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
978       ::LocalFree(lpMsgBuf);
979     }
980   }
981 #else
982   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
983   if ( !modLib ) {
984     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
985   } else {
986     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
987     if ( !crtInst ) {
988       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
989     }
990   }
991 #endif
992
993   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
994
995   if (!err.isEmpty()) {
996     if (desktop()) {
997       Events_Error::send(err.toStdString());
998     } else {
999       qWarning(qPrintable(err));
1000     }
1001   }
1002   return aModule;
1003 }
1004
1005 //******************************************************
1006 bool XGUI_Workshop::createModule()
1007 {
1008   Config_ModuleReader aModuleReader;
1009   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1010   myModule = loadModule(moduleName);
1011   if (!myModule)
1012     return false;
1013
1014   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1015   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1016   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1017   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1018
1019   myModule->createFeatures();
1020 #ifdef HAVE_SALOME
1021   salomeConnector()->createFeatureActions();
1022 #endif
1023   //myActionsMgr->update();
1024   return true;
1025 }
1026
1027 //******************************************************
1028 void XGUI_Workshop::updateCommandStatus()
1029 {
1030   QList<QAction*> aCommands;
1031 #ifdef HAVE_SALOME
1032     aCommands = salomeConnector()->commandList();
1033 #else
1034     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1035     foreach (AppElements_Command* aCmd, aMenuBar->features())
1036       aCommands.append(aCmd);
1037 #endif
1038   SessionPtr aMgr = ModelAPI_Session::get();
1039   if (aMgr->hasModuleDocument()) {
1040     foreach(QAction* aCmd, aCommands) {
1041       QString aId = aCmd->data().toString();
1042       if (aId == "UNDO_CMD")
1043         aCmd->setEnabled(myModule->canUndo());
1044       else if (aId == "REDO_CMD")
1045         aCmd->setEnabled(myModule->canRedo());
1046       else
1047         // Enable all commands
1048         aCmd->setEnabled(true);
1049     }
1050     updateHistory();
1051   } else {
1052     foreach(QAction* aCmd, aCommands) {
1053       QString aId = aCmd->data().toString();
1054       if (aId == "NEW_CMD")
1055         aCmd->setEnabled(true);
1056       else if (aId == "EXIT_CMD")
1057         aCmd->setEnabled(true);
1058       else
1059         aCmd->setEnabled(false);
1060     }
1061   }
1062   myActionsMgr->updateCommandsStatus();
1063   emit commandStatusUpdated();
1064 }
1065
1066 void XGUI_Workshop::updateHistory()
1067 {
1068   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1069   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1070   emit updateUndoHistory(aUndoRes);
1071
1072   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1073   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1074   emit updateRedoHistory(aRedoRes);
1075 }
1076
1077 //******************************************************
1078 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1079 {
1080   QDockWidget* aObjDock = new QDockWidget(theParent);
1081   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1082   aObjDock->setWindowTitle(tr("Object browser"));
1083   aObjDock->setStyleSheet(
1084       "::title { position: relative; padding-left: 5px; text-align: left center }");
1085   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1086   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1087   myModule->customizeObjectBrowser(myObjectBrowser);
1088   aObjDock->setWidget(myObjectBrowser);
1089
1090   myContextMenuMgr->connectObjectBrowser();
1091   return aObjDock;
1092 }
1093
1094 //******************************************************
1095 /*
1096  * Creates dock widgets, places them in corresponding area
1097  * and tabifies if necessary.
1098  */
1099 void XGUI_Workshop::createDockWidgets()
1100 {
1101   QMainWindow* aDesktop = desktop();
1102   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1103   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1104   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1105   myPropertyPanel->setupActions(myActionsMgr);
1106   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1107   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1108   hidePropertyPanel();  ///<! Invisible by default
1109   hideObjectBrowser();
1110   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1111   myPropertyPanel->installEventFilter(myOperationMgr);
1112
1113   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1114   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1115
1116   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1117   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1118
1119   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1120   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1121
1122   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1123           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1124   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1125           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1126 }
1127
1128 //******************************************************
1129 void XGUI_Workshop::showPropertyPanel()
1130 {
1131   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1132   ///<! Restore ability to close panel from the window's menu
1133   aViewAct->setEnabled(true);
1134   myPropertyPanel->show();
1135   myPropertyPanel->raise();
1136
1137   // The next code is necessary to made the property panel the active window
1138   // in order to operation manager could process key events of the panel.
1139   // otherwise they are ignored. It happens only if the same(activateWindow) is
1140   // not happened by property panel activation(e.g. resume operation of Sketch)
1141   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1142   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1143 }
1144
1145 //******************************************************
1146 void XGUI_Workshop::hidePropertyPanel()
1147 {
1148   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1149   ///<! Do not allow to show empty property panel
1150   aViewAct->setEnabled(false);
1151   myPropertyPanel->hide();
1152
1153   // the property panel is active window of the desktop, when it is
1154   // hidden, it is undefined which window becomes active. By this reason
1155   // it is defined to perform the desktop as the active window.
1156   // in SALOME mode, workstack made the PyConsole the active window,
1157   // set the focus on it. As a result, shortcuts of the application, like
1158   // are processed by this console. For example Undo actions.
1159   // It is possible that this code is to be moved to SHAPER package
1160   QMainWindow* aDesktop = desktop();
1161   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1162   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1163 }
1164
1165 //******************************************************
1166 void XGUI_Workshop::showObjectBrowser()
1167 {
1168   if (!isSalomeMode())
1169     myObjectBrowser->parentWidget()->show();
1170 }
1171
1172 //******************************************************
1173 void XGUI_Workshop::hideObjectBrowser()
1174 {
1175   if (!isSalomeMode())
1176     myObjectBrowser->parentWidget()->hide();
1177 }
1178
1179 //******************************************************
1180 void XGUI_Workshop::salomeViewerSelectionChanged()
1181 {
1182   emit salomeViewerSelection();
1183 }
1184
1185 //**************************************************************
1186 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1187 {
1188   return mySalomeConnector->viewer();
1189 }
1190
1191 //**************************************************************
1192 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1193 {
1194   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1195   if (theId == "DELETE_CMD")
1196     deleteObjects();
1197   else if (theId == "CLEAN_HISTORY_CMD")
1198     cleanHistory();
1199   else if (theId == "MOVE_CMD")
1200     moveObjects();
1201   else if (theId == "COLOR_CMD")
1202     changeColor(aObjects);
1203   else if (theId == "SHOW_CMD") {
1204     showObjects(aObjects, true);
1205     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1206   }
1207   else if (theId == "HIDE_CMD")
1208     showObjects(aObjects, false);
1209   else if (theId == "SHOW_ONLY_CMD") {
1210     showOnlyObjects(aObjects);
1211     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1212   }
1213   else if (theId == "SHADING_CMD")
1214     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1215   else if (theId == "WIREFRAME_CMD")
1216     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1217   else if (theId == "HIDEALL_CMD") {
1218     QObjectPtrList aList = myDisplayer->displayedObjects();
1219     foreach (ObjectPtr aObj, aList) {
1220       if (module()->canEraseObject(aObj))
1221         aObj->setDisplayed(false);
1222     }
1223     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1224   } else if (theId == "SELECT_VERTEX_CMD") {
1225     setViewerSelectionMode(TopAbs_VERTEX);
1226   } else if (theId == "SELECT_EDGE_CMD") {
1227     setViewerSelectionMode(TopAbs_EDGE);
1228   } else if (theId == "SELECT_FACE_CMD") {
1229     setViewerSelectionMode(TopAbs_FACE);
1230   } else if (theId == "SELECT_RESULT_CMD") {
1231     setViewerSelectionMode(-1);
1232   } else if (theId == "SHOW_RESULTS_CMD") {
1233     highlightResults(aObjects);
1234   }
1235 }
1236
1237 //**************************************************************
1238 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1239 {
1240   myViewerSelMode = theMode;
1241   activateObjectsSelection(myDisplayer->displayedObjects());
1242 }
1243
1244 //**************************************************************
1245 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1246 {
1247   QIntList aModes;
1248   module()->activeSelectionModes(aModes);
1249   if (aModes.isEmpty() && (myViewerSelMode != -1))
1250     aModes.append(myViewerSelMode);
1251   myDisplayer->activateObjects(aModes, theList);
1252 }
1253
1254
1255 //**************************************************************
1256 void XGUI_Workshop::deleteObjects()
1257 {
1258   ModuleBase_IModule* aModule = module();
1259   // 1. allow the module to delete objects, do nothing if it has succeed
1260   if (aModule->deleteObjects()) {
1261     updateCommandStatus();
1262     return;
1263   }
1264
1265   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1266   if (!abortAllOperations())
1267     return;
1268   // check whether the object can be deleted. There should not be parts which are not loaded
1269   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1270     return;
1271
1272   bool hasResult = false;
1273   bool hasFeature = false;
1274   bool hasParameter = false;
1275   bool hasCompositeOwner = false;
1276   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1277   if (!(hasFeature || hasParameter))
1278     return;
1279
1280   // 3. delete objects
1281   std::set<FeaturePtr> anIgnoredFeatures;
1282   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1283   findReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures);
1284
1285   bool doDeleteReferences = true;
1286   if (isDeleteFeatureWithReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1287                                     desktop(), doDeleteReferences)) {
1288     // start operation
1289     QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1290     aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1291     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1292     operationMgr()->startOperation(anOpAction);
1293
1294     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1295     // It is necessary to clear selection in order to avoid selection changed event during
1296     // deletion and negative consequences connected with processing of already deleted items
1297     mySelector->clearSelection();
1298
1299     // delete and commit/abort operation in model
1300     if (deleteFeaturesInternal(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1301                                anIgnoredFeatures, doDeleteReferences))
1302       operationMgr()->commitOperation();
1303     else
1304       operationMgr()->abortOperation(operationMgr()->currentOperation());
1305   }
1306 }
1307
1308 //**************************************************************
1309 void XGUI_Workshop::cleanHistory()
1310 {
1311   if (!abortAllOperations())
1312     return;
1313
1314   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1315   QObjectPtrList aFeatures;
1316   foreach (ObjectPtr anObject, anObjects) {
1317     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1318     // for parameter result, use the corresponded reature to be removed
1319     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1320       aFeature = ModelAPI_Feature::feature(anObject);
1321     }
1322     aFeatures.append(aFeature);
1323   }
1324
1325   // 1. find all referenced features
1326   QList<ObjectPtr> anUnusedObjects;
1327   std::set<FeaturePtr> aDirectRefFeatures;
1328   //foreach (ObjectPtr anObject, anObjects) {
1329   foreach (ObjectPtr anObject, aFeatures) {
1330     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1331     // for parameter result, use the corresponded reature to be removed
1332     //if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1333     //  aFeature = ModelAPI_Feature::feature(anObject);
1334     //}
1335     if (aFeature.get()) {
1336       std::set<FeaturePtr> alreadyProcessed;
1337       aDirectRefFeatures.clear();
1338       XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, aFeatures,
1339                                                     aDirectRefFeatures, alreadyProcessed);
1340       if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1341         anUnusedObjects.append(aFeature);
1342     }
1343   }
1344
1345   // 2. warn about the references remove, break the delete operation if the user chose it
1346   if (!anUnusedObjects.empty()) {
1347     QStringList aNames;
1348     foreach (const ObjectPtr& anObject, anUnusedObjects) {
1349       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1350       aNames.append(aFeature->name().c_str());
1351     }
1352     QString anUnusedNames = aNames.join(", ");
1353
1354     QString anActionId = "CLEAN_HISTORY_CMD";
1355     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1356
1357     QMessageBox aMessageBox(desktop());
1358     aMessageBox.setWindowTitle(aDescription);
1359     aMessageBox.setIcon(QMessageBox::Warning);
1360     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1361     aMessageBox.setDefaultButton(QMessageBox::No);
1362
1363     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1364                    .arg(anUnusedNames));
1365     /*QString aText;
1366     if (anUnusedNames.isEmpty()) {
1367       aMessageBox.setStandardButtons(QMessageBox::Ok);
1368       aMessageBox.setDefaultButton(QMessageBox::Ok);
1369
1370       aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1371     }
1372     else {
1373       aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1374       aMessageBox.setDefaultButton(QMessageBox::No);
1375
1376       aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1377         .arg(anUnusedNames));
1378     }*/
1379
1380     aMessageBox.setText(aText);
1381     if (aMessageBox.exec() == QMessageBox::No)
1382       return;
1383
1384     // 1. start operation
1385     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1386     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1387     operationMgr()->startOperation(anOpAction);
1388
1389     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1390     // It is necessary to clear selection in order to avoid selection changed event during
1391     // deletion and negative consequences connected with processing of already deleted items
1392     mySelector->clearSelection();
1393
1394     std::set<FeaturePtr> anIgnoredFeatures;
1395     if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId, true)) {
1396       operationMgr()->commitOperation();
1397     }
1398     else {
1399       operationMgr()->abortOperation(operationMgr()->currentOperation());
1400     }
1401   }
1402   else {
1403     QString anActionId = "CLEAN_HISTORY_CMD";
1404     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1405
1406     QMessageBox aMessageBox(desktop());
1407     aMessageBox.setWindowTitle(aDescription);
1408     aMessageBox.setIcon(QMessageBox::Warning);
1409     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1410     aMessageBox.setDefaultButton(QMessageBox::No);
1411
1412     QString aText;
1413     aMessageBox.setStandardButtons(QMessageBox::Ok);
1414     aMessageBox.setDefaultButton(QMessageBox::Ok);
1415
1416     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1417     aMessageBox.setText(aText);
1418
1419     if (aMessageBox.exec() == QMessageBox::No)
1420       return;
1421   }
1422 }
1423
1424 //**************************************************************
1425 void XGUI_Workshop::moveObjects()
1426 {
1427   if (!abortAllOperations())
1428     return;
1429
1430   SessionPtr aMgr = ModelAPI_Session::get();
1431
1432   QString anActionId = "MOVE_CMD";
1433   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1434   aMgr->startOperation(aDescription.toStdString());
1435
1436   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1437   // It is necessary to clear selection in order to avoid selection changed event during
1438   // moving and negative consequences connected with processing of already moved items
1439   mySelector->clearSelection();
1440   // check whether the object can be moved. There should not be parts which are not loaded
1441   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1442     return;
1443
1444   DocumentPtr anActiveDocument = aMgr->activeDocument();
1445   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1446   foreach (ObjectPtr aObject, anObjects) {
1447     if (!myModule->canApplyAction(aObject, anActionId))
1448       continue;
1449
1450     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1451     if (aFeature.get()) {
1452       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1453       aCurrentFeature = anActiveDocument->currentFeature(true);
1454     }
1455   }
1456   aMgr->finishOperation();
1457 }
1458
1459 //**************************************************************
1460 void XGUI_Workshop::findReferences(const QObjectPtrList& theList,
1461                                    std::set<FeaturePtr>& aDirectRefFeatures,
1462                                    std::set<FeaturePtr>& aIndirectRefFeatures)
1463 {
1464   foreach (ObjectPtr aDeletedObj, theList) {
1465     std::set<FeaturePtr> alreadyProcessed;
1466     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1467                                             aIndirectRefFeatures, alreadyProcessed);
1468     std::set<FeaturePtr> aDifference;
1469     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1470                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1471                         std::inserter(aDifference, aDifference.begin()));
1472     aIndirectRefFeatures = aDifference;
1473   }
1474 }
1475
1476 bool XGUI_Workshop::isDeleteFeatureWithReferences(const QObjectPtrList& theList,
1477                                    const std::set<FeaturePtr>& aDirectRefFeatures,
1478                                    const std::set<FeaturePtr>& aIndirectRefFeatures,
1479                                    QWidget* theParent,
1480                                    bool& doDeleteReferences)
1481 {
1482   doDeleteReferences = true;
1483
1484   QString aDirectNames, aIndirectNames;
1485   if (!aDirectRefFeatures.empty()) {
1486     QStringList aDirectRefNames;
1487     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1488       aDirectRefNames.append(aFeature->name().c_str());
1489     aDirectNames = aDirectRefNames.join(", ");
1490
1491     QStringList aIndirectRefNames;
1492     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1493       aIndirectRefNames.append(aFeature->name().c_str());
1494     aIndirectNames = aIndirectRefNames.join(", ");
1495   }
1496
1497   bool aCanReplaceParameters = !aDirectRefFeatures.empty();
1498   QStringList aPartFeatureNames;
1499   foreach (ObjectPtr aObj, theList) {
1500     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1501     // invalid feature data means that the feature is already removed in model,
1502     // we needn't process it. E.g. delete of feature from create operation. The operation abort
1503     // will delete the operation
1504     if (!aFeature->data()->isValid())
1505       continue;
1506     ResultPtr aFirstResult = aFeature->firstResult();
1507     if (!aFirstResult.get())
1508       continue;
1509     std::string aResultGroupName = aFirstResult->groupName();
1510     if (aResultGroupName == ModelAPI_ResultPart::group())
1511       aPartFeatureNames.append(aFeature->name().c_str());
1512
1513     if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
1514       aCanReplaceParameters = false;
1515   }
1516   QString aPartNames = aPartFeatureNames.join(", ");
1517
1518   QMessageBox aMessageBox(theParent);
1519   aMessageBox.setWindowTitle(tr("Delete features"));
1520   aMessageBox.setIcon(QMessageBox::Warning);
1521   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1522   aMessageBox.setDefaultButton(QMessageBox::No);
1523
1524   QString aText;
1525   if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
1526     if (aCanReplaceParameters) {
1527       aText = QString(tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\nOr parameters could be replaced by their values.\n")
1528                       .arg(aDirectNames));
1529       if (!aIndirectNames.isEmpty())
1530         aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1531       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1532     } else {
1533       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
1534       if (!aIndirectNames.isEmpty())
1535         aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1536     }
1537   }
1538   if (!aPartNames.isEmpty())
1539     aText += QString(tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
1540
1541   if (!aText.isEmpty()) {
1542     aText += "Would you like to continue?";
1543     aMessageBox.setText(aText);
1544     aMessageBox.exec();
1545     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1546
1547     if (aButtonRole == QMessageBox::NoRole)
1548       return false;
1549
1550     if (aButtonRole == QMessageBox::ActionRole) {
1551       foreach (ObjectPtr aObj, theList)
1552         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1553       doDeleteReferences = false;
1554     }
1555   }
1556   return true;
1557 }
1558
1559 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theFeatures,
1560                                    const std::set<FeaturePtr>& theIgnoredFeatures)
1561 {
1562   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1563   findReferences(theFeatures, aDirectRefFeatures, aIndirectRefFeatures);
1564   return deleteFeaturesInternal(theFeatures, aDirectRefFeatures, aIndirectRefFeatures,
1565                                 theIgnoredFeatures);
1566 }
1567
1568 bool XGUI_Workshop::deleteFeaturesInternal(const QObjectPtrList& theList,
1569                                            const std::set<FeaturePtr>& aDirectRefFeatures,
1570                                            const std::set<FeaturePtr>& aIndirectRefFeatures,
1571                                            const std::set<FeaturePtr>& theIgnoredFeatures,
1572                                            const bool doDeleteReferences)
1573 {
1574   bool isDone = false;
1575   if (doDeleteReferences) {
1576     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1577     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1578     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1579                                          aLast = aFeaturesToDelete.end();
1580 #ifdef DEBUG_DELETE
1581     QStringList anInfo;
1582 #endif
1583     for (; anIt != aLast; anIt++) {
1584       FeaturePtr aFeature = (*anIt);
1585       DocumentPtr aDoc = aFeature->document();
1586       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1587         // flush REDISPLAY signal after remove feature
1588         aDoc->removeFeature(aFeature);
1589         isDone = true;
1590 #ifdef DEBUG_DELETE
1591         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1592 #endif
1593       }
1594     }
1595 #ifdef DEBUG_DELETE
1596     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1597     anInfo.clear();
1598 #endif
1599   }
1600
1601   QString anActionId = "DELETE_CMD";
1602   isDone = removeFeatures(theList, theIgnoredFeatures, anActionId, false) || isDone;
1603
1604   if (isDone) {
1605     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
1606     // if should be done after removeFeature() of document
1607     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
1608   }
1609   return isDone;
1610 }
1611
1612 //**************************************************************
1613 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1614                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1615                                    const QString& theActionId,
1616                                    const bool theFlushRedisplay)
1617 {
1618   bool isDone = false;
1619
1620   QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1621   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1622   // 4. remove the parameter features
1623   foreach (ObjectPtr aObj, theList) {
1624     // features and parameters can be removed here,
1625     // the results are removed only by a corresponded feature remove
1626     std::string aGroupName = aObj->groupName();
1627     if (!anObjectGroups.contains(aGroupName.c_str()))
1628       continue;
1629
1630     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1631     if (aFeature) {
1632       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1633       // part features are removed in the PartSet module. This condition should be moved there
1634       if (aFeature->getKind() == "Part")
1635         continue;
1636         */
1637       DocumentPtr aDoc = aObj->document();
1638       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1639 #ifdef DEBUG_DELETE
1640         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1641         anInfo.append(anInfoStr);
1642         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1643 #endif
1644         // flush REDISPLAY signal after remove feature
1645         aDoc->removeFeature(aFeature);
1646         isDone = true;
1647       }
1648     }
1649   }
1650   if (isDone && theFlushRedisplay) {
1651     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
1652     // if should be done after removeFeature() of document
1653     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
1654   }
1655
1656 #ifdef DEBUG_DELETE
1657   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1658 #endif
1659   return true;
1660 }
1661
1662 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1663 {
1664   bool isFoundResultType = false;
1665   foreach(ObjectPtr anObj, theObjects)
1666   {
1667     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1668     if (aResult.get() == NULL)
1669       continue;
1670
1671     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1672     if (isFoundResultType)
1673       break;
1674   }
1675   return isFoundResultType;
1676 }
1677
1678 //**************************************************************
1679 // Returns the list of all features for theDocument and all features of
1680 // all nested parts.
1681 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1682 {
1683   std::list<FeaturePtr> aResultList;
1684   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1685   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1686     // The order of appending features of the part and the part itself is important
1687
1688     // Append features from a part feature
1689     foreach (const ResultPtr& aResult, aFeature->results()) {
1690       ResultPartPtr aResultPart =
1691           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1692       if (aResultPart.get() && aResultPart->partDoc().get()) {
1693         // Recursion
1694         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1695         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1696       }
1697     }
1698
1699     aResultList.push_back(aFeature);
1700   }
1701   return aResultList;
1702 }
1703
1704 //**************************************************************
1705 // Returns the list of features placed between theObject and the current feature
1706 // in the same document. Excludes theObject, includes the current feature.
1707 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1708 {
1709   std::list<FeaturePtr> aResult;
1710   DocumentPtr aDocument = theObject->document();
1711   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1712   // find the object iterator
1713   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1714   if (aObjectIt == anAllFeatures.end())
1715     return aResult;
1716   // find the current feature iterator
1717   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1718   if (aCurrentIt == anAllFeatures.end())
1719     return aResult;
1720   // check the right order
1721   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1722     return aResult;
1723   // exclude the object
1724   std::advance(aObjectIt, 1);
1725   // include the current feature
1726   std::advance(aCurrentIt, 1);
1727   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1728 }
1729
1730 bool XGUI_Workshop::canMoveFeature()
1731 {
1732   QString anActionId = "MOVE_CMD";
1733
1734   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1735   QObjectPtrList aValidatedObjects;
1736   foreach (ObjectPtr aObject, aObjects) {
1737     if (!myModule->canApplyAction(aObject, anActionId))
1738       continue;
1739     // To be moved feature should be in active document
1740     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1741       continue;
1742     aValidatedObjects.append(aObject);
1743   }
1744   if (aValidatedObjects.size() != aObjects.size())
1745     aObjects = aValidatedObjects;
1746
1747   bool aCanMove = !aObjects.empty();
1748
1749   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1750   for (; anIt != aLast && aCanMove; anIt++) {
1751     ObjectPtr aObject = *anIt;
1752     // 1. Get features placed between selected and current in the document 
1753     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1754     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1755     if (aFeaturesBetween.empty())
1756       aCanMove = false;
1757     else {
1758       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1759       // 2. Get all reference features to the selected object in the document 
1760       std::set<FeaturePtr> aRefFeatures;
1761       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1762
1763       if (aRefFeatures.empty())
1764         continue;
1765       else {
1766         // 3. Find any placed features in all reference features
1767         std::set<FeaturePtr> aIntersectionFeatures;
1768         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1769                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1770                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1771         // 4. Return false if any reference feature is placed before current feature
1772         if (!aIntersectionFeatures.empty())
1773           aCanMove = false;
1774       }
1775     }
1776   }
1777   return aCanMove;
1778 }
1779
1780 //**************************************************************
1781 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1782 {
1783   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1784   if (!aCanBeShaded) {
1785     ResultCompSolidPtr aCompsolidResult =
1786                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1787     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1788       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1789         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1790     }
1791   }
1792   return aCanBeShaded;
1793 }
1794
1795 //**************************************************************
1796 bool XGUI_Workshop::canChangeColor() const
1797 {
1798   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1799
1800   std::set<std::string> aTypes;
1801   aTypes.insert(ModelAPI_ResultGroup::group());
1802   aTypes.insert(ModelAPI_ResultConstruction::group());
1803   aTypes.insert(ModelAPI_ResultBody::group());
1804   aTypes.insert(ModelAPI_ResultPart::group());
1805
1806   return hasResults(aObjects, aTypes);
1807 }
1808
1809 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1810 {
1811   if (!theResult.get())
1812     return;
1813
1814   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1815   if (aColorAttr.get() != NULL) {
1816     if (!aColorAttr->size()) {
1817       aColorAttr->setSize(3);
1818     }
1819     aColorAttr->setValue(0, theColor[0]);
1820     aColorAttr->setValue(1, theColor[1]);
1821     aColorAttr->setValue(2, theColor[2]);
1822   }
1823 }
1824
1825 //**************************************************************
1826 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1827 {
1828
1829   AttributeIntArrayPtr aColorAttr;
1830   // 1. find the current color of the object. This is a color of AIS presentation
1831   // The objects are iterated until a first valid color is found 
1832   std::vector<int> aColor;
1833   foreach(ObjectPtr anObject, theObjects) {
1834     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1835     if (aResult.get()) {
1836       XGUI_CustomPrs::getResultColor(aResult, aColor);
1837     }
1838     else {
1839       // TODO: remove the obtaining a color from the AIS object
1840       // this does not happen never because:
1841       // 1. The color can be changed only on results
1842       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1843       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1844       if (anAISObj.get()) {
1845         aColor.resize(3);
1846         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1847       }
1848     }
1849     if (!aColor.empty())
1850       break;
1851   }
1852   if (aColor.size() != 3)
1853     return;
1854
1855   if (!abortAllOperations())
1856   return; 
1857   // 2. show the dialog to change the value
1858   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1859   aDlg->setColor(aColor);
1860   aDlg->move(QCursor::pos());
1861   bool isDone = aDlg->exec() == QDialog::Accepted;
1862   if (!isDone)
1863     return;
1864
1865   bool isRandomColor = aDlg->isRandomColor();
1866
1867   // 3. abort the previous operation and start a new one
1868   SessionPtr aMgr = ModelAPI_Session::get();
1869   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1870   aMgr->startOperation(aDescription.toStdString());
1871
1872   // 4. set the value to all results
1873   std::vector<int> aColorResult = aDlg->getColor();
1874   foreach(ObjectPtr anObj, theObjects) {
1875     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1876     if (aResult.get() != NULL) {
1877       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1878       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1879         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1880           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1881         }
1882       }
1883       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1884     }
1885   }
1886   aMgr->finishOperation();
1887   updateCommandStatus();
1888 }
1889
1890 //**************************************************************
1891 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1892 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1893   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1894 }
1895 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1896 {
1897   foreach (ObjectPtr aObj, theList) {
1898     /*
1899     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1900     if (aPartRes) {
1901       DocumentPtr aDoc = aPartRes->partDoc();
1902       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1903       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1904       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1905     } else {
1906     */
1907       aObj->setDisplayed(isVisible);
1908     //}
1909   }
1910   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1911 }
1912
1913 //**************************************************************
1914 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1915 {
1916   // Hide all displayed objects
1917   QObjectPtrList aList = myDisplayer->displayedObjects();
1918   foreach (ObjectPtr aObj, aList) {
1919     if (module()->canEraseObject(aObj))
1920       aObj->setDisplayed(false);
1921   }
1922
1923   // Show only objects from the list
1924   foreach (ObjectPtr aObj, theList) {
1925     /*
1926     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1927     if (aPartRes) {
1928       DocumentPtr aDoc = aPartRes->partDoc();
1929       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1930       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1931       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1932     } else {
1933     */
1934       aObj->setDisplayed(true);
1935     //}
1936   }
1937   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1938
1939 }
1940
1941
1942 //**************************************************************
1943 void XGUI_Workshop::registerValidators() const
1944 {
1945   SessionPtr aMgr = ModelAPI_Session::get();
1946   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1947 }
1948
1949 //**************************************************************
1950 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1951 {
1952   if (!theDoc)
1953     return;
1954   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1955   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1956 }
1957
1958 //**************************************************************
1959 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1960 {
1961   for (int i = 0; i < theDoc->size(theGroup); i++) 
1962     theDoc->object(theGroup, i)->setDisplayed(true);
1963     //displayObject(theDoc->object(theGroup, i));
1964   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1965 }
1966
1967 //**************************************************************
1968 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1969 {
1970   foreach(ObjectPtr aObj, theList) {
1971     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1972
1973     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1974     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1975       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1976           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1977                                       (XGUI_Displayer::DisplayMode)theMode, false);
1978       }
1979     }
1980   }
1981   if (theList.size() > 0)
1982     myDisplayer->updateViewer();
1983 }
1984
1985 //**************************************************************
1986 void XGUI_Workshop::closeDocument()
1987 {
1988   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1989   while (anOperation) {
1990     anOperation->abort();
1991     anOperation = operationMgr()->currentOperation();
1992   }
1993   myDisplayer->closeLocalContexts();
1994   myDisplayer->eraseAll();
1995   objectBrowser()->clearContent();
1996
1997   module()->closeDocument();
1998
1999   SessionPtr aMgr = ModelAPI_Session::get();
2000   aMgr->closeAll();
2001 }
2002
2003 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2004 {
2005   XGUI_HistoryMenu* aMenu = NULL;
2006   if (isSalomeMode()) {
2007     QAction* anAction = qobject_cast<QAction*>(theObject);
2008     if (!anAction)
2009       return;
2010     aMenu = new XGUI_HistoryMenu(anAction);
2011   } else {
2012     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2013     aMenu = new XGUI_HistoryMenu(aButton);
2014   }
2015   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2016   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2017 }
2018
2019 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2020 {
2021   QList<ActionInfo> aResult;
2022   std::list<std::string>::const_iterator it = theList.cbegin();
2023   for (; it != theList.cend(); it++) {
2024     QString anId = QString::fromStdString(*it);
2025     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2026     if (isEditing) {
2027       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2028     }
2029     ActionInfo anInfo;
2030     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2031     if (aContextMenuAct) {
2032       anInfo.initFrom(aContextMenuAct);
2033     } else {
2034       anInfo = myActionsMgr->actionInfoById(anId);
2035     }
2036     if (isEditing) {
2037       anInfo.text = anInfo.text.prepend("Modify ");
2038     }
2039     aResult << anInfo;
2040   }
2041   return aResult;
2042 }
2043
2044 void XGUI_Workshop::synchronizeViewer()
2045 {
2046   SessionPtr aMgr = ModelAPI_Session::get();
2047   DocumentPtr aDoc = aMgr->activeDocument();
2048
2049   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2050   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2051   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2052   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2053 }
2054
2055 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
2056                                              const std::string& theGroup, 
2057                                              bool theUpdateViewer)
2058 {
2059   ObjectPtr aObj;
2060   int aSize = theDoc->size(theGroup);
2061   for (int i = 0; i < aSize; i++) {
2062     aObj = theDoc->object(theGroup, i);
2063     if (aObj->isDisplayed()) {
2064       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2065       // be changed to the object becomes visible when the shape becomes not empty
2066       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2067       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2068         continue;
2069       myDisplayer->display(aObj, false);
2070     }
2071   }
2072   if (theUpdateViewer)
2073     myDisplayer->updateViewer();
2074 }
2075
2076 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2077 {
2078   FeaturePtr aFeature;
2079   QObjectPtrList aSelList = theObjects;
2080   std::list<ResultPtr> aResList;
2081   foreach(ObjectPtr aObj, theObjects) {
2082     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2083     if (aFeature.get()) {
2084       aResList = aFeature->results();
2085       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2086       for(aIt = aResList.cbegin(); aIt != aResList.cend(); aIt++) {
2087         aSelList.append(*aIt);
2088       }
2089     }
2090   }
2091   if (aSelList.count() > theObjects.count()) {
2092     // if something was found
2093     bool aBlocked = objectBrowser()->blockSignals(true);
2094     objectBrowser()->setObjectsSelected(aSelList);
2095     objectBrowser()->blockSignals(aBlocked);
2096   }
2097 }