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