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>
108 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
110 //#define DEBUG_DELETE
112 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
114 myCurrentDir(QString()),
116 mySalomeConnector(theConnector),
122 myMainWindow = new AppElements_MainWindow();
124 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
125 bool aCloc = aResMgr->booleanValue("language", "locale", true);
127 QLocale::setDefault( QLocale::c() );
129 QLocale::setDefault( QLocale::system() );
132 myDisplayer = new XGUI_Displayer(this);
134 mySelector = new XGUI_SelectionMgr(this);
135 connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
137 myOperationMgr = new XGUI_OperationMgr(this, 0);
138 myActionsMgr = new XGUI_ActionsMgr(this);
139 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
140 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
141 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
142 SLOT(onContextMenuCommand(const QString&, bool)));
144 myViewerProxy = new XGUI_ViewerProxy(this);
145 connect(myViewerProxy, SIGNAL(selectionChanged()),
146 myActionsMgr, SLOT(updateOnViewSelection()));
148 myModuleConnector = new XGUI_ModuleConnector(this);
150 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
151 myOperationMgr->setWorkshop(aWorkshop);
153 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
154 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
156 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
157 SLOT(onOperationStarted(ModuleBase_Operation*)));
158 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
159 SLOT(onOperationResumed(ModuleBase_Operation*)));
160 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
161 SLOT(onOperationStopped(ModuleBase_Operation*)));
162 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
163 SLOT(onOperationCommitted(ModuleBase_Operation*)));
164 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
165 SLOT(onOperationAborted(ModuleBase_Operation*)));
166 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
167 // myErrorMgr, SLOT(onValidationStateChanged()));
170 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
173 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
174 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
175 myErrorDlg, SLOT(addError(const QString&)));
177 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
178 // Config_Prop::Color, "225,225,225");
180 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
181 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
182 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
183 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
184 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
185 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
186 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
187 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
190 //******************************************************
191 XGUI_Workshop::~XGUI_Workshop(void)
196 //******************************************************
197 void XGUI_Workshop::startApplication()
201 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
202 Config_Prop::Directory, "");
204 //Initialize event listening
205 myEventsListener->initializeEventListening();
207 registerValidators();
209 // Calling of loadCustomProps before activating module is required
210 // by Config_PropManger to restore user-defined path to plugins
211 ModuleBase_Preferences::loadCustomProps();
215 myMainWindow->show();
216 updateCommandStatus();
221 emit applicationStarted();
224 void XGUI_Workshop::activateModule()
226 myModule->activateSelectionFilters();
228 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
229 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
230 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
231 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
233 updateCommandStatus();
235 // activate visualized objects in the viewer
236 XGUI_Displayer* aDisplayer = displayer();
237 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
239 module()->activeSelectionModes(aModes);
240 aDisplayer->activateObjects(aModes, aDisplayed);
243 void XGUI_Workshop::deactivateModule()
245 myModule->deactivateSelectionFilters();
247 // remove internal displayer filter
248 displayer()->deactivateSelectionFilters();
250 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
251 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
252 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
253 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
255 XGUI_Displayer* aDisplayer = displayer();
256 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
257 aDisplayer->deactivateObjects(aDisplayed, true);
260 //******************************************************
261 void XGUI_Workshop::initMenu()
263 myContextMenuMgr->createActions();
266 // Create only Undo, Redo commands
267 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
268 tr("Undo last command"),
269 QIcon(":pictures/undo.png"),
270 QKeySequence::Undo, false, "MEN_DESK_EDIT");
271 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
272 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
274 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
275 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
277 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
278 QIcon(":pictures/redo.png"), QKeySequence::Redo,
279 false, "MEN_DESK_EDIT");
280 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
282 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
283 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
285 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
286 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
287 // QIcon(":pictures/rebuild.png"), QKeySequence(),
288 // false, "MEN_DESK_EDIT");
289 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
291 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
292 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
294 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
295 QIcon(), QKeySequence(),
296 false, "MEN_DESK_FILE");
297 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
299 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
300 QIcon(), QKeySequence(),
301 false, "MEN_DESK_FILE");
302 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
303 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
306 // File commands group
307 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
309 AppElements_Command* aCommand;
311 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
312 QIcon(":pictures/save.png"), QKeySequence::Save);
313 aCommand->connectTo(this, SLOT(onSave()));
314 //aCommand->disable();
316 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
317 QIcon(":pictures/save.png"), QKeySequence());
318 aCommand->connectTo(this, SLOT(onSaveAs()));
320 QString aUndoId = "UNDO_CMD";
321 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
322 QIcon(":pictures/undo.png"), QKeySequence::Undo);
323 aCommand->connectTo(this, SLOT(onUndo()));
324 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
325 addHistoryMenu(aUndoButton,
326 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
329 QString aRedoId = "REDO_CMD";
330 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
331 QIcon(":pictures/redo.png"), QKeySequence::Redo);
332 aCommand->connectTo(this, SLOT(onRedo()));
333 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
334 addHistoryMenu(aRedoButton,
335 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
338 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
339 // QIcon(":pictures/rebuild.png"), QKeySequence());
340 //aCommand->connectTo(this, SLOT(onRebuild()));
342 //aCommand->disable();
344 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
345 QIcon(":pictures/open.png"), QKeySequence::Open);
346 aCommand->connectTo(this, SLOT(onOpen()));
348 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
349 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
350 aCommand->connectTo(this, SLOT(onPreferences()));
352 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
353 QIcon(":pictures/close.png"), QKeySequence::Close);
354 aCommand->connectTo(this, SLOT(onExit()));
359 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
361 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
362 return aMenuBar->addWorkbench(theName);
366 //******************************************************
367 QMainWindow* XGUI_Workshop::desktop() const
370 return salomeConnector()->desktop();
376 //******************************************************
377 void XGUI_Workshop::onStartWaiting()
379 if (Events_LongOp::isPerformed()) {
380 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
384 //******************************************************
385 void XGUI_Workshop::onAcceptActionClicked()
387 QAction* anAction = dynamic_cast<QAction*>(sender());
388 XGUI_OperationMgr* anOperationMgr = operationMgr();
389 if (anOperationMgr) {
390 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
391 (anOperationMgr->currentOperation());
393 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
394 myOperationMgr->onCommitOperation();
399 //******************************************************
400 /*void XGUI_Workshop::onValidationStateChanged(bool theEnabled)
402 XGUI_OperationMgr* anOperationMgr = operationMgr();
403 if (anOperationMgr) {
404 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
405 (anOperationMgr->currentOperation());
407 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
408 myErrorMgr->updateActionState(anAction, aFOperation->feature(), theEnabled);
414 //******************************************************
415 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
417 if (!myModule->canActivateSelection(theObject)) {
418 if (myDisplayer->isActive(theObject)) {
419 QObjectPtrList anObjects;
420 anObjects.append(theObject);
421 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
426 //******************************************************
427 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
429 bool aHasNested = false;
430 std::string aFeatureKind = theFeature->getKind();
432 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
433 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
436 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
437 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
438 if (aCommand && aCommand->button()->additionalButtonWidget())
444 //******************************************************
445 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
447 setGrantedFeatures(theOperation);
449 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
454 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
455 setPropertyPanel(aFOperation);
456 // filling the operation values by the current selection
457 // if the operation can be committed after the controls filling, the method perform should
458 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
459 if (!aFOperation->isEditOperation()) {
460 aFOperation->activateByPreselection();
461 if (operationMgr()->currentOperation() != aFOperation)
465 updateCommandStatus();
467 connectToPropertyPanel(true);
468 myModule->operationStarted(aFOperation);
470 // the objects of the current operation should be deactivated
471 QObjectPtrList anObjects;
472 FeaturePtr aFeature = aFOperation->feature();
473 anObjects.append(aFeature);
474 std::list<ResultPtr> aResults = aFeature->results();
475 std::list<ResultPtr>::const_iterator aIt;
476 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
477 anObjects.append(*aIt);
479 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
480 for (; anIt != aLast; anIt++)
481 deactivateActiveObject(*anIt, false);
482 if (anObjects.size() > 0)
483 myDisplayer->updateViewer();
486 //******************************************************
487 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
489 setGrantedFeatures(theOperation);
491 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
492 setPropertyPanel(theOperation);
493 connectToPropertyPanel(true);
495 updateCommandStatus();
497 myModule->operationResumed(theOperation);
501 //******************************************************
502 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
504 updateCommandStatus();
506 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
511 ModuleBase_ISelection* aSel = mySelector->selection();
512 QObjectPtrList aObj = aSel->selectedPresentations();
513 //!< No need for property panel
515 myPropertyPanel->cleanContent();
517 connectToPropertyPanel(false);
518 myModule->operationStopped(aFOperation);
520 // the deactivated objects of the current operation should be activated back.
521 // They were deactivated on operation start or an object redisplay
522 QObjectPtrList anObjects;
523 FeaturePtr aFeature = aFOperation->feature();
524 if (aFeature.get()) { // feature may be not created (plugin load fail)
525 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
526 anObjects.append(aFeature);
527 std::list<ResultPtr> aResults = aFeature->results();
528 std::list<ResultPtr>::const_iterator aIt;
529 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
530 ResultPtr anObject = *aIt;
531 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
532 anObjects.append(anObject);
537 module()->activeSelectionModes(aModes);
538 myDisplayer->activateObjects(aModes, anObjects);
542 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
544 myModule->operationCommitted(theOperation);
547 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
549 myModule->operationAborted(theOperation);
552 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
554 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
558 QStringList aGrantedIds;
560 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
562 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
564 ModuleBase_IModule* aModule = module();
566 aModule->grantedOperationIds(theOperation, aGrantedIds);
568 aFOperation->setGrantedOperationIds(aGrantedIds);
571 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
573 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
578 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
579 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
581 myPropertyPanel->cleanContent();
582 aFactory.createWidget(myPropertyPanel->contentWidget());
584 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
586 // check compatibility of feature and widgets
587 FeaturePtr aFeature = aFOperation->feature();
588 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
589 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
590 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
591 + aWidget->attributeID() + "' used by widget '"
592 + aWidget->metaObject()->className() + "'.";
593 Events_Error::send(anErrorMsg);
594 myPropertyPanel->cleanContent();
599 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
600 bool isStoreValue = !aFOperation->isEditOperation() &&
601 !aWidget->getDefaultValue().empty() &&
602 !aWidget->isComputedDefault();
603 aWidget->setFeature(aFOperation->feature(), isStoreValue);
604 aWidget->enableFocusProcessing();
607 myPropertyPanel->setModelWidgets(aWidgets);
608 aFOperation->setPropertyPanel(myPropertyPanel);
610 myModule->propertyPanelDefined(theOperation);
612 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
614 myErrorMgr->setPropertyPanel(myPropertyPanel);
617 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
619 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
620 if (aPropertyPanel) {
621 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
622 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
623 myModule->connectToPropertyPanel(aWidget, isToConnect);
625 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
628 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
635 * Saves document with given name.
637 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
639 QApplication::restoreOverrideCursor();
640 SessionPtr aMgr = ModelAPI_Session::get();
641 aMgr->save(theName.toLatin1().constData(), theFileNames);
642 QApplication::restoreOverrideCursor();
645 bool XGUI_Workshop::abortAllOperations()
647 return myOperationMgr->abortAllOperations();
650 //******************************************************
651 void XGUI_Workshop::onOpen()
653 if(!abortAllOperations())
655 //save current file before close if modified
656 SessionPtr aSession = ModelAPI_Session::get();
657 if (aSession->isModified()) {
658 //TODO(sbh): re-launch the app?
659 int anAnswer = QMessageBox::question(
660 desktop(), tr("Save current file"),
661 tr("The document is modified, save before opening another?"),
662 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
663 if (anAnswer == QMessageBox::Save) {
665 } else if (anAnswer == QMessageBox::Cancel) {
671 //show file dialog, check if readable and open
672 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
673 if (myCurrentDir.isEmpty())
675 QFileInfo aFileInfo(myCurrentDir);
676 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
677 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
681 QApplication::setOverrideCursor(Qt::WaitCursor);
682 aSession->closeAll();
683 aSession->load(myCurrentDir.toLatin1().constData());
684 myObjectBrowser->rebuildDataTree();
685 updateCommandStatus();
686 QApplication::restoreOverrideCursor();
689 //******************************************************
690 void XGUI_Workshop::onNew()
692 QApplication::setOverrideCursor(Qt::WaitCursor);
693 if (objectBrowser() == 0) {
695 mySelector->connectViewers();
697 myViewerProxy->connectToViewer();
700 myMainWindow->showPythonConsole();
701 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
702 aWnd->showMaximized();
703 updateCommandStatus();
705 myContextMenuMgr->connectViewer();
706 QApplication::restoreOverrideCursor();
710 //******************************************************
711 void XGUI_Workshop::onExit()
713 SessionPtr aMgr = ModelAPI_Session::get();
714 if (aMgr->isModified()) {
715 int anAnswer = QMessageBox::question(
716 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
717 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
718 if (anAnswer == QMessageBox::Save) {
719 bool saved = onSave();
723 } else if (anAnswer == QMessageBox::Cancel) {
730 //******************************************************
731 void XGUI_Workshop::onPreferences()
733 ModuleBase_Prefs aModif;
734 ModuleBase_Preferences::editPreferences(aModif);
735 if (aModif.size() > 0) {
737 foreach (ModuleBase_Pref aPref, aModif)
739 aSection = aPref.first;
740 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
741 myMainWindow->viewer()->updateFromResources();
742 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
743 myMainWindow->menuObject()->updateFromResources();
746 displayer()->redisplayObjects();
751 //******************************************************
752 bool XGUI_Workshop::onSave()
754 if(!abortAllOperations())
756 if (myCurrentDir.isEmpty()) {
759 std::list<std::string> aFiles;
760 saveDocument(myCurrentDir, aFiles);
761 updateCommandStatus();
763 myMainWindow->setModifiedState(false);
768 //******************************************************
769 bool XGUI_Workshop::onSaveAs()
771 if(!abortAllOperations())
773 QFileDialog dialog(desktop());
774 dialog.setWindowTitle(tr("Select directory to save files..."));
775 dialog.setFileMode(QFileDialog::Directory);
776 dialog.setFilter(tr("Directories (*)"));
777 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
778 dialog.setViewMode(QFileDialog::Detail);
780 if (!dialog.exec()) {
784 QString aTempDir = dialog.selectedFiles().first();
786 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
787 int answer = QMessageBox::question(
789 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
791 tr("The directory already contains some files, save anyway?"),
792 QMessageBox::Save | QMessageBox::Cancel);
793 if (answer == QMessageBox::Cancel) {
797 myCurrentDir = aTempDir;
799 myMainWindow->setCurrentDir(myCurrentDir, false);
800 myMainWindow->setModifiedState(false);
805 //******************************************************
806 void XGUI_Workshop::onUndo(int theTimes)
808 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
809 SessionPtr aMgr = ModelAPI_Session::get();
810 std::list<std::string> aUndoList = aMgr->undoList();
811 if (aMgr->isOperation()) {
812 /// this is important for nested operations
813 /// when sketch operation is active, this condition is false and
814 /// the sketch operation is not aborted
815 operationMgr()->onAbortOperation();
817 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
818 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
820 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
821 myObjectBrowser->rebuildDataTree();
824 operationMgr()->updateApplyOfOperations();
825 updateCommandStatus();
828 //******************************************************
829 void XGUI_Workshop::onRedo(int theTimes)
831 // the viewer update should be blocked in order to avoid the features blinking. For the created
832 // feature a results are created, the flush of the created signal caused the viewer redisplay for
833 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
834 // redo of all possible objects happens
835 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
837 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
838 SessionPtr aMgr = ModelAPI_Session::get();
839 std::list<std::string> aRedoList = aMgr->redoList();
840 if (aMgr->isOperation()) {
841 /// this is important for nested operations
842 /// when sketch operation is active, this condition is false and
843 /// the sketch operation is not aborted
844 operationMgr()->onAbortOperation();
846 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
847 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
849 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
850 myObjectBrowser->rebuildDataTree();
852 operationMgr()->updateApplyOfOperations();
853 updateCommandStatus();
855 // unblock the viewer update functionality and make update on purpose
856 myDisplayer->enableUpdateViewer(isUpdateEnabled);
857 myDisplayer->updateViewer();
860 //******************************************************
861 //void XGUI_Workshop::onRebuild()
863 // SessionPtr aMgr = ModelAPI_Session::get();
864 // bool aWasOperation = aMgr->isOperation(); // keep this value
865 // if (!aWasOperation) {
866 // aMgr->startOperation("Rebuild");
868 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
869 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
870 // new Events_Message(aRebuildEvent, this)));
871 // if (!aWasOperation) {
872 // aMgr->finishOperation();
874 // updateCommandStatus();
877 //******************************************************
878 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
880 ModuleBase_ModelWidget* anActiveWidget = 0;
881 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
883 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
885 anActiveWidget = aPanel->activeWidget();
888 operationMgr()->onValidateOperation();
890 myModule->widgetStateChanged(thePreviousState);
893 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
895 QString libName = QString::fromStdString(library(theModule.toStdString()));
896 if (libName.isEmpty()) {
897 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
902 CREATE_FUNC crtInst = 0;
905 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
909 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
910 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
911 QString aMsg((char*) &lpMsgBuf);
912 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
913 ::LocalFree(lpMsgBuf);
915 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
919 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
920 | FORMAT_MESSAGE_IGNORE_INSERTS,
921 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
922 QString aMsg((char*) &lpMsgBuf);
923 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
924 ::LocalFree(lpMsgBuf);
928 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
930 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
932 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
934 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
939 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
941 if (!err.isEmpty()) {
943 Events_Error::send(err.toStdString());
945 qWarning(qPrintable(err));
951 //******************************************************
952 bool XGUI_Workshop::createModule()
954 Config_ModuleReader aModuleReader;
955 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
956 myModule = loadModule(moduleName);
960 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
961 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
962 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
963 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
965 myModule->createFeatures();
966 //myActionsMgr->update();
970 //******************************************************
971 void XGUI_Workshop::updateCommandStatus()
973 QList<QAction*> aCommands;
975 aCommands = salomeConnector()->commandList();
977 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
978 foreach (AppElements_Command* aCmd, aMenuBar->features())
979 aCommands.append(aCmd);
981 SessionPtr aMgr = ModelAPI_Session::get();
982 if (aMgr->hasModuleDocument()) {
983 foreach(QAction* aCmd, aCommands) {
984 QString aId = aCmd->data().toString();
985 if (aId == "UNDO_CMD")
986 aCmd->setEnabled(myModule->canUndo());
987 else if (aId == "REDO_CMD")
988 aCmd->setEnabled(myModule->canRedo());
990 // Enable all commands
991 aCmd->setEnabled(true);
995 foreach(QAction* aCmd, aCommands) {
996 QString aId = aCmd->data().toString();
997 if (aId == "NEW_CMD")
998 aCmd->setEnabled(true);
999 else if (aId == "EXIT_CMD")
1000 aCmd->setEnabled(true);
1002 aCmd->setEnabled(false);
1005 myActionsMgr->updateCommandsStatus();
1006 emit commandStatusUpdated();
1009 void XGUI_Workshop::updateHistory()
1011 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1012 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1013 emit updateUndoHistory(aUndoRes);
1015 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1016 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1017 emit updateRedoHistory(aRedoRes);
1020 //******************************************************
1021 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1023 QDockWidget* aObjDock = new QDockWidget(theParent);
1024 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1025 aObjDock->setWindowTitle(tr("Object browser"));
1026 aObjDock->setStyleSheet(
1027 "::title { position: relative; padding-left: 5px; text-align: left center }");
1028 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1029 myModule->customizeObjectBrowser(myObjectBrowser);
1030 aObjDock->setWidget(myObjectBrowser);
1032 myContextMenuMgr->connectObjectBrowser();
1036 //******************************************************
1038 * Creates dock widgets, places them in corresponding area
1039 * and tabifies if necessary.
1041 void XGUI_Workshop::createDockWidgets()
1043 QMainWindow* aDesktop = desktop();
1044 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1045 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1046 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1047 myPropertyPanel->setupActions(myActionsMgr);
1048 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1049 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1050 hidePropertyPanel(); ///<! Invisible by default
1051 hideObjectBrowser();
1052 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1053 myPropertyPanel->installEventFilter(myOperationMgr);
1055 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1056 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1058 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1059 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1060 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1061 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1063 connect(myPropertyPanel, SIGNAL(enterClicked()),
1064 myOperationMgr, SLOT(onProcessEnter()));
1065 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1066 // this, SLOT(onValidationStateChanged(bool)));
1069 //******************************************************
1070 void XGUI_Workshop::showPropertyPanel()
1072 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1073 ///<! Restore ability to close panel from the window's menu
1074 aViewAct->setEnabled(true);
1075 myPropertyPanel->show();
1076 myPropertyPanel->raise();
1078 // The next code is necessary to made the property panel the active window
1079 // in order to operation manager could process key events of the panel.
1080 // otherwise they are ignored. It happens only if the same(activateWindow) is
1081 // not happened by property panel activation(e.g. resume operation of Sketch)
1082 ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1083 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1086 //******************************************************
1087 void XGUI_Workshop::hidePropertyPanel()
1089 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1090 ///<! Do not allow to show empty property panel
1091 aViewAct->setEnabled(false);
1092 myPropertyPanel->hide();
1094 // the property panel is active window of the desktop, when it is
1095 // hidden, it is undefined which window becomes active. By this reason
1096 // it is defined to perform the desktop as the active window.
1097 // in SALOME mode, workstack made the PyConsole the active window,
1098 // set the focus on it. As a result, shortcuts of the application, like
1099 // are processed by this console. For example Undo actions.
1100 // It is possible that this code is to be moved to NewGeom package
1101 QMainWindow* aDesktop = desktop();
1102 ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1103 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1106 //******************************************************
1107 void XGUI_Workshop::showObjectBrowser()
1109 myObjectBrowser->parentWidget()->show();
1112 //******************************************************
1113 void XGUI_Workshop::hideObjectBrowser()
1115 myObjectBrowser->parentWidget()->hide();
1118 //******************************************************
1119 void XGUI_Workshop::salomeViewerSelectionChanged()
1121 emit salomeViewerSelection();
1124 //**************************************************************
1125 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1127 return mySalomeConnector->viewer();
1130 //**************************************************************
1131 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1133 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1134 if (theId == "DELETE_CMD")
1136 else if (theId == "MOVE_CMD")
1138 else if (theId == "COLOR_CMD")
1139 changeColor(aObjects);
1140 else if (theId == "SHOW_CMD")
1141 showObjects(aObjects, true);
1142 else if (theId == "HIDE_CMD")
1143 showObjects(aObjects, false);
1144 else if (theId == "SHOW_ONLY_CMD")
1145 showOnlyObjects(aObjects);
1146 else if (theId == "SHADING_CMD")
1147 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1148 else if (theId == "WIREFRAME_CMD")
1149 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1150 else if (theId == "HIDEALL_CMD") {
1151 QObjectPtrList aList = myDisplayer->displayedObjects();
1152 foreach (ObjectPtr aObj, aList) {
1153 if (module()->canEraseObject(aObj))
1154 aObj->setDisplayed(false);
1156 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1160 //**************************************************************
1161 void XGUI_Workshop::deleteObjects()
1163 ModuleBase_IModule* aModule = module();
1164 // 1. allow the module to delete objects, do nothing if it has succeed
1165 if (aModule->deleteObjects()) {
1166 updateCommandStatus();
1170 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1171 if (!abortAllOperations())
1173 // It is necessary to clear selection in order to avoid selection changed event during
1174 // deletion and negative consequences connected with processing of already deleted items
1175 mySelector->clearSelection();
1176 // check whether the object can be deleted. There should not be parts which are not loaded
1177 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1180 bool hasResult = false;
1181 bool hasFeature = false;
1182 bool hasParameter = false;
1183 bool hasSubFeature = false;
1184 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1185 if (!(hasFeature || hasParameter))
1188 // 1. start operation
1189 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1190 aDescription += tr(" %1");
1191 QStringList aObjectNames;
1192 foreach (ObjectPtr aObj, anObjects) {
1193 if (!aObj->data()->isValid())
1195 aObjectNames << QString::fromStdString(aObj->data()->name());
1197 aDescription = aDescription.arg(aObjectNames.join(", "));
1198 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1200 operationMgr()->startOperation(anOpAction);
1201 // 3. delete objects
1202 std::set<FeaturePtr> anIgnoredFeatures;
1203 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1204 operationMgr()->commitOperation();
1207 operationMgr()->abortOperation(operationMgr()->currentOperation());
1211 //**************************************************************
1212 void XGUI_Workshop::moveObjects()
1214 if (!abortAllOperations())
1217 SessionPtr aMgr = ModelAPI_Session::get();
1219 QString anActionId = "MOVE_CMD";
1220 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1221 aMgr->startOperation(aDescription.toStdString());
1223 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1224 // It is necessary to clear selection in order to avoid selection changed event during
1225 // moving and negative consequences connected with processing of already moved items
1226 mySelector->clearSelection();
1227 // check whether the object can be moved. There should not be parts which are not loaded
1228 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1231 DocumentPtr anActiveDocument = aMgr->activeDocument();
1232 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1233 foreach (ObjectPtr aObject, anObjects) {
1234 if (!myModule->canApplyAction(aObject, anActionId))
1237 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1238 if (aFeature.get()) {
1239 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1240 aCurrentFeature = anActiveDocument->currentFeature(true);
1243 aMgr->finishOperation();
1246 //**************************************************************
1247 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1248 const std::set<FeaturePtr>& theIgnoredFeatures,
1250 const bool theAskAboutDeleteReferences)
1254 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1255 for (; aDIt != aDLast; ++aDIt) {
1256 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1258 QString anInfoStr = aDInfo.join(", ");
1259 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1262 // 1. find all referenced features
1263 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1264 foreach (ObjectPtr aDeletedObj, theList) {
1265 std::set<FeaturePtr> alreadyProcessed;
1266 XGUI_Tools::refsToFeatureInAllDocuments(
1267 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1268 std::set<FeaturePtr> aDifference;
1269 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1270 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1271 std::inserter(aDifference, aDifference.begin()));
1272 aIndirectRefFeatures = aDifference;
1275 bool doDeleteReferences = true;
1277 // 2. warn about the references remove, break the delete operation if the user chose it
1278 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1279 QStringList aDirectRefNames;
1280 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1281 aDirectRefNames.append(aFeature->name().c_str());
1282 QString aDirectNames = aDirectRefNames.join(", ");
1284 QStringList aIndirectRefNames;
1285 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1286 aIndirectRefNames.append(aFeature->name().c_str());
1287 QString aIndirectNames = aIndirectRefNames.join(", ");
1289 bool canReplaceParameters = true;
1290 foreach (ObjectPtr aObj, theList) {
1291 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1292 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1293 canReplaceParameters = false;
1298 QMessageBox aMessageBox(theParent);
1299 aMessageBox.setWindowTitle(tr("Delete features"));
1300 aMessageBox.setIcon(QMessageBox::Warning);
1301 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1302 aMessageBox.setDefaultButton(QMessageBox::No);
1305 if (canReplaceParameters) {
1306 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?"))
1307 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1308 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1310 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1311 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1313 aMessageBox.setText(aText);
1315 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1317 if (aButtonRole == QMessageBox::NoRole)
1320 if (aButtonRole == QMessageBox::ActionRole) {
1321 foreach (ObjectPtr aObj, theList)
1322 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1323 doDeleteReferences = false;
1327 // 3. remove referenced features
1328 if (doDeleteReferences) {
1329 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1330 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1331 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1332 aLast = aFeaturesToDelete.end();
1336 for (; anIt != aLast; anIt++) {
1337 FeaturePtr aFeature = (*anIt);
1338 DocumentPtr aDoc = aFeature->document();
1339 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1340 aDoc->removeFeature(aFeature);
1342 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1347 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1352 QString anActionId = "DELETE_CMD";
1353 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1354 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1355 // 4. remove the parameter features
1356 foreach (ObjectPtr aObj, theList) {
1357 // features and parameters can be removed here,
1358 // the results are removed only by a corresponded feature remove
1359 std::string aGroupName = aObj->groupName();
1360 if (!anObjectGroups.contains(aGroupName.c_str()))
1363 if (!myModule->canApplyAction(aObj, anActionId))
1366 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1368 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1369 // part features are removed in the PartSet module. This condition should be moved there
1370 if (aFeature->getKind() == "Part")
1373 DocumentPtr aDoc = aObj->document();
1374 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1376 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1377 anInfo.append(anInfoStr);
1378 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1380 aDoc->removeFeature(aFeature);
1385 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1390 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1392 bool isFoundResultType = false;
1393 foreach(ObjectPtr anObj, theObjects)
1395 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1396 if (aResult.get() == NULL)
1399 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1400 if (isFoundResultType)
1403 return isFoundResultType;
1406 //**************************************************************
1407 // Returns the list of all features for theDocument and all features of
1408 // all nested parts.
1409 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1411 std::list<FeaturePtr> aResultList;
1412 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1413 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1414 // The order of appending features of the part and the part itself is important
1416 // Append features from a part feature
1417 foreach (const ResultPtr& aResult, aFeature->results()) {
1418 ResultPartPtr aResultPart =
1419 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1420 if (aResultPart.get() && aResultPart->partDoc().get()) {
1422 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1423 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1427 aResultList.push_back(aFeature);
1432 //**************************************************************
1433 // Returns the list of features placed between theObject and the current feature
1434 // in the same document. Excludes theObject, includes the current feature.
1435 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1437 std::list<FeaturePtr> aResult;
1438 DocumentPtr aDocument = theObject->document();
1439 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1440 // find the object iterator
1441 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1442 if (aObjectIt == anAllFeatures.end())
1444 // find the current feature iterator
1445 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1446 if (aCurrentIt == anAllFeatures.end())
1448 // check the right order
1449 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1451 // exclude the object
1452 std::advance(aObjectIt, 1);
1453 // include the current feature
1454 std::advance(aCurrentIt, 1);
1455 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1458 bool XGUI_Workshop::canMoveFeature()
1460 QString anActionId = "MOVE_CMD";
1462 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1463 QObjectPtrList aValidatedObjects;
1464 foreach (ObjectPtr aObject, aObjects) {
1465 if (!myModule->canApplyAction(aObject, anActionId))
1467 // To be moved feature should be in active document
1468 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1470 aValidatedObjects.append(aObject);
1472 if (aValidatedObjects.size() != aObjects.size())
1473 aObjects = aValidatedObjects;
1475 bool aCanMove = !aObjects.empty();
1477 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1478 for (; anIt != aLast && aCanMove; anIt++) {
1479 ObjectPtr aObject = *anIt;
1480 // 1. Get features placed between selected and current in the document
1481 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1482 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1483 if (aFeaturesBetween.empty())
1486 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1487 // 2. Get all reference features to the selected object in the document
1488 std::set<FeaturePtr> aRefFeatures;
1489 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1491 if (aRefFeatures.empty())
1494 // 3. Find any placed features in all reference features
1495 std::set<FeaturePtr> aIntersectionFeatures;
1496 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1497 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1498 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1499 // 4. Return false if any reference feature is placed before current feature
1500 if (!aIntersectionFeatures.empty())
1508 //**************************************************************
1509 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1511 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1512 if (!aCanBeShaded) {
1513 ResultCompSolidPtr aCompsolidResult =
1514 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1515 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1516 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1517 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1520 return aCanBeShaded;
1523 //**************************************************************
1524 bool XGUI_Workshop::canChangeColor() const
1526 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1528 std::set<std::string> aTypes;
1529 aTypes.insert(ModelAPI_ResultGroup::group());
1530 aTypes.insert(ModelAPI_ResultConstruction::group());
1531 aTypes.insert(ModelAPI_ResultBody::group());
1532 aTypes.insert(ModelAPI_ResultPart::group());
1534 return hasResults(aObjects, aTypes);
1537 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1539 if (!theResult.get())
1542 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1543 if (aColorAttr.get() != NULL) {
1544 if (!aColorAttr->size()) {
1545 aColorAttr->setSize(3);
1547 aColorAttr->setValue(0, theColor[0]);
1548 aColorAttr->setValue(1, theColor[1]);
1549 aColorAttr->setValue(2, theColor[2]);
1553 //**************************************************************
1554 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1557 AttributeIntArrayPtr aColorAttr;
1558 // 1. find the current color of the object. This is a color of AIS presentation
1559 // The objects are iterated until a first valid color is found
1560 std::vector<int> aColor;
1561 foreach(ObjectPtr anObject, theObjects) {
1562 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1563 if (aResult.get()) {
1564 XGUI_CustomPrs::getResultColor(aResult, aColor);
1567 // TODO: remove the obtaining a color from the AIS object
1568 // this does not happen never because:
1569 // 1. The color can be changed only on results
1570 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1571 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1572 if (anAISObj.get()) {
1574 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1577 if (!aColor.empty())
1580 if (aColor.size() != 3)
1583 if (!abortAllOperations())
1585 // 2. show the dialog to change the value
1586 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1587 aDlg->setColor(aColor);
1588 aDlg->move(QCursor::pos());
1589 bool isDone = aDlg->exec() == QDialog::Accepted;
1593 bool isRandomColor = aDlg->isRandomColor();
1595 // 3. abort the previous operation and start a new one
1596 SessionPtr aMgr = ModelAPI_Session::get();
1597 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1598 aMgr->startOperation(aDescription.toStdString());
1600 // 4. set the value to all results
1601 std::vector<int> aColorResult = aDlg->getColor();
1602 foreach(ObjectPtr anObj, theObjects) {
1603 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1604 if (aResult.get() != NULL) {
1605 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1606 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1607 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1608 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1611 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1614 aMgr->finishOperation();
1615 updateCommandStatus();
1618 //**************************************************************
1619 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1620 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1621 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1623 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1625 foreach (ObjectPtr aObj, theList) {
1627 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1629 DocumentPtr aDoc = aPartRes->partDoc();
1630 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1631 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1632 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1635 aObj->setDisplayed(isVisible);
1638 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1641 //**************************************************************
1642 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1644 // Hide all displayed objects
1645 QObjectPtrList aList = myDisplayer->displayedObjects();
1646 foreach (ObjectPtr aObj, aList) {
1647 if (module()->canEraseObject(aObj))
1648 aObj->setDisplayed(false);
1651 // Show only objects from the list
1652 foreach (ObjectPtr aObj, theList) {
1654 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1656 DocumentPtr aDoc = aPartRes->partDoc();
1657 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1658 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1659 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1662 aObj->setDisplayed(true);
1665 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1670 //**************************************************************
1671 void XGUI_Workshop::registerValidators() const
1673 SessionPtr aMgr = ModelAPI_Session::get();
1674 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1677 //**************************************************************
1678 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1682 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1683 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1686 //**************************************************************
1687 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1689 for (int i = 0; i < theDoc->size(theGroup); i++)
1690 theDoc->object(theGroup, i)->setDisplayed(true);
1691 //displayObject(theDoc->object(theGroup, i));
1692 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1695 //**************************************************************
1696 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1698 foreach(ObjectPtr aObj, theList) {
1699 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1701 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1702 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1703 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1704 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1705 (XGUI_Displayer::DisplayMode)theMode, false);
1709 if (theList.size() > 0)
1710 myDisplayer->updateViewer();
1713 //**************************************************************
1714 void XGUI_Workshop::closeDocument()
1716 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1717 while (anOperation) {
1718 anOperation->abort();
1719 anOperation = operationMgr()->currentOperation();
1721 myDisplayer->closeLocalContexts();
1722 myDisplayer->eraseAll();
1723 objectBrowser()->clearContent();
1725 module()->closeDocument();
1727 SessionPtr aMgr = ModelAPI_Session::get();
1731 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1733 XGUI_HistoryMenu* aMenu = NULL;
1734 if (isSalomeMode()) {
1735 QAction* anAction = qobject_cast<QAction*>(theObject);
1738 aMenu = new XGUI_HistoryMenu(anAction);
1740 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1741 aMenu = new XGUI_HistoryMenu(aButton);
1743 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1744 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1747 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1749 QList<ActionInfo> aResult;
1750 std::list<std::string>::const_iterator it = theList.cbegin();
1751 for (; it != theList.cend(); it++) {
1752 QString anId = QString::fromStdString(*it);
1753 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1755 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1758 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1759 if (aContextMenuAct) {
1760 anInfo.initFrom(aContextMenuAct);
1762 anInfo = myActionsMgr->actionInfoById(anId);
1765 anInfo.text = anInfo.text.prepend("Modify ");
1772 void XGUI_Workshop::synchronizeViewer()
1774 SessionPtr aMgr = ModelAPI_Session::get();
1775 DocumentPtr aDoc = aMgr->activeDocument();
1777 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1778 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1779 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1780 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1783 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1784 const std::string& theGroup,
1785 bool theUpdateViewer)
1788 int aSize = theDoc->size(theGroup);
1789 for (int i = 0; i < aSize; i++) {
1790 aObj = theDoc->object(theGroup, i);
1791 if (aObj->isDisplayed())
1792 myDisplayer->display(aObj, false);
1794 if (theUpdateViewer)
1795 myDisplayer->updateViewer();