1 // Copyright (C) 2014-2019 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 email : webmaster.salome@opencascade.com
20 #include "XGUI_Workshop.h"
22 #include "XGUI_ActionsMgr.h"
23 #include "XGUI_ActiveControlMgr.h"
24 #include "XGUI_ActiveControlSelector.h"
25 #include "XGUI_MenuMgr.h"
26 #include "XGUI_ColorDialog.h"
27 #include "XGUI_DeflectionDialog.h"
28 #include "XGUI_TransparencyWidget.h"
29 #include "XGUI_ContextMenuMgr.h"
30 #include "XGUI_Displayer.h"
31 #include "XGUI_ErrorDialog.h"
32 #include "XGUI_ErrorMgr.h"
33 #include "XGUI_FacesPanel.h"
34 #include "XGUI_FacesPanelSelector.h"
35 #include "XGUI_ModuleConnector.h"
36 #include "XGUI_ObjectsBrowser.h"
37 #include "XGUI_OperationMgr.h"
38 #include "XGUI_PropertyPanel.h"
39 #include "XGUI_PropertyPanelSelector.h"
40 #include "XGUI_PropertyDialog.h"
41 #include "XGUI_SalomeConnector.h"
42 #include "XGUI_Selection.h"
43 #include "XGUI_SelectionActivate.h"
44 #include "XGUI_SelectionMgr.h"
45 #include "XGUI_Tools.h"
46 #include "XGUI_ViewerProxy.h"
47 #include "XGUI_WorkshopListener.h"
48 #include <XGUI_HistoryMenu.h>
49 #include <XGUI_QtEvents.h>
50 #include <XGUI_DataModel.h>
51 #include <XGUI_InspectionPanel.h>
52 #include <XGUI_CompressFiles.h>
55 #include <AppElements_Button.h>
56 #include <AppElements_Command.h>
57 #include <AppElements_MainMenu.h>
58 #include <AppElements_MainWindow.h>
59 #include <AppElements_MenuGroupPanel.h>
60 #include <AppElements_Viewer.h>
61 #include <AppElements_Workbench.h>
64 #include <Config_XMLReader.h>
66 #include <ModelAPI_AttributeDocRef.h>
67 #include <ModelAPI_AttributeIntArray.h>
68 #include <ModelAPI_AttributeDouble.h>
69 #include <ModelAPI_AttributeString.h>
70 #include <ModelAPI_Data.h>
71 #include <ModelAPI_Events.h>
72 #include <ModelAPI_Feature.h>
73 #include <ModelAPI_Object.h>
74 #include <ModelAPI_ResultBody.h>
75 #include <ModelAPI_ResultConstruction.h>
76 #include <ModelAPI_ResultGroup.h>
77 #include <ModelAPI_ResultParameter.h>
78 #include <ModelAPI_ResultField.h>
79 #include <ModelAPI_Session.h>
80 #include <ModelAPI_Validator.h>
81 #include <ModelAPI_Tools.h>
82 #include <ModelAPI_ResultField.h>
84 //#include <PartSetPlugin_Part.h>
86 #include <Events_Loop.h>
87 #include <Events_InfoMessage.h>
88 #include <Events_LongOp.h>
90 #include <ExchangePlugin_ExportPart.h>
91 #include <ExchangePlugin_ImportPart.h>
93 #include <GeomAPI_Pnt.h>
95 #include <ModuleBase_IModule.h>
96 #include <ModuleBase_IViewer.h>
97 #include <ModuleBase_Operation.h>
98 #include <ModuleBase_OperationDescription.h>
99 #include <ModuleBase_PageBase.h>
100 #include <ModuleBase_Preferences.h>
101 #include <ModuleBase_SelectionValidator.h>
102 #include <ModuleBase_Tools.h>
103 #include <ModuleBase_WidgetFactory.h>
104 #include <ModuleBase_OperationFeature.h>
105 #include <ModuleBase_PagedContainer.h>
106 #include <ModuleBase_WidgetValidated.h>
107 #include <ModuleBase_ModelWidget.h>
108 #include <ModuleBase_ResultPrs.h>
109 #include <ModuleBase_ActionIntParameter.h>
110 #include <ModuleBase_IStepPrs.h>
112 #include <Config_Common.h>
113 #include <Config_FeatureMessage.h>
114 #include <Config_ModuleReader.h>
115 #include <Config_PointerMessage.h>
116 #include <Config_PropManager.h>
117 #include <Config_DataModelReader.h>
118 #include <Config_Translator.h>
119 #include <Config_WidgetAPI.h>
120 #include <Config_Keywords.h>
122 #include <SUIT_ResourceMgr.h>
124 #include <AIS_Trihedron.hxx>
125 #ifdef BEFORE_TRIHEDRON_PATCH
126 #include <AIS_Point.hxx>
127 #include <AIS_Axis.hxx>
130 #include <QApplication>
131 #include <QFileDialog>
132 #include <QMessageBox>
133 #include <QMdiSubWindow>
134 #include <QMainWindow>
135 #include <QPushButton>
136 #include <QDockWidget>
141 #include <QToolButton>
143 #include <QDesktopWidget>
145 #include <QDesktopServices>
150 #include <CDF_Session.hxx>
151 #include <CDF_Application.hxx>
152 #include <inspector/TInspector_Communicator.hxx>
153 #include <inspector/VInspector_CallBack.hxx>
154 static TInspector_Communicator* MyTCommunicator;
155 static Handle(VInspector_CallBack) MyVCallBack;
170 //#define DEBUG_WITH_MESSAGE_REPORT
172 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
174 //#define DEBUG_DELETE
175 //#define DEBUG_FEATURE_NAME
176 //#define DEBUG_CLEAN_HISTORY
179 static QString MyFilter(QObject::tr("SHAPER files (*.shaper *.cadbld)"));
180 static QString MyFilter2(QObject::tr("SHAPER files (*.shaper)"));
181 static QString MyExtension(".shaper");
183 static QString MyFilter(QObject::tr("CAD Builder files (*.cadbld);;All files (*.*)"));
184 static QString MyFilter2(QObject::tr("CAD Builder files (*.cadbld)"));
185 static QString MyExtension(".cadbld");
188 static QString MyImportPartFilter(QObject::tr("Part files (*.shaperpart);;All files (*.*)"));
191 //******************************************************
192 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
195 mySalomeConnector(theConnector),
197 myInspectionPanel(0),
201 //myViewerSelMode(TopAbs_FACE)
203 mySelector = new XGUI_SelectionMgr(this);
204 myModuleConnector = new XGUI_ModuleConnector(this);
205 myOperationMgr = new XGUI_OperationMgr(this, 0);
206 ModuleBase_IWorkshop* aWorkshop = moduleConnector();
207 // Has to be defined first in order to get errors and messages from other components
208 myEventsListener = new XGUI_WorkshopListener(this);
209 mySelectionActivate = new XGUI_SelectionActivate(aWorkshop);
211 SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
213 myMainWindow = new AppElements_MainWindow();
215 bool aCloc = aResMgr->booleanValue("language", "locale", true);
217 QLocale::setDefault( QLocale::c() );
219 QLocale::setDefault( QLocale::system() );
221 QString aPath = Config_XMLReader::pluginConfigFile().c_str();
226 aLangs << "*_en.ts"; // load by default eng translations
227 QString aCurrLang = aResMgr->stringValue("language", "language", "en");
228 if(aCurrLang != "en") {
229 aLangs << "*_" + aCurrLang + ".ts"; // then replace with translated files
232 foreach(QString aLang, aLangs) {
233 QStringList aFilters;
235 QStringList aTsFiles = aDir.entryList(aFilters, QDir::Files);
236 foreach(QString aFileName, aTsFiles) {
237 Config_Translator::load(aFileName.toStdString());
241 myDataModelXMLReader = new Config_DataModelReader();
242 //myDataModelXMLReader->readAll();
244 myDisplayer = new XGUI_Displayer(this);
246 connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
248 myActionsMgr = new XGUI_ActionsMgr(this);
249 myActiveControlMgr = new XGUI_ActiveControlMgr(myModuleConnector);
250 myMenuMgr = new XGUI_MenuMgr(this);
251 myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
252 myContextMenuMgr = new XGUI_ContextMenuMgr(this);
253 connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
254 SLOT(onContextMenuCommand(const QString&, bool)));
256 myViewerProxy = new XGUI_ViewerProxy(this);
257 //connect(myViewerProxy, SIGNAL(selectionChanged()),
258 // myActionsMgr, SLOT(updateOnViewSelection()));
260 myOperationMgr->setWorkshop(aWorkshop);
262 myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
264 connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
265 SLOT(onOperationResumed(ModuleBase_Operation*)));
266 connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
267 SLOT(onOperationStopped(ModuleBase_Operation*)));
268 connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
269 SLOT(onOperationCommitted(ModuleBase_Operation*)));
270 connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
271 SLOT(onOperationAborted(ModuleBase_Operation*)));
274 connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
275 myDisplayer->displayTrihedron(true);
278 connect(myEventsListener, SIGNAL(errorOccurred(std::shared_ptr<Events_InfoMessage>)),
279 myErrorDlg, SLOT(addError(std::shared_ptr<Events_InfoMessage>)));
281 Config_PropManager::registerProp("Visualization", "selection_color", "Selection color",
282 Config_Prop::Color, "255,255,255");
284 if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "face-selection", true))
285 myViewerSelMode.append(TopAbs_FACE);
286 if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "edge-selection", true))
287 myViewerSelMode.append(TopAbs_EDGE);
288 if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "vertex-selection", true))
289 myViewerSelMode.append(TopAbs_VERTEX);
290 //IMP: an attempt to use result selection with other selection modes
291 myViewerSelMode.append(ModuleBase_ResultPrs::Sel_Result);//TopAbs_VERTEX);
292 myViewerSelMode.append(TopAbs_COMPSOLID);
295 //******************************************************
296 XGUI_Workshop::~XGUI_Workshop(void)
299 #ifdef MISSED_TRANSLATION
300 // Save Missed translations
301 Config_Translator::saveMissedTranslations();
306 delete myDataModelXMLReader;
307 delete mySelectionActivate;
312 //******************************************************
313 void XGUI_Workshop::startApplication()
315 //Initialize event listening
316 myEventsListener->initializeEventListening();
318 myDataModelXMLReader->readAll();
321 Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
322 Config_Prop::Directory, "");
324 std::string aDir = Config_XMLReader::resourcesConfigFile();
325 Config_PropManager::registerProp("Plugins", "import_initial_path", "Import initial directory",
326 Config_Prop::Directory, aDir);
329 Config_PropManager::registerProp("Plugins", "create_part_by_start", "Create Part by Start",
330 Config_Prop::Boolean, "false");
332 Config_PropManager::registerProp("Plugins", "show_hide_faces", "Show Hide Faces (on the right)",
333 Config_Prop::Boolean, "false");
335 registerValidators();
337 // Calling of loadCustomProps before activating module is required
338 // by Config_PropManger to restore user-defined path to plugins
339 ModuleBase_Preferences::loadCustomProps();
340 std::vector<int> aColor;
342 aColor = Config_PropManager::color("Visualization", "selection_color");
346 if (aColor.size() == 3)
347 myDisplayer->setSelectionColor(aColor);
352 myMainWindow->show();
353 updateCommandStatus();
358 myViewerProxy->connectViewProxy();
359 connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
360 SLOT(onTrihedronVisibilityChanged(bool)));
362 emit applicationStarted();
365 bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
367 module()->launchOperation("Part", false); // PartSetPlugin_Part::ID()
372 //******************************************************
373 void XGUI_Workshop::activateModule()
375 selectionActivate()->updateSelectionFilters();
377 connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
378 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
379 connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
380 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
382 updateCommandStatus();
384 // TODO: get default selection mode
386 // activate visualized objects in the viewer
387 activateObjectsSelection(displayer()->displayedObjects());
388 myOperationMgr->activate();
391 //******************************************************
392 void XGUI_Workshop::deactivateModule()
394 // remove internal displayer filter
395 displayer()->deactivateSelectionFilters(false);
397 disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
398 myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
399 disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
400 myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
402 XGUI_Displayer* aDisplayer = displayer();
403 QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
404 aDisplayer->deactivateObjects(aDisplayed, true);
405 selectionActivate()->deactivateTrihedronInSelectionModes();
407 #ifdef BEFORE_TRIHEDRON_PATCH
408 //Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aDisplayer->getTrihedron());
409 /// Trihedron problem: objects stayed in the viewer, should be removed manually
410 /// otherwise in SALOME happens crash by HideAll in the viewer
411 aContext->Remove(aTrihedron->Position(), true);
412 aContext->Remove(aTrihedron->Axis(), true);
413 aContext->Remove(aTrihedron->XAxis(), true);
414 aContext->Remove(aTrihedron->YAxis(), true);
417 myOperationMgr->deactivate();
420 //******************************************************
421 void XGUI_Workshop::initMenu()
423 myContextMenuMgr->createActions();
426 // Create only Undo, Redo commands
427 QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
428 tr("Undo last command"),
429 QIcon(":pictures/undo.png"),
430 QKeySequence::Undo, false,
432 QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
433 salomeConnector()->addActionInToolbar( aAction,aToolBarTitle );
435 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
436 addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
438 aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
439 QIcon(":pictures/redo.png"), QKeySequence::Redo,
440 false, "MEN_DESK_EDIT");
441 salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
443 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
444 addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
446 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
448 //aAction = salomeConnector()->addDesktopCommand("AUTOCOMPUTE_CMD", tr("Auto rebuild"),
449 // tr("Blocks immediate apply of modifications"),
450 // QIcon(":pictures/autoapply.png"), QKeySequence(),
451 // false, "MEN_DESK_EDIT");
452 //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
454 //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onAutoApply()));
456 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
459 // Add commands to a file menu
460 aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."),
461 tr("Export the current document into a native file"),
462 QIcon(), QKeySequence(),
463 false, "MEN_DESK_FILE");
464 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
466 aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."),
467 tr("Import native file"),
468 QIcon(), QKeySequence(),
469 false, "MEN_DESK_FILE");
470 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
471 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
473 aAction = salomeConnector()->addDesktopCommand("EXPORT_PART_CMD", tr("Export part..."),
474 tr("Export a part of the current document into a file"),
475 QIcon(), QKeySequence(),
476 false, "MEN_DESK_FILE");
477 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onExportPart()));
479 aAction = salomeConnector()->addDesktopCommand("IMPORT_PART_CMD", tr("Import part..."),
480 tr("Import structure of a part"),
481 QIcon(), QKeySequence(),
482 false, "MEN_DESK_FILE");
483 connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onImportPart()));
484 salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
487 // File commands group
488 AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
490 AppElements_Command* aCommand;
492 aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
493 QIcon(":pictures/save.png"), QKeySequence::Save);
494 aCommand->connectTo(this, SLOT(onSave()));
495 //aCommand->disable();
497 aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
498 QIcon(":pictures/save.png"), QKeySequence());
499 aCommand->connectTo(this, SLOT(onSaveAs()));
501 QString aUndoId = "UNDO_CMD";
502 aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
503 QIcon(":pictures/undo.png"), QKeySequence::Undo);
504 aCommand->connectTo(this, SLOT(onUndo()));
505 AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
506 addHistoryMenu(aUndoButton,
507 SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
510 QString aRedoId = "REDO_CMD";
511 aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
512 QIcon(":pictures/redo.png"), QKeySequence::Redo);
513 aCommand->connectTo(this, SLOT(onRedo()));
514 AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
515 addHistoryMenu(aRedoButton,
516 SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
519 aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
520 QIcon(":pictures/open.png"), QKeySequence::Open);
521 aCommand->connectTo(this, SLOT(onOpen()));
524 aCommand = aGroup->addFeature("AUTOCOMPUTE_CMD", tr("Auto rebuild"),
525 tr("Blocks immediate apply of modifications"),
526 QIcon(":pictures/autoapply_start.png"), QKeySequence());
527 aCommand->setChecked(ModelAPI_Session::get()->isAutoUpdateBlocked());
528 aCommand->connectTo(this, SLOT(onAutoApply()));
530 aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
531 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
532 aCommand->connectTo(this, SLOT(onPreferences()));
534 aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
535 QIcon(":pictures/close.png"), QKeySequence::Close);
536 aCommand->connectTo(this, SLOT(onExit()));
541 //******************************************************
542 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
544 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
545 return aMenuBar->addWorkbench(theName);
549 //******************************************************
550 QMainWindow* XGUI_Workshop::desktop() const
553 return salomeConnector()->desktop();
559 //******************************************************
560 void XGUI_Workshop::onStartWaiting()
562 if (Events_LongOp::isPerformed()) {
563 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
567 //******************************************************
568 void XGUI_Workshop::onAcceptActionClicked()
570 QAction* anAction = dynamic_cast<QAction*>(sender());
571 XGUI_OperationMgr* anOperationMgr = operationMgr();
572 if (anOperationMgr) {
573 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
574 (anOperationMgr->currentOperation());
576 //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
577 myOperationMgr->commitOperation();
582 //******************************************************
583 void XGUI_Workshop::onAcceptPlusActionClicked()
585 QAction* anAction = dynamic_cast<QAction*>(sender());
586 XGUI_OperationMgr* anOperationMgr = operationMgr();
587 if (anOperationMgr) {
588 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
589 (anOperationMgr->currentOperation());
591 if (myOperationMgr->commitOperation())
592 module()->launchOperation(aFOperation->id(), false);
597 //******************************************************
598 void XGUI_Workshop::onPreviewActionClicked()
600 ModuleBase_IPropertyPanel* aPanel = propertyPanel();
602 ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
603 if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
604 anActiveWidget->storeValue();
607 std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
608 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
609 Events_Loop::loop()->send(aMsg);
613 //******************************************************
614 void XGUI_Workshop::onHelpActionClicked()
616 XGUI_OperationMgr* anOperationMgr = operationMgr();
617 if (anOperationMgr) {
618 ModuleBase_Operation* aOperation = anOperationMgr->currentOperation();
620 QString aHelpPage = aOperation->helpFileName();
621 if (!aHelpPage.isEmpty()) {
623 const QChar aSep = QDir::separator();
625 // SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
627 // platform = "winapplication";
629 // platform = "application";
631 // QString aBrowserName = aResMgr->stringValue("ExternalBrowser", platform);
634 QString aDir(getenv("SHAPER_ROOT_DIR"));
635 if (!aDir.isEmpty()) {
636 aDocDir = aDir + aSep + "share" + aSep + "doc" + aSep +
637 "salome" + aSep + "gui" + aSep + "SHAPER";
640 QString aDir(getenv("CADBUILDER_ROOT_DIR"));
641 aDocDir = aDir + aSep + "doc" + aSep + "gui";
643 QString aFileName = aDocDir + aSep + aHelpPage;
644 if (QFile::exists(aFileName)) {
645 QUrl aUrl = QUrl::fromLocalFile(aFileName);
646 QDesktopServices::openUrl(aUrl);
654 //******************************************************
655 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
657 if (!myModule->canActivateSelection(theObject)) {
658 if (selectionActivate()->isActive(theObject)) {
659 QObjectPtrList anObjects;
660 anObjects.append(theObject);
661 myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
666 //******************************************************
667 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
669 bool aHasNested = false;
670 std::string aFeatureKind = theFeature->getKind();
672 XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
673 if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
676 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
677 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
678 if (aCommand && aCommand->button()->additionalButtonWidget())
684 //******************************************************
685 void XGUI_Workshop::fillPropertyPanel(ModuleBase_Operation* theOperation)
687 ModuleBase_OperationFeature* aFOperation =
688 dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
692 myPropertyPanel->cleanContent();
694 QList<ModuleBase_ModelWidget*> aWidgets;
695 QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
696 if (!module()->createWidgets(aFOperation->feature(), aXmlRepr, aWidgets)) {
697 ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
698 aFactory.createWidget(myPropertyPanel->contentWidget());
699 aWidgets = aFactory.getModelWidgets();
702 // check compatibility of feature and widgets
703 FeaturePtr aFeature = aFOperation->feature();
704 std::string aFeatureKind = aFeature->getKind();
705 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
706 if (aWidget->usesAttribute()) {
707 if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
708 std::string anErrorMsg = "The feature '%1' has no attribute '%2' used by widget '%3'.";
709 Events_InfoMessage("XGUI_Workshop", anErrorMsg)
710 .arg(aFeatureKind).arg(aWidget->attributeID())
711 .arg(aWidget->metaObject()->className()).send();
712 myPropertyPanel->cleanContent();
717 // for performance purpose, flush should be done after all controls are filled
718 bool isUpdateFlushed = false;
719 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
720 bool isStoreValue = !aFOperation->isEditOperation() &&
721 !aWidget->getDefaultValue().empty() &&
722 !aWidget->isComputedDefault();
723 aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
725 aWidget->restoreValue();
726 aWidget->enableFocusProcessing();
728 // update visible state of Preview button
729 std::shared_ptr<Config_FeatureMessage> aFeatureInfo;
731 aFeatureInfo = mySalomeConnector->featureInfo(aFeatureKind.c_str());
733 AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
734 AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
736 aFeatureInfo = aCommand->featureMessage();
738 bool anIsAutoPreview = true;
739 if (aFeatureInfo.get()) {
740 anIsAutoPreview = aFeatureInfo->isAutoPreview();
741 theOperation->setHelpFileName(aFeatureInfo->helpFileName().c_str());
743 std::string aXmlCfg, aDescription;
744 module()->getXMLRepresentation(aFeatureKind, aXmlCfg, aDescription);
745 ModuleBase_WidgetFactory aFactory(aXmlCfg, moduleConnector());
746 anIsAutoPreview = aFactory.widgetAPI()->getBooleanAttribute(FEATURE_AUTO_PREVIEW, true);
749 if (!anIsAutoPreview) {
750 myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
751 // send signal about preview should not be computed automatically, click on preview
752 // button should initiate it
753 std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
754 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
755 Events_Loop::loop()->send(aMsg);
757 // if update happens after preview is blocked, it does nothing when blocked
758 // it improves performance for valid objects on feature start
759 ModuleBase_Tools::flushUpdated(aFeature);
761 myPropertyPanel->setModelWidgets(aWidgets);
762 aFOperation->setPropertyPanel(myPropertyPanel);
764 myModule->propertyPanelDefined(theOperation);
766 #ifndef DEBUG_FEATURE_NAME
767 myPropertyPanel->setWindowTitle(ModuleBase_Tools::translate("workshop",
768 theOperation->getDescription()->description().toStdString()));
770 std::string aFeatureName = aFeature->name();
771 myPropertyPanel->setWindowTitle(QString("%1: %2")
772 .arg(translate(theOperation->getDescription()->description()))
773 .arg(translate(aFeatureName.c_str())));
776 myErrorMgr->setPropertyPanel(myPropertyPanel);
777 theOperation->setHideFacesVisible(myFacesPanel->isVisible());
778 if (aFeatureInfo.get() && aFeatureInfo->isHideFacesPanel() && !myFacesPanel->isVisible())
779 myFacesPanel->show();
780 showPanel(myPropertyPanel);
783 //******************************************************
784 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
786 XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
787 if (aPropertyPanel) {
788 const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
789 foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
790 myModule->connectToPropertyPanel(aWidget, isToConnect);
792 connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
793 connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
794 connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
797 disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
798 disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
799 disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
805 //******************************************************
806 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
808 setGrantedFeatures(theOperation);
810 if (theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
811 fillPropertyPanel(theOperation);
812 connectToPropertyPanel(true);
813 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
816 myPropertyPanel->updateApplyPlusButton(aFOperation->feature());
818 myPropertyPanel->updateApplyPlusButton(FeaturePtr());
820 updateCommandStatus();
822 myModule->operationResumed(theOperation);
825 //******************************************************
826 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
828 updateCommandStatus();
830 ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
835 ModuleBase_ISelection* aSel = mySelector->selection();
836 QObjectPtrList aObj = aSel->selectedPresentations();
837 //!< No need for property panel
838 hidePanel(myPropertyPanel);
839 myPropertyPanel->cleanContent();
841 connectToPropertyPanel(false);
842 myModule->operationStopped(aFOperation);
844 // the deactivated objects of the current operation should be activated back.
845 // They were deactivated on operation start or an object redisplay
846 QObjectPtrList anObjects;
847 FeaturePtr aFeature = aFOperation->feature();
848 if (aFeature.get()) { // feature may be not created (plugin load fail)
849 if (myDisplayer->isVisible(aFeature) && !selectionActivate()->isActive(aFeature))
850 anObjects.append(aFeature);
851 std::list<ResultPtr> aResults;
852 ModelAPI_Tools::allResults(aFeature, aResults);
853 std::list<ResultPtr>::const_iterator aIt;
854 for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
855 ResultPtr anObject = *aIt;
856 if (myDisplayer->isVisible(anObject) && !selectionActivate()->isActive(anObject)) {
857 anObjects.append(anObject);
861 activateObjectsSelection(anObjects);
863 if (!theOperation->isHideFacesVisible())
864 myFacesPanel->hide();
867 //******************************************************
868 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
870 myModule->operationCommitted(theOperation);
873 //******************************************************
874 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
876 myModule->operationAborted(theOperation);
879 //******************************************************
880 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
882 ModuleBase_OperationFeature* aFOperation =
883 dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
887 QStringList aGrantedIds;
888 if (isSalomeMode()) {
889 const std::shared_ptr<Config_FeatureMessage>& anInfo =
890 mySalomeConnector->featureInfo(theOperation->id());
892 aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
893 .split(" ", QString::SkipEmptyParts);
896 aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
898 ModuleBase_IModule* aModule = module();
900 aModule->grantedOperationIds(theOperation, aGrantedIds);
902 aFOperation->setGrantedOperationIds(aGrantedIds);
905 //******************************************************
906 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
908 QApplication::restoreOverrideCursor();
909 SessionPtr aMgr = ModelAPI_Session::get();
911 std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
912 std::list<DocumentPtr>::const_iterator aIt;
913 for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
914 std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
915 (*aIt)->storeNodesState(aState);
918 aMgr->save(theName.toLatin1().constData(), theFileNames);
920 QApplication::restoreOverrideCursor();
923 //******************************************************
924 bool XGUI_Workshop::abortAllOperations()
926 return myOperationMgr->abortAllOperations();
929 //******************************************************
930 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
932 setGrantedFeatures(theOperation);
933 if (!theOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
934 updateCommandStatus();
937 myModule->operationStarted(theOperation);
941 //******************************************************
942 void XGUI_Workshop::onOpen()
944 if(!abortAllOperations())
946 //save current file before close if modified
947 SessionPtr aSession = ModelAPI_Session::get();
948 if (aSession->isModified()) {
949 int anAnswer = QMessageBox::question(
950 desktop(), tr("Save current file"),
951 tr("The document is modified, save before opening another?"),
952 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
953 if (anAnswer == QMessageBox::Save) {
955 } else if (anAnswer == QMessageBox::Cancel) {
958 myCurrentFile = QString();
961 //show file dialog, check if readable and open
962 qreal aRatio = ModuleBase_Tools::currentPixelRatio();
963 // If the ratio is > 1 (HD screen) then QT has a bug in
964 // displaying of system open file dialog (too small)
965 QString aFile = QFileDialog::getOpenFileName(desktop(), tr("Open file"), QString(), MyFilter,
966 Q_NULLPTR, ((aRatio > 1)? QFileDialog::DontUseNativeDialog : QFileDialog::Options()));
971 //******************************************************
972 void XGUI_Workshop::openFile(const QString& theDirectory)
974 myCurrentFile = theDirectory;
975 if (myCurrentFile.isEmpty())
978 QFileInfo aFileInfo(myCurrentFile);
979 if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
980 QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
981 myCurrentFile = QString();
985 QApplication::setOverrideCursor(Qt::WaitCursor);
986 module()->closeDocument();
987 SessionPtr aSession = ModelAPI_Session::get();
988 aSession->closeAll();
991 if (!XGUI_CompressFiles::uncompress(myCurrentFile, myTmpDir.path()))
994 aSession->load(myTmpDir.path().toLatin1().constData());
995 myObjectBrowser->rebuildDataTree();
997 // Open first level of data tree
998 DocumentPtr aRootDoc = aSession->moduleDocument();
999 std::list<bool> aStates;
1000 aRootDoc->restoreNodesState(aStates);
1001 myObjectBrowser->setStateForDoc(aRootDoc, aStates);
1003 updateCommandStatus();
1005 myMainWindow->setCurrentDir(myCurrentFile, true);
1009 bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
1012 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1013 int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
1015 ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), 0);
1016 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1023 QApplication::restoreOverrideCursor();
1026 //******************************************************
1027 void XGUI_Workshop::onNew()
1029 QApplication::setOverrideCursor(Qt::WaitCursor);
1030 if (objectBrowser() == 0) {
1031 createDockWidgets();
1032 mySelector->connectViewers();
1034 myViewerProxy->connectToViewer();
1035 showObjectBrowser();
1037 myMainWindow->showPythonConsole();
1038 QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
1039 aWnd->showMaximized();
1040 updateCommandStatus();
1042 myContextMenuMgr->connectViewer();
1043 QApplication::restoreOverrideCursor();
1047 //******************************************************
1048 void XGUI_Workshop::onExit()
1050 SessionPtr aMgr = ModelAPI_Session::get();
1051 if (aMgr->isModified()) {
1052 int anAnswer = QMessageBox::question(
1053 myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
1054 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
1055 if (anAnswer == QMessageBox::Save) {
1056 bool saved = onSave();
1060 } else if (anAnswer == QMessageBox::Cancel) {
1067 //******************************************************
1068 void XGUI_Workshop::onPreferences()
1070 ModuleBase_Prefs aModif;
1071 ModuleBase_Preferences::editPreferences(aModif);
1072 if (aModif.size() > 0) {
1074 foreach (ModuleBase_Pref aPref, aModif) {
1075 aSection = aPref.first;
1076 if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1077 myMainWindow->viewer()->updateFromResources();
1078 } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1079 myMainWindow->menuObject()->updateFromResources();
1082 std::vector<int> aColor;
1084 aColor = Config_PropManager::color("Visualization", "selection_color");
1088 if (aColor.size() == 3)
1089 displayer()->setSelectionColor(aColor);
1091 displayer()->redisplayObjects();
1096 //******************************************************
1097 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
1099 XGUI_Displayer* aDisplayer = displayer();
1101 aDisplayer->displayTrihedron(theState);
1102 aDisplayer->updateViewer();
1106 //******************************************************
1107 bool XGUI_Workshop::onSave()
1109 if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
1111 if (myCurrentFile.isEmpty()) {
1114 SessionPtr aMgr = ModelAPI_Session::get();
1115 if (aMgr->isAutoUpdateBlocked())
1116 aMgr->blockAutoUpdate(false);
1118 std::list<std::string> aFiles;
1119 // issue #2899: create a temporary directory, save and then remove it
1121 std::string aTmpDir = XGUI_Tools::getTmpDirByEnv("SALOME_TMP_DIR");
1123 std::string aTmpDir = XGUI_Tools::getTmpDirByEnv("");
1125 saveDocument(QString(aTmpDir.c_str()), aFiles);
1126 bool aResult = XGUI_CompressFiles::compress(myCurrentFile, aFiles);
1127 XGUI_Tools::removeTemporaryFiles(aTmpDir, aFiles);
1130 updateCommandStatus();
1132 myMainWindow->setModifiedState(false);
1138 //******************************************************
1139 bool XGUI_Workshop::onSaveAs()
1141 if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
1143 qreal aRatio = ModuleBase_Tools::currentPixelRatio();
1144 myCurrentFile = QFileDialog::getSaveFileName(desktop(), tr("Select name to save file..."),
1145 QString(), MyFilter2,
1146 Q_NULLPTR, ((aRatio > 1) ? QFileDialog::DontUseNativeDialog : QFileDialog::Options()));
1147 if (!myCurrentFile.isNull()) {
1148 if (!myCurrentFile.endsWith(MyExtension)) {
1149 myCurrentFile += MyExtension;
1155 myMainWindow->setCurrentDir(myCurrentFile, false);
1156 myMainWindow->setModifiedState(false);
1161 //******************************************************
1162 void XGUI_Workshop::onUndo(int theTimes)
1164 processUndoRedo(ActionUndo, theTimes);
1165 myObjectBrowser->updateAllIndexes(1);
1168 //******************************************************
1169 void XGUI_Workshop::onRedo(int theTimes)
1171 processUndoRedo(ActionRedo, theTimes);
1172 myObjectBrowser->updateAllIndexes(1);
1175 //******************************************************
1176 void XGUI_Workshop::processUndoRedo(const ModuleBase_ActionType theActionType, int theTimes)
1178 ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1179 if (anActiveWidget) {
1180 ActionIntParamPtr aParam(new ModuleBase_ActionIntParameter(theTimes));
1181 if (anActiveWidget->processAction(theActionType, aParam))
1184 // the viewer update should be blocked in order to avoid the features blinking. For the created
1185 // feature a results are created, the flush of the created signal caused the viewer redisplay for
1186 // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1187 // until redo of all possible objects happens
1188 bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1190 SessionPtr aMgr = ModelAPI_Session::get();
1191 if (aMgr->isOperation()) {
1192 XGUI_OperationMgr* aOpMgr = operationMgr();
1193 /// this is important for nested operations
1194 /// when sketch operation is active, this condition is false and
1195 /// the sketch operation is not aborted
1196 if (aOpMgr->canStopOperation(aOpMgr->currentOperation()))
1197 aOpMgr->abortOperation(aOpMgr->currentOperation());
1200 myDisplayer->enableUpdateViewer(isUpdateEnabled);
1204 objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1205 std::list<std::string> anActionList = theActionType == ActionUndo ? aMgr->undoList()
1207 std::list<std::string>::const_iterator aIt = anActionList.cbegin();
1208 for (int i = 0; (i < theTimes) && (aIt != anActionList.cend()); ++i, ++aIt) {
1209 if (theActionType == ActionUndo)
1214 if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1215 myObjectBrowser->rebuildDataTree();
1217 operationMgr()->updateApplyOfOperations();
1218 facesPanel()->reset(true);
1219 updateCommandStatus();
1221 // unblock the viewer update functionality and make update on purpose
1222 myDisplayer->enableUpdateViewer(isUpdateEnabled);
1223 myDisplayer->updateViewer();
1224 // Clear messages in status bar from previous operations if exists
1225 setStatusBarMessage("");
1228 //******************************************************
1229 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1231 ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1232 //ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1233 //if (anOperation) {
1234 // ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1236 // anActiveWidget = aPanel->activeWidget();
1239 operationMgr()->onValidateOperation();
1241 myModule->widgetStateChanged(thePreviousState);
1244 //******************************************************
1245 void XGUI_Workshop::onValuesChanged()
1247 ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1248 if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1251 ModuleBase_ModelWidget* anActiveWidget = 0;
1252 ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1254 ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1256 anActiveWidget = aPanel->activeWidget();
1258 if (anActiveWidget) {
1259 ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1261 if (aWidgetValidated)
1262 aWidgetValidated->clearValidatedCash();
1266 //******************************************************
1267 void XGUI_Workshop::onWidgetObjectUpdated()
1269 operationMgr()->onValidateOperation();
1270 myDisplayer->updateViewer();
1273 //******************************************************
1274 void XGUI_Workshop::onImportPart()
1276 if (!abortAllOperations())
1279 //show file dialog, check if readable and open
1280 qreal aRatio = ModuleBase_Tools::currentPixelRatio();
1281 // If the ratio is > 1 (HD screen) then QT has a bug in
1282 // displaying of system open file dialog (too small)
1283 QString aFile = QFileDialog::getOpenFileName(desktop(), tr("Import part"), QString(),
1284 MyImportPartFilter, Q_NULLPTR,
1285 ((aRatio > 1) ? QFileDialog::DontUseNativeDialog : QFileDialog::Options()));
1286 if (!aFile.isNull()) {
1287 ModuleBase_OperationFeature* anImportPartOp = dynamic_cast<ModuleBase_OperationFeature*>(
1288 module()->createOperation(ExchangePlugin_ImportPart::ID()));
1289 if (operationMgr()->startOperation(anImportPartOp)) {
1290 // initialize the filename to be imported
1291 FeaturePtr aFeature = anImportPartOp->feature();
1292 aFeature->string(ExchangePlugin_ImportPart::FILE_PATH_ID())->setValue(aFile.toStdString());
1293 ModuleBase_Tools::flushUpdated(aFeature);
1294 operationMgr()->commitOperation();
1295 setStatusBarMessage("");
1300 //******************************************************
1301 void XGUI_Workshop::onExportPart()
1303 if (abortAllOperations()) {
1304 ModuleBase_OperationFeature* anExportPartOp = dynamic_cast<ModuleBase_OperationFeature*>(
1305 module()->createOperation(ExchangePlugin_ExportPart::ID()));
1306 operationMgr()->startOperation(anExportPartOp);
1310 //******************************************************
1311 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1313 QString libName = QString::fromStdString(library(theModule.toStdString()));
1314 if (libName.isEmpty()) {
1315 qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1320 CREATE_FUNC crtInst = 0;
1323 HINSTANCE modLib = ::LoadLibraryA(qPrintable(libName));
1327 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1328 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1329 QString aMsg((char*) &lpMsgBuf);
1330 err = QString("Failed to load %1. %2").arg(libName).arg(aMsg);
1331 ::LocalFree(lpMsgBuf);
1333 crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1337 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1338 | FORMAT_MESSAGE_IGNORE_INSERTS,
1339 0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1340 QString aMsg((char*) &lpMsgBuf);
1341 err = QString("Failed to find %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1342 ::LocalFree(lpMsgBuf);
1346 void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1348 err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1350 crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1352 err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1357 ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1359 if (!err.isEmpty()) {
1361 Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1363 qWarning(qPrintable(err));
1369 //******************************************************
1370 bool XGUI_Workshop::createModule()
1372 Config_ModuleReader aModuleReader;
1373 QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1374 myModule = loadModule(moduleName);
1378 //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1379 // myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1380 //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1381 // myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1383 myModule->createFeatures();
1385 salomeConnector()->createFeatureActions();
1387 //myActionsMgr->update();
1391 //******************************************************
1392 void XGUI_Workshop::updateCommandStatus()
1394 QList<QAction*> aCommands;
1396 aCommands = salomeConnector()->commandList();
1398 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1399 foreach (AppElements_Command* aCmd, aMenuBar->features())
1400 aCommands.append(aCmd);
1402 SessionPtr aMgr = ModelAPI_Session::get();
1403 if (aMgr->hasModuleDocument()) {
1404 foreach(QAction* aCmd, aCommands) {
1405 QString aId = aCmd->data().toString();
1406 if (aId == "UNDO_CMD") {
1407 bool isActionEnabled = false;
1408 // if ultimate is true -> using result of operation only, or using OR combination
1409 ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1410 if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled))
1411 aCmd->setEnabled(isActionEnabled);
1413 aCmd->setEnabled(myModule->canUndo());
1415 else if (aId == "REDO_CMD") {
1416 bool isActionEnabled = false;
1417 // if ultimate is true -> using result of operation only, or using OR combination
1418 ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1419 if (anActiveWidget && anActiveWidget->canProcessAction(ActionRedo, isActionEnabled))
1420 aCmd->setEnabled(isActionEnabled);
1422 aCmd->setEnabled(myModule->canRedo());
1424 else if (aId == "AUTOCOMPUTE_CMD") {
1425 aCmd->setIcon(aMgr->isAutoUpdateBlocked() ?
1426 QIcon(":pictures/autoapply_stop.png") :
1427 QIcon(":pictures/autoapply_start.png"));
1430 // Enable all commands
1431 aCmd->setEnabled(true);
1435 foreach(QAction* aCmd, aCommands) {
1436 QString aId = aCmd->data().toString();
1437 if (aId == "NEW_CMD")
1438 aCmd->setEnabled(true);
1439 else if (aId == "EXIT_CMD")
1440 aCmd->setEnabled(true);
1442 aCmd->setEnabled(false);
1445 myActionsMgr->updateCommandsStatus();
1446 emit commandStatusUpdated();
1449 //******************************************************
1450 void XGUI_Workshop::updateHistory()
1452 bool isActionEnabled = false;
1453 ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1454 QList<ActionInfo> aUndoRes;
1455 QList<ActionInfo> aRedoRes;
1456 if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled)) {
1457 aUndoRes = anActiveWidget->actionsList(ActionUndo);
1458 aRedoRes = anActiveWidget->actionsList(ActionRedo);
1460 std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1461 aUndoRes = processHistoryList(aUndoList);
1463 std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1464 aRedoRes = processHistoryList(aRedoList);
1466 emit updateUndoHistory(aUndoRes);
1467 emit updateRedoHistory(aRedoRes);
1470 //******************************************************
1471 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1473 QDockWidget* aObjDock = new QDockWidget(theParent);
1474 aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1475 Qt::RightDockWidgetArea);
1476 aObjDock->setWindowTitle(tr("Object browser"));
1477 aObjDock->setStyleSheet(
1478 "::title { position: relative; padding-left: 5px; text-align: left center }");
1479 myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1480 myObjectBrowser->initialize(myModule->rootNode());
1481 myModule->customizeObjectBrowser(myObjectBrowser);
1482 aObjDock->setWidget(myObjectBrowser);
1484 connect(myObjectBrowser, SIGNAL(sizeChanged()), SLOT(onDockSizeChanged()));
1486 myContextMenuMgr->connectObjectBrowser();
1490 //******************************************************
1492 * Creates dock widgets, places them in corresponding area
1493 * and tabifies if necessary.
1495 void XGUI_Workshop::createDockWidgets()
1497 QMainWindow* aDesktop = desktop();
1498 QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1499 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1500 myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1501 myActiveControlMgr->addSelector(new XGUI_PropertyPanelSelector(myPropertyPanel));
1503 myPropertyPanel->setupActions(myActionsMgr);
1504 myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1505 Qt::RightDockWidgetArea);
1506 aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1508 hidePanel(myPropertyPanel); ///<! Invisible by default
1510 myFacesPanel = new XGUI_FacesPanel(aDesktop, this);
1511 myActiveControlMgr->addSelector(new XGUI_FacesPanelSelector(myFacesPanel));
1512 myFacesPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1513 Qt::RightDockWidgetArea |
1514 Qt::BottomDockWidgetArea);
1515 connect(myFacesPanel, SIGNAL(closed()), myFacesPanel, SLOT(onClosed()));
1517 myInspectionPanel = new XGUI_InspectionPanel(aDesktop, this);
1518 myInspectionPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1519 Qt::RightDockWidgetArea);
1520 aDesktop->addDockWidget(Qt::RightDockWidgetArea, myInspectionPanel);
1522 myInspectionPanel->hide();
1524 aDesktop->addDockWidget(
1526 Qt::RightDockWidgetArea,
1528 Qt::LeftDockWidgetArea,
1531 hidePanel(myFacesPanel); ///<! Invisible by default
1534 bool aShowOnTheRight = Config_PropManager::boolean("Plugins", "show_hide_faces");
1535 if (aShowOnTheRight) {
1536 aDesktop->addDockWidget(Qt::RightDockWidgetArea, myFacesPanel);
1537 showPanel(myFacesPanel);
1540 hideObjectBrowser();
1544 if (!aShowOnTheRight)
1547 aDesktop->tabifyDockWidget(myFacesPanel, aObjDock);
1552 #endif // HAVE_SALOME
1554 aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1555 myPropertyPanel->installEventFilter(myOperationMgr);
1557 QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1558 connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1560 QAction* aOkContAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptPlus);
1561 connect(aOkContAct, SIGNAL(triggered()), this, SLOT(onAcceptPlusActionClicked()));
1563 QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1564 connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1566 QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1567 connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1569 QAction* aHelpAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Help);
1570 connect(aHelpAct, SIGNAL(triggered()), this, SLOT(onHelpActionClicked()));
1572 connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1573 myOperationMgr, SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1574 connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1575 myOperationMgr, SLOT(onProcessEnter(QObject*)));
1578 //******************************************************
1579 void XGUI_Workshop::showPanel(QDockWidget* theDockWidget)
1581 if (theDockWidget == myPropertyPanel) {
1582 QAction* aViewAct = myPropertyPanel->toggleViewAction();
1583 ///<! Restore ability to close panel from the window's menu
1584 aViewAct->setEnabled(true);
1586 theDockWidget->show();
1587 theDockWidget->raise();
1589 // The next code is necessary to made the property panel the active window
1590 // in order to operation manager could process key events of the panel.
1591 // otherwise they are ignored. It happens only if the same(activateWindow) is
1592 // not happened by property panel activation(e.g. resume operation of Sketch)
1593 ModuleBase_Tools::setFocus(theDockWidget, "XGUI_Workshop::showPanel()");
1596 //******************************************************
1597 void XGUI_Workshop::hidePanel(QDockWidget* theDockWidget)
1599 if (theDockWidget && theDockWidget == myPropertyPanel) {
1600 QAction* aViewAct = theDockWidget->toggleViewAction();
1601 ///<! Do not allow to show empty property panel
1602 aViewAct->setEnabled(false);
1604 theDockWidget->hide();
1606 // the property panel is active window of the desktop, when it is
1607 // hidden, it is undefined which window becomes active. By this reason
1608 // it is defined to perform the desktop as the active window.
1609 // in SALOME mode, work-stack made the PyConsole the active window,
1610 // set the focus on it. As a result, shortcuts of the application, like
1611 // are processed by this console. For example Undo actions.
1612 // It is possible that this code is to be moved to SHAPER package
1613 QMainWindow* aDesktop = desktop();
1614 ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::hidePanel()");
1617 //******************************************************
1618 void XGUI_Workshop::showObjectBrowser()
1620 if (!isSalomeMode()) {
1621 myObjectBrowser->parentWidget()->show();
1625 //******************************************************
1626 void XGUI_Workshop::hideObjectBrowser()
1628 if (!isSalomeMode())
1629 myObjectBrowser->parentWidget()->hide();
1632 //******************************************************
1633 void XGUI_Workshop::salomeViewerSelectionChanged()
1635 emit salomeViewerSelection();
1638 //**************************************************************
1639 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1641 return mySalomeConnector->viewer();
1644 //**************************************************************
1645 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1647 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1648 if (theId == "DELETE_CMD")
1650 else if (theId == "CLEAN_HISTORY_CMD")
1652 else if (theId == "MOVE_CMD")
1654 else if (theId == "COLOR_CMD")
1655 changeColor(aObjects);
1656 else if (theId == "DEFLECTION_CMD")
1657 changeDeflection(aObjects);
1658 else if (theId == "TRANSPARENCY_CMD")
1659 changeTransparency(aObjects);
1660 else if (theId == "SHOW_CMD") {
1661 showObjects(aObjects, true);
1662 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1663 updateCommandStatus();
1665 else if (theId == "HIDE_CMD") {
1666 showObjects(aObjects, false);
1667 updateCommandStatus();
1669 else if (theId == "SHOW_ONLY_CMD") {
1670 showOnlyObjects(aObjects);
1671 mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1672 updateCommandStatus();
1674 else if (theId == "SHADING_CMD")
1675 setDisplayMode(aObjects, XGUI_Displayer::Shading);
1676 else if (theId == "WIREFRAME_CMD")
1677 setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1678 else if (theId == "HIDEALL_CMD") {
1679 QObjectPtrList aList = myDisplayer->displayedObjects();
1680 foreach (ObjectPtr aObj, aList) {
1681 if (module()->canEraseObject(aObj))
1682 aObj->setDisplayed(false);
1684 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1686 //issue #2159 Hide all incomplete behavior
1687 viewer()->eraseAll();
1689 updateCommandStatus();
1690 // Necessary for update icons in ObjectBrowser on Linux
1691 myObjectBrowser->updateAllIndexes();
1692 } else if (theId == "SELECT_VERTEX_CMD") {
1693 setViewerSelectionMode(TopAbs_VERTEX);
1694 } else if (theId == "SELECT_EDGE_CMD") {
1695 setViewerSelectionMode(TopAbs_EDGE);
1696 } else if (theId == "SELECT_FACE_CMD") {
1697 setViewerSelectionMode(TopAbs_FACE);
1698 } else if (theId == "INSERT_FOLDER_CMD") {
1699 insertFeatureFolder();
1700 } else if (theId == "ADD_TO_FOLDER_BEFORE_CMD") {
1701 insertToFolder(true);
1702 } else if (theId == "ADD_TO_FOLDER_AFTER_CMD") {
1703 insertToFolder(false);
1704 } else if (theId == "ADD_OUT_FOLDER_BEFORE_CMD") {
1705 moveOutFolder(true);
1706 } else if (theId == "ADD_OUT_FOLDER_AFTER_CMD") {
1707 moveOutFolder(false);
1708 } else if (theId == "SELECT_RESULT_CMD") {
1709 //setViewerSelectionMode(-1);
1710 //IMP: an attempt to use result selection with other selection modes
1711 setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1712 setViewerSelectionMode(TopAbs_COMPSOLID);
1713 } else if (theId == "SHOW_RESULTS_CMD") {
1714 highlightResults(aObjects);
1715 } else if (theId == "SHOW_FEATURE_CMD") {
1716 highlightFeature(aObjects);
1717 } else if (theId == "SET_VIEW_NORMAL_CMD") {
1719 } else if (theId == "SET_VIEW_INVERTEDNORMAL_CMD") {
1720 setNormalView(true);
1723 else if (theId == "TINSPECTOR_VIEW") {
1724 Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1725 if (!anApplication.IsNull())
1727 if (!MyTCommunicator)
1729 MyTCommunicator = new TInspector_Communicator();
1731 NCollection_List<Handle(Standard_Transient)> aParameters;
1732 aParameters.Append(anApplication);
1733 Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1734 if (!aContext.IsNull())
1735 aParameters.Append(aContext);
1737 #ifdef DEBUG_WITH_MESSAGE_REPORT
1738 Handle(Message_Report) aContextReport = aContext->GetReport();
1739 aContext->SetReportActive (Standard_True);
1740 aContextReport->SetLimit (1000);
1741 if (!aContextReport.IsNull())
1742 aParameters.Append(aContextReport);
1744 MyVCallBack = new VInspector_CallBack();
1745 myDisplayer->setCallBack(MyVCallBack);
1747 AppElements_Viewer* aViewer = mainWindow()->viewer();
1749 aViewer->setCallBack(MyVCallBack);
1751 aParameters.Append(MyVCallBack);
1753 MyTCommunicator->RegisterPlugin("TKDFBrowser");
1754 MyTCommunicator->RegisterPlugin("TKShapeView");
1755 MyTCommunicator->RegisterPlugin("TKVInspector");
1756 #ifdef DEBUG_WITH_MESSAGE_REPORT
1757 MyTCommunicator->RegisterPlugin("TKMessageView");
1759 //MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1760 //MyTCommunicator->RegisterPlugin("TKSMBrowser"); // custom plugin to view ModelAPI
1762 MyTCommunicator->Init(aParameters);
1763 MyTCommunicator->Activate("TKSMBrowser"); // to have button in TInspector
1764 #ifndef DEBUG_WITH_MESSAGE_REPORT
1765 MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1767 MyTCommunicator->Activate("TKDFBrowser");
1769 #ifdef DEBUG_WITH_MESSAGE_REPORT
1770 MyTCommunicator->Activate("TKMessageView"); // temporary
1771 MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1774 MyTCommunicator->SetVisible(true);
1780 //**************************************************************
1781 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1784 myViewerSelMode.clear();
1786 if (myViewerSelMode.contains(theMode))
1787 myViewerSelMode.removeAll(theMode);
1789 myViewerSelMode.append(theMode);
1791 selectionActivate()->updateSelectionModes();
1794 //**************************************************************
1795 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1798 module()->activeSelectionModes(aModes);
1799 if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1800 aModes.append(myViewerSelMode);
1801 selectionActivate()->activateObjects(aModes, theList);
1804 //**************************************************************
1805 bool XGUI_Workshop::prepareForDisplay(const std::set<ObjectPtr>& theObjects) const
1807 if (facesPanel()->isEmpty())
1810 // generate container of objects taking into account sub elments of compsolid
1811 std::set<ObjectPtr> anAllProcessedObjects;
1812 for (std::set<ObjectPtr>::const_iterator anObjectsIt = theObjects.begin();
1813 anObjectsIt != theObjects.end(); anObjectsIt++) {
1814 ObjectPtr anObject = *anObjectsIt;
1815 ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
1816 if (aCompRes.get()) {
1817 std::list<ResultPtr> allRes;
1818 ModelAPI_Tools::allSubs(aCompRes, allRes);
1819 if (allRes.empty()) {
1820 anAllProcessedObjects.insert(anObject);
1822 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1823 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1824 if (aBody.get() && aBody->numberOfSubs() == 0)
1825 anAllProcessedObjects.insert(aBody);
1829 anAllProcessedObjects.insert(anObject);
1832 // find hidden objects in faces panel
1833 std::set<ObjectPtr> aHiddenObjects;
1834 QStringList aHiddenObjectNames;
1835 for (std::set<ObjectPtr>::const_iterator anObjectsIt = anAllProcessedObjects.begin();
1836 anObjectsIt != anAllProcessedObjects.end(); anObjectsIt++) {
1837 if (!facesPanel()->isObjectHiddenByPanel(*anObjectsIt))
1839 aHiddenObjects.insert(*anObjectsIt);
1840 aHiddenObjectNames.append((*anObjectsIt)->data()->name().c_str());
1842 if (aHiddenObjects.empty()) // in parameter objects there are no hidden objects in hide face
1845 int anAnswer = QMessageBox::question(
1846 desktop(), tr("Show object"),
1847 tr("'%1'\n are hidden by %2:\nRemove objects from the panel to be displayed?")
1848 .arg(aHiddenObjectNames.join(", ")).arg(facesPanel()->windowTitle()),
1849 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
1851 bool aToBeDisplayed = anAnswer == QMessageBox::Yes;
1853 facesPanel()->restoreObjects(aHiddenObjects);
1855 return aToBeDisplayed;
1858 //**************************************************************
1859 void XGUI_Workshop::deleteObjects()
1861 ModuleBase_IModule* aModule = module();
1862 // allow the module to delete objects, do nothing if it has succeed
1863 if (aModule->deleteObjects()) {
1864 updateCommandStatus();
1865 myDisplayer->updateViewer();
1869 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1870 if (!abortAllOperations())
1873 bool hasResult = false;
1874 bool hasFeature = false;
1875 bool hasParameter = false;
1876 bool hasCompositeOwner = false;
1877 bool hasResultInHistory = false;
1878 bool hasFolder = false;
1879 ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1880 hasResultInHistory, hasFolder);
1881 if (!(hasResult || hasFeature || hasParameter || hasFolder))
1884 // Remove from the list non-deletable objects: infinite constructions which are not in history
1885 bool notDelete = true;
1886 QObjectPtrList::iterator aIt;
1887 for (aIt = anObjects.begin(); aIt != anObjects.end(); aIt++) {
1888 ObjectPtr aObj = (*aIt);
1889 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
1890 FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1892 notDelete = (!aFeature->isInHistory()) && aConstr->isInfinite();
1894 anObjects.removeAll(aObj);
1900 std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1901 std::set<FeaturePtr> aFeatures;
1902 ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1903 ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1905 std::set<FolderPtr> aFolders;
1906 ModuleBase_Tools::convertToFolders(anObjects, aFolders);
1909 QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1910 aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1911 ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, module());
1913 operationMgr()->startOperation(anOpAction);
1915 std::set<FeaturePtr> aFeatureRefsToDelete;
1916 if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1917 // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1918 // It is necessary to clear selection in order to avoid selection changed event during
1919 // deletion and negative consequences connected with processing of already deleted items
1920 mySelector->clearSelection();
1922 if (!aFeatureRefsToDelete.empty())
1923 aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1924 aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1926 if (aFolders.size() > 0) {
1927 std::set<FolderPtr>::const_iterator anIt = aFolders.begin(),
1928 aLast = aFolders.end();
1929 for (; anIt != aLast; anIt++) {
1930 FolderPtr aFolder = *anIt;
1931 if (aFolder.get()) {
1932 DocumentPtr aDoc = aFolder->document();
1933 aDoc->removeFolder(aFolder);
1937 // remove results selected
1938 std::list<ResultPtr> aResults;
1939 for(QObjectPtrList::const_iterator anIt = anObjects.begin(); anIt != anObjects.end(); anIt++) {
1940 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anIt);
1941 if (aRes.get() && aRes->data()->isValid() && !aRes->data()->isDeleted() &&
1942 aRes->groupName() != ModelAPI_ResultGroup::group() && // don't remove groups and fields
1943 aRes->groupName() != ModelAPI_ResultField::group()) // because they are badly selected
1944 aResults.push_back(aRes);
1946 if (!aResults.empty()) {
1947 ModelAPI_Tools::removeResults(aResults);
1951 operationMgr()->commitOperation();
1953 operationMgr()->abortOperation(operationMgr()->currentOperation());
1955 myDisplayer->updateViewer();
1958 //**************************************************************
1959 void addRefsToFeature(const FeaturePtr& theFeature,
1960 const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1961 std::set<FeaturePtr>& theReferences)
1963 //if (theReferences.find(theFeature) != theReferences.end())
1965 if (theMainList.find(theFeature) == theMainList.end())
1966 return; // this feature is not in the selection list, so exists without references to it
1967 std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1969 std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1970 aLast = aMainReferences.end();
1971 for (; anIt != aLast; anIt++) {
1972 FeaturePtr aRefFeature = *anIt;
1973 if (theReferences.find(aRefFeature) == theReferences.end())
1974 theReferences.insert(aRefFeature);
1975 addRefsToFeature(aRefFeature, theMainList, theReferences);
1979 //**************************************************************
1980 void XGUI_Workshop::cleanHistory()
1982 if (!abortAllOperations())
1985 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1986 std::set<FeaturePtr> aFeatures;
1987 ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1989 #ifdef DEBUG_CLEAN_HISTORY
1991 std::set<FeaturePtr>::const_iterator aFIt;
1992 for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1993 FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1994 anInfo.append(aFeature->name().c_str());
1996 QString anInfoStr = anInfo.join(";\t");
1997 qDebug(QString("cleanHistory for: [%1] - %2").
1998 arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
2001 std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
2002 ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
2003 // find for each object whether all reference values are in the map as key, that means that there
2004 // is no other reference in the model to this object, so it might be removed by cleaning history
2005 // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - can't be deleted, dependency to bool_1
2006 // ext_1(bool_1, sk_3) - can't be deleted, dependency to bool_1
2008 // sk_2(ext_2) + (bool_1) - can't be deleted, dependency to bool_1
2009 // ext_2(bool_1) - can't be deleted, dependency to bool_1
2011 // Information: bool_1 is not selected
2012 std::set<FeaturePtr> anUnusedObjects;
2013 std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
2014 aMainLast = aReferences.end();
2015 for (; aMainIt != aMainLast; aMainIt++) {
2016 FeaturePtr aMainListFeature = aMainIt->first;
2017 std::set<FeaturePtr> aMainRefList = aMainIt->second;
2018 std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
2019 aRefLast = aMainRefList.end();
2020 bool aFeatureOutOfTheList = false;
2021 for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
2022 FeaturePtr aRefFeature = *aRefIt;
2023 aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
2025 if (!aFeatureOutOfTheList)
2026 anUnusedObjects.insert(aMainListFeature);
2029 #ifdef DEBUG_CLEAN_HISTORY
2031 for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
2032 FeaturePtr aFeature = *aFIt;
2033 anInfo.append(aFeature->name().c_str());
2035 qDebug(QString("unused objects: [%1] - %2").
2036 arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
2039 // warn about the references remove, break the delete operation if the user chose it
2040 if (!anUnusedObjects.empty()) {
2042 foreach (const FeaturePtr& aFeature, anUnusedObjects) {
2043 aNames.append(aFeature->name().c_str());
2046 QString anUnusedNames = aNames.join(", ");
2048 QString anActionId = "CLEAN_HISTORY_CMD";
2049 QString aDescription = ModuleBase_Tools::translate("workshop",
2050 contextMenuMgr()->action(anActionId)->text().toStdString());
2052 QMessageBox aMessageBox(desktop());
2053 aMessageBox.setWindowTitle(aDescription);
2054 aMessageBox.setIcon(QMessageBox::Warning);
2055 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2056 aMessageBox.setDefaultButton(QMessageBox::No);
2058 const char* aKeyStr = "Unused features are the following: "
2059 "%1.\nThese features will be deleted.\nWould you like to continue?";
2060 QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
2061 aMessageBox.setText(aText);
2062 if (aMessageBox.exec() == QMessageBox::No)
2065 // 1. start operation
2066 aDescription += "by deleting of " +
2067 aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
2068 ModuleBase_Operation* anOpAction = new ModuleBase_Operation(aDescription, module());
2069 operationMgr()->startOperation(anOpAction);
2071 // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
2072 // It is necessary to clear selection in order to avoid selection changed event during
2073 // deletion and negative consequences connected with processing of already deleted items
2074 mySelector->clearSelection();
2076 std::set<FeaturePtr> anIgnoredFeatures;
2077 if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
2078 operationMgr()->commitOperation();
2081 operationMgr()->abortOperation(operationMgr()->currentOperation());
2085 QString anActionId = "CLEAN_HISTORY_CMD";
2086 QString aDescription = contextMenuMgr()->action(anActionId)->text();
2088 QMessageBox aMessageBox(desktop());
2089 aMessageBox.setWindowTitle(aDescription);
2090 aMessageBox.setIcon(QMessageBox::Warning);
2091 aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2092 aMessageBox.setDefaultButton(QMessageBox::No);
2095 aMessageBox.setStandardButtons(QMessageBox::Ok);
2096 aMessageBox.setDefaultButton(QMessageBox::Ok);
2098 aText = QString(tr("All features are relevant, there is nothing to be deleted"));
2099 aMessageBox.setText(aText);
2101 if (aMessageBox.exec() == QMessageBox::No)
2106 //**************************************************************
2107 bool compareFeature(const FeaturePtr& theF1, const FeaturePtr& theF2) {
2108 DocumentPtr aDoc = theF1->document();
2109 return aDoc->index(theF1) < aDoc->index(theF2);
2111 void XGUI_Workshop::moveObjects()
2113 if (!abortAllOperations())
2116 SessionPtr aMgr = ModelAPI_Session::get();
2118 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2119 // It is necessary to clear selection in order to avoid selection changed event during
2120 // moving and negative consequences connected with processing of already moved items
2121 mySelector->clearSelection();
2122 // check whether the object can be moved. There should not be parts which are not loaded
2123 std::set<FeaturePtr> aFeatures;
2124 ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2125 if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
2128 QString anActionId = "MOVE_CMD";
2129 QString aDescription = contextMenuMgr()->action(anActionId)->text();
2130 aMgr->startOperation(aDescription.toStdString());
2132 // Sort features by index in document
2133 std::list<FeaturePtr> aFList(aFeatures.begin(), aFeatures.end());
2134 aFList.sort(compareFeature);
2136 DocumentPtr anActiveDocument = aMgr->activeDocument();
2137 FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
2138 std::list<FeaturePtr>::const_iterator anIt = aFList.begin(), aLast = aFList.end();
2139 for (; anIt != aLast; anIt++) {
2140 FeaturePtr aFeature = *anIt;
2141 if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
2144 anActiveDocument->moveFeature(aFeature, aCurrentFeature);
2145 aCurrentFeature = anActiveDocument->currentFeature(true);
2147 aMgr->finishOperation();
2148 updateCommandStatus();
2151 //**************************************************************
2152 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
2154 std::set<FeaturePtr> aFeatures;
2155 ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
2157 return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
2160 //******************************************************
2161 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
2163 bool isFoundResultType = false;
2164 foreach(ObjectPtr anObj, theObjects)
2166 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2167 if (aResult.get() == NULL)
2170 isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
2171 if (isFoundResultType)
2174 return isFoundResultType;
2177 //**************************************************************
2178 // Returns the list of all features for theDocument and all features of
2179 // all nested parts.
2180 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
2182 std::list<FeaturePtr> aResultList;
2183 std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
2184 foreach (const FeaturePtr& aFeature, anAllFeatures) {
2185 // The order of appending features of the part and the part itself is important
2187 // Append features from a part feature
2188 std::list<ResultPtr> aResults;
2189 ModelAPI_Tools::allResults(aFeature, aResults);
2190 foreach (const ResultPtr& aResult, aResults) {
2191 ResultPartPtr aResultPart =
2192 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
2193 if (aResultPart.get() && aResultPart->partDoc().get()) {
2195 std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
2196 aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
2200 aResultList.push_back(aFeature);
2205 //**************************************************************
2206 // Returns the list of features placed between theObject and the current feature
2207 // in the same document. Excludes theObject, includes the current feature.
2208 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
2210 std::list<FeaturePtr> aResult;
2211 DocumentPtr aDocument = theObject->document();
2212 std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
2213 // find the object iterator
2214 std::list<FeaturePtr>::iterator aObjectIt =
2215 std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
2216 if (aObjectIt == anAllFeatures.end())
2218 // find the current feature iterator
2219 std::list<FeaturePtr>::iterator aCurrentIt =
2220 std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
2221 if (aCurrentIt == anAllFeatures.end())
2223 // check the right order
2224 if (std::distance(aObjectIt, anAllFeatures.end()) <=
2225 std::distance(aCurrentIt, anAllFeatures.end()))
2227 // exclude the object
2228 std::advance(aObjectIt, 1);
2229 // include the current feature
2230 std::advance(aCurrentIt, 1);
2231 return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
2234 //******************************************************
2235 bool XGUI_Workshop::canMoveFeature()
2237 QString anActionId = "MOVE_CMD";
2239 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2240 QObjectPtrList aValidatedObjects;
2241 foreach (ObjectPtr aObject, aObjects) {
2242 if (!myModule->canApplyAction(aObject, anActionId))
2244 // To be moved feature should be in active document
2245 if (aObject->document() != ModelAPI_Session::get()->activeDocument())
2247 aValidatedObjects.append(aObject);
2249 if (aValidatedObjects.size() != aObjects.size())
2250 aObjects = aValidatedObjects;
2252 bool aCanMove = !aObjects.empty();
2254 QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
2255 for (; anIt != aLast && aCanMove; anIt++) {
2256 ObjectPtr aObject = *anIt;
2257 if (!aObject.get() || !aObject->data().get() || !aObject->data()->isValid()) {
2261 FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
2262 // only groups can be moved to the end for now (#2451)
2263 if (aFeat.get() && aFeat->getKind() != "Group") {
2268 // 1. Get features placed between selected and current in the document
2269 std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
2270 // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
2271 if (aFeaturesBetween.empty())
2274 std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
2275 // 2. Get all reference features to the selected object in the document
2276 std::set<FeaturePtr> aRefFeatures;
2277 ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
2279 if (aRefFeatures.empty())
2282 // 3. Find any placed features in all reference features
2283 std::set<FeaturePtr> aIntersectionFeatures;
2284 std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
2285 aPlacedFeatures.begin(), aPlacedFeatures.end(),
2286 std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
2287 // 4. Return false if any reference feature is placed before current feature
2288 if (!aIntersectionFeatures.empty())
2296 //**************************************************************
2297 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
2299 bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
2300 if (!aCanBeShaded) {
2301 ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
2302 if (aCompRes.get() != NULL) { // change colors for all sub-solids
2303 std::list<ResultPtr> allRes;
2304 ModelAPI_Tools::allSubs(aCompRes, allRes);
2305 std::list<ResultPtr>::iterator aRes = allRes.begin();
2306 for(; aRes != allRes.end() && !aCanBeShaded; aRes++) {
2307 aCanBeShaded = myDisplayer->canBeShaded(*aRes);
2311 return aCanBeShaded;
2314 //**************************************************************
2315 bool XGUI_Workshop::canChangeProperty(const QString& theActionName) const
2317 if (theActionName == "COLOR_CMD" ||
2318 theActionName == "DEFLECTION_CMD" ||
2319 theActionName == "TRANSPARENCY_CMD") {
2320 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2322 std::set<std::string> aTypes;
2323 aTypes.insert(ModelAPI_ResultGroup::group());
2324 aTypes.insert(ModelAPI_ResultConstruction::group());
2325 aTypes.insert(ModelAPI_ResultBody::group());
2326 aTypes.insert(ModelAPI_ResultPart::group());
2328 return hasResults(aObjects, aTypes);
2333 //******************************************************
2334 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
2336 if (!theResult.get())
2339 AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
2340 if (aColorAttr.get() != NULL) {
2341 if (!aColorAttr->size()) {
2342 aColorAttr->setSize(3);
2344 aColorAttr->setValue(0, theColor[0]);
2345 aColorAttr->setValue(1, theColor[1]);
2346 aColorAttr->setValue(2, theColor[2]);
2348 static const Events_ID kRedisplayEvent =
2349 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2350 ModelAPI_EventCreator::get()->sendUpdated(theResult, kRedisplayEvent);
2353 //**************************************************************
2354 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
2357 AttributeIntArrayPtr aColorAttr;
2358 // 1. find the current color of the object. This is a color of AIS presentation
2359 // The objects are iterated until a first valid color is found
2360 std::vector<int> aColor;
2361 foreach(ObjectPtr anObject, theObjects) {
2362 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2363 if (aResult.get()) {
2364 ModelAPI_Tools::getColor(aResult, aColor);
2367 // TODO: remove the obtaining a color from the AIS object
2368 // this does not happen never because:
2369 // 1. The color can be changed only on results
2370 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2371 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2372 if (anAISObj.get()) {
2374 anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
2377 if (!aColor.empty())
2380 if (aColor.size() != 3)
2383 if (!abortAllOperations())
2385 // 2. show the dialog to change the value
2386 XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
2387 aDlg->setColor(aColor);
2388 aDlg->move(QCursor::pos());
2389 bool isDone = aDlg->exec() == QDialog::Accepted;
2393 bool isRandomColor = aDlg->isRandomColor();
2395 // 3. abort the previous operation and start a new one
2396 SessionPtr aMgr = ModelAPI_Session::get();
2397 QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
2398 aMgr->startOperation(aDescription.toStdString());
2400 // 4. set the value to all results
2401 std::vector<int> aColorResult = aDlg->getColor();
2402 foreach(ObjectPtr anObj, theObjects) {
2403 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2404 if (aResult.get() != NULL) {
2405 ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2406 if (aBodyResult.get() != NULL) { // change colors for all sub-solids
2407 std::list<ResultPtr> allRes;
2408 ModelAPI_Tools::allSubs(aBodyResult, allRes);
2409 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2410 setColor(*aRes, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2413 setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2416 aMgr->finishOperation();
2417 updateCommandStatus();
2420 //**************************************************************
2421 void setDeflection(ResultPtr theResult, const double theDeflection)
2423 if (!theResult.get())
2426 AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
2427 if (aDeflectionAttr.get() != NULL)
2428 aDeflectionAttr->setValue(theDeflection);
2429 static const Events_ID kRedisplayEvent =
2430 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2431 ModelAPI_EventCreator::get()->sendUpdated(theResult, kRedisplayEvent);
2434 //**************************************************************
2435 void setTransparency(ResultPtr theResult, double theTransparency)
2437 if (!theResult.get())
2440 AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
2441 if (anAttribute.get() != NULL)
2442 anAttribute->setValue(theTransparency);
2443 static const Events_ID kRedisplayEvent =
2444 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2445 ModelAPI_EventCreator::get()->sendUpdated(theResult, kRedisplayEvent);
2448 //**************************************************************
2449 void setTransparency(double theTransparency, const QObjectPtrList& theObjects)
2451 foreach(ObjectPtr anObj, theObjects) {
2452 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2453 if (aResult.get() != NULL) {
2454 ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2455 if (aBodyResult.get() != NULL) { // change property for all sub-solids
2456 std::list<ResultPtr> allRes;
2457 ModelAPI_Tools::allSubs(aBodyResult, allRes);
2458 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2459 setTransparency(*aRes, theTransparency);
2462 setTransparency(aResult, theTransparency);
2467 //**************************************************************
2468 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
2470 AttributeDoublePtr aDoubleAttr;
2471 // 1. find the current property of the object. This is a property of AIS presentation
2472 // The objects are iterated until a first valid property is found
2473 double aDeflection = -1;
2474 foreach(ObjectPtr anObject, theObjects) {
2475 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2476 if (aResult.get()) {
2477 aDeflection = ModelAPI_Tools::getDeflection(aResult);
2480 // TODO: remove the obtaining a property from the AIS object
2481 // this does not happen never because:
2482 // 1. The property can be changed only on results
2483 // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2484 AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2485 if (anAISObj.get()) {
2486 aDeflection = anAISObj->getDeflection();
2489 if (aDeflection > 0)
2492 if (aDeflection < 0)
2495 if (!abortAllOperations())
2497 // 2. show the dialog to change the value
2498 XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
2499 aDlg->setDeflection(aDeflection);
2500 aDlg->move(QCursor::pos());
2501 bool isDone = aDlg->exec() == QDialog::Accepted;
2505 // 3. abort the previous operation and start a new one
2506 SessionPtr aMgr = ModelAPI_Session::get();
2507 QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2508 aMgr->startOperation(aDescription.toStdString());
2510 // 4. set the value to all results
2511 aDeflection = aDlg->getDeflection();
2512 foreach(ObjectPtr anObj, theObjects) {
2513 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2514 if (aResult.get() != NULL) {
2515 ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2516 if (aBodyResult.get() != NULL) { // change property for all sub-solids
2517 std::list<ResultPtr> allRes;
2518 ModelAPI_Tools::allSubs(aBodyResult, allRes);
2519 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2520 setDeflection(*aRes, aDeflection);
2523 setDeflection(aResult, aDeflection);
2526 aMgr->finishOperation();
2527 updateCommandStatus();
2530 //**************************************************************
2531 void XGUI_Workshop::changeTransparency(const QObjectPtrList& theObjects)
2533 AttributeDoublePtr aDoubleAttr;
2534 // 1. find the current property of the object. This is a property of AIS presentation
2535 // The objects are iterated until a first valid property is found
2536 double aCurrentValue = -1;
2537 foreach(ObjectPtr anObject, theObjects) {
2538 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2539 if (aResult.get()) {
2540 aCurrentValue = ModelAPI_Tools::getTransparency(aResult);
2542 if (aCurrentValue > 0)
2545 if (aCurrentValue < 0)
2548 if (!abortAllOperations())
2551 // 2. show the dialog to change the value
2552 XGUI_PropertyDialog* aDlg = new XGUI_PropertyDialog(desktop());
2553 aDlg->setWindowTitle(tr("Transparency"));
2554 XGUI_TransparencyWidget* aTransparencyWidget = new XGUI_TransparencyWidget(aDlg);
2555 connect(aTransparencyWidget, SIGNAL(transparencyValueChanged()),
2556 this, SLOT(onTransparencyValueChanged()));
2557 aDlg->setContent(aTransparencyWidget);
2558 aTransparencyWidget->setValue(aCurrentValue);
2560 // 3. abort the previous operation and start a new one
2561 SessionPtr aMgr = ModelAPI_Session::get();
2562 QString aDescription = contextMenuMgr()->action("TRANSPARENCY_CMD")->text();
2563 aMgr->startOperation(aDescription.toStdString());
2565 if (aDlg->exec() == QDialog::Accepted) {
2566 // 4. set the value to all results
2567 aCurrentValue = aTransparencyWidget->getValue();
2568 setTransparency(aCurrentValue, theObjects);
2569 aMgr->finishOperation();
2571 aMgr->abortOperation();
2572 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2575 updateCommandStatus();
2578 //**************************************************************
2579 void XGUI_Workshop::onTransparencyValueChanged()
2581 XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2582 if (!aTransparencyWidget)
2585 QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2586 setTransparency(aTransparencyWidget->getValue(), anObjects);
2587 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2591 //******************************************************
2592 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2595 std::set<ObjectPtr> anObjects;
2596 foreach (ObjectPtr aObj, theList) {
2597 anObjects.insert(aObj);
2599 if (!prepareForDisplay(anObjects))
2603 foreach (ObjectPtr aObj, theList) {
2604 aObj->setDisplayed(isVisible);
2606 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2607 myObjectBrowser->updateAllIndexes();
2609 updateColorScaleVisibility();
2610 displayer()->updateViewer();
2613 //**************************************************************
2614 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2616 QObjectPtrList aSrcList = theList;
2617 // Hide all displayed objects
2618 QObjectPtrList aList = myDisplayer->displayedObjects();
2619 foreach (ObjectPtr aObj, aList) {
2620 if ((!aSrcList.contains(aObj)) && (module()->canEraseObject(aObj)))
2621 aObj->setDisplayed(false);
2623 aSrcList.removeAll(aObj);
2625 //Do not use eraseAll if you didn't send Redisplay event:
2626 //all objects are erased from viewer, but considered as displayed in displayer
2627 // Problem in bug 2218
2628 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2630 //issue #2159 Hide all incomplete behavior
2631 viewer()->eraseAll();
2634 std::set<ObjectPtr> anObjects;
2635 foreach (ObjectPtr aObj, aSrcList) {
2636 anObjects.insert(aObj);
2639 if (!prepareForDisplay(anObjects))
2642 // Show only objects from the list
2643 foreach (ObjectPtr aObj, aSrcList) {
2644 aObj->setDisplayed(true);
2646 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2648 // Necessary for update icons in ObjectBrowser on Linux
2649 myObjectBrowser->updateAllIndexes();
2650 updateColorScaleVisibility();
2651 displayer()->updateViewer();
2655 //**************************************************************
2656 void XGUI_Workshop::updateColorScaleVisibility()
2658 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2659 viewer()->setColorScaleShown(false);
2660 if (aObjects.size() == 1) {
2661 FieldStepPtr aStep =
2662 std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(aObjects.first());
2663 if (aStep.get() && myDisplayer->isVisible(aStep)) {
2664 AISObjectPtr aAisPtr = myDisplayer->getAISObject(aStep);
2665 Handle(AIS_InteractiveObject) aIO = aAisPtr->impl<Handle(AIS_InteractiveObject)>();
2666 ModuleBase_IStepPrs* aPrs = dynamic_cast<ModuleBase_IStepPrs*>(aIO.get());
2668 ModelAPI_AttributeTables::ValueType aType = aPrs->dataType();
2669 if ((aType == ModelAPI_AttributeTables::DOUBLE) ||
2670 (aType == ModelAPI_AttributeTables::INTEGER) ||
2671 (aType == ModelAPI_AttributeTables::BOOLEAN)) {
2672 myViewerProxy->setupColorScale();
2673 if (aType == ModelAPI_AttributeTables::BOOLEAN) {
2674 myViewerProxy->setColorScaleIntervals(2);
2675 myViewerProxy->setColorScaleRange(0., 1.);
2679 aPrs->dataRange(aMin, aMax);
2680 myViewerProxy->setColorScaleRange(aMin, aMax);
2682 myViewerProxy->setColorScaleTitle(aStep->name().c_str());
2683 myViewerProxy->setColorScaleShown(true);
2691 //**************************************************************
2692 void XGUI_Workshop::setNormalView(bool toInvert)
2694 QList<ModuleBase_ViewerPrsPtr> aPrsList =
2695 mySelector->selection()->getSelected(ModuleBase_ISelection::Viewer);
2696 GeomShapePtr aPlanarFace;
2697 foreach(ModuleBase_ViewerPrsPtr aPrs, aPrsList) {
2698 GeomShapePtr aShape = aPrs->shape();
2699 if (aShape.get() && aShape->isPlanar()) {
2700 aPlanarFace = aShape;
2704 if (aPlanarFace.get()) {
2705 GeomFacePtr aFace(new GeomAPI_Face(aPlanarFace));
2706 GeomPlanePtr aPlane = aFace->getPlane();
2707 GeomDirPtr aNormal = aPlane->direction();
2710 GeomPointPtr aPos = aPlane->location();
2712 double aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2713 aFace->computeSize(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2715 Handle(V3d_View) aView = myViewerProxy->activeView();
2716 double aScale = aView->Scale();
2717 aView->SetAt(aPos->x(), aPos->y(), aPos->z());
2718 aView->SetProj(aNormal->x(), aNormal->y(), aNormal->z());
2720 aBox.Update(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2721 aView->FitAll(aBox);
2725 //**************************************************************
2726 void XGUI_Workshop::registerValidators() const
2728 SessionPtr aMgr = ModelAPI_Session::get();
2729 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2732 //**************************************************************
2733 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2737 displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2738 displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2741 //**************************************************************
2742 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2744 for (int i = 0; i < theDoc->size(theGroup); i++)
2745 theDoc->object(theGroup, i)->setDisplayed(true);
2746 //displayObject(theDoc->object(theGroup, i));
2747 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2750 //**************************************************************
2751 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2753 foreach(ObjectPtr anObj, theList) {
2754 myDisplayer->setDisplayMode(anObj, (XGUI_Displayer::DisplayMode)theMode, false);
2756 ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObj);
2757 if (aBodyResult.get() != NULL) { // change display mode for all sub-solids
2758 std::list<ResultPtr> allRes;
2759 ModelAPI_Tools::allSubs(aBodyResult, allRes);
2760 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2761 myDisplayer->setDisplayMode(*aRes, (XGUI_Displayer::DisplayMode)theMode, false);
2765 if (theList.size() > 0)
2766 myDisplayer->updateViewer();
2769 //**************************************************************
2770 void XGUI_Workshop::closeDocument()
2772 ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2773 while (anOperation) {
2774 anOperation->abort();
2775 anOperation = operationMgr()->currentOperation();
2777 //myDisplayer->closeLocalContexts();
2778 myDisplayer->eraseAll();
2779 objectBrowser()->clearContent();
2781 module()->closeDocument();
2782 // we need to clear viewer (with created filters) to do not have problems in 2nd SALOME study
2783 module()->clearViewer();
2786 // data model need not process the document's signals about objects modifications as
2787 // the document is closed
2788 //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2790 SessionPtr aMgr = ModelAPI_Session::get();
2793 //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2796 //******************************************************
2797 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2799 XGUI_HistoryMenu* aMenu = NULL;
2800 if (isSalomeMode()) {
2801 QAction* anAction = qobject_cast<QAction*>(theObject);
2804 aMenu = new XGUI_HistoryMenu(anAction);
2806 QToolButton* aButton = qobject_cast<QToolButton*>(theObject);
2807 aMenu = new XGUI_HistoryMenu(aButton);
2809 connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2810 connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2813 //******************************************************
2814 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2816 QList<ActionInfo> aResult;
2817 std::list<std::string>::const_iterator it = theList.cbegin();
2818 for (; it != theList.cend(); it++) {
2819 QString anId = QString::fromStdString(*it);
2820 bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2822 anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2825 QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2826 if (aContextMenuAct) {
2827 anInfo.initFrom(aContextMenuAct);
2829 anInfo = myActionsMgr->actionInfoById(anId);
2832 anInfo.text = anInfo.text.prepend("Modify ");
2839 //******************************************************
2840 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2843 salomeConnector()->putInfo(theMessage, -1);
2845 myMainWindow->putInfo(theMessage, -1);
2850 //******************************************************
2851 void XGUI_Workshop::synchronizeViewer()
2853 SessionPtr aMgr = ModelAPI_Session::get();
2854 QList<DocumentPtr> aDocs;
2855 aDocs.append(aMgr->activeDocument());
2856 aDocs.append(aMgr->moduleDocument());
2858 foreach(DocumentPtr aDoc, aDocs) {
2859 synchronizeGroupInViewer(aDoc, false);
2863 //******************************************************
2864 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2865 bool theUpdateViewer)
2867 FeaturePtr aFeature;
2869 int aSize = theDoc->numInternalFeatures();
2870 for (int i = 0; i < aSize; i++) {
2871 aFeature = theDoc->internalFeature(i);
2872 if (!aFeature.get())
2874 const std::list<ResultPtr>& aResults = aFeature->results();
2875 std::list<ResultPtr>::const_iterator aIt;
2876 aFeature->setDisplayed(false);
2877 for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2879 if (aRes->isDisplayed() && !aRes->isConcealed()) {
2880 // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2881 // be changed to the object becomes visible when the shape becomes not empty
2882 if (!aRes->shape().get() || aRes->shape()->isNull())
2884 ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aRes);
2886 synchronizeResultTree(aResBody, false);
2888 if (aRes->isInHistory()) {
2889 if (aRes->isDisplayed())
2890 myDisplayer->display(aRes, false);
2892 myDisplayer->erase(aRes, false);
2895 aRes->setDisplayed(false);
2900 if (theUpdateViewer)
2901 myDisplayer->updateViewer();
2904 void XGUI_Workshop::synchronizeResultTree(const ResultBodyPtr& theRes, bool theUpdateViewer)
2906 if (theRes->numberOfSubs() > 0)
2907 for (int i = 0; i < theRes->numberOfSubs(); i++) {
2908 ResultBodyPtr aRes = theRes->subResult(i);
2910 synchronizeResultTree(aRes, theUpdateViewer);
2913 if (theRes->isDisplayed())
2914 myDisplayer->display(theRes, theUpdateViewer);
2916 myDisplayer->erase(theRes, theUpdateViewer);
2921 //******************************************************
2922 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2924 FeaturePtr aFeature;
2925 QObjectPtrList aSelList = theObjects;
2926 QObjectPtrList aNewSel;
2927 bool aHasHidden = false;
2928 foreach(ObjectPtr aObj, theObjects) {
2929 aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2930 if (aFeature.get()) {
2931 std::list<ResultPtr> aResults;
2932 ModelAPI_Tools::allResults(aFeature, aResults);
2933 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2934 for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2935 aHasHidden |= (*aIt)->isConcealed();
2936 aSelList.append(*aIt);
2937 aNewSel.append(*aIt);
2941 if (aSelList.count() > theObjects.count()) {
2942 // if something was found
2943 objectBrowser()->setObjectsSelected(aSelList);
2944 objectBrowser()->ensureVisible(aNewSel.first());
2947 QMessageBox::information(desktop(), tr("Find results"),
2948 tr("Results not found"), QMessageBox::Ok);
2951 //******************************************************
2952 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2955 QObjectPtrList aSelList = theObjects;
2956 QObjectPtrList aNewSel;
2957 FeaturePtr aFeature;
2958 foreach(ObjectPtr aObj, theObjects) {
2959 aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2960 if (aResult.get()) {
2961 aFeature = ModelAPI_Feature::feature(aResult);
2962 if (aFeature.get()) {
2963 aSelList.append(aFeature);
2964 aNewSel.append(aFeature);
2968 if (aSelList.count() > theObjects.count()) {
2969 // if something was found
2970 objectBrowser()->setObjectsSelected(aSelList);
2971 objectBrowser()->ensureVisible(aNewSel.first());
2975 void XGUI_Workshop::insertFeatureFolder()
2977 QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2978 if (aObjects.isEmpty())
2980 ObjectPtr aObj = aObjects.first();
2981 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2982 if (aFeature.get() == NULL)
2984 SessionPtr aMgr = ModelAPI_Session::get();
2985 DocumentPtr aDoc = aMgr->activeDocument();
2987 QString aDescription = contextMenuMgr()->action("INSERT_FOLDER_CMD")->text();
2989 aMgr->startOperation(aDescription.toStdString());
2990 aDoc->addFolder(aFeature);
2991 aMgr->finishOperation();
2993 updateCommandStatus();
2997 void XGUI_Workshop::insertToFolder(bool isBefore)
2999 std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
3000 if (aFeatures.empty())
3003 SessionPtr aMgr = ModelAPI_Session::get();
3004 DocumentPtr aDoc = aMgr->activeDocument();
3006 FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
3007 aDoc->findFolderBelow(aFeatures);
3011 QString aDescription = contextMenuMgr()->action(
3012 isBefore ? "ADD_TO_FOLDER_BEFORE_CMD" : "ADD_TO_FOLDER_AFTER_CMD")->text();
3014 QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
3016 aMgr->startOperation(aDescription.toStdString());
3017 aDoc->moveToFolder(aFeatures, aFolder);
3018 aMgr->finishOperation();
3020 myObjectBrowser->setFoldersState(aStates);
3022 updateCommandStatus();
3025 void XGUI_Workshop::moveOutFolder(bool isBefore)
3027 std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
3028 if (aFeatures.empty())
3031 SessionPtr aMgr = ModelAPI_Session::get();
3032 DocumentPtr aDoc = aMgr->activeDocument();
3034 QString aDescription = contextMenuMgr()->action(
3035 isBefore ? "ADD_OUT_FOLDER_BEFORE_CMD" : "ADD_OUT_FOLDER_AFTER_CMD")->text();
3037 QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
3039 aMgr->startOperation(aDescription.toStdString());
3040 aDoc->removeFromFolder(aFeatures, isBefore);
3041 aMgr->finishOperation();
3043 myObjectBrowser->setFoldersState(aStates);
3045 updateCommandStatus();
3048 void XGUI_Workshop::onAutoApply()
3050 SessionPtr aMgr = ModelAPI_Session::get();
3051 bool isBlocked = aMgr->isAutoUpdateBlocked();
3052 aMgr->blockAutoUpdate(!isBlocked);
3055 void XGUI_Workshop::updateAutoComputeState()
3057 SessionPtr aMgr = ModelAPI_Session::get();
3058 bool isComputeBlocked = aMgr->isAutoUpdateBlocked();
3060 // QAction* aUpdateCmd;
3061 // QList<QAction*> aCommands = mySalomeConnector->commandList();
3062 // foreach(QAction* aCmd, aCommands) {
3063 // if (aCmd->data().toString() == "AUTOCOMPUTE_CMD") {
3064 // aUpdateCmd = aCmd;
3068 // aUpdateCmd->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
3069 // QIcon(":pictures/autoapply_start.png"));
3071 AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
3072 AppElements_Command* aUpdateCmd = aMenuBar->feature("AUTOCOMPUTE_CMD");
3073 aUpdateCmd->button()->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
3074 QIcon(":pictures/autoapply_start.png"));
3079 void XGUI_Workshop::clearTemporaryDir()
3081 QDir aDir(myTmpDir.path());
3082 if (!aDir.isEmpty()) {
3083 QStringList aEntries;
3084 aDir.entryList(aEntries);
3085 foreach(QString aFile, aEntries) {
3092 void XGUI_Workshop::onDockSizeChanged()
3094 QDockWidget* aDockWgt = dynamic_cast<QDockWidget*>(myObjectBrowser->parentWidget());
3095 int aObWidth = aDockWgt->size().width();
3096 if (myPropertyPanel->width() != aObWidth) {
3097 QList<QDockWidget*> aWgtList;
3098 aWgtList << myPropertyPanel << aDockWgt;
3099 QList<int> aSizeList;
3100 aSizeList << aObWidth << aObWidth;
3101 desktop()->resizeDocks(aWgtList, aSizeList, Qt::Horizontal);
3102 disconnect(myObjectBrowser, SIGNAL(sizeChanged()), this, SLOT(onDockSizeChanged()));
3106 void XGUI_Workshop::deactivateCurrentSelector()
3108 myActiveControlMgr->deactivateSelector(myActiveControlMgr->activeSelector());