1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Tools.h"
5 #include "XGUI_Workshop.h"
6 #include "XGUI_SelectionMgr.h"
7 #include "XGUI_Selection.h"
8 #include "XGUI_ObjectsBrowser.h"
9 #include "XGUI_Displayer.h"
10 #include "XGUI_OperationMgr.h"
11 #include "XGUI_SalomeConnector.h"
12 #include "XGUI_ActionsMgr.h"
13 #include "XGUI_ErrorDialog.h"
14 #include "XGUI_ColorDialog.h"
15 #include "XGUI_ViewerProxy.h"
16 #include "XGUI_PropertyPanel.h"
17 #include "XGUI_ContextMenuMgr.h"
18 #include "XGUI_ModuleConnector.h"
19 #include <XGUI_QtEvents.h>
20 #include <XGUI_HistoryMenu.h>
21 #include <XGUI_CustomPrs.h>
23 #include <AppElements_Workbench.h>
24 #include <AppElements_Viewer.h>
25 #include <AppElements_Command.h>
26 #include <AppElements_MainMenu.h>
27 #include <AppElements_MainWindow.h>
28 #include <AppElements_MenuGroupPanel.h>
29 #include <AppElements_Button.h>
31 #include <ModuleBase_IModule.h>
32 #include <ModuleBase_Preferences.h>
34 #include <ModelAPI_Events.h>
35 #include <ModelAPI_Session.h>
36 #include <ModelAPI_Feature.h>
37 #include <ModelAPI_Data.h>
38 #include <ModelAPI_AttributeDocRef.h>
39 #include <ModelAPI_Object.h>
40 #include <ModelAPI_Validator.h>
41 #include <ModelAPI_ResultGroup.h>
42 #include <ModelAPI_ResultConstruction.h>
43 #include <ModelAPI_ResultBody.h>
44 #include <ModelAPI_AttributeIntArray.h>
45 #include <ModelAPI_ResultParameter.h>
47 //#include <PartSetPlugin_Part.h>
49 #include <Events_Loop.h>
50 #include <Events_Error.h>
51 #include <Events_LongOp.h>
53 #include <ModuleBase_Operation.h>
54 #include <ModuleBase_Operation.h>
55 #include <ModuleBase_OperationDescription.h>
56 #include <ModuleBase_SelectionValidator.h>
57 #include <ModuleBase_WidgetFactory.h>
58 #include <ModuleBase_Tools.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_FilterFactory.h>
61 #include <ModuleBase_PageBase.h>
62 #include <ModuleBase_Tools.h>
64 #include <Config_Common.h>
65 #include <Config_FeatureMessage.h>
66 #include <Config_PointerMessage.h>
67 #include <Config_ModuleReader.h>
68 #include <Config_PropManager.h>
69 #include <Config_SelectionFilterMessage.h>
71 #include <QApplication>
72 #include <QFileDialog>
73 #include <QMessageBox>
74 #include <QMdiSubWindow>
75 #include <QPushButton>
76 #include <QDockWidget>
81 #include <QToolButton>
95 //#define DEBUG_FEATURE_CREATED
96 //#define DEBUG_FEATURE_REDISPLAY
97 //#define DEBUG_DELETE
99 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
101 myCurrentDir(QString()),
103 mySalomeConnector(theConnector),
107 myUpdatePrefs(false),
108 myPartActivating(false),
109 myIsLoadingData(false)
111 myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
113 myDisplayer = new XGUI_Displayer(this);
115 mySelector = new XGUI_SelectionMgr(this);
116 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
118 myOperationMgr = new XGUI_OperationMgr(this);
119 myActionsMgr = new XGUI_ActionsMgr(this);
120 myErrorDlg = new XGUI_ErrorDialog(myMainWindow);
121 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
122 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
123 SLOT(onContextMenuCommand(const QString&, bool)));
125 myViewerProxy = new XGUI_ViewerProxy(this);
126 connect(myViewerProxy, SIGNAL(selectionChanged()),
127 myActionsMgr, SLOT(updateOnViewSelection()));
129 myModuleConnector = new XGUI_ModuleConnector(this);
131 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
132 SLOT(onOperationStarted(ModuleBase_Operation*)));
133 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
134 SLOT(onOperationResumed(ModuleBase_Operation*)));
135 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
136 SLOT(onOperationStopped(ModuleBase_Operation*)));
137 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
138 SLOT(onOperationCommitted(ModuleBase_Operation*)));
139 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
140 SLOT(onOperationAborted(ModuleBase_Operation*)));
141 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
142 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
145 //******************************************************
146 XGUI_Workshop::~XGUI_Workshop(void)
151 //******************************************************
152 void XGUI_Workshop::startApplication()
156 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
157 Config_Prop::Directory, "");
159 //Initialize event listening
160 Events_Loop* aLoop = Events_Loop::loop();
161 aLoop->registerListener(this, Events_Error::errorID()); //!< Listening application errors.
162 aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
163 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
164 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
165 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
166 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
167 aLoop->registerListener(this, Events_LongOp::eventID());
168 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
169 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
171 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
172 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
174 registerValidators();
176 // Calling of loadCustomProps before activating module is required
177 // by Config_PropManger to restore user-defined path to plugins
178 ModuleBase_Preferences::loadCustomProps();
181 myMainWindow->show();
182 updateCommandStatus();
187 emit applicationStarted();
190 void XGUI_Workshop::activateModule()
192 myModule->activateSelectionFilters();
194 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
195 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
196 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
197 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
199 myActionsMgr->update();
203 void XGUI_Workshop::deactivateModule()
205 myModule->deactivateSelectionFilters();
207 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
208 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
209 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
210 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
213 //******************************************************
214 void XGUI_Workshop::initMenu()
216 myContextMenuMgr->createActions();
218 if (isSalomeMode()) {
219 // Create only Undo, Redo commands
220 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
221 tr("Undo last command"),
222 QIcon(":pictures/undo.png"),
223 QKeySequence::Undo, false, "MEN_DESK_EDIT");
224 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
225 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
227 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
228 QIcon(":pictures/redo.png"), QKeySequence::Redo,
229 false, "MEN_DESK_EDIT");
230 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
231 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
233 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
234 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
235 QIcon(":pictures/rebuild.png"), QKeySequence(),
236 false, "MEN_DESK_EDIT");
237 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
238 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
240 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
241 QIcon(), QKeySequence(),
242 false, "MEN_DESK_FILE");
243 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
245 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
246 QIcon(), QKeySequence(),
247 false, "MEN_DESK_FILE");
248 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
249 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
253 // File commands group
254 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
256 AppElements_Command* aCommand;
258 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
259 QIcon(":pictures/save.png"), QKeySequence::Save);
260 aCommand->connectTo(this, SLOT(onSave()));
261 //aCommand->disable();
263 QString aUndoId = "UNDO_CMD";
264 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
265 QIcon(":pictures/undo.png"), QKeySequence::Undo);
266 aCommand->connectTo(this, SLOT(onUndo()));
267 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
268 addHistoryMenu(aUndoButton,
269 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
272 QString aRedoId = "REDO_CMD";
273 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
274 QIcon(":pictures/redo.png"), QKeySequence::Redo);
275 aCommand->connectTo(this, SLOT(onRedo()));
276 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
277 addHistoryMenu(aRedoButton,
278 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
281 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
282 QIcon(":pictures/rebuild.png"), QKeySequence());
283 aCommand->connectTo(this, SLOT(onRebuild()));
285 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
286 QIcon(":pictures/save.png"), QKeySequence());
287 aCommand->connectTo(this, SLOT(onSaveAs()));
288 //aCommand->disable();
290 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
291 QIcon(":pictures/open.png"), QKeySequence::Open);
292 aCommand->connectTo(this, SLOT(onOpen()));
294 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
295 // QIcon(":pictures/new.png"), QKeySequence::New);
296 //aCommand->connectTo(this, SLOT(onNew()));
298 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
299 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
300 aCommand->connectTo(this, SLOT(onPreferences()));
302 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
303 QIcon(":pictures/close.png"), QKeySequence::Close);
304 aCommand->connectTo(this, SLOT(onExit()));
305 //FIXME: SBH's test action. Can be used for some GUI tests.
307 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
308 // QIcon(":pictures/close.png"), QKeySequence(), true);
309 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
313 //******************************************************
314 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
316 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
317 return aMenuBar->addWorkbench(theName);
320 //******************************************************
321 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
323 if (QApplication::instance()->thread() != QThread::currentThread()) {
325 std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
327 SessionPtr aMgr = ModelAPI_Session::get();
328 PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
329 QApplication::postEvent(this, aPostponeEvent);
333 //A message to start feature creation received.
334 if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
335 std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
336 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
337 if (!aFeatureMsg->isInternal()) {
338 addFeature(aFeatureMsg);
341 // Process creation of Part
342 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
343 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
344 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
345 onFeatureCreatedMsg(aUpdMsg);
347 if (mySalomeConnector)
348 mySalomeConnector->createPreferences();
349 myUpdatePrefs = false;
352 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
353 myUpdatePrefs = true;
356 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
357 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
358 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
359 onFeatureRedisplayMsg(aUpdMsg);
361 //Update property panel on corresponding message. If there is no current operation (no
362 //property panel), or received message has different feature to the current - do nothing.
363 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
364 std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
365 std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
366 onFeatureUpdatedMsg(anUpdateMsg);
367 } else if (theMessage->eventID() == Events_LongOp::eventID()) {
368 if (Events_LongOp::isPerformed()) {
369 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
371 QApplication::restoreOverrideCursor();
374 //An operation passed by message. Start it, process and commit.
375 else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
376 std::shared_ptr<Config_PointerMessage> aPartSetMsg =
377 std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
378 //myPropertyPanel->cleanContent();
379 ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
381 if (myOperationMgr->startOperation(anOperation)) {
382 myPropertyPanel->updateContentWidget(anOperation->feature());
383 if (!anOperation->getDescription()->hasXmlRepresentation()) {
384 if (anOperation->commit())
385 updateCommandStatus();
389 else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
390 std::shared_ptr<Config_SelectionFilterMessage> aMsg =
391 std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
393 ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
394 if (!aMsg->attributeId().empty()) {
395 aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
399 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
400 // the viewer's update context will not happens until viewer updated is emitted
401 myDisplayer->enableUpdateViewer(false);
402 } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
403 // the viewer's update context is unblocked, the viewer's update works
404 myDisplayer->enableUpdateViewer(true);
405 myDisplayer->updateViewer();
407 //Show error dialog if error message received.
408 std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
410 emit errorOccurred(QString::fromLatin1(anAppError->description()));
414 if (!isSalomeMode()) {
415 SessionPtr aMgr = ModelAPI_Session::get();
416 if (aMgr->isModified() != myMainWindow->isModifiedState())
417 myMainWindow->setModifiedState(aMgr->isModified());
421 //******************************************************
422 QMainWindow* XGUI_Workshop::desktop() const
424 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
427 //******************************************************
428 void XGUI_Workshop::onStartWaiting()
430 if (Events_LongOp::isPerformed()) {
431 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
435 //******************************************************
436 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
438 std::set<ObjectPtr> aFeatures = theMsg->objects();
439 if (myOperationMgr->hasOperation()) {
440 FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
441 std::set<ObjectPtr>::const_iterator aIt;
442 for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
443 ObjectPtr aNewFeature = (*aIt);
444 if (aNewFeature == aCurrentFeature) {
445 myPropertyPanel->updateContentWidget(aCurrentFeature);
450 myOperationMgr->onValidateOperation();
451 //if (myObjectBrowser)
452 // myObjectBrowser->processEvent(theMsg);
455 //******************************************************
456 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
458 std::set<ObjectPtr> aObjects = theMsg->objects();
459 std::set<ObjectPtr>::const_iterator aIt;
461 #ifdef DEBUG_FEATURE_REDISPLAY
463 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
464 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
466 QString anInfoStr = anInfo.join(", ");
467 qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
470 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
471 ObjectPtr aObj = (*aIt);
473 // Hide the object if it is invalid or concealed one
474 bool aHide = !aObj->data() || !aObj->data()->isValid() ||
475 aObj->isDisabled() || (!aObj->isDisplayed());
476 if (!aHide) { // check that this is not hidden result
477 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
478 aHide = aRes && aRes->isConcealed();
481 myDisplayer->erase(aObj, false);
483 // Redisplay the visible object or the object of the current operation
484 bool isVisibleObject = myDisplayer->isVisible(aObj);
485 #ifdef DEBUG_FEATURE_REDISPLAY
486 //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
487 //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
490 if (isVisibleObject) { // redisplay visible object
491 //displayObject(aObj); // In order to update presentation
492 // in order to avoid the check whether the object can be redisplayed, the exact method
493 // of redisplay is called. This modification is made in order to have the line is updated
494 // by creation of a horizontal constraint on the line by preselection
495 myDisplayer->redisplay(aObj, false);
496 // Deactivate object of current operation from selection
497 deactivateActiveObject(aObj, false);
498 } else { // display object if the current operation has it
499 if (displayObject(aObj)) {
500 // Deactivate object of current operation from selection
501 deactivateActiveObject(aObj, false);
506 myDisplayer->updateViewer();
509 //******************************************************
510 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
512 if (!myModule->canActivateSelection(theObject)) {
513 if (myDisplayer->isActive(theObject))
514 myDisplayer->deactivate(theObject, theUpdateViewer);
518 //******************************************************
519 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
521 std::set<ObjectPtr> aObjects = theMsg->objects();
522 std::set<ObjectPtr>::const_iterator aIt;
523 #ifdef DEBUG_FEATURE_CREATED
525 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
526 anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
528 QString anInfoStr = anInfo.join(", ");
529 qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
532 //bool aHasPart = false;
533 bool isDisplayed = false;
534 for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
535 ObjectPtr anObject = *aIt;
536 // the validity of the data should be checked here in order to avoid display of the objects,
537 // which were created, then deleted, but flush for the creation event happens after that
538 // we should not display disabled objects
539 bool aHide = !anObject->data()->isValid() ||
540 anObject->isDisabled() ||
541 !anObject->isDisplayed();
543 // setDisplayed has to be called in order to synchronize internal state of the object
544 // with list of displayed objects
545 if (myModule->canDisplayObject(anObject)) {
546 anObject->setDisplayed(true);
547 isDisplayed = displayObject(*aIt);
549 anObject->setDisplayed(false);
552 //if (myObjectBrowser)
553 // myObjectBrowser->processEvent(theMsg);
555 myDisplayer->updateViewer();
556 //if (aHasPart) { // TODO: Avoid activate last part on loading of document
557 // activateLastPart();
561 //******************************************************
562 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
564 setNestedFeatures(theOperation);
566 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
567 connectWithOperation(theOperation);
568 setPropertyPanel(theOperation);
570 updateCommandStatus();
572 myModule->onOperationStarted(theOperation);
574 // the objects of the current operation should be deactivated
575 QObjectPtrList anObjects;
576 FeaturePtr aFeature = theOperation->feature();
577 anObjects.append(aFeature);
578 std::list<ResultPtr> aResults = aFeature->results();
579 std::list<ResultPtr>::const_iterator aIt;
580 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
581 anObjects.append(*aIt);
583 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
584 for (; anIt != aLast; anIt++)
585 deactivateActiveObject(*anIt, false);
586 if (anObjects.size() > 0)
587 myDisplayer->updateViewer();
590 //******************************************************
591 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
593 setNestedFeatures(theOperation);
595 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
596 // connectWithOperation(theOperation); already connected
597 setPropertyPanel(theOperation);
599 updateCommandStatus();
601 myModule->onOperationResumed(theOperation);
605 //******************************************************
606 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
608 ModuleBase_ISelection* aSel = mySelector->selection();
609 QObjectPtrList aObj = aSel->selectedPresentations();
610 //!< No need for property panel
611 updateCommandStatus();
613 myPropertyPanel->cleanContent();
615 myModule->onOperationStopped(theOperation);
617 // the deactivated objects of the current operation should be activated back.
618 // They were deactivated on operation start or an object redisplay
619 QObjectPtrList anObjects;
620 FeaturePtr aFeature = theOperation->feature();
621 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
622 anObjects.append(aFeature);
623 std::list<ResultPtr> aResults = aFeature->results();
624 std::list<ResultPtr>::const_iterator aIt;
625 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
626 ResultPtr anObject = *aIt;
627 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
628 anObjects.append(anObject);
632 module()->activeSelectionModes(aModes);
633 myDisplayer->activateObjects(aModes, anObjects);
637 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
639 myModule->onOperationCommitted(theOperation);
642 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
644 myModule->onOperationAborted(theOperation);
647 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
649 if (this->isSalomeMode())
650 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
652 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
655 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
658 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
659 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
662 myPropertyPanel->cleanContent();
663 aFactory.createWidget(myPropertyPanel->contentWidget());
665 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
666 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
667 bool isStoreValue = !theOperation->isEditOperation() &&
668 !aWidget->getDefaultValue().empty() &&
669 !aWidget->isComputedDefault();
670 aWidget->setFeature(theOperation->feature(), isStoreValue);
671 aWidget->enableFocusProcessing();
674 myPropertyPanel->setModelWidgets(aWidgets);
675 theOperation->setPropertyPanel(myPropertyPanel);
677 myModule->propertyPanelDefined(theOperation);
679 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
682 bool XGUI_Workshop::event(QEvent * theEvent)
684 PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
686 std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
687 processEvent(aEventPtr);
696 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
700 qDebug() << "XGUI_Workshop::addFeature: NULL message.";
704 ActionInfo aFeatureInfo;
705 aFeatureInfo.initFrom(theMessage);
707 QString aWchName = QString::fromStdString(theMessage->workbenchId());
708 QStringList aNestedFeatures =
709 QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
710 QString aDocKind = QString::fromStdString(theMessage->documentKind());
711 QList<QAction*> aNestedActList;
712 bool isColumnButton = !aNestedFeatures.isEmpty();
713 if (isColumnButton) {
714 QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
715 if (aNestedActions.contains("accept")) {
716 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
717 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
718 aNestedActList << anAction;
720 if (aNestedActions.contains("abort")) {
721 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
722 connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
723 aNestedActList << anAction;
727 if (isSalomeMode()) {
729 if (isColumnButton) {
730 aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
732 aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
734 salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
735 salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
737 myActionsMgr->addCommand(aAction);
738 myModule->actionCreated(aAction);
740 //Find or create Workbench
741 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
742 AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
744 aPage = addWorkbench(aWchName);
746 //Find or create Group
747 QString aGroupName = QString::fromStdString(theMessage->groupId());
748 AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
750 aGroup = aPage->addGroup(aGroupName);
752 // Check if hotkey sequence is already defined:
753 QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
754 if(aHotKey != aFeatureInfo.shortcut) {
755 aFeatureInfo.shortcut = aHotKey;
758 AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
761 // Enrich created button with accept/abort buttons if necessary
762 AppElements_Button* aButton = aCommand->button();
763 if (aButton->isColumnButton()) {
764 aButton->setAdditionalButtons(aNestedActList);
766 myActionsMgr->addCommand(aCommand);
767 myModule->actionCreated(aCommand);
772 * Makes a signal/slot connections between Property Panel
773 * and given operation. The given operation becomes a
774 * current operation and previous operation if exists
776 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
778 QAction* aCommand = 0;
779 if (isSalomeMode()) {
780 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
782 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
783 FeaturePtr aFeature = theOperation->feature();
785 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
787 //Abort operation on uncheck the command
789 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
794 * Saves document with given name.
796 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
798 QApplication::restoreOverrideCursor();
799 SessionPtr aMgr = ModelAPI_Session::get();
800 aMgr->save(theName.toLatin1().constData(), theFileNames);
801 QApplication::restoreOverrideCursor();
804 bool XGUI_Workshop::isActiveOperationAborted()
806 return myOperationMgr->abortAllOperations();
809 //******************************************************
810 void XGUI_Workshop::onExit()
812 SessionPtr aMgr = ModelAPI_Session::get();
813 if (aMgr->isModified()) {
814 int anAnswer = QMessageBox::question(
815 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
816 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
817 if (anAnswer == QMessageBox::Save) {
818 bool saved = onSave();
822 } else if (anAnswer == QMessageBox::Cancel) {
829 //******************************************************
830 void XGUI_Workshop::onNew()
832 QApplication::setOverrideCursor(Qt::WaitCursor);
833 if (objectBrowser() == 0) {
835 mySelector->connectViewers();
837 myViewerProxy->connectToViewer();
839 if (!isSalomeMode()) {
840 myMainWindow->showPythonConsole();
841 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
842 aWnd->showMaximized();
843 updateCommandStatus();
845 myContextMenuMgr->connectViewer();
846 QApplication::restoreOverrideCursor();
849 //******************************************************
850 void XGUI_Workshop::onOpen()
852 if(!isActiveOperationAborted())
854 //save current file before close if modified
855 SessionPtr aSession = ModelAPI_Session::get();
856 if (aSession->isModified()) {
857 //TODO(sbh): re-launch the app?
858 int anAnswer = QMessageBox::question(
859 myMainWindow, tr("Save current file"),
860 tr("The document is modified, save before opening another?"),
861 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
862 if (anAnswer == QMessageBox::Save) {
864 } else if (anAnswer == QMessageBox::Cancel) {
870 //show file dialog, check if readable and open
871 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
872 if (myCurrentDir.isEmpty())
874 QFileInfo aFileInfo(myCurrentDir);
875 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
876 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
880 QApplication::setOverrideCursor(Qt::WaitCursor);
881 myIsLoadingData = true;
882 aSession->closeAll();
883 aSession->load(myCurrentDir.toLatin1().constData());
884 myObjectBrowser->rebuildDataTree();
885 //displayAllResults();
886 updateCommandStatus();
887 myIsLoadingData = false;
888 QApplication::restoreOverrideCursor();
891 //******************************************************
892 bool XGUI_Workshop::onSave()
894 if(!isActiveOperationAborted())
896 if (myCurrentDir.isEmpty()) {
899 std::list<std::string> aFiles;
900 saveDocument(myCurrentDir, aFiles);
901 updateCommandStatus();
903 myMainWindow->setModifiedState(false);
907 //******************************************************
908 bool XGUI_Workshop::onSaveAs()
910 if(!isActiveOperationAborted())
912 QFileDialog dialog(mainWindow());
913 dialog.setWindowTitle(tr("Select directory to save files..."));
914 dialog.setFileMode(QFileDialog::Directory);
915 dialog.setFilter(tr("Folders (*)"));
916 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
917 dialog.setViewMode(QFileDialog::Detail);
919 if (!dialog.exec()) {
922 QString aTempDir = dialog.selectedFiles().first();
924 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
925 int answer = QMessageBox::question(
927 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
929 tr("The folder already contains some files, save anyway?"),
930 QMessageBox::Save | QMessageBox::Cancel);
931 if (answer == QMessageBox::Cancel) {
935 myCurrentDir = aTempDir;
936 if (!isSalomeMode()) {
937 myMainWindow->setCurrentDir(myCurrentDir, false);
938 myMainWindow->setModifiedState(false);
943 //******************************************************
944 void XGUI_Workshop::onUndo(int theTimes)
946 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
947 SessionPtr aMgr = ModelAPI_Session::get();
948 if (aMgr->isOperation())
949 operationMgr()->onAbortOperation();
950 for (int i = 0; i < theTimes; ++i) {
953 updateCommandStatus();
956 //******************************************************
957 void XGUI_Workshop::onRedo(int theTimes)
959 // the viewer update should be blocked in order to avoid the features blinking. For the created
960 // feature a results are created, the flush of the created signal caused the viewer redisplay for
961 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
962 // redo of all possible objects happens
963 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
965 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
966 SessionPtr aMgr = ModelAPI_Session::get();
967 if (aMgr->isOperation())
968 operationMgr()->onAbortOperation();
969 for (int i = 0; i < theTimes; ++i) {
972 updateCommandStatus();
974 // unblock the viewer update functionality and make update on purpose
975 myDisplayer->enableUpdateViewer(isUpdateEnabled);
976 myDisplayer->updateViewer();
979 //******************************************************
980 void XGUI_Workshop::onRebuild()
982 SessionPtr aMgr = ModelAPI_Session::get();
983 bool aWasOperation = aMgr->isOperation(); // keep this value
984 if (!aWasOperation) {
985 aMgr->startOperation("Rebuild");
987 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
988 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
989 new Events_Message(aRebuildEvent, this)));
990 if (!aWasOperation) {
991 aMgr->finishOperation();
993 updateCommandStatus();
996 //******************************************************
997 void XGUI_Workshop::onPreferences()
999 ModuleBase_Prefs aModif;
1000 ModuleBase_Preferences::editPreferences(aModif);
1001 if (aModif.size() > 0) {
1003 foreach (ModuleBase_Pref aPref, aModif)
1005 aSection = aPref.first;
1006 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1007 if (!isSalomeMode())
1008 myMainWindow->viewer()->updateFromResources();
1009 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1010 if (!isSalomeMode())
1011 myMainWindow->menuObject()->updateFromResources();
1017 //******************************************************
1018 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1020 QString libName = QString::fromStdString(library(theModule.toStdString()));
1021 if (libName.isEmpty()) {
1022 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1027 CREATE_FUNC crtInst = 0;
1030 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1034 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1035 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1036 QString aMsg((char*) &lpMsgBuf);
1037 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1038 ::LocalFree(lpMsgBuf);
1040 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1044 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1045 | FORMAT_MESSAGE_IGNORE_INSERTS,
1046 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1047 QString aMsg((char*) &lpMsgBuf);
1048 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1049 ::LocalFree(lpMsgBuf);
1053 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1055 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1057 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1059 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1064 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1066 if (!err.isEmpty()) {
1068 Events_Error::send(err.toStdString());
1070 qWarning(qPrintable(err));
1076 //******************************************************
1077 bool XGUI_Workshop::createModule()
1079 Config_ModuleReader aModuleReader;
1080 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1081 myModule = loadModule(moduleName);
1085 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1086 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1087 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1088 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1090 myModule->createFeatures();
1091 //myActionsMgr->update();
1095 //******************************************************
1096 void XGUI_Workshop::updateCommandStatus()
1098 QList<QAction*> aCommands;
1099 if (isSalomeMode()) { // update commands in SALOME mode
1100 aCommands = salomeConnector()->commandList();
1102 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1103 foreach (AppElements_Command* aCmd, aMenuBar->features())
1104 aCommands.append(aCmd);
1106 SessionPtr aMgr = ModelAPI_Session::get();
1107 if (aMgr->hasModuleDocument()) {
1108 QAction *aUndoCmd, *aRedoCmd;
1109 foreach(QAction* aCmd, aCommands) {
1110 QString aId = aCmd->data().toString();
1111 if (aId == "UNDO_CMD")
1113 else if (aId == "REDO_CMD")
1116 // Enable all commands
1117 aCmd->setEnabled(true);
1120 aUndoCmd->setEnabled(myModule->canUndo());
1121 aRedoCmd->setEnabled(myModule->canRedo());
1124 foreach(QAction* aCmd, aCommands) {
1125 QString aId = aCmd->data().toString();
1126 if (aId == "NEW_CMD")
1127 aCmd->setEnabled(true);
1128 else if (aId == "EXIT_CMD")
1129 aCmd->setEnabled(true);
1131 aCmd->setEnabled(false);
1134 myActionsMgr->update();
1135 emit commandStatusUpdated();
1138 void XGUI_Workshop::updateHistory()
1140 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1141 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1142 emit updateUndoHistory(aUndoRes);
1144 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1145 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1146 emit updateRedoHistory(aRedoRes);
1149 //******************************************************
1150 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1152 QDockWidget* aObjDock = new QDockWidget(theParent);
1153 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1154 aObjDock->setWindowTitle(tr("Object browser"));
1155 aObjDock->setStyleSheet(
1156 "::title { position: relative; padding-left: 5px; text-align: left center }");
1157 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1158 myObjectBrowser->setDataModel(myModule->dataModel());
1159 myModule->customizeObjectBrowser(myObjectBrowser);
1160 aObjDock->setWidget(myObjectBrowser);
1162 myContextMenuMgr->connectObjectBrowser();
1166 //******************************************************
1168 * Creates dock widgets, places them in corresponding area
1169 * and tabifies if necessary.
1171 void XGUI_Workshop::createDockWidgets()
1173 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1174 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1175 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1176 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1177 myPropertyPanel->setupActions(myActionsMgr);
1178 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1179 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1180 hidePropertyPanel(); ///<! Invisible by default
1181 hideObjectBrowser();
1182 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1183 myPropertyPanel->installEventFilter(myOperationMgr);
1185 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1186 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1187 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1188 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1189 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1190 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1191 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1192 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1193 aOkAct, SLOT(setEnabled(bool)));
1194 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1195 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
1196 aAcceptAllAct, SLOT(setEnabled(bool)));
1200 //******************************************************
1201 void XGUI_Workshop::showPropertyPanel()
1203 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1204 ///<! Restore ability to close panel from the window's menu
1205 aViewAct->setEnabled(true);
1206 myPropertyPanel->show();
1207 myPropertyPanel->raise();
1210 //******************************************************
1211 void XGUI_Workshop::hidePropertyPanel()
1213 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1214 ///<! Do not allow to show empty property panel
1215 aViewAct->setEnabled(false);
1216 myPropertyPanel->hide();
1219 //******************************************************
1220 void XGUI_Workshop::showObjectBrowser()
1222 myObjectBrowser->parentWidget()->show();
1225 //******************************************************
1226 void XGUI_Workshop::hideObjectBrowser()
1228 myObjectBrowser->parentWidget()->hide();
1231 //******************************************************
1232 //void XGUI_Workshop::onFeatureTriggered()
1234 // QAction* aCmd = dynamic_cast<QAction*>(sender());
1236 // QString aId = salomeConnector()->commandId(aCmd);
1237 // if (!aId.isNull())
1238 // myModule->launchOperation(aId);
1242 //******************************************************
1243 void XGUI_Workshop::salomeViewerSelectionChanged()
1245 emit salomeViewerSelection();
1248 //**************************************************************
1249 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1251 return mySalomeConnector->viewer();
1254 //**************************************************************
1255 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1257 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1258 if (theId == "DELETE_CMD")
1260 else if (theId == "COLOR_CMD")
1261 changeColor(aObjects);
1262 else if (theId == "SHOW_CMD")
1263 showObjects(aObjects, true);
1264 else if (theId == "HIDE_CMD")
1265 showObjects(aObjects, false);
1266 else if (theId == "SHOW_ONLY_CMD")
1267 showOnlyObjects(aObjects);
1268 else if (theId == "SHADING_CMD")
1269 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1270 else if (theId == "WIREFRAME_CMD")
1271 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1272 else if (theId == "HIDEALL_CMD") {
1273 QObjectPtrList aList = myDisplayer->displayedObjects();
1274 foreach (ObjectPtr aObj, aList)
1275 aObj->setDisplayed(false);
1276 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1280 //**************************************************************
1281 void XGUI_Workshop::deleteObjects()
1283 ModuleBase_IModule* aModule = module();
1284 // 1. allow the module to delete objects, do nothing if it has succeed
1285 if (aModule->deleteObjects()) {
1286 updateCommandStatus();
1290 if (!isActiveOperationAborted())
1292 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1293 bool hasResult = false;
1294 bool hasFeature = false;
1295 bool hasParameter = false;
1296 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1297 if (!(hasFeature || hasParameter))
1300 // 1. start operation
1301 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1302 aDescription += tr(" %1");
1303 QStringList aObjectNames;
1304 foreach (ObjectPtr aObj, anObjects) {
1305 if (!aObj->data()->isValid())
1307 aObjectNames << QString::fromStdString(aObj->data()->name());
1309 aDescription = aDescription.arg(aObjectNames.join(", "));
1311 SessionPtr aMgr = ModelAPI_Session::get();
1312 aMgr->startOperation(aDescription.toStdString());
1313 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1314 // this is performed in the RemoveFeature of Part object.
1315 /*foreach (ObjectPtr aObj, anObjects)
1317 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1319 DocumentPtr aDoc = aObj->document();
1320 if (aDoc == aMgr->activeDocument()) {
1325 // 3. delete objects
1326 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1327 std::set<FeaturePtr> anIgnoredFeatures;
1328 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1329 myDisplayer->updateViewer();
1330 aMgr->finishOperation();
1331 updateCommandStatus();
1334 aMgr->abortOperation();
1338 //**************************************************************
1339 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1340 std::set<FeaturePtr> theIgnoredFeatures,
1342 const bool theAskAboutDeleteReferences)
1344 // 1. find all referenced features
1345 std::set<FeaturePtr> aRefFeatures;
1346 foreach (ObjectPtr aDeletedObj, theList) {
1347 FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1348 if (aDeletedFeature.get() != NULL) {
1349 DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1350 // 1.1 find references in the current document
1351 aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1352 // 1.2 find references in all documents if the document of the feature is
1353 // "PartSet". Features of this document can be used in all other documents
1354 SessionPtr aMgr = ModelAPI_Session::get();
1355 DocumentPtr aModuleDoc = aMgr->moduleDocument();
1356 if (aDeletedFeatureDoc == aModuleDoc) {
1357 // the deleted feature and results of the feature should be found in references
1358 std::list<ObjectPtr> aDeletedObjects;
1359 aDeletedObjects.push_back(aDeletedFeature);
1360 typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1361 const ResultsList& aDeletedResults = aDeletedFeature->results();
1362 ResultsList::const_iterator aRIter = aDeletedResults.begin();
1363 for (; aRIter != aDeletedResults.cend(); aRIter++) {
1364 ResultPtr aRes = *aRIter;
1366 aDeletedObjects.push_back(aRes);
1368 // get all opened documents; found features in the documents;
1369 // get a list of objects where a feature refers;
1370 // search in these objects the deleted objects.
1371 std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1372 std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1373 aLast = anOpenedDocs.end();
1374 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1375 for (; anIt != aLast; anIt++) {
1376 DocumentPtr aDocument = *anIt;
1377 if (aDocument == aDeletedFeatureDoc)
1378 continue; // this document has been already processed in 1.1
1380 int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1381 for (int aId = 0; aId < aFeaturesCount; aId++) {
1382 ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1383 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1384 if (!aFeature.get())
1388 aFeature->data()->referencesToObjects(aRefs);
1389 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1390 bool aHasReferenceToDeleted = false;
1391 for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1392 std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1393 for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1394 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1395 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1396 aHasReferenceToDeleted = *aDelIt == *aRefObj;
1400 if (aHasReferenceToDeleted)
1401 aRefFeatures.insert(aFeature);
1407 // 2. warn about the references remove, break the delete operation if the user chose it
1408 if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1409 QStringList aRefNames;
1410 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1411 aLast = aRefFeatures.end();
1412 for (; anIt != aLast; anIt++) {
1413 aRefNames.append((*anIt)->name().c_str());
1415 QString aNames = aRefNames.join(", ");
1417 QMessageBox::StandardButton aRes = QMessageBox::warning(
1418 theParent, tr("Delete features"),
1419 QString(tr("Selected features are used in the following features: %1.\
1420 These features will be deleted also. Would you like to continue?")).arg(aNames),
1421 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1422 if (aRes != QMessageBox::Yes)
1426 // 3. remove referenced features
1427 std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1428 aLast = aRefFeatures.end();
1432 for (; anIt != aLast; anIt++) {
1433 FeaturePtr aFeature = (*anIt);
1434 DocumentPtr aDoc = aFeature->document();
1435 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1436 aDoc->removeFeature(aFeature);
1438 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1443 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1447 // 4. remove the parameter features
1448 foreach (ObjectPtr aObj, theList) {
1449 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1450 if (aResult.get() != NULL) { // results could not be removed,
1451 // they are removed by a corresponded feature remove
1454 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1456 // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1457 // part features are removed in the PartSet module. This condition should be moved there
1458 if (aFeature->getKind() == "Part")
1461 DocumentPtr aDoc = aObj->document();
1462 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1463 aDoc->removeFeature(aFeature);
1465 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1466 anInfo.append(anInfoStr);
1467 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1473 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1478 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1480 bool isFoundResultType = false;
1481 foreach(ObjectPtr anObj, theObjects)
1483 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1484 if (aResult.get() == NULL)
1487 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1488 if (isFoundResultType)
1491 return isFoundResultType;
1494 //**************************************************************
1495 bool XGUI_Workshop::canChangeColor() const
1497 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1499 std::set<std::string> aTypes;
1500 aTypes.insert(ModelAPI_ResultGroup::group());
1501 aTypes.insert(ModelAPI_ResultConstruction::group());
1502 aTypes.insert(ModelAPI_ResultBody::group());
1503 aTypes.insert(ModelAPI_ResultPart::group());
1505 return hasResults(aObjects, aTypes);
1508 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1510 if (!theResult.get())
1513 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1514 if (aColorAttr.get() != NULL) {
1515 if (!aColorAttr->size()) {
1516 aColorAttr->setSize(3);
1518 aColorAttr->setValue(0, theColor[0]);
1519 aColorAttr->setValue(1, theColor[1]);
1520 aColorAttr->setValue(2, theColor[2]);
1524 //**************************************************************
1525 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1527 AttributeIntArrayPtr aColorAttr;
1528 // 1. find the current color of the object. This is a color of AIS presentation
1529 // The objects are iterated until a first valid color is found
1530 std::vector<int> aColor;
1531 foreach(ObjectPtr anObject, theObjects) {
1532 if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1533 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1534 DocumentPtr aPartDoc = aPart->partDoc();
1535 // the document should be checked on null, because in opened document if the part
1536 // has not been activated yet, the part document is empty
1537 if (!aPartDoc.get()) {
1538 emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1541 if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1542 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1543 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1545 XGUI_CustomPrs::getResultColor(aBody, aColor);
1551 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1553 XGUI_CustomPrs::getResultColor(aResult, aColor);
1555 // TODO: remove the obtaining a color from the AIS object
1556 // this does not happen never because:
1557 // 1. The color can be changed only on results
1558 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1559 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1560 if (anAISObj.get()) {
1562 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1566 if (!aColor.empty())
1569 if (aColor.size() != 3)
1572 // 2. show the dialog to change the value
1573 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1574 aDlg->setColor(aColor);
1575 aDlg->move(QCursor::pos());
1576 bool isDone = aDlg->exec() == QDialog::Accepted;
1580 bool isRandomColor = aDlg->isRandomColor();
1582 // 3. abort the previous operation and start a new one
1583 SessionPtr aMgr = ModelAPI_Session::get();
1584 bool aWasOperation = aMgr->isOperation(); // keep this value
1585 if (!aWasOperation) {
1586 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1587 aMgr->startOperation(aDescription.toStdString());
1590 // 4. set the value to all results
1591 foreach(ObjectPtr anObj, theObjects) {
1592 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1593 if (aResult.get() != NULL) {
1594 if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1595 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1596 DocumentPtr aPartDoc = aPart->partDoc();
1597 // the document should be checked on null, because in opened document if the part
1598 // has not been activated yet, the part document is empty
1599 if (aPartDoc.get()) {
1600 for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1601 ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1602 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1603 std::vector<int> aColorResult = aDlg->getColor();
1604 setColor(aBody, aColorResult);
1609 std::vector<int> aColorResult = aDlg->getColor();
1610 setColor(aResult, aColorResult);
1615 aMgr->finishOperation();
1616 updateCommandStatus();
1619 //**************************************************************
1620 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1621 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1622 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1624 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1626 foreach (ObjectPtr aObj, theList) {
1627 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1629 DocumentPtr aDoc = aPartRes->partDoc();
1630 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1631 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1632 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1634 aObj->setDisplayed(isVisible);
1637 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1640 //**************************************************************
1641 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1643 // Hide all displayed objects
1644 QObjectPtrList aList = myDisplayer->displayedObjects();
1645 foreach (ObjectPtr aObj, aList)
1646 aObj->setDisplayed(false);
1648 // Show only objects from the list
1649 foreach (ObjectPtr aObj, theList) {
1650 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1652 DocumentPtr aDoc = aPartRes->partDoc();
1653 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1654 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1655 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1657 aObj->setDisplayed(true);
1660 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1665 //**************************************************************
1666 void XGUI_Workshop::registerValidators() const
1668 SessionPtr aMgr = ModelAPI_Session::get();
1669 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1672 //**************************************************************
1673 /*void XGUI_Workshop::displayAllResults()
1675 SessionPtr aMgr = ModelAPI_Session::get();
1676 DocumentPtr aRootDoc = aMgr->moduleDocument();
1677 displayDocumentResults(aRootDoc);
1678 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1679 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1680 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1681 displayDocumentResults(aPart->partDoc());
1683 myDisplayer->updateViewer();
1686 //**************************************************************
1687 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1691 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1692 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1695 //**************************************************************
1696 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1698 for (int i = 0; i < theDoc->size(theGroup); i++)
1699 theDoc->object(theGroup, i)->setDisplayed(true);
1700 //displayObject(theDoc->object(theGroup, i));
1701 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1704 //**************************************************************
1705 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1707 foreach(ObjectPtr aObj, theList) {
1708 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1710 if (theList.size() > 0)
1711 myDisplayer->updateViewer();
1714 //**************************************************************
1715 void XGUI_Workshop::closeDocument()
1717 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1718 while (anOperation) {
1719 anOperation->abort();
1720 anOperation = operationMgr()->currentOperation();
1722 myDisplayer->closeLocalContexts();
1723 myDisplayer->eraseAll();
1724 objectBrowser()->clearContent();
1726 SessionPtr aMgr = ModelAPI_Session::get();
1730 //**************************************************************
1731 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1733 if (!myModule->canDisplayObject(theObj))
1736 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1737 if (aBody.get() != NULL) {
1738 int aNb = myDisplayer->objectsCount();
1739 myDisplayer->display(theObj, false);
1742 } else if (!(myIsLoadingData || myPartActivating))
1743 myDisplayer->display(theObj, false);
1748 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1750 XGUI_HistoryMenu* aMenu = NULL;
1751 if (isSalomeMode()) {
1752 QAction* anAction = qobject_cast<QAction*>(theObject);
1755 aMenu = new XGUI_HistoryMenu(anAction);
1757 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1758 aMenu = new XGUI_HistoryMenu(aButton);
1760 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1761 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1764 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1766 QList<ActionInfo> aResult;
1767 std::list<std::string>::const_iterator it = theList.cbegin();
1768 for (; it != theList.cend(); it++) {
1769 QString anId = QString::fromStdString(*it);
1770 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1772 anId.chop(ModuleBase_Operation::EditSuffix().size());
1775 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1776 if (aContextMenuAct) {
1777 anInfo.initFrom(aContextMenuAct);
1779 anInfo = myActionsMgr->actionInfoById(anId);
1782 anInfo.text = anInfo.text.prepend("Modify ");