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