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_MenuMgr.h"
8 #include "XGUI_ColorDialog.h"
9 #include "XGUI_ContextMenuMgr.h"
10 #include "XGUI_Displayer.h"
11 #include "XGUI_ErrorDialog.h"
12 #include "XGUI_ErrorMgr.h"
13 #include "XGUI_ModuleConnector.h"
14 #include "XGUI_ObjectsBrowser.h"
15 #include "XGUI_OperationMgr.h"
16 #include "XGUI_PropertyPanel.h"
17 #include "XGUI_SalomeConnector.h"
18 #include "XGUI_Selection.h"
19 #include "XGUI_SelectionMgr.h"
20 #include "XGUI_Tools.h"
21 #include "XGUI_ViewerProxy.h"
22 #include "XGUI_WorkshopListener.h"
23 #include <XGUI_CustomPrs.h>
24 #include <XGUI_HistoryMenu.h>
25 #include <XGUI_QtEvents.h>
28 #include <AppElements_Button.h>
29 #include <AppElements_Command.h>
30 #include <AppElements_MainMenu.h>
31 #include <AppElements_MainWindow.h>
32 #include <AppElements_MenuGroupPanel.h>
33 #include <AppElements_Viewer.h>
34 #include <AppElements_Workbench.h>
37 #include <ModelAPI_AttributeDocRef.h>
38 #include <ModelAPI_AttributeIntArray.h>
39 #include <ModelAPI_Data.h>
40 #include <ModelAPI_Events.h>
41 #include <ModelAPI_Feature.h>
42 #include <ModelAPI_Object.h>
43 #include <ModelAPI_ResultBody.h>
44 #include <ModelAPI_ResultConstruction.h>
45 #include <ModelAPI_ResultGroup.h>
46 #include <ModelAPI_ResultParameter.h>
47 #include <ModelAPI_Session.h>
48 #include <ModelAPI_Validator.h>
49 #include <ModelAPI_ResultCompSolid.h>
50 #include <ModelAPI_Tools.h>
52 //#include <PartSetPlugin_Part.h>
54 #include <Events_Loop.h>
55 #include <Events_Error.h>
56 #include <Events_LongOp.h>
58 #include <ModuleBase_FilterFactory.h>
59 #include <ModuleBase_IModule.h>
60 #include <ModuleBase_IViewer.h>
61 #include <ModuleBase_Operation.h>
62 #include <ModuleBase_OperationDescription.h>
63 #include <ModuleBase_PageBase.h>
64 #include <ModuleBase_Preferences.h>
65 #include <ModuleBase_SelectionValidator.h>
66 #include <ModuleBase_Tools.h>
67 #include <ModuleBase_WidgetFactory.h>
68 #include <ModuleBase_OperationFeature.h>
69 #include <ModuleBase_OperationAction.h>
70 #include <ModuleBase_PagedContainer.h>
71 #include <ModuleBase_WidgetValidated.h>
72 #include <ModuleBase_ModelWidget.h>
74 #include <Config_Common.h>
75 #include <Config_FeatureMessage.h>
76 #include <Config_ModuleReader.h>
77 #include <Config_PointerMessage.h>
78 #include <Config_PropManager.h>
79 #include <Config_SelectionFilterMessage.h>
80 #include <Config_DataModelReader.h>
82 #include <SUIT_ResourceMgr.h>
84 #include <QApplication>
85 #include <QFileDialog>
86 #include <QMessageBox>
87 #include <QMdiSubWindow>
88 #include <QMainWindow>
89 #include <QPushButton>
90 #include <QDockWidget>
95 #include <QToolButton>
97 #include <QDesktopWidget>
113 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
115 //#define DEBUG_DELETE
116 //#define DEBUG_FEATURE_NAME
118 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
120 myCurrentDir(QString()),
122 mySalomeConnector(theConnector),
126 myViewerSelMode(TopAbs_FACE)
129 myMainWindow = new AppElements_MainWindow();
131 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
132 bool aCloc = aResMgr->booleanValue("language", "locale", true);
134 QLocale::setDefault( QLocale::c() );
136 QLocale::setDefault( QLocale::system() );
139 myDataModelXMLReader = new Config_DataModelReader();
140 myDataModelXMLReader->readAll();
142 myDisplayer = new XGUI_Displayer(this);
144 mySelector = new XGUI_SelectionMgr(this);
145 connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
147 myOperationMgr = new XGUI_OperationMgr(this, 0);
148 myActionsMgr = new XGUI_ActionsMgr(this);
149 myMenuMgr = new XGUI_MenuMgr(this);
150 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
151 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
152 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
153 SLOT(onContextMenuCommand(const QString&, bool)));
155 myViewerProxy = new XGUI_ViewerProxy(this);
156 //connect(myViewerProxy, SIGNAL(selectionChanged()),
157 // myActionsMgr, SLOT(updateOnViewSelection()));
159 myModuleConnector = new XGUI_ModuleConnector(this);
161 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
162 myOperationMgr->setWorkshop(aWorkshop);
164 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
165 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
167 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
168 SLOT(onOperationStarted(ModuleBase_Operation*)));
169 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
170 SLOT(onOperationResumed(ModuleBase_Operation*)));
171 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
172 SLOT(onOperationStopped(ModuleBase_Operation*)));
173 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
174 SLOT(onOperationCommitted(ModuleBase_Operation*)));
175 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
176 SLOT(onOperationAborted(ModuleBase_Operation*)));
179 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
180 onTrihedronVisibilityChanged(true);
183 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
184 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
185 myErrorDlg, SLOT(addError(const QString&)));
187 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
188 // Config_Prop::Color, "225,225,225");
190 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
191 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
192 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
193 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
194 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
195 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
196 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
197 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
200 ModuleBase_Preferences::resourceMgr()->integerValue("Viewer", "selection", TopAbs_FACE);
203 //******************************************************
204 XGUI_Workshop::~XGUI_Workshop(void)
207 delete myDataModelXMLReader;
210 //******************************************************
211 void XGUI_Workshop::startApplication()
215 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
216 Config_Prop::Directory, "");
218 //Initialize event listening
219 myEventsListener->initializeEventListening();
221 registerValidators();
223 // Calling of loadCustomProps before activating module is required
224 // by Config_PropManger to restore user-defined path to plugins
225 ModuleBase_Preferences::loadCustomProps();
229 myMainWindow->show();
230 updateCommandStatus();
235 myViewerProxy->connectViewProxy();
236 connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
237 SLOT(onTrihedronVisibilityChanged(bool)));
239 emit applicationStarted();
242 void XGUI_Workshop::activateModule()
244 myModule->activateSelectionFilters();
246 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
247 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
248 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
249 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
251 updateCommandStatus();
253 // TODO: get default selection mode
255 // activate visualized objects in the viewer
256 activateObjectsSelection(displayer()->displayedObjects());
257 myOperationMgr->activate();
260 void XGUI_Workshop::deactivateModule()
262 myModule->deactivateSelectionFilters();
264 // remove internal displayer filter
265 displayer()->deactivateSelectionFilters();
267 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
268 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
269 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
270 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
272 XGUI_Displayer* aDisplayer = displayer();
273 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
274 aDisplayer->deactivateObjects(aDisplayed, true);
276 myOperationMgr->deactivate();
279 //******************************************************
280 void XGUI_Workshop::initMenu()
282 myContextMenuMgr->createActions();
285 // Create only Undo, Redo commands
286 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
287 tr("Undo last command"),
288 QIcon(":pictures/undo.png"),
289 QKeySequence::Undo, false, "MEN_DESK_EDIT");
290 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
291 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
293 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
294 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
296 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
297 QIcon(":pictures/redo.png"), QKeySequence::Redo,
298 false, "MEN_DESK_EDIT");
299 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
301 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
302 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
304 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
305 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
306 // QIcon(":pictures/rebuild.png"), QKeySequence(),
307 // false, "MEN_DESK_EDIT");
308 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
310 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
311 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
313 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."), tr("Export the current document into a native file"),
314 QIcon(), QKeySequence(),
315 false, "MEN_DESK_FILE");
316 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
318 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."), tr("Import native file"),
319 QIcon(), QKeySequence(),
320 false, "MEN_DESK_FILE");
321 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
322 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
325 // File commands group
326 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
328 AppElements_Command* aCommand;
330 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
331 QIcon(":pictures/save.png"), QKeySequence::Save);
332 aCommand->connectTo(this, SLOT(onSave()));
333 //aCommand->disable();
335 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
336 QIcon(":pictures/save.png"), QKeySequence());
337 aCommand->connectTo(this, SLOT(onSaveAs()));
339 QString aUndoId = "UNDO_CMD";
340 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
341 QIcon(":pictures/undo.png"), QKeySequence::Undo);
342 aCommand->connectTo(this, SLOT(onUndo()));
343 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
344 addHistoryMenu(aUndoButton,
345 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
348 QString aRedoId = "REDO_CMD";
349 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
350 QIcon(":pictures/redo.png"), QKeySequence::Redo);
351 aCommand->connectTo(this, SLOT(onRedo()));
352 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
353 addHistoryMenu(aRedoButton,
354 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
357 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
358 // QIcon(":pictures/rebuild.png"), QKeySequence());
359 //aCommand->connectTo(this, SLOT(onRebuild()));
361 //aCommand->disable();
363 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
364 QIcon(":pictures/open.png"), QKeySequence::Open);
365 aCommand->connectTo(this, SLOT(onOpen()));
367 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
368 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
369 aCommand->connectTo(this, SLOT(onPreferences()));
371 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
372 QIcon(":pictures/close.png"), QKeySequence::Close);
373 aCommand->connectTo(this, SLOT(onExit()));
378 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
380 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
381 return aMenuBar->addWorkbench(theName);
385 //******************************************************
386 QMainWindow* XGUI_Workshop::desktop() const
389 return salomeConnector()->desktop();
395 //******************************************************
396 void XGUI_Workshop::onStartWaiting()
398 if (Events_LongOp::isPerformed()) {
399 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
403 //******************************************************
404 void XGUI_Workshop::onAcceptActionClicked()
406 QAction* anAction = dynamic_cast<QAction*>(sender());
407 XGUI_OperationMgr* anOperationMgr = operationMgr();
408 if (anOperationMgr) {
409 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
410 (anOperationMgr->currentOperation());
412 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
413 myOperationMgr->onCommitOperation();
418 //******************************************************
419 void XGUI_Workshop::onPreviewActionClicked()
421 ModuleBase_IPropertyPanel* aPanel = propertyPanel();
423 ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
424 if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
425 anActiveWidget->storeValue();
428 std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
429 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
430 Events_Loop::loop()->send(aMsg);
433 //******************************************************
434 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
436 if (!myModule->canActivateSelection(theObject)) {
437 if (myDisplayer->isActive(theObject)) {
438 QObjectPtrList anObjects;
439 anObjects.append(theObject);
440 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
445 //******************************************************
446 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
448 bool aHasNested = false;
449 std::string aFeatureKind = theFeature->getKind();
451 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
452 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
455 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
456 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
457 if (aCommand && aCommand->button()->additionalButtonWidget())
463 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
465 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
470 myPropertyPanel->cleanContent();
472 QList<ModuleBase_ModelWidget*> aWidgets;
473 if (!module()->createWidgets(theOperation, aWidgets)) {
474 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
475 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
476 aFactory.createWidget(myPropertyPanel->contentWidget());
477 aWidgets = aFactory.getModelWidgets();
480 // check compatibility of feature and widgets
481 FeaturePtr aFeature = aFOperation->feature();
482 std::string aFeatureKind = aFeature->getKind();
483 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
484 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
485 std::string anErrorMsg = "The feature '" + aFeatureKind + "' has no attribute '"
486 + aWidget->attributeID() + "' used by widget '"
487 + aWidget->metaObject()->className() + "'.";
488 Events_Error::send(anErrorMsg);
489 myPropertyPanel->cleanContent();
493 // for performance purpose, flush should be done after all controls are filled
494 bool isUpdateFlushed = false;
495 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
496 bool isStoreValue = !aFOperation->isEditOperation() &&
497 !aWidget->getDefaultValue().empty() &&
498 !aWidget->isComputedDefault();
499 aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
500 aWidget->enableFocusProcessing();
502 ModuleBase_Tools::flushUpdated(aFeature);
504 // update visible state of Preview button
506 bool anIsAutoPreview = mySalomeConnector->featureInfo(aFeatureKind.c_str())->isAutoPreview();
508 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
509 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
510 bool anIsAutoPreview = aCommand && aCommand->featureMessage()->isAutoPreview();
512 if (!anIsAutoPreview) {
513 myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
514 // send signal about preview should not be computed automatically, click on preview
515 // button should initiate it
516 std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
517 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
518 Events_Loop::loop()->send(aMsg);
520 myPropertyPanel->setModelWidgets(aWidgets);
521 aFOperation->setPropertyPanel(myPropertyPanel);
523 myModule->propertyPanelDefined(theOperation);
525 #ifndef DEBUG_FEATURE_NAME
526 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
528 std::string aFeatureName = aFeature->name();
529 myPropertyPanel->setWindowTitle(QString("%1: %2").arg(theOperation->getDescription()->description())
530 .arg(aFeatureName.c_str()));
533 myErrorMgr->setPropertyPanel(myPropertyPanel);
536 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
538 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
539 if (aPropertyPanel) {
540 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
541 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
542 myModule->connectToPropertyPanel(aWidget, isToConnect);
544 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
545 connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
546 connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
549 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
550 disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
551 disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
557 //******************************************************
558 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
560 setGrantedFeatures(theOperation);
561 myModule->operationStarted(theOperation);
564 //******************************************************
565 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
567 setGrantedFeatures(theOperation);
569 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
570 setPropertyPanel(theOperation);
571 connectToPropertyPanel(true);
573 updateCommandStatus();
575 myModule->operationResumed(theOperation);
579 //******************************************************
580 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
582 updateCommandStatus();
584 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
589 ModuleBase_ISelection* aSel = mySelector->selection();
590 QObjectPtrList aObj = aSel->selectedPresentations();
591 //!< No need for property panel
593 myPropertyPanel->cleanContent();
595 connectToPropertyPanel(false);
596 myModule->operationStopped(aFOperation);
598 // the deactivated objects of the current operation should be activated back.
599 // They were deactivated on operation start or an object redisplay
600 QObjectPtrList anObjects;
601 FeaturePtr aFeature = aFOperation->feature();
602 if (aFeature.get()) { // feature may be not created (plugin load fail)
603 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
604 anObjects.append(aFeature);
605 std::list<ResultPtr> aResults = aFeature->results();
606 std::list<ResultPtr>::const_iterator aIt;
607 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
608 ResultPtr anObject = *aIt;
609 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
610 anObjects.append(anObject);
614 activateObjectsSelection(anObjects);
618 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
620 myModule->operationCommitted(theOperation);
623 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
625 myModule->operationAborted(theOperation);
628 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
630 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
634 QStringList aGrantedIds;
635 if (isSalomeMode()) {
636 const std::shared_ptr<Config_FeatureMessage>& anInfo =
637 mySalomeConnector->featureInfo(theOperation->id());
639 aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
640 .split(" ", QString::SkipEmptyParts);
643 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
645 ModuleBase_IModule* aModule = module();
647 aModule->grantedOperationIds(theOperation, aGrantedIds);
649 aFOperation->setGrantedOperationIds(aGrantedIds);
654 * Saves document with given name.
656 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
658 QApplication::restoreOverrideCursor();
659 SessionPtr aMgr = ModelAPI_Session::get();
660 aMgr->save(theName.toLatin1().constData(), theFileNames);
661 QApplication::restoreOverrideCursor();
664 bool XGUI_Workshop::abortAllOperations()
666 return myOperationMgr->abortAllOperations();
669 //******************************************************
670 void XGUI_Workshop::onOpen()
672 if(!abortAllOperations())
674 //save current file before close if modified
675 SessionPtr aSession = ModelAPI_Session::get();
676 if (aSession->isModified()) {
677 //TODO(sbh): re-launch the app?
678 int anAnswer = QMessageBox::question(
679 desktop(), tr("Save current file"),
680 tr("The document is modified, save before opening another?"),
681 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
682 if (anAnswer == QMessageBox::Save) {
684 } else if (anAnswer == QMessageBox::Cancel) {
690 //show file dialog, check if readable and open
691 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
692 if (myCurrentDir.isEmpty())
694 QFileInfo aFileInfo(myCurrentDir);
695 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
696 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
700 QApplication::setOverrideCursor(Qt::WaitCursor);
701 aSession->closeAll();
702 aSession->load(myCurrentDir.toLatin1().constData());
703 myObjectBrowser->rebuildDataTree();
704 updateCommandStatus();
705 QApplication::restoreOverrideCursor();
708 //******************************************************
709 void XGUI_Workshop::onNew()
711 QApplication::setOverrideCursor(Qt::WaitCursor);
712 if (objectBrowser() == 0) {
714 mySelector->connectViewers();
716 myViewerProxy->connectToViewer();
719 myMainWindow->showPythonConsole();
720 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
721 aWnd->showMaximized();
722 updateCommandStatus();
724 myContextMenuMgr->connectViewer();
725 QApplication::restoreOverrideCursor();
729 //******************************************************
730 void XGUI_Workshop::onExit()
732 SessionPtr aMgr = ModelAPI_Session::get();
733 if (aMgr->isModified()) {
734 int anAnswer = QMessageBox::question(
735 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
736 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
737 if (anAnswer == QMessageBox::Save) {
738 bool saved = onSave();
742 } else if (anAnswer == QMessageBox::Cancel) {
749 //******************************************************
750 void XGUI_Workshop::onPreferences()
752 ModuleBase_Prefs aModif;
753 ModuleBase_Preferences::editPreferences(aModif);
754 if (aModif.size() > 0) {
756 foreach (ModuleBase_Pref aPref, aModif)
758 aSection = aPref.first;
759 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
760 myMainWindow->viewer()->updateFromResources();
761 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
762 myMainWindow->menuObject()->updateFromResources();
765 displayer()->redisplayObjects();
770 //******************************************************
771 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
773 XGUI_Displayer* aDisplayer = displayer();
775 aDisplayer->displayTrihedron(theState);
778 //******************************************************
779 bool XGUI_Workshop::onSave()
781 if(!abortAllOperations())
783 if (myCurrentDir.isEmpty()) {
786 std::list<std::string> aFiles;
787 saveDocument(myCurrentDir, aFiles);
788 updateCommandStatus();
790 myMainWindow->setModifiedState(false);
795 //******************************************************
796 bool XGUI_Workshop::onSaveAs()
798 if(!abortAllOperations())
800 QFileDialog dialog(desktop());
801 dialog.setWindowTitle(tr("Select directory to save files..."));
802 dialog.setFileMode(QFileDialog::Directory);
803 dialog.setFilter(tr("Directories (*)"));
804 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
805 dialog.setViewMode(QFileDialog::Detail);
807 if (!dialog.exec()) {
811 QString aTempDir = dialog.selectedFiles().first();
813 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
814 int answer = QMessageBox::question(
816 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
818 tr("The directory already contains some files, save anyway?"),
819 QMessageBox::Save | QMessageBox::Cancel);
820 if (answer == QMessageBox::Cancel) {
824 myCurrentDir = aTempDir;
826 myMainWindow->setCurrentDir(myCurrentDir, false);
827 myMainWindow->setModifiedState(false);
832 //******************************************************
833 void XGUI_Workshop::onUndo(int theTimes)
835 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
836 SessionPtr aMgr = ModelAPI_Session::get();
837 std::list<std::string> aUndoList = aMgr->undoList();
838 if (aMgr->isOperation()) {
839 /// this is important for nested operations
840 /// when sketch operation is active, this condition is false and
841 /// the sketch operation is not aborted
842 operationMgr()->onAbortOperation();
844 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
845 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
847 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
848 myObjectBrowser->rebuildDataTree();
851 operationMgr()->updateApplyOfOperations();
852 updateCommandStatus();
855 //******************************************************
856 void XGUI_Workshop::onRedo(int theTimes)
858 // the viewer update should be blocked in order to avoid the features blinking. For the created
859 // feature a results are created, the flush of the created signal caused the viewer redisplay for
860 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
861 // redo of all possible objects happens
862 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
864 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
865 SessionPtr aMgr = ModelAPI_Session::get();
866 std::list<std::string> aRedoList = aMgr->redoList();
867 if (aMgr->isOperation()) {
868 /// this is important for nested operations
869 /// when sketch operation is active, this condition is false and
870 /// the sketch operation is not aborted
871 operationMgr()->onAbortOperation();
873 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
874 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
876 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
877 myObjectBrowser->rebuildDataTree();
879 operationMgr()->updateApplyOfOperations();
880 updateCommandStatus();
882 // unblock the viewer update functionality and make update on purpose
883 myDisplayer->enableUpdateViewer(isUpdateEnabled);
884 myDisplayer->updateViewer();
887 //******************************************************
888 //void XGUI_Workshop::onRebuild()
890 // SessionPtr aMgr = ModelAPI_Session::get();
891 // bool aWasOperation = aMgr->isOperation(); // keep this value
892 // if (!aWasOperation) {
893 // aMgr->startOperation("Rebuild");
895 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
896 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
897 // new Events_Message(aRebuildEvent, this)));
898 // if (!aWasOperation) {
899 // aMgr->finishOperation();
901 // updateCommandStatus();
904 //******************************************************
905 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
907 ModuleBase_ModelWidget* anActiveWidget = 0;
908 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
910 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
912 anActiveWidget = aPanel->activeWidget();
915 operationMgr()->onValidateOperation();
917 myModule->widgetStateChanged(thePreviousState);
920 //******************************************************
921 void XGUI_Workshop::onValuesChanged()
923 ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
924 if (!aSenderWidget || aSenderWidget->canAcceptFocus())
927 ModuleBase_ModelWidget* anActiveWidget = 0;
928 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
930 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
932 anActiveWidget = aPanel->activeWidget();
934 if (anActiveWidget) {
935 ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
937 if (aWidgetValidated)
938 aWidgetValidated->clearValidatedCash();
942 void XGUI_Workshop::onWidgetObjectUpdated()
944 operationMgr()->onValidateOperation();
947 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
949 QString libName = QString::fromStdString(library(theModule.toStdString()));
950 if (libName.isEmpty()) {
951 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
956 CREATE_FUNC crtInst = 0;
959 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
963 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
964 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
965 QString aMsg((char*) &lpMsgBuf);
966 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
967 ::LocalFree(lpMsgBuf);
969 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
973 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
974 | FORMAT_MESSAGE_IGNORE_INSERTS,
975 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
976 QString aMsg((char*) &lpMsgBuf);
977 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
978 ::LocalFree(lpMsgBuf);
982 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
984 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
986 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
988 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
993 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
995 if (!err.isEmpty()) {
997 Events_Error::send(err.toStdString());
999 qWarning(qPrintable(err));
1005 //******************************************************
1006 bool XGUI_Workshop::createModule()
1008 Config_ModuleReader aModuleReader;
1009 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1010 myModule = loadModule(moduleName);
1014 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1015 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1016 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1017 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1019 myModule->createFeatures();
1021 salomeConnector()->createFeatureActions();
1023 //myActionsMgr->update();
1027 //******************************************************
1028 void XGUI_Workshop::updateCommandStatus()
1030 QList<QAction*> aCommands;
1032 aCommands = salomeConnector()->commandList();
1034 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1035 foreach (AppElements_Command* aCmd, aMenuBar->features())
1036 aCommands.append(aCmd);
1038 SessionPtr aMgr = ModelAPI_Session::get();
1039 if (aMgr->hasModuleDocument()) {
1040 foreach(QAction* aCmd, aCommands) {
1041 QString aId = aCmd->data().toString();
1042 if (aId == "UNDO_CMD")
1043 aCmd->setEnabled(myModule->canUndo());
1044 else if (aId == "REDO_CMD")
1045 aCmd->setEnabled(myModule->canRedo());
1047 // Enable all commands
1048 aCmd->setEnabled(true);
1052 foreach(QAction* aCmd, aCommands) {
1053 QString aId = aCmd->data().toString();
1054 if (aId == "NEW_CMD")
1055 aCmd->setEnabled(true);
1056 else if (aId == "EXIT_CMD")
1057 aCmd->setEnabled(true);
1059 aCmd->setEnabled(false);
1062 myActionsMgr->updateCommandsStatus();
1063 emit commandStatusUpdated();
1066 void XGUI_Workshop::updateHistory()
1068 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1069 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1070 emit updateUndoHistory(aUndoRes);
1072 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1073 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1074 emit updateRedoHistory(aRedoRes);
1077 //******************************************************
1078 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1080 QDockWidget* aObjDock = new QDockWidget(theParent);
1081 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1082 aObjDock->setWindowTitle(tr("Object browser"));
1083 aObjDock->setStyleSheet(
1084 "::title { position: relative; padding-left: 5px; text-align: left center }");
1085 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1086 myObjectBrowser->setXMLReader(myDataModelXMLReader);
1087 myModule->customizeObjectBrowser(myObjectBrowser);
1088 aObjDock->setWidget(myObjectBrowser);
1090 myContextMenuMgr->connectObjectBrowser();
1094 //******************************************************
1096 * Creates dock widgets, places them in corresponding area
1097 * and tabifies if necessary.
1099 void XGUI_Workshop::createDockWidgets()
1101 QMainWindow* aDesktop = desktop();
1102 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1103 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1104 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1105 myPropertyPanel->setupActions(myActionsMgr);
1106 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1107 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1108 hidePropertyPanel(); ///<! Invisible by default
1109 hideObjectBrowser();
1110 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1111 myPropertyPanel->installEventFilter(myOperationMgr);
1113 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1114 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1116 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1117 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1119 QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1120 connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1122 connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1123 myOperationMgr, SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1124 connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1125 myOperationMgr, SLOT(onProcessEnter(QObject*)));
1128 //******************************************************
1129 void XGUI_Workshop::showPropertyPanel()
1131 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1132 ///<! Restore ability to close panel from the window's menu
1133 aViewAct->setEnabled(true);
1134 myPropertyPanel->show();
1135 myPropertyPanel->raise();
1137 // The next code is necessary to made the property panel the active window
1138 // in order to operation manager could process key events of the panel.
1139 // otherwise they are ignored. It happens only if the same(activateWindow) is
1140 // not happened by property panel activation(e.g. resume operation of Sketch)
1141 ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1142 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1145 //******************************************************
1146 void XGUI_Workshop::hidePropertyPanel()
1148 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1149 ///<! Do not allow to show empty property panel
1150 aViewAct->setEnabled(false);
1151 myPropertyPanel->hide();
1153 // the property panel is active window of the desktop, when it is
1154 // hidden, it is undefined which window becomes active. By this reason
1155 // it is defined to perform the desktop as the active window.
1156 // in SALOME mode, workstack made the PyConsole the active window,
1157 // set the focus on it. As a result, shortcuts of the application, like
1158 // are processed by this console. For example Undo actions.
1159 // It is possible that this code is to be moved to SHAPER package
1160 QMainWindow* aDesktop = desktop();
1161 ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1162 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1165 //******************************************************
1166 void XGUI_Workshop::showObjectBrowser()
1168 if (!isSalomeMode())
1169 myObjectBrowser->parentWidget()->show();
1172 //******************************************************
1173 void XGUI_Workshop::hideObjectBrowser()
1175 if (!isSalomeMode())
1176 myObjectBrowser->parentWidget()->hide();
1179 //******************************************************
1180 void XGUI_Workshop::salomeViewerSelectionChanged()
1182 emit salomeViewerSelection();
1185 //**************************************************************
1186 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1188 return mySalomeConnector->viewer();
1191 //**************************************************************
1192 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1194 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1195 if (theId == "DELETE_CMD")
1197 else if (theId == "CLEAN_HISTORY_CMD")
1199 else if (theId == "MOVE_CMD")
1201 else if (theId == "COLOR_CMD")
1202 changeColor(aObjects);
1203 else if (theId == "SHOW_CMD") {
1204 showObjects(aObjects, true);
1205 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1207 else if (theId == "HIDE_CMD")
1208 showObjects(aObjects, false);
1209 else if (theId == "SHOW_ONLY_CMD") {
1210 showOnlyObjects(aObjects);
1211 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1213 else if (theId == "SHADING_CMD")
1214 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1215 else if (theId == "WIREFRAME_CMD")
1216 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1217 else if (theId == "HIDEALL_CMD") {
1218 QObjectPtrList aList = myDisplayer->displayedObjects();
1219 foreach (ObjectPtr aObj, aList) {
1220 if (module()->canEraseObject(aObj))
1221 aObj->setDisplayed(false);
1223 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1224 } else if (theId == "SELECT_VERTEX_CMD") {
1225 setViewerSelectionMode(TopAbs_VERTEX);
1226 } else if (theId == "SELECT_EDGE_CMD") {
1227 setViewerSelectionMode(TopAbs_EDGE);
1228 } else if (theId == "SELECT_FACE_CMD") {
1229 setViewerSelectionMode(TopAbs_FACE);
1230 } else if (theId == "SELECT_RESULT_CMD") {
1231 setViewerSelectionMode(-1);
1232 } else if (theId == "SHOW_RESULTS_CMD") {
1233 highlightResults(aObjects);
1237 //**************************************************************
1238 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1240 myViewerSelMode = theMode;
1241 activateObjectsSelection(myDisplayer->displayedObjects());
1244 //**************************************************************
1245 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1248 module()->activeSelectionModes(aModes);
1249 if (aModes.isEmpty() && (myViewerSelMode != -1))
1250 aModes.append(myViewerSelMode);
1251 myDisplayer->activateObjects(aModes, theList);
1255 //**************************************************************
1256 void XGUI_Workshop::deleteObjects()
1258 ModuleBase_IModule* aModule = module();
1259 // 1. allow the module to delete objects, do nothing if it has succeed
1260 if (aModule->deleteObjects()) {
1261 updateCommandStatus();
1265 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1266 if (!abortAllOperations())
1268 // check whether the object can be deleted. There should not be parts which are not loaded
1269 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1272 bool hasResult = false;
1273 bool hasFeature = false;
1274 bool hasParameter = false;
1275 bool hasCompositeOwner = false;
1276 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1277 if (!(hasFeature || hasParameter))
1280 // 3. delete objects
1281 std::set<FeaturePtr> anIgnoredFeatures;
1282 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1283 findReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures);
1285 bool doDeleteReferences = true;
1286 if (isDeleteFeatureWithReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1287 desktop(), doDeleteReferences)) {
1289 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1290 aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1291 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1292 operationMgr()->startOperation(anOpAction);
1294 // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1295 // It is necessary to clear selection in order to avoid selection changed event during
1296 // deletion and negative consequences connected with processing of already deleted items
1297 mySelector->clearSelection();
1299 // delete and commit/abort operation in model
1300 if (deleteFeaturesInternal(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1301 anIgnoredFeatures, doDeleteReferences))
1302 operationMgr()->commitOperation();
1304 operationMgr()->abortOperation(operationMgr()->currentOperation());
1308 //**************************************************************
1309 void XGUI_Workshop::cleanHistory()
1311 if (!abortAllOperations())
1314 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1315 QObjectPtrList aFeatures;
1316 foreach (ObjectPtr anObject, anObjects) {
1317 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1318 // for parameter result, use the corresponded reature to be removed
1319 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1320 aFeature = ModelAPI_Feature::feature(anObject);
1322 aFeatures.append(aFeature);
1325 // 1. find all referenced features
1326 QList<ObjectPtr> anUnusedObjects;
1327 std::set<FeaturePtr> aDirectRefFeatures;
1328 //foreach (ObjectPtr anObject, anObjects) {
1329 foreach (ObjectPtr anObject, aFeatures) {
1330 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1331 // for parameter result, use the corresponded reature to be removed
1332 //if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1333 // aFeature = ModelAPI_Feature::feature(anObject);
1335 if (aFeature.get()) {
1336 std::set<FeaturePtr> alreadyProcessed;
1337 aDirectRefFeatures.clear();
1338 XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, aFeatures,
1339 aDirectRefFeatures, alreadyProcessed);
1340 if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1341 anUnusedObjects.append(aFeature);
1345 // 2. warn about the references remove, break the delete operation if the user chose it
1346 if (!anUnusedObjects.empty()) {
1348 foreach (const ObjectPtr& anObject, anUnusedObjects) {
1349 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1350 aNames.append(aFeature->name().c_str());
1352 QString anUnusedNames = aNames.join(", ");
1354 QString anActionId = "CLEAN_HISTORY_CMD";
1355 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1357 QMessageBox aMessageBox(desktop());
1358 aMessageBox.setWindowTitle(aDescription);
1359 aMessageBox.setIcon(QMessageBox::Warning);
1360 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1361 aMessageBox.setDefaultButton(QMessageBox::No);
1363 QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1364 .arg(anUnusedNames));
1366 if (anUnusedNames.isEmpty()) {
1367 aMessageBox.setStandardButtons(QMessageBox::Ok);
1368 aMessageBox.setDefaultButton(QMessageBox::Ok);
1370 aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1373 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1374 aMessageBox.setDefaultButton(QMessageBox::No);
1376 aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1377 .arg(anUnusedNames));
1380 aMessageBox.setText(aText);
1381 if (aMessageBox.exec() == QMessageBox::No)
1384 // 1. start operation
1385 aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1386 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1387 operationMgr()->startOperation(anOpAction);
1389 // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1390 // It is necessary to clear selection in order to avoid selection changed event during
1391 // deletion and negative consequences connected with processing of already deleted items
1392 mySelector->clearSelection();
1394 std::set<FeaturePtr> anIgnoredFeatures;
1395 if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId, true)) {
1396 operationMgr()->commitOperation();
1399 operationMgr()->abortOperation(operationMgr()->currentOperation());
1403 QString anActionId = "CLEAN_HISTORY_CMD";
1404 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1406 QMessageBox aMessageBox(desktop());
1407 aMessageBox.setWindowTitle(aDescription);
1408 aMessageBox.setIcon(QMessageBox::Warning);
1409 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1410 aMessageBox.setDefaultButton(QMessageBox::No);
1413 aMessageBox.setStandardButtons(QMessageBox::Ok);
1414 aMessageBox.setDefaultButton(QMessageBox::Ok);
1416 aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1417 aMessageBox.setText(aText);
1419 if (aMessageBox.exec() == QMessageBox::No)
1424 //**************************************************************
1425 void XGUI_Workshop::moveObjects()
1427 if (!abortAllOperations())
1430 SessionPtr aMgr = ModelAPI_Session::get();
1432 QString anActionId = "MOVE_CMD";
1433 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1434 aMgr->startOperation(aDescription.toStdString());
1436 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1437 // It is necessary to clear selection in order to avoid selection changed event during
1438 // moving and negative consequences connected with processing of already moved items
1439 mySelector->clearSelection();
1440 // check whether the object can be moved. There should not be parts which are not loaded
1441 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1444 DocumentPtr anActiveDocument = aMgr->activeDocument();
1445 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1446 foreach (ObjectPtr aObject, anObjects) {
1447 if (!myModule->canApplyAction(aObject, anActionId))
1450 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1451 if (aFeature.get()) {
1452 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1453 aCurrentFeature = anActiveDocument->currentFeature(true);
1456 aMgr->finishOperation();
1459 //**************************************************************
1460 void XGUI_Workshop::findReferences(const QObjectPtrList& theList,
1461 std::set<FeaturePtr>& aDirectRefFeatures,
1462 std::set<FeaturePtr>& aIndirectRefFeatures)
1464 foreach (ObjectPtr aDeletedObj, theList) {
1465 std::set<FeaturePtr> alreadyProcessed;
1466 XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1467 aIndirectRefFeatures, alreadyProcessed);
1468 std::set<FeaturePtr> aDifference;
1469 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1470 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1471 std::inserter(aDifference, aDifference.begin()));
1472 aIndirectRefFeatures = aDifference;
1476 bool XGUI_Workshop::isDeleteFeatureWithReferences(const QObjectPtrList& theList,
1477 const std::set<FeaturePtr>& aDirectRefFeatures,
1478 const std::set<FeaturePtr>& aIndirectRefFeatures,
1480 bool& doDeleteReferences)
1482 doDeleteReferences = true;
1484 QString aDirectNames, aIndirectNames;
1485 if (!aDirectRefFeatures.empty()) {
1486 QStringList aDirectRefNames;
1487 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1488 aDirectRefNames.append(aFeature->name().c_str());
1489 aDirectNames = aDirectRefNames.join(", ");
1491 QStringList aIndirectRefNames;
1492 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1493 aIndirectRefNames.append(aFeature->name().c_str());
1494 aIndirectNames = aIndirectRefNames.join(", ");
1497 bool aCanReplaceParameters = !aDirectRefFeatures.empty();
1498 QStringList aPartFeatureNames;
1499 foreach (ObjectPtr aObj, theList) {
1500 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1501 // invalid feature data means that the feature is already removed in model,
1502 // we needn't process it. E.g. delete of feature from create operation. The operation abort
1503 // will delete the operation
1504 if (!aFeature->data()->isValid())
1506 ResultPtr aFirstResult = aFeature->firstResult();
1507 if (!aFirstResult.get())
1509 std::string aResultGroupName = aFirstResult->groupName();
1510 if (aResultGroupName == ModelAPI_ResultPart::group())
1511 aPartFeatureNames.append(aFeature->name().c_str());
1513 if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
1514 aCanReplaceParameters = false;
1516 QString aPartNames = aPartFeatureNames.join(", ");
1518 QMessageBox aMessageBox(theParent);
1519 aMessageBox.setWindowTitle(tr("Delete features"));
1520 aMessageBox.setIcon(QMessageBox::Warning);
1521 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1522 aMessageBox.setDefaultButton(QMessageBox::No);
1525 if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
1526 if (aCanReplaceParameters) {
1527 aText = QString(tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\nOr parameters could be replaced by their values.\n")
1528 .arg(aDirectNames));
1529 if (!aIndirectNames.isEmpty())
1530 aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1531 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1533 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
1534 if (!aIndirectNames.isEmpty())
1535 aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1538 if (!aPartNames.isEmpty())
1539 aText += QString(tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
1541 if (!aText.isEmpty()) {
1542 aText += "Would you like to continue?";
1543 aMessageBox.setText(aText);
1545 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1547 if (aButtonRole == QMessageBox::NoRole)
1550 if (aButtonRole == QMessageBox::ActionRole) {
1551 foreach (ObjectPtr aObj, theList)
1552 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1553 doDeleteReferences = false;
1559 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theFeatures,
1560 const std::set<FeaturePtr>& theIgnoredFeatures)
1562 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1563 findReferences(theFeatures, aDirectRefFeatures, aIndirectRefFeatures);
1564 return deleteFeaturesInternal(theFeatures, aDirectRefFeatures, aIndirectRefFeatures,
1565 theIgnoredFeatures);
1568 bool XGUI_Workshop::deleteFeaturesInternal(const QObjectPtrList& theList,
1569 const std::set<FeaturePtr>& aDirectRefFeatures,
1570 const std::set<FeaturePtr>& aIndirectRefFeatures,
1571 const std::set<FeaturePtr>& theIgnoredFeatures,
1572 const bool doDeleteReferences)
1574 bool isDone = false;
1575 if (doDeleteReferences) {
1576 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1577 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1578 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1579 aLast = aFeaturesToDelete.end();
1583 for (; anIt != aLast; anIt++) {
1584 FeaturePtr aFeature = (*anIt);
1585 DocumentPtr aDoc = aFeature->document();
1586 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1587 // flush REDISPLAY signal after remove feature
1588 aDoc->removeFeature(aFeature);
1591 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1596 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1601 QString anActionId = "DELETE_CMD";
1602 isDone = removeFeatures(theList, theIgnoredFeatures, anActionId, false) || isDone;
1605 // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
1606 // if should be done after removeFeature() of document
1607 Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
1612 //**************************************************************
1613 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1614 const std::set<FeaturePtr>& theIgnoredFeatures,
1615 const QString& theActionId,
1616 const bool theFlushRedisplay)
1618 bool isDone = false;
1620 QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1621 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1622 // 4. remove the parameter features
1623 foreach (ObjectPtr aObj, theList) {
1624 // features and parameters can be removed here,
1625 // the results are removed only by a corresponded feature remove
1626 std::string aGroupName = aObj->groupName();
1627 if (!anObjectGroups.contains(aGroupName.c_str()))
1630 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1632 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1633 // part features are removed in the PartSet module. This condition should be moved there
1634 if (aFeature->getKind() == "Part")
1637 DocumentPtr aDoc = aObj->document();
1638 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1640 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1641 anInfo.append(anInfoStr);
1642 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1644 // flush REDISPLAY signal after remove feature
1645 aDoc->removeFeature(aFeature);
1650 if (isDone && theFlushRedisplay) {
1651 // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
1652 // if should be done after removeFeature() of document
1653 Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
1657 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1662 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1664 bool isFoundResultType = false;
1665 foreach(ObjectPtr anObj, theObjects)
1667 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1668 if (aResult.get() == NULL)
1671 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1672 if (isFoundResultType)
1675 return isFoundResultType;
1678 //**************************************************************
1679 // Returns the list of all features for theDocument and all features of
1680 // all nested parts.
1681 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1683 std::list<FeaturePtr> aResultList;
1684 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1685 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1686 // The order of appending features of the part and the part itself is important
1688 // Append features from a part feature
1689 foreach (const ResultPtr& aResult, aFeature->results()) {
1690 ResultPartPtr aResultPart =
1691 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1692 if (aResultPart.get() && aResultPart->partDoc().get()) {
1694 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1695 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1699 aResultList.push_back(aFeature);
1704 //**************************************************************
1705 // Returns the list of features placed between theObject and the current feature
1706 // in the same document. Excludes theObject, includes the current feature.
1707 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1709 std::list<FeaturePtr> aResult;
1710 DocumentPtr aDocument = theObject->document();
1711 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1712 // find the object iterator
1713 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1714 if (aObjectIt == anAllFeatures.end())
1716 // find the current feature iterator
1717 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1718 if (aCurrentIt == anAllFeatures.end())
1720 // check the right order
1721 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1723 // exclude the object
1724 std::advance(aObjectIt, 1);
1725 // include the current feature
1726 std::advance(aCurrentIt, 1);
1727 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1730 bool XGUI_Workshop::canMoveFeature()
1732 QString anActionId = "MOVE_CMD";
1734 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1735 QObjectPtrList aValidatedObjects;
1736 foreach (ObjectPtr aObject, aObjects) {
1737 if (!myModule->canApplyAction(aObject, anActionId))
1739 // To be moved feature should be in active document
1740 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1742 aValidatedObjects.append(aObject);
1744 if (aValidatedObjects.size() != aObjects.size())
1745 aObjects = aValidatedObjects;
1747 bool aCanMove = !aObjects.empty();
1749 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1750 for (; anIt != aLast && aCanMove; anIt++) {
1751 ObjectPtr aObject = *anIt;
1752 // 1. Get features placed between selected and current in the document
1753 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1754 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1755 if (aFeaturesBetween.empty())
1758 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1759 // 2. Get all reference features to the selected object in the document
1760 std::set<FeaturePtr> aRefFeatures;
1761 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1763 if (aRefFeatures.empty())
1766 // 3. Find any placed features in all reference features
1767 std::set<FeaturePtr> aIntersectionFeatures;
1768 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1769 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1770 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1771 // 4. Return false if any reference feature is placed before current feature
1772 if (!aIntersectionFeatures.empty())
1780 //**************************************************************
1781 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1783 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1784 if (!aCanBeShaded) {
1785 ResultCompSolidPtr aCompsolidResult =
1786 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1787 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1788 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1789 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1792 return aCanBeShaded;
1795 //**************************************************************
1796 bool XGUI_Workshop::canChangeColor() const
1798 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1800 std::set<std::string> aTypes;
1801 aTypes.insert(ModelAPI_ResultGroup::group());
1802 aTypes.insert(ModelAPI_ResultConstruction::group());
1803 aTypes.insert(ModelAPI_ResultBody::group());
1804 aTypes.insert(ModelAPI_ResultPart::group());
1806 return hasResults(aObjects, aTypes);
1809 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1811 if (!theResult.get())
1814 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1815 if (aColorAttr.get() != NULL) {
1816 if (!aColorAttr->size()) {
1817 aColorAttr->setSize(3);
1819 aColorAttr->setValue(0, theColor[0]);
1820 aColorAttr->setValue(1, theColor[1]);
1821 aColorAttr->setValue(2, theColor[2]);
1825 //**************************************************************
1826 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1829 AttributeIntArrayPtr aColorAttr;
1830 // 1. find the current color of the object. This is a color of AIS presentation
1831 // The objects are iterated until a first valid color is found
1832 std::vector<int> aColor;
1833 foreach(ObjectPtr anObject, theObjects) {
1834 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1835 if (aResult.get()) {
1836 XGUI_CustomPrs::getResultColor(aResult, aColor);
1839 // TODO: remove the obtaining a color from the AIS object
1840 // this does not happen never because:
1841 // 1. The color can be changed only on results
1842 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1843 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1844 if (anAISObj.get()) {
1846 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1849 if (!aColor.empty())
1852 if (aColor.size() != 3)
1855 if (!abortAllOperations())
1857 // 2. show the dialog to change the value
1858 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1859 aDlg->setColor(aColor);
1860 aDlg->move(QCursor::pos());
1861 bool isDone = aDlg->exec() == QDialog::Accepted;
1865 bool isRandomColor = aDlg->isRandomColor();
1867 // 3. abort the previous operation and start a new one
1868 SessionPtr aMgr = ModelAPI_Session::get();
1869 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1870 aMgr->startOperation(aDescription.toStdString());
1872 // 4. set the value to all results
1873 std::vector<int> aColorResult = aDlg->getColor();
1874 foreach(ObjectPtr anObj, theObjects) {
1875 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1876 if (aResult.get() != NULL) {
1877 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1878 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1879 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1880 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1883 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1886 aMgr->finishOperation();
1887 updateCommandStatus();
1890 //**************************************************************
1891 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1892 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1893 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1895 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1897 foreach (ObjectPtr aObj, theList) {
1899 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1901 DocumentPtr aDoc = aPartRes->partDoc();
1902 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1903 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1904 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1907 aObj->setDisplayed(isVisible);
1910 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1913 //**************************************************************
1914 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1916 // Hide all displayed objects
1917 QObjectPtrList aList = myDisplayer->displayedObjects();
1918 foreach (ObjectPtr aObj, aList) {
1919 if (module()->canEraseObject(aObj))
1920 aObj->setDisplayed(false);
1923 // Show only objects from the list
1924 foreach (ObjectPtr aObj, theList) {
1926 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1928 DocumentPtr aDoc = aPartRes->partDoc();
1929 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1930 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1931 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1934 aObj->setDisplayed(true);
1937 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1942 //**************************************************************
1943 void XGUI_Workshop::registerValidators() const
1945 SessionPtr aMgr = ModelAPI_Session::get();
1946 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1949 //**************************************************************
1950 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1954 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1955 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1958 //**************************************************************
1959 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1961 for (int i = 0; i < theDoc->size(theGroup); i++)
1962 theDoc->object(theGroup, i)->setDisplayed(true);
1963 //displayObject(theDoc->object(theGroup, i));
1964 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1967 //**************************************************************
1968 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1970 foreach(ObjectPtr aObj, theList) {
1971 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1973 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1974 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1975 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1976 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1977 (XGUI_Displayer::DisplayMode)theMode, false);
1981 if (theList.size() > 0)
1982 myDisplayer->updateViewer();
1985 //**************************************************************
1986 void XGUI_Workshop::closeDocument()
1988 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1989 while (anOperation) {
1990 anOperation->abort();
1991 anOperation = operationMgr()->currentOperation();
1993 myDisplayer->closeLocalContexts();
1994 myDisplayer->eraseAll();
1995 objectBrowser()->clearContent();
1997 module()->closeDocument();
1999 SessionPtr aMgr = ModelAPI_Session::get();
2003 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2005 XGUI_HistoryMenu* aMenu = NULL;
2006 if (isSalomeMode()) {
2007 QAction* anAction = qobject_cast<QAction*>(theObject);
2010 aMenu = new XGUI_HistoryMenu(anAction);
2012 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
2013 aMenu = new XGUI_HistoryMenu(aButton);
2015 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2016 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2019 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2021 QList<ActionInfo> aResult;
2022 std::list<std::string>::const_iterator it = theList.cbegin();
2023 for (; it != theList.cend(); it++) {
2024 QString anId = QString::fromStdString(*it);
2025 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2027 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2030 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2031 if (aContextMenuAct) {
2032 anInfo.initFrom(aContextMenuAct);
2034 anInfo = myActionsMgr->actionInfoById(anId);
2037 anInfo.text = anInfo.text.prepend("Modify ");
2044 void XGUI_Workshop::synchronizeViewer()
2046 SessionPtr aMgr = ModelAPI_Session::get();
2047 DocumentPtr aDoc = aMgr->activeDocument();
2049 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2050 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2051 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2052 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2055 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2056 const std::string& theGroup,
2057 bool theUpdateViewer)
2060 int aSize = theDoc->size(theGroup);
2061 for (int i = 0; i < aSize; i++) {
2062 aObj = theDoc->object(theGroup, i);
2063 if (aObj->isDisplayed()) {
2064 // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2065 // be changed to the object becomes visible when the shape becomes not empty
2066 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2067 if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2069 myDisplayer->display(aObj, false);
2072 if (theUpdateViewer)
2073 myDisplayer->updateViewer();
2076 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2078 FeaturePtr aFeature;
2079 QObjectPtrList aSelList = theObjects;
2080 std::list<ResultPtr> aResList;
2081 foreach(ObjectPtr aObj, theObjects) {
2082 aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2083 if (aFeature.get()) {
2084 aResList = aFeature->results();
2085 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2086 for(aIt = aResList.cbegin(); aIt != aResList.cend(); aIt++) {
2087 aSelList.append(*aIt);
2091 if (aSelList.count() > theObjects.count()) {
2092 // if something was found
2093 bool aBlocked = objectBrowser()->blockSignals(true);
2094 objectBrowser()->setObjectsSelected(aSelList);
2095 objectBrowser()->blockSignals(aBlocked);