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);
383 //Show error dialog if error message received.
384 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
386 emit errorOccurred(QString::fromLatin1(anAppError->description()));
390 if (!isSalomeMode()) {
391 SessionPtr aMgr = ModelAPI_Session::get();
392 if (aMgr->isModified() != myMainWindow->isModifiedState())
393 myMainWindow->setModifiedState(aMgr->isModified());
397 //******************************************************
398 QMainWindow* XGUI_Workshop::desktop() const
400 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
403 //******************************************************
404 void XGUI_Workshop::onStartWaiting()
406 if (Events_LongOp::isPerformed()) {
407 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
411 //******************************************************
412 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
414 std::set<ObjectPtr> aFeatures = theMsg->objects();
415 if (myOperationMgr->hasOperation()) {
416 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
417 std::set<ObjectPtr>::const_iterator aIt;
418 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
419 ObjectPtr aNewFeature = (*aIt);
420 if (aNewFeature == aCurrentFeature) {
421 myPropertyPanel->updateContentWidget(aCurrentFeature);
426 myOperationMgr->onValidateOperation();
427 //if (myObjectBrowser)
428 // myObjectBrowser->processEvent(theMsg);
431 //******************************************************
432 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
434 std::set<ObjectPtr> aObjects = theMsg->objects();
435 std::set<ObjectPtr>::const_iterator aIt;
437 #ifdef DEBUG_FEATURE_REDISPLAY
439 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
440 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
442 QString anInfoStr = anInfo.join(", ");
443 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
446 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
447 ObjectPtr aObj = (*aIt);
449 // Hide the object if it is invalid or concealed one
450 bool aHide = !aObj->data() || !aObj->data()->isValid() ||
451 aObj->isDisabled() || (!aObj->isDisplayed());
452 if (!aHide) { // check that this is not hidden result
453 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
454 aHide = aRes && aRes->isConcealed();
457 myDisplayer->erase(aObj, false);
459 // Redisplay the visible object or the object of the current operation
460 bool isVisibleObject = myDisplayer->isVisible(aObj);
461 #ifdef DEBUG_FEATURE_REDISPLAY
462 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
463 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
466 if (isVisibleObject) { // redisplay visible object
467 //displayObject(aObj); // In order to update presentation
468 // in order to avoid the check whether the object can be redisplayed, the exact method
469 // of redisplay is called. This modification is made in order to have the line is updated
470 // by creation of a horizontal constraint on the line by preselection
471 myDisplayer->redisplay(aObj, false);
472 //if (myOperationMgr->hasOperation()) {
473 // ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
474 // if (!aOperation->isEditOperation() &&
475 // aOperation->hasObject(aObj) && myDisplayer->isActive(aObj))
476 if (!myModule->canActivateSelection(aObj)) {
477 if (myDisplayer->isActive(aObj))
478 myDisplayer->deactivate(aObj);
480 } else { // display object if the current operation has it
481 if (displayObject(aObj)) {
482 //ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
483 //if (aOperation && aOperation->hasObject(aObj)) {
484 if (!myModule->canActivateSelection(aObj)) {
485 #ifdef DEBUG_FEATURE_REDISPLAY
486 QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
487 qDebug(QString(" display object = %1").arg(anObjInfo).toStdString().c_str());
489 // Deactivate object of current operation from selection
490 if (myDisplayer->isActive(aObj))
491 myDisplayer->deactivate(aObj);
497 myDisplayer->updateViewer();
500 //******************************************************
501 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
503 std::set<ObjectPtr> aObjects = theMsg->objects();
504 std::set<ObjectPtr>::const_iterator aIt;
505 #ifdef DEBUG_FEATURE_CREATED
507 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
508 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
510 QString anInfoStr = anInfo.join(", ");
511 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
514 //bool aHasPart = false;
515 bool isDisplayed = false;
516 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
517 ObjectPtr anObject = *aIt;
518 // the validity of the data should be checked here in order to avoid display of the objects,
519 // which were created, then deleted, but flush for the creation event happens after that
520 // we should not display disabled objects
521 bool aHide = !anObject->data()->isValid() ||
522 anObject->isDisabled() ||
523 !anObject->isDisplayed();
525 // setDisplayed has to be called in order to synchronize internal state of the object
526 // with list of displayed objects
527 if (myModule->canDisplayObject(anObject)) {
528 anObject->setDisplayed(true);
529 isDisplayed = displayObject(*aIt);
531 anObject->setDisplayed(false);
534 //if (myObjectBrowser)
535 // myObjectBrowser->processEvent(theMsg);
537 myDisplayer->updateViewer();
538 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
539 // activateLastPart();
543 //******************************************************
544 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
546 setNestedFeatures(theOperation);
548 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
549 connectWithOperation(theOperation);
550 setPropertyPanel(theOperation);
552 updateCommandStatus();
554 myModule->operationStarted(theOperation);
557 //******************************************************
558 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
560 setNestedFeatures(theOperation);
562 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
563 // connectWithOperation(theOperation); already connected
564 setPropertyPanel(theOperation);
566 updateCommandStatus();
568 myModule->operationResumed(theOperation);
572 //******************************************************
573 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
575 ModuleBase_ISelection* aSel = mySelector->selection();
576 QObjectPtrList aObj = aSel->selectedPresentations();
577 //!< No need for property panel
578 updateCommandStatus();
580 myPropertyPanel->cleanContent();
582 // Activate objects created by current operation
583 // in order to clean selection modes
584 // the deactivation should be pefromed in the same place, where the mode is activated,
585 // e.g. activation in the current widget activation, deactivation - in the widget's deactivation
587 //myDisplayer->activateObjects(aModes);
588 myModule->operationStopped(theOperation);
590 // if the operation is nested, do not deactivate objects
591 //if (myOperationMgr->operationsCount() == 0) {
592 // Activate selection mode for all objects
594 // TODO: check on OCC_6.9.0
595 // the module current active modes should not be deactivated in order to save the objects selected
596 // the deactivate object in the mode of selection leads to the object is deselected in the viewer.
597 // But, in OCC_6.8.0 this deselection does not happened automatically. It is necessary to call
598 // ClearOutdatedSelection, but this method has an error in the realization, which should be fixed in
599 // the OCC_6.9.0 release. Moreother, it is possible that ClearOutdatedSelection will be called inside
600 // Deactivate method of AIS_InteractiveContext. In this case, we need not call it.
601 module()->activeSelectionModes(aModes);
602 myDisplayer->activateObjects(aModes);
607 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
609 myModule->operationCommitted(theOperation);
612 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
614 myModule->operationAborted(theOperation);
617 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
619 if (this->isSalomeMode())
620 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
622 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
625 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
628 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
629 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
632 myPropertyPanel->cleanContent();
633 aFactory.createWidget(myPropertyPanel->contentWidget());
635 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
636 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
637 bool isStoreValue = !theOperation->isEditOperation() &&
638 !aWidget->getDefaultValue().empty() &&
639 !aWidget->isComputedDefault();
640 aWidget->setFeature(theOperation->feature(), isStoreValue);
641 aWidget->enableFocusProcessing();
644 myPropertyPanel->setModelWidgets(aWidgets);
645 theOperation->setPropertyPanel(myPropertyPanel);
647 myModule->propertyPanelDefined(theOperation);
649 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
652 bool XGUI_Workshop::event(QEvent * theEvent)
654 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
656 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
657 processEvent(aEventPtr);
666 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
670 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
674 ActionInfo aFeatureInfo;
675 aFeatureInfo.initFrom(theMessage);
677 QString aWchName = QString::fromStdString(theMessage->workbenchId());
678 QStringList aNestedFeatures =
679 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
680 QString aDocKind = QString::fromStdString(theMessage->documentKind());
681 QList<QAction*> aNestedActList;
682 bool isColumnButton = !aNestedFeatures.isEmpty();
683 if (isColumnButton) {
684 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
685 if (aNestedActions.contains("accept")) {
686 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
687 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
688 aNestedActList << anAction;
690 if (aNestedActions.contains("abort")) {
691 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
692 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
693 aNestedActList << anAction;
697 if (isSalomeMode()) {
699 if (isColumnButton) {
700 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
702 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
704 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
705 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
707 myActionsMgr->addCommand(aAction);
708 myModule->actionCreated(aAction);
710 //Find or create Workbench
711 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
712 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
714 aPage = addWorkbench(aWchName);
716 //Find or create Group
717 QString aGroupName = QString::fromStdString(theMessage->groupId());
718 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
720 aGroup = aPage->addGroup(aGroupName);
722 // Check if hotkey sequence is already defined:
723 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
724 if(aHotKey != aFeatureInfo.shortcut) {
725 aFeatureInfo.shortcut = aHotKey;
728 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
731 // Enrich created button with accept/abort buttons if necessary
732 AppElements_Button* aButton = aCommand->button();
733 if (aButton->isColumnButton()) {
734 aButton->setAdditionalButtons(aNestedActList);
736 myActionsMgr->addCommand(aCommand);
737 myModule->actionCreated(aCommand);
742 * Makes a signal/slot connections between Property Panel
743 * and given operation. The given operation becomes a
744 * current operation and previous operation if exists
746 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
748 QAction* aCommand = 0;
749 if (isSalomeMode()) {
750 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
752 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
753 FeaturePtr aFeature = theOperation->feature();
755 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
757 //Abort operation on uncheck the command
759 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
764 * Saves document with given name.
766 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
768 QApplication::restoreOverrideCursor();
769 SessionPtr aMgr = ModelAPI_Session::get();
770 aMgr->save(theName.toLatin1().constData(), theFileNames);
771 QApplication::restoreOverrideCursor();
774 bool XGUI_Workshop::isActiveOperationAborted()
776 return myOperationMgr->abortAllOperations();
779 //******************************************************
780 void XGUI_Workshop::onExit()
782 SessionPtr aMgr = ModelAPI_Session::get();
783 if (aMgr->isModified()) {
784 int anAnswer = QMessageBox::question(
785 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
786 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
787 if (anAnswer == QMessageBox::Save) {
788 bool saved = onSave();
792 } else if (anAnswer == QMessageBox::Cancel) {
799 //******************************************************
800 void XGUI_Workshop::onNew()
802 QApplication::setOverrideCursor(Qt::WaitCursor);
803 if (objectBrowser() == 0) {
805 mySelector->connectViewers();
807 myViewerProxy->connectToViewer();
809 if (!isSalomeMode()) {
810 myMainWindow->showPythonConsole();
811 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
812 aWnd->showMaximized();
813 updateCommandStatus();
815 myContextMenuMgr->connectViewer();
816 QApplication::restoreOverrideCursor();
819 //******************************************************
820 void XGUI_Workshop::onOpen()
822 if(!isActiveOperationAborted())
824 //save current file before close if modified
825 SessionPtr aSession = ModelAPI_Session::get();
826 if (aSession->isModified()) {
827 //TODO(sbh): re-launch the app?
828 int anAnswer = QMessageBox::question(
829 myMainWindow, tr("Save current file"),
830 tr("The document is modified, save before opening another?"),
831 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
832 if (anAnswer == QMessageBox::Save) {
834 } else if (anAnswer == QMessageBox::Cancel) {
840 //show file dialog, check if readable and open
841 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
842 if (myCurrentDir.isEmpty())
844 QFileInfo aFileInfo(myCurrentDir);
845 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
846 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
850 QApplication::setOverrideCursor(Qt::WaitCursor);
851 myIsLoadingData = true;
852 aSession->closeAll();
853 aSession->load(myCurrentDir.toLatin1().constData());
854 myObjectBrowser->rebuildDataTree();
855 //displayAllResults();
856 updateCommandStatus();
857 myIsLoadingData = false;
858 QApplication::restoreOverrideCursor();
861 //******************************************************
862 bool XGUI_Workshop::onSave()
864 if(!isActiveOperationAborted())
866 if (myCurrentDir.isEmpty()) {
869 std::list<std::string> aFiles;
870 saveDocument(myCurrentDir, aFiles);
871 updateCommandStatus();
873 myMainWindow->setModifiedState(false);
877 //******************************************************
878 bool XGUI_Workshop::onSaveAs()
880 if(!isActiveOperationAborted())
882 QFileDialog dialog(mainWindow());
883 dialog.setWindowTitle(tr("Select directory to save files..."));
884 dialog.setFileMode(QFileDialog::Directory);
885 dialog.setFilter(tr("Folders (*)"));
886 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
887 dialog.setViewMode(QFileDialog::Detail);
889 if (!dialog.exec()) {
892 QString aTempDir = dialog.selectedFiles().first();
894 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
895 int answer = QMessageBox::question(
897 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
899 tr("The folder already contains some files, save anyway?"),
900 QMessageBox::Save | QMessageBox::Cancel);
901 if (answer == QMessageBox::Cancel) {
905 myCurrentDir = aTempDir;
906 if (!isSalomeMode()) {
907 myMainWindow->setCurrentDir(myCurrentDir, false);
908 myMainWindow->setModifiedState(false);
913 //******************************************************
914 void XGUI_Workshop::onUndo(int theTimes)
916 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
917 SessionPtr aMgr = ModelAPI_Session::get();
918 if (aMgr->isOperation())
919 operationMgr()->onAbortOperation();
920 for (int i = 0; i < theTimes; ++i) {
923 updateCommandStatus();
926 //******************************************************
927 void XGUI_Workshop::onRedo(int theTimes)
929 // the viewer update should be blocked in order to avoid the features blinking. For the created
930 // feature a results are created, the flush of the created signal caused the viewer redisplay for
931 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
932 // redo of all possible objects happens
933 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
935 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
936 SessionPtr aMgr = ModelAPI_Session::get();
937 if (aMgr->isOperation())
938 operationMgr()->onAbortOperation();
939 for (int i = 0; i < theTimes; ++i) {
942 updateCommandStatus();
944 // unblock the viewer update functionality and make update on purpose
945 myDisplayer->enableUpdateViewer(isUpdateEnabled);
946 myDisplayer->updateViewer();
949 //******************************************************
950 void XGUI_Workshop::onRebuild()
952 SessionPtr aMgr = ModelAPI_Session::get();
953 bool aWasOperation = aMgr->isOperation(); // keep this value
954 if (!aWasOperation) {
955 aMgr->startOperation("Rebuild");
957 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
958 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
959 new Events_Message(aRebuildEvent, this)));
960 if (!aWasOperation) {
961 aMgr->finishOperation();
963 updateCommandStatus();
966 //******************************************************
967 void XGUI_Workshop::onPreferences()
969 ModuleBase_Prefs aModif;
970 ModuleBase_Preferences::editPreferences(aModif);
971 if (aModif.size() > 0) {
973 foreach (ModuleBase_Pref aPref, aModif)
975 aSection = aPref.first;
976 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
978 myMainWindow->viewer()->updateFromResources();
979 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
981 myMainWindow->menuObject()->updateFromResources();
987 //******************************************************
988 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
990 QString libName = QString::fromStdString(library(theModule.toStdString()));
991 if (libName.isEmpty()) {
992 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
997 CREATE_FUNC crtInst = 0;
1000 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1004 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1005 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1006 QString aMsg((char*) &lpMsgBuf);
1007 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1008 ::LocalFree(lpMsgBuf);
1010 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1014 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1015 | FORMAT_MESSAGE_IGNORE_INSERTS,
1016 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1017 QString aMsg((char*) &lpMsgBuf);
1018 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1019 ::LocalFree(lpMsgBuf);
1023 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1025 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1027 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1029 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1034 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1036 if (!err.isEmpty()) {
1038 Events_Error::send(err.toStdString());
1040 qWarning(qPrintable(err));
1046 //******************************************************
1047 bool XGUI_Workshop::activateModule()
1049 Config_ModuleReader aModuleReader;
1050 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1051 myModule = loadModule(moduleName);
1055 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1056 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1057 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1058 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1060 myModule->createFeatures();
1061 myActionsMgr->update();
1065 //******************************************************
1066 void XGUI_Workshop::updateCommandStatus()
1068 QList<QAction*> aCommands;
1069 if (isSalomeMode()) { // update commands in SALOME mode
1070 aCommands = salomeConnector()->commandList();
1072 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1073 foreach (AppElements_Command* aCmd, aMenuBar->features())
1074 aCommands.append(aCmd);
1076 SessionPtr aMgr = ModelAPI_Session::get();
1077 if (aMgr->hasModuleDocument()) {
1078 QAction *aUndoCmd, *aRedoCmd;
1079 foreach(QAction* aCmd, aCommands) {
1080 QString aId = aCmd->data().toString();
1081 if (aId == "UNDO_CMD")
1083 else if (aId == "REDO_CMD")
1086 // Enable all commands
1087 aCmd->setEnabled(true);
1090 aUndoCmd->setEnabled(myModule->canUndo());
1091 aRedoCmd->setEnabled(myModule->canRedo());
1094 foreach(QAction* aCmd, aCommands) {
1095 QString aId = aCmd->data().toString();
1096 if (aId == "NEW_CMD")
1097 aCmd->setEnabled(true);
1098 else if (aId == "EXIT_CMD")
1099 aCmd->setEnabled(true);
1101 aCmd->setEnabled(false);
1104 myActionsMgr->update();
1105 emit commandStatusUpdated();
1108 void XGUI_Workshop::updateHistory()
1110 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1111 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1112 emit updateUndoHistory(aUndoRes);
1114 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1115 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1116 emit updateRedoHistory(aRedoRes);
1119 //******************************************************
1120 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1122 QDockWidget* aObjDock = new QDockWidget(theParent);
1123 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1124 aObjDock->setWindowTitle(tr("Object browser"));
1125 aObjDock->setStyleSheet(
1126 "::title { position: relative; padding-left: 5px; text-align: left center }");
1127 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1128 myObjectBrowser->setDataModel(myModule->dataModel());
1129 myModule->customizeObjectBrowser(myObjectBrowser);
1130 aObjDock->setWidget(myObjectBrowser);
1132 myContextMenuMgr->connectObjectBrowser();
1136 //******************************************************
1138 * Creates dock widgets, places them in corresponding area
1139 * and tabifies if necessary.
1141 void XGUI_Workshop::createDockWidgets()
1143 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1144 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1145 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1146 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1147 myPropertyPanel->setupActions(myActionsMgr);
1148 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1149 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1150 hidePropertyPanel(); ///<! Invisible by default
1151 hideObjectBrowser();
1152 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1153 myPropertyPanel->installEventFilter(myOperationMgr);
1155 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1156 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1157 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1158 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1159 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1160 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1161 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1162 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1163 aOkAct, SLOT(setEnabled(bool)));
1164 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1165 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1166 aAcceptAllAct, SLOT(setEnabled(bool)));
1170 //******************************************************
1171 void XGUI_Workshop::showPropertyPanel()
1173 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1174 ///<! Restore ability to close panel from the window's menu
1175 aViewAct->setEnabled(true);
1176 myPropertyPanel->show();
1177 myPropertyPanel->raise();
1180 //******************************************************
1181 void XGUI_Workshop::hidePropertyPanel()
1183 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1184 ///<! Do not allow to show empty property panel
1185 aViewAct->setEnabled(false);
1186 myPropertyPanel->hide();
1189 //******************************************************
1190 void XGUI_Workshop::showObjectBrowser()
1192 myObjectBrowser->parentWidget()->show();
1195 //******************************************************
1196 void XGUI_Workshop::hideObjectBrowser()
1198 myObjectBrowser->parentWidget()->hide();
1201 //******************************************************
1202 void XGUI_Workshop::onFeatureTriggered()
1204 QAction* aCmd = dynamic_cast<QAction*>(sender());
1206 QString aId = salomeConnector()->commandId(aCmd);
1208 myModule->launchOperation(aId);
1212 //******************************************************
1213 void XGUI_Workshop::salomeViewerSelectionChanged()
1215 emit salomeViewerSelection();
1218 //**************************************************************
1219 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1221 return mySalomeConnector->viewer();
1224 //**************************************************************
1225 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1227 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1228 if (theId == "DELETE_CMD")
1230 else if (theId == "COLOR_CMD")
1231 changeColor(aObjects);
1232 else if (theId == "SHOW_CMD")
1233 showObjects(aObjects, true);
1234 else if (theId == "HIDE_CMD")
1235 showObjects(aObjects, false);
1236 else if (theId == "SHOW_ONLY_CMD")
1237 showOnlyObjects(aObjects);
1238 else if (theId == "SHADING_CMD")
1239 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1240 else if (theId == "WIREFRAME_CMD")
1241 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1242 else if (theId == "HIDEALL_CMD") {
1243 QObjectPtrList aList = myDisplayer->displayedObjects();
1244 foreach (ObjectPtr aObj, aList)
1245 aObj->setDisplayed(false);
1246 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1250 //**************************************************************
1251 void XGUI_Workshop::deleteObjects()
1253 ModuleBase_IModule* aModule = module();
1254 // 1. allow the module to delete objects, do nothing if it has succeed
1255 if (aModule->deleteObjects()) {
1256 updateCommandStatus();
1260 if (!isActiveOperationAborted())
1262 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1263 bool hasResult = false;
1264 bool hasFeature = false;
1265 bool hasParameter = false;
1266 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1267 if (!(hasFeature || hasParameter))
1270 // 1. start operation
1271 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1272 aDescription += tr(" %1");
1273 QStringList aObjectNames;
1274 foreach (ObjectPtr aObj, anObjects) {
1275 if (!aObj->data()->isValid())
1277 aObjectNames << QString::fromStdString(aObj->data()->name());
1279 aDescription = aDescription.arg(aObjectNames.join(", "));
1281 SessionPtr aMgr = ModelAPI_Session::get();
1282 aMgr->startOperation(aDescription.toStdString());
1283 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1284 // this is performed in the RemoveFeature of Part object.
1285 /*foreach (ObjectPtr aObj, anObjects)
1287 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1289 DocumentPtr aDoc = aObj->document();
1290 if (aDoc == aMgr->activeDocument()) {
1295 // 3. delete objects
1296 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1297 std::set<FeaturePtr> anIgnoredFeatures;
1298 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1299 myDisplayer->updateViewer();
1300 aMgr->finishOperation();
1301 updateCommandStatus();
1304 aMgr->abortOperation();
1308 //**************************************************************
1309 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1310 std::set<FeaturePtr> theIgnoredFeatures,
1312 const bool theAskAboutDeleteReferences)
1314 // 1. find all referenced features
1315 std::set<FeaturePtr> aRefFeatures;
1316 foreach (ObjectPtr aDeletedObj, theList) {
1317 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1318 if (aDeletedFeature.get() != NULL) {
1319 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1320 // 1.1 find references in the current document
1321 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1322 // 1.2 find references in all documents if the document of the feature is
1323 // "PartSet". Features of this document can be used in all other documents
1324 SessionPtr aMgr = ModelAPI_Session::get();
1325 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1326 if (aDeletedFeatureDoc == aModuleDoc) {
1327 // the deleted feature and results of the feature should be found in references
1328 std::list<ObjectPtr> aDeletedObjects;
1329 aDeletedObjects.push_back(aDeletedFeature);
1330 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1331 const ResultsList& aDeletedResults = aDeletedFeature->results();
1332 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1333 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1334 ResultPtr aRes = *aRIter;
1336 aDeletedObjects.push_back(aRes);
1338 // get all opened documents; found features in the documents;
1339 // get a list of objects where a feature refers;
1340 // search in these objects the deleted objects.
1341 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1342 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1343 aLast = anOpenedDocs.end();
1344 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1345 for (; anIt != aLast; anIt++) {
1346 DocumentPtr aDocument = *anIt;
1347 if (aDocument == aDeletedFeatureDoc)
1348 continue; // this document has been already processed in 1.1
1350 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1351 for (int aId = 0; aId < aFeaturesCount; aId++) {
1352 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1353 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1354 if (!aFeature.get())
1358 aFeature->data()->referencesToObjects(aRefs);
1359 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1360 bool aHasReferenceToDeleted = false;
1361 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1362 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1363 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1364 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1365 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1366 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1370 if (aHasReferenceToDeleted)
1371 aRefFeatures.insert(aFeature);
1377 // 2. warn about the references remove, break the delete operation if the user chose it
1378 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1379 QStringList aRefNames;
1380 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1381 aLast = aRefFeatures.end();
1382 for (; anIt != aLast; anIt++) {
1383 aRefNames.append((*anIt)->name().c_str());
1385 QString aNames = aRefNames.join(", ");
1387 QMessageBox::StandardButton aRes = QMessageBox::warning(
1388 theParent, tr("Delete features"),
1389 QString(tr("Selected features are used in the following features: %1.\
1390 These features will be deleted also. Would you like to continue?")).arg(aNames),
1391 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1392 if (aRes != QMessageBox::Yes)
1396 // 3. remove referenced features
1397 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1398 aLast = aRefFeatures.end();
1402 for (; anIt != aLast; anIt++) {
1403 FeaturePtr aFeature = (*anIt);
1404 DocumentPtr aDoc = aFeature->document();
1405 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1406 aDoc->removeFeature(aFeature);
1408 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1413 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1417 // 4. remove the parameter features
1418 foreach (ObjectPtr aObj, theList) {
1419 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1420 if (aResult.get() != NULL) { // results could not be removed,
1421 // they are removed by a corresponded feature remove
1424 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1426 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1427 // part features are removed in the PartSet module. This condition should be moved there
1428 if (aFeature->getKind() == "Part")
1431 DocumentPtr aDoc = aObj->document();
1432 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1433 aDoc->removeFeature(aFeature);
1435 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1436 anInfo.append(anInfoStr);
1437 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1443 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1448 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1450 bool isFoundResultType = false;
1451 foreach(ObjectPtr anObj, theObjects)
1453 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1454 if (aResult.get() == NULL)
1457 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1458 if (isFoundResultType)
1461 return isFoundResultType;
1464 //**************************************************************
1465 bool XGUI_Workshop::canChangeColor() const
1467 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1469 std::set<std::string> aTypes;
1470 aTypes.insert(ModelAPI_ResultGroup::group());
1471 aTypes.insert(ModelAPI_ResultConstruction::group());
1472 aTypes.insert(ModelAPI_ResultBody::group());
1473 aTypes.insert(ModelAPI_ResultPart::group());
1475 return hasResults(aObjects, aTypes);
1478 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1480 if (!theResult.get())
1483 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1484 if (aColorAttr.get() != NULL) {
1485 if (!aColorAttr->size()) {
1486 aColorAttr->setSize(3);
1488 aColorAttr->setValue(0, theColor[0]);
1489 aColorAttr->setValue(1, theColor[1]);
1490 aColorAttr->setValue(2, theColor[2]);
1494 //**************************************************************
1495 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1497 AttributeIntArrayPtr aColorAttr;
1498 // 1. find the current color of the object. This is a color of AIS presentation
1499 // The objects are iterated until a first valid color is found
1500 std::vector<int> aColor;
1501 foreach(ObjectPtr anObject, theObjects) {
1502 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1503 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1504 DocumentPtr aPartDoc = aPart->partDoc();
1505 // the document should be checked on null, because in opened document if the part
1506 // has not been activated yet, the part document is empty
1507 if (!aPartDoc.get()) {
1508 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1511 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1512 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1513 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1515 XGUI_CustomPrs::getResultColor(aBody, aColor);
1521 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1523 XGUI_CustomPrs::getResultColor(aResult, aColor);
1525 // TODO: remove the obtaining a color from the AIS object
1526 // this does not happen never because:
1527 // 1. The color can be changed only on results
1528 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1529 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1530 if (anAISObj.get()) {
1532 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1536 if (!aColor.empty())
1539 if (aColor.size() != 3)
1542 // 2. show the dialog to change the value
1543 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1544 aDlg->setColor(aColor);
1545 aDlg->move(QCursor::pos());
1546 bool isDone = aDlg->exec() == QDialog::Accepted;
1550 bool isRandomColor = aDlg->isRandomColor();
1552 // 3. abort the previous operation and start a new one
1553 SessionPtr aMgr = ModelAPI_Session::get();
1554 bool aWasOperation = aMgr->isOperation(); // keep this value
1555 if (!aWasOperation) {
1556 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1557 aMgr->startOperation(aDescription.toStdString());
1560 // 4. set the value to all results
1561 foreach(ObjectPtr anObj, theObjects) {
1562 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1563 if (aResult.get() != NULL) {
1564 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1565 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1566 DocumentPtr aPartDoc = aPart->partDoc();
1567 // the document should be checked on null, because in opened document if the part
1568 // has not been activated yet, the part document is empty
1569 if (aPartDoc.get()) {
1570 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1571 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1572 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1573 std::vector<int> aColorResult = aDlg->getColor();
1574 setColor(aBody, aColorResult);
1579 std::vector<int> aColorResult = aDlg->getColor();
1580 setColor(aResult, aColorResult);
1585 aMgr->finishOperation();
1586 updateCommandStatus();
1589 //**************************************************************
1590 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1592 foreach (ObjectPtr aObj, theList) {
1594 aObj->setDisplayed(true);
1595 //displayObject(aObj);
1597 aObj->setDisplayed(false);
1598 //myDisplayer->erase(aObj, false);
1601 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1602 //myDisplayer->updateViewer();
1605 //**************************************************************
1606 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1608 QObjectPtrList aList = myDisplayer->displayedObjects();
1609 foreach (ObjectPtr aObj, aList)
1610 aObj->setDisplayed(false);
1611 foreach (ObjectPtr aObj, theList)
1612 aObj->setDisplayed(true);
1613 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1618 //**************************************************************
1619 void XGUI_Workshop::registerValidators() const
1621 SessionPtr aMgr = ModelAPI_Session::get();
1622 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1625 //**************************************************************
1626 /*void XGUI_Workshop::displayAllResults()
1628 SessionPtr aMgr = ModelAPI_Session::get();
1629 DocumentPtr aRootDoc = aMgr->moduleDocument();
1630 displayDocumentResults(aRootDoc);
1631 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1632 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1633 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1634 displayDocumentResults(aPart->partDoc());
1636 myDisplayer->updateViewer();
1639 //**************************************************************
1640 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1644 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1645 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1648 //**************************************************************
1649 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1651 for (int i = 0; i < theDoc->size(theGroup); i++)
1652 theDoc->object(theGroup, i)->setDisplayed(true);
1653 //displayObject(theDoc->object(theGroup, i));
1654 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1657 //**************************************************************
1658 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1660 foreach(ObjectPtr aObj, theList) {
1661 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1663 if (theList.size() > 0)
1664 myDisplayer->updateViewer();
1667 //**************************************************************
1668 void XGUI_Workshop::closeDocument()
1670 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1671 while (anOperation) {
1672 anOperation->abort();
1673 anOperation = operationMgr()->currentOperation();
1675 myDisplayer->closeLocalContexts();
1676 myDisplayer->eraseAll();
1677 objectBrowser()->clearContent();
1679 SessionPtr aMgr = ModelAPI_Session::get();
1683 //**************************************************************
1684 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1686 if (!myModule->canDisplayObject(theObj))
1689 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1690 if (aBody.get() != NULL) {
1691 int aNb = myDisplayer->objectsCount();
1692 myDisplayer->display(theObj, false);
1695 } else if (!(myIsLoadingData || myPartActivating))
1696 myDisplayer->display(theObj, false);
1701 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1703 XGUI_HistoryMenu* aMenu = NULL;
1704 if (isSalomeMode()) {
1705 QAction* anAction = qobject_cast<QAction*>(theObject);
1708 aMenu = new XGUI_HistoryMenu(anAction);
1710 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1711 aMenu = new XGUI_HistoryMenu(aButton);
1713 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1714 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1717 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1719 QList<ActionInfo> aResult;
1720 std::list<std::string>::const_iterator it = theList.cbegin();
1721 for (; it != theList.cend(); it++) {
1722 QString anId = QString::fromStdString(*it);
1723 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1725 anId.chop(ModuleBase_Operation::EditSuffix().size());
1728 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1729 if (aContextMenuAct) {
1730 anInfo.initFrom(aContextMenuAct);
1732 anInfo = myActionsMgr->actionInfoById(anId);
1735 anInfo.text = anInfo.text.prepend("Modify ");