]> 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 = true;//mySalomeConnector->featureInfo(aFeatureKind)->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     aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
617   else
618     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
619
620   ModuleBase_IModule* aModule = module();
621   if (aModule)
622     aModule->grantedOperationIds(theOperation, aGrantedIds);
623
624   aFOperation->setGrantedOperationIds(aGrantedIds);
625 }
626
627
628 /*
629  * Saves document with given name.
630  */
631 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
632 {
633   QApplication::restoreOverrideCursor();
634   SessionPtr aMgr = ModelAPI_Session::get();
635   aMgr->save(theName.toLatin1().constData(), theFileNames);
636   QApplication::restoreOverrideCursor();
637 }
638
639 bool XGUI_Workshop::abortAllOperations()
640 {
641   return myOperationMgr->abortAllOperations();
642 }
643
644 //******************************************************
645 void XGUI_Workshop::onOpen()
646 {
647   if(!abortAllOperations())
648     return;
649   //save current file before close if modified
650   SessionPtr aSession = ModelAPI_Session::get();
651   if (aSession->isModified()) {
652     //TODO(sbh): re-launch the app?
653     int anAnswer = QMessageBox::question(
654         desktop(), tr("Save current file"),
655         tr("The document is modified, save before opening another?"),
656         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
657     if (anAnswer == QMessageBox::Save) {
658       onSave();
659     } else if (anAnswer == QMessageBox::Cancel) {
660       return;
661     }
662     myCurrentDir = "";
663   }
664
665   //show file dialog, check if readable and open
666   myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
667   if (myCurrentDir.isEmpty())
668     return;
669   QFileInfo aFileInfo(myCurrentDir);
670   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
671     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
672     myCurrentDir = "";
673     return;
674   }
675   QApplication::setOverrideCursor(Qt::WaitCursor);
676   aSession->closeAll();
677   aSession->load(myCurrentDir.toLatin1().constData());
678   myObjectBrowser->rebuildDataTree();
679   updateCommandStatus();
680   QApplication::restoreOverrideCursor();
681 }
682
683 //******************************************************
684 void XGUI_Workshop::onNew()
685 {
686   QApplication::setOverrideCursor(Qt::WaitCursor);
687   if (objectBrowser() == 0) {
688     createDockWidgets();
689     mySelector->connectViewers();
690   }
691   myViewerProxy->connectToViewer();
692   showObjectBrowser();
693 #ifndef HAVE_SALOME
694   myMainWindow->showPythonConsole();
695   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
696   aWnd->showMaximized();
697   updateCommandStatus();
698 #endif
699   myContextMenuMgr->connectViewer();
700   QApplication::restoreOverrideCursor();
701 }
702
703 #ifndef HAVE_SALOME
704 //******************************************************
705 void XGUI_Workshop::onExit()
706 {
707   SessionPtr aMgr = ModelAPI_Session::get();
708   if (aMgr->isModified()) {
709     int anAnswer = QMessageBox::question(
710         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
711         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
712     if (anAnswer == QMessageBox::Save) {
713       bool saved = onSave();
714       if (!saved) {
715         return;
716       }
717     } else if (anAnswer == QMessageBox::Cancel) {
718       return;
719     }
720   }
721   qApp->exit();
722 }
723
724 //******************************************************
725 void XGUI_Workshop::onPreferences()
726 {
727   ModuleBase_Prefs aModif;
728   ModuleBase_Preferences::editPreferences(aModif);
729   if (aModif.size() > 0) {
730     QString aSection;
731     foreach (ModuleBase_Pref aPref, aModif)
732     {
733       aSection = aPref.first;
734       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
735         myMainWindow->viewer()->updateFromResources();
736       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
737         myMainWindow->menuObject()->updateFromResources();
738       }
739     }
740     displayer()->redisplayObjects();
741   }
742 }
743 #endif
744
745 //******************************************************
746 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
747 {
748   XGUI_Displayer* aDisplayer = displayer();
749   if (aDisplayer)
750     aDisplayer->displayTrihedron(theState);
751 }
752
753 //******************************************************
754 bool XGUI_Workshop::onSave()
755 {
756   if(!abortAllOperations())
757     return false;
758   if (myCurrentDir.isEmpty()) {
759     return onSaveAs();
760   }
761   std::list<std::string> aFiles;
762   saveDocument(myCurrentDir, aFiles);
763   updateCommandStatus();
764 #ifndef HAVE_SALOME
765     myMainWindow->setModifiedState(false);
766 #endif
767   return true;
768 }
769
770 //******************************************************
771 bool XGUI_Workshop::onSaveAs()
772 {
773   if(!abortAllOperations())
774     return false;
775   QFileDialog dialog(desktop());
776   dialog.setWindowTitle(tr("Select directory to save files..."));
777   dialog.setFileMode(QFileDialog::Directory);
778   dialog.setFilter(tr("Directories (*)"));
779   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
780   dialog.setViewMode(QFileDialog::Detail);
781
782   if (!dialog.exec()) {
783     return false;
784   }
785
786   QString aTempDir = dialog.selectedFiles().first();
787   QDir aDir(aTempDir);
788   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
789     int answer = QMessageBox::question(
790         desktop(),
791         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
792         tr("Save"),
793         tr("The directory already contains some files, save anyway?"),
794         QMessageBox::Save | QMessageBox::Cancel);
795     if (answer == QMessageBox::Cancel) {
796       return false;
797     }
798   }
799   myCurrentDir = aTempDir;
800 #ifndef HAVE_SALOME
801     myMainWindow->setCurrentDir(myCurrentDir, false);
802     myMainWindow->setModifiedState(false);
803 #endif
804   return onSave();
805 }
806
807 //******************************************************
808 void XGUI_Workshop::onUndo(int theTimes)
809 {
810   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
811   SessionPtr aMgr = ModelAPI_Session::get();
812   std::list<std::string> aUndoList = aMgr->undoList();
813   if (aMgr->isOperation()) {
814     /// this is important for nested operations
815     /// when sketch operation is active, this condition is false and
816     /// the sketch operation is not aborted
817     operationMgr()->onAbortOperation();
818   }
819   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
820   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
821     aMgr->undo();
822     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
823       myObjectBrowser->rebuildDataTree();
824   }
825
826   operationMgr()->updateApplyOfOperations();
827   updateCommandStatus();
828 }
829
830 //******************************************************
831 void XGUI_Workshop::onRedo(int theTimes)
832 {
833   // the viewer update should be blocked in order to avoid the features blinking. For the created
834   // feature a results are created, the flush of the created signal caused the viewer redisplay for
835   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
836   // redo of all possible objects happens
837   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
838
839   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
840   SessionPtr aMgr = ModelAPI_Session::get();
841   std::list<std::string> aRedoList = aMgr->redoList();
842   if (aMgr->isOperation()) {
843     /// this is important for nested operations
844     /// when sketch operation is active, this condition is false and
845     /// the sketch operation is not aborted
846     operationMgr()->onAbortOperation();
847   }
848   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
849   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
850     aMgr->redo();
851     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
852       myObjectBrowser->rebuildDataTree();
853   }
854   operationMgr()->updateApplyOfOperations();
855   updateCommandStatus();
856
857   // unblock the viewer update functionality and make update on purpose
858   myDisplayer->enableUpdateViewer(isUpdateEnabled);
859   myDisplayer->updateViewer();
860 }
861
862 //******************************************************
863 //void XGUI_Workshop::onRebuild()
864 //{
865 //  SessionPtr aMgr = ModelAPI_Session::get();
866 //  bool aWasOperation = aMgr->isOperation(); // keep this value
867 //  if (!aWasOperation) {
868 //    aMgr->startOperation("Rebuild");
869 //  }
870 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
871 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
872 //    new Events_Message(aRebuildEvent, this)));
873 //  if (!aWasOperation) {
874 //    aMgr->finishOperation();
875 //  }
876 //  updateCommandStatus();
877 //}
878
879 //******************************************************
880 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
881 {
882   ModuleBase_ModelWidget* anActiveWidget = 0;
883   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
884   if (anOperation) {
885     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
886     if (aPanel)
887       anActiveWidget = aPanel->activeWidget();
888   }
889   if (anActiveWidget)
890     operationMgr()->onValidateOperation();
891
892   myModule->widgetStateChanged(thePreviousState);
893 }
894
895 //******************************************************
896 void XGUI_Workshop::onValuesChanged()
897 {
898   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
899   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
900     return;
901
902   ModuleBase_ModelWidget* anActiveWidget = 0;
903   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
904   if (anOperation) {
905     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
906     if (aPanel)
907       anActiveWidget = aPanel->activeWidget();
908   }
909   if (anActiveWidget) {
910     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
911                                                                            (anActiveWidget);
912     if (aWidgetValidated)
913       aWidgetValidated->clearValidatedCash();
914   }
915 }
916
917 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
918 {
919   QString libName = QString::fromStdString(library(theModule.toStdString()));
920   if (libName.isEmpty()) {
921     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
922     return 0;
923   }
924
925   QString err;
926   CREATE_FUNC crtInst = 0;
927
928 #ifdef WIN32
929   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
930   if (!modLib) {
931     LPVOID lpMsgBuf;
932     ::FormatMessage(
933         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
934         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
935     QString aMsg((char*) &lpMsgBuf);
936     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
937     ::LocalFree(lpMsgBuf);
938   } else {
939     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
940     if (!crtInst) {
941       LPVOID lpMsgBuf;
942       ::FormatMessage(
943           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
944               | FORMAT_MESSAGE_IGNORE_INSERTS,
945           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
946       QString aMsg((char*) &lpMsgBuf);
947       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
948       ::LocalFree(lpMsgBuf);
949     }
950   }
951 #else
952   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
953   if ( !modLib ) {
954     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
955   } else {
956     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
957     if ( !crtInst ) {
958       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
959     }
960   }
961 #endif
962
963   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
964
965   if (!err.isEmpty()) {
966     if (desktop()) {
967       Events_Error::send(err.toStdString());
968     } else {
969       qWarning(qPrintable(err));
970     }
971   }
972   return aModule;
973 }
974
975 //******************************************************
976 bool XGUI_Workshop::createModule()
977 {
978   Config_ModuleReader aModuleReader;
979   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
980   myModule = loadModule(moduleName);
981   if (!myModule)
982     return false;
983
984   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
985   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
986   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
987   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
988
989   myModule->createFeatures();
990   //myActionsMgr->update();
991   return true;
992 }
993
994 //******************************************************
995 void XGUI_Workshop::updateCommandStatus()
996 {
997   QList<QAction*> aCommands;
998 #ifdef HAVE_SALOME
999     aCommands = salomeConnector()->commandList();
1000 #else
1001     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1002     foreach (AppElements_Command* aCmd, aMenuBar->features())
1003       aCommands.append(aCmd);
1004 #endif
1005   SessionPtr aMgr = ModelAPI_Session::get();
1006   if (aMgr->hasModuleDocument()) {
1007     foreach(QAction* aCmd, aCommands) {
1008       QString aId = aCmd->data().toString();
1009       if (aId == "UNDO_CMD")
1010         aCmd->setEnabled(myModule->canUndo());
1011       else if (aId == "REDO_CMD")
1012         aCmd->setEnabled(myModule->canRedo());
1013       else
1014         // Enable all commands
1015         aCmd->setEnabled(true);
1016     }
1017     updateHistory();
1018   } else {
1019     foreach(QAction* aCmd, aCommands) {
1020       QString aId = aCmd->data().toString();
1021       if (aId == "NEW_CMD")
1022         aCmd->setEnabled(true);
1023       else if (aId == "EXIT_CMD")
1024         aCmd->setEnabled(true);
1025       else
1026         aCmd->setEnabled(false);
1027     }
1028   }
1029   myActionsMgr->updateCommandsStatus();
1030   emit commandStatusUpdated();
1031 }
1032
1033 void XGUI_Workshop::updateHistory()
1034 {
1035   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1036   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1037   emit updateUndoHistory(aUndoRes);
1038
1039   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1040   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1041   emit updateRedoHistory(aRedoRes);
1042 }
1043
1044 //******************************************************
1045 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1046 {
1047   QDockWidget* aObjDock = new QDockWidget(theParent);
1048   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1049   aObjDock->setWindowTitle(tr("Object browser"));
1050   aObjDock->setStyleSheet(
1051       "::title { position: relative; padding-left: 5px; text-align: left center }");
1052   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1053   myModule->customizeObjectBrowser(myObjectBrowser);
1054   aObjDock->setWidget(myObjectBrowser);
1055
1056   myContextMenuMgr->connectObjectBrowser();
1057   return aObjDock;
1058 }
1059
1060 //******************************************************
1061 /*
1062  * Creates dock widgets, places them in corresponding area
1063  * and tabifies if necessary.
1064  */
1065 void XGUI_Workshop::createDockWidgets()
1066 {
1067   QMainWindow* aDesktop = desktop();
1068   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1069   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1070   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1071   myPropertyPanel->setupActions(myActionsMgr);
1072   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1073   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1074   hidePropertyPanel();  ///<! Invisible by default
1075   hideObjectBrowser();
1076   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1077   myPropertyPanel->installEventFilter(myOperationMgr);
1078
1079   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1080   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1081
1082   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1083   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1084
1085   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1086   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreivewActionClicked()));
1087
1088   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1089           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1090   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1091           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1092 }
1093
1094 //******************************************************
1095 void XGUI_Workshop::showPropertyPanel()
1096 {
1097   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1098   ///<! Restore ability to close panel from the window's menu
1099   aViewAct->setEnabled(true);
1100   myPropertyPanel->show();
1101   myPropertyPanel->raise();
1102
1103   // The next code is necessary to made the property panel the active window
1104   // in order to operation manager could process key events of the panel.
1105   // otherwise they are ignored. It happens only if the same(activateWindow) is
1106   // not happened by property panel activation(e.g. resume operation of Sketch)
1107   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1108   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1109 }
1110
1111 //******************************************************
1112 void XGUI_Workshop::hidePropertyPanel()
1113 {
1114   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1115   ///<! Do not allow to show empty property panel
1116   aViewAct->setEnabled(false);
1117   myPropertyPanel->hide();
1118
1119   // the property panel is active window of the desktop, when it is
1120   // hidden, it is undefined which window becomes active. By this reason
1121   // it is defined to perform the desktop as the active window.
1122   // in SALOME mode, workstack made the PyConsole the active window,
1123   // set the focus on it. As a result, shortcuts of the application, like
1124   // are processed by this console. For example Undo actions.
1125   // It is possible that this code is to be moved to SHAPER package
1126   QMainWindow* aDesktop = desktop();
1127   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1128   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1129 }
1130
1131 //******************************************************
1132 void XGUI_Workshop::showObjectBrowser()
1133 {
1134   if (!isSalomeMode())
1135     myObjectBrowser->parentWidget()->show();
1136 }
1137
1138 //******************************************************
1139 void XGUI_Workshop::hideObjectBrowser()
1140 {
1141   if (!isSalomeMode())
1142     myObjectBrowser->parentWidget()->hide();
1143 }
1144
1145 //******************************************************
1146 void XGUI_Workshop::salomeViewerSelectionChanged()
1147 {
1148   emit salomeViewerSelection();
1149 }
1150
1151 //**************************************************************
1152 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1153 {
1154   return mySalomeConnector->viewer();
1155 }
1156
1157 //**************************************************************
1158 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1159 {
1160   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1161   if (theId == "DELETE_CMD")
1162     deleteObjects();
1163   else if (theId == "CLEAN_HISTORY_CMD")
1164     cleanHistory();
1165   else if (theId == "MOVE_CMD")
1166     moveObjects();
1167   else if (theId == "COLOR_CMD")
1168     changeColor(aObjects);
1169   else if (theId == "SHOW_CMD") {
1170     showObjects(aObjects, true);
1171     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1172   }
1173   else if (theId == "HIDE_CMD")
1174     showObjects(aObjects, false);
1175   else if (theId == "SHOW_ONLY_CMD") {
1176     showOnlyObjects(aObjects);
1177     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1178   }
1179   else if (theId == "SHADING_CMD")
1180     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1181   else if (theId == "WIREFRAME_CMD")
1182     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1183   else if (theId == "HIDEALL_CMD") {
1184     QObjectPtrList aList = myDisplayer->displayedObjects();
1185     foreach (ObjectPtr aObj, aList) {
1186       if (module()->canEraseObject(aObj))
1187         aObj->setDisplayed(false);
1188     }
1189     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1190   } else if (theId == "SELECT_VERTEX_CMD") {
1191     setViewerSelectionMode(TopAbs_VERTEX);
1192   } else if (theId == "SELECT_EDGE_CMD") {
1193     setViewerSelectionMode(TopAbs_EDGE);
1194   } else if (theId == "SELECT_FACE_CMD") {
1195     setViewerSelectionMode(TopAbs_FACE);
1196   } else if (theId == "SELECT_RESULT_CMD") {
1197     setViewerSelectionMode(-1);
1198   } else if (theId == "SHOW_RESULTS_CMD") {
1199     highlightResults(aObjects);
1200   }
1201 }
1202
1203 //**************************************************************
1204 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1205 {
1206   myViewerSelMode = theMode;
1207   activateObjectsSelection(myDisplayer->displayedObjects());
1208 }
1209
1210 //**************************************************************
1211 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1212 {
1213   QIntList aModes;
1214   module()->activeSelectionModes(aModes);
1215   if (aModes.isEmpty() && (myViewerSelMode != -1))
1216     aModes.append(myViewerSelMode);
1217   myDisplayer->activateObjects(aModes, theList);
1218 }
1219
1220
1221 //**************************************************************
1222 void XGUI_Workshop::deleteObjects()
1223 {
1224   ModuleBase_IModule* aModule = module();
1225   // 1. allow the module to delete objects, do nothing if it has succeed
1226   if (aModule->deleteObjects()) {
1227     updateCommandStatus();
1228     return;
1229   }
1230
1231   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1232   if (!abortAllOperations())
1233     return;
1234   // check whether the object can be deleted. There should not be parts which are not loaded
1235   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1236     return;
1237
1238   bool hasResult = false;
1239   bool hasFeature = false;
1240   bool hasParameter = false;
1241   bool hasCompositeOwner = false;
1242   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1243   if (!(hasFeature || hasParameter))
1244     return;
1245
1246   // 3. delete objects
1247   std::set<FeaturePtr> anIgnoredFeatures;
1248   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1249   findReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures);
1250
1251   bool doDeleteReferences = true;
1252   if (isDeleteFeatureWithReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1253                                     desktop(), doDeleteReferences)) {
1254     // start operation
1255     QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1256     aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1257     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1258     operationMgr()->startOperation(anOpAction);
1259
1260     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1261     // It is necessary to clear selection in order to avoid selection changed event during
1262     // deletion and negative consequences connected with processing of already deleted items
1263     mySelector->clearSelection();
1264
1265     // delete and commit/abort operation in model
1266     if (deleteFeaturesInternal(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1267                                anIgnoredFeatures, doDeleteReferences))
1268       operationMgr()->commitOperation();
1269     else
1270       operationMgr()->abortOperation(operationMgr()->currentOperation());
1271   }
1272 }
1273
1274 //**************************************************************
1275 void XGUI_Workshop::cleanHistory()
1276 {
1277   if (!abortAllOperations())
1278     return;
1279
1280   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1281   QObjectPtrList aFeatures;
1282   foreach (ObjectPtr anObject, anObjects) {
1283     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1284     // for parameter result, use the corresponded reature to be removed
1285     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1286       aFeature = ModelAPI_Feature::feature(anObject);
1287     }
1288     aFeatures.append(aFeature);
1289   }
1290
1291   // 1. find all referenced features
1292   QList<ObjectPtr> anUnusedObjects;
1293   std::set<FeaturePtr> aDirectRefFeatures;
1294   //foreach (ObjectPtr anObject, anObjects) {
1295   foreach (ObjectPtr anObject, aFeatures) {
1296     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1297     // for parameter result, use the corresponded reature to be removed
1298     //if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1299     //  aFeature = ModelAPI_Feature::feature(anObject);
1300     //}
1301     if (aFeature.get()) {
1302       std::set<FeaturePtr> alreadyProcessed;
1303       aDirectRefFeatures.clear();
1304       XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, aFeatures,
1305                                                     aDirectRefFeatures, alreadyProcessed);
1306       if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1307         anUnusedObjects.append(aFeature);
1308     }
1309   }
1310
1311   // 2. warn about the references remove, break the delete operation if the user chose it
1312   if (!anUnusedObjects.empty()) {
1313     QStringList aNames;
1314     foreach (const ObjectPtr& anObject, anUnusedObjects) {
1315       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1316       aNames.append(aFeature->name().c_str());
1317     }
1318     QString anUnusedNames = aNames.join(", ");
1319
1320     QString anActionId = "CLEAN_HISTORY_CMD";
1321     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1322
1323     QMessageBox aMessageBox(desktop());
1324     aMessageBox.setWindowTitle(aDescription);
1325     aMessageBox.setIcon(QMessageBox::Warning);
1326     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1327     aMessageBox.setDefaultButton(QMessageBox::No);
1328
1329     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1330                    .arg(anUnusedNames));
1331     /*QString aText;
1332     if (anUnusedNames.isEmpty()) {
1333       aMessageBox.setStandardButtons(QMessageBox::Ok);
1334       aMessageBox.setDefaultButton(QMessageBox::Ok);
1335
1336       aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1337     }
1338     else {
1339       aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1340       aMessageBox.setDefaultButton(QMessageBox::No);
1341
1342       aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1343         .arg(anUnusedNames));
1344     }*/
1345
1346     aMessageBox.setText(aText);
1347     if (aMessageBox.exec() == QMessageBox::No)
1348       return;
1349
1350     // 1. start operation
1351     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1352     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1353     operationMgr()->startOperation(anOpAction);
1354
1355     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1356     // It is necessary to clear selection in order to avoid selection changed event during
1357     // deletion and negative consequences connected with processing of already deleted items
1358     mySelector->clearSelection();
1359
1360     std::set<FeaturePtr> anIgnoredFeatures;
1361     if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId)) {
1362       operationMgr()->commitOperation();
1363     }
1364     else {
1365       operationMgr()->abortOperation(operationMgr()->currentOperation());
1366     }
1367   }
1368   else {
1369     QString anActionId = "CLEAN_HISTORY_CMD";
1370     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1371
1372     QMessageBox aMessageBox(desktop());
1373     aMessageBox.setWindowTitle(aDescription);
1374     aMessageBox.setIcon(QMessageBox::Warning);
1375     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1376     aMessageBox.setDefaultButton(QMessageBox::No);
1377
1378     QString aText;
1379     aMessageBox.setStandardButtons(QMessageBox::Ok);
1380     aMessageBox.setDefaultButton(QMessageBox::Ok);
1381
1382     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1383     aMessageBox.setText(aText);
1384
1385     if (aMessageBox.exec() == QMessageBox::No)
1386       return;
1387   }
1388 }
1389
1390 //**************************************************************
1391 void XGUI_Workshop::moveObjects()
1392 {
1393   if (!abortAllOperations())
1394     return;
1395
1396   SessionPtr aMgr = ModelAPI_Session::get();
1397
1398   QString anActionId = "MOVE_CMD";
1399   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1400   aMgr->startOperation(aDescription.toStdString());
1401
1402   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1403   // It is necessary to clear selection in order to avoid selection changed event during
1404   // moving and negative consequences connected with processing of already moved items
1405   mySelector->clearSelection();
1406   // check whether the object can be moved. There should not be parts which are not loaded
1407   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1408     return;
1409
1410   DocumentPtr anActiveDocument = aMgr->activeDocument();
1411   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1412   foreach (ObjectPtr aObject, anObjects) {
1413     if (!myModule->canApplyAction(aObject, anActionId))
1414       continue;
1415
1416     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1417     if (aFeature.get()) {
1418       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1419       aCurrentFeature = anActiveDocument->currentFeature(true);
1420     }
1421   }
1422   aMgr->finishOperation();
1423 }
1424
1425 //**************************************************************
1426 void XGUI_Workshop::findReferences(const QObjectPtrList& theList,
1427                                    std::set<FeaturePtr>& aDirectRefFeatures,
1428                                    std::set<FeaturePtr>& aIndirectRefFeatures)
1429 {
1430   foreach (ObjectPtr aDeletedObj, theList) {
1431     std::set<FeaturePtr> alreadyProcessed;
1432     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1433                                             aIndirectRefFeatures, alreadyProcessed);
1434     std::set<FeaturePtr> aDifference;
1435     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1436                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1437                         std::inserter(aDifference, aDifference.begin()));
1438     aIndirectRefFeatures = aDifference;
1439   }
1440 }
1441
1442 bool XGUI_Workshop::isDeleteFeatureWithReferences(const QObjectPtrList& theList,
1443                                    const std::set<FeaturePtr>& aDirectRefFeatures,
1444                                    const std::set<FeaturePtr>& aIndirectRefFeatures,
1445                                    QWidget* theParent,
1446                                    bool& doDeleteReferences)
1447 {
1448   doDeleteReferences = true;
1449
1450   QString aDirectNames, aIndirectNames;
1451   if (!aDirectRefFeatures.empty()) {
1452     QStringList aDirectRefNames;
1453     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1454       aDirectRefNames.append(aFeature->name().c_str());
1455     aDirectNames = aDirectRefNames.join(", ");
1456
1457     QStringList aIndirectRefNames;
1458     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1459       aIndirectRefNames.append(aFeature->name().c_str());
1460     aIndirectNames = aIndirectRefNames.join(", ");
1461   }
1462
1463   bool aCanReplaceParameters = !aDirectRefFeatures.empty();
1464   QStringList aPartFeatureNames;
1465   foreach (ObjectPtr aObj, theList) {
1466     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1467     // invalid feature data means that the feature is already removed in model,
1468     // we needn't process it. E.g. delete of feature from create operation. The operation abort
1469     // will delete the operation
1470     if (!aFeature->data()->isValid())
1471       continue;
1472     ResultPtr aFirstResult = aFeature->firstResult();
1473     if (!aFirstResult.get())
1474       continue;
1475     std::string aResultGroupName = aFirstResult->groupName();
1476     if (aResultGroupName == ModelAPI_ResultPart::group())
1477       aPartFeatureNames.append(aFeature->name().c_str());
1478
1479     if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
1480       aCanReplaceParameters = false;
1481   }
1482   QString aPartNames = aPartFeatureNames.join(", ");
1483
1484   QMessageBox aMessageBox(theParent);
1485   aMessageBox.setWindowTitle(tr("Delete features"));
1486   aMessageBox.setIcon(QMessageBox::Warning);
1487   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1488   aMessageBox.setDefaultButton(QMessageBox::No);
1489
1490   QString aText;
1491   if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
1492     if (aCanReplaceParameters) {
1493       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")
1494                       .arg(aDirectNames));
1495       if (!aIndirectNames.isEmpty())
1496         aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1497       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1498     } else {
1499       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
1500       if (!aIndirectNames.isEmpty())
1501         aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1502     }
1503   }
1504   if (!aPartNames.isEmpty())
1505     aText += QString(tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
1506
1507   if (!aText.isEmpty()) {
1508     aText += "Would you like to continue?";
1509     aMessageBox.setText(aText);
1510     aMessageBox.exec();
1511     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1512
1513     if (aButtonRole == QMessageBox::NoRole)
1514       return false;
1515
1516     if (aButtonRole == QMessageBox::ActionRole) {
1517       foreach (ObjectPtr aObj, theList)
1518         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1519       doDeleteReferences = false;
1520     }
1521   }
1522   return true;
1523 }
1524
1525 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theFeatures,
1526                                    const std::set<FeaturePtr>& theIgnoredFeatures)
1527 {
1528   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1529   findReferences(theFeatures, aDirectRefFeatures, aIndirectRefFeatures);
1530   return deleteFeaturesInternal(theFeatures, aDirectRefFeatures, aIndirectRefFeatures,
1531                                 theIgnoredFeatures);
1532 }
1533
1534 bool XGUI_Workshop::deleteFeaturesInternal(const QObjectPtrList& theList,
1535                                            const std::set<FeaturePtr>& aDirectRefFeatures,
1536                                            const std::set<FeaturePtr>& aIndirectRefFeatures,
1537                                            const std::set<FeaturePtr>& theIgnoredFeatures,
1538                                            const bool doDeleteReferences)
1539 {
1540   if (doDeleteReferences) {
1541     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1542     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1543     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1544                                          aLast = aFeaturesToDelete.end();
1545 #ifdef DEBUG_DELETE
1546     QStringList anInfo;
1547 #endif
1548     for (; anIt != aLast; anIt++) {
1549       FeaturePtr aFeature = (*anIt);
1550       DocumentPtr aDoc = aFeature->document();
1551       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1552         aDoc->removeFeature(aFeature);
1553 #ifdef DEBUG_DELETE
1554         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1555 #endif
1556       }
1557     }
1558 #ifdef DEBUG_DELETE
1559     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1560     anInfo.clear();
1561 #endif
1562   }
1563
1564   QString anActionId = "DELETE_CMD";
1565   return removeFeatures(theList, theIgnoredFeatures, anActionId);
1566 }
1567
1568 //**************************************************************
1569 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1570                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1571                                    const QString& theActionId)
1572 {
1573   bool isDone = false;
1574
1575   QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1576   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1577   // 4. remove the parameter features
1578   foreach (ObjectPtr aObj, theList) {
1579     // features and parameters can be removed here,
1580     // the results are removed only by a corresponded feature remove
1581     std::string aGroupName = aObj->groupName();
1582     if (!anObjectGroups.contains(aGroupName.c_str()))
1583       continue;
1584
1585     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1586     if (aFeature) {
1587       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1588       // part features are removed in the PartSet module. This condition should be moved there
1589       if (aFeature->getKind() == "Part")
1590         continue;
1591         */
1592       DocumentPtr aDoc = aObj->document();
1593       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1594 #ifdef DEBUG_DELETE
1595         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1596         anInfo.append(anInfoStr);
1597         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1598 #endif
1599         aDoc->removeFeature(aFeature);
1600         isDone = true;
1601       }
1602     }
1603   }
1604 #ifdef DEBUG_DELETE
1605   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1606 #endif
1607   return true;
1608 }
1609
1610 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1611 {
1612   bool isFoundResultType = false;
1613   foreach(ObjectPtr anObj, theObjects)
1614   {
1615     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1616     if (aResult.get() == NULL)
1617       continue;
1618
1619     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1620     if (isFoundResultType)
1621       break;
1622   }
1623   return isFoundResultType;
1624 }
1625
1626 //**************************************************************
1627 // Returns the list of all features for theDocument and all features of
1628 // all nested parts.
1629 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1630 {
1631   std::list<FeaturePtr> aResultList;
1632   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1633   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1634     // The order of appending features of the part and the part itself is important
1635
1636     // Append features from a part feature
1637     foreach (const ResultPtr& aResult, aFeature->results()) {
1638       ResultPartPtr aResultPart =
1639           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1640       if (aResultPart.get() && aResultPart->partDoc().get()) {
1641         // Recursion
1642         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1643         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1644       }
1645     }
1646
1647     aResultList.push_back(aFeature);
1648   }
1649   return aResultList;
1650 }
1651
1652 //**************************************************************
1653 // Returns the list of features placed between theObject and the current feature
1654 // in the same document. Excludes theObject, includes the current feature.
1655 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1656 {
1657   std::list<FeaturePtr> aResult;
1658   DocumentPtr aDocument = theObject->document();
1659   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1660   // find the object iterator
1661   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1662   if (aObjectIt == anAllFeatures.end())
1663     return aResult;
1664   // find the current feature iterator
1665   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1666   if (aCurrentIt == anAllFeatures.end())
1667     return aResult;
1668   // check the right order
1669   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1670     return aResult;
1671   // exclude the object
1672   std::advance(aObjectIt, 1);
1673   // include the current feature
1674   std::advance(aCurrentIt, 1);
1675   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1676 }
1677
1678 bool XGUI_Workshop::canMoveFeature()
1679 {
1680   QString anActionId = "MOVE_CMD";
1681
1682   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1683   QObjectPtrList aValidatedObjects;
1684   foreach (ObjectPtr aObject, aObjects) {
1685     if (!myModule->canApplyAction(aObject, anActionId))
1686       continue;
1687     // To be moved feature should be in active document
1688     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1689       continue;
1690     aValidatedObjects.append(aObject);
1691   }
1692   if (aValidatedObjects.size() != aObjects.size())
1693     aObjects = aValidatedObjects;
1694
1695   bool aCanMove = !aObjects.empty();
1696
1697   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1698   for (; anIt != aLast && aCanMove; anIt++) {
1699     ObjectPtr aObject = *anIt;
1700     // 1. Get features placed between selected and current in the document 
1701     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1702     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1703     if (aFeaturesBetween.empty())
1704       aCanMove = false;
1705     else {
1706       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1707       // 2. Get all reference features to the selected object in the document 
1708       std::set<FeaturePtr> aRefFeatures;
1709       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1710
1711       if (aRefFeatures.empty())
1712         continue;
1713       else {
1714         // 3. Find any placed features in all reference features
1715         std::set<FeaturePtr> aIntersectionFeatures;
1716         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1717                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1718                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1719         // 4. Return false if any reference feature is placed before current feature
1720         if (!aIntersectionFeatures.empty())
1721           aCanMove = false;
1722       }
1723     }
1724   }
1725   return aCanMove;
1726 }
1727
1728 //**************************************************************
1729 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1730 {
1731   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1732   if (!aCanBeShaded) {
1733     ResultCompSolidPtr aCompsolidResult =
1734                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1735     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1736       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1737         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1738     }
1739   }
1740   return aCanBeShaded;
1741 }
1742
1743 //**************************************************************
1744 bool XGUI_Workshop::canChangeColor() const
1745 {
1746   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1747
1748   std::set<std::string> aTypes;
1749   aTypes.insert(ModelAPI_ResultGroup::group());
1750   aTypes.insert(ModelAPI_ResultConstruction::group());
1751   aTypes.insert(ModelAPI_ResultBody::group());
1752   aTypes.insert(ModelAPI_ResultPart::group());
1753
1754   return hasResults(aObjects, aTypes);
1755 }
1756
1757 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1758 {
1759   if (!theResult.get())
1760     return;
1761
1762   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1763   if (aColorAttr.get() != NULL) {
1764     if (!aColorAttr->size()) {
1765       aColorAttr->setSize(3);
1766     }
1767     aColorAttr->setValue(0, theColor[0]);
1768     aColorAttr->setValue(1, theColor[1]);
1769     aColorAttr->setValue(2, theColor[2]);
1770   }
1771 }
1772
1773 //**************************************************************
1774 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1775 {
1776
1777   AttributeIntArrayPtr aColorAttr;
1778   // 1. find the current color of the object. This is a color of AIS presentation
1779   // The objects are iterated until a first valid color is found 
1780   std::vector<int> aColor;
1781   foreach(ObjectPtr anObject, theObjects) {
1782     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1783     if (aResult.get()) {
1784       XGUI_CustomPrs::getResultColor(aResult, aColor);
1785     }
1786     else {
1787       // TODO: remove the obtaining a color from the AIS object
1788       // this does not happen never because:
1789       // 1. The color can be changed only on results
1790       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1791       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1792       if (anAISObj.get()) {
1793         aColor.resize(3);
1794         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1795       }
1796     }
1797     if (!aColor.empty())
1798       break;
1799   }
1800   if (aColor.size() != 3)
1801     return;
1802
1803   if (!abortAllOperations())
1804   return; 
1805   // 2. show the dialog to change the value
1806   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1807   aDlg->setColor(aColor);
1808   aDlg->move(QCursor::pos());
1809   bool isDone = aDlg->exec() == QDialog::Accepted;
1810   if (!isDone)
1811     return;
1812
1813   bool isRandomColor = aDlg->isRandomColor();
1814
1815   // 3. abort the previous operation and start a new one
1816   SessionPtr aMgr = ModelAPI_Session::get();
1817   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1818   aMgr->startOperation(aDescription.toStdString());
1819
1820   // 4. set the value to all results
1821   std::vector<int> aColorResult = aDlg->getColor();
1822   foreach(ObjectPtr anObj, theObjects) {
1823     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1824     if (aResult.get() != NULL) {
1825       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1826       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1827         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1828           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1829         }
1830       }
1831       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1832     }
1833   }
1834   aMgr->finishOperation();
1835   updateCommandStatus();
1836 }
1837
1838 //**************************************************************
1839 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1840 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1841   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1842 }
1843 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1844 {
1845   foreach (ObjectPtr aObj, theList) {
1846     /*
1847     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1848     if (aPartRes) {
1849       DocumentPtr aDoc = aPartRes->partDoc();
1850       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1851       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1852       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1853     } else {
1854     */
1855       aObj->setDisplayed(isVisible);
1856     //}
1857   }
1858   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1859 }
1860
1861 //**************************************************************
1862 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1863 {
1864   // Hide all displayed objects
1865   QObjectPtrList aList = myDisplayer->displayedObjects();
1866   foreach (ObjectPtr aObj, aList) {
1867     if (module()->canEraseObject(aObj))
1868       aObj->setDisplayed(false);
1869   }
1870
1871   // Show only objects from the list
1872   foreach (ObjectPtr aObj, theList) {
1873     /*
1874     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1875     if (aPartRes) {
1876       DocumentPtr aDoc = aPartRes->partDoc();
1877       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1878       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1879       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1880     } else {
1881     */
1882       aObj->setDisplayed(true);
1883     //}
1884   }
1885   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1886
1887 }
1888
1889
1890 //**************************************************************
1891 void XGUI_Workshop::registerValidators() const
1892 {
1893   SessionPtr aMgr = ModelAPI_Session::get();
1894   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1895 }
1896
1897 //**************************************************************
1898 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1899 {
1900   if (!theDoc)
1901     return;
1902   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1903   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1904 }
1905
1906 //**************************************************************
1907 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1908 {
1909   for (int i = 0; i < theDoc->size(theGroup); i++) 
1910     theDoc->object(theGroup, i)->setDisplayed(true);
1911     //displayObject(theDoc->object(theGroup, i));
1912   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1913 }
1914
1915 //**************************************************************
1916 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1917 {
1918   foreach(ObjectPtr aObj, theList) {
1919     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1920
1921     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1922     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1923       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1924           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1925                                       (XGUI_Displayer::DisplayMode)theMode, false);
1926       }
1927     }
1928   }
1929   if (theList.size() > 0)
1930     myDisplayer->updateViewer();
1931 }
1932
1933 //**************************************************************
1934 void XGUI_Workshop::closeDocument()
1935 {
1936   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1937   while (anOperation) {
1938     anOperation->abort();
1939     anOperation = operationMgr()->currentOperation();
1940   }
1941   myDisplayer->closeLocalContexts();
1942   myDisplayer->eraseAll();
1943   objectBrowser()->clearContent();
1944
1945   module()->closeDocument();
1946
1947   SessionPtr aMgr = ModelAPI_Session::get();
1948   aMgr->closeAll();
1949 }
1950
1951 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1952 {
1953   XGUI_HistoryMenu* aMenu = NULL;
1954   if (isSalomeMode()) {
1955     QAction* anAction = qobject_cast<QAction*>(theObject);
1956     if (!anAction)
1957       return;
1958     aMenu = new XGUI_HistoryMenu(anAction);
1959   } else {
1960     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1961     aMenu = new XGUI_HistoryMenu(aButton);
1962   }
1963   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1964   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1965 }
1966
1967 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1968 {
1969   QList<ActionInfo> aResult;
1970   std::list<std::string>::const_iterator it = theList.cbegin();
1971   for (; it != theList.cend(); it++) {
1972     QString anId = QString::fromStdString(*it);
1973     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1974     if (isEditing) {
1975       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1976     }
1977     ActionInfo anInfo;
1978     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1979     if (aContextMenuAct) {
1980       anInfo.initFrom(aContextMenuAct);
1981     } else {
1982       anInfo = myActionsMgr->actionInfoById(anId);
1983     }
1984     if (isEditing) {
1985       anInfo.text = anInfo.text.prepend("Modify ");
1986     }
1987     aResult << anInfo;
1988   }
1989   return aResult;
1990 }
1991
1992 void XGUI_Workshop::synchronizeViewer()
1993 {
1994   SessionPtr aMgr = ModelAPI_Session::get();
1995   DocumentPtr aDoc = aMgr->activeDocument();
1996
1997   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1998   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1999   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2000   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2001 }
2002
2003 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
2004                                              const std::string& theGroup, 
2005                                              bool theUpdateViewer)
2006 {
2007   ObjectPtr aObj;
2008   int aSize = theDoc->size(theGroup);
2009   for (int i = 0; i < aSize; i++) {
2010     aObj = theDoc->object(theGroup, i);
2011     if (aObj->isDisplayed()) {
2012       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2013       // be changed to the object becomes visible when the shape becomes not empty
2014       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2015       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2016         continue;
2017       myDisplayer->display(aObj, false);
2018     }
2019   }
2020   if (theUpdateViewer)
2021     myDisplayer->updateViewer();
2022 }
2023
2024 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2025 {
2026   FeaturePtr aFeature;
2027   QObjectPtrList aSelList = theObjects;
2028   std::list<ResultPtr> aResList;
2029   foreach(ObjectPtr aObj, theObjects) {
2030     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2031     if (aFeature.get()) {
2032       aResList = aFeature->results();
2033       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2034       for(aIt = aResList.cbegin(); aIt != aResList.cend(); aIt++) {
2035         aSelList.append(*aIt);
2036       }
2037     }
2038   }
2039   if (aSelList.count() > theObjects.count()) {
2040     // if something was found
2041     bool aBlocked = objectBrowser()->blockSignals(true);
2042     objectBrowser()->setObjectsSelected(aSelList);
2043     objectBrowser()->blockSignals(aBlocked);
2044   }
2045 }