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 emit applicationStarted();
222 void XGUI_Workshop::activateModule()
224 myModule->activateSelectionFilters();
226 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
227 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
228 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
229 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
231 updateCommandStatus();
233 // activate visualized objects in the viewer
234 XGUI_Displayer* aDisplayer = displayer();
235 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
237 module()->activeSelectionModes(aModes);
238 aDisplayer->activateObjects(aModes, aDisplayed);
241 void XGUI_Workshop::deactivateModule()
243 myModule->deactivateSelectionFilters();
245 // remove internal displayer filter
246 displayer()->deactivateSelectionFilters();
248 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
249 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
250 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
251 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
253 XGUI_Displayer* aDisplayer = displayer();
254 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
255 aDisplayer->deactivateObjects(aDisplayed, true);
258 //******************************************************
259 void XGUI_Workshop::initMenu()
261 myContextMenuMgr->createActions();
264 // Create only Undo, Redo commands
265 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
266 tr("Undo last command"),
267 QIcon(":pictures/undo.png"),
268 QKeySequence::Undo, false, "MEN_DESK_EDIT");
269 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
270 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
272 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
273 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
275 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
276 QIcon(":pictures/redo.png"), QKeySequence::Redo,
277 false, "MEN_DESK_EDIT");
278 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
280 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
281 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
283 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
284 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
285 // QIcon(":pictures/rebuild.png"), QKeySequence(),
286 // false, "MEN_DESK_EDIT");
287 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
289 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
290 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
292 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
293 QIcon(), QKeySequence(),
294 false, "MEN_DESK_FILE");
295 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
297 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
298 QIcon(), QKeySequence(),
299 false, "MEN_DESK_FILE");
300 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
301 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
304 // File commands group
305 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
307 AppElements_Command* aCommand;
309 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
310 QIcon(":pictures/save.png"), QKeySequence::Save);
311 aCommand->connectTo(this, SLOT(onSave()));
312 //aCommand->disable();
314 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
315 QIcon(":pictures/save.png"), QKeySequence());
316 aCommand->connectTo(this, SLOT(onSaveAs()));
318 QString aUndoId = "UNDO_CMD";
319 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
320 QIcon(":pictures/undo.png"), QKeySequence::Undo);
321 aCommand->connectTo(this, SLOT(onUndo()));
322 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
323 addHistoryMenu(aUndoButton,
324 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
327 QString aRedoId = "REDO_CMD";
328 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
329 QIcon(":pictures/redo.png"), QKeySequence::Redo);
330 aCommand->connectTo(this, SLOT(onRedo()));
331 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
332 addHistoryMenu(aRedoButton,
333 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
336 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
337 // QIcon(":pictures/rebuild.png"), QKeySequence());
338 //aCommand->connectTo(this, SLOT(onRebuild()));
340 //aCommand->disable();
342 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
343 QIcon(":pictures/open.png"), QKeySequence::Open);
344 aCommand->connectTo(this, SLOT(onOpen()));
346 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
347 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
348 aCommand->connectTo(this, SLOT(onPreferences()));
350 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
351 QIcon(":pictures/close.png"), QKeySequence::Close);
352 aCommand->connectTo(this, SLOT(onExit()));
357 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
359 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
360 return aMenuBar->addWorkbench(theName);
364 //******************************************************
365 QMainWindow* XGUI_Workshop::desktop() const
368 return salomeConnector()->desktop();
374 //******************************************************
375 void XGUI_Workshop::onStartWaiting()
377 if (Events_LongOp::isPerformed()) {
378 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
382 //******************************************************
383 void XGUI_Workshop::onAcceptActionClicked()
385 QAction* anAction = dynamic_cast<QAction*>(sender());
386 XGUI_OperationMgr* anOperationMgr = operationMgr();
387 if (anOperationMgr) {
388 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
389 (anOperationMgr->currentOperation());
391 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
392 myOperationMgr->onCommitOperation();
397 //******************************************************
398 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
400 if (!myModule->canActivateSelection(theObject)) {
401 if (myDisplayer->isActive(theObject)) {
402 QObjectPtrList anObjects;
403 anObjects.append(theObject);
404 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
409 //******************************************************
410 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
412 bool aHasNested = false;
413 std::string aFeatureKind = theFeature->getKind();
415 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
416 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
419 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
420 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
421 if (aCommand && aCommand->button()->additionalButtonWidget())
427 //******************************************************
428 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
430 setGrantedFeatures(theOperation);
432 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
437 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
438 setPropertyPanel(aFOperation);
439 // filling the operation values by the current selection
440 // if the operation can be committed after the controls filling, the method perform should
441 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
442 if (!aFOperation->isEditOperation()) {
443 aFOperation->activateByPreselection();
444 if (operationMgr()->currentOperation() != aFOperation)
448 updateCommandStatus();
450 connectToPropertyPanel(true);
451 myModule->operationStarted(aFOperation);
453 // the objects of the current operation should be deactivated
454 QObjectPtrList anObjects;
455 FeaturePtr aFeature = aFOperation->feature();
456 anObjects.append(aFeature);
457 std::list<ResultPtr> aResults = aFeature->results();
458 std::list<ResultPtr>::const_iterator aIt;
459 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
460 anObjects.append(*aIt);
462 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
463 for (; anIt != aLast; anIt++)
464 deactivateActiveObject(*anIt, false);
465 if (anObjects.size() > 0)
466 myDisplayer->updateViewer();
469 //******************************************************
470 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
472 setGrantedFeatures(theOperation);
474 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
475 setPropertyPanel(theOperation);
476 connectToPropertyPanel(true);
478 updateCommandStatus();
480 myModule->operationResumed(theOperation);
484 //******************************************************
485 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
487 updateCommandStatus();
489 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
494 ModuleBase_ISelection* aSel = mySelector->selection();
495 QObjectPtrList aObj = aSel->selectedPresentations();
496 //!< No need for property panel
498 myPropertyPanel->cleanContent();
500 connectToPropertyPanel(false);
501 myModule->operationStopped(aFOperation);
503 // the deactivated objects of the current operation should be activated back.
504 // They were deactivated on operation start or an object redisplay
505 QObjectPtrList anObjects;
506 FeaturePtr aFeature = aFOperation->feature();
507 if (aFeature.get()) { // feature may be not created (plugin load fail)
508 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
509 anObjects.append(aFeature);
510 std::list<ResultPtr> aResults = aFeature->results();
511 std::list<ResultPtr>::const_iterator aIt;
512 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
513 ResultPtr anObject = *aIt;
514 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
515 anObjects.append(anObject);
520 module()->activeSelectionModes(aModes);
521 myDisplayer->activateObjects(aModes, anObjects);
525 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
527 myModule->operationCommitted(theOperation);
530 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
532 myModule->operationAborted(theOperation);
535 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
537 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
541 QStringList aGrantedIds;
543 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
545 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
547 ModuleBase_IModule* aModule = module();
549 aModule->grantedOperationIds(theOperation, aGrantedIds);
551 aFOperation->setGrantedOperationIds(aGrantedIds);
554 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
556 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
561 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
562 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
564 myPropertyPanel->cleanContent();
565 aFactory.createWidget(myPropertyPanel->contentWidget());
567 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
569 // check compatibility of feature and widgets
570 FeaturePtr aFeature = aFOperation->feature();
571 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
572 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
573 std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
574 + aWidget->attributeID() + "' used by widget '"
575 + aWidget->metaObject()->className() + "'.";
576 Events_Error::send(anErrorMsg);
577 myPropertyPanel->cleanContent();
582 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
583 bool isStoreValue = !aFOperation->isEditOperation() &&
584 !aWidget->getDefaultValue().empty() &&
585 !aWidget->isComputedDefault();
586 aWidget->setFeature(aFOperation->feature(), isStoreValue);
587 aWidget->enableFocusProcessing();
590 myPropertyPanel->setModelWidgets(aWidgets);
591 aFOperation->setPropertyPanel(myPropertyPanel);
593 myModule->propertyPanelDefined(theOperation);
595 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
597 myErrorMgr->setPropertyPanel(myPropertyPanel);
600 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
602 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
603 if (aPropertyPanel) {
604 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
605 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
606 myModule->connectToPropertyPanel(aWidget, isToConnect);
608 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
611 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
618 * Saves document with given name.
620 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
622 QApplication::restoreOverrideCursor();
623 SessionPtr aMgr = ModelAPI_Session::get();
624 aMgr->save(theName.toLatin1().constData(), theFileNames);
625 QApplication::restoreOverrideCursor();
628 bool XGUI_Workshop::abortAllOperations()
630 return myOperationMgr->abortAllOperations();
633 //******************************************************
634 void XGUI_Workshop::onOpen()
636 if(!abortAllOperations())
638 //save current file before close if modified
639 SessionPtr aSession = ModelAPI_Session::get();
640 if (aSession->isModified()) {
641 //TODO(sbh): re-launch the app?
642 int anAnswer = QMessageBox::question(
643 desktop(), tr("Save current file"),
644 tr("The document is modified, save before opening another?"),
645 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
646 if (anAnswer == QMessageBox::Save) {
648 } else if (anAnswer == QMessageBox::Cancel) {
654 //show file dialog, check if readable and open
655 myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
656 if (myCurrentDir.isEmpty())
658 QFileInfo aFileInfo(myCurrentDir);
659 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
660 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
664 QApplication::setOverrideCursor(Qt::WaitCursor);
665 aSession->closeAll();
666 aSession->load(myCurrentDir.toLatin1().constData());
667 myObjectBrowser->rebuildDataTree();
668 updateCommandStatus();
669 QApplication::restoreOverrideCursor();
672 //******************************************************
673 void XGUI_Workshop::onNew()
675 QApplication::setOverrideCursor(Qt::WaitCursor);
676 if (objectBrowser() == 0) {
678 mySelector->connectViewers();
680 myViewerProxy->connectToViewer();
683 myMainWindow->showPythonConsole();
684 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
685 aWnd->showMaximized();
686 updateCommandStatus();
688 myContextMenuMgr->connectViewer();
689 QApplication::restoreOverrideCursor();
693 //******************************************************
694 void XGUI_Workshop::onExit()
696 SessionPtr aMgr = ModelAPI_Session::get();
697 if (aMgr->isModified()) {
698 int anAnswer = QMessageBox::question(
699 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
700 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
701 if (anAnswer == QMessageBox::Save) {
702 bool saved = onSave();
706 } else if (anAnswer == QMessageBox::Cancel) {
713 //******************************************************
714 void XGUI_Workshop::onPreferences()
716 ModuleBase_Prefs aModif;
717 ModuleBase_Preferences::editPreferences(aModif);
718 if (aModif.size() > 0) {
720 foreach (ModuleBase_Pref aPref, aModif)
722 aSection = aPref.first;
723 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
724 myMainWindow->viewer()->updateFromResources();
725 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
726 myMainWindow->menuObject()->updateFromResources();
729 displayer()->redisplayObjects();
734 //******************************************************
735 bool XGUI_Workshop::onSave()
737 if(!abortAllOperations())
739 if (myCurrentDir.isEmpty()) {
742 std::list<std::string> aFiles;
743 saveDocument(myCurrentDir, aFiles);
744 updateCommandStatus();
746 myMainWindow->setModifiedState(false);
751 //******************************************************
752 bool XGUI_Workshop::onSaveAs()
754 if(!abortAllOperations())
756 QFileDialog dialog(desktop());
757 dialog.setWindowTitle(tr("Select directory to save files..."));
758 dialog.setFileMode(QFileDialog::Directory);
759 dialog.setFilter(tr("Directories (*)"));
760 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
761 dialog.setViewMode(QFileDialog::Detail);
763 if (!dialog.exec()) {
767 QString aTempDir = dialog.selectedFiles().first();
769 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
770 int answer = QMessageBox::question(
772 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
774 tr("The directory already contains some files, save anyway?"),
775 QMessageBox::Save | QMessageBox::Cancel);
776 if (answer == QMessageBox::Cancel) {
780 myCurrentDir = aTempDir;
782 myMainWindow->setCurrentDir(myCurrentDir, false);
783 myMainWindow->setModifiedState(false);
788 //******************************************************
789 void XGUI_Workshop::onUndo(int theTimes)
791 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
792 SessionPtr aMgr = ModelAPI_Session::get();
793 std::list<std::string> aUndoList = aMgr->undoList();
794 if (aMgr->isOperation()) {
795 /// this is important for nested operations
796 /// when sketch operation is active, this condition is false and
797 /// the sketch operation is not aborted
798 operationMgr()->onAbortOperation();
800 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
801 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
803 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
804 myObjectBrowser->rebuildDataTree();
807 operationMgr()->updateApplyOfOperations();
808 updateCommandStatus();
811 //******************************************************
812 void XGUI_Workshop::onRedo(int theTimes)
814 // the viewer update should be blocked in order to avoid the features blinking. For the created
815 // feature a results are created, the flush of the created signal caused the viewer redisplay for
816 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
817 // redo of all possible objects happens
818 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
820 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
821 SessionPtr aMgr = ModelAPI_Session::get();
822 std::list<std::string> aRedoList = aMgr->redoList();
823 if (aMgr->isOperation()) {
824 /// this is important for nested operations
825 /// when sketch operation is active, this condition is false and
826 /// the sketch operation is not aborted
827 operationMgr()->onAbortOperation();
829 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
830 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
832 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
833 myObjectBrowser->rebuildDataTree();
835 operationMgr()->updateApplyOfOperations();
836 updateCommandStatus();
838 // unblock the viewer update functionality and make update on purpose
839 myDisplayer->enableUpdateViewer(isUpdateEnabled);
840 myDisplayer->updateViewer();
843 //******************************************************
844 //void XGUI_Workshop::onRebuild()
846 // SessionPtr aMgr = ModelAPI_Session::get();
847 // bool aWasOperation = aMgr->isOperation(); // keep this value
848 // if (!aWasOperation) {
849 // aMgr->startOperation("Rebuild");
851 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
852 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
853 // new Events_Message(aRebuildEvent, this)));
854 // if (!aWasOperation) {
855 // aMgr->finishOperation();
857 // updateCommandStatus();
860 //******************************************************
861 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
863 ModuleBase_ModelWidget* anActiveWidget = 0;
864 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
866 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
868 anActiveWidget = aPanel->activeWidget();
871 operationMgr()->onValidateOperation();
873 myModule->widgetStateChanged(thePreviousState);
876 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
878 QString libName = QString::fromStdString(library(theModule.toStdString()));
879 if (libName.isEmpty()) {
880 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
885 CREATE_FUNC crtInst = 0;
888 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
892 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
893 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
894 QString aMsg((char*) &lpMsgBuf);
895 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
896 ::LocalFree(lpMsgBuf);
898 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
902 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
903 | FORMAT_MESSAGE_IGNORE_INSERTS,
904 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
905 QString aMsg((char*) &lpMsgBuf);
906 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
907 ::LocalFree(lpMsgBuf);
911 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
913 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
915 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
917 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
922 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
924 if (!err.isEmpty()) {
926 Events_Error::send(err.toStdString());
928 qWarning(qPrintable(err));
934 //******************************************************
935 bool XGUI_Workshop::createModule()
937 Config_ModuleReader aModuleReader;
938 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
939 myModule = loadModule(moduleName);
943 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
944 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
945 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
946 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
948 myModule->createFeatures();
949 //myActionsMgr->update();
953 //******************************************************
954 void XGUI_Workshop::updateCommandStatus()
956 QList<QAction*> aCommands;
958 aCommands = salomeConnector()->commandList();
960 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
961 foreach (AppElements_Command* aCmd, aMenuBar->features())
962 aCommands.append(aCmd);
964 SessionPtr aMgr = ModelAPI_Session::get();
965 if (aMgr->hasModuleDocument()) {
966 foreach(QAction* aCmd, aCommands) {
967 QString aId = aCmd->data().toString();
968 if (aId == "UNDO_CMD")
969 aCmd->setEnabled(myModule->canUndo());
970 else if (aId == "REDO_CMD")
971 aCmd->setEnabled(myModule->canRedo());
973 // Enable all commands
974 aCmd->setEnabled(true);
978 foreach(QAction* aCmd, aCommands) {
979 QString aId = aCmd->data().toString();
980 if (aId == "NEW_CMD")
981 aCmd->setEnabled(true);
982 else if (aId == "EXIT_CMD")
983 aCmd->setEnabled(true);
985 aCmd->setEnabled(false);
988 myActionsMgr->updateCommandsStatus();
989 emit commandStatusUpdated();
992 void XGUI_Workshop::updateHistory()
994 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
995 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
996 emit updateUndoHistory(aUndoRes);
998 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
999 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1000 emit updateRedoHistory(aRedoRes);
1003 //******************************************************
1004 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1006 QDockWidget* aObjDock = new QDockWidget(theParent);
1007 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1008 aObjDock->setWindowTitle(tr("Object browser"));
1009 aObjDock->setStyleSheet(
1010 "::title { position: relative; padding-left: 5px; text-align: left center }");
1011 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1012 myModule->customizeObjectBrowser(myObjectBrowser);
1013 aObjDock->setWidget(myObjectBrowser);
1015 myContextMenuMgr->connectObjectBrowser();
1019 //******************************************************
1021 * Creates dock widgets, places them in corresponding area
1022 * and tabifies if necessary.
1024 void XGUI_Workshop::createDockWidgets()
1026 QMainWindow* aDesktop = desktop();
1027 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1028 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1029 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1030 myPropertyPanel->setupActions(myActionsMgr);
1031 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1032 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1033 hidePropertyPanel(); ///<! Invisible by default
1034 hideObjectBrowser();
1035 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1036 myPropertyPanel->installEventFilter(myOperationMgr);
1038 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1039 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1041 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1042 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1043 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1044 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1046 connect(myPropertyPanel, SIGNAL(enterClicked()),
1047 myOperationMgr, SLOT(onProcessEnter()));
1050 //******************************************************
1051 void XGUI_Workshop::showPropertyPanel()
1053 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1054 ///<! Restore ability to close panel from the window's menu
1055 aViewAct->setEnabled(true);
1056 myPropertyPanel->show();
1057 myPropertyPanel->raise();
1059 // The next code is necessary to made the property panel the active window
1060 // in order to operation manager could process key events of the panel.
1061 // otherwise they are ignored. It happens only if the same(activateWindow) is
1062 // not happened by property panel activation(e.g. resume operation of Sketch)
1063 ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1064 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1067 //******************************************************
1068 void XGUI_Workshop::hidePropertyPanel()
1070 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1071 ///<! Do not allow to show empty property panel
1072 aViewAct->setEnabled(false);
1073 myPropertyPanel->hide();
1075 // the property panel is active window of the desktop, when it is
1076 // hidden, it is undefined which window becomes active. By this reason
1077 // it is defined to perform the desktop as the active window.
1078 // in SALOME mode, workstack made the PyConsole the active window,
1079 // set the focus on it. As a result, shortcuts of the application, like
1080 // are processed by this console. For example Undo actions.
1081 // It is possible that this code is to be moved to NewGeom package
1082 QMainWindow* aDesktop = desktop();
1083 ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1084 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1087 //******************************************************
1088 void XGUI_Workshop::showObjectBrowser()
1090 myObjectBrowser->parentWidget()->show();
1093 //******************************************************
1094 void XGUI_Workshop::hideObjectBrowser()
1096 myObjectBrowser->parentWidget()->hide();
1099 //******************************************************
1100 void XGUI_Workshop::salomeViewerSelectionChanged()
1102 emit salomeViewerSelection();
1105 //**************************************************************
1106 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1108 return mySalomeConnector->viewer();
1111 //**************************************************************
1112 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1114 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1115 if (theId == "DELETE_CMD")
1117 else if (theId == "MOVE_CMD")
1119 else if (theId == "COLOR_CMD")
1120 changeColor(aObjects);
1121 else if (theId == "SHOW_CMD")
1122 showObjects(aObjects, true);
1123 else if (theId == "HIDE_CMD")
1124 showObjects(aObjects, false);
1125 else if (theId == "SHOW_ONLY_CMD")
1126 showOnlyObjects(aObjects);
1127 else if (theId == "SHADING_CMD")
1128 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1129 else if (theId == "WIREFRAME_CMD")
1130 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1131 else if (theId == "HIDEALL_CMD") {
1132 QObjectPtrList aList = myDisplayer->displayedObjects();
1133 foreach (ObjectPtr aObj, aList) {
1134 if (module()->canEraseObject(aObj))
1135 aObj->setDisplayed(false);
1137 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1141 //**************************************************************
1142 void XGUI_Workshop::deleteObjects()
1144 ModuleBase_IModule* aModule = module();
1145 // 1. allow the module to delete objects, do nothing if it has succeed
1146 if (aModule->deleteObjects()) {
1147 updateCommandStatus();
1151 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1152 if (!abortAllOperations())
1154 // It is necessary to clear selection in order to avoid selection changed event during
1155 // deletion and negative consequences connected with processing of already deleted items
1156 mySelector->clearSelection();
1157 // check whether the object can be deleted. There should not be parts which are not loaded
1158 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1161 bool hasResult = false;
1162 bool hasFeature = false;
1163 bool hasParameter = false;
1164 bool hasSubFeature = false;
1165 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1166 if (!(hasFeature || hasParameter))
1169 // 1. start operation
1170 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1171 aDescription += tr(" %1");
1172 QStringList aObjectNames;
1173 foreach (ObjectPtr aObj, anObjects) {
1174 if (!aObj->data()->isValid())
1176 aObjectNames << QString::fromStdString(aObj->data()->name());
1178 aDescription = aDescription.arg(aObjectNames.join(", "));
1179 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1181 operationMgr()->startOperation(anOpAction);
1182 // 3. delete objects
1183 std::set<FeaturePtr> anIgnoredFeatures;
1184 if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1185 operationMgr()->commitOperation();
1188 operationMgr()->abortOperation(operationMgr()->currentOperation());
1192 //**************************************************************
1193 void XGUI_Workshop::moveObjects()
1195 if (!abortAllOperations())
1198 SessionPtr aMgr = ModelAPI_Session::get();
1200 QString anActionId = "MOVE_CMD";
1201 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1202 aMgr->startOperation(aDescription.toStdString());
1204 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1205 // It is necessary to clear selection in order to avoid selection changed event during
1206 // moving and negative consequences connected with processing of already moved items
1207 mySelector->clearSelection();
1208 // check whether the object can be moved. There should not be parts which are not loaded
1209 if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1212 DocumentPtr anActiveDocument = aMgr->activeDocument();
1213 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1214 foreach (ObjectPtr aObject, anObjects) {
1215 if (!myModule->canApplyAction(aObject, anActionId))
1218 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1219 if (aFeature.get()) {
1220 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1221 aCurrentFeature = anActiveDocument->currentFeature(true);
1224 aMgr->finishOperation();
1227 //**************************************************************
1228 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1229 const std::set<FeaturePtr>& theIgnoredFeatures,
1231 const bool theAskAboutDeleteReferences)
1235 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1236 for (; aDIt != aDLast; ++aDIt) {
1237 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1239 QString anInfoStr = aDInfo.join(", ");
1240 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1243 // 1. find all referenced features
1244 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1245 foreach (ObjectPtr aDeletedObj, theList) {
1246 std::set<FeaturePtr> alreadyProcessed;
1247 XGUI_Tools::refsToFeatureInAllDocuments(
1248 aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1249 std::set<FeaturePtr> aDifference;
1250 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1251 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1252 std::inserter(aDifference, aDifference.begin()));
1253 aIndirectRefFeatures = aDifference;
1256 bool doDeleteReferences = true;
1258 // 2. warn about the references remove, break the delete operation if the user chose it
1259 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1260 QStringList aDirectRefNames;
1261 foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1262 aDirectRefNames.append(aFeature->name().c_str());
1263 QString aDirectNames = aDirectRefNames.join(", ");
1265 QStringList aIndirectRefNames;
1266 foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1267 aIndirectRefNames.append(aFeature->name().c_str());
1268 QString aIndirectNames = aIndirectRefNames.join(", ");
1270 bool canReplaceParameters = true;
1271 foreach (ObjectPtr aObj, theList) {
1272 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1273 if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1274 canReplaceParameters = false;
1279 QMessageBox aMessageBox(theParent);
1280 aMessageBox.setWindowTitle(tr("Delete features"));
1281 aMessageBox.setIcon(QMessageBox::Warning);
1282 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1283 aMessageBox.setDefaultButton(QMessageBox::No);
1286 if (canReplaceParameters) {
1287 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?"))
1288 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1289 QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1291 aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1292 .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1294 aMessageBox.setText(aText);
1296 QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1298 if (aButtonRole == QMessageBox::NoRole)
1301 if (aButtonRole == QMessageBox::ActionRole) {
1302 foreach (ObjectPtr aObj, theList)
1303 ModelAPI_ReplaceParameterMessage::send(aObj, this);
1304 doDeleteReferences = false;
1308 // 3. remove referenced features
1309 if (doDeleteReferences) {
1310 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1311 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1312 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1313 aLast = aFeaturesToDelete.end();
1317 for (; anIt != aLast; anIt++) {
1318 FeaturePtr aFeature = (*anIt);
1319 DocumentPtr aDoc = aFeature->document();
1320 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1321 aDoc->removeFeature(aFeature);
1323 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1328 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1333 QString anActionId = "DELETE_CMD";
1334 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1335 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1336 // 4. remove the parameter features
1337 foreach (ObjectPtr aObj, theList) {
1338 // features and parameters can be removed here,
1339 // the results are removed only by a corresponded feature remove
1340 std::string aGroupName = aObj->groupName();
1341 if (!anObjectGroups.contains(aGroupName.c_str()))
1344 if (!myModule->canApplyAction(aObj, anActionId))
1347 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1349 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1350 // part features are removed in the PartSet module. This condition should be moved there
1351 if (aFeature->getKind() == "Part")
1354 DocumentPtr aDoc = aObj->document();
1355 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1357 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1358 anInfo.append(anInfoStr);
1359 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1361 aDoc->removeFeature(aFeature);
1366 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1371 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1373 bool isFoundResultType = false;
1374 foreach(ObjectPtr anObj, theObjects)
1376 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1377 if (aResult.get() == NULL)
1380 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1381 if (isFoundResultType)
1384 return isFoundResultType;
1387 //**************************************************************
1388 // Returns the list of all features for theDocument and all features of
1389 // all nested parts.
1390 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1392 std::list<FeaturePtr> aResultList;
1393 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1394 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1395 // The order of appending features of the part and the part itself is important
1397 // Append features from a part feature
1398 foreach (const ResultPtr& aResult, aFeature->results()) {
1399 ResultPartPtr aResultPart =
1400 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1401 if (aResultPart.get() && aResultPart->partDoc().get()) {
1403 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1404 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1408 aResultList.push_back(aFeature);
1413 //**************************************************************
1414 // Returns the list of features placed between theObject and the current feature
1415 // in the same document. Excludes theObject, includes the current feature.
1416 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1418 std::list<FeaturePtr> aResult;
1419 DocumentPtr aDocument = theObject->document();
1420 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1421 // find the object iterator
1422 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1423 if (aObjectIt == anAllFeatures.end())
1425 // find the current feature iterator
1426 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1427 if (aCurrentIt == anAllFeatures.end())
1429 // check the right order
1430 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1432 // exclude the object
1433 std::advance(aObjectIt, 1);
1434 // include the current feature
1435 std::advance(aCurrentIt, 1);
1436 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1439 bool XGUI_Workshop::canMoveFeature()
1441 QString anActionId = "MOVE_CMD";
1443 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1444 QObjectPtrList aValidatedObjects;
1445 foreach (ObjectPtr aObject, aObjects) {
1446 if (!myModule->canApplyAction(aObject, anActionId))
1448 // To be moved feature should be in active document
1449 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1451 aValidatedObjects.append(aObject);
1453 if (aValidatedObjects.size() != aObjects.size())
1454 aObjects = aValidatedObjects;
1456 bool aCanMove = !aObjects.empty();
1458 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1459 for (; anIt != aLast && aCanMove; anIt++) {
1460 ObjectPtr aObject = *anIt;
1461 // 1. Get features placed between selected and current in the document
1462 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1463 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1464 if (aFeaturesBetween.empty())
1467 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1468 // 2. Get all reference features to the selected object in the document
1469 std::set<FeaturePtr> aRefFeatures;
1470 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1472 if (aRefFeatures.empty())
1475 // 3. Find any placed features in all reference features
1476 std::set<FeaturePtr> aIntersectionFeatures;
1477 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1478 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1479 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1480 // 4. Return false if any reference feature is placed before current feature
1481 if (!aIntersectionFeatures.empty())
1489 //**************************************************************
1490 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1492 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1493 if (!aCanBeShaded) {
1494 ResultCompSolidPtr aCompsolidResult =
1495 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1496 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1497 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1498 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1501 return aCanBeShaded;
1504 //**************************************************************
1505 bool XGUI_Workshop::canChangeColor() const
1507 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1509 std::set<std::string> aTypes;
1510 aTypes.insert(ModelAPI_ResultGroup::group());
1511 aTypes.insert(ModelAPI_ResultConstruction::group());
1512 aTypes.insert(ModelAPI_ResultBody::group());
1513 aTypes.insert(ModelAPI_ResultPart::group());
1515 return hasResults(aObjects, aTypes);
1518 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1520 if (!theResult.get())
1523 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1524 if (aColorAttr.get() != NULL) {
1525 if (!aColorAttr->size()) {
1526 aColorAttr->setSize(3);
1528 aColorAttr->setValue(0, theColor[0]);
1529 aColorAttr->setValue(1, theColor[1]);
1530 aColorAttr->setValue(2, theColor[2]);
1534 //**************************************************************
1535 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1538 AttributeIntArrayPtr aColorAttr;
1539 // 1. find the current color of the object. This is a color of AIS presentation
1540 // The objects are iterated until a first valid color is found
1541 std::vector<int> aColor;
1542 foreach(ObjectPtr anObject, theObjects) {
1543 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1544 if (aResult.get()) {
1545 XGUI_CustomPrs::getResultColor(aResult, aColor);
1548 // TODO: remove the obtaining a color from the AIS object
1549 // this does not happen never because:
1550 // 1. The color can be changed only on results
1551 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1552 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1553 if (anAISObj.get()) {
1555 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1558 if (!aColor.empty())
1561 if (aColor.size() != 3)
1564 if (!abortAllOperations())
1566 // 2. show the dialog to change the value
1567 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1568 aDlg->setColor(aColor);
1569 aDlg->move(QCursor::pos());
1570 bool isDone = aDlg->exec() == QDialog::Accepted;
1574 bool isRandomColor = aDlg->isRandomColor();
1576 // 3. abort the previous operation and start a new one
1577 SessionPtr aMgr = ModelAPI_Session::get();
1578 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1579 aMgr->startOperation(aDescription.toStdString());
1581 // 4. set the value to all results
1582 std::vector<int> aColorResult = aDlg->getColor();
1583 foreach(ObjectPtr anObj, theObjects) {
1584 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1585 if (aResult.get() != NULL) {
1586 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1587 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1588 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1589 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1592 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1595 aMgr->finishOperation();
1596 updateCommandStatus();
1599 //**************************************************************
1600 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1601 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1602 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1604 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1606 foreach (ObjectPtr aObj, theList) {
1608 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1610 DocumentPtr aDoc = aPartRes->partDoc();
1611 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1612 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1613 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1616 aObj->setDisplayed(isVisible);
1619 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1622 //**************************************************************
1623 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1625 // Hide all displayed objects
1626 QObjectPtrList aList = myDisplayer->displayedObjects();
1627 foreach (ObjectPtr aObj, aList) {
1628 if (module()->canEraseObject(aObj))
1629 aObj->setDisplayed(false);
1632 // Show only objects from the list
1633 foreach (ObjectPtr aObj, theList) {
1635 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1637 DocumentPtr aDoc = aPartRes->partDoc();
1638 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1639 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1640 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1643 aObj->setDisplayed(true);
1646 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1651 //**************************************************************
1652 void XGUI_Workshop::registerValidators() const
1654 SessionPtr aMgr = ModelAPI_Session::get();
1655 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1658 //**************************************************************
1659 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1663 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1664 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1667 //**************************************************************
1668 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1670 for (int i = 0; i < theDoc->size(theGroup); i++)
1671 theDoc->object(theGroup, i)->setDisplayed(true);
1672 //displayObject(theDoc->object(theGroup, i));
1673 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1676 //**************************************************************
1677 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1679 foreach(ObjectPtr aObj, theList) {
1680 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1682 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1683 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1684 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1685 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1686 (XGUI_Displayer::DisplayMode)theMode, false);
1690 if (theList.size() > 0)
1691 myDisplayer->updateViewer();
1694 //**************************************************************
1695 void XGUI_Workshop::closeDocument()
1697 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1698 while (anOperation) {
1699 anOperation->abort();
1700 anOperation = operationMgr()->currentOperation();
1702 myDisplayer->closeLocalContexts();
1703 myDisplayer->eraseAll();
1704 objectBrowser()->clearContent();
1706 module()->closeDocument();
1708 SessionPtr aMgr = ModelAPI_Session::get();
1712 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1714 XGUI_HistoryMenu* aMenu = NULL;
1715 if (isSalomeMode()) {
1716 QAction* anAction = qobject_cast<QAction*>(theObject);
1719 aMenu = new XGUI_HistoryMenu(anAction);
1721 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1722 aMenu = new XGUI_HistoryMenu(aButton);
1724 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1725 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1728 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1730 QList<ActionInfo> aResult;
1731 std::list<std::string>::const_iterator it = theList.cbegin();
1732 for (; it != theList.cend(); it++) {
1733 QString anId = QString::fromStdString(*it);
1734 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1736 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1739 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1740 if (aContextMenuAct) {
1741 anInfo.initFrom(aContextMenuAct);
1743 anInfo = myActionsMgr->actionInfoById(anId);
1746 anInfo.text = anInfo.text.prepend("Modify ");
1753 void XGUI_Workshop::synchronizeViewer()
1755 SessionPtr aMgr = ModelAPI_Session::get();
1756 DocumentPtr aDoc = aMgr->activeDocument();
1758 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1759 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1760 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1761 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1764 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
1765 const std::string& theGroup,
1766 bool theUpdateViewer)
1769 int aSize = theDoc->size(theGroup);
1770 for (int i = 0; i < aSize; i++) {
1771 aObj = theDoc->object(theGroup, i);
1772 if (aObj->isDisplayed())
1773 myDisplayer->display(aObj, false);
1775 if (theUpdateViewer)
1776 myDisplayer->updateViewer();