Salome HOME
Merge branch 'master' of newgeom:newgeom
[modules/shaper.git] / src / XGUI / XGUI_Workshop.cpp
index 4bd292de7fcd7459df0e1c9f91e07bbb84aeea0b..6507c3557c4f4ffd26c5584d8807a725c52cc6af 100644 (file)
 #include "XGUI_ContextMenuMgr.h"
 #include "XGUI_ModuleConnector.h"
 #include "XGUI_Preferences.h"
+#include <XGUI_QtEvents.h>
 
 #include <ModelAPI_Events.h>
-#include <ModelAPI_PluginManager.h>
+#include <ModelAPI_Session.h>
 #include <ModelAPI_Feature.h>
 #include <ModelAPI_Data.h>
 #include <ModelAPI_AttributeDocRef.h>
@@ -43,7 +44,8 @@
 #include <ModuleBase_Operation.h>
 #include <ModuleBase_OperationDescription.h>
 #include <ModuleBase_SelectionValidator.h>
-#include "ModuleBase_WidgetFactory.h"
+#include <ModuleBase_WidgetFactory.h>
+#include <ModuleBase_Tools.h>
 
 #include <Config_Common.h>
 #include <Config_FeatureMessage.h>
 #include <QPushButton>
 #include <QDockWidget>
 #include <QLayout>
-#include <QTimer>
+#include <QThread>
+#include <QObject>
 
 #ifdef _DEBUG
 #include <QDebug>
+#include <iostream>
 #endif
 
 #ifdef WIN32
@@ -87,7 +91,8 @@ XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
       myPropertyPanel(0),
       myObjectBrowser(0),
       myDisplayer(0),
-      myUpdatePrefs(false)
+      myUpdatePrefs(false),
+      myPartActivating(false)
 {
   myMainWindow = mySalomeConnector ? 0 : new XGUI_MainWindow();
 
@@ -122,6 +127,7 @@ XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
 //******************************************************
 XGUI_Workshop::~XGUI_Workshop(void)
 {
+  delete myDisplayer;
 }
 
 //******************************************************
@@ -141,6 +147,9 @@ void XGUI_Workshop::startApplication()
   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
   aLoop->registerListener(this, Events_Loop::eventByName("LongOperation"));
   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
+  aLoop->registerListener(this, Events_Loop::eventByName("CurrentDocumentChanged"));
+  aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOSHOW));
+  aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
 
   registerValidators();
   activateModule();
@@ -190,10 +199,11 @@ void XGUI_Workshop::initMenu()
   aCommand->connectTo(this, SLOT(onRedo()));
 
   aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
-                                QIcon(":pictures/rebuild.png"));
+    QIcon(":pictures/rebuild.png"), QKeySequence());
+  aCommand->connectTo(this, SLOT(onRebuild()));
 
   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
-                                QIcon(":pictures/save.png"));
+                                QIcon(":pictures/save.png"), QKeySequence());
   aCommand->connectTo(this, SLOT(onSaveAs()));
   //aCommand->disable();
 
@@ -228,72 +238,96 @@ XGUI_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
 }
 
 //******************************************************
-void XGUI_Workshop::processEvent(const Events_Message* theMessage)
+void XGUI_Workshop::processEvent(const boost::shared_ptr<Events_Message>& theMessage)
 {
+  if (QApplication::instance()->thread() != QThread::currentThread()) {
+    #ifdef _DEBUG
+    std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
+    #endif
+    SessionPtr aMgr = ModelAPI_Session::get();
+    PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
+    QApplication::postEvent(this, aPostponeEvent);
+    return;
+  }
+
   //A message to start feature creation received.
   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_LOADED)) {
-    const Config_FeatureMessage* aFeatureMsg =
-        dynamic_cast<const Config_FeatureMessage*>(theMessage);
+    boost::shared_ptr<Config_FeatureMessage> aFeatureMsg =
+       boost::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
     if (!aFeatureMsg->isInternal()) {
       addFeature(aFeatureMsg);
     }
-    return;
   }
 
   // Process creation of Part
-  if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
-    const ModelAPI_ObjectUpdatedMessage* aUpdMsg =
-        dynamic_cast<const ModelAPI_ObjectUpdatedMessage*>(theMessage);
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
+    boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
+        boost::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
     onFeatureCreatedMsg(aUpdMsg);
     if (myUpdatePrefs) {
       if (mySalomeConnector)
         mySalomeConnector->createPreferences();
       myUpdatePrefs = false;
     }
-    return;
   }
-  if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
     myUpdatePrefs = true;
-    return;
   }
 
   // Redisplay feature
-  if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
-    const ModelAPI_ObjectUpdatedMessage* aUpdMsg =
-        dynamic_cast<const ModelAPI_ObjectUpdatedMessage*>(theMessage);
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
+    boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
+        boost::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
     onFeatureRedisplayMsg(aUpdMsg);
-    return;
   }
 
   //Update property panel on corresponding message. If there is no current operation (no
   //property panel), or received message has different feature to the current - do nothing.
-  if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
-    const ModelAPI_ObjectUpdatedMessage* anUpdateMsg =
-        dynamic_cast<const ModelAPI_ObjectUpdatedMessage*>(theMessage);
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
+    boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
+        boost::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
     onFeatureUpdatedMsg(anUpdateMsg);
-    return;
   }
 
-  if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
-    const ModelAPI_ObjectDeletedMessage* aDelMsg =
-        dynamic_cast<const ModelAPI_ObjectDeletedMessage*>(theMessage);
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
+    boost::shared_ptr<ModelAPI_ObjectDeletedMessage> aDelMsg =
+        boost::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
     onObjectDeletedMsg(aDelMsg);
-    return;
   }
 
-  if (theMessage->eventID() == Events_LongOp::eventID()) {
+  else if (theMessage->eventID() == Events_LongOp::eventID()) {
     if (Events_LongOp::isPerformed())
       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    //QTimer::singleShot(10, this, SLOT(onStartWaiting()));
     else
       QApplication::restoreOverrideCursor();
-    return;
+  }
+
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOSHOW)) {
+    boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
+        boost::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
+    const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
+    QList<ObjectPtr> aList;
+    std::set<ObjectPtr>::const_iterator aIt;
+    for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
+      aList.append(*aIt);
+    showObjects(aList, true);
+  }
+
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE)) {
+    boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
+        boost::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
+    const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
+    QList<ObjectPtr> aList;
+    std::set<ObjectPtr>::const_iterator aIt;
+    for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
+      aList.append(*aIt);
+    showObjects(aList, false);
   }
 
   //An operation passed by message. Start it, process and commit.
-  if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
-    const Config_PointerMessage* aPartSetMsg =
-        dynamic_cast<const Config_PointerMessage*>(theMessage);
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
+    boost::shared_ptr<Config_PointerMessage> aPartSetMsg =
+        boost::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
     //myPropertyPanel->cleanContent();
     ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
 
@@ -304,12 +338,41 @@ void XGUI_Workshop::processEvent(const Events_Message* theMessage)
           updateCommandStatus();
       }
     }
-    return;
   }
-  //Show error dialog if error message received.
-  const Events_Error* anAppError = dynamic_cast<const Events_Error*>(theMessage);
-  if (anAppError) {
-    emit errorOccurred(QString::fromLatin1(anAppError->description()));
+  else if (theMessage->eventID() == Events_Loop::loop()->eventByName("CurrentDocumentChanged")) {
+    // Find and Activate active part
+    if (myPartActivating)
+      return;
+    myActionsMgr->update();
+    SessionPtr aMgr = ModelAPI_Session::get();
+    DocumentPtr aActiveDoc = aMgr->activeDocument();
+    DocumentPtr aDoc = aMgr->moduleDocument();
+    if (aActiveDoc == aDoc) {
+      activatePart(ResultPartPtr()); 
+      return;
+    }
+    std::string aGrpName = ModelAPI_ResultPart::group();
+    for (int i = 0; i < aDoc->size(aGrpName); i++) {
+      ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aDoc->object(aGrpName, i));
+      if (aPart->partDoc() == aActiveDoc) {
+        activatePart(aPart); // Activate a part which corresponds to active Doc
+        return;
+      }
+    }
+    // If not found then activate global document
+    activatePart(ResultPartPtr()); 
+
+  } else {
+    //Show error dialog if error message received.
+    boost::shared_ptr<Events_Error> anAppError = boost::dynamic_pointer_cast<Events_Error>(theMessage);
+    if (anAppError) {
+      emit errorOccurred(QString::fromLatin1(anAppError->description()));
+    }
+  }
+  if (!isSalomeMode()) {
+    SessionPtr aMgr = ModelAPI_Session::get();
+    if (aMgr->isModified() != myMainWindow->isModifiedState())
+      myMainWindow->setModifiedState(aMgr->isModified());
   }
 }
 
@@ -323,7 +386,7 @@ void XGUI_Workshop::onStartWaiting()
 }
 
 //******************************************************
-void XGUI_Workshop::onFeatureUpdatedMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
+void XGUI_Workshop::onFeatureUpdatedMsg(const boost::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
 {
   std::set<ObjectPtr> aFeatures = theMsg->objects();
   if (myOperationMgr->hasOperation()) {
@@ -337,26 +400,38 @@ void XGUI_Workshop::onFeatureUpdatedMsg(const ModelAPI_ObjectUpdatedMessage* the
       }
     }
   }
-  myOperationMgr->validateCurrentOperation();
+  myOperationMgr->onValidateOperation();
+  if (myObjectBrowser)
+    myObjectBrowser->processEvent(theMsg);
 }
 
 //******************************************************
-void XGUI_Workshop::onFeatureRedisplayMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
+void XGUI_Workshop::onFeatureRedisplayMsg(const boost::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
 {
   std::set<ObjectPtr> aObjects = theMsg->objects();
   std::set<ObjectPtr>::const_iterator aIt;
   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
     ObjectPtr aObj = (*aIt);
-    if (!aObj->data() || !aObj->data()->isValid())
+    if (!aObj->data() || !aObj->data()->isValid() || aObj->document()->isConcealed(aObj))
       myDisplayer->erase(aObj, false);
     else {
-      if (myDisplayer->isVisible(aObj))  // TODO VSV: Correction sketch drawing
+      if (myDisplayer->isVisible(aObj))  {
         myDisplayer->display(aObj, false);  // In order to update presentation
-      else {
         if (myOperationMgr->hasOperation()) {
           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
-          if (aOperation->hasObject(aObj)) {  // Display only current operation results
+          if (!aOperation->hasObject(aObj))
+            if (!myDisplayer->isActive(aObj))
+              myDisplayer->activate(aObj);
+        }
+      } else {
+        if (myOperationMgr->hasOperation()) {
+          ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
+          // Display only current operation results if operation has preview
+          if (aOperation->hasObject(aObj) && aOperation->hasPreview()) {
             myDisplayer->display(aObj, false);
+            // Deactivate object of current operation from selection
+            if (myDisplayer->isActive(aObj))
+              myDisplayer->deactivate(aObj);
           }
         }
       }
@@ -366,7 +441,7 @@ void XGUI_Workshop::onFeatureRedisplayMsg(const ModelAPI_ObjectUpdatedMessage* t
 }
 
 //******************************************************
-void XGUI_Workshop::onFeatureCreatedMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
+void XGUI_Workshop::onFeatureCreatedMsg(const boost::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
 {
   std::set<ObjectPtr> aObjects = theMsg->objects();
 
@@ -381,24 +456,27 @@ void XGUI_Workshop::onFeatureCreatedMsg(const ModelAPI_ObjectUpdatedMessage* the
       // it doesn't stored in the operation mgr and doesn't displayed
     } else if (myOperationMgr->hasOperation()) {
       ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
-      if (aOperation->hasObject(*aIt)) {  // Display only current operation results
+      if (!(*aIt)->document()->isConcealed(*aIt) &&
+          aOperation->hasObject(*aIt)) {  // Display only current operation results
         myDisplayer->display(*aIt, false);
         isDisplayed = true;
       }
     }
   }
+  if (myObjectBrowser)
+    myObjectBrowser->processEvent(theMsg);
   if (isDisplayed)
     myDisplayer->updateViewer();
-  if (aHasPart) {
-    //The created part will be created in Object Browser later and we have to activate it
-    // only when it is created everywere
-    QTimer::singleShot(50, this, SLOT(activateLastPart()));
-  }
+  //if (aHasPart) { // TODO: Avoid activate last part on loading of document
+  //  activateLastPart();
+  //}
 }
 
 //******************************************************
-void XGUI_Workshop::onObjectDeletedMsg(const ModelAPI_ObjectDeletedMessage* theMsg)
+void XGUI_Workshop::onObjectDeletedMsg(const boost::shared_ptr<ModelAPI_ObjectDeletedMessage>& theMsg)
 {
+  if (myObjectBrowser)
+    myObjectBrowser->processEvent(theMsg);
   //std::set<ObjectPtr> aFeatures = theMsg->objects();
 }
 
@@ -421,6 +499,7 @@ void XGUI_Workshop::onOperationStarted()
 
     myPropertyPanel->cleanContent();
     aFactory.createWidget(myPropertyPanel->contentWidget());
+    ModuleBase_Tools::zeroMargins(myPropertyPanel->contentWidget());
 
     QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
     QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
@@ -428,6 +507,7 @@ void XGUI_Workshop::onOperationStarted()
     for (; anIt != aLast; anIt++) {
       aWidget = *anIt;
       aWidget->setFeature(aOperation->feature());
+      aWidget->enableFocusProcessing();
       QObject::connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onWidgetValuesChanged()));
       // Init default values
       if (!aOperation->isEditOperation() && !aWidget->isComputedDefault()) {
@@ -435,8 +515,14 @@ void XGUI_Workshop::onOperationStarted()
       }
     }
 
+    aOperation->setPropertyPanel(myPropertyPanel);
     myPropertyPanel->setModelWidgets(aWidgets);
-    myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
+    myPropertyPanel->activateNextWidget(NULL);
+    // Widget activation (from the previous method) may commit the current operation
+    // if pre-selection is enougth for it. So we shouldn't update prop panel's title
+    if(myOperationMgr->isCurrentOperation(aOperation)) {
+      myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
+    }
   }
   updateCommandStatus();
 }
@@ -450,10 +536,21 @@ void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
   myPropertyPanel->cleanContent();
 }
 
+bool XGUI_Workshop::event(QEvent * theEvent)
+{
+  PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
+  if (aPostponedEv) {
+    boost::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
+    processEvent(aEventPtr);
+    return true;
+  }
+  return false;
+}
+
 /*
  *
  */
-void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
+void XGUI_Workshop::addFeature(const boost::shared_ptr<Config_FeatureMessage>& theMessage)
 {
   if (!theMessage) {
 #ifdef _DEBUG
@@ -474,7 +571,8 @@ void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
                                                      QString::fromStdString(theMessage->text()),
                                                      QString::fromStdString(theMessage->tooltip()),
                                                      QIcon(theMessage->icon().c_str()),
-                                                     QKeySequence(), isUsePropPanel);
+                                                     QKeySequence(),
+                                                     isUsePropPanel);
     salomeConnector()->setNestedActions(aFeatureId, aNestedFeatures.split(" ", QString::SkipEmptyParts));
     myActionsMgr->addCommand(aAction);
     myModule->featureCreated(aAction);
@@ -491,6 +589,7 @@ void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
     if (!aGroup) {
       aGroup = aPage->addGroup(aGroupName);
     }
+    QString aDocKind = QString::fromStdString(theMessage->documentKind());
     // Check if hotkey sequence is already defined:
     QKeySequence aHotKey = myActionsMgr->registerShortcut(
         QString::fromStdString(theMessage->keysequence()));
@@ -498,7 +597,9 @@ void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
     XGUI_Command* aCommand = aGroup->addFeature(aFeatureId,
                                                 QString::fromStdString(theMessage->text()),
                                                 QString::fromStdString(theMessage->tooltip()),
-                                                QIcon(theMessage->icon().c_str()), aHotKey,
+                                                QIcon(theMessage->icon().c_str()),
+                                                aDocKind,
+                                                aHotKey,
                                                 isUsePropPanel);
     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
     myActionsMgr->addCommand(aCommand);
@@ -518,32 +619,37 @@ void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
   } else {
     XGUI_MainMenu* aMenu = myMainWindow->menuObject();
-    aCommand = aMenu->feature(theOperation->getDescription()->operationId());
+    FeaturePtr aFeature = theOperation->feature();
+    if(aFeature)
+      aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
   }
   //Abort operation on uncheck the command
-  if (aCommand)
+  if (aCommand) {
     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
+  }
 }
 
 /*
  * Saves document with given name.
  */
-void XGUI_Workshop::saveDocument(QString theName)
+void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
 {
   QApplication::restoreOverrideCursor();
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aDoc = aMgr->rootDocument();
-  std::list<std::string> aFileNames;
-  aDoc->save(theName.toLatin1().constData(), aFileNames);
+  SessionPtr aMgr = ModelAPI_Session::get();
+  aMgr->save(theName.toLatin1().constData(), theFileNames);
   QApplication::restoreOverrideCursor();
 }
 
+bool XGUI_Workshop::isActiveOperationAborted()
+{
+  return myOperationMgr->abortAllOperations();
+}
+
 //******************************************************
 void XGUI_Workshop::onExit()
 {
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aDoc = aMgr->rootDocument();
-  if (aDoc->isModified()) {
+  SessionPtr aMgr = ModelAPI_Session::get();
+  if (aMgr->isModified()) {
     int anAnswer = QMessageBox::question(
         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
@@ -582,10 +688,11 @@ void XGUI_Workshop::onNew()
 //******************************************************
 void XGUI_Workshop::onOpen()
 {
+  if(!isActiveOperationAborted())
+    return;
   //save current file before close if modified
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aDoc = aMgr->rootDocument();
-  if (aDoc->isModified()) {
+  SessionPtr aSession = ModelAPI_Session::get();
+  if (aSession->isModified()) {
     //TODO(sbh): re-launch the app?
     int anAnswer = QMessageBox::question(
         myMainWindow, tr("Save current file"),
@@ -596,7 +703,7 @@ void XGUI_Workshop::onOpen()
     } else if (anAnswer == QMessageBox::Cancel) {
       return;
     }
-    aDoc->close();
+    aSession->moduleDocument()->close();
     myCurrentDir = "";
   }
 
@@ -611,7 +718,7 @@ void XGUI_Workshop::onOpen()
     return;
   }
   QApplication::setOverrideCursor(Qt::WaitCursor);
-  aDoc->load(myCurrentDir.toLatin1().constData());
+  aSession->load(myCurrentDir.toLatin1().constData());
   myObjectBrowser->rebuildDataTree();
   displayAllResults();
   updateCommandStatus();
@@ -621,17 +728,23 @@ void XGUI_Workshop::onOpen()
 //******************************************************
 bool XGUI_Workshop::onSave()
 {
+  if(!isActiveOperationAborted())
+    return false;
   if (myCurrentDir.isEmpty()) {
     return onSaveAs();
   }
-  saveDocument(myCurrentDir);
+  std::list<std::string> aFiles;
+  saveDocument(myCurrentDir, aFiles);
   updateCommandStatus();
+  myMainWindow->setModifiedState(false);
   return true;
 }
 
 //******************************************************
 bool XGUI_Workshop::onSaveAs()
 {
+  if(!isActiveOperationAborted())
+    return false;
   QFileDialog dialog(mainWindow());
   dialog.setWindowTitle(tr("Select directory to save files..."));
   dialog.setFileMode(QFileDialog::Directory);
@@ -656,6 +769,10 @@ bool XGUI_Workshop::onSaveAs()
     }
   }
   myCurrentDir = aTempDir;
+  if (!isSalomeMode()) {
+    myMainWindow->setCurrentDir(myCurrentDir, false);
+    myMainWindow->setModifiedState(false);
+  }
   return onSave();
 }
 
@@ -663,11 +780,10 @@ bool XGUI_Workshop::onSaveAs()
 void XGUI_Workshop::onUndo()
 {
   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aDoc = aMgr->rootDocument();
-  if (aDoc->isOperation())
-    operationMgr()->abortOperation();
-  aDoc->undo();
+  SessionPtr aMgr = ModelAPI_Session::get();
+  if (aMgr->isOperation())
+    operationMgr()->onAbortOperation();
+  aMgr->undo();
   updateCommandStatus();
 }
 
@@ -675,14 +791,29 @@ void XGUI_Workshop::onUndo()
 void XGUI_Workshop::onRedo()
 {
   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aDoc = aMgr->rootDocument();
-  if (aDoc->isOperation())
-    operationMgr()->abortOperation();
-  aDoc->redo();
+  SessionPtr aMgr = ModelAPI_Session::get();
+  if (aMgr->isOperation())
+    operationMgr()->onAbortOperation();
+  aMgr->redo();
   updateCommandStatus();
 }
 
+//******************************************************
+void XGUI_Workshop::onRebuild()
+{
+  SessionPtr aMgr = ModelAPI_Session::get();
+  bool aWasOperation = aMgr->isOperation(); // keep this value
+  if (!aWasOperation) {
+    aMgr->startOperation();
+  }
+  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
+  Events_Loop::loop()->send(boost::shared_ptr<Events_Message>(
+    new Events_Message(aRebuildEvent, this)));
+  if (!aWasOperation) {
+    aMgr->finishOperation();
+  }
+}
+
 //******************************************************
 void XGUI_Workshop::onPreferences()
 {
@@ -755,7 +886,7 @@ ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
 
   if (!err.isEmpty()) {
     if (mainWindow()) {
-      QMessageBox::warning(mainWindow(), tr("Error"), err);
+      Events_Error::send(err.toStdString());
     } else {
       qWarning(qPrintable(err));
     }
@@ -787,12 +918,11 @@ void XGUI_Workshop::updateCommandStatus()
     foreach (XGUI_Command* aCmd, aMenuBar->features())
       aCommands.append(aCmd);
   }
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  if (aMgr->hasRootDocument()) {
+  SessionPtr aMgr = ModelAPI_Session::get();
+  if (aMgr->hasModuleDocument()) {
     QAction* aUndoCmd;
     QAction* aRedoCmd;
-    foreach(QAction* aCmd, aCommands)
-    {
+    foreach(QAction* aCmd, aCommands) {
       QString aId = aCmd->data().toString();
       if (aId == "UNDO_CMD")
         aUndoCmd = aCmd;
@@ -802,12 +932,10 @@ void XGUI_Workshop::updateCommandStatus()
         // Enable all commands
         aCmd->setEnabled(true);
     }
-    DocumentPtr aDoc = aMgr->rootDocument();
-    aUndoCmd->setEnabled(aDoc->canUndo());
-    aRedoCmd->setEnabled(aDoc->canRedo());
+    aUndoCmd->setEnabled(aMgr->canUndo());
+    aRedoCmd->setEnabled(aMgr->canRedo());
   } else {
-    foreach(QAction* aCmd, aCommands)
-    {
+    foreach(QAction* aCmd, aCommands) {
       QString aId = aCmd->data().toString();
       if (aId == "NEW_CMD")
         aCmd->setEnabled(true);
@@ -874,14 +1002,12 @@ void XGUI_Workshop::createDockWidgets()
   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_CANCEL);
   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
-//TODO(sbh): KeyReleasedProblem
   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)), myOperationMgr,
           SLOT(onKeyReleased(QKeyEvent*)));
-
-  connect(myPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)), myOperationMgr,
-          SLOT(onWidgetActivated(ModuleBase_ModelWidget*)));
-  connect(myOperationMgr, SIGNAL(activateNextWidget(ModuleBase_ModelWidget*)), myPropertyPanel,
-          SLOT(onActivateNextWidget(ModuleBase_ModelWidget*)));
+  //connect(myPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)), myOperationMgr,
+  //        SLOT(onWidgetActivated(ModuleBase_ModelWidget*)));
+  //connect(myOperationMgr, SIGNAL(activateNextWidget(ModuleBase_ModelWidget*)), myPropertyPanel,
+  //        SLOT(onActivateNextWidget(ModuleBase_ModelWidget*)));
   connect(myOperationMgr, SIGNAL(operationValidated(bool)), myPropertyPanel,
           SLOT(setAcceptEnabled(bool)));
 
@@ -932,18 +1058,18 @@ void XGUI_Workshop::onFeatureTriggered()
 //******************************************************
 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
 {
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
+  SessionPtr aMgr = ModelAPI_Session::get();
   if (theObj) {
     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
     if (aPart) {
       DocumentPtr aPartDoc = aPart->partDoc();
       if (aPartDoc) {
-        aMgr->setCurrentDocument(aPartDoc);
+        aMgr->setActiveDocument(aPartDoc);
         return;
       }
     }
   }
-  aMgr->setCurrentDocument(aMgr->rootDocument());
+  aMgr->setActiveDocument(aMgr->moduleDocument());
 }
 
 //******************************************************
@@ -975,6 +1101,12 @@ void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
     showObjects(aObjects, false);
   else if (theId == "SHOW_ONLY_CMD")
     showOnlyObjects(aObjects);
+  else if (theId == "SHADING_CMD")
+    setDisplayMode(aObjects, XGUI_Displayer::Shading);
+  else if (theId == "WIREFRAME_CMD")
+    setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
+  else if (theId == "HIDEALL_CMD")
+    myDisplayer->eraseAll();
 }
 
 //**************************************************************
@@ -1001,22 +1133,27 @@ void XGUI_Workshop::onWidgetValuesChanged()
 //**************************************************************
 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
 {
-  if (theFeature)
-    theFeature->activate();
-  changeCurrentDocument(theFeature);
-  myObjectBrowser->activatePart(theFeature);
+  if (!myPartActivating) {
+    myPartActivating = true;
+    if (theFeature)
+      theFeature->activate();
+    changeCurrentDocument(theFeature);
+    myObjectBrowser->activatePart(theFeature);
+    myPartActivating = false;
+  }
 }
 
 //**************************************************************
 void XGUI_Workshop::activateLastPart()
 {
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aDoc = aMgr->rootDocument();
+  SessionPtr aMgr = ModelAPI_Session::get();
+  DocumentPtr aDoc = aMgr->moduleDocument();
   std::string aGrpName = ModelAPI_ResultPart::group();
   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
   ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
-  if (aPart)
+  if (aPart) {
     activatePart(aPart);
+  }
 }
 
 //**************************************************************
@@ -1028,17 +1165,17 @@ void XGUI_Workshop::deleteObjects(const QList<ObjectPtr>& theList)
       QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
   // ToDo: definbe deleting method
   if (aRes == QMessageBox::Yes) {
-    PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-    aMgr->rootDocument()->startOperation();
+    SessionPtr aMgr = ModelAPI_Session::get();
+    aMgr->startOperation();
     foreach (ObjectPtr aObj, theList)
     {
       ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
       if (aPart) {
         DocumentPtr aDoc = aPart->document();
-        if (aDoc == aMgr->currentDocument()) {
+        if (aDoc == aMgr->activeDocument()) {
           aDoc->close();
         }
-        //aMgr->rootDocument()->removeFeature(aPart->owner());
+        //aMgr->moduleDocument()->removeFeature(aPart->owner());
       } else {
         FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
         if (aFeature)
@@ -1046,7 +1183,7 @@ void XGUI_Workshop::deleteObjects(const QList<ObjectPtr>& theList)
       }
     }
     myDisplayer->updateViewer();
-    aMgr->rootDocument()->finishOperation();
+    aMgr->finishOperation();
   }
 }
 
@@ -1078,16 +1215,27 @@ void XGUI_Workshop::showOnlyObjects(const QList<ObjectPtr>& theList)
 //**************************************************************
 void XGUI_Workshop::updateCommandsOnViewSelection()
 {
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
   XGUI_Selection* aSelection = mySelector->selection();
   if (aSelection->getSelected().size() == 0)
     return;
 
+  // Restrict validators to manage only nested (child) features
+  // of the current feature i.e. if current feature is Sketch -
+  // Sketch Features & Constraints can be validated.
+  QStringList aNestedIds;
+  if(myOperationMgr->hasOperation()) {
+    FeaturePtr aFeature = myOperationMgr->currentOperation()->feature();
+    if(aFeature) {
+      aNestedIds << myActionsMgr->nestedCommands(QString::fromStdString(aFeature->getKind()));
+    }
+  }
+  SessionPtr aMgr = ModelAPI_Session::get();
+  ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
   QList<QAction*> aActions = getModuleCommands();
-  foreach(QAction* aAction, aActions)
-  {
+  foreach(QAction* aAction, aActions) {
     QString aId = aAction->data().toString();
+    if(!aNestedIds.contains(aId))
+      continue;
     std::list<ModelAPI_Validator*> aValidators;
     std::list<std::list<std::string> > anArguments;
     aFactory->validators(aId.toStdString(), aValidators, anArguments);
@@ -1107,15 +1255,15 @@ void XGUI_Workshop::updateCommandsOnViewSelection()
 //**************************************************************
 void XGUI_Workshop::registerValidators() const
 {
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
+  SessionPtr aMgr = ModelAPI_Session::get();
   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
 }
 
 //**************************************************************
 void XGUI_Workshop::displayAllResults()
 {
-  PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
-  DocumentPtr aRootDoc = aMgr->rootDocument();
+  SessionPtr aMgr = ModelAPI_Session::get();
+  DocumentPtr aRootDoc = aMgr->moduleDocument();
   displayDocumentResults(aRootDoc);
   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
@@ -1140,3 +1288,13 @@ void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup
   for (int i = 0; i < theDoc->size(theGroup); i++)
     myDisplayer->display(theDoc->object(theGroup, i), false);
 }
+
+//**************************************************************
+void XGUI_Workshop::setDisplayMode(const QList<ObjectPtr>& theList, int theMode)
+{
+  foreach(ObjectPtr aObj, theList) {
+    myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
+  }
+  if (theList.size() > 0)
+    myDisplayer->updateViewer();
+}