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 //if (myOperationMgr->hasOperation()) {
474 // ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
475 // if (!aOperation->isEditOperation() &&
476 // aOperation->hasObject(aObj) && myDisplayer->isActive(aObj))
477 if (!myModule->canActivateSelection(aObj)) {
478 if (myDisplayer->isActive(aObj))
479 myDisplayer->deactivate(aObj);
481 } else { // display object if the current operation has it
482 if (displayObject(aObj)) {
483 //ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
484 //if (aOperation && aOperation->hasObject(aObj)) {
485 if (!myModule->canActivateSelection(aObj)) {
486 #ifdef DEBUG_FEATURE_REDISPLAY
487 QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
488 qDebug(QString(" display object = %1").arg(anObjInfo).toStdString().c_str());
490 // Deactivate object of current operation from selection
491 if (myDisplayer->isActive(aObj))
492 myDisplayer->deactivate(aObj);
498 myDisplayer->updateViewer();
501 //******************************************************
502 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
504 std::set<ObjectPtr> aObjects = theMsg->objects();
505 std::set<ObjectPtr>::const_iterator aIt;
506 #ifdef DEBUG_FEATURE_CREATED
508 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
509 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
511 QString anInfoStr = anInfo.join(", ");
512 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
515 //bool aHasPart = false;
516 bool isDisplayed = false;
517 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
518 ObjectPtr anObject = *aIt;
519 // the validity of the data should be checked here in order to avoid display of the objects,
520 // which were created, then deleted, but flush for the creation event happens after that
521 // we should not display disabled objects
522 bool aHide = !anObject->data()->isValid() ||
523 anObject->isDisabled() ||
524 !anObject->isDisplayed();
526 // setDisplayed has to be called in order to synchronize internal state of the object
527 // with list of displayed objects
528 if (myModule->canDisplayObject(anObject)) {
529 anObject->setDisplayed(true);
530 isDisplayed = displayObject(*aIt);
532 anObject->setDisplayed(false);
535 //if (myObjectBrowser)
536 // myObjectBrowser->processEvent(theMsg);
538 myDisplayer->updateViewer();
539 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
540 // activateLastPart();
544 //******************************************************
545 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
547 setNestedFeatures(theOperation);
549 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
550 connectWithOperation(theOperation);
551 setPropertyPanel(theOperation);
553 updateCommandStatus();
555 myModule->operationStarted(theOperation);
558 //******************************************************
559 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
561 setNestedFeatures(theOperation);
563 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
564 // connectWithOperation(theOperation); already connected
565 setPropertyPanel(theOperation);
567 updateCommandStatus();
569 myModule->operationResumed(theOperation);
573 //******************************************************
574 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
576 ModuleBase_ISelection* aSel = mySelector->selection();
577 QObjectPtrList aObj = aSel->selectedPresentations();
578 //!< No need for property panel
579 updateCommandStatus();
581 myPropertyPanel->cleanContent();
583 // Activate objects created by current operation
584 // in order to clean selection modes
585 // the deactivation should be pefromed in the same place, where the mode is activated,
586 // e.g. activation in the current widget activation, deactivation - in the widget's deactivation
588 //myDisplayer->activateObjects(aModes);
589 myModule->operationStopped(theOperation);
591 // if the operation is nested, do not deactivate objects
592 //if (myOperationMgr->operationsCount() == 0) {
593 // Activate selection mode for all objects
595 // TODO: check on OCC_6.9.0
596 // the module current active modes should not be deactivated in order to save the objects selected
597 // the deactivate object in the mode of selection leads to the object is deselected in the viewer.
598 // But, in OCC_6.8.0 this deselection does not happened automatically. It is necessary to call
599 // ClearOutdatedSelection, but this method has an error in the realization, which should be fixed in
600 // the OCC_6.9.0 release. Moreother, it is possible that ClearOutdatedSelection will be called inside
601 // Deactivate method of AIS_InteractiveContext. In this case, we need not call it.
602 module()->activeSelectionModes(aModes);
603 myDisplayer->activateObjects(aModes);
608 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
610 myModule->operationCommitted(theOperation);
613 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
615 myModule->operationAborted(theOperation);
618 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
620 if (this->isSalomeMode())
621 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
623 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
626 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
629 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
630 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
633 myPropertyPanel->cleanContent();
634 aFactory.createWidget(myPropertyPanel->contentWidget());
636 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
637 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
638 bool isStoreValue = !theOperation->isEditOperation() &&
639 !aWidget->getDefaultValue().empty() &&
640 !aWidget->isComputedDefault();
641 aWidget->setFeature(theOperation->feature(), isStoreValue);
642 aWidget->enableFocusProcessing();
645 myPropertyPanel->setModelWidgets(aWidgets);
646 theOperation->setPropertyPanel(myPropertyPanel);
648 myModule->propertyPanelDefined(theOperation);
650 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
653 bool XGUI_Workshop::event(QEvent * theEvent)
655 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
657 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
658 processEvent(aEventPtr);
667 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
671 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
675 ActionInfo aFeatureInfo;
676 aFeatureInfo.initFrom(theMessage);
678 QString aWchName = QString::fromStdString(theMessage->workbenchId());
679 QStringList aNestedFeatures =
680 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
681 QString aDocKind = QString::fromStdString(theMessage->documentKind());
682 QList<QAction*> aNestedActList;
683 bool isColumnButton = !aNestedFeatures.isEmpty();
684 if (isColumnButton) {
685 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
686 if (aNestedActions.contains("accept")) {
687 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
688 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
689 aNestedActList << anAction;
691 if (aNestedActions.contains("abort")) {
692 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
693 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
694 aNestedActList << anAction;
698 if (isSalomeMode()) {
700 if (isColumnButton) {
701 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
703 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
705 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
706 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
708 myActionsMgr->addCommand(aAction);
709 myModule->actionCreated(aAction);
711 //Find or create Workbench
712 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
713 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
715 aPage = addWorkbench(aWchName);
717 //Find or create Group
718 QString aGroupName = QString::fromStdString(theMessage->groupId());
719 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
721 aGroup = aPage->addGroup(aGroupName);
723 // Check if hotkey sequence is already defined:
724 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
725 if(aHotKey != aFeatureInfo.shortcut) {
726 aFeatureInfo.shortcut = aHotKey;
729 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
732 // Enrich created button with accept/abort buttons if necessary
733 AppElements_Button* aButton = aCommand->button();
734 if (aButton->isColumnButton()) {
735 aButton->setAdditionalButtons(aNestedActList);
737 myActionsMgr->addCommand(aCommand);
738 myModule->actionCreated(aCommand);
743 * Makes a signal/slot connections between Property Panel
744 * and given operation. The given operation becomes a
745 * current operation and previous operation if exists
747 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
749 QAction* aCommand = 0;
750 if (isSalomeMode()) {
751 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
753 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
754 FeaturePtr aFeature = theOperation->feature();
756 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
758 //Abort operation on uncheck the command
760 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
765 * Saves document with given name.
767 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
769 QApplication::restoreOverrideCursor();
770 SessionPtr aMgr = ModelAPI_Session::get();
771 aMgr->save(theName.toLatin1().constData(), theFileNames);
772 QApplication::restoreOverrideCursor();
775 bool XGUI_Workshop::isActiveOperationAborted()
777 return myOperationMgr->abortAllOperations();
780 //******************************************************
781 void XGUI_Workshop::onExit()
783 SessionPtr aMgr = ModelAPI_Session::get();
784 if (aMgr->isModified()) {
785 int anAnswer = QMessageBox::question(
786 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
787 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
788 if (anAnswer == QMessageBox::Save) {
789 bool saved = onSave();
793 } else if (anAnswer == QMessageBox::Cancel) {
800 //******************************************************
801 void XGUI_Workshop::onNew()
803 QApplication::setOverrideCursor(Qt::WaitCursor);
804 if (objectBrowser() == 0) {
806 mySelector->connectViewers();
808 myViewerProxy->connectToViewer();
810 if (!isSalomeMode()) {
811 myMainWindow->showPythonConsole();
812 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
813 aWnd->showMaximized();
814 updateCommandStatus();
816 myContextMenuMgr->connectViewer();
817 QApplication::restoreOverrideCursor();
820 //******************************************************
821 void XGUI_Workshop::onOpen()
823 if(!isActiveOperationAborted())
825 //save current file before close if modified
826 SessionPtr aSession = ModelAPI_Session::get();
827 if (aSession->isModified()) {
828 //TODO(sbh): re-launch the app?
829 int anAnswer = QMessageBox::question(
830 myMainWindow, tr("Save current file"),
831 tr("The document is modified, save before opening another?"),
832 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
833 if (anAnswer == QMessageBox::Save) {
835 } else if (anAnswer == QMessageBox::Cancel) {
841 //show file dialog, check if readable and open
842 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
843 if (myCurrentDir.isEmpty())
845 QFileInfo aFileInfo(myCurrentDir);
846 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
847 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
851 QApplication::setOverrideCursor(Qt::WaitCursor);
852 myIsLoadingData = true;
853 aSession->closeAll();
854 aSession->load(myCurrentDir.toLatin1().constData());
855 myObjectBrowser->rebuildDataTree();
856 //displayAllResults();
857 updateCommandStatus();
858 myIsLoadingData = false;
859 QApplication::restoreOverrideCursor();
862 //******************************************************
863 bool XGUI_Workshop::onSave()
865 if(!isActiveOperationAborted())
867 if (myCurrentDir.isEmpty()) {
870 std::list<std::string> aFiles;
871 saveDocument(myCurrentDir, aFiles);
872 updateCommandStatus();
874 myMainWindow->setModifiedState(false);
878 //******************************************************
879 bool XGUI_Workshop::onSaveAs()
881 if(!isActiveOperationAborted())
883 QFileDialog dialog(mainWindow());
884 dialog.setWindowTitle(tr("Select directory to save files..."));
885 dialog.setFileMode(QFileDialog::Directory);
886 dialog.setFilter(tr("Folders (*)"));
887 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
888 dialog.setViewMode(QFileDialog::Detail);
890 if (!dialog.exec()) {
893 QString aTempDir = dialog.selectedFiles().first();
895 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
896 int answer = QMessageBox::question(
898 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
900 tr("The folder already contains some files, save anyway?"),
901 QMessageBox::Save | QMessageBox::Cancel);
902 if (answer == QMessageBox::Cancel) {
906 myCurrentDir = aTempDir;
907 if (!isSalomeMode()) {
908 myMainWindow->setCurrentDir(myCurrentDir, false);
909 myMainWindow->setModifiedState(false);
914 //******************************************************
915 void XGUI_Workshop::onUndo(int theTimes)
917 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
918 SessionPtr aMgr = ModelAPI_Session::get();
919 if (aMgr->isOperation())
920 operationMgr()->onAbortOperation();
921 for (int i = 0; i < theTimes; ++i) {
924 updateCommandStatus();
927 //******************************************************
928 void XGUI_Workshop::onRedo(int theTimes)
930 // the viewer update should be blocked in order to avoid the features blinking. For the created
931 // feature a results are created, the flush of the created signal caused the viewer redisplay for
932 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
933 // redo of all possible objects happens
934 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
936 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
937 SessionPtr aMgr = ModelAPI_Session::get();
938 if (aMgr->isOperation())
939 operationMgr()->onAbortOperation();
940 for (int i = 0; i < theTimes; ++i) {
943 updateCommandStatus();
945 // unblock the viewer update functionality and make update on purpose
946 myDisplayer->enableUpdateViewer(isUpdateEnabled);
947 myDisplayer->updateViewer();
950 //******************************************************
951 void XGUI_Workshop::onRebuild()
953 SessionPtr aMgr = ModelAPI_Session::get();
954 bool aWasOperation = aMgr->isOperation(); // keep this value
955 if (!aWasOperation) {
956 aMgr->startOperation("Rebuild");
958 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
959 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
960 new Events_Message(aRebuildEvent, this)));
961 if (!aWasOperation) {
962 aMgr->finishOperation();
964 updateCommandStatus();
967 //******************************************************
968 void XGUI_Workshop::onPreferences()
970 ModuleBase_Prefs aModif;
971 ModuleBase_Preferences::editPreferences(aModif);
972 if (aModif.size() > 0) {
974 foreach (ModuleBase_Pref aPref, aModif)
976 aSection = aPref.first;
977 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
979 myMainWindow->viewer()->updateFromResources();
980 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
982 myMainWindow->menuObject()->updateFromResources();
988 //******************************************************
989 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
991 QString libName = QString::fromStdString(library(theModule.toStdString()));
992 if (libName.isEmpty()) {
993 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
998 CREATE_FUNC crtInst = 0;
1001 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1005 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1006 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1007 QString aMsg((char*) &lpMsgBuf);
1008 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1009 ::LocalFree(lpMsgBuf);
1011 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1015 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1016 | FORMAT_MESSAGE_IGNORE_INSERTS,
1017 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1018 QString aMsg((char*) &lpMsgBuf);
1019 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1020 ::LocalFree(lpMsgBuf);
1024 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1026 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1028 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1030 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1035 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1037 if (!err.isEmpty()) {
1039 Events_Error::send(err.toStdString());
1041 qWarning(qPrintable(err));
1047 //******************************************************
1048 bool XGUI_Workshop::activateModule()
1050 Config_ModuleReader aModuleReader;
1051 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1052 myModule = loadModule(moduleName);
1056 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1057 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1058 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1059 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1061 myModule->createFeatures();
1062 myActionsMgr->update();
1066 //******************************************************
1067 void XGUI_Workshop::updateCommandStatus()
1069 QList<QAction*> aCommands;
1070 if (isSalomeMode()) { // update commands in SALOME mode
1071 aCommands = salomeConnector()->commandList();
1073 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1074 foreach (AppElements_Command* aCmd, aMenuBar->features())
1075 aCommands.append(aCmd);
1077 SessionPtr aMgr = ModelAPI_Session::get();
1078 if (aMgr->hasModuleDocument()) {
1079 QAction *aUndoCmd, *aRedoCmd;
1080 foreach(QAction* aCmd, aCommands) {
1081 QString aId = aCmd->data().toString();
1082 if (aId == "UNDO_CMD")
1084 else if (aId == "REDO_CMD")
1087 // Enable all commands
1088 aCmd->setEnabled(true);
1091 aUndoCmd->setEnabled(myModule->canUndo());
1092 aRedoCmd->setEnabled(myModule->canRedo());
1095 foreach(QAction* aCmd, aCommands) {
1096 QString aId = aCmd->data().toString();
1097 if (aId == "NEW_CMD")
1098 aCmd->setEnabled(true);
1099 else if (aId == "EXIT_CMD")
1100 aCmd->setEnabled(true);
1102 aCmd->setEnabled(false);
1105 myActionsMgr->update();
1106 emit commandStatusUpdated();
1109 void XGUI_Workshop::updateHistory()
1111 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1112 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1113 emit updateUndoHistory(aUndoRes);
1115 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1116 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1117 emit updateRedoHistory(aRedoRes);
1120 //******************************************************
1121 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1123 QDockWidget* aObjDock = new QDockWidget(theParent);
1124 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1125 aObjDock->setWindowTitle(tr("Object browser"));
1126 aObjDock->setStyleSheet(
1127 "::title { position: relative; padding-left: 5px; text-align: left center }");
1128 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1129 myObjectBrowser->setDataModel(myModule->dataModel());
1130 myModule->customizeObjectBrowser(myObjectBrowser);
1131 aObjDock->setWidget(myObjectBrowser);
1133 myContextMenuMgr->connectObjectBrowser();
1137 //******************************************************
1139 * Creates dock widgets, places them in corresponding area
1140 * and tabifies if necessary.
1142 void XGUI_Workshop::createDockWidgets()
1144 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1145 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1146 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1147 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1148 myPropertyPanel->setupActions(myActionsMgr);
1149 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1150 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1151 hidePropertyPanel(); ///<! Invisible by default
1152 hideObjectBrowser();
1153 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1154 myPropertyPanel->installEventFilter(myOperationMgr);
1156 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1157 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1158 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1159 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1160 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1161 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1162 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1163 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1164 aOkAct, SLOT(setEnabled(bool)));
1165 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1166 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1167 aAcceptAllAct, SLOT(setEnabled(bool)));
1171 //******************************************************
1172 void XGUI_Workshop::showPropertyPanel()
1174 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1175 ///<! Restore ability to close panel from the window's menu
1176 aViewAct->setEnabled(true);
1177 myPropertyPanel->show();
1178 myPropertyPanel->raise();
1181 //******************************************************
1182 void XGUI_Workshop::hidePropertyPanel()
1184 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1185 ///<! Do not allow to show empty property panel
1186 aViewAct->setEnabled(false);
1187 myPropertyPanel->hide();
1190 //******************************************************
1191 void XGUI_Workshop::showObjectBrowser()
1193 myObjectBrowser->parentWidget()->show();
1196 //******************************************************
1197 void XGUI_Workshop::hideObjectBrowser()
1199 myObjectBrowser->parentWidget()->hide();
1202 //******************************************************
1203 void XGUI_Workshop::onFeatureTriggered()
1205 QAction* aCmd = dynamic_cast<QAction*>(sender());
1207 QString aId = salomeConnector()->commandId(aCmd);
1209 myModule->launchOperation(aId);
1213 //******************************************************
1214 void XGUI_Workshop::salomeViewerSelectionChanged()
1216 emit salomeViewerSelection();
1219 //**************************************************************
1220 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1222 return mySalomeConnector->viewer();
1225 //**************************************************************
1226 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1228 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1229 if (theId == "DELETE_CMD")
1231 else if (theId == "COLOR_CMD")
1232 changeColor(aObjects);
1233 else if (theId == "SHOW_CMD")
1234 showObjects(aObjects, true);
1235 else if (theId == "HIDE_CMD")
1236 showObjects(aObjects, false);
1237 else if (theId == "SHOW_ONLY_CMD")
1238 showOnlyObjects(aObjects);
1239 else if (theId == "SHADING_CMD")
1240 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1241 else if (theId == "WIREFRAME_CMD")
1242 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1243 else if (theId == "HIDEALL_CMD") {
1244 QObjectPtrList aList = myDisplayer->displayedObjects();
1245 foreach (ObjectPtr aObj, aList)
1246 aObj->setDisplayed(false);
1247 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
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()->isValid())
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 // this is performed in the RemoveFeature of Part object.
1286 /*foreach (ObjectPtr aObj, anObjects)
1288 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1290 DocumentPtr aDoc = aObj->document();
1291 if (aDoc == aMgr->activeDocument()) {
1296 // 3. delete objects
1297 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1298 std::set<FeaturePtr> anIgnoredFeatures;
1299 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1300 myDisplayer->updateViewer();
1301 aMgr->finishOperation();
1302 updateCommandStatus();
1305 aMgr->abortOperation();
1309 //**************************************************************
1310 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1311 std::set<FeaturePtr> theIgnoredFeatures,
1313 const bool theAskAboutDeleteReferences)
1315 // 1. find all referenced features
1316 std::set<FeaturePtr> aRefFeatures;
1317 foreach (ObjectPtr aDeletedObj, theList) {
1318 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1319 if (aDeletedFeature.get() != NULL) {
1320 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1321 // 1.1 find references in the current document
1322 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1323 // 1.2 find references in all documents if the document of the feature is
1324 // "PartSet". Features of this document can be used in all other documents
1325 SessionPtr aMgr = ModelAPI_Session::get();
1326 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1327 if (aDeletedFeatureDoc == aModuleDoc) {
1328 // the deleted feature and results of the feature should be found in references
1329 std::list<ObjectPtr> aDeletedObjects;
1330 aDeletedObjects.push_back(aDeletedFeature);
1331 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1332 const ResultsList& aDeletedResults = aDeletedFeature->results();
1333 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1334 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1335 ResultPtr aRes = *aRIter;
1337 aDeletedObjects.push_back(aRes);
1339 // get all opened documents; found features in the documents;
1340 // get a list of objects where a feature refers;
1341 // search in these objects the deleted objects.
1342 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1343 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1344 aLast = anOpenedDocs.end();
1345 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1346 for (; anIt != aLast; anIt++) {
1347 DocumentPtr aDocument = *anIt;
1348 if (aDocument == aDeletedFeatureDoc)
1349 continue; // this document has been already processed in 1.1
1351 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1352 for (int aId = 0; aId < aFeaturesCount; aId++) {
1353 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1354 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1355 if (!aFeature.get())
1359 aFeature->data()->referencesToObjects(aRefs);
1360 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1361 bool aHasReferenceToDeleted = false;
1362 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1363 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1364 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1365 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1366 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1367 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1371 if (aHasReferenceToDeleted)
1372 aRefFeatures.insert(aFeature);
1378 // 2. warn about the references remove, break the delete operation if the user chose it
1379 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1380 QStringList aRefNames;
1381 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1382 aLast = aRefFeatures.end();
1383 for (; anIt != aLast; anIt++) {
1384 aRefNames.append((*anIt)->name().c_str());
1386 QString aNames = aRefNames.join(", ");
1388 QMessageBox::StandardButton aRes = QMessageBox::warning(
1389 theParent, tr("Delete features"),
1390 QString(tr("Selected features are used in the following features: %1.\
1391 These features will be deleted also. Would you like to continue?")).arg(aNames),
1392 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1393 if (aRes != QMessageBox::Yes)
1397 // 3. remove referenced features
1398 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1399 aLast = aRefFeatures.end();
1403 for (; anIt != aLast; anIt++) {
1404 FeaturePtr aFeature = (*anIt);
1405 DocumentPtr aDoc = aFeature->document();
1406 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1407 aDoc->removeFeature(aFeature);
1409 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1414 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1418 // 4. remove the parameter features
1419 foreach (ObjectPtr aObj, theList) {
1420 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1421 if (aResult.get() != NULL) { // results could not be removed,
1422 // they are removed by a corresponded feature remove
1425 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1427 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1428 // part features are removed in the PartSet module. This condition should be moved there
1429 if (aFeature->getKind() == "Part")
1432 DocumentPtr aDoc = aObj->document();
1433 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1434 aDoc->removeFeature(aFeature);
1436 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1437 anInfo.append(anInfoStr);
1438 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1444 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1449 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1451 bool isFoundResultType = false;
1452 foreach(ObjectPtr anObj, theObjects)
1454 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1455 if (aResult.get() == NULL)
1458 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1459 if (isFoundResultType)
1462 return isFoundResultType;
1465 //**************************************************************
1466 bool XGUI_Workshop::canChangeColor() const
1468 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1470 std::set<std::string> aTypes;
1471 aTypes.insert(ModelAPI_ResultGroup::group());
1472 aTypes.insert(ModelAPI_ResultConstruction::group());
1473 aTypes.insert(ModelAPI_ResultBody::group());
1474 aTypes.insert(ModelAPI_ResultPart::group());
1476 return hasResults(aObjects, aTypes);
1479 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1481 if (!theResult.get())
1484 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1485 if (aColorAttr.get() != NULL) {
1486 if (!aColorAttr->size()) {
1487 aColorAttr->setSize(3);
1489 aColorAttr->setValue(0, theColor[0]);
1490 aColorAttr->setValue(1, theColor[1]);
1491 aColorAttr->setValue(2, theColor[2]);
1495 //**************************************************************
1496 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1498 AttributeIntArrayPtr aColorAttr;
1499 // 1. find the current color of the object. This is a color of AIS presentation
1500 // The objects are iterated until a first valid color is found
1501 std::vector<int> aColor;
1502 foreach(ObjectPtr anObject, theObjects) {
1503 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1504 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1505 DocumentPtr aPartDoc = aPart->partDoc();
1506 // the document should be checked on null, because in opened document if the part
1507 // has not been activated yet, the part document is empty
1508 if (!aPartDoc.get()) {
1509 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1512 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1513 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1514 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1516 XGUI_CustomPrs::getResultColor(aBody, aColor);
1522 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1524 XGUI_CustomPrs::getResultColor(aResult, aColor);
1526 // TODO: remove the obtaining a color from the AIS object
1527 // this does not happen never because:
1528 // 1. The color can be changed only on results
1529 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1530 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1531 if (anAISObj.get()) {
1533 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1537 if (!aColor.empty())
1540 if (aColor.size() != 3)
1543 // 2. show the dialog to change the value
1544 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1545 aDlg->setColor(aColor);
1546 aDlg->move(QCursor::pos());
1547 bool isDone = aDlg->exec() == QDialog::Accepted;
1551 bool isRandomColor = aDlg->isRandomColor();
1553 // 3. abort the previous operation and start a new one
1554 SessionPtr aMgr = ModelAPI_Session::get();
1555 bool aWasOperation = aMgr->isOperation(); // keep this value
1556 if (!aWasOperation) {
1557 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1558 aMgr->startOperation(aDescription.toStdString());
1561 // 4. set the value to all results
1562 foreach(ObjectPtr anObj, theObjects) {
1563 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1564 if (aResult.get() != NULL) {
1565 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1566 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1567 DocumentPtr aPartDoc = aPart->partDoc();
1568 // the document should be checked on null, because in opened document if the part
1569 // has not been activated yet, the part document is empty
1570 if (aPartDoc.get()) {
1571 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1572 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1573 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1574 std::vector<int> aColorResult = aDlg->getColor();
1575 setColor(aBody, aColorResult);
1580 std::vector<int> aColorResult = aDlg->getColor();
1581 setColor(aResult, aColorResult);
1586 aMgr->finishOperation();
1587 updateCommandStatus();
1590 //**************************************************************
1591 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1592 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1593 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1595 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1597 foreach (ObjectPtr aObj, theList) {
1598 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1600 DocumentPtr aDoc = aPartRes->partDoc();
1601 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1602 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1603 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1605 aObj->setDisplayed(isVisible);
1608 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1611 //**************************************************************
1612 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1614 // Hide all displayed objects
1615 QObjectPtrList aList = myDisplayer->displayedObjects();
1616 foreach (ObjectPtr aObj, aList)
1617 aObj->setDisplayed(false);
1619 // Show only objects from the list
1620 foreach (ObjectPtr aObj, theList) {
1621 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1623 DocumentPtr aDoc = aPartRes->partDoc();
1624 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1625 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1626 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1628 aObj->setDisplayed(true);
1631 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1636 //**************************************************************
1637 void XGUI_Workshop::registerValidators() const
1639 SessionPtr aMgr = ModelAPI_Session::get();
1640 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1643 //**************************************************************
1644 /*void XGUI_Workshop::displayAllResults()
1646 SessionPtr aMgr = ModelAPI_Session::get();
1647 DocumentPtr aRootDoc = aMgr->moduleDocument();
1648 displayDocumentResults(aRootDoc);
1649 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1650 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1651 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1652 displayDocumentResults(aPart->partDoc());
1654 myDisplayer->updateViewer();
1657 //**************************************************************
1658 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1662 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1663 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1666 //**************************************************************
1667 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1669 for (int i = 0; i < theDoc->size(theGroup); i++)
1670 theDoc->object(theGroup, i)->setDisplayed(true);
1671 //displayObject(theDoc->object(theGroup, i));
1672 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1675 //**************************************************************
1676 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1678 foreach(ObjectPtr aObj, theList) {
1679 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1681 if (theList.size() > 0)
1682 myDisplayer->updateViewer();
1685 //**************************************************************
1686 void XGUI_Workshop::closeDocument()
1688 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1689 while (anOperation) {
1690 anOperation->abort();
1691 anOperation = operationMgr()->currentOperation();
1693 myDisplayer->closeLocalContexts();
1694 myDisplayer->eraseAll();
1695 objectBrowser()->clearContent();
1697 SessionPtr aMgr = ModelAPI_Session::get();
1701 //**************************************************************
1702 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1704 if (!myModule->canDisplayObject(theObj))
1707 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1708 if (aBody.get() != NULL) {
1709 int aNb = myDisplayer->objectsCount();
1710 myDisplayer->display(theObj, false);
1713 } else if (!(myIsLoadingData || myPartActivating))
1714 myDisplayer->display(theObj, false);
1719 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1721 XGUI_HistoryMenu* aMenu = NULL;
1722 if (isSalomeMode()) {
1723 QAction* anAction = qobject_cast<QAction*>(theObject);
1726 aMenu = new XGUI_HistoryMenu(anAction);
1728 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1729 aMenu = new XGUI_HistoryMenu(aButton);
1731 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1732 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1735 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1737 QList<ActionInfo> aResult;
1738 std::list<std::string>::const_iterator it = theList.cbegin();
1739 for (; it != theList.cend(); it++) {
1740 QString anId = QString::fromStdString(*it);
1741 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1743 anId.chop(ModuleBase_Operation::EditSuffix().size());
1746 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1747 if (aContextMenuAct) {
1748 anInfo.initFrom(aContextMenuAct);
1750 anInfo = myActionsMgr->actionInfoById(anId);
1753 anInfo.text = anInfo.text.prepend("Modify ");