Salome HOME
Simplified calculation of fly out distance and creation of constraints limited only...
[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   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
135   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
136           SLOT(onContextMenuCommand(const QString&, bool)));
137
138   myViewerProxy = new XGUI_ViewerProxy(this);
139   connect(myViewerProxy, SIGNAL(selectionChanged()),
140           myActionsMgr,  SLOT(updateOnViewSelection()));
141
142   myModuleConnector = new XGUI_ModuleConnector(this);
143
144   ModuleBase_IWorkshop* aWorkshop = moduleConnector();
145   myOperationMgr->setWorkshop(aWorkshop);
146
147   myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
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 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
423 {
424   bool aHasNested = false;
425   std::string aFeatureKind = theFeature->getKind();
426   if (isSalomeMode()) {
427     XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
428     if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
429       aHasNested = true;
430   } else {
431     AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
432     AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
433     if (aCommand && aCommand->button()->additionalButtonWidget())
434       aHasNested = true;
435   }
436   return aHasNested;
437 }
438
439 //******************************************************
440 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
441 {
442   setGrantedFeatures(theOperation);
443
444   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
445                                                                                (theOperation);
446   if (!aFOperation)
447     return;
448
449   if (aFOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
450     setPropertyPanel(aFOperation);
451     // filling the operation values by the current selection
452     // if the operation can be committed after the controls filling, the method perform should
453     // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
454     if (!aFOperation->isEditOperation()) {
455       aFOperation->activateByPreselection();
456       if (operationMgr()->currentOperation() != aFOperation)
457         return;
458     }
459   }
460   updateCommandStatus();
461
462   myModule->onOperationStarted(aFOperation);
463
464   // the objects of the current operation should be deactivated
465   QObjectPtrList anObjects;
466   FeaturePtr aFeature = aFOperation->feature();
467   anObjects.append(aFeature);
468   std::list<ResultPtr> aResults = aFeature->results();
469   std::list<ResultPtr>::const_iterator aIt;
470   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
471     anObjects.append(*aIt);
472   }
473   QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
474   for (; anIt != aLast; anIt++)
475     deactivateActiveObject(*anIt, false);
476   if (anObjects.size() > 0)
477     myDisplayer->updateViewer();
478 }
479
480 //******************************************************
481 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
482 {
483   setGrantedFeatures(theOperation);
484
485   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
486     setPropertyPanel(theOperation);
487   }
488   updateCommandStatus();
489
490   myModule->onOperationResumed(theOperation);
491 }
492
493
494 //******************************************************
495 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
496 {
497   updateCommandStatus();
498
499   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
500                                                                         (theOperation);
501   if (!aFOperation)
502     return;
503
504   ModuleBase_ISelection* aSel = mySelector->selection();
505   QObjectPtrList aObj = aSel->selectedPresentations();
506   //!< No need for property panel
507   hidePropertyPanel();
508   myPropertyPanel->cleanContent();
509
510   myModule->onOperationStopped(aFOperation);
511
512   // the deactivated objects of the current operation should be activated back.
513   // They were deactivated on operation start or an object redisplay
514   QObjectPtrList anObjects;
515   FeaturePtr aFeature = aFOperation->feature();
516   if (aFeature.get()) { // feature may be not created (plugin load fail)
517     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
518       anObjects.append(aFeature);
519     std::list<ResultPtr> aResults = aFeature->results();
520     std::list<ResultPtr>::const_iterator aIt;
521     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
522       ResultPtr anObject = *aIt;
523       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
524         anObjects.append(anObject);
525       }
526     }
527   }
528   QIntList aModes;
529   module()->activeSelectionModes(aModes);
530   myDisplayer->activateObjects(aModes, anObjects);
531 }
532
533
534 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
535 {
536   myModule->onOperationCommitted(theOperation);
537 }
538
539 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
540 {
541   myModule->onOperationAborted(theOperation);
542 }
543
544 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
545 {
546   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
547   if (!aFOperation)
548     return;
549
550   QStringList aGrantedIds;
551   if (isSalomeMode())
552     aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
553   else
554     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
555
556   aFOperation->setGrantedOperationIds(aGrantedIds);
557 }
558
559 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
560 {
561   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
562   if (!aFOperation)
563     return;
564
565   showPropertyPanel();
566   QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
567   ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
568                                                                 myModuleConnector);
569
570   myPropertyPanel->cleanContent();
571   aFactory.createWidget(myPropertyPanel->contentWidget());
572
573   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
574   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
575     bool isStoreValue = !aFOperation->isEditOperation() &&
576                         !aWidget->getDefaultValue().empty() &&
577                         !aWidget->isComputedDefault();
578     aWidget->setFeature(aFOperation->feature(), isStoreValue);
579     aWidget->enableFocusProcessing();
580   }
581   
582   myPropertyPanel->setModelWidgets(aWidgets);
583   aFOperation->setPropertyPanel(myPropertyPanel);
584
585   myModule->propertyPanelDefined(theOperation);
586
587   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
588
589   myErrorMgr->setPropertyPanel(myPropertyPanel);
590 }
591
592 /*
593  * Saves document with given name.
594  */
595 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
596 {
597   QApplication::restoreOverrideCursor();
598   SessionPtr aMgr = ModelAPI_Session::get();
599   aMgr->save(theName.toLatin1().constData(), theFileNames);
600   QApplication::restoreOverrideCursor();
601 }
602
603 bool XGUI_Workshop::abortAllOperations()
604 {
605   return myOperationMgr->abortAllOperations();
606 }
607
608 //******************************************************
609 void XGUI_Workshop::onExit()
610 {
611   SessionPtr aMgr = ModelAPI_Session::get();
612   if (aMgr->isModified()) {
613     int anAnswer = QMessageBox::question(
614         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
615         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
616     if (anAnswer == QMessageBox::Save) {
617       bool saved = onSave();
618       if (!saved) {
619         return;
620       }
621     } else if (anAnswer == QMessageBox::Cancel) {
622       return;
623     }
624   }
625   qApp->exit();
626 }
627
628 //******************************************************
629 void XGUI_Workshop::onNew()
630 {
631   QApplication::setOverrideCursor(Qt::WaitCursor);
632   if (objectBrowser() == 0) {
633     createDockWidgets();
634     mySelector->connectViewers();
635   }
636   myViewerProxy->connectToViewer();
637   showObjectBrowser();
638   if (!isSalomeMode()) {
639     myMainWindow->showPythonConsole();
640     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
641     aWnd->showMaximized();
642     updateCommandStatus();
643   }
644   myContextMenuMgr->connectViewer();
645   QApplication::restoreOverrideCursor();
646 }
647
648 //******************************************************
649 void XGUI_Workshop::onOpen()
650 {
651   if(!abortAllOperations())
652     return;
653   //save current file before close if modified
654   SessionPtr aSession = ModelAPI_Session::get();
655   if (aSession->isModified()) {
656     //TODO(sbh): re-launch the app?
657     int anAnswer = QMessageBox::question(
658         myMainWindow, tr("Save current file"),
659         tr("The document is modified, save before opening another?"),
660         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
661     if (anAnswer == QMessageBox::Save) {
662       onSave();
663     } else if (anAnswer == QMessageBox::Cancel) {
664       return;
665     }
666     myCurrentDir = "";
667   }
668
669   //show file dialog, check if readable and open
670   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow(), tr("Select directory"));
671   if (myCurrentDir.isEmpty())
672     return;
673   QFileInfo aFileInfo(myCurrentDir);
674   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
675     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
676     myCurrentDir = "";
677     return;
678   }
679   QApplication::setOverrideCursor(Qt::WaitCursor);
680   aSession->closeAll();
681   aSession->load(myCurrentDir.toLatin1().constData());
682   myObjectBrowser->rebuildDataTree();
683   updateCommandStatus();
684   QApplication::restoreOverrideCursor();
685 }
686
687 //******************************************************
688 bool XGUI_Workshop::onSave()
689 {
690   if(!abortAllOperations())
691     return false;
692   if (myCurrentDir.isEmpty()) {
693     return onSaveAs();
694   }
695   std::list<std::string> aFiles;
696   saveDocument(myCurrentDir, aFiles);
697   updateCommandStatus();
698   if (!isSalomeMode())
699     myMainWindow->setModifiedState(false);
700   return true;
701 }
702
703 //******************************************************
704 bool XGUI_Workshop::onSaveAs()
705 {
706   if(!abortAllOperations())
707     return false;
708   QFileDialog dialog(mainWindow());
709   dialog.setWindowTitle(tr("Select directory to save files..."));
710   dialog.setFileMode(QFileDialog::Directory);
711   dialog.setFilter(tr("Directories (*)"));
712   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
713   dialog.setViewMode(QFileDialog::Detail);
714
715   if (!dialog.exec()) {
716     return false;
717   }
718
719   QString aTempDir = dialog.selectedFiles().first();
720   QDir aDir(aTempDir);
721   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
722     int answer = QMessageBox::question(
723         myMainWindow,
724         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
725         tr("Save"),
726         tr("The directory already contains some files, save anyway?"),
727         QMessageBox::Save | QMessageBox::Cancel);
728     if (answer == QMessageBox::Cancel) {
729       return false;
730     }
731   }
732   myCurrentDir = aTempDir;
733   if (!isSalomeMode()) {
734     myMainWindow->setCurrentDir(myCurrentDir, false);
735     myMainWindow->setModifiedState(false);
736   }
737   return onSave();
738 }
739
740 //******************************************************
741 void XGUI_Workshop::onUndo(int theTimes)
742 {
743   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
744   SessionPtr aMgr = ModelAPI_Session::get();
745   if (aMgr->isOperation()) {
746     /// this is important for nested operrations
747     /// when sketch opeation is active, this condition is false and 
748     /// the sketch operation is not aborted
749     operationMgr()->onAbortOperation();
750   }
751   for (int i = 0; i < theTimes; ++i) {
752     aMgr->undo();
753   }
754
755   operationMgr()->updateApplyOfOperations();
756   updateCommandStatus();
757 }
758
759 //******************************************************
760 void XGUI_Workshop::onRedo(int theTimes)
761 {
762   // the viewer update should be blocked in order to avoid the features blinking. For the created
763   // feature a results are created, the flush of the created signal caused the viewer redisplay for
764   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
765   // redo of all possible objects happens
766   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
767
768   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
769   SessionPtr aMgr = ModelAPI_Session::get();
770   if (aMgr->isOperation()) {
771     /// this is important for nested operrations
772     /// when sketch opeation is active, this condition is false and 
773     /// the sketch operation is not aborted
774     operationMgr()->onAbortOperation();
775   }
776   for (int i = 0; i < theTimes; ++i) {
777     aMgr->redo();
778   }
779   operationMgr()->updateApplyOfOperations();
780   updateCommandStatus();
781
782   // unblock the viewer update functionality and make update on purpose
783   myDisplayer->enableUpdateViewer(isUpdateEnabled);
784   myDisplayer->updateViewer();
785 }
786
787 //******************************************************
788 void XGUI_Workshop::onRebuild()
789 {
790   SessionPtr aMgr = ModelAPI_Session::get();
791   bool aWasOperation = aMgr->isOperation(); // keep this value
792   if (!aWasOperation) {
793     aMgr->startOperation("Rebuild");
794   }
795   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
796   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
797     new Events_Message(aRebuildEvent, this)));
798   if (!aWasOperation) {
799     aMgr->finishOperation();
800   }
801   updateCommandStatus();
802 }
803
804 //******************************************************
805 void XGUI_Workshop::onPreferences()
806 {
807   ModuleBase_Prefs aModif;
808   ModuleBase_Preferences::editPreferences(aModif);
809   if (aModif.size() > 0) {
810     QString aSection;
811     foreach (ModuleBase_Pref aPref, aModif)
812     {
813       aSection = aPref.first;
814       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
815         if (!isSalomeMode())
816           myMainWindow->viewer()->updateFromResources();
817       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
818         if (!isSalomeMode())
819           myMainWindow->menuObject()->updateFromResources();
820       }
821     }
822     displayer()->redisplayObjects();
823   }
824 }
825
826 //******************************************************
827 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
828 {
829   QString libName = QString::fromStdString(library(theModule.toStdString()));
830   if (libName.isEmpty()) {
831     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
832     return 0;
833   }
834
835   QString err;
836   CREATE_FUNC crtInst = 0;
837
838 #ifdef WIN32
839   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
840   if (!modLib) {
841     LPVOID lpMsgBuf;
842     ::FormatMessage(
843         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
844         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
845     QString aMsg((char*) &lpMsgBuf);
846     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
847     ::LocalFree(lpMsgBuf);
848   } else {
849     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
850     if (!crtInst) {
851       LPVOID lpMsgBuf;
852       ::FormatMessage(
853           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
854               | FORMAT_MESSAGE_IGNORE_INSERTS,
855           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
856       QString aMsg((char*) &lpMsgBuf);
857       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
858       ::LocalFree(lpMsgBuf);
859     }
860   }
861 #else
862   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
863   if ( !modLib ) {
864     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
865   } else {
866     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
867     if ( !crtInst ) {
868       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
869     }
870   }
871 #endif
872
873   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
874
875   if (!err.isEmpty()) {
876     if (mainWindow()) {
877       Events_Error::send(err.toStdString());
878     } else {
879       qWarning(qPrintable(err));
880     }
881   }
882   return aModule;
883 }
884
885 //******************************************************
886 bool XGUI_Workshop::createModule()
887 {
888   Config_ModuleReader aModuleReader;
889   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
890   myModule = loadModule(moduleName);
891   if (!myModule)
892     return false;
893
894   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
895   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
896   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
897   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
898
899   myModule->createFeatures();
900   //myActionsMgr->update();
901   return true;
902 }
903
904 //******************************************************
905 void XGUI_Workshop::updateCommandStatus()
906 {
907   QList<QAction*> aCommands;
908   if (isSalomeMode()) {  // update commands in SALOME mode
909     aCommands = salomeConnector()->commandList();
910   } else {
911     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
912     foreach (AppElements_Command* aCmd, aMenuBar->features())
913       aCommands.append(aCmd);
914   }
915   SessionPtr aMgr = ModelAPI_Session::get();
916   if (aMgr->hasModuleDocument()) {
917     foreach(QAction* aCmd, aCommands) {
918       QString aId = aCmd->data().toString();
919       if (aId == "UNDO_CMD")
920         aCmd->setEnabled(myModule->canUndo());
921       else if (aId == "REDO_CMD")
922         aCmd->setEnabled(myModule->canRedo());
923       else
924         // Enable all commands
925         aCmd->setEnabled(true);
926     }
927     updateHistory();
928   } else {
929     foreach(QAction* aCmd, aCommands) {
930       QString aId = aCmd->data().toString();
931       if (aId == "NEW_CMD")
932         aCmd->setEnabled(true);
933       else if (aId == "EXIT_CMD")
934         aCmd->setEnabled(true);
935       else
936         aCmd->setEnabled(false);
937     }
938   }
939   myActionsMgr->update();
940   emit commandStatusUpdated();
941 }
942
943 void XGUI_Workshop::updateHistory()
944 {
945   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
946   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
947   emit updateUndoHistory(aUndoRes);
948
949   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
950   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
951   emit updateRedoHistory(aRedoRes);
952 }
953
954 //******************************************************
955 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
956 {
957   QDockWidget* aObjDock = new QDockWidget(theParent);
958   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
959   aObjDock->setWindowTitle(tr("Object browser"));
960   aObjDock->setStyleSheet(
961       "::title { position: relative; padding-left: 5px; text-align: left center }");
962   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
963 #ifdef ModuleDataModel
964   myObjectBrowser->setDataModel(myModule->dataModel());
965 #endif
966   myModule->customizeObjectBrowser(myObjectBrowser);
967   aObjDock->setWidget(myObjectBrowser);
968
969   myContextMenuMgr->connectObjectBrowser();
970   return aObjDock;
971 }
972
973 //******************************************************
974 /*
975  * Creates dock widgets, places them in corresponding area
976  * and tabifies if necessary.
977  */
978 void XGUI_Workshop::createDockWidgets()
979 {
980   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
981   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
982   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
983   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
984   myPropertyPanel->setupActions(myActionsMgr);
985   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
986   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
987   hidePropertyPanel();  ///<! Invisible by default
988   hideObjectBrowser();
989   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
990   myPropertyPanel->installEventFilter(myOperationMgr);
991
992   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
993   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
994
995   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
996   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
997   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
998   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
999           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1000   //connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1001   //        this, SLOT(onValidationStateChanged(bool)));
1002 }
1003
1004 //******************************************************
1005 void XGUI_Workshop::showPropertyPanel()
1006 {
1007   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1008   ///<! Restore ability to close panel from the window's menu
1009   aViewAct->setEnabled(true);
1010   myPropertyPanel->show();
1011   myPropertyPanel->raise();
1012 }
1013
1014 //******************************************************
1015 void XGUI_Workshop::hidePropertyPanel()
1016 {
1017   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1018   ///<! Do not allow to show empty property panel
1019   aViewAct->setEnabled(false);
1020   myPropertyPanel->hide();
1021 }
1022
1023 //******************************************************
1024 void XGUI_Workshop::showObjectBrowser()
1025 {
1026   myObjectBrowser->parentWidget()->show();
1027 }
1028
1029 //******************************************************
1030 void XGUI_Workshop::hideObjectBrowser()
1031 {
1032   myObjectBrowser->parentWidget()->hide();
1033 }
1034
1035 //******************************************************
1036 void XGUI_Workshop::salomeViewerSelectionChanged()
1037 {
1038   emit salomeViewerSelection();
1039 }
1040
1041 //**************************************************************
1042 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1043 {
1044   return mySalomeConnector->viewer();
1045 }
1046
1047 //**************************************************************
1048 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1049 {
1050   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1051   if (theId == "DELETE_CMD")
1052     deleteObjects();
1053   else if (theId == "MOVE_CMD")
1054     moveObjects();
1055   else if (theId == "COLOR_CMD")
1056     changeColor(aObjects);
1057   else if (theId == "SHOW_CMD")
1058     showObjects(aObjects, true);
1059   else if (theId == "HIDE_CMD")
1060     showObjects(aObjects, false);
1061   else if (theId == "SHOW_ONLY_CMD")
1062     showOnlyObjects(aObjects);
1063   else if (theId == "SHADING_CMD")
1064     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1065   else if (theId == "WIREFRAME_CMD")
1066     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1067   else if (theId == "HIDEALL_CMD") {
1068     QObjectPtrList aList = myDisplayer->displayedObjects();
1069     foreach (ObjectPtr aObj, aList) {
1070       if (module()->canEraseObject(aObj))
1071         aObj->setDisplayed(false);
1072     }
1073     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1074   }
1075 }
1076
1077 //**************************************************************
1078 void XGUI_Workshop::deleteObjects()
1079 {
1080   ModuleBase_IModule* aModule = module();
1081   // 1. allow the module to delete objects, do nothing if it has succeed
1082   if (aModule->deleteObjects()) {
1083     updateCommandStatus();
1084     return;
1085   }
1086
1087   if (!abortAllOperations())
1088     return;
1089   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1090   // It is necessary to clear selection in order to avoid selection changed event during
1091   // deleteion and negative consequences connected with processing of already deleted items
1092   mySelector->clearSelection();
1093   // check whether the object can be deleted. There should not be parts which are not loaded
1094   if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1095     return;
1096
1097   bool hasResult = false;
1098   bool hasFeature = false;
1099   bool hasParameter = false;
1100   bool hasSubFeature = false;
1101   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1102   if (!(hasFeature || hasParameter))
1103     return;
1104
1105   // 1. start operation
1106   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1107   aDescription += tr(" %1");
1108   QStringList aObjectNames;
1109   foreach (ObjectPtr aObj, anObjects) {
1110     if (!aObj->data()->isValid())
1111       continue;
1112     aObjectNames << QString::fromStdString(aObj->data()->name());
1113   }
1114   aDescription = aDescription.arg(aObjectNames.join(", "));
1115   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1116
1117   operationMgr()->startOperation(anOpAction);
1118   // 3. delete objects
1119   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1120   std::set<FeaturePtr> anIgnoredFeatures;
1121   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1122     operationMgr()->commitOperation();
1123   }
1124   else {
1125     operationMgr()->abortOperation(operationMgr()->currentOperation());
1126   }
1127 }
1128
1129 //**************************************************************
1130 void XGUI_Workshop::moveObjects()
1131 {
1132   if (!abortAllOperations())
1133     return;
1134
1135   SessionPtr aMgr = ModelAPI_Session::get();
1136
1137   QString anActionId = "MOVE_CMD";
1138   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1139   aMgr->startOperation(aDescription.toStdString());
1140
1141   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1142   DocumentPtr anActiveDocument = aMgr->activeDocument();
1143
1144   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1145   foreach (ObjectPtr aObject, anObjects) {
1146     if (!myModule->canApplyAction(aObject, anActionId))
1147       continue;
1148
1149     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1150     if (aFeature.get()) {
1151       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1152       aCurrentFeature = anActiveDocument->currentFeature(true);
1153     }
1154   }
1155   aMgr->finishOperation();
1156 }
1157
1158 //**************************************************************
1159 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1160                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1161                                    QWidget* theParent,
1162                                    const bool theAskAboutDeleteReferences)
1163 {
1164 #ifdef DEBUG_DELETE
1165   QStringList aDInfo;
1166   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1167   for (; aDIt != aDLast; ++aDIt) {
1168     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1169   }
1170   QString anInfoStr = aDInfo.join(", ");
1171   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1172 #endif
1173
1174   // 1. find all referenced features
1175   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1176   foreach (ObjectPtr aDeletedObj, theList) {
1177     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures);
1178     std::set<FeaturePtr> aDifference;
1179     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1180                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1181                         std::inserter(aDifference, aDifference.begin()));
1182     aIndirectRefFeatures = aDifference;
1183   }
1184   // 2. warn about the references remove, break the delete operation if the user chose it
1185   if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1186     QStringList aDirectRefNames;
1187     foreach(const FeaturePtr& aFeature, aDirectRefFeatures)
1188       aDirectRefNames.append(aFeature->name().c_str());
1189     QString aDirectNames = aDirectRefNames.join(", ");
1190
1191     QStringList aIndirectRefNames;
1192     foreach(const FeaturePtr& aFeature, aIndirectRefFeatures)
1193       aIndirectRefNames.append(aFeature->name().c_str());
1194     QString aIndirectNames = aIndirectRefNames.join(", ");
1195
1196     QMessageBox::StandardButton aRes = QMessageBox::warning(
1197         theParent, tr("Delete features"),
1198         QString(tr("Selected features are used in the following features: %1.\
1199  These features will be deleted.\n%2Would you like to continue?")).arg(aDirectNames)
1200             .arg(aIndirectNames.isEmpty() ? QString() : QString("Also these features will be deleted: %1.\n").arg(aIndirectNames)),
1201         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1202     if (aRes != QMessageBox::Yes)
1203       return false;
1204   }
1205
1206   // 3. remove referenced features
1207   std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1208   aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1209   std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1210                                        aLast = aFeaturesToDelete.end();
1211 #ifdef DEBUG_DELETE
1212   QStringList anInfo;
1213 #endif
1214   for (; anIt != aLast; anIt++) {
1215     FeaturePtr aFeature = (*anIt);
1216     DocumentPtr aDoc = aFeature->document();
1217     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1218       aDoc->removeFeature(aFeature);
1219 #ifdef DEBUG_DELETE
1220       anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1221 #endif
1222     }
1223   }
1224 #ifdef DEBUG_DELETE
1225   qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1226   anInfo.clear();
1227 #endif
1228
1229   QString anActionId = "DELETE_CMD";
1230   QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1231   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1232   // 4. remove the parameter features
1233   foreach (ObjectPtr aObj, theList) {
1234     // features and parameters can be removed here,
1235     // the results are removed only by a corresponded feature remove
1236     std::string aGroupName = aObj->groupName();
1237     if (!anObjectGroups.contains(aGroupName.c_str()))
1238       continue;
1239
1240     if (!myModule->canApplyAction(aObj, anActionId))
1241       continue;
1242
1243     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1244     if (aFeature) {
1245       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1246       // part features are removed in the PartSet module. This condition should be moved there
1247       if (aFeature->getKind() == "Part")
1248         continue;
1249         */
1250       DocumentPtr aDoc = aObj->document();
1251       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1252 #ifdef DEBUG_DELETE
1253         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1254         anInfo.append(anInfoStr);
1255         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1256 #endif
1257         aDoc->removeFeature(aFeature);
1258       }
1259     }
1260   }
1261 #ifdef DEBUG_DELETE
1262   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1263 #endif
1264   return true;
1265 }
1266
1267 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1268 {
1269   bool isFoundResultType = false;
1270   foreach(ObjectPtr anObj, theObjects)
1271   {
1272     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1273     if (aResult.get() == NULL)
1274       continue;
1275
1276     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1277     if (isFoundResultType)
1278       break;
1279   }
1280   return isFoundResultType;
1281 }
1282
1283 //**************************************************************
1284 // Returns the list of features placed between theObject and the current feature
1285 // in the same document. Excludes theObject, includes the current feature.
1286 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1287 {
1288   std::list<FeaturePtr> aResult;
1289   DocumentPtr aDocument = theObject->document();
1290   std::list<FeaturePtr> anAllFeatures = aDocument->allFeatures();
1291   // find the object iterator
1292   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1293   if (aObjectIt == anAllFeatures.end()) 
1294     return aResult;
1295   // find the current feature iterator
1296   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1297   if (aCurrentIt == anAllFeatures.end()) 
1298     return aResult;
1299   // check the right order
1300   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1301     return aResult;
1302   // exclude the object
1303   std::advance(aObjectIt, 1);
1304   // include the current feature
1305   std::advance(aCurrentIt, 1);
1306   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1307 }
1308
1309 bool XGUI_Workshop::canMoveFeature()
1310 {
1311   QString anActionId = "MOVE_CMD";
1312
1313   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1314   QObjectPtrList aValidatedObjects;
1315   foreach (ObjectPtr aObject, aObjects) {
1316     if (!myModule->canApplyAction(aObject, anActionId))
1317       continue;
1318     // To be moved feature should be in active document
1319     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1320       continue;
1321     aValidatedObjects.append(aObject);
1322   }
1323   if (aValidatedObjects.size() != aObjects.size())
1324     aObjects = aValidatedObjects;
1325
1326   bool aCanMove = !aObjects.empty();
1327
1328   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1329   for (; anIt != aLast && aCanMove; anIt++) {
1330     ObjectPtr aObject = *anIt;
1331     // 1. Get features placed between selected and current in the document 
1332     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1333     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1334     if (aFeaturesBetween.empty())
1335       aCanMove = false;
1336     else {
1337       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1338       // 2. Get all reference features to the selected object in the document 
1339       std::set<FeaturePtr> aRefFeatures;
1340       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1341
1342       if (aRefFeatures.empty())
1343         continue;
1344       else {
1345         // 3. Find any placed features in all reference features
1346         std::set<FeaturePtr> aIntersectionFeatures;
1347         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1348                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1349                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1350         // 4. Return false if any reference feature is placed before current feature
1351         if (!aIntersectionFeatures.empty())
1352           aCanMove = false;
1353       }
1354     }
1355   }
1356   return aCanMove;
1357 }
1358
1359 //**************************************************************
1360 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1361 {
1362   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1363   if (!aCanBeShaded) {
1364     ResultCompSolidPtr aCompsolidResult =
1365                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1366     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1367       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1368         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1369     }
1370   }
1371   return aCanBeShaded;
1372 }
1373
1374 //**************************************************************
1375 bool XGUI_Workshop::canChangeColor() const
1376 {
1377   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1378
1379   std::set<std::string> aTypes;
1380   aTypes.insert(ModelAPI_ResultGroup::group());
1381   aTypes.insert(ModelAPI_ResultConstruction::group());
1382   aTypes.insert(ModelAPI_ResultBody::group());
1383   aTypes.insert(ModelAPI_ResultPart::group());
1384
1385   return hasResults(aObjects, aTypes);
1386 }
1387
1388 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1389 {
1390   if (!theResult.get())
1391     return;
1392
1393   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1394   if (aColorAttr.get() != NULL) {
1395     if (!aColorAttr->size()) {
1396       aColorAttr->setSize(3);
1397     }
1398     aColorAttr->setValue(0, theColor[0]);
1399     aColorAttr->setValue(1, theColor[1]);
1400     aColorAttr->setValue(2, theColor[2]);
1401   }
1402 }
1403
1404 //**************************************************************
1405 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1406 {
1407   AttributeIntArrayPtr aColorAttr;
1408   // 1. find the current color of the object. This is a color of AIS presentation
1409   // The objects are iterated until a first valid color is found 
1410   std::vector<int> aColor;
1411   foreach(ObjectPtr anObject, theObjects) {
1412     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1413     if (aResult.get()) {
1414       XGUI_CustomPrs::getResultColor(aResult, aColor);
1415     }
1416     else {
1417       // TODO: remove the obtaining a color from the AIS object
1418       // this does not happen never because:
1419       // 1. The color can be changed only on results
1420       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1421       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1422       if (anAISObj.get()) {
1423         aColor.resize(3);
1424         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1425       }
1426     }
1427     if (!aColor.empty())
1428       break;
1429   }
1430   if (aColor.size() != 3)
1431     return;
1432
1433   // 2. show the dialog to change the value
1434   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1435   aDlg->setColor(aColor);
1436   aDlg->move(QCursor::pos());
1437   bool isDone = aDlg->exec() == QDialog::Accepted;
1438   if (!isDone)
1439     return;
1440
1441   bool isRandomColor = aDlg->isRandomColor();
1442
1443   // 3. abort the previous operation and start a new one
1444   SessionPtr aMgr = ModelAPI_Session::get();
1445   bool aWasOperation = aMgr->isOperation(); // keep this value
1446   if (!aWasOperation) {
1447     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1448     aMgr->startOperation(aDescription.toStdString());
1449   }
1450
1451   // 4. set the value to all results
1452   std::vector<int> aColorResult = aDlg->getColor();
1453   foreach(ObjectPtr anObj, theObjects) {
1454     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1455     if (aResult.get() != NULL) {
1456       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1457       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1458         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++)
1459           setColor(aCompsolidResult->subResult(i), aColorResult);
1460       }
1461       setColor(aResult, aColorResult);
1462     }
1463   }
1464   if (!aWasOperation)
1465     aMgr->finishOperation();
1466   updateCommandStatus();
1467 }
1468
1469 //**************************************************************
1470 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1471 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1472   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1473 }
1474 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1475 {
1476   foreach (ObjectPtr aObj, theList) {
1477     /*
1478     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1479     if (aPartRes) {
1480       DocumentPtr aDoc = aPartRes->partDoc();
1481       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1482       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1483       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1484     } else {
1485     */
1486       aObj->setDisplayed(isVisible);
1487     //}
1488   }
1489   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1490 }
1491
1492 //**************************************************************
1493 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1494 {
1495   // Hide all displayed objects
1496   QObjectPtrList aList = myDisplayer->displayedObjects();
1497   foreach (ObjectPtr aObj, aList) {
1498     if (module()->canEraseObject(aObj))
1499       aObj->setDisplayed(false);
1500   }
1501
1502   // Show only objects from the list
1503   foreach (ObjectPtr aObj, theList) {
1504     /*
1505     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1506     if (aPartRes) {
1507       DocumentPtr aDoc = aPartRes->partDoc();
1508       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1509       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1510       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1511     } else {
1512     */
1513       aObj->setDisplayed(true);
1514     //}
1515   }
1516   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1517
1518 }
1519
1520
1521 //**************************************************************
1522 void XGUI_Workshop::registerValidators() const
1523 {
1524   SessionPtr aMgr = ModelAPI_Session::get();
1525   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1526 }
1527
1528 //**************************************************************
1529 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1530 {
1531   if (!theDoc)
1532     return;
1533   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1534   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1535 }
1536
1537 //**************************************************************
1538 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1539 {
1540   for (int i = 0; i < theDoc->size(theGroup); i++) 
1541     theDoc->object(theGroup, i)->setDisplayed(true);
1542     //displayObject(theDoc->object(theGroup, i));
1543   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1544 }
1545
1546 //**************************************************************
1547 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1548 {
1549   foreach(ObjectPtr aObj, theList) {
1550     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1551
1552     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1553     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1554       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1555           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1556                                       (XGUI_Displayer::DisplayMode)theMode, false);
1557       }
1558     }
1559   }
1560   if (theList.size() > 0)
1561     myDisplayer->updateViewer();
1562 }
1563
1564 //**************************************************************
1565 void XGUI_Workshop::closeDocument()
1566 {
1567   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1568   while (anOperation) {
1569     anOperation->abort();
1570     anOperation = operationMgr()->currentOperation();
1571   }
1572   myDisplayer->closeLocalContexts();
1573   myDisplayer->eraseAll();
1574   objectBrowser()->clearContent();
1575
1576   module()->closeDocument();
1577
1578   SessionPtr aMgr = ModelAPI_Session::get();
1579   aMgr->closeAll();
1580 }
1581
1582 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1583 {
1584   XGUI_HistoryMenu* aMenu = NULL;
1585   if (isSalomeMode()) {
1586     QAction* anAction = qobject_cast<QAction*>(theObject);
1587     if (!anAction)
1588       return;
1589     aMenu = new XGUI_HistoryMenu(anAction);
1590   } else {
1591     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1592     aMenu = new XGUI_HistoryMenu(aButton);
1593   }
1594   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1595   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1596 }
1597
1598 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1599 {
1600   QList<ActionInfo> aResult;
1601   std::list<std::string>::const_iterator it = theList.cbegin();
1602   for (; it != theList.cend(); it++) {
1603     QString anId = QString::fromStdString(*it);
1604     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1605     if (isEditing) {
1606       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1607     }
1608     ActionInfo anInfo;
1609     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1610     if (aContextMenuAct) {
1611       anInfo.initFrom(aContextMenuAct);
1612     } else {
1613       anInfo = myActionsMgr->actionInfoById(anId);
1614     }
1615     if (isEditing) {
1616       anInfo.text = anInfo.text.prepend("Modify ");
1617     }
1618     aResult << anInfo;
1619   }
1620   return aResult;
1621 }