Salome HOME
Merge branch 'Dev_1.2.0' of newgeom:newgeom into Dev_1.2.0
[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             myDisplayer->deactivate(aObj);
476         }
477       } else { // display object if the current operation has it
478         if (displayObject(aObj)) {
479           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
480           if (aOperation && aOperation->hasObject(aObj)) {
481             ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
482             #ifdef DEBUG_FEATURE_REDISPLAY
483               QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
484               qDebug(QString("  display object = %1").arg(anObjInfo).toStdString().c_str());
485             #endif
486             // Deactivate object of current operation from selection
487             if (myDisplayer->isActive(aObj))
488               myDisplayer->deactivate(aObj);
489           }
490         }
491       }
492     }
493   }
494   myDisplayer->updateViewer();
495 }
496
497 //******************************************************
498 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
499 {
500   std::set<ObjectPtr> aObjects = theMsg->objects();
501   std::set<ObjectPtr>::const_iterator aIt;
502 #ifdef DEBUG_FEATURE_CREATED
503   QStringList anInfo;
504   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
505     anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
506   }
507   QString anInfoStr = anInfo.join(", ");
508   qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
509 #endif
510
511   //bool aHasPart = false;
512   bool isDisplayed = false;
513   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
514     ObjectPtr anObject = *aIt;
515     // the validity of the data should be checked here in order to avoid display of the objects,
516     // which were created, then deleted, but flush for the creation event happens after that
517     // we should not display disabled objects
518     bool aHide = !anObject->data() || !anObject->data()->isValid() || 
519       anObject->isDisabled() || (!anObject->isDisplayed());
520     if (!aHide) {
521       // setDisplayed has to be called in order to synchronize internal state of the object 
522       // with list of displayed objects
523       if (myModule->canDisplayObject(anObject)) {
524         anObject->setDisplayed(true);
525         isDisplayed = displayObject(*aIt);
526       } else 
527         anObject->setDisplayed(false);
528     }
529   }
530   //if (myObjectBrowser)
531   //  myObjectBrowser->processEvent(theMsg);
532   if (isDisplayed)
533     myDisplayer->updateViewer();
534   //if (aHasPart) { // TODO: Avoid activate last part on loading of document
535   //  activateLastPart();
536   //}
537 }
538
539 //******************************************************
540 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
541 {
542   setNestedFeatures(theOperation);
543
544   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
545     connectWithOperation(theOperation);
546     setPropertyPanel(theOperation);
547   }
548   updateCommandStatus();
549
550   myModule->operationStarted(theOperation);
551 }
552
553 //******************************************************
554 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
555 {
556   setNestedFeatures(theOperation);
557
558   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
559     // connectWithOperation(theOperation); already connected
560     setPropertyPanel(theOperation);
561   }
562   updateCommandStatus();
563
564   myModule->operationResumed(theOperation);
565 }
566
567
568 //******************************************************
569 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
570 {
571   ModuleBase_ISelection* aSel = mySelector->selection();
572   QObjectPtrList aObj = aSel->selectedPresentations();
573   //!< No need for property panel
574   updateCommandStatus();
575   hidePropertyPanel();
576   myPropertyPanel->cleanContent();
577
578   // Activate objects created by current operation 
579   // in order to clean selection modes
580   // the deactivation should be pefromed in the same place, where the mode is activated,
581   // e.g. activation in the current widget activation, deactivation - in the widget's deactivation
582   //QIntList aModes;
583   //myDisplayer->activateObjects(aModes);
584   myModule->operationStopped(theOperation);
585
586   // if the operation is nested, do not deactivate objects
587   //if (myOperationMgr->operationsCount() == 0) {
588     // Activate selection mode for all objects
589   QIntList aModes;
590   // TODO: check on OCC_6.9.0
591   // the module current active modes should not be deactivated in order to save the objects selected
592   // the deactivate object in the mode of selection leads to the object is deselected in the viewer.
593   // But, in OCC_6.8.0 this deselection does not happened automatically. It is necessary to call
594   // ClearOutdatedSelection, but this method has an error in the realization, which should be fixed in
595   // the OCC_6.9.0 release. Moreother, it is possible that ClearOutdatedSelection will be called inside
596   // Deactivate method of AIS_InteractiveContext. In this case, we need not call it.
597   module()->activeSelectionModes(aModes);
598   myDisplayer->activateObjects(aModes);
599   //}
600 }
601
602
603 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
604 {
605   myModule->operationCommitted(theOperation);
606 }
607
608 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
609 {
610   myModule->operationAborted(theOperation);
611 }
612
613 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
614 {
615   if (this->isSalomeMode()) 
616     theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
617   else 
618     theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
619 }
620
621 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
622 {
623   showPropertyPanel();
624   QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
625   ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
626                                                                 myModuleConnector);
627
628   myPropertyPanel->cleanContent();
629   aFactory.createWidget(myPropertyPanel->contentWidget());
630
631   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
632   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
633     bool isStoreValue = !theOperation->isEditOperation() &&
634                         !aWidget->getDefaultValue().empty() &&
635                         !aWidget->isComputedDefault();
636     aWidget->setFeature(theOperation->feature(), isStoreValue);
637     aWidget->enableFocusProcessing();
638   }
639   
640   myPropertyPanel->setModelWidgets(aWidgets);
641   theOperation->setPropertyPanel(myPropertyPanel);
642
643   myModule->propertyPanelDefined(theOperation);
644
645   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
646 }
647
648 bool XGUI_Workshop::event(QEvent * theEvent)
649 {
650   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
651   if (aPostponedEv) {
652     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
653     processEvent(aEventPtr);
654     return true;
655   }
656   return false;
657 }
658
659 /*
660  *
661  */
662 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
663 {
664   if (!theMessage) {
665 #ifdef _DEBUG
666     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
667 #endif
668     return;
669   }
670   ActionInfo aFeatureInfo;
671   aFeatureInfo.initFrom(theMessage);
672
673   QString aWchName = QString::fromStdString(theMessage->workbenchId());
674   QStringList aNestedFeatures =
675       QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
676   QString aDocKind = QString::fromStdString(theMessage->documentKind());
677   QList<QAction*> aNestedActList;
678   bool isColumnButton = !aNestedFeatures.isEmpty();
679   if (isColumnButton) {
680     QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
681     if (aNestedActions.contains("accept")) {
682       QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
683       connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
684       aNestedActList << anAction;
685     }
686     if (aNestedActions.contains("abort")) {
687       QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
688       connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
689       aNestedActList << anAction;
690     }
691   }
692
693   if (isSalomeMode()) {
694     QAction* aAction;
695     if (isColumnButton) {
696       aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
697     } else {
698       aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
699     }
700     salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
701     salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
702
703     myActionsMgr->addCommand(aAction);
704     myModule->actionCreated(aAction);
705   } else {
706     //Find or create Workbench
707     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
708     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
709     if (!aPage) {
710       aPage = addWorkbench(aWchName);
711     }
712     //Find or create Group
713     QString aGroupName = QString::fromStdString(theMessage->groupId());
714     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
715     if (!aGroup) {
716       aGroup = aPage->addGroup(aGroupName);
717     }
718     // Check if hotkey sequence is already defined:
719     QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
720     if(aHotKey != aFeatureInfo.shortcut) {
721       aFeatureInfo.shortcut = aHotKey;
722     }
723     // Create feature...
724     AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
725                                                        aDocKind,
726                                                        aNestedFeatures);
727     // Enrich created button with accept/abort buttons if necessary
728     AppElements_Button* aButton = aCommand->button();
729     if (aButton->isColumnButton()) {
730       aButton->setAdditionalButtons(aNestedActList);
731     }
732     myActionsMgr->addCommand(aCommand);
733     myModule->actionCreated(aCommand);
734   }
735 }
736
737 /*
738  * Makes a signal/slot connections between Property Panel
739  * and given operation. The given operation becomes a
740  * current operation and previous operation if exists
741  */
742 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
743 {
744   QAction* aCommand = 0;
745   if (isSalomeMode()) {
746     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
747   } else {
748     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
749     FeaturePtr aFeature = theOperation->feature();
750     if(aFeature)
751       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
752   }
753   //Abort operation on uncheck the command
754   if (aCommand) {
755     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
756   }
757 }
758
759 /*
760  * Saves document with given name.
761  */
762 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
763 {
764   QApplication::restoreOverrideCursor();
765   SessionPtr aMgr = ModelAPI_Session::get();
766   aMgr->save(theName.toLatin1().constData(), theFileNames);
767   QApplication::restoreOverrideCursor();
768 }
769
770 bool XGUI_Workshop::isActiveOperationAborted()
771 {
772   return myOperationMgr->abortAllOperations();
773 }
774
775 //******************************************************
776 void XGUI_Workshop::onExit()
777 {
778   SessionPtr aMgr = ModelAPI_Session::get();
779   if (aMgr->isModified()) {
780     int anAnswer = QMessageBox::question(
781         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
782         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
783     if (anAnswer == QMessageBox::Save) {
784       bool saved = onSave();
785       if (!saved) {
786         return;
787       }
788     } else if (anAnswer == QMessageBox::Cancel) {
789       return;
790     }
791   }
792   qApp->exit();
793 }
794
795 //******************************************************
796 void XGUI_Workshop::onNew()
797 {
798   QApplication::setOverrideCursor(Qt::WaitCursor);
799   if (objectBrowser() == 0) {
800     createDockWidgets();
801     mySelector->connectViewers();
802   }
803   myViewerProxy->connectToViewer();
804   showObjectBrowser();
805   if (!isSalomeMode()) {
806     myMainWindow->showPythonConsole();
807     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
808     aWnd->showMaximized();
809     updateCommandStatus();
810   }
811   myContextMenuMgr->connectViewer();
812   QApplication::restoreOverrideCursor();
813 }
814
815 //******************************************************
816 void XGUI_Workshop::onOpen()
817 {
818   if(!isActiveOperationAborted())
819     return;
820   //save current file before close if modified
821   SessionPtr aSession = ModelAPI_Session::get();
822   if (aSession->isModified()) {
823     //TODO(sbh): re-launch the app?
824     int anAnswer = QMessageBox::question(
825         myMainWindow, tr("Save current file"),
826         tr("The document is modified, save before opening another?"),
827         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
828     if (anAnswer == QMessageBox::Save) {
829       onSave();
830     } else if (anAnswer == QMessageBox::Cancel) {
831       return;
832     }
833     myCurrentDir = "";
834   }
835
836   //show file dialog, check if readable and open
837   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
838   if (myCurrentDir.isEmpty())
839     return;
840   QFileInfo aFileInfo(myCurrentDir);
841   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
842     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
843     myCurrentDir = "";
844     return;
845   }
846   QApplication::setOverrideCursor(Qt::WaitCursor);
847   myIsLoadingData = true;
848   aSession->closeAll();
849   aSession->load(myCurrentDir.toLatin1().constData());
850   myObjectBrowser->rebuildDataTree();
851   //displayAllResults();
852   updateCommandStatus();
853   myIsLoadingData = false;
854   QApplication::restoreOverrideCursor();
855 }
856
857 //******************************************************
858 bool XGUI_Workshop::onSave()
859 {
860   if(!isActiveOperationAborted())
861     return false;
862   if (myCurrentDir.isEmpty()) {
863     return onSaveAs();
864   }
865   std::list<std::string> aFiles;
866   saveDocument(myCurrentDir, aFiles);
867   updateCommandStatus();
868   if (!isSalomeMode())
869     myMainWindow->setModifiedState(false);
870   return true;
871 }
872
873 //******************************************************
874 bool XGUI_Workshop::onSaveAs()
875 {
876   if(!isActiveOperationAborted())
877     return false;
878   QFileDialog dialog(mainWindow());
879   dialog.setWindowTitle(tr("Select directory to save files..."));
880   dialog.setFileMode(QFileDialog::Directory);
881   dialog.setFilter(tr("Folders (*)"));
882   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
883   dialog.setViewMode(QFileDialog::Detail);
884
885   if (!dialog.exec()) {
886     return false;
887   }
888   QString aTempDir = dialog.selectedFiles().first();
889   QDir aDir(aTempDir);
890   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
891     int answer = QMessageBox::question(
892         myMainWindow,
893         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
894         tr("Save"),
895         tr("The folder already contains some files, save anyway?"),
896         QMessageBox::Save | QMessageBox::Cancel);
897     if (answer == QMessageBox::Cancel) {
898       return false;
899     }
900   }
901   myCurrentDir = aTempDir;
902   if (!isSalomeMode()) {
903     myMainWindow->setCurrentDir(myCurrentDir, false);
904     myMainWindow->setModifiedState(false);
905   }
906   return onSave();
907 }
908
909 //******************************************************
910 void XGUI_Workshop::onUndo(int theTimes)
911 {
912   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
913   SessionPtr aMgr = ModelAPI_Session::get();
914   if (aMgr->isOperation())
915     operationMgr()->onAbortOperation();
916   for (int i = 0; i < theTimes; ++i) {
917     aMgr->undo();
918   }
919   updateCommandStatus();
920 }
921
922 //******************************************************
923 void XGUI_Workshop::onRedo(int theTimes)
924 {
925   // the viewer update should be blocked in order to avoid the features blinking. For the created
926   // feature a results are created, the flush of the created signal caused the viewer redisplay for
927   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
928   // redo of all possible objects happens
929   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
930
931   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
932   SessionPtr aMgr = ModelAPI_Session::get();
933   if (aMgr->isOperation())
934     operationMgr()->onAbortOperation();
935   for (int i = 0; i < theTimes; ++i) {
936     aMgr->redo();
937   }
938   updateCommandStatus();
939
940   // unblock the viewer update functionality and make update on purpose
941   myDisplayer->enableUpdateViewer(isUpdateEnabled);
942   myDisplayer->updateViewer();
943 }
944
945 //******************************************************
946 void XGUI_Workshop::onRebuild()
947 {
948   SessionPtr aMgr = ModelAPI_Session::get();
949   bool aWasOperation = aMgr->isOperation(); // keep this value
950   if (!aWasOperation) {
951     aMgr->startOperation("Rebuild");
952   }
953   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
954   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
955     new Events_Message(aRebuildEvent, this)));
956   if (!aWasOperation) {
957     aMgr->finishOperation();
958   }
959   updateCommandStatus();
960 }
961
962 //******************************************************
963 void XGUI_Workshop::onPreferences()
964 {
965   ModuleBase_Prefs aModif;
966   ModuleBase_Preferences::editPreferences(aModif);
967   if (aModif.size() > 0) {
968     QString aSection;
969     foreach (ModuleBase_Pref aPref, aModif)
970     {
971       aSection = aPref.first;
972       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
973         if (!isSalomeMode())
974           myMainWindow->viewer()->updateFromResources();
975       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
976         if (!isSalomeMode())
977           myMainWindow->menuObject()->updateFromResources();
978       }
979     }
980   }
981 }
982
983 //******************************************************
984 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
985 {
986   QString libName = QString::fromStdString(library(theModule.toStdString()));
987   if (libName.isEmpty()) {
988     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
989     return 0;
990   }
991
992   QString err;
993   CREATE_FUNC crtInst = 0;
994
995 #ifdef WIN32
996   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
997   if (!modLib) {
998     LPVOID lpMsgBuf;
999     ::FormatMessage(
1000         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1001         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1002     QString aMsg((char*) &lpMsgBuf);
1003     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1004     ::LocalFree(lpMsgBuf);
1005   } else {
1006     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1007     if (!crtInst) {
1008       LPVOID lpMsgBuf;
1009       ::FormatMessage(
1010           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1011               | FORMAT_MESSAGE_IGNORE_INSERTS,
1012           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1013       QString aMsg((char*) &lpMsgBuf);
1014       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1015       ::LocalFree(lpMsgBuf);
1016     }
1017   }
1018 #else
1019   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1020   if ( !modLib ) {
1021     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1022   } else {
1023     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1024     if ( !crtInst ) {
1025       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1026     }
1027   }
1028 #endif
1029
1030   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1031
1032   if (!err.isEmpty()) {
1033     if (mainWindow()) {
1034       Events_Error::send(err.toStdString());
1035     } else {
1036       qWarning(qPrintable(err));
1037     }
1038   }
1039   return aModule;
1040 }
1041
1042 //******************************************************
1043 bool XGUI_Workshop::activateModule()
1044 {
1045   Config_ModuleReader aModuleReader;
1046   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1047   myModule = loadModule(moduleName);
1048   if (!myModule)
1049     return false;
1050
1051   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1052     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1053   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1054     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1055
1056   myModule->createFeatures();
1057   myActionsMgr->update();
1058   return true;
1059 }
1060
1061 //******************************************************
1062 void XGUI_Workshop::updateCommandStatus()
1063 {
1064   QList<QAction*> aCommands;
1065   if (isSalomeMode()) {  // update commands in SALOME mode
1066     aCommands = salomeConnector()->commandList();
1067   } else {
1068     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1069     foreach (AppElements_Command* aCmd, aMenuBar->features())
1070       aCommands.append(aCmd);
1071   }
1072   SessionPtr aMgr = ModelAPI_Session::get();
1073   if (aMgr->hasModuleDocument()) {
1074     QAction *aUndoCmd, *aRedoCmd;
1075     foreach(QAction* aCmd, aCommands) {
1076       QString aId = aCmd->data().toString();
1077       if (aId == "UNDO_CMD")
1078         aUndoCmd = aCmd;
1079       else if (aId == "REDO_CMD")
1080         aRedoCmd = aCmd;
1081       else
1082         // Enable all commands
1083         aCmd->setEnabled(true);
1084     }
1085
1086     aUndoCmd->setEnabled(myModule->canUndo());
1087     aRedoCmd->setEnabled(myModule->canRedo());
1088     updateHistory();
1089   } else {
1090     foreach(QAction* aCmd, aCommands) {
1091       QString aId = aCmd->data().toString();
1092       if (aId == "NEW_CMD")
1093         aCmd->setEnabled(true);
1094       else if (aId == "EXIT_CMD")
1095         aCmd->setEnabled(true);
1096       else
1097         aCmd->setEnabled(false);
1098     }
1099   }
1100   myActionsMgr->update();
1101   emit commandStatusUpdated();
1102 }
1103
1104 void XGUI_Workshop::updateHistory()
1105 {
1106   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1107   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1108   emit updateUndoHistory(aUndoRes);
1109
1110   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1111   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1112   emit updateRedoHistory(aRedoRes);
1113 }
1114
1115 //******************************************************
1116 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1117 {
1118   QDockWidget* aObjDock = new QDockWidget(theParent);
1119   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1120   aObjDock->setWindowTitle(tr("Object browser"));
1121   aObjDock->setStyleSheet(
1122       "::title { position: relative; padding-left: 5px; text-align: left center }");
1123   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1124   myObjectBrowser->setDataModel(myModule->dataModel());
1125   myModule->customizeObjectBrowser(myObjectBrowser);
1126   aObjDock->setWidget(myObjectBrowser);
1127
1128   myContextMenuMgr->connectObjectBrowser();
1129   return aObjDock;
1130 }
1131
1132 //******************************************************
1133 /*
1134  * Creates dock widgets, places them in corresponding area
1135  * and tabifies if necessary.
1136  */
1137 void XGUI_Workshop::createDockWidgets()
1138 {
1139   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1140   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1141   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1142   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1143   myPropertyPanel->setupActions(myActionsMgr);
1144   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1145   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1146   hidePropertyPanel();  ///<! Invisible by default
1147   hideObjectBrowser();
1148   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1149   myPropertyPanel->installEventFilter(myOperationMgr);
1150
1151   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1152   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1153   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1154   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1155   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1156   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1157           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1158   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1159           aOkAct,          SLOT(setEnabled(bool)));
1160   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1161   connect(myOperationMgr,  SIGNAL(nestedStateChanged(bool)),
1162           aAcceptAllAct,   SLOT(setEnabled(bool)));
1163
1164 }
1165
1166 //******************************************************
1167 void XGUI_Workshop::showPropertyPanel()
1168 {
1169   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1170   ///<! Restore ability to close panel from the window's menu
1171   aViewAct->setEnabled(true);
1172   myPropertyPanel->show();
1173   myPropertyPanel->raise();
1174 }
1175
1176 //******************************************************
1177 void XGUI_Workshop::hidePropertyPanel()
1178 {
1179   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1180   ///<! Do not allow to show empty property panel
1181   aViewAct->setEnabled(false);
1182   myPropertyPanel->hide();
1183 }
1184
1185 //******************************************************
1186 void XGUI_Workshop::showObjectBrowser()
1187 {
1188   myObjectBrowser->parentWidget()->show();
1189 }
1190
1191 //******************************************************
1192 void XGUI_Workshop::hideObjectBrowser()
1193 {
1194   myObjectBrowser->parentWidget()->hide();
1195 }
1196
1197 //******************************************************
1198 void XGUI_Workshop::onFeatureTriggered()
1199 {
1200   QAction* aCmd = dynamic_cast<QAction*>(sender());
1201   if (aCmd) {
1202     QString aId = salomeConnector()->commandId(aCmd);
1203     if (!aId.isNull())
1204       myModule->launchOperation(aId);
1205   }
1206 }
1207
1208 //******************************************************
1209 void XGUI_Workshop::salomeViewerSelectionChanged()
1210 {
1211   emit salomeViewerSelection();
1212 }
1213
1214 //**************************************************************
1215 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1216 {
1217   return mySalomeConnector->viewer();
1218 }
1219
1220 //**************************************************************
1221 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1222 {
1223   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1224   if (theId == "DELETE_CMD")
1225     deleteObjects();
1226   else if (theId == "COLOR_CMD")
1227     changeColor(aObjects);
1228   else if (theId == "SHOW_CMD")
1229     showObjects(aObjects, true);
1230   else if (theId == "HIDE_CMD")
1231     showObjects(aObjects, false);
1232   else if (theId == "SHOW_ONLY_CMD")
1233     showOnlyObjects(aObjects);
1234   else if (theId == "SHADING_CMD")
1235     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1236   else if (theId == "WIREFRAME_CMD")
1237     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1238   else if (theId == "HIDEALL_CMD") {
1239     QObjectPtrList aList = myDisplayer->displayedObjects();
1240     foreach (ObjectPtr aObj, aList)
1241       aObj->setDisplayed(false);
1242     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1243   }
1244 }
1245
1246 //**************************************************************
1247 void XGUI_Workshop::deleteObjects()
1248 {
1249   ModuleBase_IModule* aModule = module();
1250   // 1. allow the module to delete objects, do nothing if it has succeed
1251   if (aModule->deleteObjects()) {
1252     updateCommandStatus();
1253     return;
1254   }
1255
1256   if (!isActiveOperationAborted())
1257     return;
1258   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1259   bool hasResult = false;
1260   bool hasFeature = false;
1261   bool hasParameter = false;
1262   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1263   if (!(hasFeature || hasParameter))
1264     return;
1265
1266   // 1. start operation
1267   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1268   aDescription += tr(" %1");
1269   QStringList aObjectNames;
1270   foreach (ObjectPtr aObj, anObjects) {
1271     if (!aObj->data()->isValid())
1272       continue;
1273     aObjectNames << QString::fromStdString(aObj->data()->name());
1274   }
1275   aDescription = aDescription.arg(aObjectNames.join(", "));
1276
1277   SessionPtr aMgr = ModelAPI_Session::get();
1278   aMgr->startOperation(aDescription.toStdString());
1279   // 2. close the documents of the removed parts if the result part is in a list of selected objects
1280   foreach (ObjectPtr aObj, anObjects)
1281   {
1282     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1283     if (aPart) {
1284       DocumentPtr aDoc = aObj->document();
1285       if (aDoc == aMgr->activeDocument()) {
1286         aDoc->close();
1287       }
1288     }
1289   }
1290   // 3. delete objects
1291   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1292   std::set<FeaturePtr> anIgnoredFeatures;
1293   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1294     myDisplayer->updateViewer();
1295     aMgr->finishOperation();
1296     updateCommandStatus();
1297   }
1298   else {
1299     aMgr->abortOperation();
1300   }
1301 }
1302
1303 //**************************************************************
1304 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1305                                    std::set<FeaturePtr> theIgnoredFeatures,
1306                                    QWidget* theParent,
1307                                    const bool theAskAboutDeleteReferences)
1308 {
1309   // 1. find all referenced features
1310   std::set<FeaturePtr> aRefFeatures;
1311   foreach (ObjectPtr aObj, theList) {
1312     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1313     if (aFeature.get() != NULL) {
1314       aObj->document()->refsToFeature(aFeature, aRefFeatures, false);
1315     }
1316   }
1317   // 2. warn about the references remove, break the delete operation if the user chose it
1318   if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1319     QStringList aRefNames;
1320     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1321                                          aLast = aRefFeatures.end();
1322     for (; anIt != aLast; anIt++) {
1323       aRefNames.append((*anIt)->name().c_str());
1324     }
1325     QString aNames = aRefNames.join(", ");
1326
1327     QMessageBox::StandardButton aRes = QMessageBox::warning(
1328         theParent, tr("Delete features"),
1329         QString(tr("Selected features are used in the following features: %1.\
1330 These features will be deleted also. Would you like to continue?")).arg(aNames),
1331         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1332     if (aRes != QMessageBox::Yes)
1333       return false;
1334   }
1335
1336   // 3. remove referenced features
1337   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1338                                        aLast = aRefFeatures.end();
1339   for (; anIt != aLast; anIt++) {
1340     FeaturePtr aFeature = (*anIt);
1341     DocumentPtr aDoc = aFeature->document();
1342     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1343       aDoc->removeFeature(aFeature);
1344   }
1345
1346   // 4. remove the parameter features
1347   foreach (ObjectPtr aObj, theList) {
1348     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1349     if (aFeature) {
1350       DocumentPtr aDoc = aObj->document();
1351       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1352         aDoc->removeFeature(aFeature);
1353     }
1354   }
1355   return true;
1356 }
1357
1358 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1359 {
1360   bool isFoundResultType = false;
1361   foreach(ObjectPtr anObj, theObjects)
1362   {
1363     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1364     if (aResult.get() == NULL)
1365       continue;
1366
1367     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1368     if (isFoundResultType)
1369       break;
1370   }
1371   return isFoundResultType;
1372 }
1373
1374 //**************************************************************
1375 bool XGUI_Workshop::canChangeColor() const
1376 {
1377   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1378
1379   std::set<std::string> aTypes;
1380   aTypes.insert(ModelAPI_ResultGroup::group());
1381   aTypes.insert(ModelAPI_ResultConstruction::group());
1382   aTypes.insert(ModelAPI_ResultBody::group());
1383   aTypes.insert(ModelAPI_ResultPart::group());
1384
1385   return hasResults(aObjects, aTypes);
1386 }
1387
1388 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1389 {
1390   if (!theResult.get())
1391     return;
1392
1393   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1394   if (aColorAttr.get() != NULL) {
1395     if (!aColorAttr->size()) {
1396       aColorAttr->setSize(3);
1397     }
1398     aColorAttr->setValue(0, theColor[0]);
1399     aColorAttr->setValue(1, theColor[1]);
1400     aColorAttr->setValue(2, theColor[2]);
1401   }
1402 }
1403
1404 //**************************************************************
1405 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1406 {
1407   AttributeIntArrayPtr aColorAttr;
1408   // 1. find the current color of the object. This is a color of AIS presentation
1409   // The objects are iterated until a first valid color is found 
1410   std::vector<int> aColor;
1411   foreach(ObjectPtr anObject, theObjects) {
1412     if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1413       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1414       DocumentPtr aPartDoc = aPart->partDoc();
1415       // the document should be checked on null, because in opened document if the part
1416       // has not been activated yet, the part document is empty
1417       if (!aPartDoc.get()) {
1418         emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1419       }
1420       else {
1421         if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1422           ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1423           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1424           if (aBody.get()) {
1425             std::string aSection, aName, aDefault;
1426             aBody->colorConfigInfo(aSection, aName, aDefault);
1427             if (!aSection.empty() && !aName.empty()) {
1428               aColor = Config_PropManager::color(aSection, aName, aDefault);
1429             }
1430           }
1431         }
1432       }
1433     }
1434     else {
1435       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1436       if (anAISObj.get()) {
1437         aColor.resize(3);
1438         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1439       }
1440     }
1441     if (!aColor.empty())
1442       break;
1443   }
1444   if (aColor.size() != 3)
1445     return;
1446
1447   // 2. show the dialog to change the value
1448   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1449   aDlg->setColor(aColor);
1450   aDlg->move(QCursor::pos());
1451   bool isDone = aDlg->exec() == QDialog::Accepted;
1452   if (!isDone)
1453     return;
1454
1455   bool isRandomColor = aDlg->isRandomColor();
1456
1457   // 3. abort the previous operation and start a new one
1458   SessionPtr aMgr = ModelAPI_Session::get();
1459   bool aWasOperation = aMgr->isOperation(); // keep this value
1460   if (!aWasOperation) {
1461     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1462     aMgr->startOperation(aDescription.toStdString());
1463   }
1464
1465   // 4. set the value to all results
1466   foreach(ObjectPtr anObj, theObjects) {
1467     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1468     if (aResult.get() != NULL) {
1469       if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1470         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1471         DocumentPtr aPartDoc = aPart->partDoc();
1472         // the document should be checked on null, because in opened document if the part
1473         // has not been activated yet, the part document is empty
1474         if (aPartDoc.get()) {
1475           for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1476             ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1477             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1478             std::vector<int> aColorResult = aDlg->getColor();
1479             setColor(aBody, aColorResult);
1480           }
1481         }
1482       }
1483       else {
1484         std::vector<int> aColorResult = aDlg->getColor();
1485         setColor(aResult, aColorResult);
1486       }
1487     }
1488   }
1489   if (!aWasOperation)
1490     aMgr->finishOperation();
1491   updateCommandStatus();
1492 }
1493
1494 //**************************************************************
1495 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1496 {
1497   foreach (ObjectPtr aObj, theList) {
1498     if (isVisible) {
1499       aObj->setDisplayed(true);
1500       //displayObject(aObj);
1501     } else {
1502       aObj->setDisplayed(false);
1503       //myDisplayer->erase(aObj, false);
1504     }
1505   }
1506   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1507   //myDisplayer->updateViewer();
1508 }
1509
1510 //**************************************************************
1511 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1512 {
1513   QObjectPtrList aList = myDisplayer->displayedObjects();
1514   foreach (ObjectPtr aObj, aList)
1515     aObj->setDisplayed(false);
1516   foreach (ObjectPtr aObj, theList)
1517     aObj->setDisplayed(true);
1518   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1519
1520 }
1521
1522
1523 //**************************************************************
1524 void XGUI_Workshop::registerValidators() const
1525 {
1526   SessionPtr aMgr = ModelAPI_Session::get();
1527   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1528 }
1529
1530 //**************************************************************
1531 void XGUI_Workshop::displayAllResults()
1532 {
1533   SessionPtr aMgr = ModelAPI_Session::get();
1534   DocumentPtr aRootDoc = aMgr->moduleDocument();
1535   displayDocumentResults(aRootDoc);
1536   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1537     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1538     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1539     displayDocumentResults(aPart->partDoc());
1540   }
1541   myDisplayer->updateViewer();
1542 }
1543
1544 //**************************************************************
1545 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1546 {
1547   if (!theDoc)
1548     return;
1549   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1550   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1551 }
1552
1553 //**************************************************************
1554 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1555 {
1556   for (int i = 0; i < theDoc->size(theGroup); i++) 
1557     theDoc->object(theGroup, i)->setDisplayed(true);
1558     //displayObject(theDoc->object(theGroup, i));
1559   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1560 }
1561
1562 //**************************************************************
1563 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1564 {
1565   foreach(ObjectPtr aObj, theList) {
1566     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1567   }
1568   if (theList.size() > 0)
1569     myDisplayer->updateViewer();
1570 }
1571
1572 //**************************************************************
1573 void XGUI_Workshop::closeDocument()
1574 {
1575   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1576   while (anOperation) {
1577     anOperation->abort();
1578     anOperation = operationMgr()->currentOperation();
1579   }
1580   myDisplayer->closeLocalContexts();
1581   myDisplayer->eraseAll();
1582   objectBrowser()->clearContent();
1583
1584   SessionPtr aMgr = ModelAPI_Session::get();
1585   aMgr->closeAll();
1586 }
1587
1588 //**************************************************************
1589 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1590 {
1591   if (!myModule->canDisplayObject(theObj))
1592     return false;
1593
1594   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1595   if (aBody.get() != NULL) {
1596     int aNb = myDisplayer->objectsCount();
1597     myDisplayer->display(theObj, false);
1598     if (aNb == 0)
1599       viewer()->fitAll();
1600   } else if (!(myIsLoadingData || myPartActivating))
1601     myDisplayer->display(theObj, false);
1602
1603   return true;
1604 }
1605
1606 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1607 {
1608   XGUI_HistoryMenu* aMenu = NULL;
1609   if (isSalomeMode()) {
1610     QAction* anAction = qobject_cast<QAction*>(theObject);
1611     if (!anAction)
1612       return;
1613     aMenu = new XGUI_HistoryMenu(anAction);
1614   } else {
1615     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1616     aMenu = new XGUI_HistoryMenu(aButton);
1617   }
1618   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1619   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1620 }
1621
1622 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1623 {
1624   QList<ActionInfo> aResult;
1625   std::list<std::string>::const_iterator it = theList.cbegin();
1626   for (; it != theList.cend(); it++) {
1627     QString anId = QString::fromStdString(*it);
1628     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1629     if (isEditing) {
1630       anId.chop(ModuleBase_Operation::EditSuffix().size());
1631     }
1632     ActionInfo anInfo;
1633     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1634     if (aContextMenuAct) {
1635       anInfo.initFrom(aContextMenuAct);
1636     } else {
1637       anInfo = myActionsMgr->actionInfoById(anId);
1638     }
1639     if (isEditing) {
1640       anInfo.text = anInfo.text.prepend("Modify ");
1641     }
1642     aResult << anInfo;
1643   }
1644   return aResult;
1645 }