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 <SUIT_ResourceMgr.h>
73 #include <QApplication>
74 #include <QFileDialog>
75 #include <QMessageBox>
76 #include <QMdiSubWindow>
77 #include <QPushButton>
78 #include <QDockWidget>
83 #include <QToolButton>
85 #include <QDesktopWidget>
98 //#define DEBUG_FEATURE_CREATED
99 //#define DEBUG_FEATURE_REDISPLAY
100 //#define DEBUG_DELETE
102 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
104 myCurrentDir(QString()),
106 mySalomeConnector(theConnector),
110 myUpdatePrefs(false),
111 myPartActivating(false),
112 myIsLoadingData(false)
114 myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
117 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
118 bool aCloc = aResMgr->booleanValue("language", "locale", true);
120 QLocale::setDefault( QLocale::c() );
122 QLocale::setDefault( QLocale::system() );
125 myDisplayer = new XGUI_Displayer(this);
127 mySelector = new XGUI_SelectionMgr(this);
128 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
130 myOperationMgr = new XGUI_OperationMgr(this);
131 myActionsMgr = new XGUI_ActionsMgr(this);
132 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
133 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
134 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
135 SLOT(onContextMenuCommand(const QString&, bool)));
137 myViewerProxy = new XGUI_ViewerProxy(this);
138 connect(myViewerProxy, SIGNAL(selectionChanged()),
139 myActionsMgr, SLOT(updateOnViewSelection()));
141 myModuleConnector = new XGUI_ModuleConnector(this);
143 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
144 SLOT(onOperationStarted(ModuleBase_Operation*)));
145 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
146 SLOT(onOperationResumed(ModuleBase_Operation*)));
147 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
148 SLOT(onOperationStopped(ModuleBase_Operation*)));
149 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
150 SLOT(onOperationCommitted(ModuleBase_Operation*)));
151 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
152 SLOT(onOperationAborted(ModuleBase_Operation*)));
154 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
155 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
158 //******************************************************
159 XGUI_Workshop::~XGUI_Workshop(void)
164 //******************************************************
165 void XGUI_Workshop::startApplication()
169 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
170 Config_Prop::Directory, "");
172 //Initialize event listening
173 Events_Loop* aLoop = Events_Loop::loop();
174 aLoop->registerListener(this, Events_Error::errorID()); //!< Listening application errors.
175 aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
176 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
177 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
178 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
179 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
180 aLoop->registerListener(this, Events_LongOp::eventID());
181 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
182 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
184 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
185 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
187 registerValidators();
189 // Calling of loadCustomProps before activating module is required
190 // by Config_PropManger to restore user-defined path to plugins
191 ModuleBase_Preferences::loadCustomProps();
194 myMainWindow->show();
195 updateCommandStatus();
200 emit applicationStarted();
203 void XGUI_Workshop::activateModule()
205 myModule->activateSelectionFilters();
207 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
208 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
209 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
210 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
212 myActionsMgr->update();
216 void XGUI_Workshop::deactivateModule()
218 myModule->deactivateSelectionFilters();
220 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
221 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
222 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
223 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
226 //******************************************************
227 void XGUI_Workshop::initMenu()
229 myContextMenuMgr->createActions();
231 if (isSalomeMode()) {
232 // Create only Undo, Redo commands
233 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
234 tr("Undo last command"),
235 QIcon(":pictures/undo.png"),
236 QKeySequence::Undo, false, "MEN_DESK_EDIT");
237 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
238 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
240 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
241 QIcon(":pictures/redo.png"), QKeySequence::Redo,
242 false, "MEN_DESK_EDIT");
243 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
244 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
246 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
247 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
248 QIcon(":pictures/rebuild.png"), QKeySequence(),
249 false, "MEN_DESK_EDIT");
250 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
251 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
253 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
254 QIcon(), QKeySequence(),
255 false, "MEN_DESK_FILE");
256 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
258 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
259 QIcon(), QKeySequence(),
260 false, "MEN_DESK_FILE");
261 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
262 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
266 // File commands group
267 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
269 AppElements_Command* aCommand;
271 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
272 QIcon(":pictures/save.png"), QKeySequence::Save);
273 aCommand->connectTo(this, SLOT(onSave()));
274 //aCommand->disable();
276 QString aUndoId = "UNDO_CMD";
277 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
278 QIcon(":pictures/undo.png"), QKeySequence::Undo);
279 aCommand->connectTo(this, SLOT(onUndo()));
280 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
281 addHistoryMenu(aUndoButton,
282 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
285 QString aRedoId = "REDO_CMD";
286 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
287 QIcon(":pictures/redo.png"), QKeySequence::Redo);
288 aCommand->connectTo(this, SLOT(onRedo()));
289 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
290 addHistoryMenu(aRedoButton,
291 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
294 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
295 QIcon(":pictures/rebuild.png"), QKeySequence());
296 aCommand->connectTo(this, SLOT(onRebuild()));
298 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
299 QIcon(":pictures/save.png"), QKeySequence());
300 aCommand->connectTo(this, SLOT(onSaveAs()));
301 //aCommand->disable();
303 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
304 QIcon(":pictures/open.png"), QKeySequence::Open);
305 aCommand->connectTo(this, SLOT(onOpen()));
307 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
308 // QIcon(":pictures/new.png"), QKeySequence::New);
309 //aCommand->connectTo(this, SLOT(onNew()));
311 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
312 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
313 aCommand->connectTo(this, SLOT(onPreferences()));
315 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
316 QIcon(":pictures/close.png"), QKeySequence::Close);
317 aCommand->connectTo(this, SLOT(onExit()));
318 //FIXME: SBH's test action. Can be used for some GUI tests.
320 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
321 // QIcon(":pictures/close.png"), QKeySequence(), true);
322 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
326 //******************************************************
327 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
329 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
330 return aMenuBar->addWorkbench(theName);
333 //******************************************************
334 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
336 if (QApplication::instance()->thread() != QThread::currentThread()) {
338 std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
340 SessionPtr aMgr = ModelAPI_Session::get();
341 PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
342 QApplication::postEvent(this, aPostponeEvent);
346 //A message to start feature creation received.
347 if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
348 std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
349 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
350 if (!aFeatureMsg->isInternal()) {
351 addFeature(aFeatureMsg);
354 // Process creation of Part
355 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
356 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
357 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
358 onFeatureCreatedMsg(aUpdMsg);
360 if (mySalomeConnector)
361 mySalomeConnector->createPreferences();
362 myUpdatePrefs = false;
365 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
366 myUpdatePrefs = true;
369 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
370 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
371 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
372 onFeatureRedisplayMsg(aUpdMsg);
374 //Update property panel on corresponding message. If there is no current operation (no
375 //property panel), or received message has different feature to the current - do nothing.
376 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
377 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
378 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
379 onFeatureUpdatedMsg(anUpdateMsg);
380 } else if (theMessage->eventID() == Events_LongOp::eventID()) {
381 if (Events_LongOp::isPerformed()) {
382 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
384 QApplication::restoreOverrideCursor();
387 //An operation passed by message. Start it, process and commit.
388 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
389 std::shared_ptr<Config_PointerMessage> aPartSetMsg =
390 std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
391 //myPropertyPanel->cleanContent();
392 ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
394 if (myOperationMgr->startOperation(anOperation)) {
395 myPropertyPanel->updateContentWidget(anOperation->feature());
396 if (!anOperation->getDescription()->hasXmlRepresentation()) {
397 if (anOperation->commit())
398 updateCommandStatus();
402 else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
403 std::shared_ptr<Config_SelectionFilterMessage> aMsg =
404 std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
406 ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
407 if (!aMsg->attributeId().empty()) {
408 aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
412 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
413 // the viewer's update context will not happens until viewer updated is emitted
414 myDisplayer->enableUpdateViewer(false);
415 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
416 // the viewer's update context is unblocked, the viewer's update works
417 myDisplayer->enableUpdateViewer(true);
418 myDisplayer->updateViewer();
420 //Show error dialog if error message received.
421 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
423 emit errorOccurred(QString::fromLatin1(anAppError->description()));
427 if (!isSalomeMode()) {
428 SessionPtr aMgr = ModelAPI_Session::get();
429 if (aMgr->isModified() != myMainWindow->isModifiedState())
430 myMainWindow->setModifiedState(aMgr->isModified());
434 //******************************************************
435 QMainWindow* XGUI_Workshop::desktop() const
437 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
440 //******************************************************
441 void XGUI_Workshop::onStartWaiting()
443 if (Events_LongOp::isPerformed()) {
444 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
448 //******************************************************
449 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
451 std::set<ObjectPtr> aFeatures = theMsg->objects();
452 if (myOperationMgr->hasOperation()) {
453 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
454 std::set<ObjectPtr>::const_iterator aIt;
455 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
456 ObjectPtr aNewFeature = (*aIt);
457 if (aNewFeature == aCurrentFeature) {
458 myPropertyPanel->updateContentWidget(aCurrentFeature);
463 myOperationMgr->onValidateOperation();
464 //if (myObjectBrowser)
465 // myObjectBrowser->processEvent(theMsg);
468 //******************************************************
469 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
471 std::set<ObjectPtr> aObjects = theMsg->objects();
472 std::set<ObjectPtr>::const_iterator aIt;
474 #ifdef DEBUG_FEATURE_REDISPLAY
476 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
477 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
479 QString anInfoStr = anInfo.join(", ");
480 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
483 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
484 ObjectPtr aObj = (*aIt);
486 // Hide the object if it is invalid or concealed one
487 bool aHide = !aObj->data() || !aObj->data()->isValid() ||
488 aObj->isDisabled() || (!aObj->isDisplayed());
489 if (!aHide) { // check that this is not hidden result
490 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
491 aHide = aRes && aRes->isConcealed();
494 myDisplayer->erase(aObj, false);
496 // Redisplay the visible object or the object of the current operation
497 bool isVisibleObject = myDisplayer->isVisible(aObj);
498 #ifdef DEBUG_FEATURE_REDISPLAY
499 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
500 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
503 if (isVisibleObject) { // redisplay visible object
504 //displayObject(aObj); // In order to update presentation
505 // in order to avoid the check whether the object can be redisplayed, the exact method
506 // of redisplay is called. This modification is made in order to have the line is updated
507 // by creation of a horizontal constraint on the line by preselection
508 myDisplayer->redisplay(aObj, false);
509 // Deactivate object of current operation from selection
510 deactivateActiveObject(aObj, false);
511 } else { // display object if the current operation has it
512 if (displayObject(aObj)) {
513 // Deactivate object of current operation from selection
514 deactivateActiveObject(aObj, false);
519 myDisplayer->updateViewer();
522 //******************************************************
523 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
525 if (!myModule->canActivateSelection(theObject)) {
526 if (myDisplayer->isActive(theObject))
527 myDisplayer->deactivate(theObject, theUpdateViewer);
531 //******************************************************
532 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
534 std::set<ObjectPtr> aObjects = theMsg->objects();
535 std::set<ObjectPtr>::const_iterator aIt;
536 #ifdef DEBUG_FEATURE_CREATED
538 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
539 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
541 QString anInfoStr = anInfo.join(", ");
542 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
545 //bool aHasPart = false;
546 bool isDisplayed = false;
547 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
548 ObjectPtr anObject = *aIt;
549 // the validity of the data should be checked here in order to avoid display of the objects,
550 // which were created, then deleted, but flush for the creation event happens after that
551 // we should not display disabled objects
552 bool aHide = !anObject->data()->isValid() ||
553 anObject->isDisabled() ||
554 !anObject->isDisplayed();
556 // setDisplayed has to be called in order to synchronize internal state of the object
557 // with list of displayed objects
558 if (myModule->canDisplayObject(anObject)) {
559 anObject->setDisplayed(true);
560 isDisplayed = displayObject(*aIt);
562 anObject->setDisplayed(false);
565 //if (myObjectBrowser)
566 // myObjectBrowser->processEvent(theMsg);
568 myDisplayer->updateViewer();
569 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
570 // activateLastPart();
574 //******************************************************
575 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
577 setNestedFeatures(theOperation);
579 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
580 connectWithOperation(theOperation);
581 setPropertyPanel(theOperation);
583 updateCommandStatus();
585 myModule->onOperationStarted(theOperation);
587 // the objects of the current operation should be deactivated
588 QObjectPtrList anObjects;
589 FeaturePtr aFeature = theOperation->feature();
590 anObjects.append(aFeature);
591 std::list<ResultPtr> aResults = aFeature->results();
592 std::list<ResultPtr>::const_iterator aIt;
593 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
594 anObjects.append(*aIt);
596 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
597 for (; anIt != aLast; anIt++)
598 deactivateActiveObject(*anIt, false);
599 if (anObjects.size() > 0)
600 myDisplayer->updateViewer();
603 //******************************************************
604 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
606 setNestedFeatures(theOperation);
608 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
609 // connectWithOperation(theOperation); already connected
610 setPropertyPanel(theOperation);
612 updateCommandStatus();
614 myModule->onOperationResumed(theOperation);
618 //******************************************************
619 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
621 ModuleBase_ISelection* aSel = mySelector->selection();
622 QObjectPtrList aObj = aSel->selectedPresentations();
623 //!< No need for property panel
624 updateCommandStatus();
626 myPropertyPanel->cleanContent();
628 myModule->onOperationStopped(theOperation);
630 // the deactivated objects of the current operation should be activated back.
631 // They were deactivated on operation start or an object redisplay
632 QObjectPtrList anObjects;
633 FeaturePtr aFeature = theOperation->feature();
634 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
635 anObjects.append(aFeature);
636 std::list<ResultPtr> aResults = aFeature->results();
637 std::list<ResultPtr>::const_iterator aIt;
638 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
639 ResultPtr anObject = *aIt;
640 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
641 anObjects.append(anObject);
645 module()->activeSelectionModes(aModes);
646 myDisplayer->activateObjects(aModes, anObjects);
650 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
652 myModule->onOperationCommitted(theOperation);
655 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
657 myModule->onOperationAborted(theOperation);
660 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
662 if (this->isSalomeMode())
663 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
665 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
668 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
671 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
672 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
675 myPropertyPanel->cleanContent();
676 aFactory.createWidget(myPropertyPanel->contentWidget());
678 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
679 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
680 bool isStoreValue = !theOperation->isEditOperation() &&
681 !aWidget->getDefaultValue().empty() &&
682 !aWidget->isComputedDefault();
683 aWidget->setFeature(theOperation->feature(), isStoreValue);
684 aWidget->enableFocusProcessing();
687 myPropertyPanel->setModelWidgets(aWidgets);
688 theOperation->setPropertyPanel(myPropertyPanel);
690 myModule->propertyPanelDefined(theOperation);
692 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
695 bool XGUI_Workshop::event(QEvent * theEvent)
697 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
699 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
700 processEvent(aEventPtr);
709 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
713 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
717 ActionInfo aFeatureInfo;
718 aFeatureInfo.initFrom(theMessage);
720 QString aWchName = QString::fromStdString(theMessage->workbenchId());
721 QStringList aNestedFeatures =
722 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
723 QString aDocKind = QString::fromStdString(theMessage->documentKind());
724 QList<QAction*> aNestedActList;
725 bool isColumnButton = !aNestedFeatures.isEmpty();
726 if (isColumnButton) {
727 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
728 if (aNestedActions.contains("accept")) {
729 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
730 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
731 aNestedActList << anAction;
733 if (aNestedActions.contains("abort")) {
734 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
735 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
736 aNestedActList << anAction;
740 if (isSalomeMode()) {
742 if (isColumnButton) {
743 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
745 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
747 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
748 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
750 myActionsMgr->addCommand(aAction);
751 myModule->actionCreated(aAction);
753 //Find or create Workbench
754 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
755 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
757 aPage = addWorkbench(aWchName);
759 //Find or create Group
760 QString aGroupName = QString::fromStdString(theMessage->groupId());
761 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
763 aGroup = aPage->addGroup(aGroupName);
765 // Check if hotkey sequence is already defined:
766 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
767 if(aHotKey != aFeatureInfo.shortcut) {
768 aFeatureInfo.shortcut = aHotKey;
771 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
774 // Enrich created button with accept/abort buttons if necessary
775 AppElements_Button* aButton = aCommand->button();
776 if (aButton->isColumnButton()) {
777 aButton->setAdditionalButtons(aNestedActList);
779 myActionsMgr->addCommand(aCommand);
780 myModule->actionCreated(aCommand);
785 * Makes a signal/slot connections between Property Panel
786 * and given operation. The given operation becomes a
787 * current operation and previous operation if exists
789 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
791 QAction* aCommand = 0;
792 if (isSalomeMode()) {
793 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
795 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
796 FeaturePtr aFeature = theOperation->feature();
798 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
800 //Abort operation on uncheck the command
802 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
807 * Saves document with given name.
809 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
811 QApplication::restoreOverrideCursor();
812 SessionPtr aMgr = ModelAPI_Session::get();
813 aMgr->save(theName.toLatin1().constData(), theFileNames);
814 QApplication::restoreOverrideCursor();
817 bool XGUI_Workshop::isActiveOperationAborted()
819 return myOperationMgr->abortAllOperations();
822 //******************************************************
823 void XGUI_Workshop::onExit()
825 SessionPtr aMgr = ModelAPI_Session::get();
826 if (aMgr->isModified()) {
827 int anAnswer = QMessageBox::question(
828 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
829 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
830 if (anAnswer == QMessageBox::Save) {
831 bool saved = onSave();
835 } else if (anAnswer == QMessageBox::Cancel) {
842 //******************************************************
843 void XGUI_Workshop::onNew()
845 QApplication::setOverrideCursor(Qt::WaitCursor);
846 if (objectBrowser() == 0) {
848 mySelector->connectViewers();
850 myViewerProxy->connectToViewer();
852 if (!isSalomeMode()) {
853 myMainWindow->showPythonConsole();
854 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
855 aWnd->showMaximized();
856 updateCommandStatus();
858 myContextMenuMgr->connectViewer();
859 QApplication::restoreOverrideCursor();
862 //******************************************************
863 void XGUI_Workshop::onOpen()
865 if(!isActiveOperationAborted())
867 //save current file before close if modified
868 SessionPtr aSession = ModelAPI_Session::get();
869 if (aSession->isModified()) {
870 //TODO(sbh): re-launch the app?
871 int anAnswer = QMessageBox::question(
872 myMainWindow, tr("Save current file"),
873 tr("The document is modified, save before opening another?"),
874 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
875 if (anAnswer == QMessageBox::Save) {
877 } else if (anAnswer == QMessageBox::Cancel) {
883 //show file dialog, check if readable and open
884 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
885 if (myCurrentDir.isEmpty())
887 QFileInfo aFileInfo(myCurrentDir);
888 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
889 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
893 QApplication::setOverrideCursor(Qt::WaitCursor);
894 myIsLoadingData = true;
895 aSession->closeAll();
896 aSession->load(myCurrentDir.toLatin1().constData());
897 myObjectBrowser->rebuildDataTree();
898 //displayAllResults();
899 updateCommandStatus();
900 myIsLoadingData = false;
901 QApplication::restoreOverrideCursor();
904 //******************************************************
905 bool XGUI_Workshop::onSave()
907 if(!isActiveOperationAborted())
909 if (myCurrentDir.isEmpty()) {
912 std::list<std::string> aFiles;
913 saveDocument(myCurrentDir, aFiles);
914 updateCommandStatus();
916 myMainWindow->setModifiedState(false);
920 //******************************************************
921 bool XGUI_Workshop::onSaveAs()
923 if(!isActiveOperationAborted())
925 QFileDialog dialog(mainWindow());
926 dialog.setWindowTitle(tr("Select directory to save files..."));
927 dialog.setFileMode(QFileDialog::Directory);
928 dialog.setFilter(tr("Folders (*)"));
929 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
930 dialog.setViewMode(QFileDialog::Detail);
932 if (!dialog.exec()) {
935 QString aTempDir = dialog.selectedFiles().first();
937 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
938 int answer = QMessageBox::question(
940 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
942 tr("The folder already contains some files, save anyway?"),
943 QMessageBox::Save | QMessageBox::Cancel);
944 if (answer == QMessageBox::Cancel) {
948 myCurrentDir = aTempDir;
949 if (!isSalomeMode()) {
950 myMainWindow->setCurrentDir(myCurrentDir, false);
951 myMainWindow->setModifiedState(false);
956 //******************************************************
957 void XGUI_Workshop::onUndo(int theTimes)
959 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
960 SessionPtr aMgr = ModelAPI_Session::get();
961 if (aMgr->isOperation())
962 operationMgr()->onAbortOperation();
963 for (int i = 0; i < theTimes; ++i) {
966 updateCommandStatus();
969 //******************************************************
970 void XGUI_Workshop::onRedo(int theTimes)
972 // the viewer update should be blocked in order to avoid the features blinking. For the created
973 // feature a results are created, the flush of the created signal caused the viewer redisplay for
974 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
975 // redo of all possible objects happens
976 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
978 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
979 SessionPtr aMgr = ModelAPI_Session::get();
980 if (aMgr->isOperation())
981 operationMgr()->onAbortOperation();
982 for (int i = 0; i < theTimes; ++i) {
985 updateCommandStatus();
987 // unblock the viewer update functionality and make update on purpose
988 myDisplayer->enableUpdateViewer(isUpdateEnabled);
989 myDisplayer->updateViewer();
992 //******************************************************
993 void XGUI_Workshop::onRebuild()
995 SessionPtr aMgr = ModelAPI_Session::get();
996 bool aWasOperation = aMgr->isOperation(); // keep this value
997 if (!aWasOperation) {
998 aMgr->startOperation("Rebuild");
1000 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1001 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1002 new Events_Message(aRebuildEvent, this)));
1003 if (!aWasOperation) {
1004 aMgr->finishOperation();
1006 updateCommandStatus();
1009 //******************************************************
1010 void XGUI_Workshop::onPreferences()
1012 ModuleBase_Prefs aModif;
1013 ModuleBase_Preferences::editPreferences(aModif);
1014 if (aModif.size() > 0) {
1016 foreach (ModuleBase_Pref aPref, aModif)
1018 aSection = aPref.first;
1019 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1020 if (!isSalomeMode())
1021 myMainWindow->viewer()->updateFromResources();
1022 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1023 if (!isSalomeMode())
1024 myMainWindow->menuObject()->updateFromResources();
1030 //******************************************************
1031 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1033 QString libName = QString::fromStdString(library(theModule.toStdString()));
1034 if (libName.isEmpty()) {
1035 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1040 CREATE_FUNC crtInst = 0;
1043 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1047 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1048 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1049 QString aMsg((char*) &lpMsgBuf);
1050 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1051 ::LocalFree(lpMsgBuf);
1053 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1057 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1058 | FORMAT_MESSAGE_IGNORE_INSERTS,
1059 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1060 QString aMsg((char*) &lpMsgBuf);
1061 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1062 ::LocalFree(lpMsgBuf);
1066 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1068 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1070 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1072 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1077 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1079 if (!err.isEmpty()) {
1081 Events_Error::send(err.toStdString());
1083 qWarning(qPrintable(err));
1089 //******************************************************
1090 bool XGUI_Workshop::createModule()
1092 Config_ModuleReader aModuleReader;
1093 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1094 myModule = loadModule(moduleName);
1098 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1099 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1100 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1101 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1103 myModule->createFeatures();
1104 //myActionsMgr->update();
1108 //******************************************************
1109 void XGUI_Workshop::updateCommandStatus()
1111 QList<QAction*> aCommands;
1112 if (isSalomeMode()) { // update commands in SALOME mode
1113 aCommands = salomeConnector()->commandList();
1115 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1116 foreach (AppElements_Command* aCmd, aMenuBar->features())
1117 aCommands.append(aCmd);
1119 SessionPtr aMgr = ModelAPI_Session::get();
1120 if (aMgr->hasModuleDocument()) {
1121 foreach(QAction* aCmd, aCommands) {
1122 QString aId = aCmd->data().toString();
1123 if (aId == "UNDO_CMD")
1124 aCmd->setEnabled(myModule->canUndo());
1125 else if (aId == "REDO_CMD")
1126 aCmd->setEnabled(myModule->canRedo());
1128 // Enable all commands
1129 aCmd->setEnabled(true);
1133 foreach(QAction* aCmd, aCommands) {
1134 QString aId = aCmd->data().toString();
1135 if (aId == "NEW_CMD")
1136 aCmd->setEnabled(true);
1137 else if (aId == "EXIT_CMD")
1138 aCmd->setEnabled(true);
1140 aCmd->setEnabled(false);
1143 myActionsMgr->update();
1144 emit commandStatusUpdated();
1147 void XGUI_Workshop::updateHistory()
1149 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1150 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1151 emit updateUndoHistory(aUndoRes);
1153 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1154 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1155 emit updateRedoHistory(aRedoRes);
1158 //******************************************************
1159 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1161 QDockWidget* aObjDock = new QDockWidget(theParent);
1162 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1163 aObjDock->setWindowTitle(tr("Object browser"));
1164 aObjDock->setStyleSheet(
1165 "::title { position: relative; padding-left: 5px; text-align: left center }");
1166 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1167 myObjectBrowser->setDataModel(myModule->dataModel());
1168 myModule->customizeObjectBrowser(myObjectBrowser);
1169 aObjDock->setWidget(myObjectBrowser);
1171 myContextMenuMgr->connectObjectBrowser();
1175 //******************************************************
1177 * Creates dock widgets, places them in corresponding area
1178 * and tabifies if necessary.
1180 void XGUI_Workshop::createDockWidgets()
1182 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1183 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1184 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1185 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1186 myPropertyPanel->setupActions(myActionsMgr);
1187 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1188 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1189 hidePropertyPanel(); ///<! Invisible by default
1190 hideObjectBrowser();
1191 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1192 myPropertyPanel->installEventFilter(myOperationMgr);
1194 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1195 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1196 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1197 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1198 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1199 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1200 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1201 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1202 aOkAct, SLOT(setEnabled(bool)));
1203 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1204 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1205 aAcceptAllAct, SLOT(setEnabled(bool)));
1209 //******************************************************
1210 void XGUI_Workshop::showPropertyPanel()
1212 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1213 ///<! Restore ability to close panel from the window's menu
1214 aViewAct->setEnabled(true);
1215 myPropertyPanel->show();
1216 myPropertyPanel->raise();
1219 //******************************************************
1220 void XGUI_Workshop::hidePropertyPanel()
1222 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1223 ///<! Do not allow to show empty property panel
1224 aViewAct->setEnabled(false);
1225 myPropertyPanel->hide();
1228 //******************************************************
1229 void XGUI_Workshop::showObjectBrowser()
1231 myObjectBrowser->parentWidget()->show();
1234 //******************************************************
1235 void XGUI_Workshop::hideObjectBrowser()
1237 myObjectBrowser->parentWidget()->hide();
1240 //******************************************************
1241 //void XGUI_Workshop::onFeatureTriggered()
1243 // QAction* aCmd = dynamic_cast<QAction*>(sender());
1245 // QString aId = salomeConnector()->commandId(aCmd);
1246 // if (!aId.isNull())
1247 // myModule->launchOperation(aId);
1251 //******************************************************
1252 void XGUI_Workshop::salomeViewerSelectionChanged()
1254 emit salomeViewerSelection();
1257 //**************************************************************
1258 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1260 return mySalomeConnector->viewer();
1263 //**************************************************************
1264 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1266 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1267 if (theId == "DELETE_CMD")
1269 else if (theId == "COLOR_CMD")
1270 changeColor(aObjects);
1271 else if (theId == "SHOW_CMD")
1272 showObjects(aObjects, true);
1273 else if (theId == "HIDE_CMD")
1274 showObjects(aObjects, false);
1275 else if (theId == "SHOW_ONLY_CMD")
1276 showOnlyObjects(aObjects);
1277 else if (theId == "SHADING_CMD")
1278 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1279 else if (theId == "WIREFRAME_CMD")
1280 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1281 else if (theId == "HIDEALL_CMD") {
1282 QObjectPtrList aList = myDisplayer->displayedObjects();
1283 foreach (ObjectPtr aObj, aList)
1284 aObj->setDisplayed(false);
1285 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1289 //**************************************************************
1290 void XGUI_Workshop::deleteObjects()
1292 ModuleBase_IModule* aModule = module();
1293 // 1. allow the module to delete objects, do nothing if it has succeed
1294 if (aModule->deleteObjects()) {
1295 updateCommandStatus();
1299 if (!isActiveOperationAborted())
1301 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1302 bool hasResult = false;
1303 bool hasFeature = false;
1304 bool hasParameter = false;
1305 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1306 if (!(hasFeature || hasParameter))
1309 // 1. start operation
1310 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1311 aDescription += tr(" %1");
1312 QStringList aObjectNames;
1313 foreach (ObjectPtr aObj, anObjects) {
1314 if (!aObj->data()->isValid())
1316 aObjectNames << QString::fromStdString(aObj->data()->name());
1318 aDescription = aDescription.arg(aObjectNames.join(", "));
1320 SessionPtr aMgr = ModelAPI_Session::get();
1321 aMgr->startOperation(aDescription.toStdString());
1322 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1323 // this is performed in the RemoveFeature of Part object.
1324 /*foreach (ObjectPtr aObj, anObjects)
1326 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1328 DocumentPtr aDoc = aObj->document();
1329 if (aDoc == aMgr->activeDocument()) {
1334 // 3. delete objects
1335 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1336 std::set<FeaturePtr> anIgnoredFeatures;
1337 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1338 myDisplayer->updateViewer();
1339 aMgr->finishOperation();
1340 updateCommandStatus();
1343 aMgr->abortOperation();
1347 //**************************************************************
1348 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1349 std::set<FeaturePtr> theIgnoredFeatures,
1351 const bool theAskAboutDeleteReferences)
1353 // 1. find all referenced features
1354 std::set<FeaturePtr> aRefFeatures;
1355 foreach (ObjectPtr aDeletedObj, theList) {
1356 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1357 if (aDeletedFeature.get() != NULL) {
1358 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1359 // 1.1 find references in the current document
1360 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1361 // 1.2 find references in all documents if the document of the feature is
1362 // "PartSet". Features of this document can be used in all other documents
1363 SessionPtr aMgr = ModelAPI_Session::get();
1364 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1365 if (aDeletedFeatureDoc == aModuleDoc) {
1366 // the deleted feature and results of the feature should be found in references
1367 std::list<ObjectPtr> aDeletedObjects;
1368 aDeletedObjects.push_back(aDeletedFeature);
1369 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1370 const ResultsList& aDeletedResults = aDeletedFeature->results();
1371 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1372 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1373 ResultPtr aRes = *aRIter;
1375 aDeletedObjects.push_back(aRes);
1377 // get all opened documents; found features in the documents;
1378 // get a list of objects where a feature refers;
1379 // search in these objects the deleted objects.
1380 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1381 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1382 aLast = anOpenedDocs.end();
1383 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1384 for (; anIt != aLast; anIt++) {
1385 DocumentPtr aDocument = *anIt;
1386 if (aDocument == aDeletedFeatureDoc)
1387 continue; // this document has been already processed in 1.1
1389 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1390 for (int aId = 0; aId < aFeaturesCount; aId++) {
1391 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1392 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1393 if (!aFeature.get())
1397 aFeature->data()->referencesToObjects(aRefs);
1398 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1399 bool aHasReferenceToDeleted = false;
1400 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1401 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1402 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1403 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1404 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1405 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1409 if (aHasReferenceToDeleted)
1410 aRefFeatures.insert(aFeature);
1416 // 2. warn about the references remove, break the delete operation if the user chose it
1417 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1418 QStringList aRefNames;
1419 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1420 aLast = aRefFeatures.end();
1421 for (; anIt != aLast; anIt++) {
1422 aRefNames.append((*anIt)->name().c_str());
1424 QString aNames = aRefNames.join(", ");
1426 QMessageBox::StandardButton aRes = QMessageBox::warning(
1427 theParent, tr("Delete features"),
1428 QString(tr("Selected features are used in the following features: %1.\
1429 These features will be deleted also. Would you like to continue?")).arg(aNames),
1430 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1431 if (aRes != QMessageBox::Yes)
1435 // 3. remove referenced features
1436 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1437 aLast = aRefFeatures.end();
1441 for (; anIt != aLast; anIt++) {
1442 FeaturePtr aFeature = (*anIt);
1443 DocumentPtr aDoc = aFeature->document();
1444 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1445 aDoc->removeFeature(aFeature);
1447 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1452 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1456 // 4. remove the parameter features
1457 foreach (ObjectPtr aObj, theList) {
1458 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1459 if (aResult.get() != NULL) { // results could not be removed,
1460 // they are removed by a corresponded feature remove
1463 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1465 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1466 // part features are removed in the PartSet module. This condition should be moved there
1467 if (aFeature->getKind() == "Part")
1470 DocumentPtr aDoc = aObj->document();
1471 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1472 aDoc->removeFeature(aFeature);
1474 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1475 anInfo.append(anInfoStr);
1476 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1482 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1487 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1489 bool isFoundResultType = false;
1490 foreach(ObjectPtr anObj, theObjects)
1492 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1493 if (aResult.get() == NULL)
1496 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1497 if (isFoundResultType)
1500 return isFoundResultType;
1503 //**************************************************************
1504 bool XGUI_Workshop::canChangeColor() const
1506 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1508 std::set<std::string> aTypes;
1509 aTypes.insert(ModelAPI_ResultGroup::group());
1510 aTypes.insert(ModelAPI_ResultConstruction::group());
1511 aTypes.insert(ModelAPI_ResultBody::group());
1512 aTypes.insert(ModelAPI_ResultPart::group());
1514 return hasResults(aObjects, aTypes);
1517 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1519 if (!theResult.get())
1522 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1523 if (aColorAttr.get() != NULL) {
1524 if (!aColorAttr->size()) {
1525 aColorAttr->setSize(3);
1527 aColorAttr->setValue(0, theColor[0]);
1528 aColorAttr->setValue(1, theColor[1]);
1529 aColorAttr->setValue(2, theColor[2]);
1533 //**************************************************************
1534 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1536 AttributeIntArrayPtr aColorAttr;
1537 // 1. find the current color of the object. This is a color of AIS presentation
1538 // The objects are iterated until a first valid color is found
1539 std::vector<int> aColor;
1540 foreach(ObjectPtr anObject, theObjects) {
1541 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1542 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1543 DocumentPtr aPartDoc = aPart->partDoc();
1544 // the document should be checked on null, because in opened document if the part
1545 // has not been activated yet, the part document is empty
1546 if (!aPartDoc.get()) {
1547 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1550 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1551 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1552 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1554 XGUI_CustomPrs::getResultColor(aBody, aColor);
1560 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1562 XGUI_CustomPrs::getResultColor(aResult, aColor);
1564 // TODO: remove the obtaining a color from the AIS object
1565 // this does not happen never because:
1566 // 1. The color can be changed only on results
1567 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1568 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1569 if (anAISObj.get()) {
1571 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1575 if (!aColor.empty())
1578 if (aColor.size() != 3)
1581 // 2. show the dialog to change the value
1582 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1583 aDlg->setColor(aColor);
1584 aDlg->move(QCursor::pos());
1585 bool isDone = aDlg->exec() == QDialog::Accepted;
1589 bool isRandomColor = aDlg->isRandomColor();
1591 // 3. abort the previous operation and start a new one
1592 SessionPtr aMgr = ModelAPI_Session::get();
1593 bool aWasOperation = aMgr->isOperation(); // keep this value
1594 if (!aWasOperation) {
1595 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1596 aMgr->startOperation(aDescription.toStdString());
1599 // 4. set the value to all results
1600 foreach(ObjectPtr anObj, theObjects) {
1601 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1602 if (aResult.get() != NULL) {
1603 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1604 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1605 DocumentPtr aPartDoc = aPart->partDoc();
1606 // the document should be checked on null, because in opened document if the part
1607 // has not been activated yet, the part document is empty
1608 if (aPartDoc.get()) {
1609 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1610 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1611 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1612 std::vector<int> aColorResult = aDlg->getColor();
1613 setColor(aBody, aColorResult);
1618 std::vector<int> aColorResult = aDlg->getColor();
1619 setColor(aResult, aColorResult);
1624 aMgr->finishOperation();
1625 updateCommandStatus();
1628 //**************************************************************
1629 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1630 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1631 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1633 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1635 foreach (ObjectPtr aObj, theList) {
1636 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1638 DocumentPtr aDoc = aPartRes->partDoc();
1639 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1640 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1641 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1643 aObj->setDisplayed(isVisible);
1646 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1649 //**************************************************************
1650 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1652 // Hide all displayed objects
1653 QObjectPtrList aList = myDisplayer->displayedObjects();
1654 foreach (ObjectPtr aObj, aList)
1655 aObj->setDisplayed(false);
1657 // Show only objects from the list
1658 foreach (ObjectPtr aObj, theList) {
1659 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1661 DocumentPtr aDoc = aPartRes->partDoc();
1662 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1663 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1664 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1666 aObj->setDisplayed(true);
1669 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1674 //**************************************************************
1675 void XGUI_Workshop::registerValidators() const
1677 SessionPtr aMgr = ModelAPI_Session::get();
1678 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1681 //**************************************************************
1682 /*void XGUI_Workshop::displayAllResults()
1684 SessionPtr aMgr = ModelAPI_Session::get();
1685 DocumentPtr aRootDoc = aMgr->moduleDocument();
1686 displayDocumentResults(aRootDoc);
1687 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1688 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1689 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1690 displayDocumentResults(aPart->partDoc());
1692 myDisplayer->updateViewer();
1695 //**************************************************************
1696 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1700 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1701 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1704 //**************************************************************
1705 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1707 for (int i = 0; i < theDoc->size(theGroup); i++)
1708 theDoc->object(theGroup, i)->setDisplayed(true);
1709 //displayObject(theDoc->object(theGroup, i));
1710 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1713 //**************************************************************
1714 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1716 foreach(ObjectPtr aObj, theList) {
1717 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1719 if (theList.size() > 0)
1720 myDisplayer->updateViewer();
1723 //**************************************************************
1724 void XGUI_Workshop::closeDocument()
1726 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1727 while (anOperation) {
1728 anOperation->abort();
1729 anOperation = operationMgr()->currentOperation();
1731 myDisplayer->closeLocalContexts();
1732 myDisplayer->eraseAll();
1733 objectBrowser()->clearContent();
1735 SessionPtr aMgr = ModelAPI_Session::get();
1739 //**************************************************************
1740 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1742 if (!myModule->canDisplayObject(theObj))
1745 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1746 if (aBody.get() != NULL) {
1747 int aNb = myDisplayer->objectsCount();
1748 myDisplayer->display(theObj, false);
1751 } else if (!(myIsLoadingData || myPartActivating))
1752 myDisplayer->display(theObj, false);
1757 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1759 XGUI_HistoryMenu* aMenu = NULL;
1760 if (isSalomeMode()) {
1761 QAction* anAction = qobject_cast<QAction*>(theObject);
1764 aMenu = new XGUI_HistoryMenu(anAction);
1766 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1767 aMenu = new XGUI_HistoryMenu(aButton);
1769 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1770 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1773 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1775 QList<ActionInfo> aResult;
1776 std::list<std::string>::const_iterator it = theList.cbegin();
1777 for (; it != theList.cend(); it++) {
1778 QString anId = QString::fromStdString(*it);
1779 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1781 anId.chop(ModuleBase_Operation::EditSuffix().size());
1784 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1785 if (aContextMenuAct) {
1786 anInfo.initFrom(aContextMenuAct);
1788 anInfo = myActionsMgr->actionInfoById(anId);
1791 anInfo.text = anInfo.text.prepend("Modify ");