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>
26 #include <AppElements_Button.h>
27 #include <AppElements_Command.h>
28 #include <AppElements_MainMenu.h>
29 #include <AppElements_MainWindow.h>
30 #include <AppElements_MenuGroupPanel.h>
31 #include <AppElements_Viewer.h>
32 #include <AppElements_Workbench.h>
34 #include <ModelAPI_AttributeDocRef.h>
35 #include <ModelAPI_AttributeIntArray.h>
36 #include <ModelAPI_Data.h>
37 #include <ModelAPI_Events.h>
38 #include <ModelAPI_Feature.h>
39 #include <ModelAPI_Object.h>
40 #include <ModelAPI_ResultBody.h>
41 #include <ModelAPI_ResultConstruction.h>
42 #include <ModelAPI_ResultGroup.h>
43 #include <ModelAPI_ResultParameter.h>
44 #include <ModelAPI_Session.h>
45 #include <ModelAPI_Validator.h>
46 #include <ModelAPI_ResultCompSolid.h>
47 #include <ModelAPI_Tools.h>
49 //#include <PartSetPlugin_Part.h>
51 #include <Events_Loop.h>
52 #include <Events_Error.h>
53 #include <Events_LongOp.h>
55 #include <ModuleBase_FilterFactory.h>
56 #include <ModuleBase_IModule.h>
57 #include <ModuleBase_IViewer.h>
58 #include <ModuleBase_Operation.h>
59 #include <ModuleBase_OperationDescription.h>
60 #include <ModuleBase_PageBase.h>
61 #include <ModuleBase_Preferences.h>
62 #include <ModuleBase_SelectionValidator.h>
63 #include <ModuleBase_Tools.h>
64 #include <ModuleBase_WidgetFactory.h>
65 #include <ModuleBase_OperationFeature.h>
66 #include <ModuleBase_OperationAction.h>
68 #include <Config_Common.h>
69 #include <Config_FeatureMessage.h>
70 #include <Config_ModuleReader.h>
71 #include <Config_PointerMessage.h>
72 #include <Config_PropManager.h>
73 #include <Config_SelectionFilterMessage.h>
75 #include <SUIT_ResourceMgr.h>
77 #include <QApplication>
78 #include <QFileDialog>
79 #include <QMessageBox>
80 #include <QMdiSubWindow>
81 #include <QPushButton>
82 #include <QDockWidget>
87 #include <QToolButton>
89 #include <QDesktopWidget>
104 //#define DEBUG_DELETE
106 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
108 myCurrentDir(QString()),
110 mySalomeConnector(theConnector),
115 myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
118 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
119 bool aCloc = aResMgr->booleanValue("language", "locale", true);
121 QLocale::setDefault( QLocale::c() );
123 QLocale::setDefault( QLocale::system() );
126 myDisplayer = new XGUI_Displayer(this);
128 mySelector = new XGUI_SelectionMgr(this);
129 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
131 myOperationMgr = new XGUI_OperationMgr(this, 0);
132 myActionsMgr = new XGUI_ActionsMgr(this);
133 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
134 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
135 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
136 SLOT(onContextMenuCommand(const QString&, bool)));
138 myViewerProxy = new XGUI_ViewerProxy(this);
139 connect(myViewerProxy, SIGNAL(selectionChanged()),
140 myActionsMgr, SLOT(updateOnViewSelection()));
142 myModuleConnector = new XGUI_ModuleConnector(this);
144 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
145 myOperationMgr->setWorkshop(aWorkshop);
147 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
148 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
150 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
151 SLOT(onOperationStarted(ModuleBase_Operation*)));
152 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
153 SLOT(onOperationResumed(ModuleBase_Operation*)));
154 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
155 SLOT(onOperationStopped(ModuleBase_Operation*)));
156 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
157 SLOT(onOperationCommitted(ModuleBase_Operation*)));
158 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
159 SLOT(onOperationAborted(ModuleBase_Operation*)));
160 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
161 // myErrorMgr, SLOT(onValidationStateChanged()));
164 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
165 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
166 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
167 myErrorDlg, SLOT(addError(const QString&)));
169 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
170 // Config_Prop::Color, "225,225,225");
172 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
173 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
174 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
175 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
176 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
177 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
178 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
179 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
182 //******************************************************
183 XGUI_Workshop::~XGUI_Workshop(void)
188 //******************************************************
189 void XGUI_Workshop::startApplication()
193 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
194 Config_Prop::Directory, "");
196 //Initialize event listening
197 myEventsListener->initializeEventListening();
199 registerValidators();
201 // Calling of loadCustomProps before activating module is required
202 // by Config_PropManger to restore user-defined path to plugins
203 ModuleBase_Preferences::loadCustomProps();
206 myMainWindow->show();
207 updateCommandStatus();
212 emit applicationStarted();
215 void XGUI_Workshop::activateModule()
217 myModule->activateSelectionFilters();
219 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
220 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
221 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
222 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
224 myActionsMgr->update();
226 // activate visualized objects in the viewer
227 XGUI_Displayer* aDisplayer = displayer();
228 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
230 module()->activeSelectionModes(aModes);
231 aDisplayer->activateObjects(aModes, aDisplayed);
234 void XGUI_Workshop::deactivateModule()
236 myModule->deactivateSelectionFilters();
238 // remove internal displayer filter
239 displayer()->deactivateSelectionFilters();
241 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
242 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
243 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
244 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
246 XGUI_Displayer* aDisplayer = displayer();
247 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
248 aDisplayer->deactivateObjects(aDisplayed, true);
251 //******************************************************
252 void XGUI_Workshop::initMenu()
254 myContextMenuMgr->createActions();
256 if (isSalomeMode()) {
257 // Create only Undo, Redo commands
258 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
259 tr("Undo last command"),
260 QIcon(":pictures/undo.png"),
261 QKeySequence::Undo, false, "MEN_DESK_EDIT");
262 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
263 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
265 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
266 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
268 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
269 QIcon(":pictures/redo.png"), QKeySequence::Redo,
270 false, "MEN_DESK_EDIT");
271 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
273 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
274 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
276 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
277 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
278 QIcon(":pictures/rebuild.png"), QKeySequence(),
279 false, "MEN_DESK_EDIT");
280 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
282 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
283 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
285 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
286 QIcon(), QKeySequence(),
287 false, "MEN_DESK_FILE");
288 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
290 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
291 QIcon(), QKeySequence(),
292 false, "MEN_DESK_FILE");
293 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
294 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
298 // File commands group
299 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
301 AppElements_Command* aCommand;
303 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
304 QIcon(":pictures/save.png"), QKeySequence::Save);
305 aCommand->connectTo(this, SLOT(onSave()));
306 //aCommand->disable();
308 QString aUndoId = "UNDO_CMD";
309 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
310 QIcon(":pictures/undo.png"), QKeySequence::Undo);
311 aCommand->connectTo(this, SLOT(onUndo()));
312 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
313 addHistoryMenu(aUndoButton,
314 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
317 QString aRedoId = "REDO_CMD";
318 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
319 QIcon(":pictures/redo.png"), QKeySequence::Redo);
320 aCommand->connectTo(this, SLOT(onRedo()));
321 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
322 addHistoryMenu(aRedoButton,
323 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
326 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
327 QIcon(":pictures/rebuild.png"), QKeySequence());
328 aCommand->connectTo(this, SLOT(onRebuild()));
330 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
331 QIcon(":pictures/save.png"), QKeySequence());
332 aCommand->connectTo(this, SLOT(onSaveAs()));
333 //aCommand->disable();
335 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
336 QIcon(":pictures/open.png"), QKeySequence::Open);
337 aCommand->connectTo(this, SLOT(onOpen()));
339 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
340 // QIcon(":pictures/new.png"), QKeySequence::New);
341 //aCommand->connectTo(this, SLOT(onNew()));
343 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
344 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
345 aCommand->connectTo(this, SLOT(onPreferences()));
347 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
348 QIcon(":pictures/close.png"), QKeySequence::Close);
349 aCommand->connectTo(this, SLOT(onExit()));
350 //FIXME: SBH's test action. Can be used for some GUI tests.
352 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
353 // QIcon(":pictures/close.png"), QKeySequence(), true);
354 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
358 //******************************************************
359 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
361 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
362 return aMenuBar->addWorkbench(theName);
365 //******************************************************
366 QMainWindow* XGUI_Workshop::desktop() const
368 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
371 //******************************************************
372 void XGUI_Workshop::onStartWaiting()
374 if (Events_LongOp::isPerformed()) {
375 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
379 //******************************************************
380 void XGUI_Workshop::onAcceptActionClicked()
382 QAction* anAction = dynamic_cast<QAction*>(sender());
383 XGUI_OperationMgr* anOperationMgr = operationMgr();
384 if (anOperationMgr) {
385 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
386 (anOperationMgr->currentOperation());
388 if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
389 myOperationMgr->onCommitOperation();
394 //******************************************************
395 /*void XGUI_Workshop::onValidationStateChanged(bool theEnabled)
397 XGUI_OperationMgr* anOperationMgr = operationMgr();
398 if (anOperationMgr) {
399 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
400 (anOperationMgr->currentOperation());
402 QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
403 myErrorMgr->updateActionState(anAction, aFOperation->feature(), theEnabled);
409 //******************************************************
410 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
412 if (!myModule->canActivateSelection(theObject)) {
413 if (myDisplayer->isActive(theObject)) {
414 QObjectPtrList anObjects;
415 anObjects.append(theObject);
416 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
421 //******************************************************
422 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
424 bool aHasNested = false;
425 std::string aFeatureKind = theFeature->getKind();
426 if (isSalomeMode()) {
427 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
428 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
431 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
432 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
433 if (aCommand && aCommand->button()->additionalButtonWidget())
439 //******************************************************
440 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
442 setGrantedFeatures(theOperation);
444 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
449 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
450 setPropertyPanel(aFOperation);
451 // filling the operation values by the current selection
452 // if the operation can be committed after the controls filling, the method perform should
453 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
454 if (!aFOperation->isEditOperation()) {
455 aFOperation->activateByPreselection();
456 if (operationMgr()->currentOperation() != aFOperation)
460 updateCommandStatus();
462 myModule->onOperationStarted(aFOperation);
464 // the objects of the current operation should be deactivated
465 QObjectPtrList anObjects;
466 FeaturePtr aFeature = aFOperation->feature();
467 anObjects.append(aFeature);
468 std::list<ResultPtr> aResults = aFeature->results();
469 std::list<ResultPtr>::const_iterator aIt;
470 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
471 anObjects.append(*aIt);
473 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
474 for (; anIt != aLast; anIt++)
475 deactivateActiveObject(*anIt, false);
476 if (anObjects.size() > 0)
477 myDisplayer->updateViewer();
480 //******************************************************
481 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
483 setGrantedFeatures(theOperation);
485 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
486 setPropertyPanel(theOperation);
488 updateCommandStatus();
490 myModule->onOperationResumed(theOperation);
494 //******************************************************
495 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
497 updateCommandStatus();
499 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
504 ModuleBase_ISelection* aSel = mySelector->selection();
505 QObjectPtrList aObj = aSel->selectedPresentations();
506 //!< No need for property panel
508 myPropertyPanel->cleanContent();
510 myModule->onOperationStopped(aFOperation);
512 // the deactivated objects of the current operation should be activated back.
513 // They were deactivated on operation start or an object redisplay
514 QObjectPtrList anObjects;
515 FeaturePtr aFeature = aFOperation->feature();
516 if (aFeature.get()) { // feature may be not created (plugin load fail)
517 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
518 anObjects.append(aFeature);
519 std::list<ResultPtr> aResults = aFeature->results();
520 std::list<ResultPtr>::const_iterator aIt;
521 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
522 ResultPtr anObject = *aIt;
523 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
524 anObjects.append(anObject);
529 module()->activeSelectionModes(aModes);
530 myDisplayer->activateObjects(aModes, anObjects);
534 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
536 myModule->onOperationCommitted(theOperation);
539 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
541 myModule->onOperationAborted(theOperation);
544 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
546 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
550 QStringList aGrantedIds;
552 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
554 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
556 aFOperation->setGrantedOperationIds(aGrantedIds);
559 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
561 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
566 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
567 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
570 myPropertyPanel->cleanContent();
571 aFactory.createWidget(myPropertyPanel->contentWidget());
573 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
574 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
575 bool isStoreValue = !aFOperation->isEditOperation() &&
576 !aWidget->getDefaultValue().empty() &&
577 !aWidget->isComputedDefault();
578 aWidget->setFeature(aFOperation->feature(), isStoreValue);
579 aWidget->enableFocusProcessing();
582 myPropertyPanel->setModelWidgets(aWidgets);
583 aFOperation->setPropertyPanel(myPropertyPanel);
585 myModule->propertyPanelDefined(theOperation);
587 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
589 myErrorMgr->setPropertyPanel(myPropertyPanel);
593 * Saves document with given name.
595 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
597 QApplication::restoreOverrideCursor();
598 SessionPtr aMgr = ModelAPI_Session::get();
599 aMgr->save(theName.toLatin1().constData(), theFileNames);
600 QApplication::restoreOverrideCursor();
603 bool XGUI_Workshop::abortAllOperations()
605 return myOperationMgr->abortAllOperations();
608 //******************************************************
609 void XGUI_Workshop::onExit()
611 SessionPtr aMgr = ModelAPI_Session::get();
612 if (aMgr->isModified()) {
613 int anAnswer = QMessageBox::question(
614 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
615 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
616 if (anAnswer == QMessageBox::Save) {
617 bool saved = onSave();
621 } else if (anAnswer == QMessageBox::Cancel) {
628 //******************************************************
629 void XGUI_Workshop::onNew()
631 QApplication::setOverrideCursor(Qt::WaitCursor);
632 if (objectBrowser() == 0) {
634 mySelector->connectViewers();
636 myViewerProxy->connectToViewer();
638 if (!isSalomeMode()) {
639 myMainWindow->showPythonConsole();
640 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
641 aWnd->showMaximized();
642 updateCommandStatus();
644 myContextMenuMgr->connectViewer();
645 QApplication::restoreOverrideCursor();
648 //******************************************************
649 void XGUI_Workshop::onOpen()
651 if(!abortAllOperations())
653 //save current file before close if modified
654 SessionPtr aSession = ModelAPI_Session::get();
655 if (aSession->isModified()) {
656 //TODO(sbh): re-launch the app?
657 int anAnswer = QMessageBox::question(
658 myMainWindow, tr("Save current file"),
659 tr("The document is modified, save before opening another?"),
660 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
661 if (anAnswer == QMessageBox::Save) {
663 } else if (anAnswer == QMessageBox::Cancel) {
669 //show file dialog, check if readable and open
670 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow(), tr("Select directory"));
671 if (myCurrentDir.isEmpty())
673 QFileInfo aFileInfo(myCurrentDir);
674 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
675 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
679 QApplication::setOverrideCursor(Qt::WaitCursor);
680 aSession->closeAll();
681 aSession->load(myCurrentDir.toLatin1().constData());
682 myObjectBrowser->rebuildDataTree();
683 updateCommandStatus();
684 QApplication::restoreOverrideCursor();
687 //******************************************************
688 bool XGUI_Workshop::onSave()
690 if(!abortAllOperations())
692 if (myCurrentDir.isEmpty()) {
695 std::list<std::string> aFiles;
696 saveDocument(myCurrentDir, aFiles);
697 updateCommandStatus();
699 myMainWindow->setModifiedState(false);
703 //******************************************************
704 bool XGUI_Workshop::onSaveAs()
706 if(!abortAllOperations())
708 QFileDialog dialog(mainWindow());
709 dialog.setWindowTitle(tr("Select directory to save files..."));
710 dialog.setFileMode(QFileDialog::Directory);
711 dialog.setFilter(tr("Directories (*)"));
712 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
713 dialog.setViewMode(QFileDialog::Detail);
715 if (!dialog.exec()) {
719 QString aTempDir = dialog.selectedFiles().first();
721 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
722 int answer = QMessageBox::question(
724 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
726 tr("The directory already contains some files, save anyway?"),
727 QMessageBox::Save | QMessageBox::Cancel);
728 if (answer == QMessageBox::Cancel) {
732 myCurrentDir = aTempDir;
733 if (!isSalomeMode()) {
734 myMainWindow->setCurrentDir(myCurrentDir, false);
735 myMainWindow->setModifiedState(false);
740 //******************************************************
741 void XGUI_Workshop::onUndo(int theTimes)
743 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
744 SessionPtr aMgr = ModelAPI_Session::get();
745 if (aMgr->isOperation()) {
746 /// this is important for nested operrations
747 /// when sketch opeation is active, this condition is false and
748 /// the sketch operation is not aborted
749 operationMgr()->onAbortOperation();
751 for (int i = 0; i < theTimes; ++i) {
755 operationMgr()->updateApplyOfOperations();
756 updateCommandStatus();
759 //******************************************************
760 void XGUI_Workshop::onRedo(int theTimes)
762 // the viewer update should be blocked in order to avoid the features blinking. For the created
763 // feature a results are created, the flush of the created signal caused the viewer redisplay for
764 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
765 // redo of all possible objects happens
766 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
768 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
769 SessionPtr aMgr = ModelAPI_Session::get();
770 if (aMgr->isOperation()) {
771 /// this is important for nested operrations
772 /// when sketch opeation is active, this condition is false and
773 /// the sketch operation is not aborted
774 operationMgr()->onAbortOperation();
776 for (int i = 0; i < theTimes; ++i) {
779 operationMgr()->updateApplyOfOperations();
780 updateCommandStatus();
782 // unblock the viewer update functionality and make update on purpose
783 myDisplayer->enableUpdateViewer(isUpdateEnabled);
784 myDisplayer->updateViewer();
787 //******************************************************
788 void XGUI_Workshop::onRebuild()
790 SessionPtr aMgr = ModelAPI_Session::get();
791 bool aWasOperation = aMgr->isOperation(); // keep this value
792 if (!aWasOperation) {
793 aMgr->startOperation("Rebuild");
795 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
796 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
797 new Events_Message(aRebuildEvent, this)));
798 if (!aWasOperation) {
799 aMgr->finishOperation();
801 updateCommandStatus();
804 //******************************************************
805 void XGUI_Workshop::onPreferences()
807 ModuleBase_Prefs aModif;
808 ModuleBase_Preferences::editPreferences(aModif);
809 if (aModif.size() > 0) {
811 foreach (ModuleBase_Pref aPref, aModif)
813 aSection = aPref.first;
814 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
816 myMainWindow->viewer()->updateFromResources();
817 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
819 myMainWindow->menuObject()->updateFromResources();
822 displayer()->redisplayObjects();
826 //******************************************************
827 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
829 QString libName = QString::fromStdString(library(theModule.toStdString()));
830 if (libName.isEmpty()) {
831 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
836 CREATE_FUNC crtInst = 0;
839 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
843 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
844 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
845 QString aMsg((char*) &lpMsgBuf);
846 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
847 ::LocalFree(lpMsgBuf);
849 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
853 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
854 | FORMAT_MESSAGE_IGNORE_INSERTS,
855 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
856 QString aMsg((char*) &lpMsgBuf);
857 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
858 ::LocalFree(lpMsgBuf);
862 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
864 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
866 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
868 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
873 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
875 if (!err.isEmpty()) {
877 Events_Error::send(err.toStdString());
879 qWarning(qPrintable(err));
885 //******************************************************
886 bool XGUI_Workshop::createModule()
888 Config_ModuleReader aModuleReader;
889 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
890 myModule = loadModule(moduleName);
894 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
895 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
896 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
897 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
899 myModule->createFeatures();
900 //myActionsMgr->update();
904 //******************************************************
905 void XGUI_Workshop::updateCommandStatus()
907 QList<QAction*> aCommands;
908 if (isSalomeMode()) { // update commands in SALOME mode
909 aCommands = salomeConnector()->commandList();
911 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
912 foreach (AppElements_Command* aCmd, aMenuBar->features())
913 aCommands.append(aCmd);
915 SessionPtr aMgr = ModelAPI_Session::get();
916 if (aMgr->hasModuleDocument()) {
917 foreach(QAction* aCmd, aCommands) {
918 QString aId = aCmd->data().toString();
919 if (aId == "UNDO_CMD")
920 aCmd->setEnabled(myModule->canUndo());
921 else if (aId == "REDO_CMD")
922 aCmd->setEnabled(myModule->canRedo());
924 // Enable all commands
925 aCmd->setEnabled(true);
929 foreach(QAction* aCmd, aCommands) {
930 QString aId = aCmd->data().toString();
931 if (aId == "NEW_CMD")
932 aCmd->setEnabled(true);
933 else if (aId == "EXIT_CMD")
934 aCmd->setEnabled(true);
936 aCmd->setEnabled(false);
939 myActionsMgr->update();
940 emit commandStatusUpdated();
943 void XGUI_Workshop::updateHistory()
945 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
946 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
947 emit updateUndoHistory(aUndoRes);
949 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
950 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
951 emit updateRedoHistory(aRedoRes);
954 //******************************************************
955 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
957 QDockWidget* aObjDock = new QDockWidget(theParent);
958 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
959 aObjDock->setWindowTitle(tr("Object browser"));
960 aObjDock->setStyleSheet(
961 "::title { position: relative; padding-left: 5px; text-align: left center }");
962 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
963 #ifdef ModuleDataModel
964 myObjectBrowser->setDataModel(myModule->dataModel());
966 myModule->customizeObjectBrowser(myObjectBrowser);
967 aObjDock->setWidget(myObjectBrowser);
969 myContextMenuMgr->connectObjectBrowser();
973 //******************************************************
975 * Creates dock widgets, places them in corresponding area
976 * and tabifies if necessary.
978 void XGUI_Workshop::createDockWidgets()
980 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
981 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
982 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
983 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
984 myPropertyPanel->setupActions(myActionsMgr);
985 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
986 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
987 hidePropertyPanel(); ///<! Invisible by default
989 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
990 myPropertyPanel->installEventFilter(myOperationMgr);
992 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
993 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
995 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
996 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
997 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
998 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
999 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
1000 //connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
1001 // this, SLOT(onValidationStateChanged(bool)));
1004 //******************************************************
1005 void XGUI_Workshop::showPropertyPanel()
1007 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1008 ///<! Restore ability to close panel from the window's menu
1009 aViewAct->setEnabled(true);
1010 myPropertyPanel->show();
1011 myPropertyPanel->raise();
1013 // The next code is necessary to made the property panel the active window
1014 // in order to operation manager could process key events of the panel.
1015 // otherwise they are ignored. It happens only if the same(activateWindow) is
1016 // not happend by property panel activation(e.g. resume operaion of Sketch)
1017 myPropertyPanel->activateWindow();
1018 myPropertyPanel->setFocus();
1021 //******************************************************
1022 void XGUI_Workshop::hidePropertyPanel()
1024 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1025 ///<! Do not allow to show empty property panel
1026 aViewAct->setEnabled(false);
1027 myPropertyPanel->hide();
1029 // the property panel is active window of the desktop, when it is
1030 // hidden, it is undefined which window becomes active. By this reason
1031 // it is defined to perform the desktop as the active window.
1032 // in SALOME mode, workstack made the PyConsole the active window,
1033 // set the focus on it. As a result, shortcuts of the application, like
1034 // are processed by this console. For example Undo actions.
1035 // It is possible that this code is to be moved to NewGeom package
1036 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1037 aDesktop->activateWindow();
1038 aDesktop->setFocus();
1041 //******************************************************
1042 void XGUI_Workshop::showObjectBrowser()
1044 myObjectBrowser->parentWidget()->show();
1047 //******************************************************
1048 void XGUI_Workshop::hideObjectBrowser()
1050 myObjectBrowser->parentWidget()->hide();
1053 //******************************************************
1054 void XGUI_Workshop::salomeViewerSelectionChanged()
1056 emit salomeViewerSelection();
1059 //**************************************************************
1060 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1062 return mySalomeConnector->viewer();
1065 //**************************************************************
1066 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1068 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1069 if (theId == "DELETE_CMD")
1071 else if (theId == "MOVE_CMD")
1073 else if (theId == "COLOR_CMD")
1074 changeColor(aObjects);
1075 else if (theId == "SHOW_CMD")
1076 showObjects(aObjects, true);
1077 else if (theId == "HIDE_CMD")
1078 showObjects(aObjects, false);
1079 else if (theId == "SHOW_ONLY_CMD")
1080 showOnlyObjects(aObjects);
1081 else if (theId == "SHADING_CMD")
1082 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1083 else if (theId == "WIREFRAME_CMD")
1084 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1085 else if (theId == "HIDEALL_CMD") {
1086 QObjectPtrList aList = myDisplayer->displayedObjects();
1087 foreach (ObjectPtr aObj, aList) {
1088 if (module()->canEraseObject(aObj))
1089 aObj->setDisplayed(false);
1091 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1095 //**************************************************************
1096 void XGUI_Workshop::deleteObjects()
1098 ModuleBase_IModule* aModule = module();
1099 // 1. allow the module to delete objects, do nothing if it has succeed
1100 if (aModule->deleteObjects()) {
1101 updateCommandStatus();
1105 if (!abortAllOperations())
1107 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1108 // It is necessary to clear selection in order to avoid selection changed event during
1109 // deleteion and negative consequences connected with processing of already deleted items
1110 mySelector->clearSelection();
1111 // check whether the object can be deleted. There should not be parts which are not loaded
1112 if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1115 bool hasResult = false;
1116 bool hasFeature = false;
1117 bool hasParameter = false;
1118 bool hasSubFeature = false;
1119 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1120 if (!(hasFeature || hasParameter))
1123 // 1. start operation
1124 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1125 aDescription += tr(" %1");
1126 QStringList aObjectNames;
1127 foreach (ObjectPtr aObj, anObjects) {
1128 if (!aObj->data()->isValid())
1130 aObjectNames << QString::fromStdString(aObj->data()->name());
1132 aDescription = aDescription.arg(aObjectNames.join(", "));
1133 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1135 operationMgr()->startOperation(anOpAction);
1136 // 3. delete objects
1137 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1138 std::set<FeaturePtr> anIgnoredFeatures;
1139 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1140 operationMgr()->commitOperation();
1143 operationMgr()->abortOperation(operationMgr()->currentOperation());
1147 //**************************************************************
1148 void XGUI_Workshop::moveObjects()
1150 if (!abortAllOperations())
1153 SessionPtr aMgr = ModelAPI_Session::get();
1155 QString anActionId = "MOVE_CMD";
1156 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1157 aMgr->startOperation(aDescription.toStdString());
1159 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1160 // It is necessary to clear selection in order to avoid selection changed event during
1161 // moving and negative consequences connected with processing of already moved items
1162 mySelector->clearSelection();
1163 // check whether the object can be moved. There should not be parts which are not loaded
1164 if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1167 DocumentPtr anActiveDocument = aMgr->activeDocument();
1168 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1169 foreach (ObjectPtr aObject, anObjects) {
1170 if (!myModule->canApplyAction(aObject, anActionId))
1173 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1174 if (aFeature.get()) {
1175 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1176 aCurrentFeature = anActiveDocument->currentFeature(true);
1179 aMgr->finishOperation();
1182 //**************************************************************
1183 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1184 const std::set<FeaturePtr>& theIgnoredFeatures,
1186 const bool theAskAboutDeleteReferences)
1190 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1191 for (; aDIt != aDLast; ++aDIt) {
1192 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1194 QString anInfoStr = aDInfo.join(", ");
1195 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1198 // 1. find all referenced features
1199 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1200 foreach (ObjectPtr aDeletedObj, theList) {
1201 XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures);
1202 std::set<FeaturePtr> aDifference;
1203 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1204 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1205 std::inserter(aDifference, aDifference.begin()));
1206 aIndirectRefFeatures = aDifference;
1208 // 2. warn about the references remove, break the delete operation if the user chose it
1209 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1210 QStringList aDirectRefNames;
1211 foreach(const FeaturePtr& aFeature, aDirectRefFeatures)
1212 aDirectRefNames.append(aFeature->name().c_str());
1213 QString aDirectNames = aDirectRefNames.join(", ");
1215 QStringList aIndirectRefNames;
1216 foreach(const FeaturePtr& aFeature, aIndirectRefFeatures)
1217 aIndirectRefNames.append(aFeature->name().c_str());
1218 QString aIndirectNames = aIndirectRefNames.join(", ");
1220 QMessageBox::StandardButton aRes = QMessageBox::warning(
1221 theParent, tr("Delete features"),
1222 QString(tr("Selected features are used in the following features: %1.\
1223 These features will be deleted.\n%2Would you like to continue?")).arg(aDirectNames)
1224 .arg(aIndirectNames.isEmpty() ? QString() : QString("Also these features will be deleted: %1.\n").arg(aIndirectNames)),
1225 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1226 if (aRes != QMessageBox::Yes)
1230 // 3. remove referenced features
1231 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1232 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1233 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1234 aLast = aFeaturesToDelete.end();
1238 for (; anIt != aLast; anIt++) {
1239 FeaturePtr aFeature = (*anIt);
1240 DocumentPtr aDoc = aFeature->document();
1241 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1242 aDoc->removeFeature(aFeature);
1244 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1249 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1253 QString anActionId = "DELETE_CMD";
1254 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1255 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1256 // 4. remove the parameter features
1257 foreach (ObjectPtr aObj, theList) {
1258 // features and parameters can be removed here,
1259 // the results are removed only by a corresponded feature remove
1260 std::string aGroupName = aObj->groupName();
1261 if (!anObjectGroups.contains(aGroupName.c_str()))
1264 if (!myModule->canApplyAction(aObj, anActionId))
1267 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1269 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1270 // part features are removed in the PartSet module. This condition should be moved there
1271 if (aFeature->getKind() == "Part")
1274 DocumentPtr aDoc = aObj->document();
1275 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1277 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1278 anInfo.append(anInfoStr);
1279 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1281 aDoc->removeFeature(aFeature);
1286 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1291 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1293 bool isFoundResultType = false;
1294 foreach(ObjectPtr anObj, theObjects)
1296 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1297 if (aResult.get() == NULL)
1300 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1301 if (isFoundResultType)
1304 return isFoundResultType;
1307 //**************************************************************
1308 // Returns the list of all features for theDocument and all features of
1309 // all nested parts.
1310 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1312 std::list<FeaturePtr> aResultList;
1313 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1314 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1315 // The order of appending features of the part and the part itself is important
1317 // Append features from a part feature
1318 foreach (const ResultPtr& aResult, aFeature->results()) {
1319 ResultPartPtr aResultPart =
1320 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1321 if (aResultPart.get() && aResultPart->partDoc().get()) {
1323 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1324 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1328 aResultList.push_back(aFeature);
1333 //**************************************************************
1334 // Returns the list of features placed between theObject and the current feature
1335 // in the same document. Excludes theObject, includes the current feature.
1336 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1338 std::list<FeaturePtr> aResult;
1339 DocumentPtr aDocument = theObject->document();
1340 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1341 // find the object iterator
1342 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1343 if (aObjectIt == anAllFeatures.end())
1345 // find the current feature iterator
1346 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1347 if (aCurrentIt == anAllFeatures.end())
1349 // check the right order
1350 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1352 // exclude the object
1353 std::advance(aObjectIt, 1);
1354 // include the current feature
1355 std::advance(aCurrentIt, 1);
1356 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1359 bool XGUI_Workshop::canMoveFeature()
1361 QString anActionId = "MOVE_CMD";
1363 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1364 QObjectPtrList aValidatedObjects;
1365 foreach (ObjectPtr aObject, aObjects) {
1366 if (!myModule->canApplyAction(aObject, anActionId))
1368 // To be moved feature should be in active document
1369 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1371 aValidatedObjects.append(aObject);
1373 if (aValidatedObjects.size() != aObjects.size())
1374 aObjects = aValidatedObjects;
1376 bool aCanMove = !aObjects.empty();
1378 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1379 for (; anIt != aLast && aCanMove; anIt++) {
1380 ObjectPtr aObject = *anIt;
1381 // 1. Get features placed between selected and current in the document
1382 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1383 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1384 if (aFeaturesBetween.empty())
1387 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1388 // 2. Get all reference features to the selected object in the document
1389 std::set<FeaturePtr> aRefFeatures;
1390 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1392 if (aRefFeatures.empty())
1395 // 3. Find any placed features in all reference features
1396 std::set<FeaturePtr> aIntersectionFeatures;
1397 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1398 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1399 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1400 // 4. Return false if any reference feature is placed before current feature
1401 if (!aIntersectionFeatures.empty())
1409 //**************************************************************
1410 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1412 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1413 if (!aCanBeShaded) {
1414 ResultCompSolidPtr aCompsolidResult =
1415 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1416 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1417 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1418 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1421 return aCanBeShaded;
1424 //**************************************************************
1425 bool XGUI_Workshop::canChangeColor() const
1427 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1429 std::set<std::string> aTypes;
1430 aTypes.insert(ModelAPI_ResultGroup::group());
1431 aTypes.insert(ModelAPI_ResultConstruction::group());
1432 aTypes.insert(ModelAPI_ResultBody::group());
1433 aTypes.insert(ModelAPI_ResultPart::group());
1435 return hasResults(aObjects, aTypes);
1438 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1440 if (!theResult.get())
1443 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1444 if (aColorAttr.get() != NULL) {
1445 if (!aColorAttr->size()) {
1446 aColorAttr->setSize(3);
1448 aColorAttr->setValue(0, theColor[0]);
1449 aColorAttr->setValue(1, theColor[1]);
1450 aColorAttr->setValue(2, theColor[2]);
1454 //**************************************************************
1455 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1457 AttributeIntArrayPtr aColorAttr;
1458 // 1. find the current color of the object. This is a color of AIS presentation
1459 // The objects are iterated until a first valid color is found
1460 std::vector<int> aColor;
1461 foreach(ObjectPtr anObject, theObjects) {
1462 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1463 if (aResult.get()) {
1464 XGUI_CustomPrs::getResultColor(aResult, aColor);
1467 // TODO: remove the obtaining a color from the AIS object
1468 // this does not happen never because:
1469 // 1. The color can be changed only on results
1470 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1471 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1472 if (anAISObj.get()) {
1474 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1477 if (!aColor.empty())
1480 if (aColor.size() != 3)
1483 // 2. show the dialog to change the value
1484 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1485 aDlg->setColor(aColor);
1486 aDlg->move(QCursor::pos());
1487 bool isDone = aDlg->exec() == QDialog::Accepted;
1491 bool isRandomColor = aDlg->isRandomColor();
1493 // 3. abort the previous operation and start a new one
1494 SessionPtr aMgr = ModelAPI_Session::get();
1495 bool aWasOperation = aMgr->isOperation(); // keep this value
1496 if (!aWasOperation) {
1497 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1498 aMgr->startOperation(aDescription.toStdString());
1501 // 4. set the value to all results
1502 std::vector<int> aColorResult = aDlg->getColor();
1503 foreach(ObjectPtr anObj, theObjects) {
1504 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1505 if (aResult.get() != NULL) {
1506 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1507 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1508 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++)
1509 setColor(aCompsolidResult->subResult(i), aColorResult);
1511 setColor(aResult, aColorResult);
1515 aMgr->finishOperation();
1516 updateCommandStatus();
1519 //**************************************************************
1520 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1521 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1522 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1524 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1526 foreach (ObjectPtr aObj, theList) {
1528 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1530 DocumentPtr aDoc = aPartRes->partDoc();
1531 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1532 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1533 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1536 aObj->setDisplayed(isVisible);
1539 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1542 //**************************************************************
1543 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1545 // Hide all displayed objects
1546 QObjectPtrList aList = myDisplayer->displayedObjects();
1547 foreach (ObjectPtr aObj, aList) {
1548 if (module()->canEraseObject(aObj))
1549 aObj->setDisplayed(false);
1552 // Show only objects from the list
1553 foreach (ObjectPtr aObj, theList) {
1555 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1557 DocumentPtr aDoc = aPartRes->partDoc();
1558 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1559 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1560 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1563 aObj->setDisplayed(true);
1566 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1571 //**************************************************************
1572 void XGUI_Workshop::registerValidators() const
1574 SessionPtr aMgr = ModelAPI_Session::get();
1575 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1578 //**************************************************************
1579 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1583 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1584 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1587 //**************************************************************
1588 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1590 for (int i = 0; i < theDoc->size(theGroup); i++)
1591 theDoc->object(theGroup, i)->setDisplayed(true);
1592 //displayObject(theDoc->object(theGroup, i));
1593 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1596 //**************************************************************
1597 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1599 foreach(ObjectPtr aObj, theList) {
1600 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1602 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1603 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1604 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1605 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1606 (XGUI_Displayer::DisplayMode)theMode, false);
1610 if (theList.size() > 0)
1611 myDisplayer->updateViewer();
1614 //**************************************************************
1615 void XGUI_Workshop::closeDocument()
1617 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1618 while (anOperation) {
1619 anOperation->abort();
1620 anOperation = operationMgr()->currentOperation();
1622 myDisplayer->closeLocalContexts();
1623 myDisplayer->eraseAll();
1624 objectBrowser()->clearContent();
1626 module()->closeDocument();
1628 SessionPtr aMgr = ModelAPI_Session::get();
1632 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1634 XGUI_HistoryMenu* aMenu = NULL;
1635 if (isSalomeMode()) {
1636 QAction* anAction = qobject_cast<QAction*>(theObject);
1639 aMenu = new XGUI_HistoryMenu(anAction);
1641 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1642 aMenu = new XGUI_HistoryMenu(aButton);
1644 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1645 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1648 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1650 QList<ActionInfo> aResult;
1651 std::list<std::string>::const_iterator it = theList.cbegin();
1652 for (; it != theList.cend(); it++) {
1653 QString anId = QString::fromStdString(*it);
1654 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1656 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1659 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1660 if (aContextMenuAct) {
1661 anInfo.initFrom(aContextMenuAct);
1663 anInfo = myActionsMgr->actionInfoById(anId);
1666 anInfo.text = anInfo.text.prepend("Modify ");