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
111 //#define DEBUG_FEATURE_NAME
113 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
115 myCurrentDir(QString()),
117 mySalomeConnector(theConnector),
123 myMainWindow = new AppElements_MainWindow();
125 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
126 bool aCloc = aResMgr->booleanValue("language", "locale", true);
128 QLocale::setDefault( QLocale::c() );
130 QLocale::setDefault( QLocale::system() );
133 myDisplayer = new XGUI_Displayer(this);
135 mySelector = new XGUI_SelectionMgr(this);
136 connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
138 myOperationMgr = new XGUI_OperationMgr(this, 0);
139 myActionsMgr = new XGUI_ActionsMgr(this);
140 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
141 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
142 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
143 SLOT(onContextMenuCommand(const QString&, bool)));
145 myViewerProxy = new XGUI_ViewerProxy(this);
146 connect(myViewerProxy, SIGNAL(selectionChanged()),
147 myActionsMgr, SLOT(updateOnViewSelection()));
149 myModuleConnector = new XGUI_ModuleConnector(this);
151 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
152 myOperationMgr->setWorkshop(aWorkshop);
154 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
155 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
157 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
158 SLOT(onOperationStarted(ModuleBase_Operation*)));
159 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
160 SLOT(onOperationResumed(ModuleBase_Operation*)));
161 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
162 SLOT(onOperationStopped(ModuleBase_Operation*)));
163 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
164 SLOT(onOperationCommitted(ModuleBase_Operation*)));
165 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
166 SLOT(onOperationAborted(ModuleBase_Operation*)));
169 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
170 onTrihedronVisibilityChanged(true);
173 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
174 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
175 myErrorDlg, SLOT(addError(const QString&)));
177 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
178 // Config_Prop::Color, "225,225,225");
180 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
181 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
182 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
183 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
184 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
185 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
186 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
187 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
190 //******************************************************
191 XGUI_Workshop::~XGUI_Workshop(void)
196 //******************************************************
197 void XGUI_Workshop::startApplication()
201 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
202 Config_Prop::Directory, "");
204 //Initialize event listening
205 myEventsListener->initializeEventListening();
207 registerValidators();
209 // Calling of loadCustomProps before activating module is required
210 // by Config_PropManger to restore user-defined path to plugins
211 ModuleBase_Preferences::loadCustomProps();
215 myMainWindow->show();
216 updateCommandStatus();
221 myViewerProxy->connectViewProxy();
222 connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
223 SLOT(onTrihedronVisibilityChanged(bool)));
225 emit applicationStarted();
228 void XGUI_Workshop::activateModule()
230 myModule->activateSelectionFilters();
232 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
233 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
234 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
235 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
237 updateCommandStatus();
239 // activate visualized objects in the viewer
240 XGUI_Displayer* aDisplayer = displayer();
241 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
243 module()->activeSelectionModes(aModes);
244 aDisplayer->activateObjects(aModes, aDisplayed);
247 void XGUI_Workshop::deactivateModule()
249 myModule->deactivateSelectionFilters();
251 // remove internal displayer filter
252 displayer()->deactivateSelectionFilters();
254 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
255 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
256 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
257 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
259 XGUI_Displayer* aDisplayer = displayer();
260 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
261 aDisplayer->deactivateObjects(aDisplayed, true);
264 //******************************************************
265 void XGUI_Workshop::initMenu()
267 myContextMenuMgr->createActions();
270 // Create only Undo, Redo commands
271 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
272 tr("Undo last command"),
273 QIcon(":pictures/undo.png"),
274 QKeySequence::Undo, false, "MEN_DESK_EDIT");
275 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
276 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
278 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
279 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
281 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
282 QIcon(":pictures/redo.png"), QKeySequence::Redo,
283 false, "MEN_DESK_EDIT");
284 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
286 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
287 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
289 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
290 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
291 // QIcon(":pictures/rebuild.png"), QKeySequence(),
292 // false, "MEN_DESK_EDIT");
293 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
295 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
296 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
298 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
299 QIcon(), QKeySequence(),
300 false, "MEN_DESK_FILE");
301 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
303 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
304 QIcon(), QKeySequence(),
305 false, "MEN_DESK_FILE");
306 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
307 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
310 // File commands group
311 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
313 AppElements_Command* aCommand;
315 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
316 QIcon(":pictures/save.png"), QKeySequence::Save);
317 aCommand->connectTo(this, SLOT(onSave()));
318 //aCommand->disable();
320 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
321 QIcon(":pictures/save.png"), QKeySequence());
322 aCommand->connectTo(this, SLOT(onSaveAs()));
324 QString aUndoId = "UNDO_CMD";
325 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
326 QIcon(":pictures/undo.png"), QKeySequence::Undo);
327 aCommand->connectTo(this, SLOT(onUndo()));
328 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
329 addHistoryMenu(aUndoButton,
330 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
333 QString aRedoId = "REDO_CMD";
334 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
335 QIcon(":pictures/redo.png"), QKeySequence::Redo);
336 aCommand->connectTo(this, SLOT(onRedo()));
337 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
338 addHistoryMenu(aRedoButton,
339 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
342 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
343 // QIcon(":pictures/rebuild.png"), QKeySequence());
344 //aCommand->connectTo(this, SLOT(onRebuild()));
346 //aCommand->disable();
348 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
349 QIcon(":pictures/open.png"), QKeySequence::Open);
350 aCommand->connectTo(this, SLOT(onOpen()));
352 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
353 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
354 aCommand->connectTo(this, SLOT(onPreferences()));
356 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
357 QIcon(":pictures/close.png"), QKeySequence::Close);
358 aCommand->connectTo(this, SLOT(onExit()));
363 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
365 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
366 return aMenuBar->addWorkbench(theName);
370 //******************************************************
371 QMainWindow* XGUI_Workshop::desktop() const
374 return salomeConnector()->desktop();
380 //******************************************************
381 void XGUI_Workshop::onStartWaiting()
383 if (Events_LongOp::isPerformed()) {
384 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
388 //******************************************************
389 void XGUI_Workshop::onAcceptActionClicked()
391 QAction* anAction = dynamic_cast<QAction*>(sender());
392 XGUI_OperationMgr* anOperationMgr = operationMgr();
393 if (anOperationMgr) {
394 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
395 (anOperationMgr->currentOperation());
397 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
398 myOperationMgr->onCommitOperation();
403 //******************************************************
404 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
406 if (!myModule->canActivateSelection(theObject)) {
407 if (myDisplayer->isActive(theObject)) {
408 QObjectPtrList anObjects;
409 anObjects.append(theObject);
410 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
415 //******************************************************
416 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
418 bool aHasNested = false;
419 std::string aFeatureKind = theFeature->getKind();
421 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
422 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
425 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
426 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
427 if (aCommand && aCommand->button()->additionalButtonWidget())
433 //******************************************************
434 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
436 setGrantedFeatures(theOperation);
438 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
443 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
444 setPropertyPanel(aFOperation);
445 // filling the operation values by the current selection
446 // if the operation can be committed after the controls filling, the method perform should
447 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
448 if (!aFOperation->isEditOperation()) {
449 aFOperation->activateByPreselection();
450 if (operationMgr()->currentOperation() != aFOperation)
454 updateCommandStatus();
456 connectToPropertyPanel(true);
457 myModule->operationStarted(aFOperation);
459 // the objects of the current operation should be deactivated
460 QObjectPtrList anObjects;
461 FeaturePtr aFeature = aFOperation->feature();
462 anObjects.append(aFeature);
463 std::list<ResultPtr> aResults = aFeature->results();
464 std::list<ResultPtr>::const_iterator aIt;
465 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
466 anObjects.append(*aIt);
468 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
469 for (; anIt != aLast; anIt++)
470 deactivateActiveObject(*anIt, false);
471 if (anObjects.size() > 0)
472 myDisplayer->updateViewer();
475 //******************************************************
476 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
478 setGrantedFeatures(theOperation);
480 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
481 setPropertyPanel(theOperation);
482 connectToPropertyPanel(true);
484 updateCommandStatus();
486 myModule->operationResumed(theOperation);
490 //******************************************************
491 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
493 updateCommandStatus();
495 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
500 ModuleBase_ISelection* aSel = mySelector->selection();
501 QObjectPtrList aObj = aSel->selectedPresentations();
502 //!< No need for property panel
504 myPropertyPanel->cleanContent();
506 connectToPropertyPanel(false);
507 myModule->operationStopped(aFOperation);
509 // the deactivated objects of the current operation should be activated back.
510 // They were deactivated on operation start or an object redisplay
511 QObjectPtrList anObjects;
512 FeaturePtr aFeature = aFOperation->feature();
513 if (aFeature.get()) { // feature may be not created (plugin load fail)
514 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
515 anObjects.append(aFeature);
516 std::list<ResultPtr> aResults = aFeature->results();
517 std::list<ResultPtr>::const_iterator aIt;
518 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
519 ResultPtr anObject = *aIt;
520 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
521 anObjects.append(anObject);
526 module()->activeSelectionModes(aModes);
527 myDisplayer->activateObjects(aModes, anObjects);
531 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
533 myModule->operationCommitted(theOperation);
536 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
538 myModule->operationAborted(theOperation);
541 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
543 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
547 QStringList aGrantedIds;
549 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
551 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
553 ModuleBase_IModule* aModule = module();
555 aModule->grantedOperationIds(theOperation, aGrantedIds);
557 aFOperation->setGrantedOperationIds(aGrantedIds);
560 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
562 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
567 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
568 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
570 myPropertyPanel->cleanContent();
571 aFactory.createWidget(myPropertyPanel->contentWidget());
573 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
575 // check compatibility of feature and widgets
576 FeaturePtr aFeature = aFOperation->feature();
577 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
578 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
579 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
580 + aWidget->attributeID() + "' used by widget '"
581 + aWidget->metaObject()->className() + "'.";
582 Events_Error::send(anErrorMsg);
583 myPropertyPanel->cleanContent();
588 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
589 bool isStoreValue = !aFOperation->isEditOperation() &&
590 !aWidget->getDefaultValue().empty() &&
591 !aWidget->isComputedDefault();
592 aWidget->setFeature(aFOperation->feature(), isStoreValue);
593 aWidget->enableFocusProcessing();
596 myPropertyPanel->setModelWidgets(aWidgets);
597 aFOperation->setPropertyPanel(myPropertyPanel);
599 myModule->propertyPanelDefined(theOperation);
601 #ifndef DEBUG_FEATURE_NAME
602 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
604 std::string aFeatureName = aFeature->name();
605 myPropertyPanel->setWindowTitle(QString("%1: %2").arg(theOperation->getDescription()->description())
606 .arg(aFeatureName.c_str()));
609 myErrorMgr->setPropertyPanel(myPropertyPanel);
612 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
614 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
615 if (aPropertyPanel) {
616 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
617 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
618 myModule->connectToPropertyPanel(aWidget, isToConnect);
620 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
623 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
630 * Saves document with given name.
632 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
634 QApplication::restoreOverrideCursor();
635 SessionPtr aMgr = ModelAPI_Session::get();
636 aMgr->save(theName.toLatin1().constData(), theFileNames);
637 QApplication::restoreOverrideCursor();
640 bool XGUI_Workshop::abortAllOperations()
642 return myOperationMgr->abortAllOperations();
645 //******************************************************
646 void XGUI_Workshop::onOpen()
648 if(!abortAllOperations())
650 //save current file before close if modified
651 SessionPtr aSession = ModelAPI_Session::get();
652 if (aSession->isModified()) {
653 //TODO(sbh): re-launch the app?
654 int anAnswer = QMessageBox::question(
655 desktop(), tr("Save current file"),
656 tr("The document is modified, save before opening another?"),
657 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
658 if (anAnswer == QMessageBox::Save) {
660 } else if (anAnswer == QMessageBox::Cancel) {
666 //show file dialog, check if readable and open
667 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
668 if (myCurrentDir.isEmpty())
670 QFileInfo aFileInfo(myCurrentDir);
671 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
672 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
676 QApplication::setOverrideCursor(Qt::WaitCursor);
677 aSession->closeAll();
678 aSession->load(myCurrentDir.toLatin1().constData());
679 myObjectBrowser->rebuildDataTree();
680 updateCommandStatus();
681 QApplication::restoreOverrideCursor();
684 //******************************************************
685 void XGUI_Workshop::onNew()
687 QApplication::setOverrideCursor(Qt::WaitCursor);
688 if (objectBrowser() == 0) {
690 mySelector->connectViewers();
692 myViewerProxy->connectToViewer();
695 myMainWindow->showPythonConsole();
696 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
697 aWnd->showMaximized();
698 updateCommandStatus();
700 myContextMenuMgr->connectViewer();
701 QApplication::restoreOverrideCursor();
705 //******************************************************
706 void XGUI_Workshop::onExit()
708 SessionPtr aMgr = ModelAPI_Session::get();
709 if (aMgr->isModified()) {
710 int anAnswer = QMessageBox::question(
711 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
712 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
713 if (anAnswer == QMessageBox::Save) {
714 bool saved = onSave();
718 } else if (anAnswer == QMessageBox::Cancel) {
725 //******************************************************
726 void XGUI_Workshop::onPreferences()
728 ModuleBase_Prefs aModif;
729 ModuleBase_Preferences::editPreferences(aModif);
730 if (aModif.size() > 0) {
732 foreach (ModuleBase_Pref aPref, aModif)
734 aSection = aPref.first;
735 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
736 myMainWindow->viewer()->updateFromResources();
737 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
738 myMainWindow->menuObject()->updateFromResources();
741 displayer()->redisplayObjects();
746 //******************************************************
747 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
749 XGUI_Displayer* aDisplayer = displayer();
751 aDisplayer->displayTrihedron(theState);
754 //******************************************************
755 bool XGUI_Workshop::onSave()
757 if(!abortAllOperations())
759 if (myCurrentDir.isEmpty()) {
762 std::list<std::string> aFiles;
763 saveDocument(myCurrentDir, aFiles);
764 updateCommandStatus();
766 myMainWindow->setModifiedState(false);
771 //******************************************************
772 bool XGUI_Workshop::onSaveAs()
774 if(!abortAllOperations())
776 QFileDialog dialog(desktop());
777 dialog.setWindowTitle(tr("Select directory to save files..."));
778 dialog.setFileMode(QFileDialog::Directory);
779 dialog.setFilter(tr("Directories (*)"));
780 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
781 dialog.setViewMode(QFileDialog::Detail);
783 if (!dialog.exec()) {
787 QString aTempDir = dialog.selectedFiles().first();
789 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
790 int answer = QMessageBox::question(
792 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
794 tr("The directory already contains some files, save anyway?"),
795 QMessageBox::Save | QMessageBox::Cancel);
796 if (answer == QMessageBox::Cancel) {
800 myCurrentDir = aTempDir;
802 myMainWindow->setCurrentDir(myCurrentDir, false);
803 myMainWindow->setModifiedState(false);
808 //******************************************************
809 void XGUI_Workshop::onUndo(int theTimes)
811 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
812 SessionPtr aMgr = ModelAPI_Session::get();
813 std::list<std::string> aUndoList = aMgr->undoList();
814 if (aMgr->isOperation()) {
815 /// this is important for nested operations
816 /// when sketch operation is active, this condition is false and
817 /// the sketch operation is not aborted
818 operationMgr()->onAbortOperation();
820 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
821 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
823 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
824 myObjectBrowser->rebuildDataTree();
827 operationMgr()->updateApplyOfOperations();
828 updateCommandStatus();
831 //******************************************************
832 void XGUI_Workshop::onRedo(int theTimes)
834 // the viewer update should be blocked in order to avoid the features blinking. For the created
835 // feature a results are created, the flush of the created signal caused the viewer redisplay for
836 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
837 // redo of all possible objects happens
838 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
840 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
841 SessionPtr aMgr = ModelAPI_Session::get();
842 std::list<std::string> aRedoList = aMgr->redoList();
843 if (aMgr->isOperation()) {
844 /// this is important for nested operations
845 /// when sketch operation is active, this condition is false and
846 /// the sketch operation is not aborted
847 operationMgr()->onAbortOperation();
849 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
850 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
852 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
853 myObjectBrowser->rebuildDataTree();
855 operationMgr()->updateApplyOfOperations();
856 updateCommandStatus();
858 // unblock the viewer update functionality and make update on purpose
859 myDisplayer->enableUpdateViewer(isUpdateEnabled);
860 myDisplayer->updateViewer();
863 //******************************************************
864 //void XGUI_Workshop::onRebuild()
866 // SessionPtr aMgr = ModelAPI_Session::get();
867 // bool aWasOperation = aMgr->isOperation(); // keep this value
868 // if (!aWasOperation) {
869 // aMgr->startOperation("Rebuild");
871 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
872 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
873 // new Events_Message(aRebuildEvent, this)));
874 // if (!aWasOperation) {
875 // aMgr->finishOperation();
877 // updateCommandStatus();
880 //******************************************************
881 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
883 ModuleBase_ModelWidget* anActiveWidget = 0;
884 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
886 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
888 anActiveWidget = aPanel->activeWidget();
891 operationMgr()->onValidateOperation();
893 myModule->widgetStateChanged(thePreviousState);
896 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
898 QString libName = QString::fromStdString(library(theModule.toStdString()));
899 if (libName.isEmpty()) {
900 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
905 CREATE_FUNC crtInst = 0;
908 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
912 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
913 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
914 QString aMsg((char*) &lpMsgBuf);
915 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
916 ::LocalFree(lpMsgBuf);
918 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
922 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
923 | FORMAT_MESSAGE_IGNORE_INSERTS,
924 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
925 QString aMsg((char*) &lpMsgBuf);
926 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
927 ::LocalFree(lpMsgBuf);
931 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
933 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
935 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
937 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
942 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
944 if (!err.isEmpty()) {
946 Events_Error::send(err.toStdString());
948 qWarning(qPrintable(err));
954 //******************************************************
955 bool XGUI_Workshop::createModule()
957 Config_ModuleReader aModuleReader;
958 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
959 myModule = loadModule(moduleName);
963 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
964 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
965 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
966 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
968 myModule->createFeatures();
969 //myActionsMgr->update();
973 //******************************************************
974 void XGUI_Workshop::updateCommandStatus()
976 QList<QAction*> aCommands;
978 aCommands = salomeConnector()->commandList();
980 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
981 foreach (AppElements_Command* aCmd, aMenuBar->features())
982 aCommands.append(aCmd);
984 SessionPtr aMgr = ModelAPI_Session::get();
985 if (aMgr->hasModuleDocument()) {
986 foreach(QAction* aCmd, aCommands) {
987 QString aId = aCmd->data().toString();
988 if (aId == "UNDO_CMD")
989 aCmd->setEnabled(myModule->canUndo());
990 else if (aId == "REDO_CMD")
991 aCmd->setEnabled(myModule->canRedo());
993 // Enable all commands
994 aCmd->setEnabled(true);
998 foreach(QAction* aCmd, aCommands) {
999 QString aId = aCmd->data().toString();
1000 if (aId == "NEW_CMD")
1001 aCmd->setEnabled(true);
1002 else if (aId == "EXIT_CMD")
1003 aCmd->setEnabled(true);
1005 aCmd->setEnabled(false);
1008 myActionsMgr->updateCommandsStatus();
1009 emit commandStatusUpdated();
1012 void XGUI_Workshop::updateHistory()
1014 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1015 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1016 emit updateUndoHistory(aUndoRes);
1018 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1019 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1020 emit updateRedoHistory(aRedoRes);
1023 //******************************************************
1024 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1026 QDockWidget* aObjDock = new QDockWidget(theParent);
1027 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1028 aObjDock->setWindowTitle(tr("Object browser"));
1029 aObjDock->setStyleSheet(
1030 "::title { position: relative; padding-left: 5px; text-align: left center }");
1031 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1032 myModule->customizeObjectBrowser(myObjectBrowser);
1033 aObjDock->setWidget(myObjectBrowser);
1035 myContextMenuMgr->connectObjectBrowser();
1039 //******************************************************
1041 * Creates dock widgets, places them in corresponding area
1042 * and tabifies if necessary.
1044 void XGUI_Workshop::createDockWidgets()
1046 QMainWindow* aDesktop = desktop();
1047 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1048 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1049 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1050 myPropertyPanel->setupActions(myActionsMgr);
1051 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1052 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1053 hidePropertyPanel(); ///<! Invisible by default
1054 hideObjectBrowser();
1055 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1056 myPropertyPanel->installEventFilter(myOperationMgr);
1058 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1059 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1061 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1062 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1063 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1064 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1066 connect(myPropertyPanel, SIGNAL(enterClicked()),
1067 myOperationMgr, SLOT(onProcessEnter()));
1070 //******************************************************
1071 void XGUI_Workshop::showPropertyPanel()
1073 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1074 ///<! Restore ability to close panel from the window's menu
1075 aViewAct->setEnabled(true);
1076 myPropertyPanel->show();
1077 myPropertyPanel->raise();
1079 // The next code is necessary to made the property panel the active window
1080 // in order to operation manager could process key events of the panel.
1081 // otherwise they are ignored. It happens only if the same(activateWindow) is
1082 // not happened by property panel activation(e.g. resume operation of Sketch)
1083 ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1084 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1087 //******************************************************
1088 void XGUI_Workshop::hidePropertyPanel()
1090 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1091 ///<! Do not allow to show empty property panel
1092 aViewAct->setEnabled(false);
1093 myPropertyPanel->hide();
1095 // the property panel is active window of the desktop, when it is
1096 // hidden, it is undefined which window becomes active. By this reason
1097 // it is defined to perform the desktop as the active window.
1098 // in SALOME mode, workstack made the PyConsole the active window,
1099 // set the focus on it. As a result, shortcuts of the application, like
1100 // are processed by this console. For example Undo actions.
1101 // It is possible that this code is to be moved to NewGeom package
1102 QMainWindow* aDesktop = desktop();
1103 ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1104 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1107 //******************************************************
1108 void XGUI_Workshop::showObjectBrowser()
1110 if (!isSalomeMode())
1111 myObjectBrowser->parentWidget()->show();
1114 //******************************************************
1115 void XGUI_Workshop::hideObjectBrowser()
1117 if (!isSalomeMode())
1118 myObjectBrowser->parentWidget()->hide();
1121 //******************************************************
1122 void XGUI_Workshop::salomeViewerSelectionChanged()
1124 emit salomeViewerSelection();
1127 //**************************************************************
1128 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1130 return mySalomeConnector->viewer();
1133 //**************************************************************
1134 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1136 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1137 if (theId == "DELETE_CMD")
1139 else if (theId == "CLEAN_HISTORY_CMD")
1141 else if (theId == "MOVE_CMD")
1143 else if (theId == "COLOR_CMD")
1144 changeColor(aObjects);
1145 else if (theId == "SHOW_CMD") {
1146 showObjects(aObjects, true);
1147 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1149 else if (theId == "HIDE_CMD")
1150 showObjects(aObjects, false);
1151 else if (theId == "SHOW_ONLY_CMD") {
1152 showOnlyObjects(aObjects);
1153 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1155 else if (theId == "SHADING_CMD")
1156 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1157 else if (theId == "WIREFRAME_CMD")
1158 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1159 else if (theId == "HIDEALL_CMD") {
1160 QObjectPtrList aList = myDisplayer->displayedObjects();
1161 foreach (ObjectPtr aObj, aList) {
1162 if (module()->canEraseObject(aObj))
1163 aObj->setDisplayed(false);
1165 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1169 //**************************************************************
1170 void XGUI_Workshop::deleteObjects()
1172 ModuleBase_IModule* aModule = module();
1173 // 1. allow the module to delete objects, do nothing if it has succeed
1174 if (aModule->deleteObjects()) {
1175 updateCommandStatus();
1179 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1180 if (!abortAllOperations())
1182 // It is necessary to clear selection in order to avoid selection changed event during
1183 // deletion and negative consequences connected with processing of already deleted items
1184 mySelector->clearSelection();
1185 // check whether the object can be deleted. There should not be parts which are not loaded
1186 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1189 bool hasResult = false;
1190 bool hasFeature = false;
1191 bool hasParameter = false;
1192 bool hasSubFeature = false;
1193 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1194 if (!(hasFeature || hasParameter))
1197 // 1. start operation
1198 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1199 aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1200 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1201 operationMgr()->startOperation(anOpAction);
1203 // 3. delete objects
1204 std::set<FeaturePtr> anIgnoredFeatures;
1205 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1206 operationMgr()->commitOperation();
1209 operationMgr()->abortOperation(operationMgr()->currentOperation());
1213 //**************************************************************
1214 void XGUI_Workshop::cleanHistory()
1216 if (!abortAllOperations())
1219 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1221 // 1. find all referenced features
1222 QList<ObjectPtr> anUnusedObjects;
1223 std::set<FeaturePtr> aDirectRefFeatures;
1224 foreach (ObjectPtr anObject, anObjects) {
1225 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1226 // for parameter result, use the corresponded reature to be removed
1227 if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1228 aFeature = ModelAPI_Feature::feature(anObject);
1230 if (aFeature.get()) {
1231 std::set<FeaturePtr> alreadyProcessed;
1232 aDirectRefFeatures.clear();
1233 XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, anObjects,
1234 aDirectRefFeatures, alreadyProcessed);
1235 if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1236 anUnusedObjects.append(aFeature);
1240 // 2. warn about the references remove, break the delete operation if the user chose it
1241 if (!anUnusedObjects.empty()) {
1243 foreach (const ObjectPtr& anObject, anUnusedObjects) {
1244 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1245 aNames.append(aFeature->name().c_str());
1247 QString anUnusedNames = aNames.join(", ");
1249 QString anActionId = "CLEAN_HISTORY_CMD";
1250 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1252 QMessageBox aMessageBox(desktop());
1253 aMessageBox.setWindowTitle(aDescription);
1254 aMessageBox.setIcon(QMessageBox::Warning);
1255 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1256 aMessageBox.setDefaultButton(QMessageBox::No);
1258 QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1259 .arg(anUnusedNames));
1260 aMessageBox.setText(aText);
1261 if (aMessageBox.exec() == QMessageBox::No)
1264 // 1. start operation
1265 aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1266 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1267 operationMgr()->startOperation(anOpAction);
1269 std::set<FeaturePtr> anIgnoredFeatures;
1270 if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId)) {
1271 operationMgr()->commitOperation();
1274 operationMgr()->abortOperation(operationMgr()->currentOperation());
1279 //**************************************************************
1280 void XGUI_Workshop::moveObjects()
1282 if (!abortAllOperations())
1285 SessionPtr aMgr = ModelAPI_Session::get();
1287 QString anActionId = "MOVE_CMD";
1288 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1289 aMgr->startOperation(aDescription.toStdString());
1291 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1292 // It is necessary to clear selection in order to avoid selection changed event during
1293 // moving and negative consequences connected with processing of already moved items
1294 mySelector->clearSelection();
1295 // check whether the object can be moved. There should not be parts which are not loaded
1296 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1299 DocumentPtr anActiveDocument = aMgr->activeDocument();
1300 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1301 foreach (ObjectPtr aObject, anObjects) {
1302 if (!myModule->canApplyAction(aObject, anActionId))
1305 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1306 if (aFeature.get()) {
1307 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1308 aCurrentFeature = anActiveDocument->currentFeature(true);
1311 aMgr->finishOperation();
1314 //**************************************************************
1315 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1316 const std::set<FeaturePtr>& theIgnoredFeatures,
1318 const bool theAskAboutDeleteReferences)
1322 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1323 for (; aDIt != aDLast; ++aDIt) {
1324 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1326 QString anInfoStr = aDInfo.join(", ");
1327 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1330 // 1. find all referenced features
1331 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1332 foreach (ObjectPtr aDeletedObj, theList) {
1333 std::set<FeaturePtr> alreadyProcessed;
1334 XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1335 aIndirectRefFeatures, alreadyProcessed);
1336 std::set<FeaturePtr> aDifference;
1337 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1338 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1339 std::inserter(aDifference, aDifference.begin()));
1340 aIndirectRefFeatures = aDifference;
1343 bool doDeleteReferences = true;
1345 // 2. warn about the references remove, break the delete operation if the user chose it
1346 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1347 QStringList aDirectRefNames;
1348 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1349 aDirectRefNames.append(aFeature->name().c_str());
1350 QString aDirectNames = aDirectRefNames.join(", ");
1352 QStringList aIndirectRefNames;
1353 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1354 aIndirectRefNames.append(aFeature->name().c_str());
1355 QString aIndirectNames = aIndirectRefNames.join(", ");
1357 bool canReplaceParameters = true;
1358 foreach (ObjectPtr aObj, theList) {
1359 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1360 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1361 canReplaceParameters = false;
1366 QMessageBox aMessageBox(theParent);
1367 aMessageBox.setWindowTitle(tr("Delete features"));
1368 aMessageBox.setIcon(QMessageBox::Warning);
1369 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1370 aMessageBox.setDefaultButton(QMessageBox::No);
1373 if (canReplaceParameters) {
1374 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?"))
1375 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1376 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1378 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1379 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1381 aMessageBox.setText(aText);
1383 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1385 if (aButtonRole == QMessageBox::NoRole)
1388 if (aButtonRole == QMessageBox::ActionRole) {
1389 foreach (ObjectPtr aObj, theList)
1390 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1391 doDeleteReferences = false;
1395 // 3. remove referenced features
1396 if (doDeleteReferences) {
1397 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1398 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1399 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1400 aLast = aFeaturesToDelete.end();
1404 for (; anIt != aLast; anIt++) {
1405 FeaturePtr aFeature = (*anIt);
1406 DocumentPtr aDoc = aFeature->document();
1407 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1408 aDoc->removeFeature(aFeature);
1410 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1415 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1420 QString anActionId = "DELETE_CMD";
1421 return removeFeatures(theList, theIgnoredFeatures, anActionId);
1424 //**************************************************************
1425 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1426 const std::set<FeaturePtr>& theIgnoredFeatures,
1427 const QString& theActionId)
1429 bool isDone = false;
1431 QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1432 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1433 // 4. remove the parameter features
1434 foreach (ObjectPtr aObj, theList) {
1435 // features and parameters can be removed here,
1436 // the results are removed only by a corresponded feature remove
1437 std::string aGroupName = aObj->groupName();
1438 if (!anObjectGroups.contains(aGroupName.c_str()))
1441 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1443 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1444 // part features are removed in the PartSet module. This condition should be moved there
1445 if (aFeature->getKind() == "Part")
1448 DocumentPtr aDoc = aObj->document();
1449 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1451 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1452 anInfo.append(anInfoStr);
1453 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1455 aDoc->removeFeature(aFeature);
1461 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1466 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1468 bool isFoundResultType = false;
1469 foreach(ObjectPtr anObj, theObjects)
1471 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1472 if (aResult.get() == NULL)
1475 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1476 if (isFoundResultType)
1479 return isFoundResultType;
1482 //**************************************************************
1483 // Returns the list of all features for theDocument and all features of
1484 // all nested parts.
1485 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1487 std::list<FeaturePtr> aResultList;
1488 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1489 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1490 // The order of appending features of the part and the part itself is important
1492 // Append features from a part feature
1493 foreach (const ResultPtr& aResult, aFeature->results()) {
1494 ResultPartPtr aResultPart =
1495 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1496 if (aResultPart.get() && aResultPart->partDoc().get()) {
1498 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1499 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1503 aResultList.push_back(aFeature);
1508 //**************************************************************
1509 // Returns the list of features placed between theObject and the current feature
1510 // in the same document. Excludes theObject, includes the current feature.
1511 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1513 std::list<FeaturePtr> aResult;
1514 DocumentPtr aDocument = theObject->document();
1515 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1516 // find the object iterator
1517 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1518 if (aObjectIt == anAllFeatures.end())
1520 // find the current feature iterator
1521 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1522 if (aCurrentIt == anAllFeatures.end())
1524 // check the right order
1525 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1527 // exclude the object
1528 std::advance(aObjectIt, 1);
1529 // include the current feature
1530 std::advance(aCurrentIt, 1);
1531 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1534 bool XGUI_Workshop::canMoveFeature()
1536 QString anActionId = "MOVE_CMD";
1538 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1539 QObjectPtrList aValidatedObjects;
1540 foreach (ObjectPtr aObject, aObjects) {
1541 if (!myModule->canApplyAction(aObject, anActionId))
1543 // To be moved feature should be in active document
1544 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1546 aValidatedObjects.append(aObject);
1548 if (aValidatedObjects.size() != aObjects.size())
1549 aObjects = aValidatedObjects;
1551 bool aCanMove = !aObjects.empty();
1553 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1554 for (; anIt != aLast && aCanMove; anIt++) {
1555 ObjectPtr aObject = *anIt;
1556 // 1. Get features placed between selected and current in the document
1557 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1558 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1559 if (aFeaturesBetween.empty())
1562 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1563 // 2. Get all reference features to the selected object in the document
1564 std::set<FeaturePtr> aRefFeatures;
1565 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1567 if (aRefFeatures.empty())
1570 // 3. Find any placed features in all reference features
1571 std::set<FeaturePtr> aIntersectionFeatures;
1572 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1573 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1574 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1575 // 4. Return false if any reference feature is placed before current feature
1576 if (!aIntersectionFeatures.empty())
1584 //**************************************************************
1585 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1587 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1588 if (!aCanBeShaded) {
1589 ResultCompSolidPtr aCompsolidResult =
1590 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1591 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1592 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1593 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1596 return aCanBeShaded;
1599 //**************************************************************
1600 bool XGUI_Workshop::canChangeColor() const
1602 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1604 std::set<std::string> aTypes;
1605 aTypes.insert(ModelAPI_ResultGroup::group());
1606 aTypes.insert(ModelAPI_ResultConstruction::group());
1607 aTypes.insert(ModelAPI_ResultBody::group());
1608 aTypes.insert(ModelAPI_ResultPart::group());
1610 return hasResults(aObjects, aTypes);
1613 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1615 if (!theResult.get())
1618 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1619 if (aColorAttr.get() != NULL) {
1620 if (!aColorAttr->size()) {
1621 aColorAttr->setSize(3);
1623 aColorAttr->setValue(0, theColor[0]);
1624 aColorAttr->setValue(1, theColor[1]);
1625 aColorAttr->setValue(2, theColor[2]);
1629 //**************************************************************
1630 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1633 AttributeIntArrayPtr aColorAttr;
1634 // 1. find the current color of the object. This is a color of AIS presentation
1635 // The objects are iterated until a first valid color is found
1636 std::vector<int> aColor;
1637 foreach(ObjectPtr anObject, theObjects) {
1638 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1639 if (aResult.get()) {
1640 XGUI_CustomPrs::getResultColor(aResult, aColor);
1643 // TODO: remove the obtaining a color from the AIS object
1644 // this does not happen never because:
1645 // 1. The color can be changed only on results
1646 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1647 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1648 if (anAISObj.get()) {
1650 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1653 if (!aColor.empty())
1656 if (aColor.size() != 3)
1659 if (!abortAllOperations())
1661 // 2. show the dialog to change the value
1662 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1663 aDlg->setColor(aColor);
1664 aDlg->move(QCursor::pos());
1665 bool isDone = aDlg->exec() == QDialog::Accepted;
1669 bool isRandomColor = aDlg->isRandomColor();
1671 // 3. abort the previous operation and start a new one
1672 SessionPtr aMgr = ModelAPI_Session::get();
1673 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1674 aMgr->startOperation(aDescription.toStdString());
1676 // 4. set the value to all results
1677 std::vector<int> aColorResult = aDlg->getColor();
1678 foreach(ObjectPtr anObj, theObjects) {
1679 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1680 if (aResult.get() != NULL) {
1681 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1682 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1683 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1684 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1687 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1690 aMgr->finishOperation();
1691 updateCommandStatus();
1694 //**************************************************************
1695 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1696 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1697 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1699 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1701 foreach (ObjectPtr aObj, theList) {
1703 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1705 DocumentPtr aDoc = aPartRes->partDoc();
1706 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1707 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1708 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1711 aObj->setDisplayed(isVisible);
1714 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1717 //**************************************************************
1718 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1720 // Hide all displayed objects
1721 QObjectPtrList aList = myDisplayer->displayedObjects();
1722 foreach (ObjectPtr aObj, aList) {
1723 if (module()->canEraseObject(aObj))
1724 aObj->setDisplayed(false);
1727 // Show only objects from the list
1728 foreach (ObjectPtr aObj, theList) {
1730 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1732 DocumentPtr aDoc = aPartRes->partDoc();
1733 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1734 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1735 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1738 aObj->setDisplayed(true);
1741 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1746 //**************************************************************
1747 void XGUI_Workshop::registerValidators() const
1749 SessionPtr aMgr = ModelAPI_Session::get();
1750 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1753 //**************************************************************
1754 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1758 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1759 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1762 //**************************************************************
1763 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1765 for (int i = 0; i < theDoc->size(theGroup); i++)
1766 theDoc->object(theGroup, i)->setDisplayed(true);
1767 //displayObject(theDoc->object(theGroup, i));
1768 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1771 //**************************************************************
1772 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1774 foreach(ObjectPtr aObj, theList) {
1775 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1777 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1778 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1779 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1780 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1781 (XGUI_Displayer::DisplayMode)theMode, false);
1785 if (theList.size() > 0)
1786 myDisplayer->updateViewer();
1789 //**************************************************************
1790 void XGUI_Workshop::closeDocument()
1792 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1793 while (anOperation) {
1794 anOperation->abort();
1795 anOperation = operationMgr()->currentOperation();
1797 myDisplayer->closeLocalContexts();
1798 myDisplayer->eraseAll();
1799 objectBrowser()->clearContent();
1801 module()->closeDocument();
1803 SessionPtr aMgr = ModelAPI_Session::get();
1807 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1809 XGUI_HistoryMenu* aMenu = NULL;
1810 if (isSalomeMode()) {
1811 QAction* anAction = qobject_cast<QAction*>(theObject);
1814 aMenu = new XGUI_HistoryMenu(anAction);
1816 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1817 aMenu = new XGUI_HistoryMenu(aButton);
1819 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1820 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1823 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1825 QList<ActionInfo> aResult;
1826 std::list<std::string>::const_iterator it = theList.cbegin();
1827 for (; it != theList.cend(); it++) {
1828 QString anId = QString::fromStdString(*it);
1829 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1831 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1834 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1835 if (aContextMenuAct) {
1836 anInfo.initFrom(aContextMenuAct);
1838 anInfo = myActionsMgr->actionInfoById(anId);
1841 anInfo.text = anInfo.text.prepend("Modify ");
1848 void XGUI_Workshop::synchronizeViewer()
1850 SessionPtr aMgr = ModelAPI_Session::get();
1851 DocumentPtr aDoc = aMgr->activeDocument();
1853 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1854 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1855 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1856 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1859 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1860 const std::string& theGroup,
1861 bool theUpdateViewer)
1864 int aSize = theDoc->size(theGroup);
1865 for (int i = 0; i < aSize; i++) {
1866 aObj = theDoc->object(theGroup, i);
1867 if (aObj->isDisplayed())
1868 myDisplayer->display(aObj, false);
1870 if (theUpdateViewer)
1871 myDisplayer->updateViewer();