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