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