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