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 myObjectBrowser->parentWidget()->show();
1106 //******************************************************
1107 void XGUI_Workshop::hideObjectBrowser()
1109 myObjectBrowser->parentWidget()->hide();
1112 //******************************************************
1113 void XGUI_Workshop::salomeViewerSelectionChanged()
1115 emit salomeViewerSelection();
1118 //**************************************************************
1119 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1121 return mySalomeConnector->viewer();
1124 //**************************************************************
1125 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1127 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1128 if (theId == "DELETE_CMD")
1130 else if (theId == "MOVE_CMD")
1132 else if (theId == "COLOR_CMD")
1133 changeColor(aObjects);
1134 else if (theId == "SHOW_CMD")
1135 showObjects(aObjects, true);
1136 else if (theId == "HIDE_CMD")
1137 showObjects(aObjects, false);
1138 else if (theId == "SHOW_ONLY_CMD")
1139 showOnlyObjects(aObjects);
1140 else if (theId == "SHADING_CMD")
1141 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1142 else if (theId == "WIREFRAME_CMD")
1143 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1144 else if (theId == "HIDEALL_CMD") {
1145 QObjectPtrList aList = myDisplayer->displayedObjects();
1146 foreach (ObjectPtr aObj, aList) {
1147 if (module()->canEraseObject(aObj))
1148 aObj->setDisplayed(false);
1150 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1154 //**************************************************************
1155 void XGUI_Workshop::deleteObjects()
1157 ModuleBase_IModule* aModule = module();
1158 // 1. allow the module to delete objects, do nothing if it has succeed
1159 if (aModule->deleteObjects()) {
1160 updateCommandStatus();
1164 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1165 if (!abortAllOperations())
1167 // It is necessary to clear selection in order to avoid selection changed event during
1168 // deletion and negative consequences connected with processing of already deleted items
1169 mySelector->clearSelection();
1170 // check whether the object can be deleted. There should not be parts which are not loaded
1171 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1174 bool hasResult = false;
1175 bool hasFeature = false;
1176 bool hasParameter = false;
1177 bool hasSubFeature = false;
1178 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1179 if (!(hasFeature || hasParameter))
1182 // 1. start operation
1183 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1184 aDescription += tr(" %1");
1185 QStringList aObjectNames;
1186 foreach (ObjectPtr aObj, anObjects) {
1187 if (!aObj->data()->isValid())
1189 aObjectNames << QString::fromStdString(aObj->data()->name());
1191 aDescription = aDescription.arg(aObjectNames.join(", "));
1192 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1194 operationMgr()->startOperation(anOpAction);
1195 // 3. delete objects
1196 std::set<FeaturePtr> anIgnoredFeatures;
1197 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1198 operationMgr()->commitOperation();
1201 operationMgr()->abortOperation(operationMgr()->currentOperation());
1205 //**************************************************************
1206 void XGUI_Workshop::moveObjects()
1208 if (!abortAllOperations())
1211 SessionPtr aMgr = ModelAPI_Session::get();
1213 QString anActionId = "MOVE_CMD";
1214 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1215 aMgr->startOperation(aDescription.toStdString());
1217 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1218 // It is necessary to clear selection in order to avoid selection changed event during
1219 // moving and negative consequences connected with processing of already moved items
1220 mySelector->clearSelection();
1221 // check whether the object can be moved. There should not be parts which are not loaded
1222 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1225 DocumentPtr anActiveDocument = aMgr->activeDocument();
1226 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1227 foreach (ObjectPtr aObject, anObjects) {
1228 if (!myModule->canApplyAction(aObject, anActionId))
1231 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1232 if (aFeature.get()) {
1233 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1234 aCurrentFeature = anActiveDocument->currentFeature(true);
1237 aMgr->finishOperation();
1240 //**************************************************************
1241 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1242 const std::set<FeaturePtr>& theIgnoredFeatures,
1244 const bool theAskAboutDeleteReferences)
1248 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1249 for (; aDIt != aDLast; ++aDIt) {
1250 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1252 QString anInfoStr = aDInfo.join(", ");
1253 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1256 // 1. find all referenced features
1257 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1258 foreach (ObjectPtr aDeletedObj, theList) {
1259 std::set<FeaturePtr> alreadyProcessed;
1260 XGUI_Tools::refsToFeatureInAllDocuments(
1261 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1262 std::set<FeaturePtr> aDifference;
1263 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1264 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1265 std::inserter(aDifference, aDifference.begin()));
1266 aIndirectRefFeatures = aDifference;
1269 bool doDeleteReferences = true;
1271 // 2. warn about the references remove, break the delete operation if the user chose it
1272 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1273 QStringList aDirectRefNames;
1274 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1275 aDirectRefNames.append(aFeature->name().c_str());
1276 QString aDirectNames = aDirectRefNames.join(", ");
1278 QStringList aIndirectRefNames;
1279 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1280 aIndirectRefNames.append(aFeature->name().c_str());
1281 QString aIndirectNames = aIndirectRefNames.join(", ");
1283 bool canReplaceParameters = true;
1284 foreach (ObjectPtr aObj, theList) {
1285 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1286 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1287 canReplaceParameters = false;
1292 QMessageBox aMessageBox(theParent);
1293 aMessageBox.setWindowTitle(tr("Delete features"));
1294 aMessageBox.setIcon(QMessageBox::Warning);
1295 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1296 aMessageBox.setDefaultButton(QMessageBox::No);
1299 if (canReplaceParameters) {
1300 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?"))
1301 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1302 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1304 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1305 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1307 aMessageBox.setText(aText);
1309 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1311 if (aButtonRole == QMessageBox::NoRole)
1314 if (aButtonRole == QMessageBox::ActionRole) {
1315 foreach (ObjectPtr aObj, theList)
1316 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1317 doDeleteReferences = false;
1321 // 3. remove referenced features
1322 if (doDeleteReferences) {
1323 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1324 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1325 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1326 aLast = aFeaturesToDelete.end();
1330 for (; anIt != aLast; anIt++) {
1331 FeaturePtr aFeature = (*anIt);
1332 DocumentPtr aDoc = aFeature->document();
1333 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1334 aDoc->removeFeature(aFeature);
1336 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1341 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1346 QString anActionId = "DELETE_CMD";
1347 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1348 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1349 // 4. remove the parameter features
1350 foreach (ObjectPtr aObj, theList) {
1351 // features and parameters can be removed here,
1352 // the results are removed only by a corresponded feature remove
1353 std::string aGroupName = aObj->groupName();
1354 if (!anObjectGroups.contains(aGroupName.c_str()))
1357 if (!myModule->canApplyAction(aObj, anActionId))
1360 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1362 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1363 // part features are removed in the PartSet module. This condition should be moved there
1364 if (aFeature->getKind() == "Part")
1367 DocumentPtr aDoc = aObj->document();
1368 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1370 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1371 anInfo.append(anInfoStr);
1372 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1374 aDoc->removeFeature(aFeature);
1379 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1384 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1386 bool isFoundResultType = false;
1387 foreach(ObjectPtr anObj, theObjects)
1389 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1390 if (aResult.get() == NULL)
1393 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1394 if (isFoundResultType)
1397 return isFoundResultType;
1400 //**************************************************************
1401 // Returns the list of all features for theDocument and all features of
1402 // all nested parts.
1403 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1405 std::list<FeaturePtr> aResultList;
1406 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1407 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1408 // The order of appending features of the part and the part itself is important
1410 // Append features from a part feature
1411 foreach (const ResultPtr& aResult, aFeature->results()) {
1412 ResultPartPtr aResultPart =
1413 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1414 if (aResultPart.get() && aResultPart->partDoc().get()) {
1416 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1417 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1421 aResultList.push_back(aFeature);
1426 //**************************************************************
1427 // Returns the list of features placed between theObject and the current feature
1428 // in the same document. Excludes theObject, includes the current feature.
1429 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1431 std::list<FeaturePtr> aResult;
1432 DocumentPtr aDocument = theObject->document();
1433 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1434 // find the object iterator
1435 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1436 if (aObjectIt == anAllFeatures.end())
1438 // find the current feature iterator
1439 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1440 if (aCurrentIt == anAllFeatures.end())
1442 // check the right order
1443 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1445 // exclude the object
1446 std::advance(aObjectIt, 1);
1447 // include the current feature
1448 std::advance(aCurrentIt, 1);
1449 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1452 bool XGUI_Workshop::canMoveFeature()
1454 QString anActionId = "MOVE_CMD";
1456 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1457 QObjectPtrList aValidatedObjects;
1458 foreach (ObjectPtr aObject, aObjects) {
1459 if (!myModule->canApplyAction(aObject, anActionId))
1461 // To be moved feature should be in active document
1462 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1464 aValidatedObjects.append(aObject);
1466 if (aValidatedObjects.size() != aObjects.size())
1467 aObjects = aValidatedObjects;
1469 bool aCanMove = !aObjects.empty();
1471 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1472 for (; anIt != aLast && aCanMove; anIt++) {
1473 ObjectPtr aObject = *anIt;
1474 // 1. Get features placed between selected and current in the document
1475 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1476 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1477 if (aFeaturesBetween.empty())
1480 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1481 // 2. Get all reference features to the selected object in the document
1482 std::set<FeaturePtr> aRefFeatures;
1483 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1485 if (aRefFeatures.empty())
1488 // 3. Find any placed features in all reference features
1489 std::set<FeaturePtr> aIntersectionFeatures;
1490 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1491 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1492 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1493 // 4. Return false if any reference feature is placed before current feature
1494 if (!aIntersectionFeatures.empty())
1502 //**************************************************************
1503 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1505 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1506 if (!aCanBeShaded) {
1507 ResultCompSolidPtr aCompsolidResult =
1508 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1509 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1510 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1511 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1514 return aCanBeShaded;
1517 //**************************************************************
1518 bool XGUI_Workshop::canChangeColor() const
1520 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1522 std::set<std::string> aTypes;
1523 aTypes.insert(ModelAPI_ResultGroup::group());
1524 aTypes.insert(ModelAPI_ResultConstruction::group());
1525 aTypes.insert(ModelAPI_ResultBody::group());
1526 aTypes.insert(ModelAPI_ResultPart::group());
1528 return hasResults(aObjects, aTypes);
1531 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1533 if (!theResult.get())
1536 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1537 if (aColorAttr.get() != NULL) {
1538 if (!aColorAttr->size()) {
1539 aColorAttr->setSize(3);
1541 aColorAttr->setValue(0, theColor[0]);
1542 aColorAttr->setValue(1, theColor[1]);
1543 aColorAttr->setValue(2, theColor[2]);
1547 //**************************************************************
1548 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1551 AttributeIntArrayPtr aColorAttr;
1552 // 1. find the current color of the object. This is a color of AIS presentation
1553 // The objects are iterated until a first valid color is found
1554 std::vector<int> aColor;
1555 foreach(ObjectPtr anObject, theObjects) {
1556 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1557 if (aResult.get()) {
1558 XGUI_CustomPrs::getResultColor(aResult, aColor);
1561 // TODO: remove the obtaining a color from the AIS object
1562 // this does not happen never because:
1563 // 1. The color can be changed only on results
1564 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1565 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1566 if (anAISObj.get()) {
1568 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1571 if (!aColor.empty())
1574 if (aColor.size() != 3)
1577 if (!abortAllOperations())
1579 // 2. show the dialog to change the value
1580 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1581 aDlg->setColor(aColor);
1582 aDlg->move(QCursor::pos());
1583 bool isDone = aDlg->exec() == QDialog::Accepted;
1587 bool isRandomColor = aDlg->isRandomColor();
1589 // 3. abort the previous operation and start a new one
1590 SessionPtr aMgr = ModelAPI_Session::get();
1591 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1592 aMgr->startOperation(aDescription.toStdString());
1594 // 4. set the value to all results
1595 std::vector<int> aColorResult = aDlg->getColor();
1596 foreach(ObjectPtr anObj, theObjects) {
1597 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1598 if (aResult.get() != NULL) {
1599 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1600 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1601 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1602 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1605 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1608 aMgr->finishOperation();
1609 updateCommandStatus();
1612 //**************************************************************
1613 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1614 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1615 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1617 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1619 foreach (ObjectPtr aObj, theList) {
1621 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1623 DocumentPtr aDoc = aPartRes->partDoc();
1624 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1625 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1626 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1629 aObj->setDisplayed(isVisible);
1632 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1635 //**************************************************************
1636 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1638 // Hide all displayed objects
1639 QObjectPtrList aList = myDisplayer->displayedObjects();
1640 foreach (ObjectPtr aObj, aList) {
1641 if (module()->canEraseObject(aObj))
1642 aObj->setDisplayed(false);
1645 // Show only objects from the list
1646 foreach (ObjectPtr aObj, theList) {
1648 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1650 DocumentPtr aDoc = aPartRes->partDoc();
1651 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1652 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1653 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1656 aObj->setDisplayed(true);
1659 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1664 //**************************************************************
1665 void XGUI_Workshop::registerValidators() const
1667 SessionPtr aMgr = ModelAPI_Session::get();
1668 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1671 //**************************************************************
1672 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1676 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1677 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1680 //**************************************************************
1681 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1683 for (int i = 0; i < theDoc->size(theGroup); i++)
1684 theDoc->object(theGroup, i)->setDisplayed(true);
1685 //displayObject(theDoc->object(theGroup, i));
1686 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1689 //**************************************************************
1690 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1692 foreach(ObjectPtr aObj, theList) {
1693 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1695 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1696 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1697 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1698 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1699 (XGUI_Displayer::DisplayMode)theMode, false);
1703 if (theList.size() > 0)
1704 myDisplayer->updateViewer();
1707 //**************************************************************
1708 void XGUI_Workshop::closeDocument()
1710 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1711 while (anOperation) {
1712 anOperation->abort();
1713 anOperation = operationMgr()->currentOperation();
1715 myDisplayer->closeLocalContexts();
1716 myDisplayer->eraseAll();
1717 objectBrowser()->clearContent();
1719 module()->closeDocument();
1721 SessionPtr aMgr = ModelAPI_Session::get();
1725 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1727 XGUI_HistoryMenu* aMenu = NULL;
1728 if (isSalomeMode()) {
1729 QAction* anAction = qobject_cast<QAction*>(theObject);
1732 aMenu = new XGUI_HistoryMenu(anAction);
1734 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1735 aMenu = new XGUI_HistoryMenu(aButton);
1737 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1738 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1741 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1743 QList<ActionInfo> aResult;
1744 std::list<std::string>::const_iterator it = theList.cbegin();
1745 for (; it != theList.cend(); it++) {
1746 QString anId = QString::fromStdString(*it);
1747 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1749 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1752 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1753 if (aContextMenuAct) {
1754 anInfo.initFrom(aContextMenuAct);
1756 anInfo = myActionsMgr->actionInfoById(anId);
1759 anInfo.text = anInfo.text.prepend("Modify ");
1766 void XGUI_Workshop::synchronizeViewer()
1768 SessionPtr aMgr = ModelAPI_Session::get();
1769 DocumentPtr aDoc = aMgr->activeDocument();
1771 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1772 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1773 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1774 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1777 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1778 const std::string& theGroup,
1779 bool theUpdateViewer)
1782 int aSize = theDoc->size(theGroup);
1783 for (int i = 0; i < aSize; i++) {
1784 aObj = theDoc->object(theGroup, i);
1785 if (aObj->isDisplayed())
1786 myDisplayer->display(aObj, false);
1788 if (theUpdateViewer)
1789 myDisplayer->updateViewer();