1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Workshop.h"
6 #include "XGUI_ActionsMgr.h"
7 #include "XGUI_ColorDialog.h"
8 #include "XGUI_ContextMenuMgr.h"
9 #include "XGUI_Displayer.h"
10 #include "XGUI_ErrorDialog.h"
11 #include "XGUI_ErrorMgr.h"
12 #include "XGUI_ModuleConnector.h"
13 #include "XGUI_ObjectsBrowser.h"
14 #include "XGUI_OperationMgr.h"
15 #include "XGUI_PropertyPanel.h"
16 #include "XGUI_SalomeConnector.h"
17 #include "XGUI_Selection.h"
18 #include "XGUI_SelectionMgr.h"
19 #include "XGUI_Tools.h"
20 #include "XGUI_ViewerProxy.h"
21 #include "XGUI_WorkshopListener.h"
22 #include <XGUI_CustomPrs.h>
23 #include <XGUI_HistoryMenu.h>
24 #include <XGUI_QtEvents.h>
27 #include <AppElements_Button.h>
28 #include <AppElements_Command.h>
29 #include <AppElements_MainMenu.h>
30 #include <AppElements_MainWindow.h>
31 #include <AppElements_MenuGroupPanel.h>
32 #include <AppElements_Viewer.h>
33 #include <AppElements_Workbench.h>
36 #include <ModelAPI_AttributeDocRef.h>
37 #include <ModelAPI_AttributeIntArray.h>
38 #include <ModelAPI_Data.h>
39 #include <ModelAPI_Events.h>
40 #include <ModelAPI_Feature.h>
41 #include <ModelAPI_Object.h>
42 #include <ModelAPI_ResultBody.h>
43 #include <ModelAPI_ResultConstruction.h>
44 #include <ModelAPI_ResultGroup.h>
45 #include <ModelAPI_ResultParameter.h>
46 #include <ModelAPI_Session.h>
47 #include <ModelAPI_Validator.h>
48 #include <ModelAPI_ResultCompSolid.h>
49 #include <ModelAPI_Tools.h>
51 //#include <PartSetPlugin_Part.h>
53 #include <Events_Loop.h>
54 #include <Events_Error.h>
55 #include <Events_LongOp.h>
57 #include <ModuleBase_FilterFactory.h>
58 #include <ModuleBase_IModule.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_Operation.h>
61 #include <ModuleBase_OperationDescription.h>
62 #include <ModuleBase_PageBase.h>
63 #include <ModuleBase_Preferences.h>
64 #include <ModuleBase_SelectionValidator.h>
65 #include <ModuleBase_Tools.h>
66 #include <ModuleBase_WidgetFactory.h>
67 #include <ModuleBase_OperationFeature.h>
68 #include <ModuleBase_OperationAction.h>
70 #include <Config_Common.h>
71 #include <Config_FeatureMessage.h>
72 #include <Config_ModuleReader.h>
73 #include <Config_PointerMessage.h>
74 #include <Config_PropManager.h>
75 #include <Config_SelectionFilterMessage.h>
77 #include <SUIT_ResourceMgr.h>
79 #include <QApplication>
80 #include <QFileDialog>
81 #include <QMessageBox>
82 #include <QMdiSubWindow>
83 #include <QMainWindow>
84 #include <QPushButton>
85 #include <QDockWidget>
90 #include <QToolButton>
92 #include <QDesktopWidget>
107 //#define DEBUG_DELETE
109 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
111 myCurrentDir(QString()),
113 mySalomeConnector(theConnector),
119 myMainWindow = new AppElements_MainWindow();
121 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
122 bool aCloc = aResMgr->booleanValue("language", "locale", true);
124 QLocale::setDefault( QLocale::c() );
126 QLocale::setDefault( QLocale::system() );
129 myDisplayer = new XGUI_Displayer(this);
131 mySelector = new XGUI_SelectionMgr(this);
132 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
134 myOperationMgr = new XGUI_OperationMgr(this, 0);
135 myActionsMgr = new XGUI_ActionsMgr(this);
136 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
137 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
138 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
139 SLOT(onContextMenuCommand(const QString&, bool)));
141 myViewerProxy = new XGUI_ViewerProxy(this);
142 connect(myViewerProxy, SIGNAL(selectionChanged()),
143 myActionsMgr, SLOT(updateOnViewSelection()));
145 myModuleConnector = new XGUI_ModuleConnector(this);
147 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
148 myOperationMgr->setWorkshop(aWorkshop);
150 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
151 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
153 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
154 SLOT(onOperationStarted(ModuleBase_Operation*)));
155 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
156 SLOT(onOperationResumed(ModuleBase_Operation*)));
157 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
158 SLOT(onOperationStopped(ModuleBase_Operation*)));
159 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
160 SLOT(onOperationCommitted(ModuleBase_Operation*)));
161 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
162 SLOT(onOperationAborted(ModuleBase_Operation*)));
163 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
164 // myErrorMgr, SLOT(onValidationStateChanged()));
167 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
170 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
171 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
172 myErrorDlg, SLOT(addError(const QString&)));
174 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
175 // Config_Prop::Color, "225,225,225");
177 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
178 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
179 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
180 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
181 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
182 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
183 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
184 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
187 //******************************************************
188 XGUI_Workshop::~XGUI_Workshop(void)
193 //******************************************************
194 void XGUI_Workshop::startApplication()
198 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
199 Config_Prop::Directory, "");
201 //Initialize event listening
202 myEventsListener->initializeEventListening();
204 registerValidators();
206 // Calling of loadCustomProps before activating module is required
207 // by Config_PropManger to restore user-defined path to plugins
208 ModuleBase_Preferences::loadCustomProps();
212 myMainWindow->show();
213 updateCommandStatus();
218 emit applicationStarted();
221 void XGUI_Workshop::activateModule()
223 myModule->activateSelectionFilters();
225 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
226 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
227 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
228 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
230 myActionsMgr->update();
232 // activate visualized objects in the viewer
233 XGUI_Displayer* aDisplayer = displayer();
234 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
236 module()->activeSelectionModes(aModes);
237 aDisplayer->activateObjects(aModes, aDisplayed);
240 void XGUI_Workshop::deactivateModule()
242 myModule->deactivateSelectionFilters();
244 // remove internal displayer filter
245 displayer()->deactivateSelectionFilters();
247 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
248 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
249 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
250 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
252 XGUI_Displayer* aDisplayer = displayer();
253 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
254 aDisplayer->deactivateObjects(aDisplayed, true);
257 //******************************************************
258 void XGUI_Workshop::initMenu()
260 myContextMenuMgr->createActions();
263 // Create only Undo, Redo commands
264 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
265 tr("Undo last command"),
266 QIcon(":pictures/undo.png"),
267 QKeySequence::Undo, false, "MEN_DESK_EDIT");
268 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
269 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
271 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
272 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
274 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
275 QIcon(":pictures/redo.png"), QKeySequence::Redo,
276 false, "MEN_DESK_EDIT");
277 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
279 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
280 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
282 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
283 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
284 QIcon(":pictures/rebuild.png"), QKeySequence(),
285 false, "MEN_DESK_EDIT");
286 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
288 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
289 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
291 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
292 QIcon(), QKeySequence(),
293 false, "MEN_DESK_FILE");
294 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
296 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
297 QIcon(), QKeySequence(),
298 false, "MEN_DESK_FILE");
299 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
300 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
303 // File commands group
304 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
306 AppElements_Command* aCommand;
308 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
309 QIcon(":pictures/save.png"), QKeySequence::Save);
310 aCommand->connectTo(this, SLOT(onSave()));
311 //aCommand->disable();
313 QString aUndoId = "UNDO_CMD";
314 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
315 QIcon(":pictures/undo.png"), QKeySequence::Undo);
316 aCommand->connectTo(this, SLOT(onUndo()));
317 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
318 addHistoryMenu(aUndoButton,
319 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
322 QString aRedoId = "REDO_CMD";
323 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
324 QIcon(":pictures/redo.png"), QKeySequence::Redo);
325 aCommand->connectTo(this, SLOT(onRedo()));
326 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
327 addHistoryMenu(aRedoButton,
328 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
331 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
332 QIcon(":pictures/rebuild.png"), QKeySequence());
333 aCommand->connectTo(this, SLOT(onRebuild()));
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()));
338 //aCommand->disable();
340 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
341 QIcon(":pictures/open.png"), QKeySequence::Open);
342 aCommand->connectTo(this, SLOT(onOpen()));
344 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
345 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
346 aCommand->connectTo(this, SLOT(onPreferences()));
348 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
349 QIcon(":pictures/close.png"), QKeySequence::Close);
350 aCommand->connectTo(this, SLOT(onExit()));
355 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
357 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
358 return aMenuBar->addWorkbench(theName);
362 //******************************************************
363 QMainWindow* XGUI_Workshop::desktop() const
366 return salomeConnector()->desktop();
372 //******************************************************
373 void XGUI_Workshop::onStartWaiting()
375 if (Events_LongOp::isPerformed()) {
376 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
380 //******************************************************
381 void XGUI_Workshop::onAcceptActionClicked()
383 QAction* anAction = dynamic_cast<QAction*>(sender());
384 XGUI_OperationMgr* anOperationMgr = operationMgr();
385 if (anOperationMgr) {
386 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
387 (anOperationMgr->currentOperation());
389 if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
390 myOperationMgr->onCommitOperation();
395 //******************************************************
396 /*void XGUI_Workshop::onValidationStateChanged(bool theEnabled)
398 XGUI_OperationMgr* anOperationMgr = operationMgr();
399 if (anOperationMgr) {
400 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
401 (anOperationMgr->currentOperation());
403 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
404 myErrorMgr->updateActionState(anAction, aFOperation->feature(), theEnabled);
410 //******************************************************
411 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
413 if (!myModule->canActivateSelection(theObject)) {
414 if (myDisplayer->isActive(theObject)) {
415 QObjectPtrList anObjects;
416 anObjects.append(theObject);
417 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
422 //******************************************************
423 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
425 bool aHasNested = false;
426 std::string aFeatureKind = theFeature->getKind();
428 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
429 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
432 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
433 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
434 if (aCommand && aCommand->button()->additionalButtonWidget())
440 //******************************************************
441 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
443 setGrantedFeatures(theOperation);
445 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
450 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
451 setPropertyPanel(aFOperation);
452 // filling the operation values by the current selection
453 // if the operation can be committed after the controls filling, the method perform should
454 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
455 if (!aFOperation->isEditOperation()) {
456 aFOperation->activateByPreselection();
457 if (operationMgr()->currentOperation() != aFOperation)
461 updateCommandStatus();
463 myModule->onOperationStarted(aFOperation);
465 // the objects of the current operation should be deactivated
466 QObjectPtrList anObjects;
467 FeaturePtr aFeature = aFOperation->feature();
468 anObjects.append(aFeature);
469 std::list<ResultPtr> aResults = aFeature->results();
470 std::list<ResultPtr>::const_iterator aIt;
471 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
472 anObjects.append(*aIt);
474 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
475 for (; anIt != aLast; anIt++)
476 deactivateActiveObject(*anIt, false);
477 if (anObjects.size() > 0)
478 myDisplayer->updateViewer();
481 //******************************************************
482 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
484 setGrantedFeatures(theOperation);
486 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
487 setPropertyPanel(theOperation);
489 updateCommandStatus();
491 myModule->onOperationResumed(theOperation);
495 //******************************************************
496 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
498 updateCommandStatus();
500 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
505 ModuleBase_ISelection* aSel = mySelector->selection();
506 QObjectPtrList aObj = aSel->selectedPresentations();
507 //!< No need for property panel
509 myPropertyPanel->cleanContent();
511 myModule->onOperationStopped(aFOperation);
513 // the deactivated objects of the current operation should be activated back.
514 // They were deactivated on operation start or an object redisplay
515 QObjectPtrList anObjects;
516 FeaturePtr aFeature = aFOperation->feature();
517 if (aFeature.get()) { // feature may be not created (plugin load fail)
518 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
519 anObjects.append(aFeature);
520 std::list<ResultPtr> aResults = aFeature->results();
521 std::list<ResultPtr>::const_iterator aIt;
522 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
523 ResultPtr anObject = *aIt;
524 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
525 anObjects.append(anObject);
530 module()->activeSelectionModes(aModes);
531 myDisplayer->activateObjects(aModes, anObjects);
535 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
537 myModule->onOperationCommitted(theOperation);
540 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
542 myModule->onOperationAborted(theOperation);
545 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
547 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
551 QStringList aGrantedIds;
553 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
555 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
557 ModuleBase_IModule* aModule = module();
559 aModule->grantedOperationIds(theOperation, aGrantedIds);
561 aFOperation->setGrantedOperationIds(aGrantedIds);
564 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
566 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
571 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
572 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
574 myPropertyPanel->cleanContent();
575 aFactory.createWidget(myPropertyPanel->contentWidget());
577 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
579 // check compatibility of feature and widgets
580 FeaturePtr aFeature = aFOperation->feature();
581 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
582 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
583 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
584 + aWidget->attributeID() + "' used by widget '"
585 + aWidget->metaObject()->className() + "'.";
586 Events_Error::send(anErrorMsg);
587 myPropertyPanel->cleanContent();
592 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
593 bool isStoreValue = !aFOperation->isEditOperation() &&
594 !aWidget->getDefaultValue().empty() &&
595 !aWidget->isComputedDefault();
596 aWidget->setFeature(aFOperation->feature(), isStoreValue);
597 aWidget->enableFocusProcessing();
600 myPropertyPanel->setModelWidgets(aWidgets);
601 aFOperation->setPropertyPanel(myPropertyPanel);
603 myModule->propertyPanelDefined(theOperation);
605 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
607 myErrorMgr->setPropertyPanel(myPropertyPanel);
611 * Saves document with given name.
613 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
615 QApplication::restoreOverrideCursor();
616 SessionPtr aMgr = ModelAPI_Session::get();
617 aMgr->save(theName.toLatin1().constData(), theFileNames);
618 QApplication::restoreOverrideCursor();
621 bool XGUI_Workshop::abortAllOperations()
623 return myOperationMgr->abortAllOperations();
626 //******************************************************
627 void XGUI_Workshop::onOpen()
629 if(!abortAllOperations())
631 //save current file before close if modified
632 SessionPtr aSession = ModelAPI_Session::get();
633 if (aSession->isModified()) {
634 //TODO(sbh): re-launch the app?
635 int anAnswer = QMessageBox::question(
636 desktop(), tr("Save current file"),
637 tr("The document is modified, save before opening another?"),
638 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
639 if (anAnswer == QMessageBox::Save) {
641 } else if (anAnswer == QMessageBox::Cancel) {
647 //show file dialog, check if readable and open
648 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
649 if (myCurrentDir.isEmpty())
651 QFileInfo aFileInfo(myCurrentDir);
652 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
653 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
657 QApplication::setOverrideCursor(Qt::WaitCursor);
658 aSession->closeAll();
659 aSession->load(myCurrentDir.toLatin1().constData());
660 myObjectBrowser->rebuildDataTree();
661 updateCommandStatus();
662 QApplication::restoreOverrideCursor();
665 //******************************************************
666 void XGUI_Workshop::onNew()
668 QApplication::setOverrideCursor(Qt::WaitCursor);
669 if (objectBrowser() == 0) {
671 mySelector->connectViewers();
673 myViewerProxy->connectToViewer();
676 myMainWindow->showPythonConsole();
677 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
678 aWnd->showMaximized();
679 updateCommandStatus();
681 myContextMenuMgr->connectViewer();
682 QApplication::restoreOverrideCursor();
686 //******************************************************
687 void XGUI_Workshop::onExit()
689 SessionPtr aMgr = ModelAPI_Session::get();
690 if (aMgr->isModified()) {
691 int anAnswer = QMessageBox::question(
692 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
693 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
694 if (anAnswer == QMessageBox::Save) {
695 bool saved = onSave();
699 } else if (anAnswer == QMessageBox::Cancel) {
706 //******************************************************
707 void XGUI_Workshop::onPreferences()
709 ModuleBase_Prefs aModif;
710 ModuleBase_Preferences::editPreferences(aModif);
711 if (aModif.size() > 0) {
713 foreach (ModuleBase_Pref aPref, aModif)
715 aSection = aPref.first;
716 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
717 myMainWindow->viewer()->updateFromResources();
718 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
719 myMainWindow->menuObject()->updateFromResources();
722 displayer()->redisplayObjects();
727 //******************************************************
728 bool XGUI_Workshop::onSave()
730 if(!abortAllOperations())
732 if (myCurrentDir.isEmpty()) {
735 std::list<std::string> aFiles;
736 saveDocument(myCurrentDir, aFiles);
737 updateCommandStatus();
739 myMainWindow->setModifiedState(false);
744 //******************************************************
745 bool XGUI_Workshop::onSaveAs()
747 if(!abortAllOperations())
749 QFileDialog dialog(desktop());
750 dialog.setWindowTitle(tr("Select directory to save files..."));
751 dialog.setFileMode(QFileDialog::Directory);
752 dialog.setFilter(tr("Directories (*)"));
753 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
754 dialog.setViewMode(QFileDialog::Detail);
756 if (!dialog.exec()) {
760 QString aTempDir = dialog.selectedFiles().first();
762 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
763 int answer = QMessageBox::question(
765 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
767 tr("The directory already contains some files, save anyway?"),
768 QMessageBox::Save | QMessageBox::Cancel);
769 if (answer == QMessageBox::Cancel) {
773 myCurrentDir = aTempDir;
775 myMainWindow->setCurrentDir(myCurrentDir, false);
776 myMainWindow->setModifiedState(false);
781 //******************************************************
782 void XGUI_Workshop::onUndo(int theTimes)
784 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
785 SessionPtr aMgr = ModelAPI_Session::get();
786 if (aMgr->isOperation()) {
787 /// this is important for nested operations
788 /// when sketch operation is active, this condition is false and
789 /// the sketch operation is not aborted
790 operationMgr()->onAbortOperation();
792 for (int i = 0; i < theTimes; ++i) {
796 operationMgr()->updateApplyOfOperations();
797 updateCommandStatus();
800 //******************************************************
801 void XGUI_Workshop::onRedo(int theTimes)
803 // the viewer update should be blocked in order to avoid the features blinking. For the created
804 // feature a results are created, the flush of the created signal caused the viewer redisplay for
805 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
806 // redo of all possible objects happens
807 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
809 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
810 SessionPtr aMgr = ModelAPI_Session::get();
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 for (int i = 0; i < theTimes; ++i) {
820 operationMgr()->updateApplyOfOperations();
821 updateCommandStatus();
823 // unblock the viewer update functionality and make update on purpose
824 myDisplayer->enableUpdateViewer(isUpdateEnabled);
825 myDisplayer->updateViewer();
828 //******************************************************
829 void XGUI_Workshop::onRebuild()
831 SessionPtr aMgr = ModelAPI_Session::get();
832 bool aWasOperation = aMgr->isOperation(); // keep this value
833 if (!aWasOperation) {
834 aMgr->startOperation("Rebuild");
836 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
837 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
838 new Events_Message(aRebuildEvent, this)));
839 if (!aWasOperation) {
840 aMgr->finishOperation();
842 updateCommandStatus();
845 //******************************************************
846 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
848 QString libName = QString::fromStdString(library(theModule.toStdString()));
849 if (libName.isEmpty()) {
850 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
855 CREATE_FUNC crtInst = 0;
858 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
862 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
863 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
864 QString aMsg((char*) &lpMsgBuf);
865 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
866 ::LocalFree(lpMsgBuf);
868 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
872 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
873 | FORMAT_MESSAGE_IGNORE_INSERTS,
874 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
875 QString aMsg((char*) &lpMsgBuf);
876 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
877 ::LocalFree(lpMsgBuf);
881 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
883 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
885 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
887 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
892 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
894 if (!err.isEmpty()) {
896 Events_Error::send(err.toStdString());
898 qWarning(qPrintable(err));
904 //******************************************************
905 bool XGUI_Workshop::createModule()
907 Config_ModuleReader aModuleReader;
908 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
909 myModule = loadModule(moduleName);
913 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
914 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
915 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
916 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
918 myModule->createFeatures();
919 //myActionsMgr->update();
923 //******************************************************
924 void XGUI_Workshop::updateCommandStatus()
926 QList<QAction*> aCommands;
928 aCommands = salomeConnector()->commandList();
930 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
931 foreach (AppElements_Command* aCmd, aMenuBar->features())
932 aCommands.append(aCmd);
934 SessionPtr aMgr = ModelAPI_Session::get();
935 if (aMgr->hasModuleDocument()) {
936 foreach(QAction* aCmd, aCommands) {
937 QString aId = aCmd->data().toString();
938 if (aId == "UNDO_CMD")
939 aCmd->setEnabled(myModule->canUndo());
940 else if (aId == "REDO_CMD")
941 aCmd->setEnabled(myModule->canRedo());
943 // Enable all commands
944 aCmd->setEnabled(true);
948 foreach(QAction* aCmd, aCommands) {
949 QString aId = aCmd->data().toString();
950 if (aId == "NEW_CMD")
951 aCmd->setEnabled(true);
952 else if (aId == "EXIT_CMD")
953 aCmd->setEnabled(true);
955 aCmd->setEnabled(false);
958 myActionsMgr->update();
959 emit commandStatusUpdated();
962 void XGUI_Workshop::updateHistory()
964 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
965 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
966 emit updateUndoHistory(aUndoRes);
968 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
969 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
970 emit updateRedoHistory(aRedoRes);
973 //******************************************************
974 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
976 QDockWidget* aObjDock = new QDockWidget(theParent);
977 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
978 aObjDock->setWindowTitle(tr("Object browser"));
979 aObjDock->setStyleSheet(
980 "::title { position: relative; padding-left: 5px; text-align: left center }");
981 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
982 myModule->customizeObjectBrowser(myObjectBrowser);
983 aObjDock->setWidget(myObjectBrowser);
985 myContextMenuMgr->connectObjectBrowser();
989 //******************************************************
991 * Creates dock widgets, places them in corresponding area
992 * and tabifies if necessary.
994 void XGUI_Workshop::createDockWidgets()
996 QMainWindow* aDesktop = desktop();
997 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
998 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
999 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1000 myPropertyPanel->setupActions(myActionsMgr);
1001 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1002 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1003 hidePropertyPanel(); ///<! Invisible by default
1004 hideObjectBrowser();
1005 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1006 myPropertyPanel->installEventFilter(myOperationMgr);
1008 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1009 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1011 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1012 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1013 connect(myPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
1014 myModule, SLOT(onNoMoreWidgets(const std::string&)));
1015 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1016 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1017 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1018 // this, SLOT(onValidationStateChanged(bool)));
1021 //******************************************************
1022 void XGUI_Workshop::showPropertyPanel()
1024 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1025 ///<! Restore ability to close panel from the window's menu
1026 aViewAct->setEnabled(true);
1027 myPropertyPanel->show();
1028 myPropertyPanel->raise();
1030 // The next code is necessary to made the property panel the active window
1031 // in order to operation manager could process key events of the panel.
1032 // otherwise they are ignored. It happens only if the same(activateWindow) is
1033 // not happened by property panel activation(e.g. resume operation of Sketch)
1034 myPropertyPanel->activateWindow();
1035 myPropertyPanel->setFocus();
1038 //******************************************************
1039 void XGUI_Workshop::hidePropertyPanel()
1041 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1042 ///<! Do not allow to show empty property panel
1043 aViewAct->setEnabled(false);
1044 myPropertyPanel->hide();
1046 // the property panel is active window of the desktop, when it is
1047 // hidden, it is undefined which window becomes active. By this reason
1048 // it is defined to perform the desktop as the active window.
1049 // in SALOME mode, workstack made the PyConsole the active window,
1050 // set the focus on it. As a result, shortcuts of the application, like
1051 // are processed by this console. For example Undo actions.
1052 // It is possible that this code is to be moved to NewGeom package
1053 QMainWindow* aDesktop = desktop();
1054 aDesktop->activateWindow();
1055 aDesktop->setFocus();
1058 //******************************************************
1059 void XGUI_Workshop::showObjectBrowser()
1061 myObjectBrowser->parentWidget()->show();
1064 //******************************************************
1065 void XGUI_Workshop::hideObjectBrowser()
1067 myObjectBrowser->parentWidget()->hide();
1070 //******************************************************
1071 void XGUI_Workshop::salomeViewerSelectionChanged()
1073 emit salomeViewerSelection();
1076 //**************************************************************
1077 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1079 return mySalomeConnector->viewer();
1082 //**************************************************************
1083 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1085 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1086 if (theId == "DELETE_CMD")
1088 else if (theId == "MOVE_CMD")
1090 else if (theId == "COLOR_CMD")
1091 changeColor(aObjects);
1092 else if (theId == "SHOW_CMD")
1093 showObjects(aObjects, true);
1094 else if (theId == "HIDE_CMD")
1095 showObjects(aObjects, false);
1096 else if (theId == "SHOW_ONLY_CMD")
1097 showOnlyObjects(aObjects);
1098 else if (theId == "SHADING_CMD")
1099 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1100 else if (theId == "WIREFRAME_CMD")
1101 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1102 else if (theId == "HIDEALL_CMD") {
1103 QObjectPtrList aList = myDisplayer->displayedObjects();
1104 foreach (ObjectPtr aObj, aList) {
1105 if (module()->canEraseObject(aObj))
1106 aObj->setDisplayed(false);
1108 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1112 //**************************************************************
1113 void XGUI_Workshop::deleteObjects()
1115 ModuleBase_IModule* aModule = module();
1116 // 1. allow the module to delete objects, do nothing if it has succeed
1117 if (aModule->deleteObjects()) {
1118 updateCommandStatus();
1122 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1123 if (!abortAllOperations())
1125 // It is necessary to clear selection in order to avoid selection changed event during
1126 // deletion and negative consequences connected with processing of already deleted items
1127 mySelector->clearSelection();
1128 // check whether the object can be deleted. There should not be parts which are not loaded
1129 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1132 bool hasResult = false;
1133 bool hasFeature = false;
1134 bool hasParameter = false;
1135 bool hasSubFeature = false;
1136 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1137 if (!(hasFeature || hasParameter))
1140 // 1. start operation
1141 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1142 aDescription += tr(" %1");
1143 QStringList aObjectNames;
1144 foreach (ObjectPtr aObj, anObjects) {
1145 if (!aObj->data()->isValid())
1147 aObjectNames << QString::fromStdString(aObj->data()->name());
1149 aDescription = aDescription.arg(aObjectNames.join(", "));
1150 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1152 operationMgr()->startOperation(anOpAction);
1153 // 3. delete objects
1154 std::set<FeaturePtr> anIgnoredFeatures;
1155 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1156 operationMgr()->commitOperation();
1159 operationMgr()->abortOperation(operationMgr()->currentOperation());
1163 //**************************************************************
1164 void XGUI_Workshop::moveObjects()
1166 if (!abortAllOperations())
1169 SessionPtr aMgr = ModelAPI_Session::get();
1171 QString anActionId = "MOVE_CMD";
1172 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1173 aMgr->startOperation(aDescription.toStdString());
1175 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1176 // It is necessary to clear selection in order to avoid selection changed event during
1177 // moving and negative consequences connected with processing of already moved items
1178 mySelector->clearSelection();
1179 // check whether the object can be moved. There should not be parts which are not loaded
1180 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1183 DocumentPtr anActiveDocument = aMgr->activeDocument();
1184 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1185 foreach (ObjectPtr aObject, anObjects) {
1186 if (!myModule->canApplyAction(aObject, anActionId))
1189 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1190 if (aFeature.get()) {
1191 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1192 aCurrentFeature = anActiveDocument->currentFeature(true);
1195 aMgr->finishOperation();
1198 //**************************************************************
1199 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1200 const std::set<FeaturePtr>& theIgnoredFeatures,
1202 const bool theAskAboutDeleteReferences)
1206 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1207 for (; aDIt != aDLast; ++aDIt) {
1208 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1210 QString anInfoStr = aDInfo.join(", ");
1211 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1214 // 1. find all referenced features
1215 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1216 foreach (ObjectPtr aDeletedObj, theList) {
1217 std::set<FeaturePtr> alreadyProcessed;
1218 XGUI_Tools::refsToFeatureInAllDocuments(
1219 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1220 std::set<FeaturePtr> aDifference;
1221 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1222 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1223 std::inserter(aDifference, aDifference.begin()));
1224 aIndirectRefFeatures = aDifference;
1227 bool doDeleteReferences = true;
1229 // 2. warn about the references remove, break the delete operation if the user chose it
1230 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1231 QStringList aDirectRefNames;
1232 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1233 aDirectRefNames.append(aFeature->name().c_str());
1234 QString aDirectNames = aDirectRefNames.join(", ");
1236 QStringList aIndirectRefNames;
1237 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1238 aIndirectRefNames.append(aFeature->name().c_str());
1239 QString aIndirectNames = aIndirectRefNames.join(", ");
1241 bool canReplaceParameters = true;
1242 foreach (ObjectPtr aObj, theList) {
1243 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1244 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1245 canReplaceParameters = false;
1250 QMessageBox aMessageBox(theParent);
1251 aMessageBox.setWindowTitle(tr("Delete features"));
1252 aMessageBox.setIcon(QMessageBox::Warning);
1253 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1254 aMessageBox.setDefaultButton(QMessageBox::No);
1257 if (canReplaceParameters) {
1258 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?"))
1259 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1260 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1262 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1263 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1265 aMessageBox.setText(aText);
1267 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1269 if (aButtonRole == QMessageBox::NoRole)
1272 if (aButtonRole == QMessageBox::ActionRole) {
1273 foreach (ObjectPtr aObj, theList)
1274 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1275 doDeleteReferences = false;
1279 // 3. remove referenced features
1280 if (doDeleteReferences) {
1281 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1282 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1283 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1284 aLast = aFeaturesToDelete.end();
1288 for (; anIt != aLast; anIt++) {
1289 FeaturePtr aFeature = (*anIt);
1290 DocumentPtr aDoc = aFeature->document();
1291 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1292 aDoc->removeFeature(aFeature);
1294 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1299 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1304 QString anActionId = "DELETE_CMD";
1305 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1306 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1307 // 4. remove the parameter features
1308 foreach (ObjectPtr aObj, theList) {
1309 // features and parameters can be removed here,
1310 // the results are removed only by a corresponded feature remove
1311 std::string aGroupName = aObj->groupName();
1312 if (!anObjectGroups.contains(aGroupName.c_str()))
1315 if (!myModule->canApplyAction(aObj, anActionId))
1318 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1320 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1321 // part features are removed in the PartSet module. This condition should be moved there
1322 if (aFeature->getKind() == "Part")
1325 DocumentPtr aDoc = aObj->document();
1326 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1328 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1329 anInfo.append(anInfoStr);
1330 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1332 aDoc->removeFeature(aFeature);
1337 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1342 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1344 bool isFoundResultType = false;
1345 foreach(ObjectPtr anObj, theObjects)
1347 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1348 if (aResult.get() == NULL)
1351 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1352 if (isFoundResultType)
1355 return isFoundResultType;
1358 //**************************************************************
1359 // Returns the list of all features for theDocument and all features of
1360 // all nested parts.
1361 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1363 std::list<FeaturePtr> aResultList;
1364 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1365 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1366 // The order of appending features of the part and the part itself is important
1368 // Append features from a part feature
1369 foreach (const ResultPtr& aResult, aFeature->results()) {
1370 ResultPartPtr aResultPart =
1371 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1372 if (aResultPart.get() && aResultPart->partDoc().get()) {
1374 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1375 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1379 aResultList.push_back(aFeature);
1384 //**************************************************************
1385 // Returns the list of features placed between theObject and the current feature
1386 // in the same document. Excludes theObject, includes the current feature.
1387 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1389 std::list<FeaturePtr> aResult;
1390 DocumentPtr aDocument = theObject->document();
1391 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1392 // find the object iterator
1393 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1394 if (aObjectIt == anAllFeatures.end())
1396 // find the current feature iterator
1397 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1398 if (aCurrentIt == anAllFeatures.end())
1400 // check the right order
1401 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1403 // exclude the object
1404 std::advance(aObjectIt, 1);
1405 // include the current feature
1406 std::advance(aCurrentIt, 1);
1407 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1410 bool XGUI_Workshop::canMoveFeature()
1412 QString anActionId = "MOVE_CMD";
1414 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1415 QObjectPtrList aValidatedObjects;
1416 foreach (ObjectPtr aObject, aObjects) {
1417 if (!myModule->canApplyAction(aObject, anActionId))
1419 // To be moved feature should be in active document
1420 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1422 aValidatedObjects.append(aObject);
1424 if (aValidatedObjects.size() != aObjects.size())
1425 aObjects = aValidatedObjects;
1427 bool aCanMove = !aObjects.empty();
1429 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1430 for (; anIt != aLast && aCanMove; anIt++) {
1431 ObjectPtr aObject = *anIt;
1432 // 1. Get features placed between selected and current in the document
1433 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1434 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1435 if (aFeaturesBetween.empty())
1438 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1439 // 2. Get all reference features to the selected object in the document
1440 std::set<FeaturePtr> aRefFeatures;
1441 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1443 if (aRefFeatures.empty())
1446 // 3. Find any placed features in all reference features
1447 std::set<FeaturePtr> aIntersectionFeatures;
1448 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1449 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1450 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1451 // 4. Return false if any reference feature is placed before current feature
1452 if (!aIntersectionFeatures.empty())
1460 //**************************************************************
1461 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1463 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1464 if (!aCanBeShaded) {
1465 ResultCompSolidPtr aCompsolidResult =
1466 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1467 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1468 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1469 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1472 return aCanBeShaded;
1475 //**************************************************************
1476 bool XGUI_Workshop::canChangeColor() const
1478 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1480 std::set<std::string> aTypes;
1481 aTypes.insert(ModelAPI_ResultGroup::group());
1482 aTypes.insert(ModelAPI_ResultConstruction::group());
1483 aTypes.insert(ModelAPI_ResultBody::group());
1484 aTypes.insert(ModelAPI_ResultPart::group());
1486 return hasResults(aObjects, aTypes);
1489 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1491 if (!theResult.get())
1494 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1495 if (aColorAttr.get() != NULL) {
1496 if (!aColorAttr->size()) {
1497 aColorAttr->setSize(3);
1499 aColorAttr->setValue(0, theColor[0]);
1500 aColorAttr->setValue(1, theColor[1]);
1501 aColorAttr->setValue(2, theColor[2]);
1505 //**************************************************************
1506 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1509 AttributeIntArrayPtr aColorAttr;
1510 // 1. find the current color of the object. This is a color of AIS presentation
1511 // The objects are iterated until a first valid color is found
1512 std::vector<int> aColor;
1513 foreach(ObjectPtr anObject, theObjects) {
1514 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1515 if (aResult.get()) {
1516 XGUI_CustomPrs::getResultColor(aResult, aColor);
1519 // TODO: remove the obtaining a color from the AIS object
1520 // this does not happen never because:
1521 // 1. The color can be changed only on results
1522 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1523 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1524 if (anAISObj.get()) {
1526 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1529 if (!aColor.empty())
1532 if (aColor.size() != 3)
1535 if (!abortAllOperations())
1537 // 2. show the dialog to change the value
1538 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1539 aDlg->setColor(aColor);
1540 aDlg->move(QCursor::pos());
1541 bool isDone = aDlg->exec() == QDialog::Accepted;
1545 bool isRandomColor = aDlg->isRandomColor();
1547 // 3. abort the previous operation and start a new one
1548 SessionPtr aMgr = ModelAPI_Session::get();
1549 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1550 aMgr->startOperation(aDescription.toStdString());
1552 // 4. set the value to all results
1553 std::vector<int> aColorResult = aDlg->getColor();
1554 foreach(ObjectPtr anObj, theObjects) {
1555 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1556 if (aResult.get() != NULL) {
1557 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1558 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1559 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1560 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1563 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1566 aMgr->finishOperation();
1567 updateCommandStatus();
1570 //**************************************************************
1571 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1572 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1573 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1575 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1577 foreach (ObjectPtr aObj, theList) {
1579 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1581 DocumentPtr aDoc = aPartRes->partDoc();
1582 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1583 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1584 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1587 aObj->setDisplayed(isVisible);
1590 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1593 //**************************************************************
1594 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1596 // Hide all displayed objects
1597 QObjectPtrList aList = myDisplayer->displayedObjects();
1598 foreach (ObjectPtr aObj, aList) {
1599 if (module()->canEraseObject(aObj))
1600 aObj->setDisplayed(false);
1603 // Show only objects from the list
1604 foreach (ObjectPtr aObj, theList) {
1606 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1608 DocumentPtr aDoc = aPartRes->partDoc();
1609 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1610 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1611 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1614 aObj->setDisplayed(true);
1617 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1622 //**************************************************************
1623 void XGUI_Workshop::registerValidators() const
1625 SessionPtr aMgr = ModelAPI_Session::get();
1626 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1629 //**************************************************************
1630 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1634 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1635 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1638 //**************************************************************
1639 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1641 for (int i = 0; i < theDoc->size(theGroup); i++)
1642 theDoc->object(theGroup, i)->setDisplayed(true);
1643 //displayObject(theDoc->object(theGroup, i));
1644 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1647 //**************************************************************
1648 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1650 foreach(ObjectPtr aObj, theList) {
1651 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1653 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1654 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1655 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1656 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1657 (XGUI_Displayer::DisplayMode)theMode, false);
1661 if (theList.size() > 0)
1662 myDisplayer->updateViewer();
1665 //**************************************************************
1666 void XGUI_Workshop::closeDocument()
1668 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1669 while (anOperation) {
1670 anOperation->abort();
1671 anOperation = operationMgr()->currentOperation();
1673 myDisplayer->closeLocalContexts();
1674 myDisplayer->eraseAll();
1675 objectBrowser()->clearContent();
1677 module()->closeDocument();
1679 SessionPtr aMgr = ModelAPI_Session::get();
1683 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1685 XGUI_HistoryMenu* aMenu = NULL;
1686 if (isSalomeMode()) {
1687 QAction* anAction = qobject_cast<QAction*>(theObject);
1690 aMenu = new XGUI_HistoryMenu(anAction);
1692 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1693 aMenu = new XGUI_HistoryMenu(aButton);
1695 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1696 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1699 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1701 QList<ActionInfo> aResult;
1702 std::list<std::string>::const_iterator it = theList.cbegin();
1703 for (; it != theList.cend(); it++) {
1704 QString anId = QString::fromStdString(*it);
1705 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1707 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1710 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1711 if (aContextMenuAct) {
1712 anInfo.initFrom(aContextMenuAct);
1714 anInfo = myActionsMgr->actionInfoById(anId);
1717 anInfo.text = anInfo.text.prepend("Modify ");
1724 void XGUI_Workshop::synchronizeViewer()
1726 SessionPtr aMgr = ModelAPI_Session::get();
1727 DocumentPtr aDoc = aMgr->activeDocument();
1729 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1730 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1731 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1732 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1735 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1736 const std::string& theGroup,
1737 bool theUpdateViewer)
1740 int aSize = theDoc->size(theGroup);
1741 for (int i = 0; i < aSize; i++) {
1742 aObj = theDoc->object(theGroup, i);
1743 if (aObj->isDisplayed())
1744 myDisplayer->display(aObj, false);
1746 if (theUpdateViewer)
1747 myDisplayer->updateViewer();