1 // Copyright (C) 2014-2017 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include "XGUI_Workshop.h"
23 #include "XGUI_ActionsMgr.h"
24 #include "XGUI_MenuMgr.h"
25 #include "XGUI_ColorDialog.h"
26 #include "XGUI_DeflectionDialog.h"
27 #include "XGUI_TransparencyWidget.h"
28 #include "XGUI_ContextMenuMgr.h"
29 #include "XGUI_Displayer.h"
30 #include "XGUI_ErrorDialog.h"
31 #include "XGUI_ErrorMgr.h"
32 #include "XGUI_ModuleConnector.h"
33 #include "XGUI_ObjectsBrowser.h"
34 #include "XGUI_OperationMgr.h"
35 #include "XGUI_PropertyPanel.h"
36 #include "XGUI_PropertyDialog.h"
37 #include "XGUI_SalomeConnector.h"
38 #include "XGUI_Selection.h"
39 #include "XGUI_SelectionMgr.h"
40 #include "XGUI_Tools.h"
41 #include "XGUI_ViewerProxy.h"
42 #include "XGUI_WorkshopListener.h"
43 #include <XGUI_CustomPrs.h>
44 #include <XGUI_HistoryMenu.h>
45 #include <XGUI_QtEvents.h>
46 #include <XGUI_DataModel.h>
49 #include <AppElements_Button.h>
50 #include <AppElements_Command.h>
51 #include <AppElements_MainMenu.h>
52 #include <AppElements_MainWindow.h>
53 #include <AppElements_MenuGroupPanel.h>
54 #include <AppElements_Viewer.h>
55 #include <AppElements_Workbench.h>
58 #include <ModelAPI_AttributeDocRef.h>
59 #include <ModelAPI_AttributeIntArray.h>
60 #include <ModelAPI_AttributeDouble.h>
61 #include <ModelAPI_Data.h>
62 #include <ModelAPI_Events.h>
63 #include <ModelAPI_Feature.h>
64 #include <ModelAPI_Object.h>
65 #include <ModelAPI_ResultBody.h>
66 #include <ModelAPI_ResultConstruction.h>
67 #include <ModelAPI_ResultGroup.h>
68 #include <ModelAPI_ResultParameter.h>
69 #include <ModelAPI_ResultField.h>
70 #include <ModelAPI_Session.h>
71 #include <ModelAPI_Validator.h>
72 #include <ModelAPI_ResultCompSolid.h>
73 #include <ModelAPI_Tools.h>
75 //#include <PartSetPlugin_Part.h>
77 #include <Events_Loop.h>
78 #include <Events_InfoMessage.h>
79 #include <Events_LongOp.h>
81 #include <ModuleBase_IModule.h>
82 #include <ModuleBase_IViewer.h>
83 #include <ModuleBase_Operation.h>
84 #include <ModuleBase_OperationDescription.h>
85 #include <ModuleBase_PageBase.h>
86 #include <ModuleBase_Preferences.h>
87 #include <ModuleBase_SelectionValidator.h>
88 #include <ModuleBase_Tools.h>
89 #include <ModuleBase_WidgetFactory.h>
90 #include <ModuleBase_OperationFeature.h>
91 #include <ModuleBase_OperationAction.h>
92 #include <ModuleBase_PagedContainer.h>
93 #include <ModuleBase_WidgetValidated.h>
94 #include <ModuleBase_ModelWidget.h>
95 #include <ModuleBase_ResultPrs.h>
97 #include <Config_Common.h>
98 #include <Config_FeatureMessage.h>
99 #include <Config_ModuleReader.h>
100 #include <Config_PointerMessage.h>
101 #include <Config_PropManager.h>
102 #include <Config_DataModelReader.h>
103 #include <Config_Translator.h>
104 #include <Config_WidgetAPI.h>
105 #include <Config_Keywords.h>
107 #include <SUIT_ResourceMgr.h>
109 #include <AIS_Trihedron.hxx>
110 #ifdef BEFORE_TRIHEDRON_PATCH
111 #include <AIS_Point.hxx>
112 #include <AIS_Axis.hxx>
115 #include <QApplication>
116 #include <QFileDialog>
117 #include <QMessageBox>
118 #include <QMdiSubWindow>
119 #include <QMainWindow>
120 #include <QPushButton>
121 #include <QDockWidget>
126 #include <QToolButton>
128 #include <QDesktopWidget>
133 #include <CDF_Session.hxx>
134 #include <CDF_Application.hxx>
135 #include <inspector/TInspector_Communicator.hxx>
136 #include <inspector/VInspector_CallBack.hxx>
137 static TInspector_Communicator* MyTCommunicator;
138 static Handle(VInspector_CallBack) MyVCallBack;
153 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
155 //#define DEBUG_DELETE
156 //#define DEBUG_FEATURE_NAME
157 //#define DEBUG_CLEAN_HISTORY
159 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
161 myCurrentDir(QString()),
163 mySalomeConnector(theConnector),
167 //myViewerSelMode(TopAbs_FACE)
169 mySelector = new XGUI_SelectionMgr(this);
170 myModuleConnector = new XGUI_ModuleConnector(this);
171 myOperationMgr = new XGUI_OperationMgr(this, 0);
172 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
173 // Has to be defined first in order to get errors and messages from other components
174 myEventsListener = new XGUI_WorkshopListener(aWorkshop);
176 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
178 myMainWindow = new AppElements_MainWindow();
180 bool aCloc = aResMgr->booleanValue("language", "locale", true);
182 QLocale::setDefault( QLocale::c() );
184 QLocale::setDefault( QLocale::system() );
186 QString aPath = Config_XMLReader::pluginConfigFile().c_str();
191 aLangs << "*_en.ts"; // load by default eng translations
192 QString aCurrLang = aResMgr->stringValue("language", "language", "en");
193 if(aCurrLang != "en") {
194 aLangs << "*_" + aCurrLang + ".ts"; // then replace with translated files
197 foreach(QString aLang, aLangs) {
198 QStringList aFilters;
200 QStringList aTsFiles = aDir.entryList(aFilters, QDir::Files);
201 foreach(QString aFileName, aTsFiles) {
202 Config_Translator::load(aFileName.toStdString());
206 myDataModelXMLReader = new Config_DataModelReader();
207 //myDataModelXMLReader->readAll();
209 myDisplayer = new XGUI_Displayer(this);
211 connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
213 myActionsMgr = new XGUI_ActionsMgr(this);
214 myMenuMgr = new XGUI_MenuMgr(this);
215 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
216 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
217 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
218 SLOT(onContextMenuCommand(const QString&, bool)));
220 myViewerProxy = new XGUI_ViewerProxy(this);
221 //connect(myViewerProxy, SIGNAL(selectionChanged()),
222 // myActionsMgr, SLOT(updateOnViewSelection()));
224 myOperationMgr->setWorkshop(aWorkshop);
226 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
228 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
229 SLOT(onOperationResumed(ModuleBase_Operation*)));
230 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
231 SLOT(onOperationStopped(ModuleBase_Operation*)));
232 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
233 SLOT(onOperationCommitted(ModuleBase_Operation*)));
234 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
235 SLOT(onOperationAborted(ModuleBase_Operation*)));
238 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
239 onTrihedronVisibilityChanged(true);
242 connect(myEventsListener, SIGNAL(errorOccurred(std::shared_ptr<Events_InfoMessage>)),
243 myErrorDlg, SLOT(addError(std::shared_ptr<Events_InfoMessage>)));
245 //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
246 // Config_Prop::Color, "225,225,225");
248 Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
249 Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
250 Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
251 Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
252 Config_PropManager::registerProp("Visualization", "result_construction_color",
253 "Construction color",
255 ModelAPI_ResultConstruction::DEFAULT_COLOR());
256 Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
257 Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
258 Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
259 Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
261 if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "face-selection", true))
262 myViewerSelMode.append(TopAbs_FACE);
263 if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "edge-selection", true))
264 myViewerSelMode.append(TopAbs_EDGE);
265 if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "vertex-selection", true))
266 myViewerSelMode.append(TopAbs_VERTEX);
267 //IMP: an attempt to use result selection with other selection modes
268 myViewerSelMode.append(ModuleBase_ResultPrs::Sel_Result);//TopAbs_VERTEX);
269 myViewerSelMode.append(TopAbs_COMPSOLID);
272 //******************************************************
273 XGUI_Workshop::~XGUI_Workshop(void)
276 #ifdef MISSED_TRANSLATION
277 // Save Missed translations
278 Config_Translator::saveMissedTranslations();
283 delete myDataModelXMLReader;
286 //******************************************************
287 void XGUI_Workshop::startApplication()
289 //Initialize event listening
290 myEventsListener->initializeEventListening();
292 myDataModelXMLReader->readAll();
295 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
296 Config_Prop::Directory, "");
298 std::string aDir = getenv(QString("%1Resources").arg(
299 ModuleBase_Preferences::resourceMgr()->appName()).toLatin1());
300 Config_PropManager::registerProp("Plugins", "import_initial_path", "Import initial directory",
301 Config_Prop::Directory, aDir);
304 Config_PropManager::registerProp("Plugins", "create_part_by_start", "Create Part by Start",
305 Config_Prop::Boolean, "false");
307 registerValidators();
309 // Calling of loadCustomProps before activating module is required
310 // by Config_PropManger to restore user-defined path to plugins
311 ModuleBase_Preferences::loadCustomProps();
315 myMainWindow->show();
316 updateCommandStatus();
321 myViewerProxy->connectViewProxy();
322 connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
323 SLOT(onTrihedronVisibilityChanged(bool)));
325 emit applicationStarted();
328 bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
330 module()->launchOperation("Part", false);
335 void XGUI_Workshop::activateModule()
337 myModule->activateSelectionFilters();
339 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
340 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
341 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
342 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
344 updateCommandStatus();
346 // TODO: get default selection mode
348 // activate visualized objects in the viewer
349 activateObjectsSelection(displayer()->displayedObjects());
350 myOperationMgr->activate();
353 void XGUI_Workshop::deactivateModule()
355 myModule->deactivateSelectionFilters();
357 // remove internal displayer filter
358 displayer()->deactivateSelectionFilters();
360 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
361 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
362 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
363 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
365 XGUI_Displayer* aDisplayer = displayer();
366 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
367 aDisplayer->deactivateObjects(aDisplayed, true);
368 Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
369 Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aDisplayer->getTrihedron());
370 /// deactivate trihedron in selection modes
371 TColStd_ListOfInteger aTColModes;
372 aContext->ActivatedModes(aTrihedron, aTColModes);
373 TColStd_ListIteratorOfListOfInteger itr( aTColModes );
374 for (; itr.More(); itr.Next() ) {
375 Standard_Integer aMode = itr.Value();
376 aContext->Deactivate(aTrihedron, aMode);
378 #ifdef BEFORE_TRIHEDRON_PATCH
379 /// Trihedron problem: objects stayed in the viewer, should be removed manually
380 /// otherwise in SALOME happens crash by HideAll in the viewer
381 aContext->Remove(aTrihedron->Position(), true);
382 aContext->Remove(aTrihedron->Axis(), true);
383 aContext->Remove(aTrihedron->XAxis(), true);
384 aContext->Remove(aTrihedron->YAxis(), true);
387 myOperationMgr->deactivate();
390 //******************************************************
391 void XGUI_Workshop::initMenu()
393 myContextMenuMgr->createActions();
396 // Create only Undo, Redo commands
397 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
398 tr("Undo last command"),
399 QIcon(":pictures/undo.png"),
400 QKeySequence::Undo, false,
402 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
403 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
405 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
406 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
408 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
409 QIcon(":pictures/redo.png"), QKeySequence::Redo,
410 false, "MEN_DESK_EDIT");
411 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
413 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
414 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
416 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
417 //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"),
418 // tr("Rebuild data objects"),
419 // QIcon(":pictures/rebuild.png"), QKeySequence(),
420 // false, "MEN_DESK_EDIT");
421 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
423 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
424 //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
426 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."),
427 tr("Export the current document into a native file"),
428 QIcon(), QKeySequence(),
429 false, "MEN_DESK_FILE");
430 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
432 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."),
433 tr("Import native file"),
434 QIcon(), QKeySequence(),
435 false, "MEN_DESK_FILE");
436 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
437 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
440 // File commands group
441 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
443 AppElements_Command* aCommand;
445 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
446 QIcon(":pictures/save.png"), QKeySequence::Save);
447 aCommand->connectTo(this, SLOT(onSave()));
448 //aCommand->disable();
450 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
451 QIcon(":pictures/save.png"), QKeySequence());
452 aCommand->connectTo(this, SLOT(onSaveAs()));
454 QString aUndoId = "UNDO_CMD";
455 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
456 QIcon(":pictures/undo.png"), QKeySequence::Undo);
457 aCommand->connectTo(this, SLOT(onUndo()));
458 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
459 addHistoryMenu(aUndoButton,
460 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
463 QString aRedoId = "REDO_CMD";
464 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
465 QIcon(":pictures/redo.png"), QKeySequence::Redo);
466 aCommand->connectTo(this, SLOT(onRedo()));
467 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
468 addHistoryMenu(aRedoButton,
469 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
472 //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
473 // QIcon(":pictures/rebuild.png"), QKeySequence());
474 //aCommand->connectTo(this, SLOT(onRebuild()));
476 //aCommand->disable();
478 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
479 QIcon(":pictures/open.png"), QKeySequence::Open);
480 aCommand->connectTo(this, SLOT(onOpen()));
482 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
483 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
484 aCommand->connectTo(this, SLOT(onPreferences()));
486 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
487 QIcon(":pictures/close.png"), QKeySequence::Close);
488 aCommand->connectTo(this, SLOT(onExit()));
493 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
495 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
496 return aMenuBar->addWorkbench(theName);
500 //******************************************************
501 QMainWindow* XGUI_Workshop::desktop() const
504 return salomeConnector()->desktop();
510 //******************************************************
511 void XGUI_Workshop::onStartWaiting()
513 if (Events_LongOp::isPerformed()) {
514 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
518 //******************************************************
519 void XGUI_Workshop::onAcceptActionClicked()
521 QAction* anAction = dynamic_cast<QAction*>(sender());
522 XGUI_OperationMgr* anOperationMgr = operationMgr();
523 if (anOperationMgr) {
524 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
525 (anOperationMgr->currentOperation());
527 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
528 myOperationMgr->commitOperation();
533 //******************************************************
534 void XGUI_Workshop::onPreviewActionClicked()
536 ModuleBase_IPropertyPanel* aPanel = propertyPanel();
538 ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
539 if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
540 anActiveWidget->storeValue();
543 std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
544 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
545 Events_Loop::loop()->send(aMsg);
548 //******************************************************
549 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
551 if (!myModule->canActivateSelection(theObject)) {
552 if (myDisplayer->isActive(theObject)) {
553 QObjectPtrList anObjects;
554 anObjects.append(theObject);
555 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
560 //******************************************************
561 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
563 bool aHasNested = false;
564 std::string aFeatureKind = theFeature->getKind();
566 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
567 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
570 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
571 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
572 if (aCommand && aCommand->button()->additionalButtonWidget())
578 void XGUI_Workshop::fillPropertyPanel(ModuleBase_Operation* theOperation)
580 ModuleBase_OperationFeature* aFOperation =
581 dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
586 myPropertyPanel->cleanContent();
588 QList<ModuleBase_ModelWidget*> aWidgets;
589 if (!module()->createWidgets(theOperation, aWidgets)) {
590 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
591 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
592 aFactory.createWidget(myPropertyPanel->contentWidget());
593 aWidgets = aFactory.getModelWidgets();
596 // check compatibility of feature and widgets
597 FeaturePtr aFeature = aFOperation->feature();
598 std::string aFeatureKind = aFeature->getKind();
599 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
600 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
601 std::string anErrorMsg = "The feature '%1' has no attribute '%2' used by widget '%3'.";
602 Events_InfoMessage("XGUI_Workshop", anErrorMsg)
603 .arg(aFeatureKind).arg(aWidget->attributeID())
604 .arg(aWidget->metaObject()->className()).send();
605 myPropertyPanel->cleanContent();
609 // for performance purpose, flush should be done after all controls are filled
610 bool isUpdateFlushed = false;
611 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
612 bool isStoreValue = !aFOperation->isEditOperation() &&
613 !aWidget->getDefaultValue().empty() &&
614 !aWidget->isComputedDefault();
615 aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
617 aWidget->restoreValue();
618 aWidget->enableFocusProcessing();
620 // update visible state of Preview button
621 std::shared_ptr<Config_FeatureMessage> aFeatureInfo;
623 aFeatureInfo = mySalomeConnector->featureInfo(aFeatureKind.c_str());
625 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
626 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
628 aFeatureInfo = aCommand->featureMessage();
630 bool anIsAutoPreview = true;
631 if (aFeatureInfo.get())
632 anIsAutoPreview = aFeatureInfo->isAutoPreview();
634 std::string aXmlCfg, aDescription;
635 module()->getXMLRepresentation(aFeatureKind, aXmlCfg, aDescription);
636 ModuleBase_WidgetFactory aFactory(aXmlCfg, moduleConnector());
637 anIsAutoPreview = aFactory.widgetAPI()->getBooleanAttribute(FEATURE_AUTO_PREVIEW, true);
640 if (!anIsAutoPreview) {
641 myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
642 // send signal about preview should not be computed automatically, click on preview
643 // button should initiate it
644 std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
645 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
646 Events_Loop::loop()->send(aMsg);
648 // if update happens after preview is blocked, it does nothing when blocked
649 // it improves performance for valid objects on feature start
650 ModuleBase_Tools::flushUpdated(aFeature);
652 myPropertyPanel->setModelWidgets(aWidgets);
653 aFOperation->setPropertyPanel(myPropertyPanel);
655 myModule->propertyPanelDefined(theOperation);
657 #ifndef DEBUG_FEATURE_NAME
658 myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
660 std::string aFeatureName = aFeature->name();
661 myPropertyPanel->setWindowTitle(QString("%1: %2")
662 .arg(theOperation->getDescription()->description())
663 .arg(aFeatureName.c_str()));
666 myErrorMgr->setPropertyPanel(myPropertyPanel);
669 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
671 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
672 if (aPropertyPanel) {
673 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
674 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
675 myModule->connectToPropertyPanel(aWidget, isToConnect);
677 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
678 connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
679 connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
682 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
683 disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
684 disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
690 //******************************************************
691 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
693 setGrantedFeatures(theOperation);
695 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
696 fillPropertyPanel(theOperation);
697 connectToPropertyPanel(true);
699 updateCommandStatus();
701 myModule->operationResumed(theOperation);
705 //******************************************************
706 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
708 updateCommandStatus();
710 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
715 ModuleBase_ISelection* aSel = mySelector->selection();
716 QObjectPtrList aObj = aSel->selectedPresentations();
717 //!< No need for property panel
719 myPropertyPanel->cleanContent();
721 connectToPropertyPanel(false);
722 myModule->operationStopped(aFOperation);
724 // the deactivated objects of the current operation should be activated back.
725 // They were deactivated on operation start or an object redisplay
726 QObjectPtrList anObjects;
727 FeaturePtr aFeature = aFOperation->feature();
728 if (aFeature.get()) { // feature may be not created (plugin load fail)
729 if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
730 anObjects.append(aFeature);
731 std::list<ResultPtr> aResults;
732 ModelAPI_Tools::allResults(aFeature, aResults);
733 std::list<ResultPtr>::const_iterator aIt;
734 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
735 ResultPtr anObject = *aIt;
736 if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
737 anObjects.append(anObject);
741 activateObjectsSelection(anObjects);
745 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
747 myModule->operationCommitted(theOperation);
750 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
752 myModule->operationAborted(theOperation);
755 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
757 ModuleBase_OperationFeature* aFOperation =
758 dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
762 QStringList aGrantedIds;
763 if (isSalomeMode()) {
764 const std::shared_ptr<Config_FeatureMessage>& anInfo =
765 mySalomeConnector->featureInfo(theOperation->id());
767 aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
768 .split(" ", QString::SkipEmptyParts);
771 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
773 ModuleBase_IModule* aModule = module();
775 aModule->grantedOperationIds(theOperation, aGrantedIds);
777 aFOperation->setGrantedOperationIds(aGrantedIds);
780 //******************************************************
781 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
783 QApplication::restoreOverrideCursor();
784 SessionPtr aMgr = ModelAPI_Session::get();
786 std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
787 std::list<DocumentPtr>::const_iterator aIt;
788 for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
789 std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
790 (*aIt)->storeNodesState(aState);
793 aMgr->save(theName.toLatin1().constData(), theFileNames);
795 QApplication::restoreOverrideCursor();
798 //******************************************************
799 bool XGUI_Workshop::abortAllOperations()
801 return myOperationMgr->abortAllOperations();
804 //******************************************************
805 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
807 setGrantedFeatures(theOperation);
808 if (!theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
809 updateCommandStatus();
812 myModule->operationStarted(theOperation);
816 //******************************************************
817 void XGUI_Workshop::onOpen()
819 if(!abortAllOperations())
821 //save current file before close if modified
822 SessionPtr aSession = ModelAPI_Session::get();
823 if (aSession->isModified()) {
824 //TODO(sbh): re-launch the app?
825 int anAnswer = QMessageBox::question(
826 desktop(), tr("Save current file"),
827 tr("The document is modified, save before opening another?"),
828 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
829 if (anAnswer == QMessageBox::Save) {
831 } else if (anAnswer == QMessageBox::Cancel) {
837 //show file dialog, check if readable and open
838 QString aDirectory = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
839 openDirectory(aDirectory);
842 //******************************************************
843 void XGUI_Workshop::openDirectory(const QString& theDirectory)
845 myCurrentDir = theDirectory;
846 if (myCurrentDir.isEmpty())
849 QFileInfo aFileInfo(myCurrentDir);
850 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
851 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
856 QApplication::setOverrideCursor(Qt::WaitCursor);
857 module()->closeDocument();
858 SessionPtr aSession = ModelAPI_Session::get();
859 aSession->closeAll();
860 aSession->load(myCurrentDir.toLatin1().constData());
861 myObjectBrowser->rebuildDataTree();
863 // Open first level of data tree
864 DocumentPtr aRootDoc = aSession->moduleDocument();
865 std::list<bool> aStates;
866 aRootDoc->restoreNodesState(aStates);
867 myObjectBrowser->setStateForDoc(aRootDoc, aStates);
869 updateCommandStatus();
871 myMainWindow->setCurrentDir(myCurrentDir, true);
873 QApplication::restoreOverrideCursor();
876 //******************************************************
877 void XGUI_Workshop::onNew()
879 QApplication::setOverrideCursor(Qt::WaitCursor);
880 if (objectBrowser() == 0) {
882 mySelector->connectViewers();
884 myViewerProxy->connectToViewer();
887 myMainWindow->showPythonConsole();
888 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
889 aWnd->showMaximized();
890 updateCommandStatus();
892 myContextMenuMgr->connectViewer();
893 QApplication::restoreOverrideCursor();
897 //******************************************************
898 void XGUI_Workshop::onExit()
900 SessionPtr aMgr = ModelAPI_Session::get();
901 if (aMgr->isModified()) {
902 int anAnswer = QMessageBox::question(
903 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
904 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
905 if (anAnswer == QMessageBox::Save) {
906 bool saved = onSave();
910 } else if (anAnswer == QMessageBox::Cancel) {
917 //******************************************************
918 void XGUI_Workshop::onPreferences()
920 ModuleBase_Prefs aModif;
921 ModuleBase_Preferences::editPreferences(aModif);
922 if (aModif.size() > 0) {
924 foreach (ModuleBase_Pref aPref, aModif)
926 aSection = aPref.first;
927 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
928 myMainWindow->viewer()->updateFromResources();
929 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
930 myMainWindow->menuObject()->updateFromResources();
933 displayer()->redisplayObjects();
938 //******************************************************
939 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
941 XGUI_Displayer* aDisplayer = displayer();
943 aDisplayer->displayTrihedron(theState);
946 //******************************************************
947 bool XGUI_Workshop::onSave()
949 if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
951 if (myCurrentDir.isEmpty()) {
954 std::list<std::string> aFiles;
955 saveDocument(myCurrentDir, aFiles);
956 updateCommandStatus();
958 myMainWindow->setModifiedState(false);
963 //******************************************************
964 bool XGUI_Workshop::onSaveAs()
966 if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
968 QFileDialog dialog(desktop());
969 dialog.setWindowTitle(tr("Select directory to save files..."));
970 dialog.setFileMode(QFileDialog::Directory);
971 dialog.setFilter(QDir::AllDirs);
972 dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
973 dialog.setViewMode(QFileDialog::Detail);
975 if (!dialog.exec()) {
979 QString aTempDir = dialog.selectedFiles().first();
981 if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
982 int answer = QMessageBox::question(
984 // Title of the dialog which asks user if he wants to save study
985 // in existing non-empty folder
987 tr("The directory already contains some files, save anyway?"),
988 QMessageBox::Save | QMessageBox::Cancel);
989 if (answer == QMessageBox::Cancel) {
993 myCurrentDir = aTempDir;
995 myMainWindow->setCurrentDir(myCurrentDir, false);
996 myMainWindow->setModifiedState(false);
1001 //******************************************************
1002 void XGUI_Workshop::onUndo(int theTimes)
1004 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1005 SessionPtr aMgr = ModelAPI_Session::get();
1006 std::list<std::string> aUndoList = aMgr->undoList();
1007 if (aMgr->isOperation()) {
1008 /// this is important for nested operations
1009 /// when sketch operation is active, this condition is false and
1010 /// the sketch operation is not aborted
1011 operationMgr()->onAbortOperation();
1013 std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
1014 for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
1016 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1017 myObjectBrowser->rebuildDataTree();
1020 operationMgr()->updateApplyOfOperations();
1021 updateCommandStatus();
1024 //******************************************************
1025 void XGUI_Workshop::onRedo(int theTimes)
1027 // the viewer update should be blocked in order to avoid the features blinking. For the created
1028 // feature a results are created, the flush of the created signal caused the viewer redisplay for
1029 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1030 // until redo of all possible objects happens
1031 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1033 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1034 SessionPtr aMgr = ModelAPI_Session::get();
1035 std::list<std::string> aRedoList = aMgr->redoList();
1036 if (aMgr->isOperation()) {
1037 /// this is important for nested operations
1038 /// when sketch operation is active, this condition is false and
1039 /// the sketch operation is not aborted
1040 operationMgr()->onAbortOperation();
1042 std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
1043 for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
1045 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1046 myObjectBrowser->rebuildDataTree();
1048 operationMgr()->updateApplyOfOperations();
1049 updateCommandStatus();
1051 // unblock the viewer update functionality and make update on purpose
1052 myDisplayer->enableUpdateViewer(isUpdateEnabled);
1053 myDisplayer->updateViewer();
1056 //******************************************************
1057 //void XGUI_Workshop::onRebuild()
1059 // SessionPtr aMgr = ModelAPI_Session::get();
1060 // bool aWasOperation = aMgr->isOperation(); // keep this value
1061 // if (!aWasOperation) {
1062 // aMgr->startOperation("Rebuild");
1064 // static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1065 // Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1066 // new Events_Message(aRebuildEvent, this)));
1067 // if (!aWasOperation) {
1068 // aMgr->finishOperation();
1070 // updateCommandStatus();
1073 //******************************************************
1074 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1076 ModuleBase_ModelWidget* anActiveWidget = 0;
1077 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1079 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1081 anActiveWidget = aPanel->activeWidget();
1084 operationMgr()->onValidateOperation();
1086 myModule->widgetStateChanged(thePreviousState);
1089 //******************************************************
1090 void XGUI_Workshop::onValuesChanged()
1092 ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1093 if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1096 ModuleBase_ModelWidget* anActiveWidget = 0;
1097 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1099 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1101 anActiveWidget = aPanel->activeWidget();
1103 if (anActiveWidget) {
1104 ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1106 if (aWidgetValidated)
1107 aWidgetValidated->clearValidatedCash();
1111 void XGUI_Workshop::onWidgetObjectUpdated()
1113 operationMgr()->onValidateOperation();
1116 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1118 QString libName = QString::fromStdString(library(theModule.toStdString()));
1119 if (libName.isEmpty()) {
1120 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1125 CREATE_FUNC crtInst = 0;
1128 HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1132 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1133 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1134 QString aMsg((char*) &lpMsgBuf);
1135 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1136 ::LocalFree(lpMsgBuf);
1138 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1142 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1143 | FORMAT_MESSAGE_IGNORE_INSERTS,
1144 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1145 QString aMsg((char*) &lpMsgBuf);
1146 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1147 ::LocalFree(lpMsgBuf);
1151 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1153 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1155 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1157 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1162 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1164 if (!err.isEmpty()) {
1166 Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1168 qWarning(qPrintable(err));
1174 //******************************************************
1175 bool XGUI_Workshop::createModule()
1177 Config_ModuleReader aModuleReader;
1178 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1179 myModule = loadModule(moduleName);
1183 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1184 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1185 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1186 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1188 myModule->createFeatures();
1190 salomeConnector()->createFeatureActions();
1192 //myActionsMgr->update();
1196 //******************************************************
1197 void XGUI_Workshop::updateCommandStatus()
1199 QList<QAction*> aCommands;
1201 aCommands = salomeConnector()->commandList();
1203 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1204 foreach (AppElements_Command* aCmd, aMenuBar->features())
1205 aCommands.append(aCmd);
1207 SessionPtr aMgr = ModelAPI_Session::get();
1208 if (aMgr->hasModuleDocument()) {
1209 foreach(QAction* aCmd, aCommands) {
1210 QString aId = aCmd->data().toString();
1211 if (aId == "UNDO_CMD")
1212 aCmd->setEnabled(myModule->canUndo());
1213 else if (aId == "REDO_CMD")
1214 aCmd->setEnabled(myModule->canRedo());
1216 // Enable all commands
1217 aCmd->setEnabled(true);
1221 foreach(QAction* aCmd, aCommands) {
1222 QString aId = aCmd->data().toString();
1223 if (aId == "NEW_CMD")
1224 aCmd->setEnabled(true);
1225 else if (aId == "EXIT_CMD")
1226 aCmd->setEnabled(true);
1228 aCmd->setEnabled(false);
1231 myActionsMgr->updateCommandsStatus();
1232 emit commandStatusUpdated();
1235 void XGUI_Workshop::updateHistory()
1237 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1238 QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1239 emit updateUndoHistory(aUndoRes);
1241 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1242 QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1243 emit updateRedoHistory(aRedoRes);
1246 //******************************************************
1247 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1249 QDockWidget* aObjDock = new QDockWidget(theParent);
1250 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1251 Qt::RightDockWidgetArea |
1252 Qt::BottomDockWidgetArea);
1253 aObjDock->setWindowTitle(tr("Object browser"));
1254 aObjDock->setStyleSheet(
1255 "::title { position: relative; padding-left: 5px; text-align: left center }");
1256 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1257 myObjectBrowser->setXMLReader(myDataModelXMLReader);
1258 myModule->customizeObjectBrowser(myObjectBrowser);
1259 aObjDock->setWidget(myObjectBrowser);
1261 myContextMenuMgr->connectObjectBrowser();
1265 //******************************************************
1267 * Creates dock widgets, places them in corresponding area
1268 * and tabifies if necessary.
1270 void XGUI_Workshop::createDockWidgets()
1272 QMainWindow* aDesktop = desktop();
1273 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1274 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1275 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1276 myPropertyPanel->setupActions(myActionsMgr);
1277 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1278 Qt::RightDockWidgetArea |
1279 Qt::BottomDockWidgetArea);
1280 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1281 hidePropertyPanel(); ///<! Invisible by default
1282 hideObjectBrowser();
1283 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1284 myPropertyPanel->installEventFilter(myOperationMgr);
1286 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1287 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1289 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1290 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1292 QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1293 connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1295 connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1296 myOperationMgr, SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1297 connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1298 myOperationMgr, SLOT(onProcessEnter(QObject*)));
1301 //******************************************************
1302 void XGUI_Workshop::showPropertyPanel()
1304 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1305 ///<! Restore ability to close panel from the window's menu
1306 aViewAct->setEnabled(true);
1307 myPropertyPanel->show();
1308 myPropertyPanel->raise();
1310 // The next code is necessary to made the property panel the active window
1311 // in order to operation manager could process key events of the panel.
1312 // otherwise they are ignored. It happens only if the same(activateWindow) is
1313 // not happened by property panel activation(e.g. resume operation of Sketch)
1314 ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1317 //******************************************************
1318 void XGUI_Workshop::hidePropertyPanel()
1320 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1321 ///<! Do not allow to show empty property panel
1322 aViewAct->setEnabled(false);
1323 myPropertyPanel->hide();
1325 // the property panel is active window of the desktop, when it is
1326 // hidden, it is undefined which window becomes active. By this reason
1327 // it is defined to perform the desktop as the active window.
1328 // in SALOME mode, workstack made the PyConsole the active window,
1329 // set the focus on it. As a result, shortcuts of the application, like
1330 // are processed by this console. For example Undo actions.
1331 // It is possible that this code is to be moved to SHAPER package
1332 QMainWindow* aDesktop = desktop();
1333 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1336 //******************************************************
1337 void XGUI_Workshop::showObjectBrowser()
1339 if (!isSalomeMode())
1340 myObjectBrowser->parentWidget()->show();
1343 //******************************************************
1344 void XGUI_Workshop::hideObjectBrowser()
1346 if (!isSalomeMode())
1347 myObjectBrowser->parentWidget()->hide();
1350 //******************************************************
1351 void XGUI_Workshop::salomeViewerSelectionChanged()
1353 emit salomeViewerSelection();
1356 //**************************************************************
1357 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1359 return mySalomeConnector->viewer();
1362 //**************************************************************
1363 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1365 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1366 if (theId == "DELETE_CMD")
1368 else if (theId == "CLEAN_HISTORY_CMD")
1370 else if (theId == "MOVE_CMD")
1372 else if (theId == "COLOR_CMD")
1373 changeColor(aObjects);
1374 else if (theId == "DEFLECTION_CMD")
1375 changeDeflection(aObjects);
1376 #ifdef USE_TRANSPARENCY
1377 else if (theId == "TRANSPARENCY_CMD")
1378 changeTransparency(aObjects);
1380 else if (theId == "SHOW_CMD") {
1381 showObjects(aObjects, true);
1382 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1383 updateCommandStatus();
1385 else if (theId == "HIDE_CMD") {
1386 showObjects(aObjects, false);
1387 updateCommandStatus();
1389 else if (theId == "SHOW_ONLY_CMD") {
1390 showOnlyObjects(aObjects);
1391 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1392 updateCommandStatus();
1394 else if (theId == "SHADING_CMD")
1395 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1396 else if (theId == "WIREFRAME_CMD")
1397 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1398 else if (theId == "HIDEALL_CMD") {
1399 QObjectPtrList aList = myDisplayer->displayedObjects();
1400 foreach (ObjectPtr aObj, aList) {
1401 if (module()->canEraseObject(aObj))
1402 aObj->setDisplayed(false);
1404 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1406 //issue #2159 Hide all incomplete behavior
1407 viewer()->eraseAll();
1409 updateCommandStatus();
1410 } else if (theId == "SELECT_VERTEX_CMD") {
1411 setViewerSelectionMode(TopAbs_VERTEX);
1412 } else if (theId == "SELECT_EDGE_CMD") {
1413 setViewerSelectionMode(TopAbs_EDGE);
1414 } else if (theId == "SELECT_FACE_CMD") {
1415 setViewerSelectionMode(TopAbs_FACE);
1416 } else if (theId == "INSERT_FOLDER_CMD") {
1417 insertFeatureFolder();
1418 } else if (theId == "ADD_TO_FOLDER_BEFORE_CMD") {
1419 insertToFolder(true);
1420 } else if (theId == "ADD_TO_FOLDER_AFTER_CMD") {
1421 insertToFolder(false);
1422 } else if (theId == "ADD_OUT_FOLDER_BEFORE_CMD") {
1423 moveOutFolder(true);
1424 } else if (theId == "ADD_OUT_FOLDER_AFTER_CMD") {
1425 moveOutFolder(false);
1426 } else if (theId == "SELECT_RESULT_CMD") {
1427 //setViewerSelectionMode(-1);
1428 //IMP: an attempt to use result selection with other selection modes
1429 setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1430 setViewerSelectionMode(TopAbs_COMPSOLID);
1431 } else if (theId == "SHOW_RESULTS_CMD") {
1432 highlightResults(aObjects);
1433 } else if (theId == "SHOW_FEATURE_CMD") {
1434 highlightFeature(aObjects);
1437 else if (theId == "TINSPECTOR_VIEW") {
1438 Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1439 if (!anApplication.IsNull())
1441 if (!MyTCommunicator)
1443 MyTCommunicator = new TInspector_Communicator();
1445 NCollection_List<Handle(Standard_Transient)> aParameters;
1446 aParameters.Append(anApplication);
1447 Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1448 if (!aContext.IsNull())
1449 aParameters.Append(aContext);
1451 MyVCallBack = new VInspector_CallBack();
1452 myDisplayer->setCallBack(MyVCallBack);
1454 AppElements_Viewer* aViewer = mainWindow()->viewer();
1456 aViewer->setCallBack(MyVCallBack);
1458 aParameters.Append(MyVCallBack);
1460 MyTCommunicator->RegisterPlugin("TKDFBrowser");
1461 MyTCommunicator->RegisterPlugin("TKShapeView");
1462 MyTCommunicator->RegisterPlugin("TKVInspector");
1463 MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1464 //MyTCommunicator->RegisterPlugin("TKSMBrowser"); // custom plugin to view ModelAPI
1466 MyTCommunicator->Init(aParameters);
1467 MyTCommunicator->Activate("TKSMBrowser"); // to have button in TInspector
1468 MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1469 MyTCommunicator->Activate("TKDFBrowser");
1471 MyTCommunicator->SetVisible(true);
1477 //**************************************************************
1478 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1481 myViewerSelMode.clear();
1483 if (myViewerSelMode.contains(theMode))
1484 myViewerSelMode.removeAll(theMode);
1486 myViewerSelMode.append(theMode);
1488 activateObjectsSelection(myDisplayer->displayedObjects());
1491 //**************************************************************
1492 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1495 module()->activeSelectionModes(aModes);
1496 if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1497 aModes.append(myViewerSelMode);
1498 myDisplayer->activateObjects(aModes, theList);
1501 //**************************************************************
1502 void XGUI_Workshop::deleteObjects()
1504 ModuleBase_IModule* aModule = module();
1505 // allow the module to delete objects, do nothing if it has succeed
1506 if (aModule->deleteObjects()) {
1507 updateCommandStatus();
1511 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1512 if (!abortAllOperations())
1515 bool hasResult = false;
1516 bool hasFeature = false;
1517 bool hasParameter = false;
1518 bool hasCompositeOwner = false;
1519 bool hasResultInHistory = false;
1520 bool hasFolder = false;
1521 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1522 hasResultInHistory, hasFolder);
1523 if (!(hasFeature || hasParameter || hasFolder))
1527 std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1528 std::set<FeaturePtr> aFeatures;
1529 ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1530 ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1532 std::set<FolderPtr> aFolders;
1533 ModuleBase_Tools::convertToFolders(anObjects, aFolders);
1536 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1537 aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1538 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1540 operationMgr()->startOperation(anOpAction);
1542 std::set<FeaturePtr> aFeatureRefsToDelete;
1543 if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1544 // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1545 // It is necessary to clear selection in order to avoid selection changed event during
1546 // deletion and negative consequences connected with processing of already deleted items
1547 mySelector->clearSelection();
1549 if (!aFeatureRefsToDelete.empty())
1550 aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1551 aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1553 if (aFolders.size() > 0) {
1554 std::set<FolderPtr>::const_iterator anIt = aFolders.begin(),
1555 aLast = aFolders.end();
1556 for (; anIt != aLast; anIt++) {
1557 FolderPtr aFolder = *anIt;
1558 if (aFolder.get()) {
1559 DocumentPtr aDoc = aFolder->document();
1560 aDoc->removeFolder(aFolder);
1566 operationMgr()->commitOperation();
1568 operationMgr()->abortOperation(operationMgr()->currentOperation());
1571 //**************************************************************
1572 void addRefsToFeature(const FeaturePtr& theFeature,
1573 const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1574 std::set<FeaturePtr>& theReferences)
1576 //if (theReferences.find(theFeature) != theReferences.end())
1578 if (theMainList.find(theFeature) == theMainList.end())
1579 return; // this feature is not in the selection list, so exists without references to it
1580 std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1582 std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1583 aLast = aMainReferences.end();
1584 for (; anIt != aLast; anIt++) {
1585 FeaturePtr aRefFeature = *anIt;
1586 if (theReferences.find(aRefFeature) == theReferences.end())
1587 theReferences.insert(aRefFeature);
1588 addRefsToFeature(aRefFeature, theMainList, theReferences);
1592 //**************************************************************
1593 void XGUI_Workshop::cleanHistory()
1595 if (!abortAllOperations())
1598 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1599 std::set<FeaturePtr> aFeatures;
1600 ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1602 #ifdef DEBUG_CLEAN_HISTORY
1604 std::set<FeaturePtr>::const_iterator aFIt;
1605 for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1606 FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1607 anInfo.append(aFeature->name().c_str());
1609 QString anInfoStr = anInfo.join(";\t");
1610 qDebug(QString("cleanHistory for: [%1] - %2").
1611 arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1614 std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1615 ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1616 // find for each object whether all reference values are in the map as key, that means that there
1617 // is no other reference in the model to this object, so it might be removed by cleaning history
1618 // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - cann't be deleted, dependency to bool_1
1619 // ext_1(bool_1, sk_3) - cann't be deleted, dependency to bool_1
1621 // sk_2(ext_2) + (bool_1) - cann't be deleted, dependency to bool_1
1622 // ext_2(bool_1) - cann't be deleted, dependency to bool_1
1624 // Information: bool_1 is not selected
1625 std::set<FeaturePtr> anUnusedObjects;
1626 std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1627 aMainLast = aReferences.end();
1628 for (; aMainIt != aMainLast; aMainIt++) {
1629 FeaturePtr aMainListFeature = aMainIt->first;
1630 std::set<FeaturePtr> aMainRefList = aMainIt->second;
1631 std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
1632 aRefLast = aMainRefList.end();
1633 bool aFeatureOutOfTheList = false;
1634 for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1635 FeaturePtr aRefFeature = *aRefIt;
1636 aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1638 if (!aFeatureOutOfTheList)
1639 anUnusedObjects.insert(aMainListFeature);
1642 #ifdef DEBUG_CLEAN_HISTORY
1644 for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1645 FeaturePtr aFeature = *aFIt;
1646 anInfo.append(aFeature->name().c_str());
1648 qDebug(QString("unused objects: [%1] - %2").
1649 arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1652 // warn about the references remove, break the delete operation if the user chose it
1653 if (!anUnusedObjects.empty()) {
1655 foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1656 aNames.append(aFeature->name().c_str());
1659 QString anUnusedNames = aNames.join(", ");
1661 QString anActionId = "CLEAN_HISTORY_CMD";
1662 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1664 QMessageBox aMessageBox(desktop());
1665 aMessageBox.setWindowTitle(aDescription);
1666 aMessageBox.setIcon(QMessageBox::Warning);
1667 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1668 aMessageBox.setDefaultButton(QMessageBox::No);
1670 const char* aKeyStr = "Unused features are the following: "
1671 "%1.\nThese features will be deleted.\nWould you like to continue?";
1672 QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
1673 aMessageBox.setText(aText);
1674 if (aMessageBox.exec() == QMessageBox::No)
1677 // 1. start operation
1678 aDescription += "by deleting of " +
1679 aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1680 ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1681 operationMgr()->startOperation(anOpAction);
1683 // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1684 // It is necessary to clear selection in order to avoid selection changed event during
1685 // deletion and negative consequences connected with processing of already deleted items
1686 mySelector->clearSelection();
1688 std::set<FeaturePtr> anIgnoredFeatures;
1689 if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
1690 operationMgr()->commitOperation();
1693 operationMgr()->abortOperation(operationMgr()->currentOperation());
1697 QString anActionId = "CLEAN_HISTORY_CMD";
1698 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1700 QMessageBox aMessageBox(desktop());
1701 aMessageBox.setWindowTitle(aDescription);
1702 aMessageBox.setIcon(QMessageBox::Warning);
1703 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1704 aMessageBox.setDefaultButton(QMessageBox::No);
1707 aMessageBox.setStandardButtons(QMessageBox::Ok);
1708 aMessageBox.setDefaultButton(QMessageBox::Ok);
1710 aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1711 aMessageBox.setText(aText);
1713 if (aMessageBox.exec() == QMessageBox::No)
1718 //**************************************************************
1719 void XGUI_Workshop::moveObjects()
1721 if (!abortAllOperations())
1724 SessionPtr aMgr = ModelAPI_Session::get();
1726 QString anActionId = "MOVE_CMD";
1727 QString aDescription = contextMenuMgr()->action(anActionId)->text();
1728 aMgr->startOperation(aDescription.toStdString());
1730 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1731 // It is necessary to clear selection in order to avoid selection changed event during
1732 // moving and negative consequences connected with processing of already moved items
1733 mySelector->clearSelection();
1734 // check whether the object can be moved. There should not be parts which are not loaded
1735 std::set<FeaturePtr> aFeatures;
1736 ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1737 if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
1740 DocumentPtr anActiveDocument = aMgr->activeDocument();
1741 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1742 std::set<FeaturePtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1743 for (; anIt != aLast; anIt++) {
1744 FeaturePtr aFeature = *anIt;
1745 if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
1748 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1749 aCurrentFeature = anActiveDocument->currentFeature(true);
1751 aMgr->finishOperation();
1754 //**************************************************************
1755 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
1757 std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1758 std::set<FeaturePtr> aFeatures;
1759 ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
1761 return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
1764 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1766 bool isFoundResultType = false;
1767 foreach(ObjectPtr anObj, theObjects)
1769 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1770 if (aResult.get() == NULL)
1773 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1774 if (isFoundResultType)
1777 return isFoundResultType;
1780 //**************************************************************
1781 // Returns the list of all features for theDocument and all features of
1782 // all nested parts.
1783 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1785 std::list<FeaturePtr> aResultList;
1786 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1787 foreach (const FeaturePtr& aFeature, anAllFeatures) {
1788 // The order of appending features of the part and the part itself is important
1790 // Append features from a part feature
1791 std::list<ResultPtr> aResults;
1792 ModelAPI_Tools::allResults(aFeature, aResults);
1793 foreach (const ResultPtr& aResult, aResults) {
1794 ResultPartPtr aResultPart =
1795 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1796 if (aResultPart.get() && aResultPart->partDoc().get()) {
1798 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1799 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1803 aResultList.push_back(aFeature);
1808 //**************************************************************
1809 // Returns the list of features placed between theObject and the current feature
1810 // in the same document. Excludes theObject, includes the current feature.
1811 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1813 std::list<FeaturePtr> aResult;
1814 DocumentPtr aDocument = theObject->document();
1815 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1816 // find the object iterator
1817 std::list<FeaturePtr>::iterator aObjectIt =
1818 std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1819 if (aObjectIt == anAllFeatures.end())
1821 // find the current feature iterator
1822 std::list<FeaturePtr>::iterator aCurrentIt =
1823 std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1824 if (aCurrentIt == anAllFeatures.end())
1826 // check the right order
1827 if (std::distance(aObjectIt, anAllFeatures.end()) <=
1828 std::distance(aCurrentIt, anAllFeatures.end()))
1830 // exclude the object
1831 std::advance(aObjectIt, 1);
1832 // include the current feature
1833 std::advance(aCurrentIt, 1);
1834 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1837 bool XGUI_Workshop::canMoveFeature()
1839 QString anActionId = "MOVE_CMD";
1841 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1842 QObjectPtrList aValidatedObjects;
1843 foreach (ObjectPtr aObject, aObjects) {
1844 if (!myModule->canApplyAction(aObject, anActionId))
1846 // To be moved feature should be in active document
1847 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1849 aValidatedObjects.append(aObject);
1851 if (aValidatedObjects.size() != aObjects.size())
1852 aObjects = aValidatedObjects;
1854 bool aCanMove = !aObjects.empty();
1856 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1857 for (; anIt != aLast && aCanMove; anIt++) {
1858 ObjectPtr aObject = *anIt;
1859 // 1. Get features placed between selected and current in the document
1860 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1861 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1862 if (aFeaturesBetween.empty())
1865 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1866 // 2. Get all reference features to the selected object in the document
1867 std::set<FeaturePtr> aRefFeatures;
1868 ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1870 if (aRefFeatures.empty())
1873 // 3. Find any placed features in all reference features
1874 std::set<FeaturePtr> aIntersectionFeatures;
1875 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1876 aPlacedFeatures.begin(), aPlacedFeatures.end(),
1877 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1878 // 4. Return false if any reference feature is placed before current feature
1879 if (!aIntersectionFeatures.empty())
1887 //**************************************************************
1888 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1890 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1891 if (!aCanBeShaded) {
1892 ResultCompSolidPtr aCompsolidResult =
1893 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1894 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1895 for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1896 aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1899 return aCanBeShaded;
1902 //**************************************************************
1903 bool XGUI_Workshop::canChangeProperty(const QString& theActionName) const
1905 if (theActionName == "COLOR_CMD" ||
1906 theActionName == "DEFLECTION_CMD"
1907 #ifdef USE_TRANSPARENCY
1908 || theActionName == "TRANSPARENCY_CMD"
1911 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1913 std::set<std::string> aTypes;
1914 aTypes.insert(ModelAPI_ResultGroup::group());
1915 aTypes.insert(ModelAPI_ResultConstruction::group());
1916 aTypes.insert(ModelAPI_ResultBody::group());
1917 aTypes.insert(ModelAPI_ResultPart::group());
1919 return hasResults(aObjects, aTypes);
1924 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1926 if (!theResult.get())
1929 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1930 if (aColorAttr.get() != NULL) {
1931 if (!aColorAttr->size()) {
1932 aColorAttr->setSize(3);
1934 aColorAttr->setValue(0, theColor[0]);
1935 aColorAttr->setValue(1, theColor[1]);
1936 aColorAttr->setValue(2, theColor[2]);
1940 //**************************************************************
1941 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1944 AttributeIntArrayPtr aColorAttr;
1945 // 1. find the current color of the object. This is a color of AIS presentation
1946 // The objects are iterated until a first valid color is found
1947 std::vector<int> aColor;
1948 foreach(ObjectPtr anObject, theObjects) {
1949 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1950 if (aResult.get()) {
1951 XGUI_CustomPrs::getResultColor(aResult, aColor);
1954 // TODO: remove the obtaining a color from the AIS object
1955 // this does not happen never because:
1956 // 1. The color can be changed only on results
1957 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1958 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1959 if (anAISObj.get()) {
1961 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1964 if (!aColor.empty())
1967 if (aColor.size() != 3)
1970 if (!abortAllOperations())
1972 // 2. show the dialog to change the value
1973 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1974 aDlg->setColor(aColor);
1975 aDlg->move(QCursor::pos());
1976 bool isDone = aDlg->exec() == QDialog::Accepted;
1980 bool isRandomColor = aDlg->isRandomColor();
1982 // 3. abort the previous operation and start a new one
1983 SessionPtr aMgr = ModelAPI_Session::get();
1984 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1985 aMgr->startOperation(aDescription.toStdString());
1987 // 4. set the value to all results
1988 std::vector<int> aColorResult = aDlg->getColor();
1989 foreach(ObjectPtr anObj, theObjects) {
1990 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1991 if (aResult.get() != NULL) {
1992 ResultCompSolidPtr aCompsolidResult =
1993 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1994 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1995 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1996 setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult :
1997 aDlg->getRandomColor());
2000 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2003 aMgr->finishOperation();
2004 updateCommandStatus();
2007 //**************************************************************
2008 void setDeflection(ResultPtr theResult, const double theDeflection)
2010 if (!theResult.get())
2013 AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
2014 if (aDeflectionAttr.get() != NULL)
2015 aDeflectionAttr->setValue(theDeflection);
2018 //**************************************************************
2019 void setTransparency(ResultPtr theResult, double theTransparency)
2021 if (!theResult.get())
2024 AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
2025 if (anAttribute.get() != NULL)
2026 anAttribute->setValue(theTransparency);
2029 //**************************************************************
2030 void setTransparency(double theTransparency, const QObjectPtrList& theObjects)
2032 foreach(ObjectPtr anObj, theObjects) {
2033 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2034 if (aResult.get() != NULL) {
2035 ResultCompSolidPtr aCompsolidResult =
2036 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
2037 if (aCompsolidResult.get() != NULL) { // change property for all sub-solids
2038 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2039 setTransparency(aCompsolidResult->subResult(i), theTransparency);
2042 setTransparency(aResult, theTransparency);
2047 //**************************************************************
2048 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
2050 AttributeDoublePtr aDoubleAttr;
2051 // 1. find the current property of the object. This is a property of AIS presentation
2052 // The objects are iterated until a first valid property is found
2053 double aDeflection = -1;
2054 foreach(ObjectPtr anObject, theObjects) {
2055 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2056 if (aResult.get()) {
2057 aDeflection = XGUI_CustomPrs::getResultDeflection(aResult);
2060 // TODO: remove the obtaining a property from the AIS object
2061 // this does not happen never because:
2062 // 1. The property can be changed only on results
2063 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2064 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2065 if (anAISObj.get()) {
2066 aDeflection = anAISObj->getDeflection();
2069 if (aDeflection > 0)
2072 if (aDeflection < 0)
2075 if (!abortAllOperations())
2077 // 2. show the dialog to change the value
2078 XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
2079 aDlg->setDeflection(aDeflection);
2080 aDlg->move(QCursor::pos());
2081 bool isDone = aDlg->exec() == QDialog::Accepted;
2085 // 3. abort the previous operation and start a new one
2086 SessionPtr aMgr = ModelAPI_Session::get();
2087 QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2088 aMgr->startOperation(aDescription.toStdString());
2090 // 4. set the value to all results
2091 aDeflection = aDlg->getDeflection();
2092 foreach(ObjectPtr anObj, theObjects) {
2093 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2094 if (aResult.get() != NULL) {
2095 ResultCompSolidPtr aCompsolidResult =
2096 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
2097 if (aCompsolidResult.get() != NULL) { // change property for all sub-solids
2098 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2099 setDeflection(aCompsolidResult->subResult(i), aDeflection);
2102 setDeflection(aResult, aDeflection);
2105 aMgr->finishOperation();
2106 updateCommandStatus();
2109 //**************************************************************
2110 void XGUI_Workshop::changeTransparency(const QObjectPtrList& theObjects)
2112 AttributeDoublePtr aDoubleAttr;
2113 // 1. find the current property of the object. This is a property of AIS presentation
2114 // The objects are iterated until a first valid property is found
2115 double aCurrentValue = -1;
2116 foreach(ObjectPtr anObject, theObjects) {
2117 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2118 if (aResult.get()) {
2119 aCurrentValue = XGUI_CustomPrs::getResultTransparency(aResult);
2122 // TODO: remove the obtaining a property from the AIS object
2123 // this does not happen never because:
2124 // 1. The property can be changed only on results
2125 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2126 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2127 if (anAISObj.get()) {
2128 aCurrentValue = anAISObj->getDeflection();
2131 if (aCurrentValue > 0)
2134 if (aCurrentValue < 0)
2137 if (!abortAllOperations())
2140 // 2. show the dialog to change the value
2141 XGUI_PropertyDialog* aDlg = new XGUI_PropertyDialog(desktop());
2142 aDlg->setWindowTitle("Transparency");
2143 XGUI_TransparencyWidget* aTransparencyWidget = new XGUI_TransparencyWidget(aDlg);
2144 connect(aTransparencyWidget, SIGNAL(transparencyValueChanged()),
2145 this, SLOT(onTransparencyValueChanged()));
2146 connect(aTransparencyWidget, SIGNAL(previewStateChanged()),
2147 this, SLOT(onPreviewStateChanged()));
2148 aDlg->setContent(aTransparencyWidget);
2149 aTransparencyWidget->setValue(aCurrentValue);
2151 // 3. abort the previous operation and start a new one
2152 SessionPtr aMgr = ModelAPI_Session::get();
2153 QString aDescription = contextMenuMgr()->action("TRANSPARENCY_CMD")->text();
2154 aMgr->startOperation(aDescription.toStdString());
2156 aDlg->move(QCursor::pos());
2157 bool isDone = aDlg->exec() == QDialog::Accepted;
2161 // 4. set the value to all results
2162 aCurrentValue = aTransparencyWidget->getValue();
2163 setTransparency(aCurrentValue, theObjects);
2165 aMgr->finishOperation();
2166 updateCommandStatus();
2169 //**************************************************************
2170 void XGUI_Workshop::onTransparencyValueChanged()
2172 XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2173 if (!aTransparencyWidget || !aTransparencyWidget->isPreviewNeeded())
2176 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2177 setTransparency(aTransparencyWidget->getValue(), anObjects);
2178 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2181 //**************************************************************
2182 void XGUI_Workshop::onPreviewStateChanged()
2184 XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2185 if (!aTransparencyWidget || !aTransparencyWidget->isPreviewNeeded())
2188 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2189 setTransparency(aTransparencyWidget->getValue(), anObjects);
2190 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2193 //**************************************************************
2194 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
2195 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
2196 aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
2198 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2200 foreach (ObjectPtr aObj, theList) {
2201 aObj->setDisplayed(isVisible);
2203 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2206 //**************************************************************
2207 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2209 // Hide all displayed objects
2210 QObjectPtrList aList = myDisplayer->displayedObjects();
2211 foreach (ObjectPtr aObj, aList) {
2212 if (module()->canEraseObject(aObj))
2213 aObj->setDisplayed(false);
2215 //Do not use eraseAll if you didn't send Redisplay event:
2216 //all objects are erased from viewer, but considered as displayed in displayer
2217 // Problem in bug 2218
2218 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2220 //issue #2159 Hide all incomplete behavior
2221 viewer()->eraseAll();
2224 // Show only objects from the list
2225 foreach (ObjectPtr aObj, theList) {
2226 aObj->setDisplayed(true);
2228 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2232 //**************************************************************
2233 void XGUI_Workshop::registerValidators() const
2235 SessionPtr aMgr = ModelAPI_Session::get();
2236 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2239 //**************************************************************
2240 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2244 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2245 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2248 //**************************************************************
2249 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2251 for (int i = 0; i < theDoc->size(theGroup); i++)
2252 theDoc->object(theGroup, i)->setDisplayed(true);
2253 //displayObject(theDoc->object(theGroup, i));
2254 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2257 //**************************************************************
2258 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2260 foreach(ObjectPtr aObj, theList) {
2261 myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
2263 ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
2264 if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2265 for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2266 myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
2267 (XGUI_Displayer::DisplayMode)theMode, false);
2271 if (theList.size() > 0)
2272 myDisplayer->updateViewer();
2275 //**************************************************************
2276 void XGUI_Workshop::closeDocument()
2278 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2279 while (anOperation) {
2280 anOperation->abort();
2281 anOperation = operationMgr()->currentOperation();
2283 //myDisplayer->closeLocalContexts();
2284 myDisplayer->eraseAll();
2285 objectBrowser()->clearContent();
2287 module()->closeDocument();
2288 // we need to clear viewer (with created filters) to do not have problems in 2nd SALOME study
2289 module()->clearViewer();
2292 // data model need not process the document's signals about objects modifications as
2293 // the document is closed
2294 //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2296 SessionPtr aMgr = ModelAPI_Session::get();
2299 //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2302 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2304 XGUI_HistoryMenu* aMenu = NULL;
2305 if (isSalomeMode()) {
2306 QAction* anAction = qobject_cast<QAction*>(theObject);
2309 aMenu = new XGUI_HistoryMenu(anAction);
2311 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
2312 aMenu = new XGUI_HistoryMenu(aButton);
2314 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2315 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2318 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2320 QList<ActionInfo> aResult;
2321 std::list<std::string>::const_iterator it = theList.cbegin();
2322 for (; it != theList.cend(); it++) {
2323 QString anId = QString::fromStdString(*it);
2324 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2326 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2329 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2330 if (aContextMenuAct) {
2331 anInfo.initFrom(aContextMenuAct);
2333 anInfo = myActionsMgr->actionInfoById(anId);
2336 anInfo.text = anInfo.text.prepend("Modify ");
2343 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2346 salomeConnector()->putInfo(theMessage, -1);
2348 myMainWindow->putInfo(theMessage, -1);
2352 void XGUI_Workshop::synchronizeViewer()
2354 SessionPtr aMgr = ModelAPI_Session::get();
2355 QList<DocumentPtr> aDocs;
2356 aDocs.append(aMgr->activeDocument());
2357 aDocs.append(aMgr->moduleDocument());
2359 foreach(DocumentPtr aDoc, aDocs) {
2360 synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2361 synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2362 synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2363 synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2367 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2368 const std::string& theGroup,
2369 bool theUpdateViewer)
2372 int aSize = theDoc->size(theGroup);
2373 for (int i = 0; i < aSize; i++) {
2374 aObj = theDoc->object(theGroup, i);
2375 if (aObj->isDisplayed()) {
2376 // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2377 // be changed to the object becomes visible when the shape becomes not empty
2378 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2379 if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2381 myDisplayer->display(aObj, false);
2384 if (theUpdateViewer)
2385 myDisplayer->updateViewer();
2388 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2390 FeaturePtr aFeature;
2391 QObjectPtrList aSelList = theObjects;
2392 bool aHasHidden = false;
2393 foreach(ObjectPtr aObj, theObjects) {
2394 aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2395 if (aFeature.get()) {
2396 std::list<ResultPtr> aResults;
2397 ModelAPI_Tools::allResults(aFeature, aResults);
2398 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2399 for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2400 aHasHidden |= (*aIt)->isConcealed();
2401 aSelList.append(*aIt);
2405 if (aSelList.count() > theObjects.count()) {
2406 // if something was found
2407 bool aBlocked = objectBrowser()->blockSignals(true);
2408 objectBrowser()->setObjectsSelected(aSelList);
2409 objectBrowser()->blockSignals(aBlocked);
2412 QMessageBox::information(desktop(), tr("Find results"),
2413 tr("Results not found"), QMessageBox::Ok);
2416 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2419 QObjectPtrList aSelList = theObjects;
2420 FeaturePtr aFeature;
2421 foreach(ObjectPtr aObj, theObjects) {
2422 aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2423 if (aResult.get()) {
2424 aFeature = ModelAPI_Feature::feature(aResult);
2425 if (aFeature.get()) {
2426 aSelList.append(aFeature);
2430 if (aSelList.count() > theObjects.count()) {
2431 // if something was found
2432 bool aBlocked = objectBrowser()->blockSignals(true);
2433 objectBrowser()->setObjectsSelected(aSelList);
2434 objectBrowser()->blockSignals(aBlocked);
2438 void XGUI_Workshop::insertFeatureFolder()
2440 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2441 if (aObjects.isEmpty())
2443 ObjectPtr aObj = aObjects.first();
2444 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2445 if (aFeature.get() == NULL)
2447 SessionPtr aMgr = ModelAPI_Session::get();
2448 DocumentPtr aDoc = aMgr->activeDocument();
2450 aMgr->startOperation();
2451 aDoc->addFolder(aFeature);
2452 aMgr->finishOperation();
2456 void XGUI_Workshop::insertToFolder(bool isBefore)
2458 std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2459 if (aFeatures.empty())
2462 SessionPtr aMgr = ModelAPI_Session::get();
2463 DocumentPtr aDoc = aMgr->activeDocument();
2465 FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
2466 aDoc->findFolderBelow(aFeatures);
2470 aMgr->startOperation();
2471 aDoc->moveToFolder(aFeatures, aFolder);
2472 aMgr->finishOperation();
2475 void XGUI_Workshop::moveOutFolder(bool isBefore)
2477 std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2478 if (aFeatures.empty())
2481 SessionPtr aMgr = ModelAPI_Session::get();
2482 DocumentPtr aDoc = aMgr->activeDocument();
2484 aMgr->startOperation();
2485 aDoc->removeFromFolder(aFeatures, isBefore);
2486 aMgr->finishOperation();