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()));
171 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
172 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
173 myErrorDlg, SLOT(addError(const QString&)));
175 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
176 // Config_Prop::Color, "225,225,225");
178 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
179 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
180 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
181 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
182 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
183 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
184 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
185 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
188 //******************************************************
189 XGUI_Workshop::~XGUI_Workshop(void)
194 //******************************************************
195 void XGUI_Workshop::startApplication()
199 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
200 Config_Prop::Directory, "");
202 //Initialize event listening
203 myEventsListener->initializeEventListening();
205 registerValidators();
207 // Calling of loadCustomProps before activating module is required
208 // by Config_PropManger to restore user-defined path to plugins
209 ModuleBase_Preferences::loadCustomProps();
213 myMainWindow->show();
214 updateCommandStatus();
219 myViewerProxy->connectViewProxy();
220 connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
221 SLOT(onTrihedronVisibilityChanged(bool)));
223 emit applicationStarted();
226 void XGUI_Workshop::activateModule()
228 myModule->activateSelectionFilters();
230 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
231 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
232 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
233 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
235 updateCommandStatus();
237 // activate visualized objects in the viewer
238 XGUI_Displayer* aDisplayer = displayer();
239 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
241 module()->activeSelectionModes(aModes);
242 aDisplayer->activateObjects(aModes, aDisplayed);
245 void XGUI_Workshop::deactivateModule()
247 myModule->deactivateSelectionFilters();
249 // remove internal displayer filter
250 displayer()->deactivateSelectionFilters();
252 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
253 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
254 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
255 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
257 XGUI_Displayer* aDisplayer = displayer();
258 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
259 aDisplayer->deactivateObjects(aDisplayed, true);
262 //******************************************************
263 void XGUI_Workshop::initMenu()
265 myContextMenuMgr->createActions();
268 // Create only Undo, Redo commands
269 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
270 tr("Undo last command"),
271 QIcon(":pictures/undo.png"),
272 QKeySequence::Undo, false, "MEN_DESK_EDIT");
273 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
274 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
276 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
277 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
279 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
280 QIcon(":pictures/redo.png"), QKeySequence::Redo,
281 false, "MEN_DESK_EDIT");
282 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
284 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
285 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
287 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
288 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
289 // QIcon(":pictures/rebuild.png"), QKeySequence(),
290 // false, "MEN_DESK_EDIT");
291 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
293 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
294 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
296 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
297 QIcon(), QKeySequence(),
298 false, "MEN_DESK_FILE");
299 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
301 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
302 QIcon(), QKeySequence(),
303 false, "MEN_DESK_FILE");
304 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
305 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
308 // File commands group
309 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
311 AppElements_Command* aCommand;
313 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
314 QIcon(":pictures/save.png"), QKeySequence::Save);
315 aCommand->connectTo(this, SLOT(onSave()));
316 //aCommand->disable();
318 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
319 QIcon(":pictures/save.png"), QKeySequence());
320 aCommand->connectTo(this, SLOT(onSaveAs()));
322 QString aUndoId = "UNDO_CMD";
323 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
324 QIcon(":pictures/undo.png"), QKeySequence::Undo);
325 aCommand->connectTo(this, SLOT(onUndo()));
326 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
327 addHistoryMenu(aUndoButton,
328 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
331 QString aRedoId = "REDO_CMD";
332 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
333 QIcon(":pictures/redo.png"), QKeySequence::Redo);
334 aCommand->connectTo(this, SLOT(onRedo()));
335 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
336 addHistoryMenu(aRedoButton,
337 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
340 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
341 // QIcon(":pictures/rebuild.png"), QKeySequence());
342 //aCommand->connectTo(this, SLOT(onRebuild()));
344 //aCommand->disable();
346 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
347 QIcon(":pictures/open.png"), QKeySequence::Open);
348 aCommand->connectTo(this, SLOT(onOpen()));
350 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
351 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
352 aCommand->connectTo(this, SLOT(onPreferences()));
354 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
355 QIcon(":pictures/close.png"), QKeySequence::Close);
356 aCommand->connectTo(this, SLOT(onExit()));
361 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
363 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
364 return aMenuBar->addWorkbench(theName);
368 //******************************************************
369 QMainWindow* XGUI_Workshop::desktop() const
372 return salomeConnector()->desktop();
378 //******************************************************
379 void XGUI_Workshop::onStartWaiting()
381 if (Events_LongOp::isPerformed()) {
382 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
386 //******************************************************
387 void XGUI_Workshop::onAcceptActionClicked()
389 QAction* anAction = dynamic_cast<QAction*>(sender());
390 XGUI_OperationMgr* anOperationMgr = operationMgr();
391 if (anOperationMgr) {
392 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
393 (anOperationMgr->currentOperation());
395 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
396 myOperationMgr->onCommitOperation();
401 //******************************************************
402 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
404 if (!myModule->canActivateSelection(theObject)) {
405 if (myDisplayer->isActive(theObject)) {
406 QObjectPtrList anObjects;
407 anObjects.append(theObject);
408 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
413 //******************************************************
414 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
416 bool aHasNested = false;
417 std::string aFeatureKind = theFeature->getKind();
419 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
420 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
423 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
424 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
425 if (aCommand && aCommand->button()->additionalButtonWidget())
431 //******************************************************
432 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
434 setGrantedFeatures(theOperation);
436 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
441 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
442 setPropertyPanel(aFOperation);
443 // filling the operation values by the current selection
444 // if the operation can be committed after the controls filling, the method perform should
445 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
446 if (!aFOperation->isEditOperation()) {
447 aFOperation->activateByPreselection();
448 if (operationMgr()->currentOperation() != aFOperation)
452 updateCommandStatus();
454 connectToPropertyPanel(true);
455 myModule->operationStarted(aFOperation);
457 // the objects of the current operation should be deactivated
458 QObjectPtrList anObjects;
459 FeaturePtr aFeature = aFOperation->feature();
460 anObjects.append(aFeature);
461 std::list<ResultPtr> aResults = aFeature->results();
462 std::list<ResultPtr>::const_iterator aIt;
463 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
464 anObjects.append(*aIt);
466 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
467 for (; anIt != aLast; anIt++)
468 deactivateActiveObject(*anIt, false);
469 if (anObjects.size() > 0)
470 myDisplayer->updateViewer();
473 //******************************************************
474 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
476 setGrantedFeatures(theOperation);
478 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
479 setPropertyPanel(theOperation);
480 connectToPropertyPanel(true);
482 updateCommandStatus();
484 myModule->operationResumed(theOperation);
488 //******************************************************
489 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
491 updateCommandStatus();
493 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
498 ModuleBase_ISelection* aSel = mySelector->selection();
499 QObjectPtrList aObj = aSel->selectedPresentations();
500 //!< No need for property panel
502 myPropertyPanel->cleanContent();
504 connectToPropertyPanel(false);
505 myModule->operationStopped(aFOperation);
507 // the deactivated objects of the current operation should be activated back.
508 // They were deactivated on operation start or an object redisplay
509 QObjectPtrList anObjects;
510 FeaturePtr aFeature = aFOperation->feature();
511 if (aFeature.get()) { // feature may be not created (plugin load fail)
512 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
513 anObjects.append(aFeature);
514 std::list<ResultPtr> aResults = aFeature->results();
515 std::list<ResultPtr>::const_iterator aIt;
516 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
517 ResultPtr anObject = *aIt;
518 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
519 anObjects.append(anObject);
524 module()->activeSelectionModes(aModes);
525 myDisplayer->activateObjects(aModes, anObjects);
529 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
531 myModule->operationCommitted(theOperation);
534 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
536 myModule->operationAborted(theOperation);
539 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
541 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
545 QStringList aGrantedIds;
547 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
549 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
551 ModuleBase_IModule* aModule = module();
553 aModule->grantedOperationIds(theOperation, aGrantedIds);
555 aFOperation->setGrantedOperationIds(aGrantedIds);
558 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
560 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
565 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
566 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
568 myPropertyPanel->cleanContent();
569 aFactory.createWidget(myPropertyPanel->contentWidget());
571 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
573 // check compatibility of feature and widgets
574 FeaturePtr aFeature = aFOperation->feature();
575 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
576 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
577 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
578 + aWidget->attributeID() + "' used by widget '"
579 + aWidget->metaObject()->className() + "'.";
580 Events_Error::send(anErrorMsg);
581 myPropertyPanel->cleanContent();
586 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
587 bool isStoreValue = !aFOperation->isEditOperation() &&
588 !aWidget->getDefaultValue().empty() &&
589 !aWidget->isComputedDefault();
590 aWidget->setFeature(aFOperation->feature(), isStoreValue);
591 aWidget->enableFocusProcessing();
594 myPropertyPanel->setModelWidgets(aWidgets);
595 aFOperation->setPropertyPanel(myPropertyPanel);
597 myModule->propertyPanelDefined(theOperation);
599 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
601 myErrorMgr->setPropertyPanel(myPropertyPanel);
604 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
606 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
607 if (aPropertyPanel) {
608 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
609 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
610 myModule->connectToPropertyPanel(aWidget, isToConnect);
612 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
615 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
622 * Saves document with given name.
624 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
626 QApplication::restoreOverrideCursor();
627 SessionPtr aMgr = ModelAPI_Session::get();
628 aMgr->save(theName.toLatin1().constData(), theFileNames);
629 QApplication::restoreOverrideCursor();
632 bool XGUI_Workshop::abortAllOperations()
634 return myOperationMgr->abortAllOperations();
637 //******************************************************
638 void XGUI_Workshop::onOpen()
640 if(!abortAllOperations())
642 //save current file before close if modified
643 SessionPtr aSession = ModelAPI_Session::get();
644 if (aSession->isModified()) {
645 //TODO(sbh): re-launch the app?
646 int anAnswer = QMessageBox::question(
647 desktop(), tr("Save current file"),
648 tr("The document is modified, save before opening another?"),
649 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
650 if (anAnswer == QMessageBox::Save) {
652 } else if (anAnswer == QMessageBox::Cancel) {
658 //show file dialog, check if readable and open
659 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
660 if (myCurrentDir.isEmpty())
662 QFileInfo aFileInfo(myCurrentDir);
663 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
664 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
668 QApplication::setOverrideCursor(Qt::WaitCursor);
669 aSession->closeAll();
670 aSession->load(myCurrentDir.toLatin1().constData());
671 myObjectBrowser->rebuildDataTree();
672 updateCommandStatus();
673 QApplication::restoreOverrideCursor();
676 //******************************************************
677 void XGUI_Workshop::onNew()
679 QApplication::setOverrideCursor(Qt::WaitCursor);
680 if (objectBrowser() == 0) {
682 mySelector->connectViewers();
684 myViewerProxy->connectToViewer();
687 myMainWindow->showPythonConsole();
688 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
689 aWnd->showMaximized();
690 updateCommandStatus();
692 myContextMenuMgr->connectViewer();
693 QApplication::restoreOverrideCursor();
697 //******************************************************
698 void XGUI_Workshop::onExit()
700 SessionPtr aMgr = ModelAPI_Session::get();
701 if (aMgr->isModified()) {
702 int anAnswer = QMessageBox::question(
703 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
704 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
705 if (anAnswer == QMessageBox::Save) {
706 bool saved = onSave();
710 } else if (anAnswer == QMessageBox::Cancel) {
717 //******************************************************
718 void XGUI_Workshop::onPreferences()
720 ModuleBase_Prefs aModif;
721 ModuleBase_Preferences::editPreferences(aModif);
722 if (aModif.size() > 0) {
724 foreach (ModuleBase_Pref aPref, aModif)
726 aSection = aPref.first;
727 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
728 myMainWindow->viewer()->updateFromResources();
729 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
730 myMainWindow->menuObject()->updateFromResources();
733 displayer()->redisplayObjects();
738 //******************************************************
739 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
741 XGUI_Displayer* aDisplayer = displayer();
743 aDisplayer->displayTrihedron(theState);
746 //******************************************************
747 bool XGUI_Workshop::onSave()
749 if(!abortAllOperations())
751 if (myCurrentDir.isEmpty()) {
754 std::list<std::string> aFiles;
755 saveDocument(myCurrentDir, aFiles);
756 updateCommandStatus();
758 myMainWindow->setModifiedState(false);
763 //******************************************************
764 bool XGUI_Workshop::onSaveAs()
766 if(!abortAllOperations())
768 QFileDialog dialog(desktop());
769 dialog.setWindowTitle(tr("Select directory to save files..."));
770 dialog.setFileMode(QFileDialog::Directory);
771 dialog.setFilter(tr("Directories (*)"));
772 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
773 dialog.setViewMode(QFileDialog::Detail);
775 if (!dialog.exec()) {
779 QString aTempDir = dialog.selectedFiles().first();
781 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
782 int answer = QMessageBox::question(
784 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
786 tr("The directory already contains some files, save anyway?"),
787 QMessageBox::Save | QMessageBox::Cancel);
788 if (answer == QMessageBox::Cancel) {
792 myCurrentDir = aTempDir;
794 myMainWindow->setCurrentDir(myCurrentDir, false);
795 myMainWindow->setModifiedState(false);
800 //******************************************************
801 void XGUI_Workshop::onUndo(int theTimes)
803 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
804 SessionPtr aMgr = ModelAPI_Session::get();
805 std::list<std::string> aUndoList = aMgr->undoList();
806 if (aMgr->isOperation()) {
807 /// this is important for nested operations
808 /// when sketch operation is active, this condition is false and
809 /// the sketch operation is not aborted
810 operationMgr()->onAbortOperation();
812 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
813 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
815 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
816 myObjectBrowser->rebuildDataTree();
819 operationMgr()->updateApplyOfOperations();
820 updateCommandStatus();
823 //******************************************************
824 void XGUI_Workshop::onRedo(int theTimes)
826 // the viewer update should be blocked in order to avoid the features blinking. For the created
827 // feature a results are created, the flush of the created signal caused the viewer redisplay for
828 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
829 // redo of all possible objects happens
830 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
832 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
833 SessionPtr aMgr = ModelAPI_Session::get();
834 std::list<std::string> aRedoList = aMgr->redoList();
835 if (aMgr->isOperation()) {
836 /// this is important for nested operations
837 /// when sketch operation is active, this condition is false and
838 /// the sketch operation is not aborted
839 operationMgr()->onAbortOperation();
841 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
842 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
844 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
845 myObjectBrowser->rebuildDataTree();
847 operationMgr()->updateApplyOfOperations();
848 updateCommandStatus();
850 // unblock the viewer update functionality and make update on purpose
851 myDisplayer->enableUpdateViewer(isUpdateEnabled);
852 myDisplayer->updateViewer();
855 //******************************************************
856 //void XGUI_Workshop::onRebuild()
858 // SessionPtr aMgr = ModelAPI_Session::get();
859 // bool aWasOperation = aMgr->isOperation(); // keep this value
860 // if (!aWasOperation) {
861 // aMgr->startOperation("Rebuild");
863 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
864 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
865 // new Events_Message(aRebuildEvent, this)));
866 // if (!aWasOperation) {
867 // aMgr->finishOperation();
869 // updateCommandStatus();
872 //******************************************************
873 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
875 ModuleBase_ModelWidget* anActiveWidget = 0;
876 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
878 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
880 anActiveWidget = aPanel->activeWidget();
883 operationMgr()->onValidateOperation();
885 myModule->widgetStateChanged(thePreviousState);
888 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
890 QString libName = QString::fromStdString(library(theModule.toStdString()));
891 if (libName.isEmpty()) {
892 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
897 CREATE_FUNC crtInst = 0;
900 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
904 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
905 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
906 QString aMsg((char*) &lpMsgBuf);
907 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
908 ::LocalFree(lpMsgBuf);
910 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
914 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
915 | FORMAT_MESSAGE_IGNORE_INSERTS,
916 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
917 QString aMsg((char*) &lpMsgBuf);
918 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
919 ::LocalFree(lpMsgBuf);
923 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
925 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
927 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
929 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
934 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
936 if (!err.isEmpty()) {
938 Events_Error::send(err.toStdString());
940 qWarning(qPrintable(err));
946 //******************************************************
947 bool XGUI_Workshop::createModule()
949 Config_ModuleReader aModuleReader;
950 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
951 myModule = loadModule(moduleName);
955 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
956 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
957 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
958 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
960 myModule->createFeatures();
961 //myActionsMgr->update();
965 //******************************************************
966 void XGUI_Workshop::updateCommandStatus()
968 QList<QAction*> aCommands;
970 aCommands = salomeConnector()->commandList();
972 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
973 foreach (AppElements_Command* aCmd, aMenuBar->features())
974 aCommands.append(aCmd);
976 SessionPtr aMgr = ModelAPI_Session::get();
977 if (aMgr->hasModuleDocument()) {
978 foreach(QAction* aCmd, aCommands) {
979 QString aId = aCmd->data().toString();
980 if (aId == "UNDO_CMD")
981 aCmd->setEnabled(myModule->canUndo());
982 else if (aId == "REDO_CMD")
983 aCmd->setEnabled(myModule->canRedo());
985 // Enable all commands
986 aCmd->setEnabled(true);
990 foreach(QAction* aCmd, aCommands) {
991 QString aId = aCmd->data().toString();
992 if (aId == "NEW_CMD")
993 aCmd->setEnabled(true);
994 else if (aId == "EXIT_CMD")
995 aCmd->setEnabled(true);
997 aCmd->setEnabled(false);
1000 myActionsMgr->updateCommandsStatus();
1001 emit commandStatusUpdated();
1004 void XGUI_Workshop::updateHistory()
1006 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1007 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1008 emit updateUndoHistory(aUndoRes);
1010 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1011 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1012 emit updateRedoHistory(aRedoRes);
1015 //******************************************************
1016 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1018 QDockWidget* aObjDock = new QDockWidget(theParent);
1019 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1020 aObjDock->setWindowTitle(tr("Object browser"));
1021 aObjDock->setStyleSheet(
1022 "::title { position: relative; padding-left: 5px; text-align: left center }");
1023 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1024 myModule->customizeObjectBrowser(myObjectBrowser);
1025 aObjDock->setWidget(myObjectBrowser);
1027 myContextMenuMgr->connectObjectBrowser();
1031 //******************************************************
1033 * Creates dock widgets, places them in corresponding area
1034 * and tabifies if necessary.
1036 void XGUI_Workshop::createDockWidgets()
1038 QMainWindow* aDesktop = desktop();
1039 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1040 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1041 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1042 myPropertyPanel->setupActions(myActionsMgr);
1043 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1044 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1045 hidePropertyPanel(); ///<! Invisible by default
1046 hideObjectBrowser();
1047 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1048 myPropertyPanel->installEventFilter(myOperationMgr);
1050 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1051 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1053 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1054 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1055 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1056 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1058 connect(myPropertyPanel, SIGNAL(enterClicked()),
1059 myOperationMgr, SLOT(onProcessEnter()));
1062 //******************************************************
1063 void XGUI_Workshop::showPropertyPanel()
1065 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1066 ///<! Restore ability to close panel from the window's menu
1067 aViewAct->setEnabled(true);
1068 myPropertyPanel->show();
1069 myPropertyPanel->raise();
1071 // The next code is necessary to made the property panel the active window
1072 // in order to operation manager could process key events of the panel.
1073 // otherwise they are ignored. It happens only if the same(activateWindow) is
1074 // not happened by property panel activation(e.g. resume operation of Sketch)
1075 ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1076 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1079 //******************************************************
1080 void XGUI_Workshop::hidePropertyPanel()
1082 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1083 ///<! Do not allow to show empty property panel
1084 aViewAct->setEnabled(false);
1085 myPropertyPanel->hide();
1087 // the property panel is active window of the desktop, when it is
1088 // hidden, it is undefined which window becomes active. By this reason
1089 // it is defined to perform the desktop as the active window.
1090 // in SALOME mode, workstack made the PyConsole the active window,
1091 // set the focus on it. As a result, shortcuts of the application, like
1092 // are processed by this console. For example Undo actions.
1093 // It is possible that this code is to be moved to NewGeom package
1094 QMainWindow* aDesktop = desktop();
1095 ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1096 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1099 //******************************************************
1100 void XGUI_Workshop::showObjectBrowser()
1102 myObjectBrowser->parentWidget()->show();
1105 //******************************************************
1106 void XGUI_Workshop::hideObjectBrowser()
1108 myObjectBrowser->parentWidget()->hide();
1111 //******************************************************
1112 void XGUI_Workshop::salomeViewerSelectionChanged()
1114 emit salomeViewerSelection();
1117 //**************************************************************
1118 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1120 return mySalomeConnector->viewer();
1123 //**************************************************************
1124 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1126 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1127 if (theId == "DELETE_CMD")
1129 else if (theId == "MOVE_CMD")
1131 else if (theId == "COLOR_CMD")
1132 changeColor(aObjects);
1133 else if (theId == "SHOW_CMD")
1134 showObjects(aObjects, true);
1135 else if (theId == "HIDE_CMD")
1136 showObjects(aObjects, false);
1137 else if (theId == "SHOW_ONLY_CMD")
1138 showOnlyObjects(aObjects);
1139 else if (theId == "SHADING_CMD")
1140 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1141 else if (theId == "WIREFRAME_CMD")
1142 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1143 else if (theId == "HIDEALL_CMD") {
1144 QObjectPtrList aList = myDisplayer->displayedObjects();
1145 foreach (ObjectPtr aObj, aList) {
1146 if (module()->canEraseObject(aObj))
1147 aObj->setDisplayed(false);
1149 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1153 //**************************************************************
1154 void XGUI_Workshop::deleteObjects()
1156 ModuleBase_IModule* aModule = module();
1157 // 1. allow the module to delete objects, do nothing if it has succeed
1158 if (aModule->deleteObjects()) {
1159 updateCommandStatus();
1163 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1164 if (!abortAllOperations())
1166 // It is necessary to clear selection in order to avoid selection changed event during
1167 // deletion and negative consequences connected with processing of already deleted items
1168 mySelector->clearSelection();
1169 // check whether the object can be deleted. There should not be parts which are not loaded
1170 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1173 bool hasResult = false;
1174 bool hasFeature = false;
1175 bool hasParameter = false;
1176 bool hasSubFeature = false;
1177 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1178 if (!(hasFeature || hasParameter))
1181 // 1. start operation
1182 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1183 aDescription += tr(" %1");
1184 QStringList aObjectNames;
1185 foreach (ObjectPtr aObj, anObjects) {
1186 if (!aObj->data()->isValid())
1188 aObjectNames << QString::fromStdString(aObj->data()->name());
1190 aDescription = aDescription.arg(aObjectNames.join(", "));
1191 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1193 operationMgr()->startOperation(anOpAction);
1194 // 3. delete objects
1195 std::set<FeaturePtr> anIgnoredFeatures;
1196 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1197 operationMgr()->commitOperation();
1200 operationMgr()->abortOperation(operationMgr()->currentOperation());
1204 //**************************************************************
1205 void XGUI_Workshop::moveObjects()
1207 if (!abortAllOperations())
1210 SessionPtr aMgr = ModelAPI_Session::get();
1212 QString anActionId = "MOVE_CMD";
1213 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1214 aMgr->startOperation(aDescription.toStdString());
1216 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1217 // It is necessary to clear selection in order to avoid selection changed event during
1218 // moving and negative consequences connected with processing of already moved items
1219 mySelector->clearSelection();
1220 // check whether the object can be moved. There should not be parts which are not loaded
1221 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1224 DocumentPtr anActiveDocument = aMgr->activeDocument();
1225 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1226 foreach (ObjectPtr aObject, anObjects) {
1227 if (!myModule->canApplyAction(aObject, anActionId))
1230 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1231 if (aFeature.get()) {
1232 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1233 aCurrentFeature = anActiveDocument->currentFeature(true);
1236 aMgr->finishOperation();
1239 //**************************************************************
1240 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1241 const std::set<FeaturePtr>& theIgnoredFeatures,
1243 const bool theAskAboutDeleteReferences)
1247 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1248 for (; aDIt != aDLast; ++aDIt) {
1249 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1251 QString anInfoStr = aDInfo.join(", ");
1252 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1255 // 1. find all referenced features
1256 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1257 foreach (ObjectPtr aDeletedObj, theList) {
1258 std::set<FeaturePtr> alreadyProcessed;
1259 XGUI_Tools::refsToFeatureInAllDocuments(
1260 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1261 std::set<FeaturePtr> aDifference;
1262 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1263 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1264 std::inserter(aDifference, aDifference.begin()));
1265 aIndirectRefFeatures = aDifference;
1268 bool doDeleteReferences = true;
1270 // 2. warn about the references remove, break the delete operation if the user chose it
1271 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1272 QStringList aDirectRefNames;
1273 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1274 aDirectRefNames.append(aFeature->name().c_str());
1275 QString aDirectNames = aDirectRefNames.join(", ");
1277 QStringList aIndirectRefNames;
1278 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1279 aIndirectRefNames.append(aFeature->name().c_str());
1280 QString aIndirectNames = aIndirectRefNames.join(", ");
1282 bool canReplaceParameters = true;
1283 foreach (ObjectPtr aObj, theList) {
1284 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1285 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1286 canReplaceParameters = false;
1291 QMessageBox aMessageBox(theParent);
1292 aMessageBox.setWindowTitle(tr("Delete features"));
1293 aMessageBox.setIcon(QMessageBox::Warning);
1294 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1295 aMessageBox.setDefaultButton(QMessageBox::No);
1298 if (canReplaceParameters) {
1299 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?"))
1300 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1301 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1303 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1304 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1306 aMessageBox.setText(aText);
1308 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1310 if (aButtonRole == QMessageBox::NoRole)
1313 if (aButtonRole == QMessageBox::ActionRole) {
1314 foreach (ObjectPtr aObj, theList)
1315 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1316 doDeleteReferences = false;
1320 // 3. remove referenced features
1321 if (doDeleteReferences) {
1322 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1323 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1324 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1325 aLast = aFeaturesToDelete.end();
1329 for (; anIt != aLast; anIt++) {
1330 FeaturePtr aFeature = (*anIt);
1331 DocumentPtr aDoc = aFeature->document();
1332 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1333 aDoc->removeFeature(aFeature);
1335 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1340 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1345 QString anActionId = "DELETE_CMD";
1346 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1347 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1348 // 4. remove the parameter features
1349 foreach (ObjectPtr aObj, theList) {
1350 // features and parameters can be removed here,
1351 // the results are removed only by a corresponded feature remove
1352 std::string aGroupName = aObj->groupName();
1353 if (!anObjectGroups.contains(aGroupName.c_str()))
1356 if (!myModule->canApplyAction(aObj, anActionId))
1359 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1361 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1362 // part features are removed in the PartSet module. This condition should be moved there
1363 if (aFeature->getKind() == "Part")
1366 DocumentPtr aDoc = aObj->document();
1367 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1369 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1370 anInfo.append(anInfoStr);
1371 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1373 aDoc->removeFeature(aFeature);
1378 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1383 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1385 bool isFoundResultType = false;
1386 foreach(ObjectPtr anObj, theObjects)
1388 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1389 if (aResult.get() == NULL)
1392 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1393 if (isFoundResultType)
1396 return isFoundResultType;
1399 //**************************************************************
1400 // Returns the list of all features for theDocument and all features of
1401 // all nested parts.
1402 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1404 std::list<FeaturePtr> aResultList;
1405 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1406 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1407 // The order of appending features of the part and the part itself is important
1409 // Append features from a part feature
1410 foreach (const ResultPtr& aResult, aFeature->results()) {
1411 ResultPartPtr aResultPart =
1412 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1413 if (aResultPart.get() && aResultPart->partDoc().get()) {
1415 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1416 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1420 aResultList.push_back(aFeature);
1425 //**************************************************************
1426 // Returns the list of features placed between theObject and the current feature
1427 // in the same document. Excludes theObject, includes the current feature.
1428 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1430 std::list<FeaturePtr> aResult;
1431 DocumentPtr aDocument = theObject->document();
1432 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1433 // find the object iterator
1434 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1435 if (aObjectIt == anAllFeatures.end())
1437 // find the current feature iterator
1438 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1439 if (aCurrentIt == anAllFeatures.end())
1441 // check the right order
1442 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1444 // exclude the object
1445 std::advance(aObjectIt, 1);
1446 // include the current feature
1447 std::advance(aCurrentIt, 1);
1448 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1451 bool XGUI_Workshop::canMoveFeature()
1453 QString anActionId = "MOVE_CMD";
1455 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1456 QObjectPtrList aValidatedObjects;
1457 foreach (ObjectPtr aObject, aObjects) {
1458 if (!myModule->canApplyAction(aObject, anActionId))
1460 // To be moved feature should be in active document
1461 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1463 aValidatedObjects.append(aObject);
1465 if (aValidatedObjects.size() != aObjects.size())
1466 aObjects = aValidatedObjects;
1468 bool aCanMove = !aObjects.empty();
1470 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1471 for (; anIt != aLast && aCanMove; anIt++) {
1472 ObjectPtr aObject = *anIt;
1473 // 1. Get features placed between selected and current in the document
1474 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1475 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1476 if (aFeaturesBetween.empty())
1479 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1480 // 2. Get all reference features to the selected object in the document
1481 std::set<FeaturePtr> aRefFeatures;
1482 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1484 if (aRefFeatures.empty())
1487 // 3. Find any placed features in all reference features
1488 std::set<FeaturePtr> aIntersectionFeatures;
1489 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1490 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1491 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1492 // 4. Return false if any reference feature is placed before current feature
1493 if (!aIntersectionFeatures.empty())
1501 //**************************************************************
1502 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1504 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1505 if (!aCanBeShaded) {
1506 ResultCompSolidPtr aCompsolidResult =
1507 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1508 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1509 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1510 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1513 return aCanBeShaded;
1516 //**************************************************************
1517 bool XGUI_Workshop::canChangeColor() const
1519 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1521 std::set<std::string> aTypes;
1522 aTypes.insert(ModelAPI_ResultGroup::group());
1523 aTypes.insert(ModelAPI_ResultConstruction::group());
1524 aTypes.insert(ModelAPI_ResultBody::group());
1525 aTypes.insert(ModelAPI_ResultPart::group());
1527 return hasResults(aObjects, aTypes);
1530 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1532 if (!theResult.get())
1535 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1536 if (aColorAttr.get() != NULL) {
1537 if (!aColorAttr->size()) {
1538 aColorAttr->setSize(3);
1540 aColorAttr->setValue(0, theColor[0]);
1541 aColorAttr->setValue(1, theColor[1]);
1542 aColorAttr->setValue(2, theColor[2]);
1546 //**************************************************************
1547 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1550 AttributeIntArrayPtr aColorAttr;
1551 // 1. find the current color of the object. This is a color of AIS presentation
1552 // The objects are iterated until a first valid color is found
1553 std::vector<int> aColor;
1554 foreach(ObjectPtr anObject, theObjects) {
1555 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1556 if (aResult.get()) {
1557 XGUI_CustomPrs::getResultColor(aResult, aColor);
1560 // TODO: remove the obtaining a color from the AIS object
1561 // this does not happen never because:
1562 // 1. The color can be changed only on results
1563 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1564 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1565 if (anAISObj.get()) {
1567 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1570 if (!aColor.empty())
1573 if (aColor.size() != 3)
1576 if (!abortAllOperations())
1578 // 2. show the dialog to change the value
1579 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1580 aDlg->setColor(aColor);
1581 aDlg->move(QCursor::pos());
1582 bool isDone = aDlg->exec() == QDialog::Accepted;
1586 bool isRandomColor = aDlg->isRandomColor();
1588 // 3. abort the previous operation and start a new one
1589 SessionPtr aMgr = ModelAPI_Session::get();
1590 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1591 aMgr->startOperation(aDescription.toStdString());
1593 // 4. set the value to all results
1594 std::vector<int> aColorResult = aDlg->getColor();
1595 foreach(ObjectPtr anObj, theObjects) {
1596 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1597 if (aResult.get() != NULL) {
1598 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1599 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1600 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1601 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1604 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1607 aMgr->finishOperation();
1608 updateCommandStatus();
1611 //**************************************************************
1612 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1613 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1614 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1616 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1618 foreach (ObjectPtr aObj, theList) {
1620 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1622 DocumentPtr aDoc = aPartRes->partDoc();
1623 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1624 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1625 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1628 aObj->setDisplayed(isVisible);
1631 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1634 //**************************************************************
1635 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1637 // Hide all displayed objects
1638 QObjectPtrList aList = myDisplayer->displayedObjects();
1639 foreach (ObjectPtr aObj, aList) {
1640 if (module()->canEraseObject(aObj))
1641 aObj->setDisplayed(false);
1644 // Show only objects from the list
1645 foreach (ObjectPtr aObj, theList) {
1647 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1649 DocumentPtr aDoc = aPartRes->partDoc();
1650 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1651 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1652 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1655 aObj->setDisplayed(true);
1658 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1663 //**************************************************************
1664 void XGUI_Workshop::registerValidators() const
1666 SessionPtr aMgr = ModelAPI_Session::get();
1667 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1670 //**************************************************************
1671 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1675 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1676 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1679 //**************************************************************
1680 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1682 for (int i = 0; i < theDoc->size(theGroup); i++)
1683 theDoc->object(theGroup, i)->setDisplayed(true);
1684 //displayObject(theDoc->object(theGroup, i));
1685 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1688 //**************************************************************
1689 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1691 foreach(ObjectPtr aObj, theList) {
1692 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1694 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1695 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1696 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1697 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1698 (XGUI_Displayer::DisplayMode)theMode, false);
1702 if (theList.size() > 0)
1703 myDisplayer->updateViewer();
1706 //**************************************************************
1707 void XGUI_Workshop::closeDocument()
1709 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1710 while (anOperation) {
1711 anOperation->abort();
1712 anOperation = operationMgr()->currentOperation();
1714 myDisplayer->closeLocalContexts();
1715 myDisplayer->eraseAll();
1716 objectBrowser()->clearContent();
1718 module()->closeDocument();
1720 SessionPtr aMgr = ModelAPI_Session::get();
1724 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1726 XGUI_HistoryMenu* aMenu = NULL;
1727 if (isSalomeMode()) {
1728 QAction* anAction = qobject_cast<QAction*>(theObject);
1731 aMenu = new XGUI_HistoryMenu(anAction);
1733 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1734 aMenu = new XGUI_HistoryMenu(aButton);
1736 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1737 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1740 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1742 QList<ActionInfo> aResult;
1743 std::list<std::string>::const_iterator it = theList.cbegin();
1744 for (; it != theList.cend(); it++) {
1745 QString anId = QString::fromStdString(*it);
1746 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1748 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1751 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1752 if (aContextMenuAct) {
1753 anInfo.initFrom(aContextMenuAct);
1755 anInfo = myActionsMgr->actionInfoById(anId);
1758 anInfo.text = anInfo.text.prepend("Modify ");
1765 void XGUI_Workshop::synchronizeViewer()
1767 SessionPtr aMgr = ModelAPI_Session::get();
1768 DocumentPtr aDoc = aMgr->activeDocument();
1770 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1771 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1772 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1773 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1776 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1777 const std::string& theGroup,
1778 bool theUpdateViewer)
1781 int aSize = theDoc->size(theGroup);
1782 for (int i = 0; i < aSize; i++) {
1783 aObj = theDoc->object(theGroup, i);
1784 if (aObj->isDisplayed())
1785 myDisplayer->display(aObj, false);
1787 if (theUpdateViewer)
1788 myDisplayer->updateViewer();