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&)));
157 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
158 // Config_Prop::Color, "225,225,225");
160 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
161 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
162 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
163 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
164 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
165 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
168 //******************************************************
169 XGUI_Workshop::~XGUI_Workshop(void)
174 //******************************************************
175 void XGUI_Workshop::startApplication()
179 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
180 Config_Prop::Directory, "");
182 //Initialize event listening
183 Events_Loop* aLoop = Events_Loop::loop();
184 aLoop->registerListener(this, Events_Error::errorID()); //!< Listening application errors.
185 aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
186 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
187 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
188 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
189 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
190 aLoop->registerListener(this, Events_LongOp::eventID());
191 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
192 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
194 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
195 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
197 registerValidators();
199 // Calling of loadCustomProps before activating module is required
200 // by Config_PropManger to restore user-defined path to plugins
201 ModuleBase_Preferences::loadCustomProps();
204 myMainWindow->show();
205 updateCommandStatus();
210 emit applicationStarted();
213 void XGUI_Workshop::activateModule()
215 myModule->activateSelectionFilters();
217 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
218 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
219 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
220 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
222 myActionsMgr->update();
226 void XGUI_Workshop::deactivateModule()
228 myModule->deactivateSelectionFilters();
230 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
231 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
232 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
233 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
236 //******************************************************
237 void XGUI_Workshop::initMenu()
239 myContextMenuMgr->createActions();
241 if (isSalomeMode()) {
242 // Create only Undo, Redo commands
243 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
244 tr("Undo last command"),
245 QIcon(":pictures/undo.png"),
246 QKeySequence::Undo, false, "MEN_DESK_EDIT");
247 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
248 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
250 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
251 QIcon(":pictures/redo.png"), QKeySequence::Redo,
252 false, "MEN_DESK_EDIT");
253 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
254 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
256 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
257 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
258 QIcon(":pictures/rebuild.png"), QKeySequence(),
259 false, "MEN_DESK_EDIT");
260 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
261 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
263 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
264 QIcon(), QKeySequence(),
265 false, "MEN_DESK_FILE");
266 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
268 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
269 QIcon(), QKeySequence(),
270 false, "MEN_DESK_FILE");
271 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
272 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
276 // File commands group
277 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
279 AppElements_Command* aCommand;
281 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
282 QIcon(":pictures/save.png"), QKeySequence::Save);
283 aCommand->connectTo(this, SLOT(onSave()));
284 //aCommand->disable();
286 QString aUndoId = "UNDO_CMD";
287 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
288 QIcon(":pictures/undo.png"), QKeySequence::Undo);
289 aCommand->connectTo(this, SLOT(onUndo()));
290 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
291 addHistoryMenu(aUndoButton,
292 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
295 QString aRedoId = "REDO_CMD";
296 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
297 QIcon(":pictures/redo.png"), QKeySequence::Redo);
298 aCommand->connectTo(this, SLOT(onRedo()));
299 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
300 addHistoryMenu(aRedoButton,
301 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
304 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
305 QIcon(":pictures/rebuild.png"), QKeySequence());
306 aCommand->connectTo(this, SLOT(onRebuild()));
308 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
309 QIcon(":pictures/save.png"), QKeySequence());
310 aCommand->connectTo(this, SLOT(onSaveAs()));
311 //aCommand->disable();
313 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
314 QIcon(":pictures/open.png"), QKeySequence::Open);
315 aCommand->connectTo(this, SLOT(onOpen()));
317 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
318 // QIcon(":pictures/new.png"), QKeySequence::New);
319 //aCommand->connectTo(this, SLOT(onNew()));
321 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
322 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
323 aCommand->connectTo(this, SLOT(onPreferences()));
325 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
326 QIcon(":pictures/close.png"), QKeySequence::Close);
327 aCommand->connectTo(this, SLOT(onExit()));
328 //FIXME: SBH's test action. Can be used for some GUI tests.
330 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
331 // QIcon(":pictures/close.png"), QKeySequence(), true);
332 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
336 //******************************************************
337 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
339 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
340 return aMenuBar->addWorkbench(theName);
343 //******************************************************
344 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
346 if (QApplication::instance()->thread() != QThread::currentThread()) {
348 std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
350 SessionPtr aMgr = ModelAPI_Session::get();
351 PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
352 QApplication::postEvent(this, aPostponeEvent);
356 //A message to start feature creation received.
357 if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
358 std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
359 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
360 if (!aFeatureMsg->isInternal()) {
361 addFeature(aFeatureMsg);
364 // Process creation of Part
365 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
366 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
367 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
368 onFeatureCreatedMsg(aUpdMsg);
370 if (mySalomeConnector)
371 mySalomeConnector->createPreferences();
372 myUpdatePrefs = false;
375 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
376 myUpdatePrefs = true;
379 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
380 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
381 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
382 onFeatureRedisplayMsg(aUpdMsg);
384 //Update property panel on corresponding message. If there is no current operation (no
385 //property panel), or received message has different feature to the current - do nothing.
386 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
387 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
388 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
389 onFeatureUpdatedMsg(anUpdateMsg);
390 } else if (theMessage->eventID() == Events_LongOp::eventID()) {
391 if (Events_LongOp::isPerformed()) {
392 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
394 QApplication::restoreOverrideCursor();
397 //An operation passed by message. Start it, process and commit.
398 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
399 std::shared_ptr<Config_PointerMessage> aPartSetMsg =
400 std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
401 //myPropertyPanel->cleanContent();
402 ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
404 if (myOperationMgr->startOperation(anOperation)) {
405 myPropertyPanel->updateContentWidget(anOperation->feature());
406 if (!anOperation->getDescription()->hasXmlRepresentation()) {
407 if (anOperation->commit())
408 updateCommandStatus();
412 else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
413 std::shared_ptr<Config_SelectionFilterMessage> aMsg =
414 std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
416 ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
417 if (!aMsg->attributeId().empty()) {
418 aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
422 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
423 // the viewer's update context will not happens until viewer updated is emitted
424 myDisplayer->enableUpdateViewer(false);
425 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
426 // the viewer's update context is unblocked, the viewer's update works
427 myDisplayer->enableUpdateViewer(true);
428 myDisplayer->updateViewer();
430 //Show error dialog if error message received.
431 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
433 emit errorOccurred(QString::fromLatin1(anAppError->description()));
437 if (!isSalomeMode()) {
438 SessionPtr aMgr = ModelAPI_Session::get();
439 if (aMgr->isModified() != myMainWindow->isModifiedState())
440 myMainWindow->setModifiedState(aMgr->isModified());
444 //******************************************************
445 QMainWindow* XGUI_Workshop::desktop() const
447 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
450 //******************************************************
451 void XGUI_Workshop::onStartWaiting()
453 if (Events_LongOp::isPerformed()) {
454 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
458 //******************************************************
459 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
461 std::set<ObjectPtr> aFeatures = theMsg->objects();
462 if (myOperationMgr->hasOperation()) {
463 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
464 std::set<ObjectPtr>::const_iterator aIt;
465 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
466 ObjectPtr aNewFeature = (*aIt);
467 if (aNewFeature == aCurrentFeature) {
468 myPropertyPanel->updateContentWidget(aCurrentFeature);
473 myOperationMgr->onValidateOperation();
474 //if (myObjectBrowser)
475 // myObjectBrowser->processEvent(theMsg);
478 //******************************************************
479 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
481 std::set<ObjectPtr> aObjects = theMsg->objects();
482 std::set<ObjectPtr>::const_iterator aIt;
484 #ifdef DEBUG_FEATURE_REDISPLAY
486 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
487 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
489 QString anInfoStr = anInfo.join(", ");
490 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
493 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
494 ObjectPtr aObj = (*aIt);
496 // Hide the object if it is invalid or concealed one
497 bool aHide = !aObj->data() || !aObj->data()->isValid() ||
498 aObj->isDisabled() || (!aObj->isDisplayed());
499 if (!aHide) { // check that this is not hidden result
500 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
501 aHide = aRes && aRes->isConcealed();
504 myDisplayer->erase(aObj, false);
506 // Redisplay the visible object or the object of the current operation
507 bool isVisibleObject = myDisplayer->isVisible(aObj);
508 #ifdef DEBUG_FEATURE_REDISPLAY
509 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
510 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
513 if (isVisibleObject) { // redisplay visible object
514 //displayObject(aObj); // In order to update presentation
515 // in order to avoid the check whether the object can be redisplayed, the exact method
516 // of redisplay is called. This modification is made in order to have the line is updated
517 // by creation of a horizontal constraint on the line by preselection
518 myDisplayer->redisplay(aObj, false);
519 // Deactivate object of current operation from selection
520 deactivateActiveObject(aObj, false);
521 } else { // display object if the current operation has it
522 if (displayObject(aObj)) {
523 // Deactivate object of current operation from selection
524 deactivateActiveObject(aObj, false);
529 myDisplayer->updateViewer();
532 //******************************************************
533 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
535 if (!myModule->canActivateSelection(theObject)) {
536 if (myDisplayer->isActive(theObject))
537 myDisplayer->deactivate(theObject, theUpdateViewer);
541 //******************************************************
542 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
544 std::set<ObjectPtr> aObjects = theMsg->objects();
545 std::set<ObjectPtr>::const_iterator aIt;
546 #ifdef DEBUG_FEATURE_CREATED
548 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
549 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
551 QString anInfoStr = anInfo.join(", ");
552 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
555 //bool aHasPart = false;
556 bool isDisplayed = false;
557 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
558 ObjectPtr anObject = *aIt;
559 // the validity of the data should be checked here in order to avoid display of the objects,
560 // which were created, then deleted, but flush for the creation event happens after that
561 // we should not display disabled objects
562 bool aHide = !anObject->data()->isValid() ||
563 anObject->isDisabled() ||
564 !anObject->isDisplayed();
566 // setDisplayed has to be called in order to synchronize internal state of the object
567 // with list of displayed objects
568 if (myModule->canDisplayObject(anObject)) {
569 anObject->setDisplayed(true);
570 isDisplayed = displayObject(*aIt);
572 anObject->setDisplayed(false);
575 //if (myObjectBrowser)
576 // myObjectBrowser->processEvent(theMsg);
578 myDisplayer->updateViewer();
579 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
580 // activateLastPart();
584 //******************************************************
585 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
587 setNestedFeatures(theOperation);
589 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
590 connectWithOperation(theOperation);
591 setPropertyPanel(theOperation);
593 updateCommandStatus();
595 myModule->onOperationStarted(theOperation);
597 // the objects of the current operation should be deactivated
598 QObjectPtrList anObjects;
599 FeaturePtr aFeature = theOperation->feature();
600 anObjects.append(aFeature);
601 std::list<ResultPtr> aResults = aFeature->results();
602 std::list<ResultPtr>::const_iterator aIt;
603 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
604 anObjects.append(*aIt);
606 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
607 for (; anIt != aLast; anIt++)
608 deactivateActiveObject(*anIt, false);
609 if (anObjects.size() > 0)
610 myDisplayer->updateViewer();
613 //******************************************************
614 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
616 setNestedFeatures(theOperation);
618 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
619 // connectWithOperation(theOperation); already connected
620 setPropertyPanel(theOperation);
622 updateCommandStatus();
624 myModule->onOperationResumed(theOperation);
628 //******************************************************
629 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
631 ModuleBase_ISelection* aSel = mySelector->selection();
632 QObjectPtrList aObj = aSel->selectedPresentations();
633 //!< No need for property panel
634 updateCommandStatus();
636 myPropertyPanel->cleanContent();
638 myModule->onOperationStopped(theOperation);
640 // the deactivated objects of the current operation should be activated back.
641 // They were deactivated on operation start or an object redisplay
642 QObjectPtrList anObjects;
643 FeaturePtr aFeature = theOperation->feature();
644 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
645 anObjects.append(aFeature);
646 std::list<ResultPtr> aResults = aFeature->results();
647 std::list<ResultPtr>::const_iterator aIt;
648 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
649 ResultPtr anObject = *aIt;
650 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
651 anObjects.append(anObject);
655 module()->activeSelectionModes(aModes);
656 myDisplayer->activateObjects(aModes, anObjects);
660 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
662 myModule->onOperationCommitted(theOperation);
665 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
667 myModule->onOperationAborted(theOperation);
670 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
672 if (this->isSalomeMode())
673 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
675 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
678 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
681 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
682 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
685 myPropertyPanel->cleanContent();
686 aFactory.createWidget(myPropertyPanel->contentWidget());
688 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
689 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
690 bool isStoreValue = !theOperation->isEditOperation() &&
691 !aWidget->getDefaultValue().empty() &&
692 !aWidget->isComputedDefault();
693 aWidget->setFeature(theOperation->feature(), isStoreValue);
694 aWidget->enableFocusProcessing();
697 myPropertyPanel->setModelWidgets(aWidgets);
698 theOperation->setPropertyPanel(myPropertyPanel);
700 myModule->propertyPanelDefined(theOperation);
702 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
705 bool XGUI_Workshop::event(QEvent * theEvent)
707 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
709 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
710 processEvent(aEventPtr);
719 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
723 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
727 ActionInfo aFeatureInfo;
728 aFeatureInfo.initFrom(theMessage);
730 QString aWchName = QString::fromStdString(theMessage->workbenchId());
731 QStringList aNestedFeatures =
732 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
733 QString aDocKind = QString::fromStdString(theMessage->documentKind());
734 QList<QAction*> aNestedActList;
735 bool isColumnButton = !aNestedFeatures.isEmpty();
736 if (isColumnButton) {
737 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
738 if (aNestedActions.contains("accept")) {
739 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
740 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
741 aNestedActList << anAction;
743 if (aNestedActions.contains("abort")) {
744 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
745 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
746 aNestedActList << anAction;
750 if (isSalomeMode()) {
752 if (isColumnButton) {
753 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
755 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
757 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
758 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
760 myActionsMgr->addCommand(aAction);
761 myModule->actionCreated(aAction);
763 //Find or create Workbench
764 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
765 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
767 aPage = addWorkbench(aWchName);
769 //Find or create Group
770 QString aGroupName = QString::fromStdString(theMessage->groupId());
771 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
773 aGroup = aPage->addGroup(aGroupName);
775 // Check if hotkey sequence is already defined:
776 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
777 if(aHotKey != aFeatureInfo.shortcut) {
778 aFeatureInfo.shortcut = aHotKey;
781 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
784 // Enrich created button with accept/abort buttons if necessary
785 AppElements_Button* aButton = aCommand->button();
786 if (aButton->isColumnButton()) {
787 aButton->setAdditionalButtons(aNestedActList);
789 myActionsMgr->addCommand(aCommand);
790 myModule->actionCreated(aCommand);
795 * Makes a signal/slot connections between Property Panel
796 * and given operation. The given operation becomes a
797 * current operation and previous operation if exists
799 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
801 QAction* aCommand = 0;
802 if (isSalomeMode()) {
803 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
805 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
806 FeaturePtr aFeature = theOperation->feature();
808 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
810 //Abort operation on uncheck the command
812 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
817 * Saves document with given name.
819 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
821 QApplication::restoreOverrideCursor();
822 SessionPtr aMgr = ModelAPI_Session::get();
823 aMgr->save(theName.toLatin1().constData(), theFileNames);
824 QApplication::restoreOverrideCursor();
827 bool XGUI_Workshop::isActiveOperationAborted()
829 return myOperationMgr->abortAllOperations();
832 //******************************************************
833 void XGUI_Workshop::onExit()
835 SessionPtr aMgr = ModelAPI_Session::get();
836 if (aMgr->isModified()) {
837 int anAnswer = QMessageBox::question(
838 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
839 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
840 if (anAnswer == QMessageBox::Save) {
841 bool saved = onSave();
845 } else if (anAnswer == QMessageBox::Cancel) {
852 //******************************************************
853 void XGUI_Workshop::onNew()
855 QApplication::setOverrideCursor(Qt::WaitCursor);
856 if (objectBrowser() == 0) {
858 mySelector->connectViewers();
860 myViewerProxy->connectToViewer();
862 if (!isSalomeMode()) {
863 myMainWindow->showPythonConsole();
864 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
865 aWnd->showMaximized();
866 updateCommandStatus();
868 myContextMenuMgr->connectViewer();
869 QApplication::restoreOverrideCursor();
872 //******************************************************
873 void XGUI_Workshop::onOpen()
875 if(!isActiveOperationAborted())
877 //save current file before close if modified
878 SessionPtr aSession = ModelAPI_Session::get();
879 if (aSession->isModified()) {
880 //TODO(sbh): re-launch the app?
881 int anAnswer = QMessageBox::question(
882 myMainWindow, tr("Save current file"),
883 tr("The document is modified, save before opening another?"),
884 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
885 if (anAnswer == QMessageBox::Save) {
887 } else if (anAnswer == QMessageBox::Cancel) {
893 //show file dialog, check if readable and open
894 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow(), tr("Select folder"));
895 if (myCurrentDir.isEmpty())
897 QFileInfo aFileInfo(myCurrentDir);
898 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
899 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
903 QApplication::setOverrideCursor(Qt::WaitCursor);
904 myIsLoadingData = true;
905 aSession->closeAll();
906 aSession->load(myCurrentDir.toLatin1().constData());
907 myObjectBrowser->rebuildDataTree();
908 //displayAllResults();
909 updateCommandStatus();
910 myIsLoadingData = false;
911 QApplication::restoreOverrideCursor();
914 //******************************************************
915 bool XGUI_Workshop::onSave()
917 if(!isActiveOperationAborted())
919 if (myCurrentDir.isEmpty()) {
922 std::list<std::string> aFiles;
923 saveDocument(myCurrentDir, aFiles);
924 updateCommandStatus();
926 myMainWindow->setModifiedState(false);
930 //******************************************************
931 bool XGUI_Workshop::onSaveAs()
933 if(!isActiveOperationAborted())
935 QFileDialog dialog(mainWindow());
936 dialog.setWindowTitle(tr("Select folder to save files..."));
937 dialog.setFileMode(QFileDialog::Directory);
938 dialog.setFilter(tr("Folders (*)"));
939 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
940 dialog.setViewMode(QFileDialog::Detail);
942 if (!dialog.exec()) {
946 QString aTempDir = dialog.selectedFiles().first();
948 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
949 int answer = QMessageBox::question(
951 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
953 tr("The folder already contains some files, save anyway?"),
954 QMessageBox::Save | QMessageBox::Cancel);
955 if (answer == QMessageBox::Cancel) {
959 myCurrentDir = aTempDir;
960 if (!isSalomeMode()) {
961 myMainWindow->setCurrentDir(myCurrentDir, false);
962 myMainWindow->setModifiedState(false);
967 //******************************************************
968 void XGUI_Workshop::onUndo(int theTimes)
970 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
971 SessionPtr aMgr = ModelAPI_Session::get();
972 if (aMgr->isOperation())
973 operationMgr()->onAbortOperation();
974 for (int i = 0; i < theTimes; ++i) {
977 updateCommandStatus();
980 //******************************************************
981 void XGUI_Workshop::onRedo(int theTimes)
983 // the viewer update should be blocked in order to avoid the features blinking. For the created
984 // feature a results are created, the flush of the created signal caused the viewer redisplay for
985 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
986 // redo of all possible objects happens
987 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
989 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
990 SessionPtr aMgr = ModelAPI_Session::get();
991 if (aMgr->isOperation())
992 operationMgr()->onAbortOperation();
993 for (int i = 0; i < theTimes; ++i) {
996 updateCommandStatus();
998 // unblock the viewer update functionality and make update on purpose
999 myDisplayer->enableUpdateViewer(isUpdateEnabled);
1000 myDisplayer->updateViewer();
1003 //******************************************************
1004 void XGUI_Workshop::onRebuild()
1006 SessionPtr aMgr = ModelAPI_Session::get();
1007 bool aWasOperation = aMgr->isOperation(); // keep this value
1008 if (!aWasOperation) {
1009 aMgr->startOperation("Rebuild");
1011 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1012 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1013 new Events_Message(aRebuildEvent, this)));
1014 if (!aWasOperation) {
1015 aMgr->finishOperation();
1017 updateCommandStatus();
1020 //******************************************************
1021 void XGUI_Workshop::onPreferences()
1023 ModuleBase_Prefs aModif;
1024 ModuleBase_Preferences::editPreferences(aModif);
1025 if (aModif.size() > 0) {
1027 foreach (ModuleBase_Pref aPref, aModif)
1029 aSection = aPref.first;
1030 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1031 if (!isSalomeMode())
1032 myMainWindow->viewer()->updateFromResources();
1033 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1034 if (!isSalomeMode())
1035 myMainWindow->menuObject()->updateFromResources();
1041 //******************************************************
1042 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1044 QString libName = QString::fromStdString(library(theModule.toStdString()));
1045 if (libName.isEmpty()) {
1046 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1051 CREATE_FUNC crtInst = 0;
1054 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1058 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1059 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1060 QString aMsg((char*) &lpMsgBuf);
1061 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1062 ::LocalFree(lpMsgBuf);
1064 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1068 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1069 | FORMAT_MESSAGE_IGNORE_INSERTS,
1070 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1071 QString aMsg((char*) &lpMsgBuf);
1072 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1073 ::LocalFree(lpMsgBuf);
1077 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1079 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1081 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1083 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1088 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1090 if (!err.isEmpty()) {
1092 Events_Error::send(err.toStdString());
1094 qWarning(qPrintable(err));
1100 //******************************************************
1101 bool XGUI_Workshop::createModule()
1103 Config_ModuleReader aModuleReader;
1104 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1105 myModule = loadModule(moduleName);
1109 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1110 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1111 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1112 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1114 myModule->createFeatures();
1115 //myActionsMgr->update();
1119 //******************************************************
1120 void XGUI_Workshop::updateCommandStatus()
1122 QList<QAction*> aCommands;
1123 if (isSalomeMode()) { // update commands in SALOME mode
1124 aCommands = salomeConnector()->commandList();
1126 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1127 foreach (AppElements_Command* aCmd, aMenuBar->features())
1128 aCommands.append(aCmd);
1130 SessionPtr aMgr = ModelAPI_Session::get();
1131 if (aMgr->hasModuleDocument()) {
1132 foreach(QAction* aCmd, aCommands) {
1133 QString aId = aCmd->data().toString();
1134 if (aId == "UNDO_CMD")
1135 aCmd->setEnabled(myModule->canUndo());
1136 else if (aId == "REDO_CMD")
1137 aCmd->setEnabled(myModule->canRedo());
1139 // Enable all commands
1140 aCmd->setEnabled(true);
1144 foreach(QAction* aCmd, aCommands) {
1145 QString aId = aCmd->data().toString();
1146 if (aId == "NEW_CMD")
1147 aCmd->setEnabled(true);
1148 else if (aId == "EXIT_CMD")
1149 aCmd->setEnabled(true);
1151 aCmd->setEnabled(false);
1154 myActionsMgr->update();
1155 emit commandStatusUpdated();
1158 void XGUI_Workshop::updateHistory()
1160 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1161 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1162 emit updateUndoHistory(aUndoRes);
1164 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1165 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1166 emit updateRedoHistory(aRedoRes);
1169 //******************************************************
1170 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1172 QDockWidget* aObjDock = new QDockWidget(theParent);
1173 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1174 aObjDock->setWindowTitle(tr("Object browser"));
1175 aObjDock->setStyleSheet(
1176 "::title { position: relative; padding-left: 5px; text-align: left center }");
1177 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1178 myObjectBrowser->setDataModel(myModule->dataModel());
1179 myModule->customizeObjectBrowser(myObjectBrowser);
1180 aObjDock->setWidget(myObjectBrowser);
1182 myContextMenuMgr->connectObjectBrowser();
1186 //******************************************************
1188 * Creates dock widgets, places them in corresponding area
1189 * and tabifies if necessary.
1191 void XGUI_Workshop::createDockWidgets()
1193 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1194 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1195 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1196 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1197 myPropertyPanel->setupActions(myActionsMgr);
1198 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1199 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1200 hidePropertyPanel(); ///<! Invisible by default
1201 hideObjectBrowser();
1202 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1203 myPropertyPanel->installEventFilter(myOperationMgr);
1205 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1206 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1207 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1208 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1209 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1210 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1211 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1212 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1213 aOkAct, SLOT(setEnabled(bool)));
1214 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1215 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1216 aAcceptAllAct, SLOT(setEnabled(bool)));
1220 //******************************************************
1221 void XGUI_Workshop::showPropertyPanel()
1223 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1224 ///<! Restore ability to close panel from the window's menu
1225 aViewAct->setEnabled(true);
1226 myPropertyPanel->show();
1227 myPropertyPanel->raise();
1230 //******************************************************
1231 void XGUI_Workshop::hidePropertyPanel()
1233 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1234 ///<! Do not allow to show empty property panel
1235 aViewAct->setEnabled(false);
1236 myPropertyPanel->hide();
1239 //******************************************************
1240 void XGUI_Workshop::showObjectBrowser()
1242 myObjectBrowser->parentWidget()->show();
1245 //******************************************************
1246 void XGUI_Workshop::hideObjectBrowser()
1248 myObjectBrowser->parentWidget()->hide();
1251 //******************************************************
1252 //void XGUI_Workshop::onFeatureTriggered()
1254 // QAction* aCmd = dynamic_cast<QAction*>(sender());
1256 // QString aId = salomeConnector()->commandId(aCmd);
1257 // if (!aId.isNull())
1258 // myModule->launchOperation(aId);
1262 //******************************************************
1263 void XGUI_Workshop::salomeViewerSelectionChanged()
1265 emit salomeViewerSelection();
1268 //**************************************************************
1269 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1271 return mySalomeConnector->viewer();
1274 //**************************************************************
1275 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1277 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1278 if (theId == "DELETE_CMD")
1280 else if (theId == "COLOR_CMD")
1281 changeColor(aObjects);
1282 else if (theId == "SHOW_CMD")
1283 showObjects(aObjects, true);
1284 else if (theId == "HIDE_CMD")
1285 showObjects(aObjects, false);
1286 else if (theId == "SHOW_ONLY_CMD")
1287 showOnlyObjects(aObjects);
1288 else if (theId == "SHADING_CMD")
1289 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1290 else if (theId == "WIREFRAME_CMD")
1291 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1292 else if (theId == "HIDEALL_CMD") {
1293 QObjectPtrList aList = myDisplayer->displayedObjects();
1294 foreach (ObjectPtr aObj, aList)
1295 aObj->setDisplayed(false);
1296 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1300 //**************************************************************
1301 void XGUI_Workshop::deleteObjects()
1303 ModuleBase_IModule* aModule = module();
1304 // 1. allow the module to delete objects, do nothing if it has succeed
1305 if (aModule->deleteObjects()) {
1306 updateCommandStatus();
1310 if (!isActiveOperationAborted())
1312 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1313 bool hasResult = false;
1314 bool hasFeature = false;
1315 bool hasParameter = false;
1316 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1317 if (!(hasFeature || hasParameter))
1320 // 1. start operation
1321 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1322 aDescription += tr(" %1");
1323 QStringList aObjectNames;
1324 foreach (ObjectPtr aObj, anObjects) {
1325 if (!aObj->data()->isValid())
1327 aObjectNames << QString::fromStdString(aObj->data()->name());
1329 aDescription = aDescription.arg(aObjectNames.join(", "));
1331 SessionPtr aMgr = ModelAPI_Session::get();
1332 aMgr->startOperation(aDescription.toStdString());
1333 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1334 // this is performed in the RemoveFeature of Part object.
1335 /*foreach (ObjectPtr aObj, anObjects)
1337 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1339 DocumentPtr aDoc = aObj->document();
1340 if (aDoc == aMgr->activeDocument()) {
1345 // 3. delete objects
1346 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1347 std::set<FeaturePtr> anIgnoredFeatures;
1348 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1349 myDisplayer->updateViewer();
1350 aMgr->finishOperation();
1351 updateCommandStatus();
1354 aMgr->abortOperation();
1358 //**************************************************************
1359 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1360 std::set<FeaturePtr> theIgnoredFeatures,
1362 const bool theAskAboutDeleteReferences)
1364 // 1. find all referenced features
1365 std::set<FeaturePtr> aRefFeatures;
1366 foreach (ObjectPtr aDeletedObj, theList) {
1367 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1368 if (aDeletedFeature.get() != NULL) {
1369 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1370 // 1.1 find references in the current document
1371 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1372 // 1.2 find references in all documents if the document of the feature is
1373 // "PartSet". Features of this document can be used in all other documents
1374 SessionPtr aMgr = ModelAPI_Session::get();
1375 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1376 if (aDeletedFeatureDoc == aModuleDoc) {
1377 // the deleted feature and results of the feature should be found in references
1378 std::list<ObjectPtr> aDeletedObjects;
1379 aDeletedObjects.push_back(aDeletedFeature);
1380 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1381 const ResultsList& aDeletedResults = aDeletedFeature->results();
1382 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1383 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1384 ResultPtr aRes = *aRIter;
1386 aDeletedObjects.push_back(aRes);
1388 // get all opened documents; found features in the documents;
1389 // get a list of objects where a feature refers;
1390 // search in these objects the deleted objects.
1391 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1392 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1393 aLast = anOpenedDocs.end();
1394 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1395 for (; anIt != aLast; anIt++) {
1396 DocumentPtr aDocument = *anIt;
1397 if (aDocument == aDeletedFeatureDoc)
1398 continue; // this document has been already processed in 1.1
1400 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1401 for (int aId = 0; aId < aFeaturesCount; aId++) {
1402 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1403 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1404 if (!aFeature.get())
1408 aFeature->data()->referencesToObjects(aRefs);
1409 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1410 bool aHasReferenceToDeleted = false;
1411 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1412 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1413 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1414 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1415 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1416 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1420 if (aHasReferenceToDeleted)
1421 aRefFeatures.insert(aFeature);
1427 // 2. warn about the references remove, break the delete operation if the user chose it
1428 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1429 QStringList aRefNames;
1430 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1431 aLast = aRefFeatures.end();
1432 for (; anIt != aLast; anIt++) {
1433 aRefNames.append((*anIt)->name().c_str());
1435 QString aNames = aRefNames.join(", ");
1437 QMessageBox::StandardButton aRes = QMessageBox::warning(
1438 theParent, tr("Delete features"),
1439 QString(tr("Selected features are used in the following features: %1.\
1440 These features will be deleted also. Would you like to continue?")).arg(aNames),
1441 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1442 if (aRes != QMessageBox::Yes)
1446 // 3. remove referenced features
1447 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1448 aLast = aRefFeatures.end();
1452 for (; anIt != aLast; anIt++) {
1453 FeaturePtr aFeature = (*anIt);
1454 DocumentPtr aDoc = aFeature->document();
1455 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1456 aDoc->removeFeature(aFeature);
1458 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1463 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1467 // 4. remove the parameter features
1468 foreach (ObjectPtr aObj, theList) {
1469 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1470 if (aResult.get() != NULL) { // results could not be removed,
1471 // they are removed by a corresponded feature remove
1474 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1476 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1477 // part features are removed in the PartSet module. This condition should be moved there
1478 if (aFeature->getKind() == "Part")
1481 DocumentPtr aDoc = aObj->document();
1482 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1483 aDoc->removeFeature(aFeature);
1485 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1486 anInfo.append(anInfoStr);
1487 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1493 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1498 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1500 bool isFoundResultType = false;
1501 foreach(ObjectPtr anObj, theObjects)
1503 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1504 if (aResult.get() == NULL)
1507 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1508 if (isFoundResultType)
1511 return isFoundResultType;
1514 //**************************************************************
1515 bool XGUI_Workshop::canChangeColor() const
1517 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1519 std::set<std::string> aTypes;
1520 aTypes.insert(ModelAPI_ResultGroup::group());
1521 aTypes.insert(ModelAPI_ResultConstruction::group());
1522 aTypes.insert(ModelAPI_ResultBody::group());
1523 aTypes.insert(ModelAPI_ResultPart::group());
1525 return hasResults(aObjects, aTypes);
1528 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1530 if (!theResult.get())
1533 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1534 if (aColorAttr.get() != NULL) {
1535 if (!aColorAttr->size()) {
1536 aColorAttr->setSize(3);
1538 aColorAttr->setValue(0, theColor[0]);
1539 aColorAttr->setValue(1, theColor[1]);
1540 aColorAttr->setValue(2, theColor[2]);
1544 //**************************************************************
1545 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1547 AttributeIntArrayPtr aColorAttr;
1548 // 1. find the current color of the object. This is a color of AIS presentation
1549 // The objects are iterated until a first valid color is found
1550 std::vector<int> aColor;
1551 foreach(ObjectPtr anObject, theObjects) {
1552 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1553 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1554 DocumentPtr aPartDoc = aPart->partDoc();
1555 // the document should be checked on null, because in opened document if the part
1556 // has not been activated yet, the part document is empty
1557 if (!aPartDoc.get()) {
1558 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1561 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1562 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1563 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1565 XGUI_CustomPrs::getResultColor(aBody, aColor);
1571 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1573 XGUI_CustomPrs::getResultColor(aResult, aColor);
1575 // TODO: remove the obtaining a color from the AIS object
1576 // this does not happen never because:
1577 // 1. The color can be changed only on results
1578 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1579 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1580 if (anAISObj.get()) {
1582 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1586 if (!aColor.empty())
1589 if (aColor.size() != 3)
1592 // 2. show the dialog to change the value
1593 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1594 aDlg->setColor(aColor);
1595 aDlg->move(QCursor::pos());
1596 bool isDone = aDlg->exec() == QDialog::Accepted;
1600 bool isRandomColor = aDlg->isRandomColor();
1602 // 3. abort the previous operation and start a new one
1603 SessionPtr aMgr = ModelAPI_Session::get();
1604 bool aWasOperation = aMgr->isOperation(); // keep this value
1605 if (!aWasOperation) {
1606 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1607 aMgr->startOperation(aDescription.toStdString());
1610 // 4. set the value to all results
1611 foreach(ObjectPtr anObj, theObjects) {
1612 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1613 if (aResult.get() != NULL) {
1614 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1615 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1616 DocumentPtr aPartDoc = aPart->partDoc();
1617 // the document should be checked on null, because in opened document if the part
1618 // has not been activated yet, the part document is empty
1619 if (aPartDoc.get()) {
1620 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1621 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1622 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1623 std::vector<int> aColorResult = aDlg->getColor();
1624 setColor(aBody, aColorResult);
1629 std::vector<int> aColorResult = aDlg->getColor();
1630 setColor(aResult, aColorResult);
1635 aMgr->finishOperation();
1636 updateCommandStatus();
1639 //**************************************************************
1640 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1641 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1642 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1644 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1646 foreach (ObjectPtr aObj, theList) {
1648 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1650 DocumentPtr aDoc = aPartRes->partDoc();
1651 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1652 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1653 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1656 aObj->setDisplayed(isVisible);
1659 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1662 //**************************************************************
1663 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1665 // Hide all displayed objects
1666 QObjectPtrList aList = myDisplayer->displayedObjects();
1667 foreach (ObjectPtr aObj, aList)
1668 aObj->setDisplayed(false);
1670 // Show only objects from the list
1671 foreach (ObjectPtr aObj, theList) {
1673 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1675 DocumentPtr aDoc = aPartRes->partDoc();
1676 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1677 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1678 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1681 aObj->setDisplayed(true);
1684 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1689 //**************************************************************
1690 void XGUI_Workshop::registerValidators() const
1692 SessionPtr aMgr = ModelAPI_Session::get();
1693 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1696 //**************************************************************
1697 /*void XGUI_Workshop::displayAllResults()
1699 SessionPtr aMgr = ModelAPI_Session::get();
1700 DocumentPtr aRootDoc = aMgr->moduleDocument();
1701 displayDocumentResults(aRootDoc);
1702 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1703 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1704 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1705 displayDocumentResults(aPart->partDoc());
1707 myDisplayer->updateViewer();
1710 //**************************************************************
1711 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1715 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1716 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1719 //**************************************************************
1720 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1722 for (int i = 0; i < theDoc->size(theGroup); i++)
1723 theDoc->object(theGroup, i)->setDisplayed(true);
1724 //displayObject(theDoc->object(theGroup, i));
1725 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1728 //**************************************************************
1729 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1731 foreach(ObjectPtr aObj, theList) {
1732 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1734 if (theList.size() > 0)
1735 myDisplayer->updateViewer();
1738 //**************************************************************
1739 void XGUI_Workshop::closeDocument()
1741 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1742 while (anOperation) {
1743 anOperation->abort();
1744 anOperation = operationMgr()->currentOperation();
1746 myDisplayer->closeLocalContexts();
1747 myDisplayer->eraseAll();
1748 objectBrowser()->clearContent();
1750 SessionPtr aMgr = ModelAPI_Session::get();
1754 //**************************************************************
1755 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1757 if (!myModule->canDisplayObject(theObj))
1760 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1761 if (aBody.get() != NULL) {
1762 int aNb = myDisplayer->objectsCount();
1763 myDisplayer->display(theObj, false);
1766 } else if (!(myIsLoadingData || myPartActivating))
1767 myDisplayer->display(theObj, false);
1772 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1774 XGUI_HistoryMenu* aMenu = NULL;
1775 if (isSalomeMode()) {
1776 QAction* anAction = qobject_cast<QAction*>(theObject);
1779 aMenu = new XGUI_HistoryMenu(anAction);
1781 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1782 aMenu = new XGUI_HistoryMenu(aButton);
1784 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1785 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1788 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1790 QList<ActionInfo> aResult;
1791 std::list<std::string>::const_iterator it = theList.cbegin();
1792 for (; it != theList.cend(); it++) {
1793 QString anId = QString::fromStdString(*it);
1794 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1796 anId.chop(ModuleBase_Operation::EditSuffix().size());
1799 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1800 if (aContextMenuAct) {
1801 anInfo.initFrom(aContextMenuAct);
1803 anInfo = myActionsMgr->actionInfoById(anId);
1806 anInfo.text = anInfo.text.prepend("Modify ");