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