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 myErrorMgr = new XGUI_ErrorMgr(this);
135 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
136 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
137 SLOT(onContextMenuCommand(const QString&, bool)));
139 myViewerProxy = new XGUI_ViewerProxy(this);
140 connect(myViewerProxy, SIGNAL(selectionChanged()),
141 myActionsMgr, SLOT(updateOnViewSelection()));
143 myModuleConnector = new XGUI_ModuleConnector(this);
145 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
146 myOperationMgr->setWorkshop(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 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
424 setGrantedFeatures(theOperation);
426 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
431 if (aFOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
432 setPropertyPanel(aFOperation);
433 // filling the operation values by the current selection
434 // if the operation can be commited after the controls filling, the method perform should
435 // be stopped. Otherwise unnecessary presentations can be shown(e.g. operation prs in sketch)
436 if (!aFOperation->isEditOperation()) {
437 aFOperation->activateByPreselection();
438 if (operationMgr()->currentOperation() != aFOperation)
442 updateCommandStatus();
444 myModule->onOperationStarted(aFOperation);
446 // the objects of the current operation should be deactivated
447 QObjectPtrList anObjects;
448 FeaturePtr aFeature = aFOperation->feature();
449 anObjects.append(aFeature);
450 std::list<ResultPtr> aResults = aFeature->results();
451 std::list<ResultPtr>::const_iterator aIt;
452 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
453 anObjects.append(*aIt);
455 QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
456 for (; anIt != aLast; anIt++)
457 deactivateActiveObject(*anIt, false);
458 if (anObjects.size() > 0)
459 myDisplayer->updateViewer();
462 //******************************************************
463 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
465 setGrantedFeatures(theOperation);
467 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
468 setPropertyPanel(theOperation);
470 updateCommandStatus();
472 myModule->onOperationResumed(theOperation);
476 //******************************************************
477 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
479 updateCommandStatus();
481 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
486 ModuleBase_ISelection* aSel = mySelector->selection();
487 QObjectPtrList aObj = aSel->selectedPresentations();
488 //!< No need for property panel
490 myPropertyPanel->cleanContent();
492 myModule->onOperationStopped(aFOperation);
494 // the deactivated objects of the current operation should be activated back.
495 // They were deactivated on operation start or an object redisplay
496 QObjectPtrList anObjects;
497 FeaturePtr aFeature = aFOperation->feature();
498 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
499 anObjects.append(aFeature);
500 std::list<ResultPtr> aResults = aFeature->results();
501 std::list<ResultPtr>::const_iterator aIt;
502 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
503 ResultPtr anObject = *aIt;
504 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
505 anObjects.append(anObject);
509 module()->activeSelectionModes(aModes);
510 myDisplayer->activateObjects(aModes, anObjects);
514 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
516 myModule->onOperationCommitted(theOperation);
519 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
521 myModule->onOperationAborted(theOperation);
524 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
526 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
530 QStringList aGrantedIds;
532 aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
534 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
536 aFOperation->setGrantedOperationIds(aGrantedIds);
539 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
541 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
546 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
547 ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
550 myPropertyPanel->cleanContent();
551 aFactory.createWidget(myPropertyPanel->contentWidget());
553 QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
554 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
555 bool isStoreValue = !aFOperation->isEditOperation() &&
556 !aWidget->getDefaultValue().empty() &&
557 !aWidget->isComputedDefault();
558 aWidget->setFeature(aFOperation->feature(), isStoreValue);
559 aWidget->enableFocusProcessing();
562 myPropertyPanel->setModelWidgets(aWidgets);
563 aFOperation->setPropertyPanel(myPropertyPanel);
565 myModule->propertyPanelDefined(theOperation);
567 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
569 myErrorMgr->setPropertyPanel(myPropertyPanel);
573 * Saves document with given name.
575 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
577 QApplication::restoreOverrideCursor();
578 SessionPtr aMgr = ModelAPI_Session::get();
579 aMgr->save(theName.toLatin1().constData(), theFileNames);
580 QApplication::restoreOverrideCursor();
583 bool XGUI_Workshop::abortAllOperations()
585 return myOperationMgr->abortAllOperations();
588 //******************************************************
589 void XGUI_Workshop::onExit()
591 SessionPtr aMgr = ModelAPI_Session::get();
592 if (aMgr->isModified()) {
593 int anAnswer = QMessageBox::question(
594 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
595 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
596 if (anAnswer == QMessageBox::Save) {
597 bool saved = onSave();
601 } else if (anAnswer == QMessageBox::Cancel) {
608 //******************************************************
609 void XGUI_Workshop::onNew()
611 QApplication::setOverrideCursor(Qt::WaitCursor);
612 if (objectBrowser() == 0) {
614 mySelector->connectViewers();
616 myViewerProxy->connectToViewer();
618 if (!isSalomeMode()) {
619 myMainWindow->showPythonConsole();
620 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
621 aWnd->showMaximized();
622 updateCommandStatus();
624 myContextMenuMgr->connectViewer();
625 QApplication::restoreOverrideCursor();
628 //******************************************************
629 void XGUI_Workshop::onOpen()
631 if(!abortAllOperations())
633 //save current file before close if modified
634 SessionPtr aSession = ModelAPI_Session::get();
635 if (aSession->isModified()) {
636 //TODO(sbh): re-launch the app?
637 int anAnswer = QMessageBox::question(
638 myMainWindow, tr("Save current file"),
639 tr("The document is modified, save before opening another?"),
640 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
641 if (anAnswer == QMessageBox::Save) {
643 } else if (anAnswer == QMessageBox::Cancel) {
649 //show file dialog, check if readable and open
650 myCurrentDir = QFileDialog::getExistingDirectory(mainWindow(), tr("Select directory"));
651 if (myCurrentDir.isEmpty())
653 QFileInfo aFileInfo(myCurrentDir);
654 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
655 QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
659 QApplication::setOverrideCursor(Qt::WaitCursor);
660 aSession->closeAll();
661 aSession->load(myCurrentDir.toLatin1().constData());
662 myObjectBrowser->rebuildDataTree();
663 updateCommandStatus();
664 QApplication::restoreOverrideCursor();
667 //******************************************************
668 bool XGUI_Workshop::onSave()
670 if(!abortAllOperations())
672 if (myCurrentDir.isEmpty()) {
675 std::list<std::string> aFiles;
676 saveDocument(myCurrentDir, aFiles);
677 updateCommandStatus();
679 myMainWindow->setModifiedState(false);
683 //******************************************************
684 bool XGUI_Workshop::onSaveAs()
686 if(!abortAllOperations())
688 QFileDialog dialog(mainWindow());
689 dialog.setWindowTitle(tr("Select directory to save files..."));
690 dialog.setFileMode(QFileDialog::Directory);
691 dialog.setFilter(tr("Directories (*)"));
692 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
693 dialog.setViewMode(QFileDialog::Detail);
695 if (!dialog.exec()) {
699 QString aTempDir = dialog.selectedFiles().first();
701 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
702 int answer = QMessageBox::question(
704 //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
706 tr("The directory already contains some files, save anyway?"),
707 QMessageBox::Save | QMessageBox::Cancel);
708 if (answer == QMessageBox::Cancel) {
712 myCurrentDir = aTempDir;
713 if (!isSalomeMode()) {
714 myMainWindow->setCurrentDir(myCurrentDir, false);
715 myMainWindow->setModifiedState(false);
720 //******************************************************
721 void XGUI_Workshop::onUndo(int theTimes)
723 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
724 SessionPtr aMgr = ModelAPI_Session::get();
725 if (aMgr->isOperation()) {
726 /// this is important for nested operrations
727 /// when sketch opeation is active, this condition is false and
728 /// the sketch operation is not aborted
729 operationMgr()->onAbortOperation();
731 for (int i = 0; i < theTimes; ++i) {
735 operationMgr()->updateApplyOfOperations();
736 updateCommandStatus();
739 //******************************************************
740 void XGUI_Workshop::onRedo(int theTimes)
742 // the viewer update should be blocked in order to avoid the features blinking. For the created
743 // feature a results are created, the flush of the created signal caused the viewer redisplay for
744 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
745 // redo of all possible objects happens
746 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
748 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
749 SessionPtr aMgr = ModelAPI_Session::get();
750 if (aMgr->isOperation()) {
751 /// this is important for nested operrations
752 /// when sketch opeation is active, this condition is false and
753 /// the sketch operation is not aborted
754 operationMgr()->onAbortOperation();
756 for (int i = 0; i < theTimes; ++i) {
759 operationMgr()->updateApplyOfOperations();
760 updateCommandStatus();
762 // unblock the viewer update functionality and make update on purpose
763 myDisplayer->enableUpdateViewer(isUpdateEnabled);
764 myDisplayer->updateViewer();
767 //******************************************************
768 void XGUI_Workshop::onRebuild()
770 SessionPtr aMgr = ModelAPI_Session::get();
771 bool aWasOperation = aMgr->isOperation(); // keep this value
772 if (!aWasOperation) {
773 aMgr->startOperation("Rebuild");
775 static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
776 Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
777 new Events_Message(aRebuildEvent, this)));
778 if (!aWasOperation) {
779 aMgr->finishOperation();
781 updateCommandStatus();
784 //******************************************************
785 void XGUI_Workshop::onPreferences()
787 ModuleBase_Prefs aModif;
788 ModuleBase_Preferences::editPreferences(aModif);
789 if (aModif.size() > 0) {
791 foreach (ModuleBase_Pref aPref, aModif)
793 aSection = aPref.first;
794 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
796 myMainWindow->viewer()->updateFromResources();
797 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
799 myMainWindow->menuObject()->updateFromResources();
802 displayer()->redisplayObjects();
806 //******************************************************
807 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
809 QString libName = QString::fromStdString(library(theModule.toStdString()));
810 if (libName.isEmpty()) {
811 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
816 CREATE_FUNC crtInst = 0;
819 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
823 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
824 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
825 QString aMsg((char*) &lpMsgBuf);
826 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
827 ::LocalFree(lpMsgBuf);
829 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
833 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
834 | FORMAT_MESSAGE_IGNORE_INSERTS,
835 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
836 QString aMsg((char*) &lpMsgBuf);
837 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
838 ::LocalFree(lpMsgBuf);
842 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
844 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
846 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
848 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
853 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
855 if (!err.isEmpty()) {
857 Events_Error::send(err.toStdString());
859 qWarning(qPrintable(err));
865 //******************************************************
866 bool XGUI_Workshop::createModule()
868 Config_ModuleReader aModuleReader;
869 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
870 myModule = loadModule(moduleName);
874 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
875 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
876 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
877 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
879 myModule->createFeatures();
880 //myActionsMgr->update();
884 //******************************************************
885 void XGUI_Workshop::updateCommandStatus()
887 QList<QAction*> aCommands;
888 if (isSalomeMode()) { // update commands in SALOME mode
889 aCommands = salomeConnector()->commandList();
891 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
892 foreach (AppElements_Command* aCmd, aMenuBar->features())
893 aCommands.append(aCmd);
895 SessionPtr aMgr = ModelAPI_Session::get();
896 if (aMgr->hasModuleDocument()) {
897 foreach(QAction* aCmd, aCommands) {
898 QString aId = aCmd->data().toString();
899 if (aId == "UNDO_CMD")
900 aCmd->setEnabled(myModule->canUndo());
901 else if (aId == "REDO_CMD")
902 aCmd->setEnabled(myModule->canRedo());
904 // Enable all commands
905 aCmd->setEnabled(true);
909 foreach(QAction* aCmd, aCommands) {
910 QString aId = aCmd->data().toString();
911 if (aId == "NEW_CMD")
912 aCmd->setEnabled(true);
913 else if (aId == "EXIT_CMD")
914 aCmd->setEnabled(true);
916 aCmd->setEnabled(false);
919 myActionsMgr->update();
920 emit commandStatusUpdated();
923 void XGUI_Workshop::updateHistory()
925 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
926 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
927 emit updateUndoHistory(aUndoRes);
929 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
930 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
931 emit updateRedoHistory(aRedoRes);
934 //******************************************************
935 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
937 QDockWidget* aObjDock = new QDockWidget(theParent);
938 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
939 aObjDock->setWindowTitle(tr("Object browser"));
940 aObjDock->setStyleSheet(
941 "::title { position: relative; padding-left: 5px; text-align: left center }");
942 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
943 #ifdef ModuleDataModel
944 myObjectBrowser->setDataModel(myModule->dataModel());
946 myModule->customizeObjectBrowser(myObjectBrowser);
947 aObjDock->setWidget(myObjectBrowser);
949 myContextMenuMgr->connectObjectBrowser();
953 //******************************************************
955 * Creates dock widgets, places them in corresponding area
956 * and tabifies if necessary.
958 void XGUI_Workshop::createDockWidgets()
960 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
961 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
962 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
963 myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
964 myPropertyPanel->setupActions(myActionsMgr);
965 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
966 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
967 hidePropertyPanel(); ///<! Invisible by default
969 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
970 myPropertyPanel->installEventFilter(myOperationMgr);
972 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
973 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
975 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
976 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
977 connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
978 connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
979 myOperationMgr, SLOT(onKeyReleased(QKeyEvent*)));
980 connect(myOperationMgr, SIGNAL(validationStateChanged(bool)),
981 this, SLOT(onValidationStateChanged(bool)));
984 //******************************************************
985 void XGUI_Workshop::showPropertyPanel()
987 QAction* aViewAct = myPropertyPanel->toggleViewAction();
988 ///<! Restore ability to close panel from the window's menu
989 aViewAct->setEnabled(true);
990 myPropertyPanel->show();
991 myPropertyPanel->raise();
994 //******************************************************
995 void XGUI_Workshop::hidePropertyPanel()
997 QAction* aViewAct = myPropertyPanel->toggleViewAction();
998 ///<! Do not allow to show empty property panel
999 aViewAct->setEnabled(false);
1000 myPropertyPanel->hide();
1003 //******************************************************
1004 void XGUI_Workshop::showObjectBrowser()
1006 myObjectBrowser->parentWidget()->show();
1009 //******************************************************
1010 void XGUI_Workshop::hideObjectBrowser()
1012 myObjectBrowser->parentWidget()->hide();
1015 //******************************************************
1016 void XGUI_Workshop::salomeViewerSelectionChanged()
1018 emit salomeViewerSelection();
1021 //**************************************************************
1022 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1024 return mySalomeConnector->viewer();
1027 //**************************************************************
1028 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1030 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1031 if (theId == "DELETE_CMD")
1033 else if (theId == "MOVE_CMD")
1035 else if (theId == "COLOR_CMD")
1036 changeColor(aObjects);
1037 else if (theId == "SHOW_CMD")
1038 showObjects(aObjects, true);
1039 else if (theId == "HIDE_CMD")
1040 showObjects(aObjects, false);
1041 else if (theId == "SHOW_ONLY_CMD")
1042 showOnlyObjects(aObjects);
1043 else if (theId == "SHADING_CMD")
1044 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1045 else if (theId == "WIREFRAME_CMD")
1046 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1047 else if (theId == "HIDEALL_CMD") {
1048 QObjectPtrList aList = myDisplayer->displayedObjects();
1049 foreach (ObjectPtr aObj, aList) {
1050 if (module()->canEraseObject(aObj))
1051 aObj->setDisplayed(false);
1053 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1057 //**************************************************************
1058 void XGUI_Workshop::deleteObjects()
1060 ModuleBase_IModule* aModule = module();
1061 // 1. allow the module to delete objects, do nothing if it has succeed
1062 if (aModule->deleteObjects()) {
1063 updateCommandStatus();
1067 if (!abortAllOperations())
1069 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1070 // It is necessary to clear selection in order to avoid selection changed event during
1071 // deleteion and negative consequences connected with processing of already deleted items
1072 mySelector->clearSelection();
1073 // check whether the object can be deleted. There should not be parts which are not loaded
1074 if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1077 bool hasResult = false;
1078 bool hasFeature = false;
1079 bool hasParameter = false;
1080 bool hasSubFeature = false;
1081 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1082 if (!(hasFeature || hasParameter))
1085 // 1. start operation
1086 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1087 aDescription += tr(" %1");
1088 QStringList aObjectNames;
1089 foreach (ObjectPtr aObj, anObjects) {
1090 if (!aObj->data()->isValid())
1092 aObjectNames << QString::fromStdString(aObj->data()->name());
1094 aDescription = aDescription.arg(aObjectNames.join(", "));
1095 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1097 operationMgr()->startOperation(anOpAction);
1098 // 3. delete objects
1099 QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1100 std::set<FeaturePtr> anIgnoredFeatures;
1101 if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1102 operationMgr()->commitOperation();
1105 operationMgr()->abortOperation(operationMgr()->currentOperation());
1109 //**************************************************************
1110 void XGUI_Workshop::moveObjects()
1112 if (!abortAllOperations())
1115 SessionPtr aMgr = ModelAPI_Session::get();
1117 QString anActionId = "MOVE_CMD";
1118 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1119 aMgr->startOperation(aDescription.toStdString());
1121 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1122 DocumentPtr anActiveDocument = aMgr->activeDocument();
1124 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1125 foreach (ObjectPtr aObject, anObjects) {
1126 if (!myModule->canApplyAction(aObject, anActionId))
1129 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1130 if (aFeature.get()) {
1131 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1132 aCurrentFeature = anActiveDocument->currentFeature(true);
1135 aMgr->finishOperation();
1138 //**************************************************************
1139 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1140 const std::set<FeaturePtr>& theIgnoredFeatures,
1142 const bool theAskAboutDeleteReferences)
1146 QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1147 for (; aDIt != aDLast; ++aDIt) {
1148 aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1150 QString anInfoStr = aDInfo.join(", ");
1151 qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1154 // 1. find all referenced features
1155 std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1156 foreach (ObjectPtr aDeletedObj, theList) {
1157 XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures);
1158 std::set<FeaturePtr> aDifference;
1159 std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(),
1160 aDirectRefFeatures.begin(), aDirectRefFeatures.end(),
1161 std::inserter(aDifference, aDifference.begin()));
1162 aIndirectRefFeatures = aDifference;
1164 // 2. warn about the references remove, break the delete operation if the user chose it
1165 if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1166 QStringList aDirectRefNames;
1167 foreach(const FeaturePtr& aFeature, aDirectRefFeatures)
1168 aDirectRefNames.append(aFeature->name().c_str());
1169 QString aDirectNames = aDirectRefNames.join(", ");
1171 QStringList aIndirectRefNames;
1172 foreach(const FeaturePtr& aFeature, aIndirectRefFeatures)
1173 aIndirectRefNames.append(aFeature->name().c_str());
1174 QString aIndirectNames = aIndirectRefNames.join(", ");
1176 QMessageBox::StandardButton aRes = QMessageBox::warning(
1177 theParent, tr("Delete features"),
1178 QString(tr("Selected features are used in the following features: %1.\
1179 These features will be deleted.\n%2Would you like to continue?")).arg(aDirectNames)
1180 .arg(aIndirectNames.isEmpty() ? QString() : QString("Also these features will be deleted: %1.\n").arg(aIndirectNames)),
1181 QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1182 if (aRes != QMessageBox::Yes)
1186 // 3. remove referenced features
1187 std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1188 aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1189 std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1190 aLast = aFeaturesToDelete.end();
1194 for (; anIt != aLast; anIt++) {
1195 FeaturePtr aFeature = (*anIt);
1196 DocumentPtr aDoc = aFeature->document();
1197 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1198 aDoc->removeFeature(aFeature);
1200 anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1205 qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1209 QString anActionId = "DELETE_CMD";
1210 QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1211 QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1212 // 4. remove the parameter features
1213 foreach (ObjectPtr aObj, theList) {
1214 // features and parameters can be removed here,
1215 // the results are removed only by a corresponded feature remove
1216 std::string aGroupName = aObj->groupName();
1217 if (!anObjectGroups.contains(aGroupName.c_str()))
1220 if (!myModule->canApplyAction(aObj, anActionId))
1223 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1225 /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1226 // part features are removed in the PartSet module. This condition should be moved there
1227 if (aFeature->getKind() == "Part")
1230 DocumentPtr aDoc = aObj->document();
1231 if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1233 QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1234 anInfo.append(anInfoStr);
1235 qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1237 aDoc->removeFeature(aFeature);
1242 qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1247 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1249 bool isFoundResultType = false;
1250 foreach(ObjectPtr anObj, theObjects)
1252 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1253 if (aResult.get() == NULL)
1256 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1257 if (isFoundResultType)
1260 return isFoundResultType;
1263 //**************************************************************
1264 // Returns the list of features placed between theObject and the current feature
1265 // in the same document. Excludes theObject, includes the current feature.
1266 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1268 std::list<FeaturePtr> aResult;
1269 DocumentPtr aDocument = theObject->document();
1270 std::list<FeaturePtr> anAllFeatures = aDocument->allFeatures();
1271 // find the object iterator
1272 std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1273 if (aObjectIt == anAllFeatures.end())
1275 // find the current feature iterator
1276 std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1277 if (aCurrentIt == anAllFeatures.end())
1279 // check the right order
1280 if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1282 // exclude the object
1283 std::advance(aObjectIt, 1);
1284 // include the current feature
1285 std::advance(aCurrentIt, 1);
1286 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1289 bool XGUI_Workshop::canMoveFeature()
1291 QString anActionId = "MOVE_CMD";
1293 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1294 QObjectPtrList aValidatedObjects;
1295 foreach (ObjectPtr aObject, aObjects) {
1296 if (myModule->canApplyAction(aObject, anActionId))
1297 aValidatedObjects.append(aObject);
1299 if (aValidatedObjects.size() != aObjects.size())
1300 aObjects = aValidatedObjects;
1302 bool aCanMove = !aObjects.empty();
1304 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1305 for (; anIt != aLast && aCanMove; anIt++) {
1306 ObjectPtr aObject = *anIt;
1307 // 1. Get features placed between selected and current in the document
1308 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1309 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1310 if (aFeaturesBetween.empty())
1313 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1314 // 2. Get all reference features to the selected object in the document
1315 std::set<FeaturePtr> aRefFeatures;
1316 XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1318 if (aRefFeatures.empty())
1321 // 3. Find any placed features in all reference features
1322 std::set<FeaturePtr> aIntersectionFeatures;
1323 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1324 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1325 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1326 // 4. Return false if any reference feature is placed before curent feature
1327 if (!aIntersectionFeatures.empty())
1335 //**************************************************************
1336 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1338 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1339 if (!aCanBeShaded) {
1340 ResultCompSolidPtr aCompsolidResult =
1341 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1342 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1343 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1344 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1347 return aCanBeShaded;
1350 //**************************************************************
1351 bool XGUI_Workshop::canChangeColor() const
1353 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1355 std::set<std::string> aTypes;
1356 aTypes.insert(ModelAPI_ResultGroup::group());
1357 aTypes.insert(ModelAPI_ResultConstruction::group());
1358 aTypes.insert(ModelAPI_ResultBody::group());
1359 aTypes.insert(ModelAPI_ResultPart::group());
1361 return hasResults(aObjects, aTypes);
1364 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1366 if (!theResult.get())
1369 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1370 if (aColorAttr.get() != NULL) {
1371 if (!aColorAttr->size()) {
1372 aColorAttr->setSize(3);
1374 aColorAttr->setValue(0, theColor[0]);
1375 aColorAttr->setValue(1, theColor[1]);
1376 aColorAttr->setValue(2, theColor[2]);
1380 //**************************************************************
1381 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1383 AttributeIntArrayPtr aColorAttr;
1384 // 1. find the current color of the object. This is a color of AIS presentation
1385 // The objects are iterated until a first valid color is found
1386 std::vector<int> aColor;
1387 foreach(ObjectPtr anObject, theObjects) {
1388 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1389 if (aResult.get()) {
1390 XGUI_CustomPrs::getResultColor(aResult, aColor);
1393 // TODO: remove the obtaining a color from the AIS object
1394 // this does not happen never because:
1395 // 1. The color can be changed only on results
1396 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1397 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1398 if (anAISObj.get()) {
1400 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1403 if (!aColor.empty())
1406 if (aColor.size() != 3)
1409 // 2. show the dialog to change the value
1410 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1411 aDlg->setColor(aColor);
1412 aDlg->move(QCursor::pos());
1413 bool isDone = aDlg->exec() == QDialog::Accepted;
1417 bool isRandomColor = aDlg->isRandomColor();
1419 // 3. abort the previous operation and start a new one
1420 SessionPtr aMgr = ModelAPI_Session::get();
1421 bool aWasOperation = aMgr->isOperation(); // keep this value
1422 if (!aWasOperation) {
1423 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1424 aMgr->startOperation(aDescription.toStdString());
1427 // 4. set the value to all results
1428 std::vector<int> aColorResult = aDlg->getColor();
1429 foreach(ObjectPtr anObj, theObjects) {
1430 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1431 if (aResult.get() != NULL) {
1432 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1433 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1434 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++)
1435 setColor(aCompsolidResult->subResult(i), aColorResult);
1437 setColor(aResult, aColorResult);
1441 aMgr->finishOperation();
1442 updateCommandStatus();
1445 //**************************************************************
1446 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1447 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1448 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1450 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1452 foreach (ObjectPtr aObj, theList) {
1454 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1456 DocumentPtr aDoc = aPartRes->partDoc();
1457 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1458 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1459 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1462 aObj->setDisplayed(isVisible);
1465 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1468 //**************************************************************
1469 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1471 // Hide all displayed objects
1472 QObjectPtrList aList = myDisplayer->displayedObjects();
1473 foreach (ObjectPtr aObj, aList) {
1474 if (module()->canEraseObject(aObj))
1475 aObj->setDisplayed(false);
1478 // Show only objects from the list
1479 foreach (ObjectPtr aObj, theList) {
1481 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1483 DocumentPtr aDoc = aPartRes->partDoc();
1484 SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1485 SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1486 SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1489 aObj->setDisplayed(true);
1492 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1497 //**************************************************************
1498 void XGUI_Workshop::registerValidators() const
1500 SessionPtr aMgr = ModelAPI_Session::get();
1501 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1504 //**************************************************************
1505 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1509 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1510 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1513 //**************************************************************
1514 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1516 for (int i = 0; i < theDoc->size(theGroup); i++)
1517 theDoc->object(theGroup, i)->setDisplayed(true);
1518 //displayObject(theDoc->object(theGroup, i));
1519 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1522 //**************************************************************
1523 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1525 foreach(ObjectPtr aObj, theList) {
1526 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1528 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1529 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1530 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1531 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1532 (XGUI_Displayer::DisplayMode)theMode, false);
1536 if (theList.size() > 0)
1537 myDisplayer->updateViewer();
1540 //**************************************************************
1541 void XGUI_Workshop::closeDocument()
1543 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1544 while (anOperation) {
1545 anOperation->abort();
1546 anOperation = operationMgr()->currentOperation();
1548 myDisplayer->closeLocalContexts();
1549 myDisplayer->eraseAll();
1550 objectBrowser()->clearContent();
1552 module()->closeDocument();
1554 SessionPtr aMgr = ModelAPI_Session::get();
1558 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1560 XGUI_HistoryMenu* aMenu = NULL;
1561 if (isSalomeMode()) {
1562 QAction* anAction = qobject_cast<QAction*>(theObject);
1565 aMenu = new XGUI_HistoryMenu(anAction);
1567 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
1568 aMenu = new XGUI_HistoryMenu(aButton);
1570 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1571 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1574 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1576 QList<ActionInfo> aResult;
1577 std::list<std::string>::const_iterator it = theList.cbegin();
1578 for (; it != theList.cend(); it++) {
1579 QString anId = QString::fromStdString(*it);
1580 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1582 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1585 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1586 if (aContextMenuAct) {
1587 anInfo.initFrom(aContextMenuAct);
1589 anInfo = myActionsMgr->actionInfoById(anId);
1592 anInfo.text = anInfo.text.prepend("Modify ");