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