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