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>
21 #include <XGUI_CustomPrs.h>
23 #include <AppElements_Workbench.h>
24 #include <AppElements_Viewer.h>
25 #include <AppElements_Command.h>
26 #include <AppElements_MainMenu.h>
27 #include <AppElements_MainWindow.h>
28 #include <AppElements_MenuGroupPanel.h>
29 #include <AppElements_Button.h>
31 #include <ModuleBase_IModule.h>
32 #include <ModuleBase_Preferences.h>
34 #include <ModelAPI_Events.h>
35 #include <ModelAPI_Session.h>
36 #include <ModelAPI_Feature.h>
37 #include <ModelAPI_Data.h>
38 #include <ModelAPI_AttributeDocRef.h>
39 #include <ModelAPI_Object.h>
40 #include <ModelAPI_Validator.h>
41 #include <ModelAPI_ResultGroup.h>
42 #include <ModelAPI_ResultConstruction.h>
43 #include <ModelAPI_ResultBody.h>
44 #include <ModelAPI_AttributeIntArray.h>
45 #include <ModelAPI_ResultParameter.h>
47 //#include <PartSetPlugin_Part.h>
49 #include <Events_Loop.h>
50 #include <Events_Error.h>
51 #include <Events_LongOp.h>
53 #include <ModuleBase_Operation.h>
54 #include <ModuleBase_Operation.h>
55 #include <ModuleBase_OperationDescription.h>
56 #include <ModuleBase_SelectionValidator.h>
57 #include <ModuleBase_WidgetFactory.h>
58 #include <ModuleBase_Tools.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_FilterFactory.h>
61 #include <ModuleBase_PageBase.h>
62 #include <ModuleBase_Tools.h>
64 #include <Config_Common.h>
65 #include <Config_FeatureMessage.h>
66 #include <Config_PointerMessage.h>
67 #include <Config_ModuleReader.h>
68 #include <Config_PropManager.h>
69 #include <Config_SelectionFilterMessage.h>
71 #include <QApplication>
72 #include <QFileDialog>
73 #include <QMessageBox>
74 #include <QMdiSubWindow>
75 #include <QPushButton>
76 #include <QDockWidget>
81 #include <QToolButton>
95 //#define DEBUG_FEATURE_CREATED
96 //#define DEBUG_FEATURE_REDISPLAY
97 //#define DEBUG_DELETE
99 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
101 myCurrentDir(QString()),
103 mySalomeConnector(theConnector),
107 myUpdatePrefs(false),
108 myPartActivating(false),
109 myIsLoadingData(false)
111 myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
113 myDisplayer = new XGUI_Displayer(this);
115 mySelector = new XGUI_SelectionMgr(this);
116 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
118 myOperationMgr = new XGUI_OperationMgr(this);
119 myActionsMgr = new XGUI_ActionsMgr(this);
120 myErrorDlg = new XGUI_ErrorDialog(myMainWindow);
121 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
122 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
123 SLOT(onContextMenuCommand(const QString&, bool)));
125 myViewerProxy = new XGUI_ViewerProxy(this);
126 connect(myViewerProxy, SIGNAL(selectionChanged()),
127 myActionsMgr, SLOT(updateOnViewSelection()));
129 myModuleConnector = new XGUI_ModuleConnector(this);
131 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
132 SLOT(onOperationStarted(ModuleBase_Operation*)));
133 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
134 SLOT(onOperationResumed(ModuleBase_Operation*)));
135 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
136 SLOT(onOperationStopped(ModuleBase_Operation*)));
137 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
138 SLOT(onOperationCommitted(ModuleBase_Operation*)));
139 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
140 SLOT(onOperationAborted(ModuleBase_Operation*)));
141 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
142 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
145 //******************************************************
146 XGUI_Workshop::~XGUI_Workshop(void)
151 //******************************************************
152 void XGUI_Workshop::startApplication()
156 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
157 Config_Prop::Directory, "");
159 //Initialize event listening
160 Events_Loop* aLoop = Events_Loop::loop();
161 aLoop->registerListener(this, Events_Error::errorID()); //!< Listening application errors.
162 aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
163 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
164 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
165 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
166 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
167 aLoop->registerListener(this, Events_LongOp::eventID());
168 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
169 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
171 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
172 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
174 registerValidators();
176 // Calling of loadCustomProps before activating module is required
177 // by Config_PropManger to restore user-defined path to plugins
178 ModuleBase_Preferences::loadCustomProps();
181 myMainWindow->show();
182 updateCommandStatus();
187 emit applicationStarted();
190 //******************************************************
191 void XGUI_Workshop::initMenu()
193 myContextMenuMgr->createActions();
195 if (isSalomeMode()) {
196 // Create only Undo, Redo commands
197 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
198 tr("Undo last command"),
199 QIcon(":pictures/undo.png"),
200 QKeySequence::Undo, false, "MEN_DESK_EDIT");
201 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
202 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
204 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
205 QIcon(":pictures/redo.png"), QKeySequence::Redo,
206 false, "MEN_DESK_EDIT");
207 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
208 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
210 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
211 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
212 QIcon(":pictures/rebuild.png"), QKeySequence(),
213 false, "MEN_DESK_EDIT");
214 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
215 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
217 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
218 QIcon(), QKeySequence(),
219 false, "MEN_DESK_FILE");
220 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
222 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
223 QIcon(), QKeySequence(),
224 false, "MEN_DESK_FILE");
225 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
226 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
230 // File commands group
231 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
233 AppElements_Command* aCommand;
235 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
236 QIcon(":pictures/save.png"), QKeySequence::Save);
237 aCommand->connectTo(this, SLOT(onSave()));
238 //aCommand->disable();
240 QString aUndoId = "UNDO_CMD";
241 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
242 QIcon(":pictures/undo.png"), QKeySequence::Undo);
243 aCommand->connectTo(this, SLOT(onUndo()));
244 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
245 addHistoryMenu(aUndoButton,
246 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
249 QString aRedoId = "REDO_CMD";
250 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
251 QIcon(":pictures/redo.png"), QKeySequence::Redo);
252 aCommand->connectTo(this, SLOT(onRedo()));
253 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
254 addHistoryMenu(aRedoButton,
255 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
258 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
259 QIcon(":pictures/rebuild.png"), QKeySequence());
260 aCommand->connectTo(this, SLOT(onRebuild()));
262 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
263 QIcon(":pictures/save.png"), QKeySequence());
264 aCommand->connectTo(this, SLOT(onSaveAs()));
265 //aCommand->disable();
267 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
268 QIcon(":pictures/open.png"), QKeySequence::Open);
269 aCommand->connectTo(this, SLOT(onOpen()));
271 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
272 // QIcon(":pictures/new.png"), QKeySequence::New);
273 //aCommand->connectTo(this, SLOT(onNew()));
275 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
276 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
277 aCommand->connectTo(this, SLOT(onPreferences()));
279 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
280 QIcon(":pictures/close.png"), QKeySequence::Close);
281 aCommand->connectTo(this, SLOT(onExit()));
282 //FIXME: SBH's test action. Can be used for some GUI tests.
284 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
285 // QIcon(":pictures/close.png"), QKeySequence(), true);
286 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
290 //******************************************************
291 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
293 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
294 return aMenuBar->addWorkbench(theName);
297 //******************************************************
298 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
300 if (QApplication::instance()->thread() != QThread::currentThread()) {
302 std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
304 SessionPtr aMgr = ModelAPI_Session::get();
305 PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
306 QApplication::postEvent(this, aPostponeEvent);
310 //A message to start feature creation received.
311 if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
312 std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
313 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
314 if (!aFeatureMsg->isInternal()) {
315 addFeature(aFeatureMsg);
318 // Process creation of Part
319 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
320 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
321 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
322 onFeatureCreatedMsg(aUpdMsg);
324 if (mySalomeConnector)
325 mySalomeConnector->createPreferences();
326 myUpdatePrefs = false;
329 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
330 myUpdatePrefs = true;
333 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
334 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
335 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
336 onFeatureRedisplayMsg(aUpdMsg);
338 //Update property panel on corresponding message. If there is no current operation (no
339 //property panel), or received message has different feature to the current - do nothing.
340 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
341 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
342 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
343 onFeatureUpdatedMsg(anUpdateMsg);
344 } else if (theMessage->eventID() == Events_LongOp::eventID()) {
345 if (Events_LongOp::isPerformed()) {
346 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
348 QApplication::restoreOverrideCursor();
351 //An operation passed by message. Start it, process and commit.
352 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
353 std::shared_ptr<Config_PointerMessage> aPartSetMsg =
354 std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
355 //myPropertyPanel->cleanContent();
356 ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
358 if (myOperationMgr->startOperation(anOperation)) {
359 myPropertyPanel->updateContentWidget(anOperation->feature());
360 if (!anOperation->getDescription()->hasXmlRepresentation()) {
361 if (anOperation->commit())
362 updateCommandStatus();
366 else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
367 std::shared_ptr<Config_SelectionFilterMessage> aMsg =
368 std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
370 ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
371 if (!aMsg->attributeId().empty()) {
372 aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
376 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
377 // the viewer's update context will not happens until viewer updated is emitted
378 myDisplayer->enableUpdateViewer(false);
379 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
380 // the viewer's update context is unblocked, the viewer's update works
381 myDisplayer->enableUpdateViewer(true);
382 myDisplayer->updateViewer();
384 //Show error dialog if error message received.
385 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
387 emit errorOccurred(QString::fromLatin1(anAppError->description()));
391 if (!isSalomeMode()) {
392 SessionPtr aMgr = ModelAPI_Session::get();
393 if (aMgr->isModified() != myMainWindow->isModifiedState())
394 myMainWindow->setModifiedState(aMgr->isModified());
398 //******************************************************
399 QMainWindow* XGUI_Workshop::desktop() const
401 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
404 //******************************************************
405 void XGUI_Workshop::onStartWaiting()
407 if (Events_LongOp::isPerformed()) {
408 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
412 //******************************************************
413 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
415 std::set<ObjectPtr> aFeatures = theMsg->objects();
416 if (myOperationMgr->hasOperation()) {
417 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
418 std::set<ObjectPtr>::const_iterator aIt;
419 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
420 ObjectPtr aNewFeature = (*aIt);
421 if (aNewFeature == aCurrentFeature) {
422 myPropertyPanel->updateContentWidget(aCurrentFeature);
427 myOperationMgr->onValidateOperation();
428 //if (myObjectBrowser)
429 // myObjectBrowser->processEvent(theMsg);
432 //******************************************************
433 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
435 std::set<ObjectPtr> aObjects = theMsg->objects();
436 std::set<ObjectPtr>::const_iterator aIt;
438 #ifdef DEBUG_FEATURE_REDISPLAY
440 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
441 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
443 QString anInfoStr = anInfo.join(", ");
444 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
447 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
448 ObjectPtr aObj = (*aIt);
450 // Hide the object if it is invalid or concealed one
451 bool aHide = !aObj->data() || !aObj->data()->isValid() ||
452 aObj->isDisabled() || (!aObj->isDisplayed());
453 if (!aHide) { // check that this is not hidden result
454 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
455 aHide = aRes && aRes->isConcealed();
458 myDisplayer->erase(aObj, false);
460 // Redisplay the visible object or the object of the current operation
461 bool isVisibleObject = myDisplayer->isVisible(aObj);
462 #ifdef DEBUG_FEATURE_REDISPLAY
463 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
464 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
467 if (isVisibleObject) { // redisplay visible object
468 //displayObject(aObj); // In order to update presentation
469 // in order to avoid the check whether the object can be redisplayed, the exact method
470 // of redisplay is called. This modification is made in order to have the line is updated
471 // by creation of a horizontal constraint on the line by preselection
472 myDisplayer->redisplay(aObj, false);
473 // Deactivate object of current operation from selection
474 deactivateActiveObject(aObj, false);
475 } else { // display object if the current operation has it
476 if (displayObject(aObj)) {
477 // Deactivate object of current operation from selection
478 deactivateActiveObject(aObj, false);
483 myDisplayer->updateViewer();
486 //******************************************************
487 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
489 if (!myModule->canActivateSelection(theObject)) {
490 if (myDisplayer->isActive(theObject))
491 myDisplayer->deactivate(theObject, theUpdateViewer);
495 //******************************************************
496 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
498 std::set<ObjectPtr> aObjects = theMsg->objects();
499 std::set<ObjectPtr>::const_iterator aIt;
500 #ifdef DEBUG_FEATURE_CREATED
502 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
503 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
505 QString anInfoStr = anInfo.join(", ");
506 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
509 //bool aHasPart = false;
510 bool isDisplayed = false;
511 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
512 ObjectPtr anObject = *aIt;
513 // the validity of the data should be checked here in order to avoid display of the objects,
514 // which were created, then deleted, but flush for the creation event happens after that
515 // we should not display disabled objects
516 bool aHide = !anObject->data()->isValid() ||
517 anObject->isDisabled() ||
518 !anObject->isDisplayed();
520 // setDisplayed has to be called in order to synchronize internal state of the object
521 // with list of displayed objects
522 if (myModule->canDisplayObject(anObject)) {
523 anObject->setDisplayed(true);
524 isDisplayed = displayObject(*aIt);
526 anObject->setDisplayed(false);
529 //if (myObjectBrowser)
530 // myObjectBrowser->processEvent(theMsg);
532 myDisplayer->updateViewer();
533 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
534 // activateLastPart();
538 //******************************************************
539 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
541 setNestedFeatures(theOperation);
543 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
544 connectWithOperation(theOperation);
545 setPropertyPanel(theOperation);
547 updateCommandStatus();
549 myModule->operationStarted(theOperation);
551 // the objects of the current operation should be deactivated
552 QObjectPtrList anObjects;
553 FeaturePtr aFeature = theOperation->feature();
554 anObjects.append(aFeature);
555 std::list<ResultPtr> aResults = aFeature->results();
556 std::list<ResultPtr>::const_iterator aIt;
557 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
558 anObjects.append(*aIt);
560 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
561 for (; anIt != aLast; anIt++)
562 deactivateActiveObject(*anIt, false);
563 if (anObjects.size() > 0)
564 myDisplayer->updateViewer();
567 //******************************************************
568 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
570 setNestedFeatures(theOperation);
572 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
573 // connectWithOperation(theOperation); already connected
574 setPropertyPanel(theOperation);
576 updateCommandStatus();
578 myModule->operationResumed(theOperation);
582 //******************************************************
583 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
585 ModuleBase_ISelection* aSel = mySelector->selection();
586 QObjectPtrList aObj = aSel->selectedPresentations();
587 //!< No need for property panel
588 updateCommandStatus();
590 myPropertyPanel->cleanContent();
592 myModule->operationStopped(theOperation);
594 // the deactivated objects of the current operation should be activated back.
595 // They were deactivated on operation start or an object redisplay
596 QObjectPtrList anObjects;
597 FeaturePtr aFeature = theOperation->feature();
598 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
599 anObjects.append(aFeature);
600 std::list<ResultPtr> aResults = aFeature->results();
601 std::list<ResultPtr>::const_iterator aIt;
602 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
603 ResultPtr anObject = *aIt;
604 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
605 anObjects.append(anObject);
609 module()->activeSelectionModes(aModes);
610 myDisplayer->activateObjects(aModes, anObjects);
614 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
616 myModule->operationCommitted(theOperation);
619 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
621 myModule->operationAborted(theOperation);
624 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
626 if (this->isSalomeMode())
627 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
629 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
632 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
635 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
636 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
639 myPropertyPanel->cleanContent();
640 aFactory.createWidget(myPropertyPanel->contentWidget());
642 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
643 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
644 bool isStoreValue = !theOperation->isEditOperation() &&
645 !aWidget->getDefaultValue().empty() &&
646 !aWidget->isComputedDefault();
647 aWidget->setFeature(theOperation->feature(), isStoreValue);
648 aWidget->enableFocusProcessing();
651 myPropertyPanel->setModelWidgets(aWidgets);
652 theOperation->setPropertyPanel(myPropertyPanel);
654 myModule->propertyPanelDefined(theOperation);
656 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
659 bool XGUI_Workshop::event(QEvent * theEvent)
661 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
663 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
664 processEvent(aEventPtr);
673 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
677 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
681 ActionInfo aFeatureInfo;
682 aFeatureInfo.initFrom(theMessage);
684 QString aWchName = QString::fromStdString(theMessage->workbenchId());
685 QStringList aNestedFeatures =
686 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
687 QString aDocKind = QString::fromStdString(theMessage->documentKind());
688 QList<QAction*> aNestedActList;
689 bool isColumnButton = !aNestedFeatures.isEmpty();
690 if (isColumnButton) {
691 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
692 if (aNestedActions.contains("accept")) {
693 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
694 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
695 aNestedActList << anAction;
697 if (aNestedActions.contains("abort")) {
698 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
699 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
700 aNestedActList << anAction;
704 if (isSalomeMode()) {
706 if (isColumnButton) {
707 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
709 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
711 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
712 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
714 myActionsMgr->addCommand(aAction);
715 myModule->actionCreated(aAction);
717 //Find or create Workbench
718 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
719 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
721 aPage = addWorkbench(aWchName);
723 //Find or create Group
724 QString aGroupName = QString::fromStdString(theMessage->groupId());
725 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
727 aGroup = aPage->addGroup(aGroupName);
729 // Check if hotkey sequence is already defined:
730 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
731 if(aHotKey != aFeatureInfo.shortcut) {
732 aFeatureInfo.shortcut = aHotKey;
735 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
738 // Enrich created button with accept/abort buttons if necessary
739 AppElements_Button* aButton = aCommand->button();
740 if (aButton->isColumnButton()) {
741 aButton->setAdditionalButtons(aNestedActList);
743 myActionsMgr->addCommand(aCommand);
744 myModule->actionCreated(aCommand);
749 * Makes a signal/slot connections between Property Panel
750 * and given operation. The given operation becomes a
751 * current operation and previous operation if exists
753 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
755 QAction* aCommand = 0;
756 if (isSalomeMode()) {
757 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
759 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
760 FeaturePtr aFeature = theOperation->feature();
762 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
764 //Abort operation on uncheck the command
766 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
771 * Saves document with given name.
773 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
775 QApplication::restoreOverrideCursor();
776 SessionPtr aMgr = ModelAPI_Session::get();
777 aMgr->save(theName.toLatin1().constData(), theFileNames);
778 QApplication::restoreOverrideCursor();
781 bool XGUI_Workshop::isActiveOperationAborted()
783 return myOperationMgr->abortAllOperations();
786 //******************************************************
787 void XGUI_Workshop::onExit()
789 SessionPtr aMgr = ModelAPI_Session::get();
790 if (aMgr->isModified()) {
791 int anAnswer = QMessageBox::question(
792 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
793 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
794 if (anAnswer == QMessageBox::Save) {
795 bool saved = onSave();
799 } else if (anAnswer == QMessageBox::Cancel) {
806 //******************************************************
807 void XGUI_Workshop::onNew()
809 QApplication::setOverrideCursor(Qt::WaitCursor);
810 if (objectBrowser() == 0) {
812 mySelector->connectViewers();
814 myViewerProxy->connectToViewer();
816 if (!isSalomeMode()) {
817 myMainWindow->showPythonConsole();
818 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
819 aWnd->showMaximized();
820 updateCommandStatus();
822 myContextMenuMgr->connectViewer();
823 QApplication::restoreOverrideCursor();
826 //******************************************************
827 void XGUI_Workshop::onOpen()
829 if(!isActiveOperationAborted())
831 //save current file before close if modified
832 SessionPtr aSession = ModelAPI_Session::get();
833 if (aSession->isModified()) {
834 //TODO(sbh): re-launch the app?
835 int anAnswer = QMessageBox::question(
836 myMainWindow, tr("Save current file"),
837 tr("The document is modified, save before opening another?"),
838 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
839 if (anAnswer == QMessageBox::Save) {
841 } else if (anAnswer == QMessageBox::Cancel) {
847 //show file dialog, check if readable and open
848 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
849 if (myCurrentDir.isEmpty())
851 QFileInfo aFileInfo(myCurrentDir);
852 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
853 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
857 QApplication::setOverrideCursor(Qt::WaitCursor);
858 myIsLoadingData = true;
859 aSession->closeAll();
860 aSession->load(myCurrentDir.toLatin1().constData());
861 myObjectBrowser->rebuildDataTree();
862 //displayAllResults();
863 updateCommandStatus();
864 myIsLoadingData = false;
865 QApplication::restoreOverrideCursor();
868 //******************************************************
869 bool XGUI_Workshop::onSave()
871 if(!isActiveOperationAborted())
873 if (myCurrentDir.isEmpty()) {
876 std::list<std::string> aFiles;
877 saveDocument(myCurrentDir, aFiles);
878 updateCommandStatus();
880 myMainWindow->setModifiedState(false);
884 //******************************************************
885 bool XGUI_Workshop::onSaveAs()
887 if(!isActiveOperationAborted())
889 QFileDialog dialog(mainWindow());
890 dialog.setWindowTitle(tr("Select directory to save files..."));
891 dialog.setFileMode(QFileDialog::Directory);
892 dialog.setFilter(tr("Folders (*)"));
893 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
894 dialog.setViewMode(QFileDialog::Detail);
896 if (!dialog.exec()) {
899 QString aTempDir = dialog.selectedFiles().first();
901 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
902 int answer = QMessageBox::question(
904 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
906 tr("The folder already contains some files, save anyway?"),
907 QMessageBox::Save | QMessageBox::Cancel);
908 if (answer == QMessageBox::Cancel) {
912 myCurrentDir = aTempDir;
913 if (!isSalomeMode()) {
914 myMainWindow->setCurrentDir(myCurrentDir, false);
915 myMainWindow->setModifiedState(false);
920 //******************************************************
921 void XGUI_Workshop::onUndo(int theTimes)
923 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
924 SessionPtr aMgr = ModelAPI_Session::get();
925 if (aMgr->isOperation())
926 operationMgr()->onAbortOperation();
927 for (int i = 0; i < theTimes; ++i) {
930 updateCommandStatus();
933 //******************************************************
934 void XGUI_Workshop::onRedo(int theTimes)
936 // the viewer update should be blocked in order to avoid the features blinking. For the created
937 // feature a results are created, the flush of the created signal caused the viewer redisplay for
938 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
939 // redo of all possible objects happens
940 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
942 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
943 SessionPtr aMgr = ModelAPI_Session::get();
944 if (aMgr->isOperation())
945 operationMgr()->onAbortOperation();
946 for (int i = 0; i < theTimes; ++i) {
949 updateCommandStatus();
951 // unblock the viewer update functionality and make update on purpose
952 myDisplayer->enableUpdateViewer(isUpdateEnabled);
953 myDisplayer->updateViewer();
956 //******************************************************
957 void XGUI_Workshop::onRebuild()
959 SessionPtr aMgr = ModelAPI_Session::get();
960 bool aWasOperation = aMgr->isOperation(); // keep this value
961 if (!aWasOperation) {
962 aMgr->startOperation("Rebuild");
964 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
965 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
966 new Events_Message(aRebuildEvent, this)));
967 if (!aWasOperation) {
968 aMgr->finishOperation();
970 updateCommandStatus();
973 //******************************************************
974 void XGUI_Workshop::onPreferences()
976 ModuleBase_Prefs aModif;
977 ModuleBase_Preferences::editPreferences(aModif);
978 if (aModif.size() > 0) {
980 foreach (ModuleBase_Pref aPref, aModif)
982 aSection = aPref.first;
983 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
985 myMainWindow->viewer()->updateFromResources();
986 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
988 myMainWindow->menuObject()->updateFromResources();
994 //******************************************************
995 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
997 QString libName = QString::fromStdString(library(theModule.toStdString()));
998 if (libName.isEmpty()) {
999 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1004 CREATE_FUNC crtInst = 0;
1007 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1011 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1012 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1013 QString aMsg((char*) &lpMsgBuf);
1014 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1015 ::LocalFree(lpMsgBuf);
1017 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1021 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1022 | FORMAT_MESSAGE_IGNORE_INSERTS,
1023 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1024 QString aMsg((char*) &lpMsgBuf);
1025 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1026 ::LocalFree(lpMsgBuf);
1030 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1032 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1034 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1036 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1041 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1043 if (!err.isEmpty()) {
1045 Events_Error::send(err.toStdString());
1047 qWarning(qPrintable(err));
1053 //******************************************************
1054 bool XGUI_Workshop::activateModule()
1056 Config_ModuleReader aModuleReader;
1057 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1058 myModule = loadModule(moduleName);
1062 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1063 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1064 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1065 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1067 myModule->createFeatures();
1068 myActionsMgr->update();
1072 //******************************************************
1073 void XGUI_Workshop::updateCommandStatus()
1075 QList<QAction*> aCommands;
1076 if (isSalomeMode()) { // update commands in SALOME mode
1077 aCommands = salomeConnector()->commandList();
1079 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1080 foreach (AppElements_Command* aCmd, aMenuBar->features())
1081 aCommands.append(aCmd);
1083 SessionPtr aMgr = ModelAPI_Session::get();
1084 if (aMgr->hasModuleDocument()) {
1085 QAction *aUndoCmd, *aRedoCmd;
1086 foreach(QAction* aCmd, aCommands) {
1087 QString aId = aCmd->data().toString();
1088 if (aId == "UNDO_CMD")
1090 else if (aId == "REDO_CMD")
1093 // Enable all commands
1094 aCmd->setEnabled(true);
1097 aUndoCmd->setEnabled(myModule->canUndo());
1098 aRedoCmd->setEnabled(myModule->canRedo());
1101 foreach(QAction* aCmd, aCommands) {
1102 QString aId = aCmd->data().toString();
1103 if (aId == "NEW_CMD")
1104 aCmd->setEnabled(true);
1105 else if (aId == "EXIT_CMD")
1106 aCmd->setEnabled(true);
1108 aCmd->setEnabled(false);
1111 myActionsMgr->update();
1112 emit commandStatusUpdated();
1115 void XGUI_Workshop::updateHistory()
1117 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1118 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1119 emit updateUndoHistory(aUndoRes);
1121 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1122 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1123 emit updateRedoHistory(aRedoRes);
1126 //******************************************************
1127 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1129 QDockWidget* aObjDock = new QDockWidget(theParent);
1130 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1131 aObjDock->setWindowTitle(tr("Object browser"));
1132 aObjDock->setStyleSheet(
1133 "::title { position: relative; padding-left: 5px; text-align: left center }");
1134 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1135 myObjectBrowser->setDataModel(myModule->dataModel());
1136 myModule->customizeObjectBrowser(myObjectBrowser);
1137 aObjDock->setWidget(myObjectBrowser);
1139 myContextMenuMgr->connectObjectBrowser();
1143 //******************************************************
1145 * Creates dock widgets, places them in corresponding area
1146 * and tabifies if necessary.
1148 void XGUI_Workshop::createDockWidgets()
1150 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1151 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1152 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1153 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1154 myPropertyPanel->setupActions(myActionsMgr);
1155 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1156 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1157 hidePropertyPanel(); ///<! Invisible by default
1158 hideObjectBrowser();
1159 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1160 myPropertyPanel->installEventFilter(myOperationMgr);
1162 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1163 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1164 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1165 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1166 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1167 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1168 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1169 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1170 aOkAct, SLOT(setEnabled(bool)));
1171 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1172 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1173 aAcceptAllAct, SLOT(setEnabled(bool)));
1177 //******************************************************
1178 void XGUI_Workshop::showPropertyPanel()
1180 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1181 ///<! Restore ability to close panel from the window's menu
1182 aViewAct->setEnabled(true);
1183 myPropertyPanel->show();
1184 myPropertyPanel->raise();
1187 //******************************************************
1188 void XGUI_Workshop::hidePropertyPanel()
1190 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1191 ///<! Do not allow to show empty property panel
1192 aViewAct->setEnabled(false);
1193 myPropertyPanel->hide();
1196 //******************************************************
1197 void XGUI_Workshop::showObjectBrowser()
1199 myObjectBrowser->parentWidget()->show();
1202 //******************************************************
1203 void XGUI_Workshop::hideObjectBrowser()
1205 myObjectBrowser->parentWidget()->hide();
1208 //******************************************************
1209 //void XGUI_Workshop::onFeatureTriggered()
1211 // QAction* aCmd = dynamic_cast<QAction*>(sender());
1213 // QString aId = salomeConnector()->commandId(aCmd);
1214 // if (!aId.isNull())
1215 // myModule->launchOperation(aId);
1219 //******************************************************
1220 void XGUI_Workshop::salomeViewerSelectionChanged()
1222 emit salomeViewerSelection();
1225 //**************************************************************
1226 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1228 return mySalomeConnector->viewer();
1231 //**************************************************************
1232 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1234 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1235 if (theId == "DELETE_CMD")
1237 else if (theId == "COLOR_CMD")
1238 changeColor(aObjects);
1239 else if (theId == "SHOW_CMD")
1240 showObjects(aObjects, true);
1241 else if (theId == "HIDE_CMD")
1242 showObjects(aObjects, false);
1243 else if (theId == "SHOW_ONLY_CMD")
1244 showOnlyObjects(aObjects);
1245 else if (theId == "SHADING_CMD")
1246 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1247 else if (theId == "WIREFRAME_CMD")
1248 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1249 else if (theId == "HIDEALL_CMD") {
1250 QObjectPtrList aList = myDisplayer->displayedObjects();
1251 foreach (ObjectPtr aObj, aList)
1252 aObj->setDisplayed(false);
1253 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1257 //**************************************************************
1258 void XGUI_Workshop::deleteObjects()
1260 ModuleBase_IModule* aModule = module();
1261 // 1. allow the module to delete objects, do nothing if it has succeed
1262 if (aModule->deleteObjects()) {
1263 updateCommandStatus();
1267 if (!isActiveOperationAborted())
1269 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1270 bool hasResult = false;
1271 bool hasFeature = false;
1272 bool hasParameter = false;
1273 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1274 if (!(hasFeature || hasParameter))
1277 // 1. start operation
1278 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1279 aDescription += tr(" %1");
1280 QStringList aObjectNames;
1281 foreach (ObjectPtr aObj, anObjects) {
1282 if (!aObj->data()->isValid())
1284 aObjectNames << QString::fromStdString(aObj->data()->name());
1286 aDescription = aDescription.arg(aObjectNames.join(", "));
1288 SessionPtr aMgr = ModelAPI_Session::get();
1289 aMgr->startOperation(aDescription.toStdString());
1290 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1291 // this is performed in the RemoveFeature of Part object.
1292 /*foreach (ObjectPtr aObj, anObjects)
1294 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1296 DocumentPtr aDoc = aObj->document();
1297 if (aDoc == aMgr->activeDocument()) {
1302 // 3. delete objects
1303 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1304 std::set<FeaturePtr> anIgnoredFeatures;
1305 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1306 myDisplayer->updateViewer();
1307 aMgr->finishOperation();
1308 updateCommandStatus();
1311 aMgr->abortOperation();
1315 //**************************************************************
1316 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1317 std::set<FeaturePtr> theIgnoredFeatures,
1319 const bool theAskAboutDeleteReferences)
1321 // 1. find all referenced features
1322 std::set<FeaturePtr> aRefFeatures;
1323 foreach (ObjectPtr aDeletedObj, theList) {
1324 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1325 if (aDeletedFeature.get() != NULL) {
1326 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1327 // 1.1 find references in the current document
1328 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1329 // 1.2 find references in all documents if the document of the feature is
1330 // "PartSet". Features of this document can be used in all other documents
1331 SessionPtr aMgr = ModelAPI_Session::get();
1332 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1333 if (aDeletedFeatureDoc == aModuleDoc) {
1334 // the deleted feature and results of the feature should be found in references
1335 std::list<ObjectPtr> aDeletedObjects;
1336 aDeletedObjects.push_back(aDeletedFeature);
1337 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1338 const ResultsList& aDeletedResults = aDeletedFeature->results();
1339 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1340 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1341 ResultPtr aRes = *aRIter;
1343 aDeletedObjects.push_back(aRes);
1345 // get all opened documents; found features in the documents;
1346 // get a list of objects where a feature refers;
1347 // search in these objects the deleted objects.
1348 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1349 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1350 aLast = anOpenedDocs.end();
1351 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1352 for (; anIt != aLast; anIt++) {
1353 DocumentPtr aDocument = *anIt;
1354 if (aDocument == aDeletedFeatureDoc)
1355 continue; // this document has been already processed in 1.1
1357 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1358 for (int aId = 0; aId < aFeaturesCount; aId++) {
1359 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1360 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1361 if (!aFeature.get())
1365 aFeature->data()->referencesToObjects(aRefs);
1366 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1367 bool aHasReferenceToDeleted = false;
1368 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1369 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1370 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1371 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1372 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1373 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1377 if (aHasReferenceToDeleted)
1378 aRefFeatures.insert(aFeature);
1384 // 2. warn about the references remove, break the delete operation if the user chose it
1385 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1386 QStringList aRefNames;
1387 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1388 aLast = aRefFeatures.end();
1389 for (; anIt != aLast; anIt++) {
1390 aRefNames.append((*anIt)->name().c_str());
1392 QString aNames = aRefNames.join(", ");
1394 QMessageBox::StandardButton aRes = QMessageBox::warning(
1395 theParent, tr("Delete features"),
1396 QString(tr("Selected features are used in the following features: %1.\
1397 These features will be deleted also. Would you like to continue?")).arg(aNames),
1398 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1399 if (aRes != QMessageBox::Yes)
1403 // 3. remove referenced features
1404 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1405 aLast = aRefFeatures.end();
1409 for (; anIt != aLast; anIt++) {
1410 FeaturePtr aFeature = (*anIt);
1411 DocumentPtr aDoc = aFeature->document();
1412 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1413 aDoc->removeFeature(aFeature);
1415 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1420 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1424 // 4. remove the parameter features
1425 foreach (ObjectPtr aObj, theList) {
1426 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1427 if (aResult.get() != NULL) { // results could not be removed,
1428 // they are removed by a corresponded feature remove
1431 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1433 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1434 // part features are removed in the PartSet module. This condition should be moved there
1435 if (aFeature->getKind() == "Part")
1438 DocumentPtr aDoc = aObj->document();
1439 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1440 aDoc->removeFeature(aFeature);
1442 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1443 anInfo.append(anInfoStr);
1444 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1450 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1455 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1457 bool isFoundResultType = false;
1458 foreach(ObjectPtr anObj, theObjects)
1460 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1461 if (aResult.get() == NULL)
1464 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1465 if (isFoundResultType)
1468 return isFoundResultType;
1471 //**************************************************************
1472 bool XGUI_Workshop::canChangeColor() const
1474 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1476 std::set<std::string> aTypes;
1477 aTypes.insert(ModelAPI_ResultGroup::group());
1478 aTypes.insert(ModelAPI_ResultConstruction::group());
1479 aTypes.insert(ModelAPI_ResultBody::group());
1480 aTypes.insert(ModelAPI_ResultPart::group());
1482 return hasResults(aObjects, aTypes);
1485 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1487 if (!theResult.get())
1490 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1491 if (aColorAttr.get() != NULL) {
1492 if (!aColorAttr->size()) {
1493 aColorAttr->setSize(3);
1495 aColorAttr->setValue(0, theColor[0]);
1496 aColorAttr->setValue(1, theColor[1]);
1497 aColorAttr->setValue(2, theColor[2]);
1501 //**************************************************************
1502 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1504 AttributeIntArrayPtr aColorAttr;
1505 // 1. find the current color of the object. This is a color of AIS presentation
1506 // The objects are iterated until a first valid color is found
1507 std::vector<int> aColor;
1508 foreach(ObjectPtr anObject, theObjects) {
1509 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1510 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1511 DocumentPtr aPartDoc = aPart->partDoc();
1512 // the document should be checked on null, because in opened document if the part
1513 // has not been activated yet, the part document is empty
1514 if (!aPartDoc.get()) {
1515 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1518 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1519 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1520 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1522 XGUI_CustomPrs::getResultColor(aBody, aColor);
1528 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1530 XGUI_CustomPrs::getResultColor(aResult, aColor);
1532 // TODO: remove the obtaining a color from the AIS object
1533 // this does not happen never because:
1534 // 1. The color can be changed only on results
1535 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1536 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1537 if (anAISObj.get()) {
1539 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1543 if (!aColor.empty())
1546 if (aColor.size() != 3)
1549 // 2. show the dialog to change the value
1550 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1551 aDlg->setColor(aColor);
1552 aDlg->move(QCursor::pos());
1553 bool isDone = aDlg->exec() == QDialog::Accepted;
1557 bool isRandomColor = aDlg->isRandomColor();
1559 // 3. abort the previous operation and start a new one
1560 SessionPtr aMgr = ModelAPI_Session::get();
1561 bool aWasOperation = aMgr->isOperation(); // keep this value
1562 if (!aWasOperation) {
1563 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1564 aMgr->startOperation(aDescription.toStdString());
1567 // 4. set the value to all results
1568 foreach(ObjectPtr anObj, theObjects) {
1569 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1570 if (aResult.get() != NULL) {
1571 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1572 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1573 DocumentPtr aPartDoc = aPart->partDoc();
1574 // the document should be checked on null, because in opened document if the part
1575 // has not been activated yet, the part document is empty
1576 if (aPartDoc.get()) {
1577 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1578 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1579 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1580 std::vector<int> aColorResult = aDlg->getColor();
1581 setColor(aBody, aColorResult);
1586 std::vector<int> aColorResult = aDlg->getColor();
1587 setColor(aResult, aColorResult);
1592 aMgr->finishOperation();
1593 updateCommandStatus();
1596 //**************************************************************
1597 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1598 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1599 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1601 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1603 foreach (ObjectPtr aObj, theList) {
1604 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1606 DocumentPtr aDoc = aPartRes->partDoc();
1607 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1608 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1609 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1611 aObj->setDisplayed(isVisible);
1614 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1617 //**************************************************************
1618 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1620 // Hide all displayed objects
1621 QObjectPtrList aList = myDisplayer->displayedObjects();
1622 foreach (ObjectPtr aObj, aList)
1623 aObj->setDisplayed(false);
1625 // Show only objects from the list
1626 foreach (ObjectPtr aObj, theList) {
1627 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1629 DocumentPtr aDoc = aPartRes->partDoc();
1630 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1631 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1632 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1634 aObj->setDisplayed(true);
1637 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1642 //**************************************************************
1643 void XGUI_Workshop::registerValidators() const
1645 SessionPtr aMgr = ModelAPI_Session::get();
1646 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1649 //**************************************************************
1650 /*void XGUI_Workshop::displayAllResults()
1652 SessionPtr aMgr = ModelAPI_Session::get();
1653 DocumentPtr aRootDoc = aMgr->moduleDocument();
1654 displayDocumentResults(aRootDoc);
1655 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1656 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1657 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1658 displayDocumentResults(aPart->partDoc());
1660 myDisplayer->updateViewer();
1663 //**************************************************************
1664 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1668 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1669 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1672 //**************************************************************
1673 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1675 for (int i = 0; i < theDoc->size(theGroup); i++)
1676 theDoc->object(theGroup, i)->setDisplayed(true);
1677 //displayObject(theDoc->object(theGroup, i));
1678 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1681 //**************************************************************
1682 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1684 foreach(ObjectPtr aObj, theList) {
1685 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1687 if (theList.size() > 0)
1688 myDisplayer->updateViewer();
1691 //**************************************************************
1692 void XGUI_Workshop::closeDocument()
1694 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1695 while (anOperation) {
1696 anOperation->abort();
1697 anOperation = operationMgr()->currentOperation();
1699 myDisplayer->closeLocalContexts();
1700 myDisplayer->eraseAll();
1701 objectBrowser()->clearContent();
1703 SessionPtr aMgr = ModelAPI_Session::get();
1707 //**************************************************************
1708 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1710 if (!myModule->canDisplayObject(theObj))
1713 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1714 if (aBody.get() != NULL) {
1715 int aNb = myDisplayer->objectsCount();
1716 myDisplayer->display(theObj, false);
1719 } else if (!(myIsLoadingData || myPartActivating))
1720 myDisplayer->display(theObj, false);
1725 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1727 XGUI_HistoryMenu* aMenu = NULL;
1728 if (isSalomeMode()) {
1729 QAction* anAction = qobject_cast<QAction*>(theObject);
1732 aMenu = new XGUI_HistoryMenu(anAction);
1734 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1735 aMenu = new XGUI_HistoryMenu(aButton);
1737 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1738 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1741 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1743 QList<ActionInfo> aResult;
1744 std::list<std::string>::const_iterator it = theList.cbegin();
1745 for (; it != theList.cend(); it++) {
1746 QString anId = QString::fromStdString(*it);
1747 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1749 anId.chop(ModuleBase_Operation::EditSuffix().size());
1752 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1753 if (aContextMenuAct) {
1754 anInfo.initFrom(aContextMenuAct);
1756 anInfo = myActionsMgr->actionInfoById(anId);
1759 anInfo.text = anInfo.text.prepend("Modify ");