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