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