1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Workshop.h"
6 #include "XGUI_ActionsMgr.h"
7 #include "XGUI_ColorDialog.h"
8 #include "XGUI_ContextMenuMgr.h"
9 #include "XGUI_Displayer.h"
10 #include "XGUI_ErrorDialog.h"
11 #include "XGUI_ErrorMgr.h"
12 #include "XGUI_ModuleConnector.h"
13 #include "XGUI_ObjectsBrowser.h"
14 #include "XGUI_OperationMgr.h"
15 #include "XGUI_PropertyPanel.h"
16 #include "XGUI_SalomeConnector.h"
17 #include "XGUI_Selection.h"
18 #include "XGUI_SelectionMgr.h"
19 #include "XGUI_Tools.h"
20 #include "XGUI_ViewerProxy.h"
21 #include "XGUI_WorkshopListener.h"
22 #include <XGUI_CustomPrs.h>
23 #include <XGUI_HistoryMenu.h>
24 #include <XGUI_QtEvents.h>
27 #include <AppElements_Button.h>
28 #include <AppElements_Command.h>
29 #include <AppElements_MainMenu.h>
30 #include <AppElements_MainWindow.h>
31 #include <AppElements_MenuGroupPanel.h>
32 #include <AppElements_Viewer.h>
33 #include <AppElements_Workbench.h>
36 #include <ModelAPI_AttributeDocRef.h>
37 #include <ModelAPI_AttributeIntArray.h>
38 #include <ModelAPI_Data.h>
39 #include <ModelAPI_Events.h>
40 #include <ModelAPI_Feature.h>
41 #include <ModelAPI_Object.h>
42 #include <ModelAPI_ResultBody.h>
43 #include <ModelAPI_ResultConstruction.h>
44 #include <ModelAPI_ResultGroup.h>
45 #include <ModelAPI_ResultParameter.h>
46 #include <ModelAPI_Session.h>
47 #include <ModelAPI_Validator.h>
48 #include <ModelAPI_ResultCompSolid.h>
49 #include <ModelAPI_Tools.h>
51 //#include <PartSetPlugin_Part.h>
53 #include <Events_Loop.h>
54 #include <Events_Error.h>
55 #include <Events_LongOp.h>
57 #include <ModuleBase_FilterFactory.h>
58 #include <ModuleBase_IModule.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_Operation.h>
61 #include <ModuleBase_OperationDescription.h>
62 #include <ModuleBase_PageBase.h>
63 #include <ModuleBase_Preferences.h>
64 #include <ModuleBase_SelectionValidator.h>
65 #include <ModuleBase_Tools.h>
66 #include <ModuleBase_WidgetFactory.h>
67 #include <ModuleBase_OperationFeature.h>
68 #include <ModuleBase_OperationAction.h>
70 #include <Config_Common.h>
71 #include <Config_FeatureMessage.h>
72 #include <Config_ModuleReader.h>
73 #include <Config_PointerMessage.h>
74 #include <Config_PropManager.h>
75 #include <Config_SelectionFilterMessage.h>
77 #include <SUIT_ResourceMgr.h>
79 #include <QApplication>
80 #include <QFileDialog>
81 #include <QMessageBox>
82 #include <QMdiSubWindow>
83 #include <QMainWindow>
84 #include <QPushButton>
85 #include <QDockWidget>
90 #include <QToolButton>
92 #include <QDesktopWidget>
107 //#define DEBUG_DELETE
109 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
111 myCurrentDir(QString()),
113 mySalomeConnector(theConnector),
119 myMainWindow = new AppElements_MainWindow();
121 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
122 bool aCloc = aResMgr->booleanValue("language", "locale", true);
124 QLocale::setDefault( QLocale::c() );
126 QLocale::setDefault( QLocale::system() );
129 myDisplayer = new XGUI_Displayer(this);
131 mySelector = new XGUI_SelectionMgr(this);
132 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
134 myOperationMgr = new XGUI_OperationMgr(this, 0);
135 myActionsMgr = new XGUI_ActionsMgr(this);
136 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
137 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
138 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
139 SLOT(onContextMenuCommand(const QString&, bool)));
141 myViewerProxy = new XGUI_ViewerProxy(this);
142 connect(myViewerProxy, SIGNAL(selectionChanged()),
143 myActionsMgr, SLOT(updateOnViewSelection()));
145 myModuleConnector = new XGUI_ModuleConnector(this);
147 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
148 myOperationMgr->setWorkshop(aWorkshop);
150 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
151 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
153 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
154 SLOT(onOperationStarted(ModuleBase_Operation*)));
155 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
156 SLOT(onOperationResumed(ModuleBase_Operation*)));
157 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
158 SLOT(onOperationStopped(ModuleBase_Operation*)));
159 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
160 SLOT(onOperationCommitted(ModuleBase_Operation*)));
161 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
162 SLOT(onOperationAborted(ModuleBase_Operation*)));
163 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
164 // myErrorMgr, SLOT(onValidationStateChanged()));
167 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
170 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
171 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
172 myErrorDlg, SLOT(addError(const QString&)));
174 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
175 // Config_Prop::Color, "225,225,225");
177 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
178 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
179 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
180 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
181 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
182 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
183 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
184 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
187 //******************************************************
188 XGUI_Workshop::~XGUI_Workshop(void)
193 //******************************************************
194 void XGUI_Workshop::startApplication()
198 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
199 Config_Prop::Directory, "");
201 //Initialize event listening
202 myEventsListener->initializeEventListening();
204 registerValidators();
206 // Calling of loadCustomProps before activating module is required
207 // by Config_PropManger to restore user-defined path to plugins
208 ModuleBase_Preferences::loadCustomProps();
212 myMainWindow->show();
213 updateCommandStatus();
218 emit applicationStarted();
221 void XGUI_Workshop::activateModule()
223 myModule->activateSelectionFilters();
225 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
226 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
227 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
228 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
230 myActionsMgr->update();
232 // activate visualized objects in the viewer
233 XGUI_Displayer* aDisplayer = displayer();
234 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
236 module()->activeSelectionModes(aModes);
237 aDisplayer->activateObjects(aModes, aDisplayed);
240 void XGUI_Workshop::deactivateModule()
242 myModule->deactivateSelectionFilters();
244 // remove internal displayer filter
245 displayer()->deactivateSelectionFilters();
247 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
248 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
249 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
250 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
252 XGUI_Displayer* aDisplayer = displayer();
253 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
254 aDisplayer->deactivateObjects(aDisplayed, true);
257 //******************************************************
258 void XGUI_Workshop::initMenu()
260 myContextMenuMgr->createActions();
263 // Create only Undo, Redo commands
264 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
265 tr("Undo last command"),
266 QIcon(":pictures/undo.png"),
267 QKeySequence::Undo, false, "MEN_DESK_EDIT");
268 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
269 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
271 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
272 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
274 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
275 QIcon(":pictures/redo.png"), QKeySequence::Redo,
276 false, "MEN_DESK_EDIT");
277 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
279 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
280 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
282 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
283 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
284 QIcon(":pictures/rebuild.png"), QKeySequence(),
285 false, "MEN_DESK_EDIT");
286 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
288 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
289 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
291 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
292 QIcon(), QKeySequence(),
293 false, "MEN_DESK_FILE");
294 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
296 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
297 QIcon(), QKeySequence(),
298 false, "MEN_DESK_FILE");
299 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
300 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
303 // File commands group
304 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
306 AppElements_Command* aCommand;
308 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
309 QIcon(":pictures/save.png"), QKeySequence::Save);
310 aCommand->connectTo(this, SLOT(onSave()));
311 //aCommand->disable();
313 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
314 QIcon(":pictures/save.png"), QKeySequence());
315 aCommand->connectTo(this, SLOT(onSaveAs()));
317 QString aUndoId = "UNDO_CMD";
318 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
319 QIcon(":pictures/undo.png"), QKeySequence::Undo);
320 aCommand->connectTo(this, SLOT(onUndo()));
321 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
322 addHistoryMenu(aUndoButton,
323 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
326 QString aRedoId = "REDO_CMD";
327 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
328 QIcon(":pictures/redo.png"), QKeySequence::Redo);
329 aCommand->connectTo(this, SLOT(onRedo()));
330 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
331 addHistoryMenu(aRedoButton,
332 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
335 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
336 // QIcon(":pictures/rebuild.png"), QKeySequence());
337 //aCommand->connectTo(this, SLOT(onRebuild()));
339 //aCommand->disable();
341 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
342 QIcon(":pictures/open.png"), QKeySequence::Open);
343 aCommand->connectTo(this, SLOT(onOpen()));
345 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
346 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
347 aCommand->connectTo(this, SLOT(onPreferences()));
349 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
350 QIcon(":pictures/close.png"), QKeySequence::Close);
351 aCommand->connectTo(this, SLOT(onExit()));
356 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
358 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
359 return aMenuBar->addWorkbench(theName);
363 //******************************************************
364 QMainWindow* XGUI_Workshop::desktop() const
367 return salomeConnector()->desktop();
373 //******************************************************
374 void XGUI_Workshop::onStartWaiting()
376 if (Events_LongOp::isPerformed()) {
377 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
381 //******************************************************
382 void XGUI_Workshop::onAcceptActionClicked()
384 QAction* anAction = dynamic_cast<QAction*>(sender());
385 XGUI_OperationMgr* anOperationMgr = operationMgr();
386 if (anOperationMgr) {
387 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
388 (anOperationMgr->currentOperation());
390 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
391 myOperationMgr->onCommitOperation();
396 //******************************************************
397 /*void XGUI_Workshop::onValidationStateChanged(bool theEnabled)
399 XGUI_OperationMgr* anOperationMgr = operationMgr();
400 if (anOperationMgr) {
401 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
402 (anOperationMgr->currentOperation());
404 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
405 myErrorMgr->updateActionState(anAction, aFOperation->feature(), theEnabled);
411 //******************************************************
412 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
414 if (!myModule->canActivateSelection(theObject)) {
415 if (myDisplayer->isActive(theObject)) {
416 QObjectPtrList anObjects;
417 anObjects.append(theObject);
418 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
423 //******************************************************
424 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
426 bool aHasNested = false;
427 std::string aFeatureKind = theFeature->getKind();
429 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
430 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
433 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
434 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
435 if (aCommand && aCommand->button()->additionalButtonWidget())
441 //******************************************************
442 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
444 setGrantedFeatures(theOperation);
446 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
451 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
452 setPropertyPanel(aFOperation);
453 // filling the operation values by the current selection
454 // if the operation can be committed after the controls filling, the method perform should
455 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
456 if (!aFOperation->isEditOperation()) {
457 aFOperation->activateByPreselection();
458 if (operationMgr()->currentOperation() != aFOperation)
462 updateCommandStatus();
464 connectToPropertyPanel(true);
465 myModule->operationStarted(aFOperation);
467 // the objects of the current operation should be deactivated
468 QObjectPtrList anObjects;
469 FeaturePtr aFeature = aFOperation->feature();
470 anObjects.append(aFeature);
471 std::list<ResultPtr> aResults = aFeature->results();
472 std::list<ResultPtr>::const_iterator aIt;
473 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
474 anObjects.append(*aIt);
476 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
477 for (; anIt != aLast; anIt++)
478 deactivateActiveObject(*anIt, false);
479 if (anObjects.size() > 0)
480 myDisplayer->updateViewer();
483 //******************************************************
484 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
486 setGrantedFeatures(theOperation);
488 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
489 setPropertyPanel(theOperation);
490 connectToPropertyPanel(true);
492 updateCommandStatus();
494 myModule->operationResumed(theOperation);
498 //******************************************************
499 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
501 updateCommandStatus();
503 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
508 ModuleBase_ISelection* aSel = mySelector->selection();
509 QObjectPtrList aObj = aSel->selectedPresentations();
510 //!< No need for property panel
512 myPropertyPanel->cleanContent();
514 connectToPropertyPanel(false);
515 myModule->operationStopped(aFOperation);
517 // the deactivated objects of the current operation should be activated back.
518 // They were deactivated on operation start or an object redisplay
519 QObjectPtrList anObjects;
520 FeaturePtr aFeature = aFOperation->feature();
521 if (aFeature.get()) { // feature may be not created (plugin load fail)
522 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
523 anObjects.append(aFeature);
524 std::list<ResultPtr> aResults = aFeature->results();
525 std::list<ResultPtr>::const_iterator aIt;
526 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
527 ResultPtr anObject = *aIt;
528 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
529 anObjects.append(anObject);
534 module()->activeSelectionModes(aModes);
535 myDisplayer->activateObjects(aModes, anObjects);
539 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
541 myModule->operationCommitted(theOperation);
544 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
546 myModule->operationAborted(theOperation);
549 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
551 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
555 QStringList aGrantedIds;
557 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
559 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
561 ModuleBase_IModule* aModule = module();
563 aModule->grantedOperationIds(theOperation, aGrantedIds);
565 aFOperation->setGrantedOperationIds(aGrantedIds);
568 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
570 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
575 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
576 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
578 myPropertyPanel->cleanContent();
579 aFactory.createWidget(myPropertyPanel->contentWidget());
581 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
583 // check compatibility of feature and widgets
584 FeaturePtr aFeature = aFOperation->feature();
585 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
586 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
587 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
588 + aWidget->attributeID() + "' used by widget '"
589 + aWidget->metaObject()->className() + "'.";
590 Events_Error::send(anErrorMsg);
591 myPropertyPanel->cleanContent();
596 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
597 bool isStoreValue = !aFOperation->isEditOperation() &&
598 !aWidget->getDefaultValue().empty() &&
599 !aWidget->isComputedDefault();
600 aWidget->setFeature(aFOperation->feature(), isStoreValue);
601 aWidget->enableFocusProcessing();
604 myPropertyPanel->setModelWidgets(aWidgets);
605 aFOperation->setPropertyPanel(myPropertyPanel);
607 myModule->propertyPanelDefined(theOperation);
609 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
611 myErrorMgr->setPropertyPanel(myPropertyPanel);
614 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
616 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
617 if (aPropertyPanel) {
618 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
619 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
620 myModule->connectToPropertyPanel(aWidget, isToConnect);
622 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
625 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
632 * Saves document with given name.
634 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
636 QApplication::restoreOverrideCursor();
637 SessionPtr aMgr = ModelAPI_Session::get();
638 aMgr->save(theName.toLatin1().constData(), theFileNames);
639 QApplication::restoreOverrideCursor();
642 bool XGUI_Workshop::abortAllOperations()
644 return myOperationMgr->abortAllOperations();
647 //******************************************************
648 void XGUI_Workshop::onOpen()
650 if(!abortAllOperations())
652 //save current file before close if modified
653 SessionPtr aSession = ModelAPI_Session::get();
654 if (aSession->isModified()) {
655 //TODO(sbh): re-launch the app?
656 int anAnswer = QMessageBox::question(
657 desktop(), tr("Save current file"),
658 tr("The document is modified, save before opening another?"),
659 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
660 if (anAnswer == QMessageBox::Save) {
662 } else if (anAnswer == QMessageBox::Cancel) {
668 //show file dialog, check if readable and open
669 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
670 if (myCurrentDir.isEmpty())
672 QFileInfo aFileInfo(myCurrentDir);
673 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
674 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
678 QApplication::setOverrideCursor(Qt::WaitCursor);
679 aSession->closeAll();
680 aSession->load(myCurrentDir.toLatin1().constData());
681 myObjectBrowser->rebuildDataTree();
682 updateCommandStatus();
683 QApplication::restoreOverrideCursor();
686 //******************************************************
687 void XGUI_Workshop::onNew()
689 QApplication::setOverrideCursor(Qt::WaitCursor);
690 if (objectBrowser() == 0) {
692 mySelector->connectViewers();
694 myViewerProxy->connectToViewer();
697 myMainWindow->showPythonConsole();
698 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
699 aWnd->showMaximized();
700 updateCommandStatus();
702 myContextMenuMgr->connectViewer();
703 QApplication::restoreOverrideCursor();
707 //******************************************************
708 void XGUI_Workshop::onExit()
710 SessionPtr aMgr = ModelAPI_Session::get();
711 if (aMgr->isModified()) {
712 int anAnswer = QMessageBox::question(
713 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
714 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
715 if (anAnswer == QMessageBox::Save) {
716 bool saved = onSave();
720 } else if (anAnswer == QMessageBox::Cancel) {
727 //******************************************************
728 void XGUI_Workshop::onPreferences()
730 ModuleBase_Prefs aModif;
731 ModuleBase_Preferences::editPreferences(aModif);
732 if (aModif.size() > 0) {
734 foreach (ModuleBase_Pref aPref, aModif)
736 aSection = aPref.first;
737 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
738 myMainWindow->viewer()->updateFromResources();
739 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
740 myMainWindow->menuObject()->updateFromResources();
743 displayer()->redisplayObjects();
748 //******************************************************
749 bool XGUI_Workshop::onSave()
751 if(!abortAllOperations())
753 if (myCurrentDir.isEmpty()) {
756 std::list<std::string> aFiles;
757 saveDocument(myCurrentDir, aFiles);
758 updateCommandStatus();
760 myMainWindow->setModifiedState(false);
765 //******************************************************
766 bool XGUI_Workshop::onSaveAs()
768 if(!abortAllOperations())
770 QFileDialog dialog(desktop());
771 dialog.setWindowTitle(tr("Select directory to save files..."));
772 dialog.setFileMode(QFileDialog::Directory);
773 dialog.setFilter(tr("Directories (*)"));
774 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
775 dialog.setViewMode(QFileDialog::Detail);
777 if (!dialog.exec()) {
781 QString aTempDir = dialog.selectedFiles().first();
783 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
784 int answer = QMessageBox::question(
786 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
788 tr("The directory already contains some files, save anyway?"),
789 QMessageBox::Save | QMessageBox::Cancel);
790 if (answer == QMessageBox::Cancel) {
794 myCurrentDir = aTempDir;
796 myMainWindow->setCurrentDir(myCurrentDir, false);
797 myMainWindow->setModifiedState(false);
802 //******************************************************
803 void XGUI_Workshop::onUndo(int theTimes)
805 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
806 SessionPtr aMgr = ModelAPI_Session::get();
807 if (aMgr->isOperation()) {
808 /// this is important for nested operations
809 /// when sketch operation is active, this condition is false and
810 /// the sketch operation is not aborted
811 operationMgr()->onAbortOperation();
813 for (int i = 0; i < theTimes; ++i) {
817 operationMgr()->updateApplyOfOperations();
818 updateCommandStatus();
821 //******************************************************
822 void XGUI_Workshop::onRedo(int theTimes)
824 // the viewer update should be blocked in order to avoid the features blinking. For the created
825 // feature a results are created, the flush of the created signal caused the viewer redisplay for
826 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
827 // redo of all possible objects happens
828 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
830 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
831 SessionPtr aMgr = ModelAPI_Session::get();
832 if (aMgr->isOperation()) {
833 /// this is important for nested operations
834 /// when sketch operation is active, this condition is false and
835 /// the sketch operation is not aborted
836 operationMgr()->onAbortOperation();
838 for (int i = 0; i < theTimes; ++i) {
841 operationMgr()->updateApplyOfOperations();
842 updateCommandStatus();
844 // unblock the viewer update functionality and make update on purpose
845 myDisplayer->enableUpdateViewer(isUpdateEnabled);
846 myDisplayer->updateViewer();
849 //******************************************************
850 void XGUI_Workshop::onRebuild()
852 SessionPtr aMgr = ModelAPI_Session::get();
853 bool aWasOperation = aMgr->isOperation(); // keep this value
854 if (!aWasOperation) {
855 aMgr->startOperation("Rebuild");
857 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
858 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
859 new Events_Message(aRebuildEvent, this)));
860 if (!aWasOperation) {
861 aMgr->finishOperation();
863 updateCommandStatus();
866 //******************************************************
867 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
869 ModuleBase_ModelWidget* anActiveWidget = 0;
870 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
872 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
874 anActiveWidget = aPanel->activeWidget();
877 operationMgr()->onValidateOperation();
879 myModule->widgetStateChanged(thePreviousState);
882 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
884 QString libName = QString::fromStdString(library(theModule.toStdString()));
885 if (libName.isEmpty()) {
886 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
891 CREATE_FUNC crtInst = 0;
894 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
898 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
899 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
900 QString aMsg((char*) &lpMsgBuf);
901 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
902 ::LocalFree(lpMsgBuf);
904 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
908 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
909 | FORMAT_MESSAGE_IGNORE_INSERTS,
910 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
911 QString aMsg((char*) &lpMsgBuf);
912 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
913 ::LocalFree(lpMsgBuf);
917 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
919 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
921 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
923 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
928 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
930 if (!err.isEmpty()) {
932 Events_Error::send(err.toStdString());
934 qWarning(qPrintable(err));
940 //******************************************************
941 bool XGUI_Workshop::createModule()
943 Config_ModuleReader aModuleReader;
944 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
945 myModule = loadModule(moduleName);
949 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
950 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
951 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
952 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
954 myModule->createFeatures();
955 //myActionsMgr->update();
959 //******************************************************
960 void XGUI_Workshop::updateCommandStatus()
962 QList<QAction*> aCommands;
964 aCommands = salomeConnector()->commandList();
966 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
967 foreach (AppElements_Command* aCmd, aMenuBar->features())
968 aCommands.append(aCmd);
970 SessionPtr aMgr = ModelAPI_Session::get();
971 if (aMgr->hasModuleDocument()) {
972 foreach(QAction* aCmd, aCommands) {
973 QString aId = aCmd->data().toString();
974 if (aId == "UNDO_CMD")
975 aCmd->setEnabled(myModule->canUndo());
976 else if (aId == "REDO_CMD")
977 aCmd->setEnabled(myModule->canRedo());
979 // Enable all commands
980 aCmd->setEnabled(true);
984 foreach(QAction* aCmd, aCommands) {
985 QString aId = aCmd->data().toString();
986 if (aId == "NEW_CMD")
987 aCmd->setEnabled(true);
988 else if (aId == "EXIT_CMD")
989 aCmd->setEnabled(true);
991 aCmd->setEnabled(false);
994 myActionsMgr->update();
995 emit commandStatusUpdated();
998 void XGUI_Workshop::updateHistory()
1000 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1001 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1002 emit updateUndoHistory(aUndoRes);
1004 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1005 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1006 emit updateRedoHistory(aRedoRes);
1009 //******************************************************
1010 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1012 QDockWidget* aObjDock = new QDockWidget(theParent);
1013 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1014 aObjDock->setWindowTitle(tr("Object browser"));
1015 aObjDock->setStyleSheet(
1016 "::title { position: relative; padding-left: 5px; text-align: left center }");
1017 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1018 myModule->customizeObjectBrowser(myObjectBrowser);
1019 aObjDock->setWidget(myObjectBrowser);
1021 myContextMenuMgr->connectObjectBrowser();
1025 //******************************************************
1027 * Creates dock widgets, places them in corresponding area
1028 * and tabifies if necessary.
1030 void XGUI_Workshop::createDockWidgets()
1032 QMainWindow* aDesktop = desktop();
1033 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1034 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1035 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1036 myPropertyPanel->setupActions(myActionsMgr);
1037 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1038 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1039 hidePropertyPanel(); ///<! Invisible by default
1040 hideObjectBrowser();
1041 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1042 myPropertyPanel->installEventFilter(myOperationMgr);
1044 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1045 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1047 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1048 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1049 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1050 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1051 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1052 // this, SLOT(onValidationStateChanged(bool)));
1055 //******************************************************
1056 void XGUI_Workshop::showPropertyPanel()
1058 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1059 ///<! Restore ability to close panel from the window's menu
1060 aViewAct->setEnabled(true);
1061 myPropertyPanel->show();
1062 myPropertyPanel->raise();
1064 // The next code is necessary to made the property panel the active window
1065 // in order to operation manager could process key events of the panel.
1066 // otherwise they are ignored. It happens only if the same(activateWindow) is
1067 // not happened by property panel activation(e.g. resume operation of Sketch)
1068 myPropertyPanel->activateWindow();
1069 myPropertyPanel->setFocus();
1072 //******************************************************
1073 void XGUI_Workshop::hidePropertyPanel()
1075 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1076 ///<! Do not allow to show empty property panel
1077 aViewAct->setEnabled(false);
1078 myPropertyPanel->hide();
1080 // the property panel is active window of the desktop, when it is
1081 // hidden, it is undefined which window becomes active. By this reason
1082 // it is defined to perform the desktop as the active window.
1083 // in SALOME mode, workstack made the PyConsole the active window,
1084 // set the focus on it. As a result, shortcuts of the application, like
1085 // are processed by this console. For example Undo actions.
1086 // It is possible that this code is to be moved to NewGeom package
1087 QMainWindow* aDesktop = desktop();
1088 aDesktop->activateWindow();
1089 aDesktop->setFocus();
1092 //******************************************************
1093 void XGUI_Workshop::showObjectBrowser()
1095 myObjectBrowser->parentWidget()->show();
1098 //******************************************************
1099 void XGUI_Workshop::hideObjectBrowser()
1101 myObjectBrowser->parentWidget()->hide();
1104 //******************************************************
1105 void XGUI_Workshop::salomeViewerSelectionChanged()
1107 emit salomeViewerSelection();
1110 //**************************************************************
1111 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1113 return mySalomeConnector->viewer();
1116 //**************************************************************
1117 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1119 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1120 if (theId == "DELETE_CMD")
1122 else if (theId == "MOVE_CMD")
1124 else if (theId == "COLOR_CMD")
1125 changeColor(aObjects);
1126 else if (theId == "SHOW_CMD")
1127 showObjects(aObjects, true);
1128 else if (theId == "HIDE_CMD")
1129 showObjects(aObjects, false);
1130 else if (theId == "SHOW_ONLY_CMD")
1131 showOnlyObjects(aObjects);
1132 else if (theId == "SHADING_CMD")
1133 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1134 else if (theId == "WIREFRAME_CMD")
1135 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1136 else if (theId == "HIDEALL_CMD") {
1137 QObjectPtrList aList = myDisplayer->displayedObjects();
1138 foreach (ObjectPtr aObj, aList) {
1139 if (module()->canEraseObject(aObj))
1140 aObj->setDisplayed(false);
1142 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1146 //**************************************************************
1147 void XGUI_Workshop::deleteObjects()
1149 ModuleBase_IModule* aModule = module();
1150 // 1. allow the module to delete objects, do nothing if it has succeed
1151 if (aModule->deleteObjects()) {
1152 updateCommandStatus();
1156 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1157 if (!abortAllOperations())
1159 // It is necessary to clear selection in order to avoid selection changed event during
1160 // deletion and negative consequences connected with processing of already deleted items
1161 mySelector->clearSelection();
1162 // check whether the object can be deleted. There should not be parts which are not loaded
1163 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1166 bool hasResult = false;
1167 bool hasFeature = false;
1168 bool hasParameter = false;
1169 bool hasSubFeature = false;
1170 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1171 if (!(hasFeature || hasParameter))
1174 // 1. start operation
1175 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1176 aDescription += tr(" %1");
1177 QStringList aObjectNames;
1178 foreach (ObjectPtr aObj, anObjects) {
1179 if (!aObj->data()->isValid())
1181 aObjectNames << QString::fromStdString(aObj->data()->name());
1183 aDescription = aDescription.arg(aObjectNames.join(", "));
1184 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1186 operationMgr()->startOperation(anOpAction);
1187 // 3. delete objects
1188 std::set<FeaturePtr> anIgnoredFeatures;
1189 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1190 operationMgr()->commitOperation();
1193 operationMgr()->abortOperation(operationMgr()->currentOperation());
1197 //**************************************************************
1198 void XGUI_Workshop::moveObjects()
1200 if (!abortAllOperations())
1203 SessionPtr aMgr = ModelAPI_Session::get();
1205 QString anActionId = "MOVE_CMD";
1206 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1207 aMgr->startOperation(aDescription.toStdString());
1209 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1210 // It is necessary to clear selection in order to avoid selection changed event during
1211 // moving and negative consequences connected with processing of already moved items
1212 mySelector->clearSelection();
1213 // check whether the object can be moved. There should not be parts which are not loaded
1214 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1217 DocumentPtr anActiveDocument = aMgr->activeDocument();
1218 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1219 foreach (ObjectPtr aObject, anObjects) {
1220 if (!myModule->canApplyAction(aObject, anActionId))
1223 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1224 if (aFeature.get()) {
1225 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1226 aCurrentFeature = anActiveDocument->currentFeature(true);
1229 aMgr->finishOperation();
1232 //**************************************************************
1233 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1234 const std::set<FeaturePtr>& theIgnoredFeatures,
1236 const bool theAskAboutDeleteReferences)
1240 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1241 for (; aDIt != aDLast; ++aDIt) {
1242 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1244 QString anInfoStr = aDInfo.join(", ");
1245 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1248 // 1. find all referenced features
1249 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1250 foreach (ObjectPtr aDeletedObj, theList) {
1251 std::set<FeaturePtr> alreadyProcessed;
1252 XGUI_Tools::refsToFeatureInAllDocuments(
1253 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1254 std::set<FeaturePtr> aDifference;
1255 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1256 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1257 std::inserter(aDifference, aDifference.begin()));
1258 aIndirectRefFeatures = aDifference;
1261 bool doDeleteReferences = true;
1263 // 2. warn about the references remove, break the delete operation if the user chose it
1264 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1265 QStringList aDirectRefNames;
1266 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1267 aDirectRefNames.append(aFeature->name().c_str());
1268 QString aDirectNames = aDirectRefNames.join(", ");
1270 QStringList aIndirectRefNames;
1271 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1272 aIndirectRefNames.append(aFeature->name().c_str());
1273 QString aIndirectNames = aIndirectRefNames.join(", ");
1275 bool canReplaceParameters = true;
1276 foreach (ObjectPtr aObj, theList) {
1277 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1278 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1279 canReplaceParameters = false;
1284 QMessageBox aMessageBox(theParent);
1285 aMessageBox.setWindowTitle(tr("Delete features"));
1286 aMessageBox.setIcon(QMessageBox::Warning);
1287 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1288 aMessageBox.setDefaultButton(QMessageBox::No);
1291 if (canReplaceParameters) {
1292 aText = QString(tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\n%2Or parameters could be replaced by their values.\nWould you like to continue?"))
1293 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1294 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1296 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1297 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1299 aMessageBox.setText(aText);
1301 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1303 if (aButtonRole == QMessageBox::NoRole)
1306 if (aButtonRole == QMessageBox::ActionRole) {
1307 foreach (ObjectPtr aObj, theList)
1308 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1309 doDeleteReferences = false;
1313 // 3. remove referenced features
1314 if (doDeleteReferences) {
1315 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1316 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1317 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1318 aLast = aFeaturesToDelete.end();
1322 for (; anIt != aLast; anIt++) {
1323 FeaturePtr aFeature = (*anIt);
1324 DocumentPtr aDoc = aFeature->document();
1325 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1326 aDoc->removeFeature(aFeature);
1328 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1333 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1338 QString anActionId = "DELETE_CMD";
1339 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1340 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1341 // 4. remove the parameter features
1342 foreach (ObjectPtr aObj, theList) {
1343 // features and parameters can be removed here,
1344 // the results are removed only by a corresponded feature remove
1345 std::string aGroupName = aObj->groupName();
1346 if (!anObjectGroups.contains(aGroupName.c_str()))
1349 if (!myModule->canApplyAction(aObj, anActionId))
1352 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1354 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1355 // part features are removed in the PartSet module. This condition should be moved there
1356 if (aFeature->getKind() == "Part")
1359 DocumentPtr aDoc = aObj->document();
1360 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1362 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1363 anInfo.append(anInfoStr);
1364 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1366 aDoc->removeFeature(aFeature);
1371 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1376 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1378 bool isFoundResultType = false;
1379 foreach(ObjectPtr anObj, theObjects)
1381 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1382 if (aResult.get() == NULL)
1385 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1386 if (isFoundResultType)
1389 return isFoundResultType;
1392 //**************************************************************
1393 // Returns the list of all features for theDocument and all features of
1394 // all nested parts.
1395 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1397 std::list<FeaturePtr> aResultList;
1398 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1399 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1400 // The order of appending features of the part and the part itself is important
1402 // Append features from a part feature
1403 foreach (const ResultPtr& aResult, aFeature->results()) {
1404 ResultPartPtr aResultPart =
1405 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1406 if (aResultPart.get() && aResultPart->partDoc().get()) {
1408 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1409 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1413 aResultList.push_back(aFeature);
1418 //**************************************************************
1419 // Returns the list of features placed between theObject and the current feature
1420 // in the same document. Excludes theObject, includes the current feature.
1421 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1423 std::list<FeaturePtr> aResult;
1424 DocumentPtr aDocument = theObject->document();
1425 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1426 // find the object iterator
1427 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1428 if (aObjectIt == anAllFeatures.end())
1430 // find the current feature iterator
1431 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1432 if (aCurrentIt == anAllFeatures.end())
1434 // check the right order
1435 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1437 // exclude the object
1438 std::advance(aObjectIt, 1);
1439 // include the current feature
1440 std::advance(aCurrentIt, 1);
1441 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1444 bool XGUI_Workshop::canMoveFeature()
1446 QString anActionId = "MOVE_CMD";
1448 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1449 QObjectPtrList aValidatedObjects;
1450 foreach (ObjectPtr aObject, aObjects) {
1451 if (!myModule->canApplyAction(aObject, anActionId))
1453 // To be moved feature should be in active document
1454 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1456 aValidatedObjects.append(aObject);
1458 if (aValidatedObjects.size() != aObjects.size())
1459 aObjects = aValidatedObjects;
1461 bool aCanMove = !aObjects.empty();
1463 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1464 for (; anIt != aLast && aCanMove; anIt++) {
1465 ObjectPtr aObject = *anIt;
1466 // 1. Get features placed between selected and current in the document
1467 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1468 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1469 if (aFeaturesBetween.empty())
1472 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1473 // 2. Get all reference features to the selected object in the document
1474 std::set<FeaturePtr> aRefFeatures;
1475 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1477 if (aRefFeatures.empty())
1480 // 3. Find any placed features in all reference features
1481 std::set<FeaturePtr> aIntersectionFeatures;
1482 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1483 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1484 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1485 // 4. Return false if any reference feature is placed before current feature
1486 if (!aIntersectionFeatures.empty())
1494 //**************************************************************
1495 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1497 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1498 if (!aCanBeShaded) {
1499 ResultCompSolidPtr aCompsolidResult =
1500 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1501 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1502 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1503 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1506 return aCanBeShaded;
1509 //**************************************************************
1510 bool XGUI_Workshop::canChangeColor() const
1512 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1514 std::set<std::string> aTypes;
1515 aTypes.insert(ModelAPI_ResultGroup::group());
1516 aTypes.insert(ModelAPI_ResultConstruction::group());
1517 aTypes.insert(ModelAPI_ResultBody::group());
1518 aTypes.insert(ModelAPI_ResultPart::group());
1520 return hasResults(aObjects, aTypes);
1523 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1525 if (!theResult.get())
1528 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1529 if (aColorAttr.get() != NULL) {
1530 if (!aColorAttr->size()) {
1531 aColorAttr->setSize(3);
1533 aColorAttr->setValue(0, theColor[0]);
1534 aColorAttr->setValue(1, theColor[1]);
1535 aColorAttr->setValue(2, theColor[2]);
1539 //**************************************************************
1540 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1543 AttributeIntArrayPtr aColorAttr;
1544 // 1. find the current color of the object. This is a color of AIS presentation
1545 // The objects are iterated until a first valid color is found
1546 std::vector<int> aColor;
1547 foreach(ObjectPtr anObject, theObjects) {
1548 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1549 if (aResult.get()) {
1550 XGUI_CustomPrs::getResultColor(aResult, aColor);
1553 // TODO: remove the obtaining a color from the AIS object
1554 // this does not happen never because:
1555 // 1. The color can be changed only on results
1556 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1557 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1558 if (anAISObj.get()) {
1560 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1563 if (!aColor.empty())
1566 if (aColor.size() != 3)
1569 if (!abortAllOperations())
1571 // 2. show the dialog to change the value
1572 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1573 aDlg->setColor(aColor);
1574 aDlg->move(QCursor::pos());
1575 bool isDone = aDlg->exec() == QDialog::Accepted;
1579 bool isRandomColor = aDlg->isRandomColor();
1581 // 3. abort the previous operation and start a new one
1582 SessionPtr aMgr = ModelAPI_Session::get();
1583 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1584 aMgr->startOperation(aDescription.toStdString());
1586 // 4. set the value to all results
1587 std::vector<int> aColorResult = aDlg->getColor();
1588 foreach(ObjectPtr anObj, theObjects) {
1589 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1590 if (aResult.get() != NULL) {
1591 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1592 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1593 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1594 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1597 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1600 aMgr->finishOperation();
1601 updateCommandStatus();
1604 //**************************************************************
1605 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1606 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1607 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1609 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1611 foreach (ObjectPtr aObj, theList) {
1613 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1615 DocumentPtr aDoc = aPartRes->partDoc();
1616 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1617 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1618 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1621 aObj->setDisplayed(isVisible);
1624 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1627 //**************************************************************
1628 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1630 // Hide all displayed objects
1631 QObjectPtrList aList = myDisplayer->displayedObjects();
1632 foreach (ObjectPtr aObj, aList) {
1633 if (module()->canEraseObject(aObj))
1634 aObj->setDisplayed(false);
1637 // Show only objects from the list
1638 foreach (ObjectPtr aObj, theList) {
1640 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1642 DocumentPtr aDoc = aPartRes->partDoc();
1643 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1644 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1645 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1648 aObj->setDisplayed(true);
1651 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1656 //**************************************************************
1657 void XGUI_Workshop::registerValidators() const
1659 SessionPtr aMgr = ModelAPI_Session::get();
1660 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1663 //**************************************************************
1664 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1668 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1669 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1672 //**************************************************************
1673 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1675 for (int i = 0; i < theDoc->size(theGroup); i++)
1676 theDoc->object(theGroup, i)->setDisplayed(true);
1677 //displayObject(theDoc->object(theGroup, i));
1678 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1681 //**************************************************************
1682 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1684 foreach(ObjectPtr aObj, theList) {
1685 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1687 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1688 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1689 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1690 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1691 (XGUI_Displayer::DisplayMode)theMode, false);
1695 if (theList.size() > 0)
1696 myDisplayer->updateViewer();
1699 //**************************************************************
1700 void XGUI_Workshop::closeDocument()
1702 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1703 while (anOperation) {
1704 anOperation->abort();
1705 anOperation = operationMgr()->currentOperation();
1707 myDisplayer->closeLocalContexts();
1708 myDisplayer->eraseAll();
1709 objectBrowser()->clearContent();
1711 module()->closeDocument();
1713 SessionPtr aMgr = ModelAPI_Session::get();
1717 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1719 XGUI_HistoryMenu* aMenu = NULL;
1720 if (isSalomeMode()) {
1721 QAction* anAction = qobject_cast<QAction*>(theObject);
1724 aMenu = new XGUI_HistoryMenu(anAction);
1726 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1727 aMenu = new XGUI_HistoryMenu(aButton);
1729 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1730 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1733 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1735 QList<ActionInfo> aResult;
1736 std::list<std::string>::const_iterator it = theList.cbegin();
1737 for (; it != theList.cend(); it++) {
1738 QString anId = QString::fromStdString(*it);
1739 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1741 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1744 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1745 if (aContextMenuAct) {
1746 anInfo.initFrom(aContextMenuAct);
1748 anInfo = myActionsMgr->actionInfoById(anId);
1751 anInfo.text = anInfo.text.prepend("Modify ");
1758 void XGUI_Workshop::synchronizeViewer()
1760 SessionPtr aMgr = ModelAPI_Session::get();
1761 DocumentPtr aDoc = aMgr->activeDocument();
1763 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1764 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1765 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1766 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1769 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1770 const std::string& theGroup,
1771 bool theUpdateViewer)
1774 int aSize = theDoc->size(theGroup);
1775 for (int i = 0; i < aSize; i++) {
1776 aObj = theDoc->object(theGroup, i);
1777 if (aObj->isDisplayed())
1778 myDisplayer->display(aObj, false);
1780 if (theUpdateViewer)
1781 myDisplayer->updateViewer();