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>
48 //#include <PartSetPlugin_Part.h>
50 #include <Events_Loop.h>
51 #include <Events_Error.h>
52 #include <Events_LongOp.h>
54 #include <ModuleBase_FilterFactory.h>
55 #include <ModuleBase_IModule.h>
56 #include <ModuleBase_IViewer.h>
57 #include <ModuleBase_Operation.h>
58 #include <ModuleBase_OperationDescription.h>
59 #include <ModuleBase_PageBase.h>
60 #include <ModuleBase_Preferences.h>
61 #include <ModuleBase_SelectionValidator.h>
62 #include <ModuleBase_Tools.h>
63 #include <ModuleBase_WidgetFactory.h>
65 #include <Config_Common.h>
66 #include <Config_FeatureMessage.h>
67 #include <Config_ModuleReader.h>
68 #include <Config_PointerMessage.h>
69 #include <Config_PropManager.h>
70 #include <Config_SelectionFilterMessage.h>
72 #include <SUIT_ResourceMgr.h>
74 #include <QApplication>
75 #include <QFileDialog>
76 #include <QMessageBox>
77 #include <QMdiSubWindow>
78 #include <QPushButton>
79 #include <QDockWidget>
84 #include <QToolButton>
86 #include <QDesktopWidget>
101 //#define DEBUG_DELETE
103 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
105 myCurrentDir(QString()),
107 mySalomeConnector(theConnector),
112 myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
115 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
116 bool aCloc = aResMgr->booleanValue("language", "locale", true);
118 QLocale::setDefault( QLocale::c() );
120 QLocale::setDefault( QLocale::system() );
123 myDisplayer = new XGUI_Displayer(this);
125 mySelector = new XGUI_SelectionMgr(this);
126 //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
128 myOperationMgr = new XGUI_OperationMgr(this, 0);
129 myActionsMgr = new XGUI_ActionsMgr(this);
130 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
131 myErrorMgr = new XGUI_ErrorMgr(this);
132 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
133 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
134 SLOT(onContextMenuCommand(const QString&, bool)));
136 myViewerProxy = new XGUI_ViewerProxy(this);
137 connect(myViewerProxy, SIGNAL(selectionChanged()),
138 myActionsMgr, SLOT(updateOnViewSelection()));
140 myModuleConnector = new XGUI_ModuleConnector(this);
142 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
143 myOperationMgr->setWorkshop(aWorkshop);
145 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
147 connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
148 SLOT(onOperationStarted(ModuleBase_Operation*)));
149 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
150 SLOT(onOperationResumed(ModuleBase_Operation*)));
151 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
152 SLOT(onOperationStopped(ModuleBase_Operation*)));
153 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
154 SLOT(onOperationCommitted(ModuleBase_Operation*)));
155 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
156 SLOT(onOperationAborted(ModuleBase_Operation*)));
157 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
158 myErrorMgr, SLOT(onValidationStateChanged()));
161 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
162 connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
163 connect(myEventsListener, SIGNAL(errorOccurred(const QString&)),
164 myErrorDlg, SLOT(addError(const QString&)));
166 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
167 // Config_Prop::Color, "225,225,225");
169 Config_PropManager::registerProp("Visualization", "result_body_color", "Body color",
170 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
171 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
172 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
173 Config_PropManager::registerProp("Visualization", "result_construction_color", "Construction color",
174 Config_Prop::Color, ModelAPI_ResultConstruction::DEFAULT_COLOR());
175 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
176 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
179 //******************************************************
180 XGUI_Workshop::~XGUI_Workshop(void)
185 //******************************************************
186 void XGUI_Workshop::startApplication()
190 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
191 Config_Prop::Directory, "");
193 //Initialize event listening
194 myEventsListener->initializeEventListening();
196 registerValidators();
198 // Calling of loadCustomProps before activating module is required
199 // by Config_PropManger to restore user-defined path to plugins
200 ModuleBase_Preferences::loadCustomProps();
203 myMainWindow->show();
204 updateCommandStatus();
209 emit applicationStarted();
212 void XGUI_Workshop::activateModule()
214 myModule->activateSelectionFilters();
216 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
217 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
218 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
219 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
221 myActionsMgr->update();
225 void XGUI_Workshop::deactivateModule()
227 myModule->deactivateSelectionFilters();
229 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
230 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
231 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
232 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
235 //******************************************************
236 void XGUI_Workshop::initMenu()
238 myContextMenuMgr->createActions();
240 if (isSalomeMode()) {
241 // Create only Undo, Redo commands
242 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
243 tr("Undo last command"),
244 QIcon(":pictures/undo.png"),
245 QKeySequence::Undo, false, "MEN_DESK_EDIT");
246 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
247 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
249 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
250 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
252 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
253 QIcon(":pictures/redo.png"), QKeySequence::Redo,
254 false, "MEN_DESK_EDIT");
255 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
257 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
258 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
260 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
261 aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
262 QIcon(":pictures/rebuild.png"), QKeySequence(),
263 false, "MEN_DESK_EDIT");
264 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
266 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
267 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
269 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
270 QIcon(), QKeySequence(),
271 false, "MEN_DESK_FILE");
272 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
274 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
275 QIcon(), QKeySequence(),
276 false, "MEN_DESK_FILE");
277 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
278 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
282 // File commands group
283 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
285 AppElements_Command* aCommand;
287 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
288 QIcon(":pictures/save.png"), QKeySequence::Save);
289 aCommand->connectTo(this, SLOT(onSave()));
290 //aCommand->disable();
292 QString aUndoId = "UNDO_CMD";
293 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
294 QIcon(":pictures/undo.png"), QKeySequence::Undo);
295 aCommand->connectTo(this, SLOT(onUndo()));
296 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
297 addHistoryMenu(aUndoButton,
298 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
301 QString aRedoId = "REDO_CMD";
302 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
303 QIcon(":pictures/redo.png"), QKeySequence::Redo);
304 aCommand->connectTo(this, SLOT(onRedo()));
305 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
306 addHistoryMenu(aRedoButton,
307 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
310 aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
311 QIcon(":pictures/rebuild.png"), QKeySequence());
312 aCommand->connectTo(this, SLOT(onRebuild()));
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()));
317 //aCommand->disable();
319 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
320 QIcon(":pictures/open.png"), QKeySequence::Open);
321 aCommand->connectTo(this, SLOT(onOpen()));
323 //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
324 // QIcon(":pictures/new.png"), QKeySequence::New);
325 //aCommand->connectTo(this, SLOT(onNew()));
327 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
328 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
329 aCommand->connectTo(this, SLOT(onPreferences()));
331 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
332 QIcon(":pictures/close.png"), QKeySequence::Close);
333 aCommand->connectTo(this, SLOT(onExit()));
334 //FIXME: SBH's test action. Can be used for some GUI tests.
336 // aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
337 // QIcon(":pictures/close.png"), QKeySequence(), true);
338 // aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
342 //******************************************************
343 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
345 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
346 return aMenuBar->addWorkbench(theName);
349 //******************************************************
350 QMainWindow* XGUI_Workshop::desktop() const
352 return isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
355 //******************************************************
356 void XGUI_Workshop::onStartWaiting()
358 if (Events_LongOp::isPerformed()) {
359 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
364 //******************************************************
365 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
367 if (!myModule->canActivateSelection(theObject)) {
368 if (myDisplayer->isActive(theObject))
369 myDisplayer->deactivate(theObject, theUpdateViewer);
373 //******************************************************
374 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
376 setNestedFeatures(theOperation);
378 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
379 connectWithOperation(theOperation);
380 setPropertyPanel(theOperation);
381 // filling the operation values by the current selection
382 // if the operation can be commited after the controls filling, the method perform should
383 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
384 if (!theOperation->isEditOperation()) {
385 theOperation->activateByPreselection();
386 if (operationMgr()->currentOperation() != theOperation)
390 updateCommandStatus();
392 myModule->onOperationStarted(theOperation);
394 // the objects of the current operation should be deactivated
395 QObjectPtrList anObjects;
396 FeaturePtr aFeature = theOperation->feature();
397 anObjects.append(aFeature);
398 std::list<ResultPtr> aResults = aFeature->results();
399 std::list<ResultPtr>::const_iterator aIt;
400 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
401 anObjects.append(*aIt);
403 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
404 for (; anIt != aLast; anIt++)
405 deactivateActiveObject(*anIt, false);
406 if (anObjects.size() > 0)
407 myDisplayer->updateViewer();
410 //******************************************************
411 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
413 setNestedFeatures(theOperation);
415 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
416 // connectWithOperation(theOperation); already connected
417 setPropertyPanel(theOperation);
419 updateCommandStatus();
421 myModule->onOperationResumed(theOperation);
425 //******************************************************
426 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
428 ModuleBase_ISelection* aSel = mySelector->selection();
429 QObjectPtrList aObj = aSel->selectedPresentations();
430 //!< No need for property panel
431 updateCommandStatus();
433 myPropertyPanel->cleanContent();
435 myModule->onOperationStopped(theOperation);
437 // the deactivated objects of the current operation should be activated back.
438 // They were deactivated on operation start or an object redisplay
439 QObjectPtrList anObjects;
440 FeaturePtr aFeature = theOperation->feature();
441 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
442 anObjects.append(aFeature);
443 std::list<ResultPtr> aResults = aFeature->results();
444 std::list<ResultPtr>::const_iterator aIt;
445 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
446 ResultPtr anObject = *aIt;
447 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
448 anObjects.append(anObject);
452 module()->activeSelectionModes(aModes);
453 myDisplayer->activateObjects(aModes, anObjects);
457 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
459 myModule->onOperationCommitted(theOperation);
462 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
464 myModule->onOperationAborted(theOperation);
467 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
469 if (this->isSalomeMode())
470 theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
472 theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
475 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
478 QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
479 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
482 myPropertyPanel->cleanContent();
483 aFactory.createWidget(myPropertyPanel->contentWidget());
485 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
486 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
487 bool isStoreValue = !theOperation->isEditOperation() &&
488 !aWidget->getDefaultValue().empty() &&
489 !aWidget->isComputedDefault();
490 aWidget->setFeature(theOperation->feature(), isStoreValue);
491 aWidget->enableFocusProcessing();
494 myPropertyPanel->setModelWidgets(aWidgets);
495 theOperation->setPropertyPanel(myPropertyPanel);
497 myModule->propertyPanelDefined(theOperation);
499 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
501 myErrorMgr->setPropertyPanel(myPropertyPanel);
505 * Makes a signal/slot connections between Property Panel
506 * and given operation. The given operation becomes a
507 * current operation and previous operation if exists
509 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
511 QAction* aCommand = 0;
512 if (isSalomeMode()) {
513 aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
515 AppElements_MainMenu* aMenu = myMainWindow->menuObject();
516 FeaturePtr aFeature = theOperation->feature();
518 aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
520 //Abort operation on uncheck the command
522 connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
527 * Saves document with given name.
529 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
531 QApplication::restoreOverrideCursor();
532 SessionPtr aMgr = ModelAPI_Session::get();
533 aMgr->save(theName.toLatin1().constData(), theFileNames);
534 QApplication::restoreOverrideCursor();
537 bool XGUI_Workshop::isActiveOperationAborted()
539 return myOperationMgr->abortAllOperations();
542 //******************************************************
543 void XGUI_Workshop::onExit()
545 SessionPtr aMgr = ModelAPI_Session::get();
546 if (aMgr->isModified()) {
547 int anAnswer = QMessageBox::question(
548 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
549 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
550 if (anAnswer == QMessageBox::Save) {
551 bool saved = onSave();
555 } else if (anAnswer == QMessageBox::Cancel) {
562 //******************************************************
563 void XGUI_Workshop::onNew()
565 QApplication::setOverrideCursor(Qt::WaitCursor);
566 if (objectBrowser() == 0) {
568 mySelector->connectViewers();
570 myViewerProxy->connectToViewer();
572 if (!isSalomeMode()) {
573 myMainWindow->showPythonConsole();
574 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
575 aWnd->showMaximized();
576 updateCommandStatus();
578 myContextMenuMgr->connectViewer();
579 QApplication::restoreOverrideCursor();
582 //******************************************************
583 void XGUI_Workshop::onOpen()
585 if(!isActiveOperationAborted())
587 //save current file before close if modified
588 SessionPtr aSession = ModelAPI_Session::get();
589 if (aSession->isModified()) {
590 //TODO(sbh): re-launch the app?
591 int anAnswer = QMessageBox::question(
592 myMainWindow, tr("Save current file"),
593 tr("The document is modified, save before opening another?"),
594 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
595 if (anAnswer == QMessageBox::Save) {
597 } else if (anAnswer == QMessageBox::Cancel) {
603 //show file dialog, check if readable and open
604 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow(), tr("Select directory"));
605 if (myCurrentDir.isEmpty())
607 QFileInfo aFileInfo(myCurrentDir);
608 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
609 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
613 QApplication::setOverrideCursor(Qt::WaitCursor);
614 aSession->closeAll();
615 aSession->load(myCurrentDir.toLatin1().constData());
616 myObjectBrowser->rebuildDataTree();
617 //displayAllResults();
618 updateCommandStatus();
619 QApplication::restoreOverrideCursor();
622 //******************************************************
623 bool XGUI_Workshop::onSave()
625 if(!isActiveOperationAborted())
627 if (myCurrentDir.isEmpty()) {
630 std::list<std::string> aFiles;
631 saveDocument(myCurrentDir, aFiles);
632 updateCommandStatus();
634 myMainWindow->setModifiedState(false);
638 //******************************************************
639 bool XGUI_Workshop::onSaveAs()
641 if(!isActiveOperationAborted())
643 QFileDialog dialog(mainWindow());
644 dialog.setWindowTitle(tr("Select directory to save files..."));
645 dialog.setFileMode(QFileDialog::Directory);
646 dialog.setFilter(tr("Directories (*)"));
647 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
648 dialog.setViewMode(QFileDialog::Detail);
650 if (!dialog.exec()) {
654 QString aTempDir = dialog.selectedFiles().first();
656 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
657 int answer = QMessageBox::question(
659 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
661 tr("The directory already contains some files, save anyway?"),
662 QMessageBox::Save | QMessageBox::Cancel);
663 if (answer == QMessageBox::Cancel) {
667 myCurrentDir = aTempDir;
668 if (!isSalomeMode()) {
669 myMainWindow->setCurrentDir(myCurrentDir, false);
670 myMainWindow->setModifiedState(false);
675 //******************************************************
676 void XGUI_Workshop::onUndo(int theTimes)
678 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
679 SessionPtr aMgr = ModelAPI_Session::get();
680 if (aMgr->isOperation())
681 operationMgr()->onAbortOperation();
682 for (int i = 0; i < theTimes; ++i) {
685 updateCompositeActionState();
686 updateCommandStatus();
689 //******************************************************
690 void XGUI_Workshop::onRedo(int theTimes)
692 // the viewer update should be blocked in order to avoid the features blinking. For the created
693 // feature a results are created, the flush of the created signal caused the viewer redisplay for
694 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
695 // redo of all possible objects happens
696 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
698 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
699 SessionPtr aMgr = ModelAPI_Session::get();
700 if (aMgr->isOperation())
701 operationMgr()->onAbortOperation();
702 for (int i = 0; i < theTimes; ++i) {
705 updateCompositeActionState();
706 updateCommandStatus();
708 // unblock the viewer update functionality and make update on purpose
709 myDisplayer->enableUpdateViewer(isUpdateEnabled);
710 myDisplayer->updateViewer();
713 //******************************************************
714 void XGUI_Workshop::onRebuild()
716 SessionPtr aMgr = ModelAPI_Session::get();
717 bool aWasOperation = aMgr->isOperation(); // keep this value
718 if (!aWasOperation) {
719 aMgr->startOperation("Rebuild");
721 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
722 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
723 new Events_Message(aRebuildEvent, this)));
724 if (!aWasOperation) {
725 aMgr->finishOperation();
727 updateCommandStatus();
730 //******************************************************
731 void XGUI_Workshop::onPreferences()
733 ModuleBase_Prefs aModif;
734 ModuleBase_Preferences::editPreferences(aModif);
735 if (aModif.size() > 0) {
737 foreach (ModuleBase_Pref aPref, aModif)
739 aSection = aPref.first;
740 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
742 myMainWindow->viewer()->updateFromResources();
743 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
745 myMainWindow->menuObject()->updateFromResources();
751 //******************************************************
752 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
754 QString libName = QString::fromStdString(library(theModule.toStdString()));
755 if (libName.isEmpty()) {
756 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
761 CREATE_FUNC crtInst = 0;
764 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
768 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
769 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
770 QString aMsg((char*) &lpMsgBuf);
771 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
772 ::LocalFree(lpMsgBuf);
774 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
778 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
779 | FORMAT_MESSAGE_IGNORE_INSERTS,
780 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
781 QString aMsg((char*) &lpMsgBuf);
782 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
783 ::LocalFree(lpMsgBuf);
787 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
789 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
791 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
793 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
798 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
800 if (!err.isEmpty()) {
802 Events_Error::send(err.toStdString());
804 qWarning(qPrintable(err));
810 //******************************************************
811 bool XGUI_Workshop::createModule()
813 Config_ModuleReader aModuleReader;
814 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
815 myModule = loadModule(moduleName);
819 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
820 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
821 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
822 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
824 myModule->createFeatures();
825 //myActionsMgr->update();
829 //******************************************************
830 void XGUI_Workshop::updateCommandStatus()
832 QList<QAction*> aCommands;
833 if (isSalomeMode()) { // update commands in SALOME mode
834 aCommands = salomeConnector()->commandList();
836 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
837 foreach (AppElements_Command* aCmd, aMenuBar->features())
838 aCommands.append(aCmd);
840 SessionPtr aMgr = ModelAPI_Session::get();
841 if (aMgr->hasModuleDocument()) {
842 foreach(QAction* aCmd, aCommands) {
843 QString aId = aCmd->data().toString();
844 if (aId == "UNDO_CMD")
845 aCmd->setEnabled(myModule->canUndo());
846 else if (aId == "REDO_CMD")
847 aCmd->setEnabled(myModule->canRedo());
849 // Enable all commands
850 aCmd->setEnabled(true);
854 foreach(QAction* aCmd, aCommands) {
855 QString aId = aCmd->data().toString();
856 if (aId == "NEW_CMD")
857 aCmd->setEnabled(true);
858 else if (aId == "EXIT_CMD")
859 aCmd->setEnabled(true);
861 aCmd->setEnabled(false);
864 myActionsMgr->update();
865 emit commandStatusUpdated();
868 //******************************************************
869 void XGUI_Workshop::updateCompositeActionState()
871 // in order to apply is enabled only if there are modifications in the model
872 // e.g. sketch can be applyed only if at least one nested element create is finished
873 bool aCanUndo = ModelAPI_Session::get()->canUndo();
874 bool aParentValid = operationMgr()->isParentOperationValid();
875 bool aCurrentValid = operationMgr()->currentOperation() &&
876 operationMgr()->currentOperation()->isValid();
878 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
879 aAcceptAllAct->setEnabled(aParentValid && (aCanUndo || aCurrentValid));
882 void XGUI_Workshop::updateHistory()
884 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
885 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
886 emit updateUndoHistory(aUndoRes);
888 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
889 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
890 emit updateRedoHistory(aRedoRes);
893 //******************************************************
894 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
896 QDockWidget* aObjDock = new QDockWidget(theParent);
897 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
898 aObjDock->setWindowTitle(tr("Object browser"));
899 aObjDock->setStyleSheet(
900 "::title { position: relative; padding-left: 5px; text-align: left center }");
901 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
902 myObjectBrowser->setDataModel(myModule->dataModel());
903 myModule->customizeObjectBrowser(myObjectBrowser);
904 aObjDock->setWidget(myObjectBrowser);
906 myContextMenuMgr->connectObjectBrowser();
910 //******************************************************
912 * Creates dock widgets, places them in corresponding area
913 * and tabifies if necessary.
915 void XGUI_Workshop::createDockWidgets()
917 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
918 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
919 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
920 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
921 myPropertyPanel->setupActions(myActionsMgr);
922 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
923 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
924 hidePropertyPanel(); ///<! Invisible by default
926 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
927 myPropertyPanel->installEventFilter(myOperationMgr);
929 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
930 connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
931 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
932 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
933 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
934 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
935 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
936 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
937 aOkAct, SLOT(setEnabled(bool)));
938 QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
939 connect(myOperationMgr, SIGNAL(nestedStateChanged(bool)),
940 aAcceptAllAct, SLOT(setEnabled(bool)));
944 //******************************************************
945 void XGUI_Workshop::showPropertyPanel()
947 QAction* aViewAct = myPropertyPanel->toggleViewAction();
948 ///<! Restore ability to close panel from the window's menu
949 aViewAct->setEnabled(true);
950 myPropertyPanel->show();
951 myPropertyPanel->raise();
954 //******************************************************
955 void XGUI_Workshop::hidePropertyPanel()
957 QAction* aViewAct = myPropertyPanel->toggleViewAction();
958 ///<! Do not allow to show empty property panel
959 aViewAct->setEnabled(false);
960 myPropertyPanel->hide();
963 //******************************************************
964 void XGUI_Workshop::showObjectBrowser()
966 myObjectBrowser->parentWidget()->show();
969 //******************************************************
970 void XGUI_Workshop::hideObjectBrowser()
972 myObjectBrowser->parentWidget()->hide();
975 //******************************************************
976 //void XGUI_Workshop::onFeatureTriggered()
978 // QAction* aCmd = dynamic_cast<QAction*>(sender());
980 // QString aId = salomeConnector()->commandId(aCmd);
981 // if (!aId.isNull())
982 // myModule->launchOperation(aId);
986 //******************************************************
987 void XGUI_Workshop::salomeViewerSelectionChanged()
989 emit salomeViewerSelection();
992 //**************************************************************
993 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
995 return mySalomeConnector->viewer();
998 //**************************************************************
999 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1001 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1002 if (theId == "DELETE_CMD")
1004 else if (theId == "MOVE_CMD")
1006 else if (theId == "COLOR_CMD")
1007 changeColor(aObjects);
1008 else if (theId == "SHOW_CMD")
1009 showObjects(aObjects, true);
1010 else if (theId == "HIDE_CMD")
1011 showObjects(aObjects, false);
1012 else if (theId == "SHOW_ONLY_CMD")
1013 showOnlyObjects(aObjects);
1014 else if (theId == "SHADING_CMD")
1015 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1016 else if (theId == "WIREFRAME_CMD")
1017 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1018 else if (theId == "HIDEALL_CMD") {
1019 QObjectPtrList aList = myDisplayer->displayedObjects();
1020 foreach (ObjectPtr aObj, aList)
1021 aObj->setDisplayed(false);
1022 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1026 //**************************************************************
1027 void XGUI_Workshop::deleteObjects()
1029 ModuleBase_IModule* aModule = module();
1030 // 1. allow the module to delete objects, do nothing if it has succeed
1031 if (aModule->deleteObjects()) {
1032 updateCommandStatus();
1036 if (!isActiveOperationAborted())
1038 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1039 // It is necessary to clear selection in order to avoid selection changed event during
1040 // deleteion and negative consequences connected with processing of already deleted items
1041 mySelector->clearSelection();
1042 // check whether the object can be deleted. There should not be parts which are not loaded
1043 if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1046 bool hasResult = false;
1047 bool hasFeature = false;
1048 bool hasParameter = false;
1049 bool hasSubFeature = false;
1050 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1051 if (!(hasFeature || hasParameter))
1054 // 1. start operation
1055 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1056 aDescription += tr(" %1");
1057 QStringList aObjectNames;
1058 foreach (ObjectPtr aObj, anObjects) {
1059 if (!aObj->data()->isValid())
1061 aObjectNames << QString::fromStdString(aObj->data()->name());
1063 aDescription = aDescription.arg(aObjectNames.join(", "));
1065 SessionPtr aMgr = ModelAPI_Session::get();
1066 aMgr->startOperation(aDescription.toStdString());
1067 // 2. close the documents of the removed parts if the result part is in a list of selected objects
1068 // this is performed in the RemoveFeature of Part object.
1069 /*foreach (ObjectPtr aObj, anObjects)
1071 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1073 DocumentPtr aDoc = aObj->document();
1074 if (aDoc == aMgr->activeDocument()) {
1079 // 3. delete objects
1080 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1081 std::set<FeaturePtr> anIgnoredFeatures;
1082 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1083 myDisplayer->updateViewer();
1084 aMgr->finishOperation();
1085 updateCommandStatus();
1088 aMgr->abortOperation();
1092 //**************************************************************
1093 void XGUI_Workshop::moveObjects()
1095 if (!isActiveOperationAborted())
1098 SessionPtr aMgr = ModelAPI_Session::get();
1100 QString anActionId = "MOVE_CMD";
1101 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1102 aMgr->startOperation(aDescription.toStdString());
1104 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1105 DocumentPtr anActiveDocument = aMgr->activeDocument();
1107 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1108 foreach (ObjectPtr aObject, anObjects) {
1109 if (!myModule->canApplyAction(aObject, anActionId))
1112 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1113 if (aFeature.get()) {
1114 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1115 aCurrentFeature = anActiveDocument->currentFeature(true);
1118 aMgr->finishOperation();
1121 //**************************************************************
1122 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1123 const std::set<FeaturePtr>& theIgnoredFeatures,
1125 const bool theAskAboutDeleteReferences)
1129 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1130 for (; aDIt != aDLast; ++aDIt) {
1131 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1133 QString anInfoStr = aDInfo.join(", ");
1134 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1137 // 1. find all referenced features
1138 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1139 foreach (ObjectPtr aDeletedObj, theList) {
1140 XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures);
1141 std::set<FeaturePtr> aDifference;
1142 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1143 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1144 std::inserter(aDifference, aDifference.begin()));
1145 aIndirectRefFeatures = aDifference;
1147 // 2. warn about the references remove, break the delete operation if the user chose it
1148 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1149 QStringList aDirectRefNames;
1150 foreach(const FeaturePtr& aFeature, aDirectRefFeatures)
1151 aDirectRefNames.append(aFeature->name().c_str());
1152 QString aDirectNames = aDirectRefNames.join(", ");
1154 QStringList aIndirectRefNames;
1155 foreach(const FeaturePtr& aFeature, aIndirectRefFeatures)
1156 aIndirectRefNames.append(aFeature->name().c_str());
1157 QString aIndirectNames = aIndirectRefNames.join(", ");
1159 QMessageBox::StandardButton aRes = QMessageBox::warning(
1160 theParent, tr("Delete features"),
1161 QString(tr("Selected features are used in the following features: %1.\
1162 These features will be deleted.\n%2Would you like to continue?")).arg(aDirectNames)
1163 .arg(aIndirectNames.isEmpty() ? QString() : QString("Also these features will be deleted: %1.\n").arg(aIndirectNames)),
1164 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1165 if (aRes != QMessageBox::Yes)
1169 // 3. remove referenced features
1170 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1171 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1172 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1173 aLast = aFeaturesToDelete.end();
1177 for (; anIt != aLast; anIt++) {
1178 FeaturePtr aFeature = (*anIt);
1179 DocumentPtr aDoc = aFeature->document();
1180 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1181 aDoc->removeFeature(aFeature);
1183 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1188 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1192 QString anActionId = "DELETE_CMD";
1193 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1194 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1195 // 4. remove the parameter features
1196 foreach (ObjectPtr aObj, theList) {
1197 // features and parameters can be removed here,
1198 // the results are removed only by a corresponded feature remove
1199 std::string aGroupName = aObj->groupName();
1200 if (!anObjectGroups.contains(aGroupName.c_str()))
1203 if (!myModule->canApplyAction(aObj, anActionId))
1206 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1208 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1209 // part features are removed in the PartSet module. This condition should be moved there
1210 if (aFeature->getKind() == "Part")
1213 DocumentPtr aDoc = aObj->document();
1214 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1216 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1217 anInfo.append(anInfoStr);
1218 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1220 aDoc->removeFeature(aFeature);
1225 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1230 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1232 bool isFoundResultType = false;
1233 foreach(ObjectPtr anObj, theObjects)
1235 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1236 if (aResult.get() == NULL)
1239 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1240 if (isFoundResultType)
1243 return isFoundResultType;
1246 //**************************************************************
1247 // Returns the list of features placed between theObject and the current feature
1248 // in the same document. Excludes theObject, includes the current feature.
1249 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1251 std::list<FeaturePtr> aResult;
1252 DocumentPtr aDocument = theObject->document();
1253 std::list<FeaturePtr> anAllFeatures = aDocument->allFeatures();
1254 // find the object iterator
1255 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1256 if (aObjectIt == anAllFeatures.end())
1258 // find the current feature iterator
1259 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1260 if (aCurrentIt == anAllFeatures.end())
1262 // check the right order
1263 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1265 // exclude the object
1266 std::advance(aObjectIt, 1);
1267 // include the current feature
1268 std::advance(aCurrentIt, 1);
1269 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1272 bool XGUI_Workshop::canMoveFeature()
1274 QString anActionId = "MOVE_CMD";
1276 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1277 QObjectPtrList aValidatedObjects;
1278 foreach (ObjectPtr aObject, aObjects) {
1279 if (myModule->canApplyAction(aObject, anActionId))
1280 aValidatedObjects.append(aObject);
1282 if (aValidatedObjects.size() != aObjects.size())
1283 aObjects = aValidatedObjects;
1285 bool aCanMove = !aObjects.empty();
1287 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1288 for (; anIt != aLast && aCanMove; anIt++) {
1289 ObjectPtr aObject = *anIt;
1290 // 1. Get features placed between selected and current in the document
1291 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1292 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1293 if (aFeaturesBetween.empty())
1296 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1297 // 2. Get all reference features to the selected object in the document
1298 std::set<FeaturePtr> aRefFeatures;
1299 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1301 if (aRefFeatures.empty())
1304 // 3. Find any placed features in all reference features
1305 std::set<FeaturePtr> aIntersectionFeatures;
1306 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1307 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1308 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1309 // 4. Return false if any reference feature is placed before curent feature
1310 if (!aIntersectionFeatures.empty())
1318 //**************************************************************
1319 bool XGUI_Workshop::canChangeColor() const
1321 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1323 std::set<std::string> aTypes;
1324 aTypes.insert(ModelAPI_ResultGroup::group());
1325 aTypes.insert(ModelAPI_ResultConstruction::group());
1326 aTypes.insert(ModelAPI_ResultBody::group());
1327 aTypes.insert(ModelAPI_ResultPart::group());
1329 return hasResults(aObjects, aTypes);
1332 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1334 if (!theResult.get())
1337 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1338 if (aColorAttr.get() != NULL) {
1339 if (!aColorAttr->size()) {
1340 aColorAttr->setSize(3);
1342 aColorAttr->setValue(0, theColor[0]);
1343 aColorAttr->setValue(1, theColor[1]);
1344 aColorAttr->setValue(2, theColor[2]);
1348 //**************************************************************
1349 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1351 AttributeIntArrayPtr aColorAttr;
1352 // 1. find the current color of the object. This is a color of AIS presentation
1353 // The objects are iterated until a first valid color is found
1354 std::vector<int> aColor;
1355 foreach(ObjectPtr anObject, theObjects) {
1356 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1357 if (aResult.get()) {
1358 XGUI_CustomPrs::getResultColor(aResult, aColor);
1361 // TODO: remove the obtaining a color from the AIS object
1362 // this does not happen never because:
1363 // 1. The color can be changed only on results
1364 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1365 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1366 if (anAISObj.get()) {
1368 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1371 if (!aColor.empty())
1374 if (aColor.size() != 3)
1377 // 2. show the dialog to change the value
1378 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1379 aDlg->setColor(aColor);
1380 aDlg->move(QCursor::pos());
1381 bool isDone = aDlg->exec() == QDialog::Accepted;
1385 bool isRandomColor = aDlg->isRandomColor();
1387 // 3. abort the previous operation and start a new one
1388 SessionPtr aMgr = ModelAPI_Session::get();
1389 bool aWasOperation = aMgr->isOperation(); // keep this value
1390 if (!aWasOperation) {
1391 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1392 aMgr->startOperation(aDescription.toStdString());
1395 // 4. set the value to all results
1396 std::vector<int> aColorResult = aDlg->getColor();
1397 foreach(ObjectPtr anObj, theObjects) {
1398 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1399 if (aResult.get() != NULL) {
1400 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1401 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1402 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1403 ResultPtr aSubResult = aCompsolidResult->subResult(i);
1404 if (aSubResult.get())
1405 setColor(aSubResult, aColorResult);
1408 setColor(aResult, aColorResult);
1412 aMgr->finishOperation();
1413 updateCommandStatus();
1416 //**************************************************************
1417 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1418 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1419 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1421 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1423 foreach (ObjectPtr aObj, theList) {
1425 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1427 DocumentPtr aDoc = aPartRes->partDoc();
1428 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1429 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1430 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1433 aObj->setDisplayed(isVisible);
1436 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1439 //**************************************************************
1440 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1442 // Hide all displayed objects
1443 QObjectPtrList aList = myDisplayer->displayedObjects();
1444 foreach (ObjectPtr aObj, aList)
1445 aObj->setDisplayed(false);
1447 // Show only objects from the list
1448 foreach (ObjectPtr aObj, theList) {
1450 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1452 DocumentPtr aDoc = aPartRes->partDoc();
1453 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1454 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1455 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1458 aObj->setDisplayed(true);
1461 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1466 //**************************************************************
1467 void XGUI_Workshop::registerValidators() const
1469 SessionPtr aMgr = ModelAPI_Session::get();
1470 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1473 //**************************************************************
1474 /*void XGUI_Workshop::displayAllResults()
1476 SessionPtr aMgr = ModelAPI_Session::get();
1477 DocumentPtr aRootDoc = aMgr->moduleDocument();
1478 displayDocumentResults(aRootDoc);
1479 for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1480 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1481 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1482 displayDocumentResults(aPart->partDoc());
1484 myDisplayer->updateViewer();
1487 //**************************************************************
1488 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1492 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1493 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1496 //**************************************************************
1497 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1499 for (int i = 0; i < theDoc->size(theGroup); i++)
1500 theDoc->object(theGroup, i)->setDisplayed(true);
1501 //displayObject(theDoc->object(theGroup, i));
1502 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1505 //**************************************************************
1506 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1508 foreach(ObjectPtr aObj, theList) {
1509 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1511 if (theList.size() > 0)
1512 myDisplayer->updateViewer();
1515 //**************************************************************
1516 void XGUI_Workshop::closeDocument()
1518 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1519 while (anOperation) {
1520 anOperation->abort();
1521 anOperation = operationMgr()->currentOperation();
1523 myDisplayer->closeLocalContexts();
1524 myDisplayer->eraseAll();
1525 objectBrowser()->clearContent();
1527 SessionPtr aMgr = ModelAPI_Session::get();
1531 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1533 XGUI_HistoryMenu* aMenu = NULL;
1534 if (isSalomeMode()) {
1535 QAction* anAction = qobject_cast<QAction*>(theObject);
1538 aMenu = new XGUI_HistoryMenu(anAction);
1540 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1541 aMenu = new XGUI_HistoryMenu(aButton);
1543 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1544 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1547 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1549 QList<ActionInfo> aResult;
1550 std::list<std::string>::const_iterator it = theList.cbegin();
1551 for (; it != theList.cend(); it++) {
1552 QString anId = QString::fromStdString(*it);
1553 bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1555 anId.chop(ModuleBase_Operation::EditSuffix().size());
1558 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1559 if (aContextMenuAct) {
1560 anInfo.initFrom(aContextMenuAct);
1562 anInfo = myActionsMgr->actionInfoById(anId);
1565 anInfo.text = anInfo.text.prepend("Modify ");