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()), myModule, SLOT(onNoMoreWidgets()));
1014 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1015 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1016 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1017 // this, SLOT(onValidationStateChanged(bool)));
1020 //******************************************************
1021 void XGUI_Workshop::showPropertyPanel()
1023 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1024 ///<! Restore ability to close panel from the window's menu
1025 aViewAct->setEnabled(true);
1026 myPropertyPanel->show();
1027 myPropertyPanel->raise();
1029 // The next code is necessary to made the property panel the active window
1030 // in order to operation manager could process key events of the panel.
1031 // otherwise they are ignored. It happens only if the same(activateWindow) is
1032 // not happened by property panel activation(e.g. resume operation of Sketch)
1033 myPropertyPanel->activateWindow();
1034 myPropertyPanel->setFocus();
1037 //******************************************************
1038 void XGUI_Workshop::hidePropertyPanel()
1040 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1041 ///<! Do not allow to show empty property panel
1042 aViewAct->setEnabled(false);
1043 myPropertyPanel->hide();
1045 // the property panel is active window of the desktop, when it is
1046 // hidden, it is undefined which window becomes active. By this reason
1047 // it is defined to perform the desktop as the active window.
1048 // in SALOME mode, workstack made the PyConsole the active window,
1049 // set the focus on it. As a result, shortcuts of the application, like
1050 // are processed by this console. For example Undo actions.
1051 // It is possible that this code is to be moved to NewGeom package
1052 QMainWindow* aDesktop = desktop();
1053 aDesktop->activateWindow();
1054 aDesktop->setFocus();
1057 //******************************************************
1058 void XGUI_Workshop::showObjectBrowser()
1060 myObjectBrowser->parentWidget()->show();
1063 //******************************************************
1064 void XGUI_Workshop::hideObjectBrowser()
1066 myObjectBrowser->parentWidget()->hide();
1069 //******************************************************
1070 void XGUI_Workshop::salomeViewerSelectionChanged()
1072 emit salomeViewerSelection();
1075 //**************************************************************
1076 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1078 return mySalomeConnector->viewer();
1081 //**************************************************************
1082 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1084 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1085 if (theId == "DELETE_CMD")
1087 else if (theId == "MOVE_CMD")
1089 else if (theId == "COLOR_CMD")
1090 changeColor(aObjects);
1091 else if (theId == "SHOW_CMD")
1092 showObjects(aObjects, true);
1093 else if (theId == "HIDE_CMD")
1094 showObjects(aObjects, false);
1095 else if (theId == "SHOW_ONLY_CMD")
1096 showOnlyObjects(aObjects);
1097 else if (theId == "SHADING_CMD")
1098 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1099 else if (theId == "WIREFRAME_CMD")
1100 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1101 else if (theId == "HIDEALL_CMD") {
1102 QObjectPtrList aList = myDisplayer->displayedObjects();
1103 foreach (ObjectPtr aObj, aList) {
1104 if (module()->canEraseObject(aObj))
1105 aObj->setDisplayed(false);
1107 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1111 //**************************************************************
1112 void XGUI_Workshop::deleteObjects()
1114 ModuleBase_IModule* aModule = module();
1115 // 1. allow the module to delete objects, do nothing if it has succeed
1116 if (aModule->deleteObjects()) {
1117 updateCommandStatus();
1121 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1122 if (!abortAllOperations())
1124 // It is necessary to clear selection in order to avoid selection changed event during
1125 // deletion and negative consequences connected with processing of already deleted items
1126 mySelector->clearSelection();
1127 // check whether the object can be deleted. There should not be parts which are not loaded
1128 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1131 bool hasResult = false;
1132 bool hasFeature = false;
1133 bool hasParameter = false;
1134 bool hasSubFeature = false;
1135 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1136 if (!(hasFeature || hasParameter))
1139 // 1. start operation
1140 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1141 aDescription += tr(" %1");
1142 QStringList aObjectNames;
1143 foreach (ObjectPtr aObj, anObjects) {
1144 if (!aObj->data()->isValid())
1146 aObjectNames << QString::fromStdString(aObj->data()->name());
1148 aDescription = aDescription.arg(aObjectNames.join(", "));
1149 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1151 operationMgr()->startOperation(anOpAction);
1152 // 3. delete objects
1153 std::set<FeaturePtr> anIgnoredFeatures;
1154 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1155 operationMgr()->commitOperation();
1158 operationMgr()->abortOperation(operationMgr()->currentOperation());
1162 //**************************************************************
1163 void XGUI_Workshop::moveObjects()
1165 if (!abortAllOperations())
1168 SessionPtr aMgr = ModelAPI_Session::get();
1170 QString anActionId = "MOVE_CMD";
1171 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1172 aMgr->startOperation(aDescription.toStdString());
1174 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1175 // It is necessary to clear selection in order to avoid selection changed event during
1176 // moving and negative consequences connected with processing of already moved items
1177 mySelector->clearSelection();
1178 // check whether the object can be moved. There should not be parts which are not loaded
1179 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1182 DocumentPtr anActiveDocument = aMgr->activeDocument();
1183 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1184 foreach (ObjectPtr aObject, anObjects) {
1185 if (!myModule->canApplyAction(aObject, anActionId))
1188 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1189 if (aFeature.get()) {
1190 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1191 aCurrentFeature = anActiveDocument->currentFeature(true);
1194 aMgr->finishOperation();
1197 //**************************************************************
1198 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1199 const std::set<FeaturePtr>& theIgnoredFeatures,
1201 const bool theAskAboutDeleteReferences)
1205 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1206 for (; aDIt != aDLast; ++aDIt) {
1207 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1209 QString anInfoStr = aDInfo.join(", ");
1210 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1213 // 1. find all referenced features
1214 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1215 foreach (ObjectPtr aDeletedObj, theList) {
1216 std::set<FeaturePtr> alreadyProcessed;
1217 XGUI_Tools::refsToFeatureInAllDocuments(
1218 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1219 std::set<FeaturePtr> aDifference;
1220 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1221 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1222 std::inserter(aDifference, aDifference.begin()));
1223 aIndirectRefFeatures = aDifference;
1226 bool doDeleteReferences = true;
1228 // 2. warn about the references remove, break the delete operation if the user chose it
1229 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1230 QStringList aDirectRefNames;
1231 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1232 aDirectRefNames.append(aFeature->name().c_str());
1233 QString aDirectNames = aDirectRefNames.join(", ");
1235 QStringList aIndirectRefNames;
1236 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1237 aIndirectRefNames.append(aFeature->name().c_str());
1238 QString aIndirectNames = aIndirectRefNames.join(", ");
1240 bool canReplaceParameters = true;
1241 foreach (ObjectPtr aObj, theList) {
1242 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1243 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1244 canReplaceParameters = false;
1249 QMessageBox aMessageBox(theParent);
1250 aMessageBox.setWindowTitle(tr("Delete features"));
1251 aMessageBox.setIcon(QMessageBox::Warning);
1252 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1253 aMessageBox.setDefaultButton(QMessageBox::No);
1256 if (canReplaceParameters) {
1257 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?"))
1258 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1259 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1261 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1262 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1264 aMessageBox.setText(aText);
1266 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1268 if (aButtonRole == QMessageBox::NoRole)
1271 if (aButtonRole == QMessageBox::ActionRole) {
1272 foreach (ObjectPtr aObj, theList)
1273 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1274 doDeleteReferences = false;
1278 // 3. remove referenced features
1279 if (doDeleteReferences) {
1280 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1281 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1282 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1283 aLast = aFeaturesToDelete.end();
1287 for (; anIt != aLast; anIt++) {
1288 FeaturePtr aFeature = (*anIt);
1289 DocumentPtr aDoc = aFeature->document();
1290 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1291 aDoc->removeFeature(aFeature);
1293 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1298 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1303 QString anActionId = "DELETE_CMD";
1304 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1305 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1306 // 4. remove the parameter features
1307 foreach (ObjectPtr aObj, theList) {
1308 // features and parameters can be removed here,
1309 // the results are removed only by a corresponded feature remove
1310 std::string aGroupName = aObj->groupName();
1311 if (!anObjectGroups.contains(aGroupName.c_str()))
1314 if (!myModule->canApplyAction(aObj, anActionId))
1317 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1319 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1320 // part features are removed in the PartSet module. This condition should be moved there
1321 if (aFeature->getKind() == "Part")
1324 DocumentPtr aDoc = aObj->document();
1325 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1327 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1328 anInfo.append(anInfoStr);
1329 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1331 aDoc->removeFeature(aFeature);
1336 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1341 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1343 bool isFoundResultType = false;
1344 foreach(ObjectPtr anObj, theObjects)
1346 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1347 if (aResult.get() == NULL)
1350 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1351 if (isFoundResultType)
1354 return isFoundResultType;
1357 //**************************************************************
1358 // Returns the list of all features for theDocument and all features of
1359 // all nested parts.
1360 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1362 std::list<FeaturePtr> aResultList;
1363 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1364 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1365 // The order of appending features of the part and the part itself is important
1367 // Append features from a part feature
1368 foreach (const ResultPtr& aResult, aFeature->results()) {
1369 ResultPartPtr aResultPart =
1370 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1371 if (aResultPart.get() && aResultPart->partDoc().get()) {
1373 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1374 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1378 aResultList.push_back(aFeature);
1383 //**************************************************************
1384 // Returns the list of features placed between theObject and the current feature
1385 // in the same document. Excludes theObject, includes the current feature.
1386 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1388 std::list<FeaturePtr> aResult;
1389 DocumentPtr aDocument = theObject->document();
1390 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1391 // find the object iterator
1392 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1393 if (aObjectIt == anAllFeatures.end())
1395 // find the current feature iterator
1396 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1397 if (aCurrentIt == anAllFeatures.end())
1399 // check the right order
1400 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1402 // exclude the object
1403 std::advance(aObjectIt, 1);
1404 // include the current feature
1405 std::advance(aCurrentIt, 1);
1406 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1409 bool XGUI_Workshop::canMoveFeature()
1411 QString anActionId = "MOVE_CMD";
1413 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1414 QObjectPtrList aValidatedObjects;
1415 foreach (ObjectPtr aObject, aObjects) {
1416 if (!myModule->canApplyAction(aObject, anActionId))
1418 // To be moved feature should be in active document
1419 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1421 aValidatedObjects.append(aObject);
1423 if (aValidatedObjects.size() != aObjects.size())
1424 aObjects = aValidatedObjects;
1426 bool aCanMove = !aObjects.empty();
1428 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1429 for (; anIt != aLast && aCanMove; anIt++) {
1430 ObjectPtr aObject = *anIt;
1431 // 1. Get features placed between selected and current in the document
1432 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1433 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1434 if (aFeaturesBetween.empty())
1437 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1438 // 2. Get all reference features to the selected object in the document
1439 std::set<FeaturePtr> aRefFeatures;
1440 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1442 if (aRefFeatures.empty())
1445 // 3. Find any placed features in all reference features
1446 std::set<FeaturePtr> aIntersectionFeatures;
1447 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1448 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1449 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1450 // 4. Return false if any reference feature is placed before current feature
1451 if (!aIntersectionFeatures.empty())
1459 //**************************************************************
1460 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1462 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1463 if (!aCanBeShaded) {
1464 ResultCompSolidPtr aCompsolidResult =
1465 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1466 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1467 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1468 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1471 return aCanBeShaded;
1474 //**************************************************************
1475 bool XGUI_Workshop::canChangeColor() const
1477 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1479 std::set<std::string> aTypes;
1480 aTypes.insert(ModelAPI_ResultGroup::group());
1481 aTypes.insert(ModelAPI_ResultConstruction::group());
1482 aTypes.insert(ModelAPI_ResultBody::group());
1483 aTypes.insert(ModelAPI_ResultPart::group());
1485 return hasResults(aObjects, aTypes);
1488 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1490 if (!theResult.get())
1493 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1494 if (aColorAttr.get() != NULL) {
1495 if (!aColorAttr->size()) {
1496 aColorAttr->setSize(3);
1498 aColorAttr->setValue(0, theColor[0]);
1499 aColorAttr->setValue(1, theColor[1]);
1500 aColorAttr->setValue(2, theColor[2]);
1504 //**************************************************************
1505 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1508 AttributeIntArrayPtr aColorAttr;
1509 // 1. find the current color of the object. This is a color of AIS presentation
1510 // The objects are iterated until a first valid color is found
1511 std::vector<int> aColor;
1512 foreach(ObjectPtr anObject, theObjects) {
1513 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1514 if (aResult.get()) {
1515 XGUI_CustomPrs::getResultColor(aResult, aColor);
1518 // TODO: remove the obtaining a color from the AIS object
1519 // this does not happen never because:
1520 // 1. The color can be changed only on results
1521 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1522 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1523 if (anAISObj.get()) {
1525 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1528 if (!aColor.empty())
1531 if (aColor.size() != 3)
1534 if (!abortAllOperations())
1536 // 2. show the dialog to change the value
1537 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1538 aDlg->setColor(aColor);
1539 aDlg->move(QCursor::pos());
1540 bool isDone = aDlg->exec() == QDialog::Accepted;
1544 bool isRandomColor = aDlg->isRandomColor();
1546 // 3. abort the previous operation and start a new one
1547 SessionPtr aMgr = ModelAPI_Session::get();
1548 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1549 aMgr->startOperation(aDescription.toStdString());
1551 // 4. set the value to all results
1552 std::vector<int> aColorResult = aDlg->getColor();
1553 foreach(ObjectPtr anObj, theObjects) {
1554 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1555 if (aResult.get() != NULL) {
1556 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1557 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1558 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1559 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1562 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1565 aMgr->finishOperation();
1566 updateCommandStatus();
1569 //**************************************************************
1570 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1571 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1572 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1574 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1576 foreach (ObjectPtr aObj, theList) {
1578 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1580 DocumentPtr aDoc = aPartRes->partDoc();
1581 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1582 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1583 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1586 aObj->setDisplayed(isVisible);
1589 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1592 //**************************************************************
1593 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1595 // Hide all displayed objects
1596 QObjectPtrList aList = myDisplayer->displayedObjects();
1597 foreach (ObjectPtr aObj, aList) {
1598 if (module()->canEraseObject(aObj))
1599 aObj->setDisplayed(false);
1602 // Show only objects from the list
1603 foreach (ObjectPtr aObj, theList) {
1605 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1607 DocumentPtr aDoc = aPartRes->partDoc();
1608 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1609 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1610 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1613 aObj->setDisplayed(true);
1616 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1621 //**************************************************************
1622 void XGUI_Workshop::registerValidators() const
1624 SessionPtr aMgr = ModelAPI_Session::get();
1625 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1628 //**************************************************************
1629 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1633 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1634 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1637 //**************************************************************
1638 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1640 for (int i = 0; i < theDoc->size(theGroup); i++)
1641 theDoc->object(theGroup, i)->setDisplayed(true);
1642 //displayObject(theDoc->object(theGroup, i));
1643 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1646 //**************************************************************
1647 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1649 foreach(ObjectPtr aObj, theList) {
1650 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1652 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1653 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1654 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1655 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1656 (XGUI_Displayer::DisplayMode)theMode, false);
1660 if (theList.size() > 0)
1661 myDisplayer->updateViewer();
1664 //**************************************************************
1665 void XGUI_Workshop::closeDocument()
1667 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1668 while (anOperation) {
1669 anOperation->abort();
1670 anOperation = operationMgr()->currentOperation();
1672 myDisplayer->closeLocalContexts();
1673 myDisplayer->eraseAll();
1674 objectBrowser()->clearContent();
1676 module()->closeDocument();
1678 SessionPtr aMgr = ModelAPI_Session::get();
1682 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1684 XGUI_HistoryMenu* aMenu = NULL;
1685 if (isSalomeMode()) {
1686 QAction* anAction = qobject_cast<QAction*>(theObject);
1689 aMenu = new XGUI_HistoryMenu(anAction);
1691 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1692 aMenu = new XGUI_HistoryMenu(aButton);
1694 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1695 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1698 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1700 QList<ActionInfo> aResult;
1701 std::list<std::string>::const_iterator it = theList.cbegin();
1702 for (; it != theList.cend(); it++) {
1703 QString anId = QString::fromStdString(*it);
1704 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1706 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1709 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1710 if (aContextMenuAct) {
1711 anInfo.initFrom(aContextMenuAct);
1713 anInfo = myActionsMgr->actionInfoById(anId);
1716 anInfo.text = anInfo.text.prepend("Modify ");
1723 void XGUI_Workshop::synchronizeViewer()
1725 SessionPtr aMgr = ModelAPI_Session::get();
1726 DocumentPtr aDoc = aMgr->activeDocument();
1728 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1729 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1730 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1731 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1734 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1735 const std::string& theGroup,
1736 bool theUpdateViewer)
1739 int aSize = theDoc->size(theGroup);
1740 for (int i = 0; i < aSize; i++) {
1741 aObj = theDoc->object(theGroup, i);
1742 if (aObj->isDisplayed())
1743 myDisplayer->display(aObj, false);
1745 if (theUpdateViewer)
1746 myDisplayer->updateViewer();