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 == "CLEAN_HISTORY_CMD")
1134 else if (theId == "MOVE_CMD")
1136 else if (theId == "COLOR_CMD")
1137 changeColor(aObjects);
1138 else if (theId == "SHOW_CMD") {
1139 showObjects(aObjects, true);
1140 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1142 else if (theId == "HIDE_CMD")
1143 showObjects(aObjects, false);
1144 else if (theId == "SHOW_ONLY_CMD") {
1145 showOnlyObjects(aObjects);
1146 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1148 else if (theId == "SHADING_CMD")
1149 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1150 else if (theId == "WIREFRAME_CMD")
1151 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1152 else if (theId == "HIDEALL_CMD") {
1153 QObjectPtrList aList = myDisplayer->displayedObjects();
1154 foreach (ObjectPtr aObj, aList) {
1155 if (module()->canEraseObject(aObj))
1156 aObj->setDisplayed(false);
1158 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1162 //**************************************************************
1163 void XGUI_Workshop::deleteObjects()
1165 ModuleBase_IModule* aModule = module();
1166 // 1. allow the module to delete objects, do nothing if it has succeed
1167 if (aModule->deleteObjects()) {
1168 updateCommandStatus();
1172 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1173 if (!abortAllOperations())
1175 // It is necessary to clear selection in order to avoid selection changed event during
1176 // deletion and negative consequences connected with processing of already deleted items
1177 mySelector->clearSelection();
1178 // check whether the object can be deleted. There should not be parts which are not loaded
1179 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1182 bool hasResult = false;
1183 bool hasFeature = false;
1184 bool hasParameter = false;
1185 bool hasSubFeature = false;
1186 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1187 if (!(hasFeature || hasParameter))
1190 // 1. start operation
1191 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1192 aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1193 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1194 operationMgr()->startOperation(anOpAction);
1196 // 3. delete objects
1197 std::set<FeaturePtr> anIgnoredFeatures;
1198 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1199 operationMgr()->commitOperation();
1202 operationMgr()->abortOperation(operationMgr()->currentOperation());
1206 //**************************************************************
1207 void XGUI_Workshop::cleanHistory()
1209 if (!abortAllOperations())
1212 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1214 // 1. find all referenced features
1215 std::set<FeaturePtr> anUnusedFeatures;
1216 std::set<FeaturePtr> aDirectRefFeatures;
1217 foreach (ObjectPtr anObject, anObjects) {
1218 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1219 if (aFeature.get()) {
1220 std::set<FeaturePtr> alreadyProcessed;
1221 aDirectRefFeatures.clear();
1222 XGUI_Tools::refsDirectToFeatureInAllDocuments(anObject, anObject, anObjects,
1223 aDirectRefFeatures, alreadyProcessed);
1224 if (aDirectRefFeatures.empty() && anUnusedFeatures.find(aFeature) == anUnusedFeatures.end())
1225 anUnusedFeatures.insert(aFeature);
1229 // 2. warn about the references remove, break the delete operation if the user chose it
1230 if (!anUnusedFeatures.empty()) {
1232 foreach (const FeaturePtr& aFeature, anUnusedFeatures)
1233 aNames.append(aFeature->name().c_str());
1234 QString anUnusedNames = aNames.join(", ");
1236 QString anActionId = "CLEAN_HISTORY_CMD";
1237 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1239 QMessageBox aMessageBox(desktop());
1240 aMessageBox.setWindowTitle(aDescription);
1241 aMessageBox.setIcon(QMessageBox::Warning);
1242 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1243 aMessageBox.setDefaultButton(QMessageBox::No);
1245 QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1246 .arg(anUnusedNames));
1247 aMessageBox.setText(aText);
1248 if (aMessageBox.exec() == QMessageBox::No)
1251 // 1. start operation
1252 aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1253 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1254 operationMgr()->startOperation(anOpAction);
1256 std::set<FeaturePtr> anIgnoredFeatures;
1257 if (removeFeatures(anObjects, anIgnoredFeatures, anActionId)) {
1258 operationMgr()->commitOperation();
1261 operationMgr()->abortOperation(operationMgr()->currentOperation());
1266 //**************************************************************
1267 void XGUI_Workshop::moveObjects()
1269 if (!abortAllOperations())
1272 SessionPtr aMgr = ModelAPI_Session::get();
1274 QString anActionId = "MOVE_CMD";
1275 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1276 aMgr->startOperation(aDescription.toStdString());
1278 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1279 // It is necessary to clear selection in order to avoid selection changed event during
1280 // moving and negative consequences connected with processing of already moved items
1281 mySelector->clearSelection();
1282 // check whether the object can be moved. There should not be parts which are not loaded
1283 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1286 DocumentPtr anActiveDocument = aMgr->activeDocument();
1287 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1288 foreach (ObjectPtr aObject, anObjects) {
1289 if (!myModule->canApplyAction(aObject, anActionId))
1292 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1293 if (aFeature.get()) {
1294 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1295 aCurrentFeature = anActiveDocument->currentFeature(true);
1298 aMgr->finishOperation();
1301 //**************************************************************
1302 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1303 const std::set<FeaturePtr>& theIgnoredFeatures,
1305 const bool theAskAboutDeleteReferences)
1309 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1310 for (; aDIt != aDLast; ++aDIt) {
1311 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1313 QString anInfoStr = aDInfo.join(", ");
1314 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1317 // 1. find all referenced features
1318 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1319 foreach (ObjectPtr aDeletedObj, theList) {
1320 std::set<FeaturePtr> alreadyProcessed;
1321 XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1322 aIndirectRefFeatures, alreadyProcessed);
1323 std::set<FeaturePtr> aDifference;
1324 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1325 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1326 std::inserter(aDifference, aDifference.begin()));
1327 aIndirectRefFeatures = aDifference;
1330 bool doDeleteReferences = true;
1332 // 2. warn about the references remove, break the delete operation if the user chose it
1333 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1334 QStringList aDirectRefNames;
1335 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1336 aDirectRefNames.append(aFeature->name().c_str());
1337 QString aDirectNames = aDirectRefNames.join(", ");
1339 QStringList aIndirectRefNames;
1340 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1341 aIndirectRefNames.append(aFeature->name().c_str());
1342 QString aIndirectNames = aIndirectRefNames.join(", ");
1344 bool canReplaceParameters = true;
1345 foreach (ObjectPtr aObj, theList) {
1346 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1347 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1348 canReplaceParameters = false;
1353 QMessageBox aMessageBox(theParent);
1354 aMessageBox.setWindowTitle(tr("Delete features"));
1355 aMessageBox.setIcon(QMessageBox::Warning);
1356 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1357 aMessageBox.setDefaultButton(QMessageBox::No);
1360 if (canReplaceParameters) {
1361 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?"))
1362 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1363 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1365 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1366 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1368 aMessageBox.setText(aText);
1370 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1372 if (aButtonRole == QMessageBox::NoRole)
1375 if (aButtonRole == QMessageBox::ActionRole) {
1376 foreach (ObjectPtr aObj, theList)
1377 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1378 doDeleteReferences = false;
1382 // 3. remove referenced features
1383 if (doDeleteReferences) {
1384 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1385 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1386 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1387 aLast = aFeaturesToDelete.end();
1391 for (; anIt != aLast; anIt++) {
1392 FeaturePtr aFeature = (*anIt);
1393 DocumentPtr aDoc = aFeature->document();
1394 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1395 aDoc->removeFeature(aFeature);
1397 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1402 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1407 QString anActionId = "DELETE_CMD";
1408 removeFeatures(theList, theIgnoredFeatures, anActionId);
1411 //**************************************************************
1412 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1413 const std::set<FeaturePtr>& theIgnoredFeatures,
1414 const QString& theActionId)
1416 bool isDone = false;
1418 QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1419 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1420 // 4. remove the parameter features
1421 foreach (ObjectPtr aObj, theList) {
1422 // features and parameters can be removed here,
1423 // the results are removed only by a corresponded feature remove
1424 std::string aGroupName = aObj->groupName();
1425 if (!anObjectGroups.contains(aGroupName.c_str()))
1428 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1430 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1431 // part features are removed in the PartSet module. This condition should be moved there
1432 if (aFeature->getKind() == "Part")
1435 DocumentPtr aDoc = aObj->document();
1436 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1438 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1439 anInfo.append(anInfoStr);
1440 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1442 aDoc->removeFeature(aFeature);
1448 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1453 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1455 bool isFoundResultType = false;
1456 foreach(ObjectPtr anObj, theObjects)
1458 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1459 if (aResult.get() == NULL)
1462 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1463 if (isFoundResultType)
1466 return isFoundResultType;
1469 //**************************************************************
1470 // Returns the list of all features for theDocument and all features of
1471 // all nested parts.
1472 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1474 std::list<FeaturePtr> aResultList;
1475 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1476 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1477 // The order of appending features of the part and the part itself is important
1479 // Append features from a part feature
1480 foreach (const ResultPtr& aResult, aFeature->results()) {
1481 ResultPartPtr aResultPart =
1482 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1483 if (aResultPart.get() && aResultPart->partDoc().get()) {
1485 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1486 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1490 aResultList.push_back(aFeature);
1495 //**************************************************************
1496 // Returns the list of features placed between theObject and the current feature
1497 // in the same document. Excludes theObject, includes the current feature.
1498 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1500 std::list<FeaturePtr> aResult;
1501 DocumentPtr aDocument = theObject->document();
1502 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1503 // find the object iterator
1504 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1505 if (aObjectIt == anAllFeatures.end())
1507 // find the current feature iterator
1508 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1509 if (aCurrentIt == anAllFeatures.end())
1511 // check the right order
1512 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1514 // exclude the object
1515 std::advance(aObjectIt, 1);
1516 // include the current feature
1517 std::advance(aCurrentIt, 1);
1518 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1521 bool XGUI_Workshop::canMoveFeature()
1523 QString anActionId = "MOVE_CMD";
1525 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1526 QObjectPtrList aValidatedObjects;
1527 foreach (ObjectPtr aObject, aObjects) {
1528 if (!myModule->canApplyAction(aObject, anActionId))
1530 // To be moved feature should be in active document
1531 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1533 aValidatedObjects.append(aObject);
1535 if (aValidatedObjects.size() != aObjects.size())
1536 aObjects = aValidatedObjects;
1538 bool aCanMove = !aObjects.empty();
1540 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1541 for (; anIt != aLast && aCanMove; anIt++) {
1542 ObjectPtr aObject = *anIt;
1543 // 1. Get features placed between selected and current in the document
1544 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1545 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1546 if (aFeaturesBetween.empty())
1549 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1550 // 2. Get all reference features to the selected object in the document
1551 std::set<FeaturePtr> aRefFeatures;
1552 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1554 if (aRefFeatures.empty())
1557 // 3. Find any placed features in all reference features
1558 std::set<FeaturePtr> aIntersectionFeatures;
1559 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1560 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1561 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1562 // 4. Return false if any reference feature is placed before current feature
1563 if (!aIntersectionFeatures.empty())
1571 //**************************************************************
1572 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1574 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1575 if (!aCanBeShaded) {
1576 ResultCompSolidPtr aCompsolidResult =
1577 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1578 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1579 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1580 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1583 return aCanBeShaded;
1586 //**************************************************************
1587 bool XGUI_Workshop::canChangeColor() const
1589 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1591 std::set<std::string> aTypes;
1592 aTypes.insert(ModelAPI_ResultGroup::group());
1593 aTypes.insert(ModelAPI_ResultConstruction::group());
1594 aTypes.insert(ModelAPI_ResultBody::group());
1595 aTypes.insert(ModelAPI_ResultPart::group());
1597 return hasResults(aObjects, aTypes);
1600 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1602 if (!theResult.get())
1605 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1606 if (aColorAttr.get() != NULL) {
1607 if (!aColorAttr->size()) {
1608 aColorAttr->setSize(3);
1610 aColorAttr->setValue(0, theColor[0]);
1611 aColorAttr->setValue(1, theColor[1]);
1612 aColorAttr->setValue(2, theColor[2]);
1616 //**************************************************************
1617 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1620 AttributeIntArrayPtr aColorAttr;
1621 // 1. find the current color of the object. This is a color of AIS presentation
1622 // The objects are iterated until a first valid color is found
1623 std::vector<int> aColor;
1624 foreach(ObjectPtr anObject, theObjects) {
1625 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1626 if (aResult.get()) {
1627 XGUI_CustomPrs::getResultColor(aResult, aColor);
1630 // TODO: remove the obtaining a color from the AIS object
1631 // this does not happen never because:
1632 // 1. The color can be changed only on results
1633 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1634 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1635 if (anAISObj.get()) {
1637 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1640 if (!aColor.empty())
1643 if (aColor.size() != 3)
1646 if (!abortAllOperations())
1648 // 2. show the dialog to change the value
1649 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1650 aDlg->setColor(aColor);
1651 aDlg->move(QCursor::pos());
1652 bool isDone = aDlg->exec() == QDialog::Accepted;
1656 bool isRandomColor = aDlg->isRandomColor();
1658 // 3. abort the previous operation and start a new one
1659 SessionPtr aMgr = ModelAPI_Session::get();
1660 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1661 aMgr->startOperation(aDescription.toStdString());
1663 // 4. set the value to all results
1664 std::vector<int> aColorResult = aDlg->getColor();
1665 foreach(ObjectPtr anObj, theObjects) {
1666 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1667 if (aResult.get() != NULL) {
1668 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1669 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1670 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1671 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1674 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1677 aMgr->finishOperation();
1678 updateCommandStatus();
1681 //**************************************************************
1682 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1683 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1684 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1686 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1688 foreach (ObjectPtr aObj, theList) {
1690 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1692 DocumentPtr aDoc = aPartRes->partDoc();
1693 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1694 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1695 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1698 aObj->setDisplayed(isVisible);
1701 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1704 //**************************************************************
1705 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1707 // Hide all displayed objects
1708 QObjectPtrList aList = myDisplayer->displayedObjects();
1709 foreach (ObjectPtr aObj, aList) {
1710 if (module()->canEraseObject(aObj))
1711 aObj->setDisplayed(false);
1714 // Show only objects from the list
1715 foreach (ObjectPtr aObj, theList) {
1717 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1719 DocumentPtr aDoc = aPartRes->partDoc();
1720 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1721 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1722 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1725 aObj->setDisplayed(true);
1728 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1733 //**************************************************************
1734 void XGUI_Workshop::registerValidators() const
1736 SessionPtr aMgr = ModelAPI_Session::get();
1737 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1740 //**************************************************************
1741 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1745 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1746 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1749 //**************************************************************
1750 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1752 for (int i = 0; i < theDoc->size(theGroup); i++)
1753 theDoc->object(theGroup, i)->setDisplayed(true);
1754 //displayObject(theDoc->object(theGroup, i));
1755 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1758 //**************************************************************
1759 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1761 foreach(ObjectPtr aObj, theList) {
1762 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1764 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1765 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1766 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1767 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1768 (XGUI_Displayer::DisplayMode)theMode, false);
1772 if (theList.size() > 0)
1773 myDisplayer->updateViewer();
1776 //**************************************************************
1777 void XGUI_Workshop::closeDocument()
1779 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1780 while (anOperation) {
1781 anOperation->abort();
1782 anOperation = operationMgr()->currentOperation();
1784 myDisplayer->closeLocalContexts();
1785 myDisplayer->eraseAll();
1786 objectBrowser()->clearContent();
1788 module()->closeDocument();
1790 SessionPtr aMgr = ModelAPI_Session::get();
1794 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1796 XGUI_HistoryMenu* aMenu = NULL;
1797 if (isSalomeMode()) {
1798 QAction* anAction = qobject_cast<QAction*>(theObject);
1801 aMenu = new XGUI_HistoryMenu(anAction);
1803 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1804 aMenu = new XGUI_HistoryMenu(aButton);
1806 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1807 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1810 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1812 QList<ActionInfo> aResult;
1813 std::list<std::string>::const_iterator it = theList.cbegin();
1814 for (; it != theList.cend(); it++) {
1815 QString anId = QString::fromStdString(*it);
1816 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1818 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1821 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1822 if (aContextMenuAct) {
1823 anInfo.initFrom(aContextMenuAct);
1825 anInfo = myActionsMgr->actionInfoById(anId);
1828 anInfo.text = anInfo.text.prepend("Modify ");
1835 void XGUI_Workshop::synchronizeViewer()
1837 SessionPtr aMgr = ModelAPI_Session::get();
1838 DocumentPtr aDoc = aMgr->activeDocument();
1840 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1841 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1842 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1843 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1846 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1847 const std::string& theGroup,
1848 bool theUpdateViewer)
1851 int aSize = theDoc->size(theGroup);
1852 for (int i = 0; i < aSize; i++) {
1853 aObj = theDoc->object(theGroup, i);
1854 if (aObj->isDisplayed())
1855 myDisplayer->display(aObj, false);
1857 if (theUpdateViewer)
1858 myDisplayer->updateViewer();