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