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, 0);
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);
142 myOperationMgr->setWorkshop(moduleConnector());
144 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
145 SLOT(onOperationStarted(ModuleBase_Operation*)));
146 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
147 SLOT(onOperationResumed(ModuleBase_Operation*)));
148 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
149 SLOT(onOperationStopped(ModuleBase_Operation*)));
150 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
151 SLOT(onOperationCommitted(ModuleBase_Operation*)));
152 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
153 SLOT(onOperationAborted(ModuleBase_Operation*)));
155 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
156 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
158 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
159 // Config_Prop::Color, "225,225,225");
161 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
162 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
163 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
164 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
165 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
166 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
167 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
168 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
171 //******************************************************
172 XGUI_Workshop::~XGUI_Workshop(void)
177 //******************************************************
178 void XGUI_Workshop::startApplication()
182 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
183 Config_Prop::Directory, "");
185 //Initialize event listening
186 Events_Loop* aLoop = Events_Loop::loop();
187 aLoop->registerListener(this, Events_Error::errorID()); //!< Listening application errors.
188 aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
189 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
190 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
191 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
192 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
193 aLoop->registerListener(this, Events_LongOp::eventID());
194 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
195 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
197 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
198 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
200 registerValidators();
202 // Calling of loadCustomProps before activating module is required
203 // by Config_PropManger to restore user-defined path to plugins
204 ModuleBase_Preferences::loadCustomProps();
207 myMainWindow->show();
208 updateCommandStatus();
213 emit applicationStarted();
216 void XGUI_Workshop::activateModule()
218 myModule->activateSelectionFilters();
220 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
221 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
222 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
223 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
225 myActionsMgr->update();
229 void XGUI_Workshop::deactivateModule()
231 myModule->deactivateSelectionFilters();
233 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
234 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
235 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
236 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
239 //******************************************************
240 void XGUI_Workshop::initMenu()
242 myContextMenuMgr->createActions();
244 if (isSalomeMode()) {
245 // Create only Undo, Redo commands
246 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
247 tr("Undo last command"),
248 QIcon(":pictures/undo.png"),
249 QKeySequence::Undo, false, "MEN_DESK_EDIT");
250 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
251 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
253 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
254 QIcon(":pictures/redo.png"), QKeySequence::Redo,
255 false, "MEN_DESK_EDIT");
256 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
257 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
259 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
260 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
261 QIcon(":pictures/rebuild.png"), QKeySequence(),
262 false, "MEN_DESK_EDIT");
263 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
264 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
266 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
267 QIcon(), QKeySequence(),
268 false, "MEN_DESK_FILE");
269 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
271 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
272 QIcon(), QKeySequence(),
273 false, "MEN_DESK_FILE");
274 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
275 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
279 // File commands group
280 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
282 AppElements_Command* aCommand;
284 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
285 QIcon(":pictures/save.png"), QKeySequence::Save);
286 aCommand->connectTo(this, SLOT(onSave()));
287 //aCommand->disable();
289 QString aUndoId = "UNDO_CMD";
290 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
291 QIcon(":pictures/undo.png"), QKeySequence::Undo);
292 aCommand->connectTo(this, SLOT(onUndo()));
293 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
294 addHistoryMenu(aUndoButton,
295 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
298 QString aRedoId = "REDO_CMD";
299 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
300 QIcon(":pictures/redo.png"), QKeySequence::Redo);
301 aCommand->connectTo(this, SLOT(onRedo()));
302 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
303 addHistoryMenu(aRedoButton,
304 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
307 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
308 QIcon(":pictures/rebuild.png"), QKeySequence());
309 aCommand->connectTo(this, SLOT(onRebuild()));
311 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
312 QIcon(":pictures/save.png"), QKeySequence());
313 aCommand->connectTo(this, SLOT(onSaveAs()));
314 //aCommand->disable();
316 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
317 QIcon(":pictures/open.png"), QKeySequence::Open);
318 aCommand->connectTo(this, SLOT(onOpen()));
320 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
321 // QIcon(":pictures/new.png"), QKeySequence::New);
322 //aCommand->connectTo(this, SLOT(onNew()));
324 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
325 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
326 aCommand->connectTo(this, SLOT(onPreferences()));
328 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
329 QIcon(":pictures/close.png"), QKeySequence::Close);
330 aCommand->connectTo(this, SLOT(onExit()));
331 //FIXME: SBH's test action. Can be used for some GUI tests.
333 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
334 // QIcon(":pictures/close.png"), QKeySequence(), true);
335 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
339 //******************************************************
340 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
342 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
343 return aMenuBar->addWorkbench(theName);
346 //******************************************************
347 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
349 if (QApplication::instance()->thread() != QThread::currentThread()) {
351 std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
353 SessionPtr aMgr = ModelAPI_Session::get();
354 PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
355 QApplication::postEvent(this, aPostponeEvent);
359 //A message to start feature creation received.
360 if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
361 std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
362 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
363 if (!aFeatureMsg->isInternal()) {
364 addFeature(aFeatureMsg);
367 // Process creation of Part
368 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
369 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
370 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
371 onFeatureCreatedMsg(aUpdMsg);
373 if (mySalomeConnector)
374 mySalomeConnector->createPreferences();
375 myUpdatePrefs = false;
378 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
379 myUpdatePrefs = true;
382 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
383 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
384 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
385 onFeatureRedisplayMsg(aUpdMsg);
387 //Update property panel on corresponding message. If there is no current operation (no
388 //property panel), or received message has different feature to the current - do nothing.
389 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
390 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
391 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
392 onFeatureUpdatedMsg(anUpdateMsg);
393 } else if (theMessage->eventID() == Events_LongOp::eventID()) {
394 if (Events_LongOp::isPerformed()) {
395 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
397 QApplication::restoreOverrideCursor();
400 //An operation passed by message. Start it, process and commit.
401 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
402 std::shared_ptr<Config_PointerMessage> aPartSetMsg =
403 std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
404 //myPropertyPanel->cleanContent();
405 ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
407 if (myOperationMgr->startOperation(anOperation)) {
408 myPropertyPanel->updateContentWidget(anOperation->feature());
409 if (!anOperation->getDescription()->hasXmlRepresentation()) {
410 if (anOperation->commit())
411 updateCommandStatus();
415 else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
416 std::shared_ptr<Config_SelectionFilterMessage> aMsg =
417 std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
419 ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
420 if (!aMsg->attributeId().empty()) {
421 aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
425 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
426 // the viewer's update context will not happens until viewer updated is emitted
427 myDisplayer->enableUpdateViewer(false);
428 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
429 // the viewer's update context is unblocked, the viewer's update works
430 myDisplayer->enableUpdateViewer(true);
431 myDisplayer->updateViewer();
433 //Show error dialog if error message received.
434 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
436 emit errorOccurred(QString::fromLatin1(anAppError->description()));
440 if (!isSalomeMode()) {
441 SessionPtr aMgr = ModelAPI_Session::get();
442 if (aMgr->isModified() != myMainWindow->isModifiedState())
443 myMainWindow->setModifiedState(aMgr->isModified());
447 //******************************************************
448 QMainWindow* XGUI_Workshop::desktop() const
450 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
453 //******************************************************
454 void XGUI_Workshop::onStartWaiting()
456 if (Events_LongOp::isPerformed()) {
457 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
461 //******************************************************
462 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
464 std::set<ObjectPtr> aFeatures = theMsg->objects();
465 if (myOperationMgr->hasOperation()) {
466 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
467 std::set<ObjectPtr>::const_iterator aIt;
468 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
469 ObjectPtr aNewFeature = (*aIt);
470 if (aNewFeature == aCurrentFeature) {
471 myPropertyPanel->updateContentWidget(aCurrentFeature);
476 myOperationMgr->onValidateOperation();
477 //if (myObjectBrowser)
478 // myObjectBrowser->processEvent(theMsg);
481 //******************************************************
482 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
484 std::set<ObjectPtr> aObjects = theMsg->objects();
485 std::set<ObjectPtr>::const_iterator aIt;
487 #ifdef DEBUG_FEATURE_REDISPLAY
489 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
490 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
492 QString anInfoStr = anInfo.join(", ");
493 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
496 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
497 ObjectPtr aObj = (*aIt);
499 // Hide the object if it is invalid or concealed one
500 bool aHide = !aObj->data() || !aObj->data()->isValid() ||
501 aObj->isDisabled() || (!aObj->isDisplayed());
502 if (!aHide) { // check that this is not hidden result
503 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
504 aHide = aRes && aRes->isConcealed();
507 myDisplayer->erase(aObj, false);
509 // Redisplay the visible object or the object of the current operation
510 bool isVisibleObject = myDisplayer->isVisible(aObj);
511 #ifdef DEBUG_FEATURE_REDISPLAY
512 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
513 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
516 if (isVisibleObject) { // redisplay visible object
517 //displayObject(aObj); // In order to update presentation
518 // in order to avoid the check whether the object can be redisplayed, the exact method
519 // of redisplay is called. This modification is made in order to have the line is updated
520 // by creation of a horizontal constraint on the line by preselection
521 myDisplayer->redisplay(aObj, false);
522 // Deactivate object of current operation from selection
523 deactivateActiveObject(aObj, false);
524 } else { // display object if the current operation has it
525 if (displayObject(aObj)) {
526 // Deactivate object of current operation from selection
527 deactivateActiveObject(aObj, false);
532 myDisplayer->updateViewer();
535 //******************************************************
536 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
538 if (!myModule->canActivateSelection(theObject)) {
539 if (myDisplayer->isActive(theObject))
540 myDisplayer->deactivate(theObject, theUpdateViewer);
544 //******************************************************
545 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
547 std::set<ObjectPtr> aObjects = theMsg->objects();
548 std::set<ObjectPtr>::const_iterator aIt;
549 #ifdef DEBUG_FEATURE_CREATED
551 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
552 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
554 QString anInfoStr = anInfo.join(", ");
555 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
558 //bool aHasPart = false;
559 bool isDisplayed = false;
560 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
561 ObjectPtr anObject = *aIt;
562 // the validity of the data should be checked here in order to avoid display of the objects,
563 // which were created, then deleted, but flush for the creation event happens after that
564 // we should not display disabled objects
565 bool aHide = !anObject->data()->isValid() ||
566 anObject->isDisabled() ||
567 !anObject->isDisplayed();
569 // setDisplayed has to be called in order to synchronize internal state of the object
570 // with list of displayed objects
571 if (myModule->canDisplayObject(anObject)) {
572 anObject->setDisplayed(true);
573 isDisplayed = displayObject(*aIt);
575 anObject->setDisplayed(false);
578 //if (myObjectBrowser)
579 // myObjectBrowser->processEvent(theMsg);
581 myDisplayer->updateViewer();
582 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
583 // activateLastPart();
587 //******************************************************
588 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
590 setNestedFeatures(theOperation);
592 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
593 connectWithOperation(theOperation);
594 setPropertyPanel(theOperation);
596 updateCommandStatus();
598 myModule->onOperationStarted(theOperation);
600 // the objects of the current operation should be deactivated
601 QObjectPtrList anObjects;
602 FeaturePtr aFeature = theOperation->feature();
603 anObjects.append(aFeature);
604 std::list<ResultPtr> aResults = aFeature->results();
605 std::list<ResultPtr>::const_iterator aIt;
606 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
607 anObjects.append(*aIt);
609 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
610 for (; anIt != aLast; anIt++)
611 deactivateActiveObject(*anIt, false);
612 if (anObjects.size() > 0)
613 myDisplayer->updateViewer();
616 //******************************************************
617 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
619 setNestedFeatures(theOperation);
621 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
622 // connectWithOperation(theOperation); already connected
623 setPropertyPanel(theOperation);
625 updateCommandStatus();
627 myModule->onOperationResumed(theOperation);
631 //******************************************************
632 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
634 ModuleBase_ISelection* aSel = mySelector->selection();
635 QObjectPtrList aObj = aSel->selectedPresentations();
636 //!< No need for property panel
637 updateCommandStatus();
639 myPropertyPanel->cleanContent();
641 myModule->onOperationStopped(theOperation);
643 // the deactivated objects of the current operation should be activated back.
644 // They were deactivated on operation start or an object redisplay
645 QObjectPtrList anObjects;
646 FeaturePtr aFeature = theOperation->feature();
647 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
648 anObjects.append(aFeature);
649 std::list<ResultPtr> aResults = aFeature->results();
650 std::list<ResultPtr>::const_iterator aIt;
651 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
652 ResultPtr anObject = *aIt;
653 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
654 anObjects.append(anObject);
658 module()->activeSelectionModes(aModes);
659 myDisplayer->activateObjects(aModes, anObjects);
663 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
665 myModule->onOperationCommitted(theOperation);
668 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
670 myModule->onOperationAborted(theOperation);
673 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
675 if (this->isSalomeMode())
676 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
678 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
681 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
684 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
685 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
688 myPropertyPanel->cleanContent();
689 aFactory.createWidget(myPropertyPanel->contentWidget());
691 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
692 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
693 bool isStoreValue = !theOperation->isEditOperation() &&
694 !aWidget->getDefaultValue().empty() &&
695 !aWidget->isComputedDefault();
696 aWidget->setFeature(theOperation->feature(), isStoreValue);
697 aWidget->enableFocusProcessing();
700 myPropertyPanel->setModelWidgets(aWidgets);
701 theOperation->setPropertyPanel(myPropertyPanel);
703 myModule->propertyPanelDefined(theOperation);
705 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
708 bool XGUI_Workshop::event(QEvent * theEvent)
710 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
712 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
713 processEvent(aEventPtr);
722 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
726 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
730 ActionInfo aFeatureInfo;
731 aFeatureInfo.initFrom(theMessage);
733 QString aWchName = QString::fromStdString(theMessage->workbenchId());
734 QStringList aNestedFeatures =
735 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
736 QString aDocKind = QString::fromStdString(theMessage->documentKind());
737 QList<QAction*> aNestedActList;
738 bool isColumnButton = !aNestedFeatures.isEmpty();
739 if (isColumnButton) {
740 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
741 if (aNestedActions.contains("accept")) {
742 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
743 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
744 aNestedActList << anAction;
746 if (aNestedActions.contains("abort")) {
747 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
748 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
749 aNestedActList << anAction;
753 if (isSalomeMode()) {
755 if (isColumnButton) {
756 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
758 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
760 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
761 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
763 myActionsMgr->addCommand(aAction);
764 myModule->actionCreated(aAction);
766 //Find or create Workbench
767 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
768 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
770 aPage = addWorkbench(aWchName);
772 //Find or create Group
773 QString aGroupName = QString::fromStdString(theMessage->groupId());
774 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
776 aGroup = aPage->addGroup(aGroupName);
778 // Check if hotkey sequence is already defined:
779 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
780 if(aHotKey != aFeatureInfo.shortcut) {
781 aFeatureInfo.shortcut = aHotKey;
784 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
787 // Enrich created button with accept/abort buttons if necessary
788 AppElements_Button* aButton = aCommand->button();
789 if (aButton->isColumnButton()) {
790 aButton->setAdditionalButtons(aNestedActList);
792 myActionsMgr->addCommand(aCommand);
793 myModule->actionCreated(aCommand);
798 * Makes a signal/slot connections between Property Panel
799 * and given operation. The given operation becomes a
800 * current operation and previous operation if exists
802 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
804 QAction* aCommand = 0;
805 if (isSalomeMode()) {
806 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
808 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
809 FeaturePtr aFeature = theOperation->feature();
811 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
813 //Abort operation on uncheck the command
815 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
820 * Saves document with given name.
822 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
824 QApplication::restoreOverrideCursor();
825 SessionPtr aMgr = ModelAPI_Session::get();
826 aMgr->save(theName.toLatin1().constData(), theFileNames);
827 QApplication::restoreOverrideCursor();
830 bool XGUI_Workshop::isActiveOperationAborted()
832 return myOperationMgr->abortAllOperations();
835 //******************************************************
836 void XGUI_Workshop::onExit()
838 SessionPtr aMgr = ModelAPI_Session::get();
839 if (aMgr->isModified()) {
840 int anAnswer = QMessageBox::question(
841 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
842 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
843 if (anAnswer == QMessageBox::Save) {
844 bool saved = onSave();
848 } else if (anAnswer == QMessageBox::Cancel) {
855 //******************************************************
856 void XGUI_Workshop::onNew()
858 QApplication::setOverrideCursor(Qt::WaitCursor);
859 if (objectBrowser() == 0) {
861 mySelector->connectViewers();
863 myViewerProxy->connectToViewer();
865 if (!isSalomeMode()) {
866 myMainWindow->showPythonConsole();
867 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
868 aWnd->showMaximized();
869 updateCommandStatus();
871 myContextMenuMgr->connectViewer();
872 QApplication::restoreOverrideCursor();
875 //******************************************************
876 void XGUI_Workshop::onOpen()
878 if(!isActiveOperationAborted())
880 //save current file before close if modified
881 SessionPtr aSession = ModelAPI_Session::get();
882 if (aSession->isModified()) {
883 //TODO(sbh): re-launch the app?
884 int anAnswer = QMessageBox::question(
885 myMainWindow, tr("Save current file"),
886 tr("The document is modified, save before opening another?"),
887 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
888 if (anAnswer == QMessageBox::Save) {
890 } else if (anAnswer == QMessageBox::Cancel) {
896 //show file dialog, check if readable and open
897 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow(), tr("Select folder"));
898 if (myCurrentDir.isEmpty())
900 QFileInfo aFileInfo(myCurrentDir);
901 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
902 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
906 QApplication::setOverrideCursor(Qt::WaitCursor);
907 myIsLoadingData = true;
908 aSession->closeAll();
909 aSession->load(myCurrentDir.toLatin1().constData());
910 myObjectBrowser->rebuildDataTree();
911 //displayAllResults();
912 updateCommandStatus();
913 myIsLoadingData = false;
914 QApplication::restoreOverrideCursor();
917 //******************************************************
918 bool XGUI_Workshop::onSave()
920 if(!isActiveOperationAborted())
922 if (myCurrentDir.isEmpty()) {
925 std::list<std::string> aFiles;
926 saveDocument(myCurrentDir, aFiles);
927 updateCommandStatus();
929 myMainWindow->setModifiedState(false);
933 //******************************************************
934 bool XGUI_Workshop::onSaveAs()
936 if(!isActiveOperationAborted())
938 QFileDialog dialog(mainWindow());
939 dialog.setWindowTitle(tr("Select folder to save files..."));
940 dialog.setFileMode(QFileDialog::Directory);
941 dialog.setFilter(tr("Folders (*)"));
942 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
943 dialog.setViewMode(QFileDialog::Detail);
945 if (!dialog.exec()) {
949 QString aTempDir = dialog.selectedFiles().first();
951 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
952 int answer = QMessageBox::question(
954 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
956 tr("The folder already contains some files, save anyway?"),
957 QMessageBox::Save | QMessageBox::Cancel);
958 if (answer == QMessageBox::Cancel) {
962 myCurrentDir = aTempDir;
963 if (!isSalomeMode()) {
964 myMainWindow->setCurrentDir(myCurrentDir, false);
965 myMainWindow->setModifiedState(false);
970 //******************************************************
971 void XGUI_Workshop::onUndo(int theTimes)
973 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
974 SessionPtr aMgr = ModelAPI_Session::get();
975 if (aMgr->isOperation())
976 operationMgr()->onAbortOperation();
977 for (int i = 0; i < theTimes; ++i) {
980 updateCommandStatus();
983 //******************************************************
984 void XGUI_Workshop::onRedo(int theTimes)
986 // the viewer update should be blocked in order to avoid the features blinking. For the created
987 // feature a results are created, the flush of the created signal caused the viewer redisplay for
988 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
989 // redo of all possible objects happens
990 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
992 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
993 SessionPtr aMgr = ModelAPI_Session::get();
994 if (aMgr->isOperation())
995 operationMgr()->onAbortOperation();
996 for (int i = 0; i < theTimes; ++i) {
999 updateCommandStatus();
1001 // unblock the viewer update functionality and make update on purpose
1002 myDisplayer->enableUpdateViewer(isUpdateEnabled);
1003 myDisplayer->updateViewer();
1006 //******************************************************
1007 void XGUI_Workshop::onRebuild()
1009 SessionPtr aMgr = ModelAPI_Session::get();
1010 bool aWasOperation = aMgr->isOperation(); // keep this value
1011 if (!aWasOperation) {
1012 aMgr->startOperation("Rebuild");
1014 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1015 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1016 new Events_Message(aRebuildEvent, this)));
1017 if (!aWasOperation) {
1018 aMgr->finishOperation();
1020 updateCommandStatus();
1023 //******************************************************
1024 void XGUI_Workshop::onPreferences()
1026 ModuleBase_Prefs aModif;
1027 ModuleBase_Preferences::editPreferences(aModif);
1028 if (aModif.size() > 0) {
1030 foreach (ModuleBase_Pref aPref, aModif)
1032 aSection = aPref.first;
1033 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1034 if (!isSalomeMode())
1035 myMainWindow->viewer()->updateFromResources();
1036 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1037 if (!isSalomeMode())
1038 myMainWindow->menuObject()->updateFromResources();
1044 //******************************************************
1045 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1047 QString libName = QString::fromStdString(library(theModule.toStdString()));
1048 if (libName.isEmpty()) {
1049 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1054 CREATE_FUNC crtInst = 0;
1057 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1061 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1062 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1063 QString aMsg((char*) &lpMsgBuf);
1064 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1065 ::LocalFree(lpMsgBuf);
1067 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1071 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1072 | FORMAT_MESSAGE_IGNORE_INSERTS,
1073 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1074 QString aMsg((char*) &lpMsgBuf);
1075 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1076 ::LocalFree(lpMsgBuf);
1080 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1082 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1084 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1086 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1091 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1093 if (!err.isEmpty()) {
1095 Events_Error::send(err.toStdString());
1097 qWarning(qPrintable(err));
1103 //******************************************************
1104 bool XGUI_Workshop::createModule()
1106 Config_ModuleReader aModuleReader;
1107 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1108 myModule = loadModule(moduleName);
1112 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1113 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1114 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1115 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1117 myModule->createFeatures();
1118 //myActionsMgr->update();
1122 //******************************************************
1123 void XGUI_Workshop::updateCommandStatus()
1125 QList<QAction*> aCommands;
1126 if (isSalomeMode()) { // update commands in SALOME mode
1127 aCommands = salomeConnector()->commandList();
1129 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1130 foreach (AppElements_Command* aCmd, aMenuBar->features())
1131 aCommands.append(aCmd);
1133 SessionPtr aMgr = ModelAPI_Session::get();
1134 if (aMgr->hasModuleDocument()) {
1135 foreach(QAction* aCmd, aCommands) {
1136 QString aId = aCmd->data().toString();
1137 if (aId == "UNDO_CMD")
1138 aCmd->setEnabled(myModule->canUndo());
1139 else if (aId == "REDO_CMD")
1140 aCmd->setEnabled(myModule->canRedo());
1142 // Enable all commands
1143 aCmd->setEnabled(true);
1147 foreach(QAction* aCmd, aCommands) {
1148 QString aId = aCmd->data().toString();
1149 if (aId == "NEW_CMD")
1150 aCmd->setEnabled(true);
1151 else if (aId == "EXIT_CMD")
1152 aCmd->setEnabled(true);
1154 aCmd->setEnabled(false);
1157 myActionsMgr->update();
1158 emit commandStatusUpdated();
1161 void XGUI_Workshop::updateHistory()
1163 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1164 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1165 emit updateUndoHistory(aUndoRes);
1167 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1168 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1169 emit updateRedoHistory(aRedoRes);
1172 //******************************************************
1173 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1175 QDockWidget* aObjDock = new QDockWidget(theParent);
1176 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1177 aObjDock->setWindowTitle(tr("Object browser"));
1178 aObjDock->setStyleSheet(
1179 "::title { position: relative; padding-left: 5px; text-align: left center }");
1180 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1181 myObjectBrowser->setDataModel(myModule->dataModel());
1182 myModule->customizeObjectBrowser(myObjectBrowser);
1183 aObjDock->setWidget(myObjectBrowser);
1185 myContextMenuMgr->connectObjectBrowser();
1189 //******************************************************
1191 * Creates dock widgets, places them in corresponding area
1192 * and tabifies if necessary.
1194 void XGUI_Workshop::createDockWidgets()
1196 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1197 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1198 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1199 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1200 myPropertyPanel->setupActions(myActionsMgr);
1201 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1202 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1203 hidePropertyPanel(); ///<! Invisible by default
1204 hideObjectBrowser();
1205 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1206 myPropertyPanel->installEventFilter(myOperationMgr);
1208 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1209 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1210 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1211 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1212 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1213 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1214 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1215 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1216 aOkAct, SLOT(setEnabled(bool)));
1217 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1218 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1219 aAcceptAllAct, SLOT(setEnabled(bool)));
1223 //******************************************************
1224 void XGUI_Workshop::showPropertyPanel()
1226 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1227 ///<! Restore ability to close panel from the window's menu
1228 aViewAct->setEnabled(true);
1229 myPropertyPanel->show();
1230 myPropertyPanel->raise();
1233 //******************************************************
1234 void XGUI_Workshop::hidePropertyPanel()
1236 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1237 ///<! Do not allow to show empty property panel
1238 aViewAct->setEnabled(false);
1239 myPropertyPanel->hide();
1242 //******************************************************
1243 void XGUI_Workshop::showObjectBrowser()
1245 myObjectBrowser->parentWidget()->show();
1248 //******************************************************
1249 void XGUI_Workshop::hideObjectBrowser()
1251 myObjectBrowser->parentWidget()->hide();
1254 //******************************************************
1255 //void XGUI_Workshop::onFeatureTriggered()
1257 // QAction* aCmd = dynamic_cast<QAction*>(sender());
1259 // QString aId = salomeConnector()->commandId(aCmd);
1260 // if (!aId.isNull())
1261 // myModule->launchOperation(aId);
1265 //******************************************************
1266 void XGUI_Workshop::salomeViewerSelectionChanged()
1268 emit salomeViewerSelection();
1271 //**************************************************************
1272 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1274 return mySalomeConnector->viewer();
1277 //**************************************************************
1278 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1280 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1281 if (theId == "DELETE_CMD")
1283 else if (theId == "COLOR_CMD")
1284 changeColor(aObjects);
1285 else if (theId == "SHOW_CMD")
1286 showObjects(aObjects, true);
1287 else if (theId == "HIDE_CMD")
1288 showObjects(aObjects, false);
1289 else if (theId == "SHOW_ONLY_CMD")
1290 showOnlyObjects(aObjects);
1291 else if (theId == "SHADING_CMD")
1292 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1293 else if (theId == "WIREFRAME_CMD")
1294 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1295 else if (theId == "HIDEALL_CMD") {
1296 QObjectPtrList aList = myDisplayer->displayedObjects();
1297 foreach (ObjectPtr aObj, aList)
1298 aObj->setDisplayed(false);
1299 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1303 //**************************************************************
1304 void XGUI_Workshop::deleteObjects()
1306 ModuleBase_IModule* aModule = module();
1307 // 1. allow the module to delete objects, do nothing if it has succeed
1308 if (aModule->deleteObjects()) {
1309 updateCommandStatus();
1313 if (!isActiveOperationAborted())
1315 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1316 bool hasResult = false;
1317 bool hasFeature = false;
1318 bool hasParameter = false;
1319 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1320 if (!(hasFeature || hasParameter))
1323 // 1. start operation
1324 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1325 aDescription += tr(" %1");
1326 QStringList aObjectNames;
1327 foreach (ObjectPtr aObj, anObjects) {
1328 if (!aObj->data()->isValid())
1330 aObjectNames << QString::fromStdString(aObj->data()->name());
1332 aDescription = aDescription.arg(aObjectNames.join(", "));
1334 SessionPtr aMgr = ModelAPI_Session::get();
1335 aMgr->startOperation(aDescription.toStdString());
1336 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1337 // this is performed in the RemoveFeature of Part object.
1338 /*foreach (ObjectPtr aObj, anObjects)
1340 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1342 DocumentPtr aDoc = aObj->document();
1343 if (aDoc == aMgr->activeDocument()) {
1348 // 3. delete objects
1349 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1350 std::set<FeaturePtr> anIgnoredFeatures;
1351 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1352 myDisplayer->updateViewer();
1353 aMgr->finishOperation();
1354 updateCommandStatus();
1357 aMgr->abortOperation();
1361 //**************************************************************
1362 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1363 std::set<FeaturePtr> theIgnoredFeatures,
1365 const bool theAskAboutDeleteReferences)
1367 // 1. find all referenced features
1368 std::set<FeaturePtr> aRefFeatures;
1369 foreach (ObjectPtr aDeletedObj, theList) {
1370 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1371 if (aDeletedFeature.get() != NULL) {
1372 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1373 // 1.1 find references in the current document
1374 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1375 // 1.2 find references in all documents if the document of the feature is
1376 // "PartSet". Features of this document can be used in all other documents
1377 SessionPtr aMgr = ModelAPI_Session::get();
1378 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1379 if (aDeletedFeatureDoc == aModuleDoc) {
1380 // the deleted feature and results of the feature should be found in references
1381 std::list<ObjectPtr> aDeletedObjects;
1382 aDeletedObjects.push_back(aDeletedFeature);
1383 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1384 const ResultsList& aDeletedResults = aDeletedFeature->results();
1385 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1386 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1387 ResultPtr aRes = *aRIter;
1389 aDeletedObjects.push_back(aRes);
1391 // get all opened documents; found features in the documents;
1392 // get a list of objects where a feature refers;
1393 // search in these objects the deleted objects.
1394 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1395 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1396 aLast = anOpenedDocs.end();
1397 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1398 for (; anIt != aLast; anIt++) {
1399 DocumentPtr aDocument = *anIt;
1400 if (aDocument == aDeletedFeatureDoc)
1401 continue; // this document has been already processed in 1.1
1403 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1404 for (int aId = 0; aId < aFeaturesCount; aId++) {
1405 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1406 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1407 if (!aFeature.get())
1411 aFeature->data()->referencesToObjects(aRefs);
1412 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1413 bool aHasReferenceToDeleted = false;
1414 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1415 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1416 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1417 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1418 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1419 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1423 if (aHasReferenceToDeleted)
1424 aRefFeatures.insert(aFeature);
1430 // 2. warn about the references remove, break the delete operation if the user chose it
1431 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1432 QStringList aRefNames;
1433 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1434 aLast = aRefFeatures.end();
1435 for (; anIt != aLast; anIt++) {
1436 aRefNames.append((*anIt)->name().c_str());
1438 QString aNames = aRefNames.join(", ");
1440 QMessageBox::StandardButton aRes = QMessageBox::warning(
1441 theParent, tr("Delete features"),
1442 QString(tr("Selected features are used in the following features: %1.\
1443 These features will be deleted also. Would you like to continue?")).arg(aNames),
1444 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1445 if (aRes != QMessageBox::Yes)
1449 // 3. remove referenced features
1450 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1451 aLast = aRefFeatures.end();
1455 for (; anIt != aLast; anIt++) {
1456 FeaturePtr aFeature = (*anIt);
1457 DocumentPtr aDoc = aFeature->document();
1458 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1459 aDoc->removeFeature(aFeature);
1461 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1466 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1470 // 4. remove the parameter features
1471 foreach (ObjectPtr aObj, theList) {
1472 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1473 if (aResult.get() != NULL) { // results could not be removed,
1474 // they are removed by a corresponded feature remove
1477 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1479 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1480 // part features are removed in the PartSet module. This condition should be moved there
1481 if (aFeature->getKind() == "Part")
1484 DocumentPtr aDoc = aObj->document();
1485 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1486 aDoc->removeFeature(aFeature);
1488 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1489 anInfo.append(anInfoStr);
1490 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1496 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1501 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1503 bool isFoundResultType = false;
1504 foreach(ObjectPtr anObj, theObjects)
1506 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1507 if (aResult.get() == NULL)
1510 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1511 if (isFoundResultType)
1514 return isFoundResultType;
1517 //**************************************************************
1518 bool XGUI_Workshop::canChangeColor() const
1520 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1522 std::set<std::string> aTypes;
1523 aTypes.insert(ModelAPI_ResultGroup::group());
1524 aTypes.insert(ModelAPI_ResultConstruction::group());
1525 aTypes.insert(ModelAPI_ResultBody::group());
1526 aTypes.insert(ModelAPI_ResultPart::group());
1528 return hasResults(aObjects, aTypes);
1531 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1533 if (!theResult.get())
1536 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1537 if (aColorAttr.get() != NULL) {
1538 if (!aColorAttr->size()) {
1539 aColorAttr->setSize(3);
1541 aColorAttr->setValue(0, theColor[0]);
1542 aColorAttr->setValue(1, theColor[1]);
1543 aColorAttr->setValue(2, theColor[2]);
1547 //**************************************************************
1548 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1550 AttributeIntArrayPtr aColorAttr;
1551 // 1. find the current color of the object. This is a color of AIS presentation
1552 // The objects are iterated until a first valid color is found
1553 std::vector<int> aColor;
1554 foreach(ObjectPtr anObject, theObjects) {
1555 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1556 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1557 DocumentPtr aPartDoc = aPart->partDoc();
1558 // the document should be checked on null, because in opened document if the part
1559 // has not been activated yet, the part document is empty
1560 if (!aPartDoc.get()) {
1561 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1564 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1565 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1566 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1568 XGUI_CustomPrs::getResultColor(aBody, aColor);
1574 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1576 XGUI_CustomPrs::getResultColor(aResult, aColor);
1578 // TODO: remove the obtaining a color from the AIS object
1579 // this does not happen never because:
1580 // 1. The color can be changed only on results
1581 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1582 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1583 if (anAISObj.get()) {
1585 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1589 if (!aColor.empty())
1592 if (aColor.size() != 3)
1595 // 2. show the dialog to change the value
1596 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1597 aDlg->setColor(aColor);
1598 aDlg->move(QCursor::pos());
1599 bool isDone = aDlg->exec() == QDialog::Accepted;
1603 bool isRandomColor = aDlg->isRandomColor();
1605 // 3. abort the previous operation and start a new one
1606 SessionPtr aMgr = ModelAPI_Session::get();
1607 bool aWasOperation = aMgr->isOperation(); // keep this value
1608 if (!aWasOperation) {
1609 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1610 aMgr->startOperation(aDescription.toStdString());
1613 // 4. set the value to all results
1614 foreach(ObjectPtr anObj, theObjects) {
1615 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1616 if (aResult.get() != NULL) {
1617 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1618 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1619 DocumentPtr aPartDoc = aPart->partDoc();
1620 // the document should be checked on null, because in opened document if the part
1621 // has not been activated yet, the part document is empty
1622 if (aPartDoc.get()) {
1623 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1624 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1625 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1626 std::vector<int> aColorResult = aDlg->getColor();
1627 setColor(aBody, aColorResult);
1632 std::vector<int> aColorResult = aDlg->getColor();
1633 setColor(aResult, aColorResult);
1638 aMgr->finishOperation();
1639 updateCommandStatus();
1642 //**************************************************************
1643 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1644 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1645 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1647 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1649 foreach (ObjectPtr aObj, theList) {
1651 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1653 DocumentPtr aDoc = aPartRes->partDoc();
1654 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1655 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1656 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1659 aObj->setDisplayed(isVisible);
1662 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1665 //**************************************************************
1666 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1668 // Hide all displayed objects
1669 QObjectPtrList aList = myDisplayer->displayedObjects();
1670 foreach (ObjectPtr aObj, aList)
1671 aObj->setDisplayed(false);
1673 // Show only objects from the list
1674 foreach (ObjectPtr aObj, theList) {
1676 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1678 DocumentPtr aDoc = aPartRes->partDoc();
1679 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1680 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1681 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1684 aObj->setDisplayed(true);
1687 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1692 //**************************************************************
1693 void XGUI_Workshop::registerValidators() const
1695 SessionPtr aMgr = ModelAPI_Session::get();
1696 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1699 //**************************************************************
1700 /*void XGUI_Workshop::displayAllResults()
1702 SessionPtr aMgr = ModelAPI_Session::get();
1703 DocumentPtr aRootDoc = aMgr->moduleDocument();
1704 displayDocumentResults(aRootDoc);
1705 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1706 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1707 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1708 displayDocumentResults(aPart->partDoc());
1710 myDisplayer->updateViewer();
1713 //**************************************************************
1714 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1718 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1719 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1722 //**************************************************************
1723 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1725 for (int i = 0; i < theDoc->size(theGroup); i++)
1726 theDoc->object(theGroup, i)->setDisplayed(true);
1727 //displayObject(theDoc->object(theGroup, i));
1728 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1731 //**************************************************************
1732 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1734 foreach(ObjectPtr aObj, theList) {
1735 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1737 if (theList.size() > 0)
1738 myDisplayer->updateViewer();
1741 //**************************************************************
1742 void XGUI_Workshop::closeDocument()
1744 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1745 while (anOperation) {
1746 anOperation->abort();
1747 anOperation = operationMgr()->currentOperation();
1749 myDisplayer->closeLocalContexts();
1750 myDisplayer->eraseAll();
1751 objectBrowser()->clearContent();
1753 SessionPtr aMgr = ModelAPI_Session::get();
1757 //**************************************************************
1758 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1760 if (!myModule->canDisplayObject(theObj))
1763 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1764 if (aBody.get() != NULL) {
1765 int aNb = myDisplayer->objectsCount();
1766 myDisplayer->display(theObj, false);
1769 } else if (!(myIsLoadingData || myPartActivating))
1770 myDisplayer->display(theObj, false);
1775 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1777 XGUI_HistoryMenu* aMenu = NULL;
1778 if (isSalomeMode()) {
1779 QAction* anAction = qobject_cast<QAction*>(theObject);
1782 aMenu = new XGUI_HistoryMenu(anAction);
1784 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1785 aMenu = new XGUI_HistoryMenu(aButton);
1787 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1788 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1791 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1793 QList<ActionInfo> aResult;
1794 std::list<std::string>::const_iterator it = theList.cbegin();
1795 for (; it != theList.cend(); it++) {
1796 QString anId = QString::fromStdString(*it);
1797 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1799 anId.chop(ModuleBase_Operation::EditSuffix().size());
1802 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1803 if (aContextMenuAct) {
1804 anInfo.initFrom(aContextMenuAct);
1806 anInfo = myActionsMgr->actionInfoById(anId);
1809 anInfo.text = anInfo.text.prepend("Modify ");