1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
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>
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>
30 #include <ModuleBase_IModule.h>
31 #include <ModuleBase_Preferences.h>
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>
46 //#include <PartSetPlugin_Part.h>
48 #include <Events_Loop.h>
49 #include <Events_Error.h>
50 #include <Events_LongOp.h>
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>
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>
70 #include <QApplication>
71 #include <QFileDialog>
72 #include <QMessageBox>
73 #include <QMdiSubWindow>
74 #include <QPushButton>
75 #include <QDockWidget>
80 #include <QToolButton>
94 //#define DEBUG_FEATURE_CREATED
95 //#define DEBUG_FEATURE_REDISPLAY
98 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
100 myCurrentDir(QString()),
102 mySalomeConnector(theConnector),
106 myUpdatePrefs(false),
107 myPartActivating(false),
108 myIsLoadingData(false)
110 myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
112 myDisplayer = new XGUI_Displayer(this);
114 mySelector = new XGUI_SelectionMgr(this);
115 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
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)));
124 myViewerProxy = new XGUI_ViewerProxy(this);
125 connect(myViewerProxy, SIGNAL(selectionChanged()),
126 myActionsMgr, SLOT(updateOnViewSelection()));
128 myModuleConnector = new XGUI_ModuleConnector(this);
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&)));
144 //******************************************************
145 XGUI_Workshop::~XGUI_Workshop(void)
150 //******************************************************
151 void XGUI_Workshop::startApplication()
155 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
156 Config_Prop::Directory, "");
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_OBJECT_TOSHOW));
169 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
170 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
172 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
173 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
175 registerValidators();
177 // Calling of loadCustomProps before activating module is required
178 // by Config_PropManger to restore user-defined path to plugins
179 ModuleBase_Preferences::loadCustomProps();
182 myMainWindow->show();
183 updateCommandStatus();
188 emit applicationStarted();
191 //******************************************************
192 void XGUI_Workshop::initMenu()
194 myContextMenuMgr->createActions();
196 if (isSalomeMode()) {
197 // Create only Undo, Redo commands
198 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
199 tr("Undo last command"),
200 QIcon(":pictures/undo.png"),
201 QKeySequence::Undo, false, "MEN_DESK_EDIT");
202 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
203 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
205 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
206 QIcon(":pictures/redo.png"), QKeySequence::Redo,
207 false, "MEN_DESK_EDIT");
208 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
209 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
211 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
212 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
213 QIcon(":pictures/rebuild.png"), QKeySequence(),
214 false, "MEN_DESK_EDIT");
215 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
216 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
218 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
219 QIcon(), QKeySequence(),
220 false, "MEN_DESK_FILE");
221 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
223 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
224 QIcon(), QKeySequence(),
225 false, "MEN_DESK_FILE");
226 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
227 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
231 // File commands group
232 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
234 AppElements_Command* aCommand;
236 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
237 QIcon(":pictures/save.png"), QKeySequence::Save);
238 aCommand->connectTo(this, SLOT(onSave()));
239 //aCommand->disable();
241 QString aUndoId = "UNDO_CMD";
242 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
243 QIcon(":pictures/undo.png"), QKeySequence::Undo);
244 aCommand->connectTo(this, SLOT(onUndo()));
245 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
246 addHistoryMenu(aUndoButton,
247 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
250 QString aRedoId = "REDO_CMD";
251 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
252 QIcon(":pictures/redo.png"), QKeySequence::Redo);
253 aCommand->connectTo(this, SLOT(onRedo()));
254 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
255 addHistoryMenu(aRedoButton,
256 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
259 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
260 QIcon(":pictures/rebuild.png"), QKeySequence());
261 aCommand->connectTo(this, SLOT(onRebuild()));
263 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
264 QIcon(":pictures/save.png"), QKeySequence());
265 aCommand->connectTo(this, SLOT(onSaveAs()));
266 //aCommand->disable();
268 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
269 QIcon(":pictures/open.png"), QKeySequence::Open);
270 aCommand->connectTo(this, SLOT(onOpen()));
272 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
273 // QIcon(":pictures/new.png"), QKeySequence::New);
274 //aCommand->connectTo(this, SLOT(onNew()));
276 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
277 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
278 aCommand->connectTo(this, SLOT(onPreferences()));
280 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
281 QIcon(":pictures/close.png"), QKeySequence::Close);
282 aCommand->connectTo(this, SLOT(onExit()));
283 //FIXME: SBH's test action. Can be used for some GUI tests.
285 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
286 // QIcon(":pictures/close.png"), QKeySequence(), true);
287 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
291 //******************************************************
292 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
294 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
295 return aMenuBar->addWorkbench(theName);
298 //******************************************************
299 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
301 if (QApplication::instance()->thread() != QThread::currentThread()) {
303 std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
305 SessionPtr aMgr = ModelAPI_Session::get();
306 PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
307 QApplication::postEvent(this, aPostponeEvent);
311 //A message to start feature creation received.
312 if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
313 std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
314 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
315 if (!aFeatureMsg->isInternal()) {
316 addFeature(aFeatureMsg);
319 // Process creation of Part
320 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
321 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
322 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
323 onFeatureCreatedMsg(aUpdMsg);
325 if (mySalomeConnector)
326 mySalomeConnector->createPreferences();
327 myUpdatePrefs = false;
330 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
331 myUpdatePrefs = true;
334 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
335 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
336 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
337 onFeatureRedisplayMsg(aUpdMsg);
339 //Update property panel on corresponding message. If there is no current operation (no
340 //property panel), or received message has different feature to the current - do nothing.
341 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
342 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
343 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
344 onFeatureUpdatedMsg(anUpdateMsg);
345 } else if (theMessage->eventID() == Events_LongOp::eventID()) {
346 if (Events_LongOp::isPerformed()) {
347 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
349 QApplication::restoreOverrideCursor();
351 } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOSHOW)) {
352 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
353 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
354 const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
355 QObjectPtrList aList;
356 std::set<ObjectPtr>::const_iterator aIt;
357 for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
359 showObjects(aList, true);
360 } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE)) {
361 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
362 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
363 const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
364 QObjectPtrList aList;
365 std::set<ObjectPtr>::const_iterator aIt;
366 for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
368 showObjects(aList, false);
370 //An operation passed by message. Start it, process and commit.
371 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
372 std::shared_ptr<Config_PointerMessage> aPartSetMsg =
373 std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
374 //myPropertyPanel->cleanContent();
375 ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
377 if (myOperationMgr->startOperation(anOperation)) {
378 myPropertyPanel->updateContentWidget(anOperation->feature());
379 if (!anOperation->getDescription()->hasXmlRepresentation()) {
380 if (anOperation->commit())
381 updateCommandStatus();
385 else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
386 std::shared_ptr<Config_SelectionFilterMessage> aMsg =
387 std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
389 ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
390 if (!aMsg->attributeId().empty()) {
391 aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
395 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
396 // the viewer's update context will not happens until viewer updated is emitted
397 myDisplayer->enableUpdateViewer(false);
398 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
399 // the viewer's update context is unblocked, the viewer's update works
400 myDisplayer->enableUpdateViewer(true);
402 //Show error dialog if error message received.
403 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
405 emit errorOccurred(QString::fromLatin1(anAppError->description()));
409 if (!isSalomeMode()) {
410 SessionPtr aMgr = ModelAPI_Session::get();
411 if (aMgr->isModified() != myMainWindow->isModifiedState())
412 myMainWindow->setModifiedState(aMgr->isModified());
416 //******************************************************
417 QMainWindow* XGUI_Workshop::desktop() const
419 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
422 //******************************************************
423 void XGUI_Workshop::onStartWaiting()
425 if (Events_LongOp::isPerformed()) {
426 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
430 //******************************************************
431 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
433 std::set<ObjectPtr> aFeatures = theMsg->objects();
434 if (myOperationMgr->hasOperation()) {
435 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
436 std::set<ObjectPtr>::const_iterator aIt;
437 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
438 ObjectPtr aNewFeature = (*aIt);
439 if (aNewFeature == aCurrentFeature) {
440 myPropertyPanel->updateContentWidget(aCurrentFeature);
445 myOperationMgr->onValidateOperation();
446 //if (myObjectBrowser)
447 // myObjectBrowser->processEvent(theMsg);
450 //******************************************************
451 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
453 std::set<ObjectPtr> aObjects = theMsg->objects();
454 std::set<ObjectPtr>::const_iterator aIt;
456 #ifdef DEBUG_FEATURE_REDISPLAY
458 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
459 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
461 QString anInfoStr = anInfo.join(", ");
462 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
465 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
466 ObjectPtr aObj = (*aIt);
468 // Hide the object if it is invalid or concealed one
469 bool aHide = !aObj->data() || !aObj->data()->isValid();
470 if (!aHide) { // check that this is not hidden result
471 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
472 aHide = aRes && aRes->isConcealed();
475 myDisplayer->erase(aObj, false);
477 // Redisplay the visible object or the object of the current operation
478 bool isVisibleObject = myDisplayer->isVisible(aObj);
479 #ifdef DEBUG_FEATURE_REDISPLAY
480 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
481 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
484 if (isVisibleObject) { // redisplay visible object
485 //displayObject(aObj); // In order to update presentation
486 // in order to avoid the check whether the object can be redisplayed, the exact method
487 // of redisplay is called. This modification is made in order to have the line is updated
488 // by creation of a horizontal constraint on the line by preselection
489 myDisplayer->redisplay(aObj, false);
490 if (myOperationMgr->hasOperation()) {
491 ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
492 if (!aOperation->isEditOperation() &&
493 aOperation->hasObject(aObj) && myDisplayer->isActive(aObj))
494 myDisplayer->deactivate(aObj);
496 } else { // display object if the current operation has it
497 ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
498 if (aOperation && aOperation->hasObject(aObj)) {
499 ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
500 #ifdef DEBUG_FEATURE_REDISPLAY
501 QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
502 qDebug(QString(" display object = %1").arg(anObjInfo).toStdString().c_str());
504 if (displayObject(aObj)) {
505 // Deactivate object of current operation from selection
506 if (myDisplayer->isActive(aObj))
507 myDisplayer->deactivate(aObj);
513 myDisplayer->updateViewer();
516 //******************************************************
517 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
519 std::set<ObjectPtr> aObjects = theMsg->objects();
520 std::set<ObjectPtr>::const_iterator aIt;
521 #ifdef DEBUG_FEATURE_CREATED
523 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
524 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
526 QString anInfoStr = anInfo.join(", ");
527 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
530 //bool aHasPart = false;
531 bool isDisplayed = false;
532 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
533 ObjectPtr anObject = *aIt;
534 // the validity of the data should be checked here in order to avoid display of the objects,
535 // which were created, then deleted, but flush for the creation event happens after that
536 if (!anObject->data() || !anObject->data()->isValid())
538 //ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aIt);
541 // If a feature is created from the aplication's python console
542 // it doesn't stored in the operation mgr and doesn't displayed
544 isDisplayed = displayObject(*aIt);
547 //if (myObjectBrowser)
548 // myObjectBrowser->processEvent(theMsg);
550 myDisplayer->updateViewer();
551 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
552 // activateLastPart();
556 //******************************************************
557 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
559 setNestedFeatures(theOperation);
561 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
562 connectWithOperation(theOperation);
563 setPropertyPanel(theOperation);
565 updateCommandStatus();
567 myModule->operationStarted(theOperation);
570 //******************************************************
571 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
573 setNestedFeatures(theOperation);
575 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
576 // connectWithOperation(theOperation); already connected
577 setPropertyPanel(theOperation);
579 updateCommandStatus();
581 myModule->operationResumed(theOperation);
585 //******************************************************
586 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
588 ModuleBase_ISelection* aSel = mySelector->selection();
589 QObjectPtrList aObj = aSel->selectedPresentations();
590 //!< No need for property panel
591 updateCommandStatus();
593 myPropertyPanel->cleanContent();
595 // Activate objects created by current operation
596 // in order to clean selection modes
597 // the deactivation should be pefromed in the same place, where the mode is activated,
598 // e.g. activation in the current widget activation, deactivation - in the widget's deactivation
600 //myDisplayer->activateObjects(aModes);
601 myModule->operationStopped(theOperation);
603 if (myOperationMgr->operationsCount() == 0) {
604 // Activate selection mode for all objects
606 myDisplayer->activateObjects(aModes);
611 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
613 myModule->operationCommitted(theOperation);
616 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
618 myModule->operationAborted(theOperation);
621 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
623 if (this->isSalomeMode())
624 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
626 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
629 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
632 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
633 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
636 myPropertyPanel->cleanContent();
637 aFactory.createWidget(myPropertyPanel->contentWidget());
639 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
640 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
641 bool isStoreValue = !theOperation->isEditOperation() &&
642 !aWidget->getDefaultValue().empty() &&
643 !aWidget->isComputedDefault();
644 aWidget->setFeature(theOperation->feature(), isStoreValue);
645 aWidget->enableFocusProcessing();
648 myPropertyPanel->setModelWidgets(aWidgets);
649 theOperation->setPropertyPanel(myPropertyPanel);
651 myModule->propertyPanelDefined(theOperation);
653 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
656 bool XGUI_Workshop::event(QEvent * theEvent)
658 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
660 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
661 processEvent(aEventPtr);
670 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
674 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
678 ActionInfo aFeatureInfo;
679 aFeatureInfo.initFrom(theMessage);
681 QString aWchName = QString::fromStdString(theMessage->workbenchId());
682 QStringList aNestedFeatures =
683 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
684 QString aDocKind = QString::fromStdString(theMessage->documentKind());
685 QList<QAction*> aNestedActList;
686 bool isColumnButton = !aNestedFeatures.isEmpty();
687 if (isColumnButton) {
688 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
689 if (aNestedActions.contains("accept")) {
690 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
691 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
692 aNestedActList << anAction;
694 if (aNestedActions.contains("abort")) {
695 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
696 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
697 aNestedActList << anAction;
701 if (isSalomeMode()) {
703 if (isColumnButton) {
704 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
706 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
708 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
709 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
711 myActionsMgr->addCommand(aAction);
712 myModule->actionCreated(aAction);
714 //Find or create Workbench
715 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
716 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
718 aPage = addWorkbench(aWchName);
720 //Find or create Group
721 QString aGroupName = QString::fromStdString(theMessage->groupId());
722 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
724 aGroup = aPage->addGroup(aGroupName);
726 // Check if hotkey sequence is already defined:
727 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
728 if(aHotKey != aFeatureInfo.shortcut) {
729 aFeatureInfo.shortcut = aHotKey;
732 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
735 // Enrich created button with accept/abort buttons if necessary
736 AppElements_Button* aButton = aCommand->button();
737 if (aButton->isColumnButton()) {
738 aButton->setAdditionalButtons(aNestedActList);
740 myActionsMgr->addCommand(aCommand);
741 myModule->actionCreated(aCommand);
746 * Makes a signal/slot connections between Property Panel
747 * and given operation. The given operation becomes a
748 * current operation and previous operation if exists
750 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
752 QAction* aCommand = 0;
753 if (isSalomeMode()) {
754 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
756 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
757 FeaturePtr aFeature = theOperation->feature();
759 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
761 //Abort operation on uncheck the command
763 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
768 * Saves document with given name.
770 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
772 QApplication::restoreOverrideCursor();
773 SessionPtr aMgr = ModelAPI_Session::get();
774 aMgr->save(theName.toLatin1().constData(), theFileNames);
775 QApplication::restoreOverrideCursor();
778 bool XGUI_Workshop::isActiveOperationAborted()
780 return myOperationMgr->abortAllOperations();
783 //******************************************************
784 void XGUI_Workshop::onExit()
786 SessionPtr aMgr = ModelAPI_Session::get();
787 if (aMgr->isModified()) {
788 int anAnswer = QMessageBox::question(
789 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
790 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
791 if (anAnswer == QMessageBox::Save) {
792 bool saved = onSave();
796 } else if (anAnswer == QMessageBox::Cancel) {
803 //******************************************************
804 void XGUI_Workshop::onNew()
806 QApplication::setOverrideCursor(Qt::WaitCursor);
807 if (objectBrowser() == 0) {
809 mySelector->connectViewers();
811 myViewerProxy->connectToViewer();
813 if (!isSalomeMode()) {
814 myMainWindow->showPythonConsole();
815 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
816 aWnd->showMaximized();
817 updateCommandStatus();
819 myContextMenuMgr->connectViewer();
820 QApplication::restoreOverrideCursor();
823 //******************************************************
824 void XGUI_Workshop::onOpen()
826 if(!isActiveOperationAborted())
828 //save current file before close if modified
829 SessionPtr aSession = ModelAPI_Session::get();
830 if (aSession->isModified()) {
831 //TODO(sbh): re-launch the app?
832 int anAnswer = QMessageBox::question(
833 myMainWindow, tr("Save current file"),
834 tr("The document is modified, save before opening another?"),
835 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
836 if (anAnswer == QMessageBox::Save) {
838 } else if (anAnswer == QMessageBox::Cancel) {
841 aSession->closeAll();
845 //show file dialog, check if readable and open
846 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
847 if (myCurrentDir.isEmpty())
849 QFileInfo aFileInfo(myCurrentDir);
850 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
851 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
855 QApplication::setOverrideCursor(Qt::WaitCursor);
856 myIsLoadingData = true;
857 aSession->load(myCurrentDir.toLatin1().constData());
858 myObjectBrowser->rebuildDataTree();
860 updateCommandStatus();
861 myIsLoadingData = false;
862 QApplication::restoreOverrideCursor();
865 //******************************************************
866 bool XGUI_Workshop::onSave()
868 if(!isActiveOperationAborted())
870 if (myCurrentDir.isEmpty()) {
873 std::list<std::string> aFiles;
874 saveDocument(myCurrentDir, aFiles);
875 updateCommandStatus();
877 myMainWindow->setModifiedState(false);
881 //******************************************************
882 bool XGUI_Workshop::onSaveAs()
884 if(!isActiveOperationAborted())
886 QFileDialog dialog(mainWindow());
887 dialog.setWindowTitle(tr("Select directory to save files..."));
888 dialog.setFileMode(QFileDialog::Directory);
889 dialog.setFilter(tr("Folders (*)"));
890 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
891 dialog.setViewMode(QFileDialog::Detail);
893 if (!dialog.exec()) {
896 QString aTempDir = dialog.selectedFiles().first();
898 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
899 int answer = QMessageBox::question(
901 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
903 tr("The folder already contains some files, save anyway?"),
904 QMessageBox::Save | QMessageBox::Cancel);
905 if (answer == QMessageBox::Cancel) {
909 myCurrentDir = aTempDir;
910 if (!isSalomeMode()) {
911 myMainWindow->setCurrentDir(myCurrentDir, false);
912 myMainWindow->setModifiedState(false);
917 //******************************************************
918 void XGUI_Workshop::onUndo(int theTimes)
920 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
921 SessionPtr aMgr = ModelAPI_Session::get();
922 if (aMgr->isOperation())
923 operationMgr()->onAbortOperation();
924 for (int i = 0; i < theTimes; ++i) {
927 updateCommandStatus();
930 //******************************************************
931 void XGUI_Workshop::onRedo(int theTimes)
933 // the viewer update should be blocked in order to avoid the features blinking. For the created
934 // feature a results are created, the flush of the created signal caused the viewer redisplay for
935 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
936 // redo of all possible objects happens
937 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
939 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
940 SessionPtr aMgr = ModelAPI_Session::get();
941 if (aMgr->isOperation())
942 operationMgr()->onAbortOperation();
943 for (int i = 0; i < theTimes; ++i) {
946 updateCommandStatus();
948 // unblock the viewer update functionality and make update on purpose
949 myDisplayer->enableUpdateViewer(isUpdateEnabled);
950 myDisplayer->updateViewer();
953 //******************************************************
954 void XGUI_Workshop::onRebuild()
956 SessionPtr aMgr = ModelAPI_Session::get();
957 bool aWasOperation = aMgr->isOperation(); // keep this value
958 if (!aWasOperation) {
959 aMgr->startOperation("Rebuild");
961 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
962 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
963 new Events_Message(aRebuildEvent, this)));
964 if (!aWasOperation) {
965 aMgr->finishOperation();
967 updateCommandStatus();
970 //******************************************************
971 void XGUI_Workshop::onPreferences()
973 ModuleBase_Prefs aModif;
974 ModuleBase_Preferences::editPreferences(aModif);
975 if (aModif.size() > 0) {
977 foreach (ModuleBase_Pref aPref, aModif)
979 aSection = aPref.first;
980 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
982 myMainWindow->viewer()->updateFromResources();
983 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
985 myMainWindow->menuObject()->updateFromResources();
991 //******************************************************
992 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
994 QString libName = QString::fromStdString(library(theModule.toStdString()));
995 if (libName.isEmpty()) {
996 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1001 CREATE_FUNC crtInst = 0;
1004 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1008 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1009 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1010 QString aMsg((char*) &lpMsgBuf);
1011 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1012 ::LocalFree(lpMsgBuf);
1014 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1018 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1019 | FORMAT_MESSAGE_IGNORE_INSERTS,
1020 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1021 QString aMsg((char*) &lpMsgBuf);
1022 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1023 ::LocalFree(lpMsgBuf);
1027 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1029 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1031 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1033 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1038 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1040 if (!err.isEmpty()) {
1042 Events_Error::send(err.toStdString());
1044 qWarning(qPrintable(err));
1050 //******************************************************
1051 bool XGUI_Workshop::activateModule()
1053 Config_ModuleReader aModuleReader;
1054 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1055 myModule = loadModule(moduleName);
1059 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1060 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1061 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1062 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1064 myModule->createFeatures();
1065 myActionsMgr->update();
1069 //******************************************************
1070 void XGUI_Workshop::updateCommandStatus()
1072 QList<QAction*> aCommands;
1073 if (isSalomeMode()) { // update commands in SALOME mode
1074 aCommands = salomeConnector()->commandList();
1076 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1077 foreach (AppElements_Command* aCmd, aMenuBar->features())
1078 aCommands.append(aCmd);
1080 SessionPtr aMgr = ModelAPI_Session::get();
1081 if (aMgr->hasModuleDocument()) {
1082 QAction *aUndoCmd, *aRedoCmd;
1083 foreach(QAction* aCmd, aCommands) {
1084 QString aId = aCmd->data().toString();
1085 if (aId == "UNDO_CMD")
1087 else if (aId == "REDO_CMD")
1090 // Enable all commands
1091 aCmd->setEnabled(true);
1094 aUndoCmd->setEnabled(myModule->canUndo());
1095 aRedoCmd->setEnabled(myModule->canRedo());
1098 foreach(QAction* aCmd, aCommands) {
1099 QString aId = aCmd->data().toString();
1100 if (aId == "NEW_CMD")
1101 aCmd->setEnabled(true);
1102 else if (aId == "EXIT_CMD")
1103 aCmd->setEnabled(true);
1105 aCmd->setEnabled(false);
1108 myActionsMgr->update();
1109 emit commandStatusUpdated();
1112 void XGUI_Workshop::updateHistory()
1114 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1115 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1116 emit updateUndoHistory(aUndoRes);
1118 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1119 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1120 emit updateRedoHistory(aRedoRes);
1123 //******************************************************
1124 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1126 QDockWidget* aObjDock = new QDockWidget(theParent);
1127 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1128 aObjDock->setWindowTitle(tr("Object browser"));
1129 aObjDock->setStyleSheet(
1130 "::title { position: relative; padding-left: 5px; text-align: left center }");
1131 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1132 myObjectBrowser->setDataModel(myModule->dataModel());
1133 //connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1134 // SLOT(changeCurrentDocument(ObjectPtr)));
1135 aObjDock->setWidget(myObjectBrowser);
1137 myContextMenuMgr->connectObjectBrowser();
1141 //******************************************************
1143 * Creates dock widgets, places them in corresponding area
1144 * and tabifies if necessary.
1146 void XGUI_Workshop::createDockWidgets()
1148 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1149 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1150 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1151 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1152 myPropertyPanel->setupActions(myActionsMgr);
1153 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1154 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1155 hidePropertyPanel(); ///<! Invisible by default
1156 hideObjectBrowser();
1157 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1158 myPropertyPanel->installEventFilter(myOperationMgr);
1160 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1161 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1162 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1163 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1164 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1165 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1166 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1167 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1168 aOkAct, SLOT(setEnabled(bool)));
1169 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1170 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1171 aAcceptAllAct, SLOT(setEnabled(bool)));
1175 //******************************************************
1176 void XGUI_Workshop::showPropertyPanel()
1178 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1179 ///<! Restore ability to close panel from the window's menu
1180 aViewAct->setEnabled(true);
1181 myPropertyPanel->show();
1182 myPropertyPanel->raise();
1185 //******************************************************
1186 void XGUI_Workshop::hidePropertyPanel()
1188 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1189 ///<! Do not allow to show empty property panel
1190 aViewAct->setEnabled(false);
1191 myPropertyPanel->hide();
1194 //******************************************************
1195 void XGUI_Workshop::showObjectBrowser()
1197 myObjectBrowser->parentWidget()->show();
1200 //******************************************************
1201 void XGUI_Workshop::hideObjectBrowser()
1203 myObjectBrowser->parentWidget()->hide();
1206 //******************************************************
1207 void XGUI_Workshop::onFeatureTriggered()
1209 QAction* aCmd = dynamic_cast<QAction*>(sender());
1211 QString aId = salomeConnector()->commandId(aCmd);
1213 myModule->launchOperation(aId);
1217 //******************************************************
1218 void XGUI_Workshop::salomeViewerSelectionChanged()
1220 emit salomeViewerSelection();
1223 //**************************************************************
1224 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1226 return mySalomeConnector->viewer();
1229 //**************************************************************
1230 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1232 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1233 if (theId == "DELETE_CMD")
1235 else if (theId == "COLOR_CMD")
1236 changeColor(aObjects);
1237 else if (theId == "SHOW_CMD")
1238 showObjects(aObjects, true);
1239 else if (theId == "HIDE_CMD")
1240 showObjects(aObjects, false);
1241 else if (theId == "SHOW_ONLY_CMD")
1242 showOnlyObjects(aObjects);
1243 else if (theId == "SHADING_CMD")
1244 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1245 else if (theId == "WIREFRAME_CMD")
1246 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1247 else if (theId == "HIDEALL_CMD")
1248 myDisplayer->eraseAll();
1251 //**************************************************************
1252 void XGUI_Workshop::deleteObjects()
1254 ModuleBase_IModule* aModule = module();
1255 // 1. allow the module to delete objects, do nothing if it has succeed
1256 if (aModule->deleteObjects()) {
1257 updateCommandStatus();
1261 if (!isActiveOperationAborted())
1263 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1264 bool hasResult = false;
1265 bool hasFeature = false;
1266 bool hasParameter = false;
1267 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1268 if (!(hasFeature || hasParameter))
1271 // 1. start operation
1272 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1273 aDescription += tr(" %1");
1274 QStringList aObjectNames;
1275 foreach (ObjectPtr aObj, anObjects) {
1276 if (!aObj->data().get())
1278 aObjectNames << QString::fromStdString(aObj->data()->name());
1280 aDescription = aDescription.arg(aObjectNames.join(", "));
1282 SessionPtr aMgr = ModelAPI_Session::get();
1283 aMgr->startOperation(aDescription.toStdString());
1284 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1285 foreach (ObjectPtr aObj, anObjects)
1287 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1289 DocumentPtr aDoc = aObj->document();
1290 if (aDoc == aMgr->activeDocument()) {
1295 // 3. delete objects
1296 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1297 std::set<FeaturePtr> anIgnoredFeatures;
1298 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1299 myDisplayer->updateViewer();
1300 aMgr->finishOperation();
1301 updateCommandStatus();
1304 aMgr->abortOperation();
1308 //**************************************************************
1309 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1310 std::set<FeaturePtr> theIgnoredFeatures,
1312 const bool theAskAboutDeleteReferences)
1314 // 1. find all referenced features
1315 std::set<FeaturePtr> aRefFeatures;
1316 foreach (ObjectPtr aObj, theList) {
1317 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1318 if (aFeature.get() != NULL) {
1319 aObj->document()->refsToFeature(aFeature, aRefFeatures, false);
1322 // 2. warn about the references remove, break the delete operation if the user chose it
1323 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1324 QStringList aRefNames;
1325 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1326 aLast = aRefFeatures.end();
1327 for (; anIt != aLast; anIt++) {
1328 aRefNames.append((*anIt)->name().c_str());
1330 QString aNames = aRefNames.join(", ");
1332 QMessageBox::StandardButton aRes = QMessageBox::warning(
1333 theParent, tr("Delete features"),
1334 QString(tr("Selected features are used in the following features: %1.\
1335 These features will be deleted also. Would you like to continue?")).arg(aNames),
1336 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1337 if (aRes != QMessageBox::Yes)
1341 // 3. remove referenced features
1342 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1343 aLast = aRefFeatures.end();
1344 for (; anIt != aLast; anIt++) {
1345 FeaturePtr aFeature = (*anIt);
1346 DocumentPtr aDoc = aFeature->document();
1347 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1348 aDoc->removeFeature(aFeature);
1351 // 4. remove the parameter features
1352 foreach (ObjectPtr aObj, theList) {
1353 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1355 DocumentPtr aDoc = aObj->document();
1356 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1357 aDoc->removeFeature(aFeature);
1363 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1365 bool isFoundResultType = false;
1366 foreach(ObjectPtr anObj, theObjects)
1368 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1369 if (aResult.get() == NULL)
1372 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1373 if (isFoundResultType)
1376 return isFoundResultType;
1379 //**************************************************************
1380 bool XGUI_Workshop::canChangeColor() const
1382 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1384 std::set<std::string> aTypes;
1385 aTypes.insert(ModelAPI_ResultGroup::group());
1386 aTypes.insert(ModelAPI_ResultConstruction::group());
1387 aTypes.insert(ModelAPI_ResultBody::group());
1388 aTypes.insert(ModelAPI_ResultPart::group());
1390 return hasResults(aObjects, aTypes);
1393 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1395 if (!theResult.get())
1398 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1399 if (aColorAttr.get() != NULL) {
1400 if (!aColorAttr->size()) {
1401 aColorAttr->setSize(3);
1403 aColorAttr->setValue(0, theColor[0]);
1404 aColorAttr->setValue(1, theColor[1]);
1405 aColorAttr->setValue(2, theColor[2]);
1409 //**************************************************************
1410 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1412 AttributeIntArrayPtr aColorAttr;
1413 // 1. find the current color of the object. This is a color of AIS presentation
1414 // The objects are iterated until a first valid color is found
1415 std::vector<int> aColor;
1416 foreach(ObjectPtr anObject, theObjects) {
1417 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1418 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1419 DocumentPtr aPartDoc = aPart->partDoc();
1420 // the document should be checked on null, because in opened document if the part
1421 // has not been activated yet, the part document is empty
1422 if (!aPartDoc.get()) {
1423 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1426 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1427 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1428 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1430 std::string aSection, aName, aDefault;
1431 aBody->colorConfigInfo(aSection, aName, aDefault);
1432 if (!aSection.empty() && !aName.empty()) {
1433 aColor = Config_PropManager::color(aSection, aName, aDefault);
1440 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1441 if (anAISObj.get()) {
1443 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1446 if (!aColor.empty())
1449 if (aColor.size() != 3)
1452 // 2. show the dialog to change the value
1453 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1454 aDlg->setColor(aColor);
1455 aDlg->move(QCursor::pos());
1456 bool isDone = aDlg->exec() == QDialog::Accepted;
1460 bool isRandomColor = aDlg->isRandomColor();
1462 // 3. abort the previous operation and start a new one
1463 SessionPtr aMgr = ModelAPI_Session::get();
1464 bool aWasOperation = aMgr->isOperation(); // keep this value
1465 if (!aWasOperation) {
1466 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1467 aMgr->startOperation(aDescription.toStdString());
1470 // 4. set the value to all results
1471 foreach(ObjectPtr anObj, theObjects) {
1472 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1473 if (aResult.get() != NULL) {
1474 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1475 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1476 DocumentPtr aPartDoc = aPart->partDoc();
1477 // the document should be checked on null, because in opened document if the part
1478 // has not been activated yet, the part document is empty
1479 if (aPartDoc.get()) {
1480 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1481 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1482 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1483 std::vector<int> aColorResult = aDlg->getColor();
1484 setColor(aBody, aColorResult);
1489 std::vector<int> aColorResult = aDlg->getColor();
1490 setColor(aResult, aColorResult);
1495 aMgr->finishOperation();
1496 updateCommandStatus();
1499 //**************************************************************
1500 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1502 foreach (ObjectPtr aObj, theList)
1505 displayObject(aObj);
1507 myDisplayer->erase(aObj, false);
1510 myDisplayer->updateViewer();
1513 //**************************************************************
1514 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1516 myDisplayer->showOnly(theList);
1520 //**************************************************************
1521 void XGUI_Workshop::registerValidators() const
1523 SessionPtr aMgr = ModelAPI_Session::get();
1524 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1527 //**************************************************************
1528 void XGUI_Workshop::displayAllResults()
1530 SessionPtr aMgr = ModelAPI_Session::get();
1531 DocumentPtr aRootDoc = aMgr->moduleDocument();
1532 displayDocumentResults(aRootDoc);
1533 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1534 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1535 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1536 displayDocumentResults(aPart->partDoc());
1538 myDisplayer->updateViewer();
1541 //**************************************************************
1542 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1546 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1547 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1550 //**************************************************************
1551 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1553 for (int i = 0; i < theDoc->size(theGroup); i++)
1554 displayObject(theDoc->object(theGroup, i));
1557 //**************************************************************
1558 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1560 foreach(ObjectPtr aObj, theList) {
1561 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1563 if (theList.size() > 0)
1564 myDisplayer->updateViewer();
1567 //**************************************************************
1568 void XGUI_Workshop::closeDocument()
1570 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1571 while (anOperation) {
1572 anOperation->abort();
1573 anOperation = operationMgr()->currentOperation();
1575 myDisplayer->closeLocalContexts();
1576 myDisplayer->eraseAll();
1577 objectBrowser()->clearContent();
1579 SessionPtr aMgr = ModelAPI_Session::get();
1581 objectBrowser()->clearContent();
1584 //**************************************************************
1585 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1587 if (!myModule->canDisplayObject(theObj))
1590 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1591 if (aBody.get() != NULL) {
1592 int aNb = myDisplayer->objectsCount();
1593 myDisplayer->display(theObj, false);
1596 } else if (!(myIsLoadingData || myPartActivating))
1597 myDisplayer->display(theObj, false);
1602 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1604 XGUI_HistoryMenu* aMenu = NULL;
1605 if (isSalomeMode()) {
1606 QAction* anAction = qobject_cast<QAction*>(theObject);
1609 aMenu = new XGUI_HistoryMenu(anAction);
1611 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1612 aMenu = new XGUI_HistoryMenu(aButton);
1614 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1615 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1618 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1620 QList<ActionInfo> aResult;
1621 std::list<std::string>::const_iterator it = theList.cbegin();
1622 for (; it != theList.cend(); it++) {
1623 QString anId = QString::fromStdString(*it);
1624 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1626 anId.chop(ModuleBase_Operation::EditSuffix().size());
1629 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1630 if (aContextMenuAct) {
1631 anInfo.initFrom(aContextMenuAct);
1633 anInfo = myActionsMgr->actionInfoById(anId);
1636 anInfo.text = anInfo.text.prepend("Modify ");