1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Workshop.h"
6 #include "XGUI_ActionsMgr.h"
7 #include "XGUI_ColorDialog.h"
8 #include "XGUI_ContextMenuMgr.h"
9 #include "XGUI_Displayer.h"
10 #include "XGUI_ErrorDialog.h"
11 #include "XGUI_ErrorMgr.h"
12 #include "XGUI_ModuleConnector.h"
13 #include "XGUI_ObjectsBrowser.h"
14 #include "XGUI_OperationMgr.h"
15 #include "XGUI_PropertyPanel.h"
16 #include "XGUI_SalomeConnector.h"
17 #include "XGUI_Selection.h"
18 #include "XGUI_SelectionMgr.h"
19 #include "XGUI_Tools.h"
20 #include "XGUI_ViewerProxy.h"
21 #include "XGUI_WorkshopListener.h"
22 #include <XGUI_CustomPrs.h>
23 #include <XGUI_HistoryMenu.h>
24 #include <XGUI_QtEvents.h>
27 #include <AppElements_Button.h>
28 #include <AppElements_Command.h>
29 #include <AppElements_MainMenu.h>
30 #include <AppElements_MainWindow.h>
31 #include <AppElements_MenuGroupPanel.h>
32 #include <AppElements_Viewer.h>
33 #include <AppElements_Workbench.h>
36 #include <ModelAPI_AttributeDocRef.h>
37 #include <ModelAPI_AttributeIntArray.h>
38 #include <ModelAPI_Data.h>
39 #include <ModelAPI_Events.h>
40 #include <ModelAPI_Feature.h>
41 #include <ModelAPI_Object.h>
42 #include <ModelAPI_ResultBody.h>
43 #include <ModelAPI_ResultConstruction.h>
44 #include <ModelAPI_ResultGroup.h>
45 #include <ModelAPI_ResultParameter.h>
46 #include <ModelAPI_Session.h>
47 #include <ModelAPI_Validator.h>
48 #include <ModelAPI_ResultCompSolid.h>
49 #include <ModelAPI_Tools.h>
51 //#include <PartSetPlugin_Part.h>
53 #include <Events_Loop.h>
54 #include <Events_Error.h>
55 #include <Events_LongOp.h>
57 #include <ModuleBase_FilterFactory.h>
58 #include <ModuleBase_IModule.h>
59 #include <ModuleBase_IViewer.h>
60 #include <ModuleBase_Operation.h>
61 #include <ModuleBase_OperationDescription.h>
62 #include <ModuleBase_PageBase.h>
63 #include <ModuleBase_Preferences.h>
64 #include <ModuleBase_SelectionValidator.h>
65 #include <ModuleBase_Tools.h>
66 #include <ModuleBase_WidgetFactory.h>
67 #include <ModuleBase_OperationFeature.h>
68 #include <ModuleBase_OperationAction.h>
70 #include <Config_Common.h>
71 #include <Config_FeatureMessage.h>
72 #include <Config_ModuleReader.h>
73 #include <Config_PointerMessage.h>
74 #include <Config_PropManager.h>
75 #include <Config_SelectionFilterMessage.h>
77 #include <SUIT_ResourceMgr.h>
79 #include <QApplication>
80 #include <QFileDialog>
81 #include <QMessageBox>
82 #include <QMdiSubWindow>
83 #include <QMainWindow>
84 #include <QPushButton>
85 #include <QDockWidget>
90 #include <QToolButton>
92 #include <QDesktopWidget>
108 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
110 //#define DEBUG_DELETE
112 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
114 myCurrentDir(QString()),
116 mySalomeConnector(theConnector),
122 myMainWindow = new AppElements_MainWindow();
124 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
125 bool aCloc = aResMgr->booleanValue("language", "locale", true);
127 QLocale::setDefault( QLocale::c() );
129 QLocale::setDefault( QLocale::system() );
132 myDisplayer = new XGUI_Displayer(this);
134 mySelector = new XGUI_SelectionMgr(this);
135 connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
137 myOperationMgr = new XGUI_OperationMgr(this, 0);
138 myActionsMgr = new XGUI_ActionsMgr(this);
139 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
140 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
141 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
142 SLOT(onContextMenuCommand(const QString&, bool)));
144 myViewerProxy = new XGUI_ViewerProxy(this);
145 connect(myViewerProxy, SIGNAL(selectionChanged()),
146 myActionsMgr, SLOT(updateOnViewSelection()));
148 myModuleConnector = new XGUI_ModuleConnector(this);
150 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
151 myOperationMgr->setWorkshop(aWorkshop);
153 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
154 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
156 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
157 SLOT(onOperationStarted(ModuleBase_Operation*)));
158 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
159 SLOT(onOperationResumed(ModuleBase_Operation*)));
160 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
161 SLOT(onOperationStopped(ModuleBase_Operation*)));
162 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
163 SLOT(onOperationCommitted(ModuleBase_Operation*)));
164 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
165 SLOT(onOperationAborted(ModuleBase_Operation*)));
168 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
169 onTrihedronVisibilityChanged(true);
172 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
173 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
174 myErrorDlg, SLOT(addError(const QString&)));
176 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
177 // Config_Prop::Color, "225,225,225");
179 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
180 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
181 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
182 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
183 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
184 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
185 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
186 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
189 //******************************************************
190 XGUI_Workshop::~XGUI_Workshop(void)
195 //******************************************************
196 void XGUI_Workshop::startApplication()
200 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
201 Config_Prop::Directory, "");
203 //Initialize event listening
204 myEventsListener->initializeEventListening();
206 registerValidators();
208 // Calling of loadCustomProps before activating module is required
209 // by Config_PropManger to restore user-defined path to plugins
210 ModuleBase_Preferences::loadCustomProps();
214 myMainWindow->show();
215 updateCommandStatus();
220 myViewerProxy->connectViewProxy();
221 connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
222 SLOT(onTrihedronVisibilityChanged(bool)));
224 emit applicationStarted();
227 void XGUI_Workshop::activateModule()
229 myModule->activateSelectionFilters();
231 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
232 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
233 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
234 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
236 updateCommandStatus();
238 // activate visualized objects in the viewer
239 XGUI_Displayer* aDisplayer = displayer();
240 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
242 module()->activeSelectionModes(aModes);
243 aDisplayer->activateObjects(aModes, aDisplayed);
246 void XGUI_Workshop::deactivateModule()
248 myModule->deactivateSelectionFilters();
250 // remove internal displayer filter
251 displayer()->deactivateSelectionFilters();
253 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
254 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
255 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
256 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
258 XGUI_Displayer* aDisplayer = displayer();
259 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
260 aDisplayer->deactivateObjects(aDisplayed, true);
263 //******************************************************
264 void XGUI_Workshop::initMenu()
266 myContextMenuMgr->createActions();
269 // Create only Undo, Redo commands
270 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
271 tr("Undo last command"),
272 QIcon(":pictures/undo.png"),
273 QKeySequence::Undo, false, "MEN_DESK_EDIT");
274 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
275 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
277 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
278 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
280 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
281 QIcon(":pictures/redo.png"), QKeySequence::Redo,
282 false, "MEN_DESK_EDIT");
283 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
285 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
286 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
288 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
289 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
290 // QIcon(":pictures/rebuild.png"), QKeySequence(),
291 // false, "MEN_DESK_EDIT");
292 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
294 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
295 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
297 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
298 QIcon(), QKeySequence(),
299 false, "MEN_DESK_FILE");
300 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
302 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
303 QIcon(), QKeySequence(),
304 false, "MEN_DESK_FILE");
305 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
306 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
309 // File commands group
310 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
312 AppElements_Command* aCommand;
314 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
315 QIcon(":pictures/save.png"), QKeySequence::Save);
316 aCommand->connectTo(this, SLOT(onSave()));
317 //aCommand->disable();
319 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
320 QIcon(":pictures/save.png"), QKeySequence());
321 aCommand->connectTo(this, SLOT(onSaveAs()));
323 QString aUndoId = "UNDO_CMD";
324 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
325 QIcon(":pictures/undo.png"), QKeySequence::Undo);
326 aCommand->connectTo(this, SLOT(onUndo()));
327 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
328 addHistoryMenu(aUndoButton,
329 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
332 QString aRedoId = "REDO_CMD";
333 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
334 QIcon(":pictures/redo.png"), QKeySequence::Redo);
335 aCommand->connectTo(this, SLOT(onRedo()));
336 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
337 addHistoryMenu(aRedoButton,
338 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
341 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
342 // QIcon(":pictures/rebuild.png"), QKeySequence());
343 //aCommand->connectTo(this, SLOT(onRebuild()));
345 //aCommand->disable();
347 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
348 QIcon(":pictures/open.png"), QKeySequence::Open);
349 aCommand->connectTo(this, SLOT(onOpen()));
351 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
352 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
353 aCommand->connectTo(this, SLOT(onPreferences()));
355 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
356 QIcon(":pictures/close.png"), QKeySequence::Close);
357 aCommand->connectTo(this, SLOT(onExit()));
362 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
364 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
365 return aMenuBar->addWorkbench(theName);
369 //******************************************************
370 QMainWindow* XGUI_Workshop::desktop() const
373 return salomeConnector()->desktop();
379 //******************************************************
380 void XGUI_Workshop::onStartWaiting()
382 if (Events_LongOp::isPerformed()) {
383 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
387 //******************************************************
388 void XGUI_Workshop::onAcceptActionClicked()
390 QAction* anAction = dynamic_cast<QAction*>(sender());
391 XGUI_OperationMgr* anOperationMgr = operationMgr();
392 if (anOperationMgr) {
393 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
394 (anOperationMgr->currentOperation());
396 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
397 myOperationMgr->onCommitOperation();
402 //******************************************************
403 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
405 if (!myModule->canActivateSelection(theObject)) {
406 if (myDisplayer->isActive(theObject)) {
407 QObjectPtrList anObjects;
408 anObjects.append(theObject);
409 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
414 //******************************************************
415 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
417 bool aHasNested = false;
418 std::string aFeatureKind = theFeature->getKind();
420 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
421 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
424 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
425 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
426 if (aCommand && aCommand->button()->additionalButtonWidget())
432 //******************************************************
433 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
435 setGrantedFeatures(theOperation);
437 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
442 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
443 setPropertyPanel(aFOperation);
444 // filling the operation values by the current selection
445 // if the operation can be committed after the controls filling, the method perform should
446 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
447 if (!aFOperation->isEditOperation()) {
448 aFOperation->activateByPreselection();
449 if (operationMgr()->currentOperation() != aFOperation)
453 updateCommandStatus();
455 connectToPropertyPanel(true);
456 myModule->operationStarted(aFOperation);
458 // the objects of the current operation should be deactivated
459 QObjectPtrList anObjects;
460 FeaturePtr aFeature = aFOperation->feature();
461 anObjects.append(aFeature);
462 std::list<ResultPtr> aResults = aFeature->results();
463 std::list<ResultPtr>::const_iterator aIt;
464 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
465 anObjects.append(*aIt);
467 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
468 for (; anIt != aLast; anIt++)
469 deactivateActiveObject(*anIt, false);
470 if (anObjects.size() > 0)
471 myDisplayer->updateViewer();
474 //******************************************************
475 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
477 setGrantedFeatures(theOperation);
479 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
480 setPropertyPanel(theOperation);
481 connectToPropertyPanel(true);
483 updateCommandStatus();
485 myModule->operationResumed(theOperation);
489 //******************************************************
490 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
492 updateCommandStatus();
494 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
499 ModuleBase_ISelection* aSel = mySelector->selection();
500 QObjectPtrList aObj = aSel->selectedPresentations();
501 //!< No need for property panel
503 myPropertyPanel->cleanContent();
505 connectToPropertyPanel(false);
506 myModule->operationStopped(aFOperation);
508 // the deactivated objects of the current operation should be activated back.
509 // They were deactivated on operation start or an object redisplay
510 QObjectPtrList anObjects;
511 FeaturePtr aFeature = aFOperation->feature();
512 if (aFeature.get()) { // feature may be not created (plugin load fail)
513 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
514 anObjects.append(aFeature);
515 std::list<ResultPtr> aResults = aFeature->results();
516 std::list<ResultPtr>::const_iterator aIt;
517 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
518 ResultPtr anObject = *aIt;
519 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
520 anObjects.append(anObject);
525 module()->activeSelectionModes(aModes);
526 myDisplayer->activateObjects(aModes, anObjects);
530 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
532 myModule->operationCommitted(theOperation);
535 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
537 myModule->operationAborted(theOperation);
540 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
542 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
546 QStringList aGrantedIds;
548 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
550 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
552 ModuleBase_IModule* aModule = module();
554 aModule->grantedOperationIds(theOperation, aGrantedIds);
556 aFOperation->setGrantedOperationIds(aGrantedIds);
559 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
561 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
566 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
567 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
569 myPropertyPanel->cleanContent();
570 aFactory.createWidget(myPropertyPanel->contentWidget());
572 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
574 // check compatibility of feature and widgets
575 FeaturePtr aFeature = aFOperation->feature();
576 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
577 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
578 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
579 + aWidget->attributeID() + "' used by widget '"
580 + aWidget->metaObject()->className() + "'.";
581 Events_Error::send(anErrorMsg);
582 myPropertyPanel->cleanContent();
587 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
588 bool isStoreValue = !aFOperation->isEditOperation() &&
589 !aWidget->getDefaultValue().empty() &&
590 !aWidget->isComputedDefault();
591 aWidget->setFeature(aFOperation->feature(), isStoreValue);
592 aWidget->enableFocusProcessing();
595 myPropertyPanel->setModelWidgets(aWidgets);
596 aFOperation->setPropertyPanel(myPropertyPanel);
598 myModule->propertyPanelDefined(theOperation);
600 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
602 myErrorMgr->setPropertyPanel(myPropertyPanel);
605 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
607 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
608 if (aPropertyPanel) {
609 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
610 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
611 myModule->connectToPropertyPanel(aWidget, isToConnect);
613 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
616 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
623 * Saves document with given name.
625 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
627 QApplication::restoreOverrideCursor();
628 SessionPtr aMgr = ModelAPI_Session::get();
629 aMgr->save(theName.toLatin1().constData(), theFileNames);
630 QApplication::restoreOverrideCursor();
633 bool XGUI_Workshop::abortAllOperations()
635 return myOperationMgr->abortAllOperations();
638 //******************************************************
639 void XGUI_Workshop::onOpen()
641 if(!abortAllOperations())
643 //save current file before close if modified
644 SessionPtr aSession = ModelAPI_Session::get();
645 if (aSession->isModified()) {
646 //TODO(sbh): re-launch the app?
647 int anAnswer = QMessageBox::question(
648 desktop(), tr("Save current file"),
649 tr("The document is modified, save before opening another?"),
650 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
651 if (anAnswer == QMessageBox::Save) {
653 } else if (anAnswer == QMessageBox::Cancel) {
659 //show file dialog, check if readable and open
660 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
661 if (myCurrentDir.isEmpty())
663 QFileInfo aFileInfo(myCurrentDir);
664 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
665 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
669 QApplication::setOverrideCursor(Qt::WaitCursor);
670 aSession->closeAll();
671 aSession->load(myCurrentDir.toLatin1().constData());
672 myObjectBrowser->rebuildDataTree();
673 updateCommandStatus();
674 QApplication::restoreOverrideCursor();
677 //******************************************************
678 void XGUI_Workshop::onNew()
680 QApplication::setOverrideCursor(Qt::WaitCursor);
681 if (objectBrowser() == 0) {
683 mySelector->connectViewers();
685 myViewerProxy->connectToViewer();
688 myMainWindow->showPythonConsole();
689 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
690 aWnd->showMaximized();
691 updateCommandStatus();
693 myContextMenuMgr->connectViewer();
694 QApplication::restoreOverrideCursor();
698 //******************************************************
699 void XGUI_Workshop::onExit()
701 SessionPtr aMgr = ModelAPI_Session::get();
702 if (aMgr->isModified()) {
703 int anAnswer = QMessageBox::question(
704 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
705 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
706 if (anAnswer == QMessageBox::Save) {
707 bool saved = onSave();
711 } else if (anAnswer == QMessageBox::Cancel) {
718 //******************************************************
719 void XGUI_Workshop::onPreferences()
721 ModuleBase_Prefs aModif;
722 ModuleBase_Preferences::editPreferences(aModif);
723 if (aModif.size() > 0) {
725 foreach (ModuleBase_Pref aPref, aModif)
727 aSection = aPref.first;
728 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
729 myMainWindow->viewer()->updateFromResources();
730 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
731 myMainWindow->menuObject()->updateFromResources();
734 displayer()->redisplayObjects();
739 //******************************************************
740 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
742 XGUI_Displayer* aDisplayer = displayer();
744 aDisplayer->displayTrihedron(theState);
747 //******************************************************
748 bool XGUI_Workshop::onSave()
750 if(!abortAllOperations())
752 if (myCurrentDir.isEmpty()) {
755 std::list<std::string> aFiles;
756 saveDocument(myCurrentDir, aFiles);
757 updateCommandStatus();
759 myMainWindow->setModifiedState(false);
764 //******************************************************
765 bool XGUI_Workshop::onSaveAs()
767 if(!abortAllOperations())
769 QFileDialog dialog(desktop());
770 dialog.setWindowTitle(tr("Select directory to save files..."));
771 dialog.setFileMode(QFileDialog::Directory);
772 dialog.setFilter(tr("Directories (*)"));
773 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
774 dialog.setViewMode(QFileDialog::Detail);
776 if (!dialog.exec()) {
780 QString aTempDir = dialog.selectedFiles().first();
782 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
783 int answer = QMessageBox::question(
785 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
787 tr("The directory already contains some files, save anyway?"),
788 QMessageBox::Save | QMessageBox::Cancel);
789 if (answer == QMessageBox::Cancel) {
793 myCurrentDir = aTempDir;
795 myMainWindow->setCurrentDir(myCurrentDir, false);
796 myMainWindow->setModifiedState(false);
801 //******************************************************
802 void XGUI_Workshop::onUndo(int theTimes)
804 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
805 SessionPtr aMgr = ModelAPI_Session::get();
806 std::list<std::string> aUndoList = aMgr->undoList();
807 if (aMgr->isOperation()) {
808 /// this is important for nested operations
809 /// when sketch operation is active, this condition is false and
810 /// the sketch operation is not aborted
811 operationMgr()->onAbortOperation();
813 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
814 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
816 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
817 myObjectBrowser->rebuildDataTree();
820 operationMgr()->updateApplyOfOperations();
821 updateCommandStatus();
824 //******************************************************
825 void XGUI_Workshop::onRedo(int theTimes)
827 // the viewer update should be blocked in order to avoid the features blinking. For the created
828 // feature a results are created, the flush of the created signal caused the viewer redisplay for
829 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
830 // redo of all possible objects happens
831 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
833 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
834 SessionPtr aMgr = ModelAPI_Session::get();
835 std::list<std::string> aRedoList = aMgr->redoList();
836 if (aMgr->isOperation()) {
837 /// this is important for nested operations
838 /// when sketch operation is active, this condition is false and
839 /// the sketch operation is not aborted
840 operationMgr()->onAbortOperation();
842 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
843 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
845 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
846 myObjectBrowser->rebuildDataTree();
848 operationMgr()->updateApplyOfOperations();
849 updateCommandStatus();
851 // unblock the viewer update functionality and make update on purpose
852 myDisplayer->enableUpdateViewer(isUpdateEnabled);
853 myDisplayer->updateViewer();
856 //******************************************************
857 //void XGUI_Workshop::onRebuild()
859 // SessionPtr aMgr = ModelAPI_Session::get();
860 // bool aWasOperation = aMgr->isOperation(); // keep this value
861 // if (!aWasOperation) {
862 // aMgr->startOperation("Rebuild");
864 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
865 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
866 // new Events_Message(aRebuildEvent, this)));
867 // if (!aWasOperation) {
868 // aMgr->finishOperation();
870 // updateCommandStatus();
873 //******************************************************
874 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
876 ModuleBase_ModelWidget* anActiveWidget = 0;
877 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
879 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
881 anActiveWidget = aPanel->activeWidget();
884 operationMgr()->onValidateOperation();
886 myModule->widgetStateChanged(thePreviousState);
889 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
891 QString libName = QString::fromStdString(library(theModule.toStdString()));
892 if (libName.isEmpty()) {
893 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
898 CREATE_FUNC crtInst = 0;
901 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
905 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
906 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
907 QString aMsg((char*) &lpMsgBuf);
908 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
909 ::LocalFree(lpMsgBuf);
911 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
915 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
916 | FORMAT_MESSAGE_IGNORE_INSERTS,
917 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
918 QString aMsg((char*) &lpMsgBuf);
919 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
920 ::LocalFree(lpMsgBuf);
924 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
926 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
928 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
930 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
935 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
937 if (!err.isEmpty()) {
939 Events_Error::send(err.toStdString());
941 qWarning(qPrintable(err));
947 //******************************************************
948 bool XGUI_Workshop::createModule()
950 Config_ModuleReader aModuleReader;
951 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
952 myModule = loadModule(moduleName);
956 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
957 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
958 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
959 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
961 myModule->createFeatures();
962 //myActionsMgr->update();
966 //******************************************************
967 void XGUI_Workshop::updateCommandStatus()
969 QList<QAction*> aCommands;
971 aCommands = salomeConnector()->commandList();
973 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
974 foreach (AppElements_Command* aCmd, aMenuBar->features())
975 aCommands.append(aCmd);
977 SessionPtr aMgr = ModelAPI_Session::get();
978 if (aMgr->hasModuleDocument()) {
979 foreach(QAction* aCmd, aCommands) {
980 QString aId = aCmd->data().toString();
981 if (aId == "UNDO_CMD")
982 aCmd->setEnabled(myModule->canUndo());
983 else if (aId == "REDO_CMD")
984 aCmd->setEnabled(myModule->canRedo());
986 // Enable all commands
987 aCmd->setEnabled(true);
991 foreach(QAction* aCmd, aCommands) {
992 QString aId = aCmd->data().toString();
993 if (aId == "NEW_CMD")
994 aCmd->setEnabled(true);
995 else if (aId == "EXIT_CMD")
996 aCmd->setEnabled(true);
998 aCmd->setEnabled(false);
1001 myActionsMgr->updateCommandsStatus();
1002 emit commandStatusUpdated();
1005 void XGUI_Workshop::updateHistory()
1007 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1008 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1009 emit updateUndoHistory(aUndoRes);
1011 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1012 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1013 emit updateRedoHistory(aRedoRes);
1016 //******************************************************
1017 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1019 QDockWidget* aObjDock = new QDockWidget(theParent);
1020 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1021 aObjDock->setWindowTitle(tr("Object browser"));
1022 aObjDock->setStyleSheet(
1023 "::title { position: relative; padding-left: 5px; text-align: left center }");
1024 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1025 myModule->customizeObjectBrowser(myObjectBrowser);
1026 aObjDock->setWidget(myObjectBrowser);
1028 myContextMenuMgr->connectObjectBrowser();
1032 //******************************************************
1034 * Creates dock widgets, places them in corresponding area
1035 * and tabifies if necessary.
1037 void XGUI_Workshop::createDockWidgets()
1039 QMainWindow* aDesktop = desktop();
1040 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1041 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1042 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1043 myPropertyPanel->setupActions(myActionsMgr);
1044 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1045 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1046 hidePropertyPanel(); ///<! Invisible by default
1047 hideObjectBrowser();
1048 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1049 myPropertyPanel->installEventFilter(myOperationMgr);
1051 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1052 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1054 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1055 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1056 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1057 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1059 connect(myPropertyPanel, SIGNAL(enterClicked()),
1060 myOperationMgr, SLOT(onProcessEnter()));
1063 //******************************************************
1064 void XGUI_Workshop::showPropertyPanel()
1066 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1067 ///<! Restore ability to close panel from the window's menu
1068 aViewAct->setEnabled(true);
1069 myPropertyPanel->show();
1070 myPropertyPanel->raise();
1072 // The next code is necessary to made the property panel the active window
1073 // in order to operation manager could process key events of the panel.
1074 // otherwise they are ignored. It happens only if the same(activateWindow) is
1075 // not happened by property panel activation(e.g. resume operation of Sketch)
1076 ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1077 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1080 //******************************************************
1081 void XGUI_Workshop::hidePropertyPanel()
1083 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1084 ///<! Do not allow to show empty property panel
1085 aViewAct->setEnabled(false);
1086 myPropertyPanel->hide();
1088 // the property panel is active window of the desktop, when it is
1089 // hidden, it is undefined which window becomes active. By this reason
1090 // it is defined to perform the desktop as the active window.
1091 // in SALOME mode, workstack made the PyConsole the active window,
1092 // set the focus on it. As a result, shortcuts of the application, like
1093 // are processed by this console. For example Undo actions.
1094 // It is possible that this code is to be moved to NewGeom package
1095 QMainWindow* aDesktop = desktop();
1096 ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1097 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1100 //******************************************************
1101 void XGUI_Workshop::showObjectBrowser()
1103 if (!isSalomeMode())
1104 myObjectBrowser->parentWidget()->show();
1107 //******************************************************
1108 void XGUI_Workshop::hideObjectBrowser()
1110 if (!isSalomeMode())
1111 myObjectBrowser->parentWidget()->hide();
1114 //******************************************************
1115 void XGUI_Workshop::salomeViewerSelectionChanged()
1117 emit salomeViewerSelection();
1120 //**************************************************************
1121 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1123 return mySalomeConnector->viewer();
1126 //**************************************************************
1127 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1129 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1130 if (theId == "DELETE_CMD")
1132 else if (theId == "MOVE_CMD")
1134 else if (theId == "COLOR_CMD")
1135 changeColor(aObjects);
1136 else if (theId == "SHOW_CMD") {
1137 showObjects(aObjects, true);
1138 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1140 else if (theId == "HIDE_CMD")
1141 showObjects(aObjects, false);
1142 else if (theId == "SHOW_ONLY_CMD") {
1143 showOnlyObjects(aObjects);
1144 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1146 else if (theId == "SHADING_CMD")
1147 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1148 else if (theId == "WIREFRAME_CMD")
1149 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1150 else if (theId == "HIDEALL_CMD") {
1151 QObjectPtrList aList = myDisplayer->displayedObjects();
1152 foreach (ObjectPtr aObj, aList) {
1153 if (module()->canEraseObject(aObj))
1154 aObj->setDisplayed(false);
1156 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1160 //**************************************************************
1161 void XGUI_Workshop::deleteObjects()
1163 ModuleBase_IModule* aModule = module();
1164 // 1. allow the module to delete objects, do nothing if it has succeed
1165 if (aModule->deleteObjects()) {
1166 updateCommandStatus();
1170 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1171 if (!abortAllOperations())
1173 // It is necessary to clear selection in order to avoid selection changed event during
1174 // deletion and negative consequences connected with processing of already deleted items
1175 mySelector->clearSelection();
1176 // check whether the object can be deleted. There should not be parts which are not loaded
1177 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1180 bool hasResult = false;
1181 bool hasFeature = false;
1182 bool hasParameter = false;
1183 bool hasSubFeature = false;
1184 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1185 if (!(hasFeature || hasParameter))
1188 // 1. start operation
1189 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1190 aDescription += tr(" %1");
1191 QStringList aObjectNames;
1192 foreach (ObjectPtr aObj, anObjects) {
1193 if (!aObj->data()->isValid())
1195 aObjectNames << QString::fromStdString(aObj->data()->name());
1197 aDescription = aDescription.arg(aObjectNames.join(", "));
1198 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1200 operationMgr()->startOperation(anOpAction);
1201 // 3. delete objects
1202 std::set<FeaturePtr> anIgnoredFeatures;
1203 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1204 operationMgr()->commitOperation();
1207 operationMgr()->abortOperation(operationMgr()->currentOperation());
1211 //**************************************************************
1212 void XGUI_Workshop::moveObjects()
1214 if (!abortAllOperations())
1217 SessionPtr aMgr = ModelAPI_Session::get();
1219 QString anActionId = "MOVE_CMD";
1220 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1221 aMgr->startOperation(aDescription.toStdString());
1223 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1224 // It is necessary to clear selection in order to avoid selection changed event during
1225 // moving and negative consequences connected with processing of already moved items
1226 mySelector->clearSelection();
1227 // check whether the object can be moved. There should not be parts which are not loaded
1228 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1231 DocumentPtr anActiveDocument = aMgr->activeDocument();
1232 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1233 foreach (ObjectPtr aObject, anObjects) {
1234 if (!myModule->canApplyAction(aObject, anActionId))
1237 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1238 if (aFeature.get()) {
1239 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1240 aCurrentFeature = anActiveDocument->currentFeature(true);
1243 aMgr->finishOperation();
1246 //**************************************************************
1247 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1248 const std::set<FeaturePtr>& theIgnoredFeatures,
1250 const bool theAskAboutDeleteReferences)
1254 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1255 for (; aDIt != aDLast; ++aDIt) {
1256 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1258 QString anInfoStr = aDInfo.join(", ");
1259 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1262 // 1. find all referenced features
1263 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1264 foreach (ObjectPtr aDeletedObj, theList) {
1265 std::set<FeaturePtr> alreadyProcessed;
1266 XGUI_Tools::refsToFeatureInAllDocuments(
1267 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1268 std::set<FeaturePtr> aDifference;
1269 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1270 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1271 std::inserter(aDifference, aDifference.begin()));
1272 aIndirectRefFeatures = aDifference;
1275 bool doDeleteReferences = true;
1277 // 2. warn about the references remove, break the delete operation if the user chose it
1278 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1279 QStringList aDirectRefNames;
1280 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1281 aDirectRefNames.append(aFeature->name().c_str());
1282 QString aDirectNames = aDirectRefNames.join(", ");
1284 QStringList aIndirectRefNames;
1285 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1286 aIndirectRefNames.append(aFeature->name().c_str());
1287 QString aIndirectNames = aIndirectRefNames.join(", ");
1289 bool canReplaceParameters = true;
1290 foreach (ObjectPtr aObj, theList) {
1291 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1292 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1293 canReplaceParameters = false;
1298 QMessageBox aMessageBox(theParent);
1299 aMessageBox.setWindowTitle(tr("Delete features"));
1300 aMessageBox.setIcon(QMessageBox::Warning);
1301 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1302 aMessageBox.setDefaultButton(QMessageBox::No);
1305 if (canReplaceParameters) {
1306 aText = QString(tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\n%2Or parameters could be replaced by their values.\nWould you like to continue?"))
1307 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1308 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1310 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1311 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1313 aMessageBox.setText(aText);
1315 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1317 if (aButtonRole == QMessageBox::NoRole)
1320 if (aButtonRole == QMessageBox::ActionRole) {
1321 foreach (ObjectPtr aObj, theList)
1322 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1323 doDeleteReferences = false;
1327 // 3. remove referenced features
1328 if (doDeleteReferences) {
1329 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1330 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1331 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1332 aLast = aFeaturesToDelete.end();
1336 for (; anIt != aLast; anIt++) {
1337 FeaturePtr aFeature = (*anIt);
1338 DocumentPtr aDoc = aFeature->document();
1339 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1340 aDoc->removeFeature(aFeature);
1342 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1347 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1352 QString anActionId = "DELETE_CMD";
1353 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1354 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1355 // 4. remove the parameter features
1356 foreach (ObjectPtr aObj, theList) {
1357 // features and parameters can be removed here,
1358 // the results are removed only by a corresponded feature remove
1359 std::string aGroupName = aObj->groupName();
1360 if (!anObjectGroups.contains(aGroupName.c_str()))
1363 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1365 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1366 // part features are removed in the PartSet module. This condition should be moved there
1367 if (aFeature->getKind() == "Part")
1370 DocumentPtr aDoc = aObj->document();
1371 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1373 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1374 anInfo.append(anInfoStr);
1375 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1377 aDoc->removeFeature(aFeature);
1382 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1387 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1389 bool isFoundResultType = false;
1390 foreach(ObjectPtr anObj, theObjects)
1392 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1393 if (aResult.get() == NULL)
1396 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1397 if (isFoundResultType)
1400 return isFoundResultType;
1403 //**************************************************************
1404 // Returns the list of all features for theDocument and all features of
1405 // all nested parts.
1406 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1408 std::list<FeaturePtr> aResultList;
1409 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1410 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1411 // The order of appending features of the part and the part itself is important
1413 // Append features from a part feature
1414 foreach (const ResultPtr& aResult, aFeature->results()) {
1415 ResultPartPtr aResultPart =
1416 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1417 if (aResultPart.get() && aResultPart->partDoc().get()) {
1419 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1420 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1424 aResultList.push_back(aFeature);
1429 //**************************************************************
1430 // Returns the list of features placed between theObject and the current feature
1431 // in the same document. Excludes theObject, includes the current feature.
1432 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1434 std::list<FeaturePtr> aResult;
1435 DocumentPtr aDocument = theObject->document();
1436 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1437 // find the object iterator
1438 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1439 if (aObjectIt == anAllFeatures.end())
1441 // find the current feature iterator
1442 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1443 if (aCurrentIt == anAllFeatures.end())
1445 // check the right order
1446 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1448 // exclude the object
1449 std::advance(aObjectIt, 1);
1450 // include the current feature
1451 std::advance(aCurrentIt, 1);
1452 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1455 bool XGUI_Workshop::canMoveFeature()
1457 QString anActionId = "MOVE_CMD";
1459 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1460 QObjectPtrList aValidatedObjects;
1461 foreach (ObjectPtr aObject, aObjects) {
1462 if (!myModule->canApplyAction(aObject, anActionId))
1464 // To be moved feature should be in active document
1465 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1467 aValidatedObjects.append(aObject);
1469 if (aValidatedObjects.size() != aObjects.size())
1470 aObjects = aValidatedObjects;
1472 bool aCanMove = !aObjects.empty();
1474 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1475 for (; anIt != aLast && aCanMove; anIt++) {
1476 ObjectPtr aObject = *anIt;
1477 // 1. Get features placed between selected and current in the document
1478 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1479 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1480 if (aFeaturesBetween.empty())
1483 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1484 // 2. Get all reference features to the selected object in the document
1485 std::set<FeaturePtr> aRefFeatures;
1486 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1488 if (aRefFeatures.empty())
1491 // 3. Find any placed features in all reference features
1492 std::set<FeaturePtr> aIntersectionFeatures;
1493 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1494 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1495 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1496 // 4. Return false if any reference feature is placed before current feature
1497 if (!aIntersectionFeatures.empty())
1505 //**************************************************************
1506 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1508 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1509 if (!aCanBeShaded) {
1510 ResultCompSolidPtr aCompsolidResult =
1511 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1512 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1513 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1514 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1517 return aCanBeShaded;
1520 //**************************************************************
1521 bool XGUI_Workshop::canChangeColor() const
1523 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1525 std::set<std::string> aTypes;
1526 aTypes.insert(ModelAPI_ResultGroup::group());
1527 aTypes.insert(ModelAPI_ResultConstruction::group());
1528 aTypes.insert(ModelAPI_ResultBody::group());
1529 aTypes.insert(ModelAPI_ResultPart::group());
1531 return hasResults(aObjects, aTypes);
1534 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1536 if (!theResult.get())
1539 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1540 if (aColorAttr.get() != NULL) {
1541 if (!aColorAttr->size()) {
1542 aColorAttr->setSize(3);
1544 aColorAttr->setValue(0, theColor[0]);
1545 aColorAttr->setValue(1, theColor[1]);
1546 aColorAttr->setValue(2, theColor[2]);
1550 //**************************************************************
1551 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1554 AttributeIntArrayPtr aColorAttr;
1555 // 1. find the current color of the object. This is a color of AIS presentation
1556 // The objects are iterated until a first valid color is found
1557 std::vector<int> aColor;
1558 foreach(ObjectPtr anObject, theObjects) {
1559 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1560 if (aResult.get()) {
1561 XGUI_CustomPrs::getResultColor(aResult, aColor);
1564 // TODO: remove the obtaining a color from the AIS object
1565 // this does not happen never because:
1566 // 1. The color can be changed only on results
1567 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1568 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1569 if (anAISObj.get()) {
1571 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1574 if (!aColor.empty())
1577 if (aColor.size() != 3)
1580 if (!abortAllOperations())
1582 // 2. show the dialog to change the value
1583 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1584 aDlg->setColor(aColor);
1585 aDlg->move(QCursor::pos());
1586 bool isDone = aDlg->exec() == QDialog::Accepted;
1590 bool isRandomColor = aDlg->isRandomColor();
1592 // 3. abort the previous operation and start a new one
1593 SessionPtr aMgr = ModelAPI_Session::get();
1594 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1595 aMgr->startOperation(aDescription.toStdString());
1597 // 4. set the value to all results
1598 std::vector<int> aColorResult = aDlg->getColor();
1599 foreach(ObjectPtr anObj, theObjects) {
1600 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1601 if (aResult.get() != NULL) {
1602 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1603 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1604 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1605 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1608 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1611 aMgr->finishOperation();
1612 updateCommandStatus();
1615 //**************************************************************
1616 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1617 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1618 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1620 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1622 foreach (ObjectPtr aObj, theList) {
1624 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1626 DocumentPtr aDoc = aPartRes->partDoc();
1627 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1628 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1629 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1632 aObj->setDisplayed(isVisible);
1635 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1638 //**************************************************************
1639 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1641 // Hide all displayed objects
1642 QObjectPtrList aList = myDisplayer->displayedObjects();
1643 foreach (ObjectPtr aObj, aList) {
1644 if (module()->canEraseObject(aObj))
1645 aObj->setDisplayed(false);
1648 // Show only objects from the list
1649 foreach (ObjectPtr aObj, theList) {
1651 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1653 DocumentPtr aDoc = aPartRes->partDoc();
1654 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1655 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1656 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1659 aObj->setDisplayed(true);
1662 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1667 //**************************************************************
1668 void XGUI_Workshop::registerValidators() const
1670 SessionPtr aMgr = ModelAPI_Session::get();
1671 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1674 //**************************************************************
1675 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1679 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1680 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1683 //**************************************************************
1684 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1686 for (int i = 0; i < theDoc->size(theGroup); i++)
1687 theDoc->object(theGroup, i)->setDisplayed(true);
1688 //displayObject(theDoc->object(theGroup, i));
1689 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1692 //**************************************************************
1693 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1695 foreach(ObjectPtr aObj, theList) {
1696 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1698 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1699 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1700 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1701 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1702 (XGUI_Displayer::DisplayMode)theMode, false);
1706 if (theList.size() > 0)
1707 myDisplayer->updateViewer();
1710 //**************************************************************
1711 void XGUI_Workshop::closeDocument()
1713 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1714 while (anOperation) {
1715 anOperation->abort();
1716 anOperation = operationMgr()->currentOperation();
1718 myDisplayer->closeLocalContexts();
1719 myDisplayer->eraseAll();
1720 objectBrowser()->clearContent();
1722 module()->closeDocument();
1724 SessionPtr aMgr = ModelAPI_Session::get();
1728 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1730 XGUI_HistoryMenu* aMenu = NULL;
1731 if (isSalomeMode()) {
1732 QAction* anAction = qobject_cast<QAction*>(theObject);
1735 aMenu = new XGUI_HistoryMenu(anAction);
1737 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1738 aMenu = new XGUI_HistoryMenu(aButton);
1740 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1741 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1744 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1746 QList<ActionInfo> aResult;
1747 std::list<std::string>::const_iterator it = theList.cbegin();
1748 for (; it != theList.cend(); it++) {
1749 QString anId = QString::fromStdString(*it);
1750 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1752 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1755 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1756 if (aContextMenuAct) {
1757 anInfo.initFrom(aContextMenuAct);
1759 anInfo = myActionsMgr->actionInfoById(anId);
1762 anInfo.text = anInfo.text.prepend("Modify ");
1769 void XGUI_Workshop::synchronizeViewer()
1771 SessionPtr aMgr = ModelAPI_Session::get();
1772 DocumentPtr aDoc = aMgr->activeDocument();
1774 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1775 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1776 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1777 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1780 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1781 const std::string& theGroup,
1782 bool theUpdateViewer)
1785 int aSize = theDoc->size(theGroup);
1786 for (int i = 0; i < aSize; i++) {
1787 aObj = theDoc->object(theGroup, i);
1788 if (aObj->isDisplayed())
1789 myDisplayer->display(aObj, false);
1791 if (theUpdateViewer)
1792 myDisplayer->updateViewer();