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