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