]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Warnings correction for moc files generation
[modules/shaper.git] / src / XGUI / XGUI_Workshop.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Workshop.h"
5
6 #include "XGUI_ActionsMgr.h"
7 #include "XGUI_MenuMgr.h"
8 #include "XGUI_ColorDialog.h"
9 #include "XGUI_DeflectionDialog.h"
10 #include "XGUI_ContextMenuMgr.h"
11 #include "XGUI_Displayer.h"
12 #include "XGUI_ErrorDialog.h"
13 #include "XGUI_ErrorMgr.h"
14 #include "XGUI_ModuleConnector.h"
15 #include "XGUI_ObjectsBrowser.h"
16 #include "XGUI_OperationMgr.h"
17 #include "XGUI_PropertyPanel.h"
18 #include "XGUI_SalomeConnector.h"
19 #include "XGUI_Selection.h"
20 #include "XGUI_SelectionMgr.h"
21 #include "XGUI_Tools.h"
22 #include "XGUI_ViewerProxy.h"
23 #include "XGUI_WorkshopListener.h"
24 #include <XGUI_CustomPrs.h>
25 #include <XGUI_HistoryMenu.h>
26 #include <XGUI_QtEvents.h>
27 #include <XGUI_DataModel.h>
28
29 #ifndef HAVE_SALOME
30 #include <AppElements_Button.h>
31 #include <AppElements_Command.h>
32 #include <AppElements_MainMenu.h>
33 #include <AppElements_MainWindow.h>
34 #include <AppElements_MenuGroupPanel.h>
35 #include <AppElements_Viewer.h>
36 #include <AppElements_Workbench.h>
37 #endif
38
39 #include <ModelAPI_AttributeDocRef.h>
40 #include <ModelAPI_AttributeIntArray.h>
41 #include <ModelAPI_AttributeDouble.h>
42 #include <ModelAPI_Data.h>
43 #include <ModelAPI_Events.h>
44 #include <ModelAPI_Feature.h>
45 #include <ModelAPI_Object.h>
46 #include <ModelAPI_ResultBody.h>
47 #include <ModelAPI_ResultConstruction.h>
48 #include <ModelAPI_ResultGroup.h>
49 #include <ModelAPI_ResultParameter.h>
50 #include <ModelAPI_Session.h>
51 #include <ModelAPI_Validator.h>
52 #include <ModelAPI_ResultCompSolid.h>
53 #include <ModelAPI_Tools.h>
54
55 //#include <PartSetPlugin_Part.h>
56
57 #include <Events_Loop.h>
58 #include <Events_InfoMessage.h>
59 #include <Events_LongOp.h>
60
61 #include <ModuleBase_IModule.h>
62 #include <ModuleBase_IViewer.h>
63 #include <ModuleBase_Operation.h>
64 #include <ModuleBase_OperationDescription.h>
65 #include <ModuleBase_PageBase.h>
66 #include <ModuleBase_Preferences.h>
67 #include <ModuleBase_SelectionValidator.h>
68 #include <ModuleBase_Tools.h>
69 #include <ModuleBase_WidgetFactory.h>
70 #include <ModuleBase_OperationFeature.h>
71 #include <ModuleBase_OperationAction.h>
72 #include <ModuleBase_PagedContainer.h>
73 #include <ModuleBase_WidgetValidated.h>
74 #include <ModuleBase_ModelWidget.h>
75 #include <ModuleBase_ResultPrs.h>
76
77 #include <Config_Common.h>
78 #include <Config_FeatureMessage.h>
79 #include <Config_ModuleReader.h>
80 #include <Config_PointerMessage.h>
81 #include <Config_PropManager.h>
82 #include <Config_DataModelReader.h>
83 #include <Config_Translator.h>
84
85 #include <SUIT_ResourceMgr.h>
86
87 #include <AIS_Trihedron.hxx>
88 #include <AIS_Point.hxx>
89 #include <AIS_Axis.hxx>
90
91 #include <QApplication>
92 #include <QFileDialog>
93 #include <QMessageBox>
94 #include <QMdiSubWindow>
95 #include <QMainWindow>
96 #include <QPushButton>
97 #include <QDockWidget>
98 #include <QLayout>
99 #include <QThread>
100 #include <QObject>
101 #include <QMenu>
102 #include <QToolButton>
103 #include <QAction>
104 #include <QDesktopWidget>
105
106 #include <iterator>
107
108 #ifdef DFBROWSER
109 #include <CDF_Session.hxx>
110 #include <CDF_Application.hxx>
111 #include <DFBrowserAPI_Communicator.hxx>
112 static bool DFBrowser_FirstCall = true;
113 #endif
114
115 #ifdef _DEBUG
116 #include <QDebug>
117 #include <iostream>
118 #endif
119
120 #ifdef WIN32
121 #include <windows.h>
122 #else
123 #include <dlfcn.h>
124 #endif
125
126 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
127
128 //#define DEBUG_DELETE
129 //#define DEBUG_FEATURE_NAME
130 //#define DEBUG_CLEAN_HISTORY
131
132 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
133     : QObject(),
134       myCurrentDir(QString()),
135       myModule(NULL),
136       mySalomeConnector(theConnector),
137       myPropertyPanel(0),
138       myObjectBrowser(0),
139       myDisplayer(0)
140       //myViewerSelMode(TopAbs_FACE)
141 {
142   mySelector = new XGUI_SelectionMgr(this);
143   myModuleConnector = new XGUI_ModuleConnector(this);
144   myOperationMgr = new XGUI_OperationMgr(this, 0);
145   ModuleBase_IWorkshop* aWorkshop = moduleConnector();
146   // Has to be defined first in order to get errors and messages from other components
147   myEventsListener = new XGUI_WorkshopListener(aWorkshop);
148
149   SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
150 #ifndef HAVE_SALOME
151   myMainWindow = new AppElements_MainWindow();
152
153   bool aCloc = aResMgr->booleanValue("language", "locale", true);
154   if (aCloc)
155     QLocale::setDefault( QLocale::c() );
156   else
157     QLocale::setDefault( QLocale::system() );
158 #endif
159   QString aPath = Config_XMLReader::pluginConfigFile().c_str();
160   QDir aDir(aPath);
161
162   // Load translations
163   QStringList aLangs;
164   aLangs << "*_en.ts"; // load by default eng translations
165   QString aCurrLang = aResMgr->stringValue("language", "language", "en");
166   if(aCurrLang != "en") {
167     aLangs << "*_" + aCurrLang + ".ts"; // then replace with translated files
168   }
169
170   foreach(QString aLang, aLangs) {
171     QStringList aFilters;
172     aFilters << aLang;
173     QStringList aTsFiles = aDir.entryList(aFilters, QDir::Files);
174     foreach(QString aFileName, aTsFiles) {
175       Config_Translator::load(aFileName.toStdString());
176     }
177   }
178
179   myDataModelXMLReader = new Config_DataModelReader();
180   //myDataModelXMLReader->readAll();
181
182   myDisplayer = new XGUI_Displayer(this);
183
184   connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
185
186   myActionsMgr = new XGUI_ActionsMgr(this);
187   myMenuMgr = new XGUI_MenuMgr(this);
188   myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
189   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
190   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
191           SLOT(onContextMenuCommand(const QString&, bool)));
192
193   myViewerProxy = new XGUI_ViewerProxy(this);
194   //connect(myViewerProxy, SIGNAL(selectionChanged()),
195   //        myActionsMgr,  SLOT(updateOnViewSelection()));
196
197   myOperationMgr->setWorkshop(aWorkshop);
198
199   myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
200
201   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
202           SLOT(onOperationResumed(ModuleBase_Operation*)));
203   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
204           SLOT(onOperationStopped(ModuleBase_Operation*)));
205   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
206           SLOT(onOperationCommitted(ModuleBase_Operation*)));
207   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
208           SLOT(onOperationAborted(ModuleBase_Operation*)));
209
210 #ifndef HAVE_SALOME
211   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
212   onTrihedronVisibilityChanged(true);
213 #endif
214
215   connect(myEventsListener, SIGNAL(errorOccurred(std::shared_ptr<Events_InfoMessage>)),
216           myErrorDlg, SLOT(addError(std::shared_ptr<Events_InfoMessage>)));
217
218   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
219   //                                 Config_Prop::Color, "225,225,225");
220
221   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
222                                    Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
223   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
224                                    Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
225   Config_PropManager::registerProp("Visualization", "result_construction_color",
226                                    "Construction color",
227                                    Config_Prop::Color,
228                                    ModelAPI_ResultConstruction::DEFAULT_COLOR());
229   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
230                                    Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
231
232   Config_PropManager::registerProp("Visualization", "body_deflection",
233                                    "Body deflection coefficient",
234                                    Config_Prop::Double,
235                                    ModelAPI_ResultBody::DEFAULT_DEFLECTION());
236
237   Config_PropManager::registerProp("Visualization", "construction_deflection",
238                                    "Construction deflection coefficient",
239                                    Config_Prop::Double,
240                                    ModelAPI_ResultConstruction::DEFAULT_DEFLECTION());
241
242   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "face-selection", true))
243     myViewerSelMode.append(TopAbs_FACE);
244   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "edge-selection", true))
245     myViewerSelMode.append(TopAbs_EDGE);
246   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "vertex-selection", true))
247     myViewerSelMode.append(TopAbs_VERTEX);
248   //IMP: an attempt to use result selection with other selection modes
249   myViewerSelMode.append(ModuleBase_ResultPrs::Sel_Result);//TopAbs_VERTEX);
250   myViewerSelMode.append(TopAbs_COMPSOLID);
251 }
252
253 //******************************************************
254 XGUI_Workshop::~XGUI_Workshop(void)
255 {
256 #ifdef _DEBUG
257 #ifdef MISSED_TRANSLATION
258   // Save Missed translations
259   Config_Translator::saveMissedTranslations();
260 #endif
261 #endif
262
263   delete myDisplayer;
264   delete myDataModelXMLReader;
265 }
266
267 //******************************************************
268 void XGUI_Workshop::startApplication()
269 {
270   //Initialize event listening
271   myEventsListener->initializeEventListening();
272
273   myDataModelXMLReader->readAll();
274   initMenu();
275
276   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
277                                    Config_Prop::Directory, "");
278
279
280   registerValidators();
281
282   // Calling of  loadCustomProps before activating module is required
283   // by Config_PropManger to restore user-defined path to plugins
284   ModuleBase_Preferences::loadCustomProps();
285   createModule();
286
287 #ifndef HAVE_SALOME
288   myMainWindow->show();
289   updateCommandStatus();
290 #endif
291
292   onNew();
293
294   myViewerProxy->connectViewProxy();
295   connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
296           SLOT(onTrihedronVisibilityChanged(bool)));
297
298   emit applicationStarted();
299 }
300
301 void XGUI_Workshop::activateModule()
302 {
303   myModule->activateSelectionFilters();
304
305   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
306     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
307   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
308     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
309
310   updateCommandStatus();
311
312   // TODO: get default selection mode
313
314   // activate visualized objects in the viewer
315   activateObjectsSelection(displayer()->displayedObjects());
316   myOperationMgr->activate();
317 }
318
319 void XGUI_Workshop::deactivateModule()
320 {
321   myModule->deactivateSelectionFilters();
322
323   // remove internal displayer filter
324   displayer()->deactivateSelectionFilters();
325
326   disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
327     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
328   disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
329     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
330
331   XGUI_Displayer* aDisplayer = displayer();
332   QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
333   aDisplayer->deactivateObjects(aDisplayed, true);
334   Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
335   Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aDisplayer->getTrihedron());
336   /// deactivate trihedron in selection modes
337   TColStd_ListOfInteger aTColModes;
338   aContext->ActivatedModes(aTrihedron, aTColModes);
339   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
340   for (; itr.More(); itr.Next() ) {
341     Standard_Integer aMode = itr.Value();
342     aContext->Deactivate(aTrihedron, aMode);
343   }
344   /// Trihedron problem: objects stayed in the viewer, should be removed manually
345   /// otherwise in SALOME happens crash by HideAll in the viewer
346   aContext->Remove(aTrihedron->Position(), true);
347   aContext->Remove(aTrihedron->Axis(), true);
348   aContext->Remove(aTrihedron->XAxis(), true);
349   aContext->Remove(aTrihedron->YAxis(), true);
350
351
352   myOperationMgr->deactivate();
353 }
354
355 //******************************************************
356 void XGUI_Workshop::initMenu()
357 {
358   myContextMenuMgr->createActions();
359
360 #ifdef HAVE_SALOME
361   // Create only Undo, Redo commands
362   QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
363                                                         tr("Undo last command"),
364                                                         QIcon(":pictures/undo.png"),
365                                                         QKeySequence::Undo, false,
366                                                         "MEN_DESK_EDIT");
367   QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
368   salomeConnector()->addActionInToolbar( aAction,aToolBarTitle  );
369
370   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
371   addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
372
373   aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
374                                               QIcon(":pictures/redo.png"), QKeySequence::Redo,
375                                               false, "MEN_DESK_EDIT");
376   salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
377
378   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
379   addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
380
381   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
382   //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"),
383   //                                            tr("Rebuild data objects"),
384   //                                            QIcon(":pictures/rebuild.png"), QKeySequence(),
385   //                                            false, "MEN_DESK_EDIT");
386   //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
387
388   //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
389   //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
390
391   aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."),
392                                              tr("Export the current document into a native file"),
393                                               QIcon(), QKeySequence(),
394                                               false, "MEN_DESK_FILE");
395   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
396
397   aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."),
398                                               tr("Import native file"),
399                                               QIcon(), QKeySequence(),
400                                               false, "MEN_DESK_FILE");
401   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
402   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
403
404 #else
405   // File commands group
406   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
407
408   AppElements_Command* aCommand;
409
410   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
411                                 QIcon(":pictures/save.png"), QKeySequence::Save);
412   aCommand->connectTo(this, SLOT(onSave()));
413   //aCommand->disable();
414
415   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
416                                 QIcon(":pictures/save.png"), QKeySequence());
417   aCommand->connectTo(this, SLOT(onSaveAs()));
418
419   QString aUndoId = "UNDO_CMD";
420   aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
421                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
422   aCommand->connectTo(this, SLOT(onUndo()));
423   AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
424   addHistoryMenu(aUndoButton,
425                  SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
426                  SLOT(onUndo(int)));
427
428   QString aRedoId = "REDO_CMD";
429   aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
430                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
431   aCommand->connectTo(this, SLOT(onRedo()));
432   AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
433   addHistoryMenu(aRedoButton,
434                  SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
435                  SLOT(onRedo(int)));
436
437   //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
438   //  QIcon(":pictures/rebuild.png"), QKeySequence());
439   //aCommand->connectTo(this, SLOT(onRebuild()));
440
441   //aCommand->disable();
442
443   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
444                                 QIcon(":pictures/open.png"), QKeySequence::Open);
445   aCommand->connectTo(this, SLOT(onOpen()));
446
447   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
448                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
449   aCommand->connectTo(this, SLOT(onPreferences()));
450
451   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
452                                 QIcon(":pictures/close.png"), QKeySequence::Close);
453   aCommand->connectTo(this, SLOT(onExit()));
454 #endif
455 }
456
457 #ifndef HAVE_SALOME
458 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
459 {
460   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
461   return aMenuBar->addWorkbench(theName);
462 }
463 #endif
464
465 //******************************************************
466 QMainWindow* XGUI_Workshop::desktop() const
467 {
468 #ifdef HAVE_SALOME
469   return salomeConnector()->desktop();
470 #else
471   return myMainWindow;
472 #endif
473 }
474
475 //******************************************************
476 void XGUI_Workshop::onStartWaiting()
477 {
478   if (Events_LongOp::isPerformed()) {
479     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
480   }
481 }
482
483 //******************************************************
484 void XGUI_Workshop::onAcceptActionClicked()
485 {
486   QAction* anAction = dynamic_cast<QAction*>(sender());
487   XGUI_OperationMgr* anOperationMgr = operationMgr();
488   if (anOperationMgr) {
489     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
490                                                     (anOperationMgr->currentOperation());
491     if (aFOperation) {
492       //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
493       myOperationMgr->onCommitOperation();
494     }
495   }
496 }
497
498 //******************************************************
499 void XGUI_Workshop::onPreviewActionClicked()
500 {
501   ModuleBase_IPropertyPanel* aPanel = propertyPanel();
502   if (aPanel) {
503     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
504     if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
505       anActiveWidget->storeValue();
506     }
507   }
508   std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
509                 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
510   Events_Loop::loop()->send(aMsg);
511 }
512
513 //******************************************************
514 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
515 {
516   if (!myModule->canActivateSelection(theObject)) {
517     if (myDisplayer->isActive(theObject)) {
518       QObjectPtrList anObjects;
519       anObjects.append(theObject);
520       myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
521     }
522   }
523 }
524
525 //******************************************************
526 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
527 {
528   bool aHasNested = false;
529   std::string aFeatureKind = theFeature->getKind();
530 #ifdef HAVE_SALOME
531     XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
532     if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
533       aHasNested = true;
534 #else
535     AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
536     AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
537     if (aCommand && aCommand->button()->additionalButtonWidget())
538       aHasNested = true;
539 #endif
540   return aHasNested;
541 }
542
543 void XGUI_Workshop::fillPropertyPanel(ModuleBase_Operation* theOperation)
544 {
545   ModuleBase_OperationFeature* aFOperation =
546     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
547   if (!aFOperation)
548     return;
549
550   showPropertyPanel();
551   myPropertyPanel->cleanContent();
552
553   QList<ModuleBase_ModelWidget*> aWidgets;
554   if (!module()->createWidgets(theOperation, aWidgets)) {
555     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
556     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
557     aFactory.createWidget(myPropertyPanel->contentWidget());
558     aWidgets = aFactory.getModelWidgets();
559   }
560
561   // check compatibility of feature and widgets
562   FeaturePtr aFeature = aFOperation->feature();
563   std::string aFeatureKind = aFeature->getKind();
564   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
565     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
566       std::string anErrorMsg = "The feature '%1' has no attribute '%2' used by widget '%3'.";
567       Events_InfoMessage("XGUI_Workshop", anErrorMsg)
568         .arg(aFeatureKind).arg(aWidget->attributeID())
569         .arg(aWidget->metaObject()->className()).send();
570       myPropertyPanel->cleanContent();
571       return;
572     }
573   }
574   // for performance purpose, flush should be done after all controls are filled
575   bool isUpdateFlushed = false;
576   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
577     bool isStoreValue = !aFOperation->isEditOperation() &&
578                         !aWidget->getDefaultValue().empty() &&
579                         !aWidget->isComputedDefault();
580     aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
581     if (!isStoreValue)
582       aWidget->restoreValue();
583     aWidget->enableFocusProcessing();
584   }
585   ModuleBase_Tools::flushUpdated(aFeature);
586
587   // update visible state of Preview button
588 #ifdef HAVE_SALOME
589   bool anIsAutoPreview =
590     mySalomeConnector->featureInfo(aFeatureKind.c_str())->isAutoPreview();
591 #else
592   AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
593   AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
594   bool anIsAutoPreview = aCommand && aCommand->featureMessage()->isAutoPreview();
595 #endif
596   if (!anIsAutoPreview) {
597     myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
598     // send signal about preview should not be computed automatically, click on preview
599     // button should initiate it
600     std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
601                   new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
602     Events_Loop::loop()->send(aMsg);
603   }
604   myPropertyPanel->setModelWidgets(aWidgets);
605   aFOperation->setPropertyPanel(myPropertyPanel);
606
607   myModule->propertyPanelDefined(theOperation);
608
609 #ifndef DEBUG_FEATURE_NAME
610   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
611 #else
612   std::string aFeatureName = aFeature->name();
613   myPropertyPanel->setWindowTitle(QString("%1: %2")
614     .arg(theOperation->getDescription()->description())
615     .arg(aFeatureName.c_str()));
616 #endif
617
618   myErrorMgr->setPropertyPanel(myPropertyPanel);
619 }
620
621 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
622 {
623   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
624   if (aPropertyPanel) {
625     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
626     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
627        myModule->connectToPropertyPanel(aWidget, isToConnect);
628        if (isToConnect) {
629         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
630         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
631         connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
632        }
633       else {
634         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
635         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
636         disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
637       }
638     }
639   }
640 }
641
642 //******************************************************
643 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
644 {
645   setGrantedFeatures(theOperation);
646
647   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
648     fillPropertyPanel(theOperation);
649     connectToPropertyPanel(true);
650   }
651   updateCommandStatus();
652
653   myModule->operationResumed(theOperation);
654 }
655
656
657 //******************************************************
658 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
659 {
660   updateCommandStatus();
661
662   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
663                                                                         (theOperation);
664   if (!aFOperation)
665     return;
666
667   ModuleBase_ISelection* aSel = mySelector->selection();
668   QObjectPtrList aObj = aSel->selectedPresentations();
669   //!< No need for property panel
670   hidePropertyPanel();
671   myPropertyPanel->cleanContent();
672
673   connectToPropertyPanel(false);
674   myModule->operationStopped(aFOperation);
675
676   // the deactivated objects of the current operation should be activated back.
677   // They were deactivated on operation start or an object redisplay
678   QObjectPtrList anObjects;
679   FeaturePtr aFeature = aFOperation->feature();
680   if (aFeature.get()) { // feature may be not created (plugin load fail)
681     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
682       anObjects.append(aFeature);
683     std::list<ResultPtr> aResults;
684     ModelAPI_Tools::allResults(aFeature, aResults);
685     std::list<ResultPtr>::const_iterator aIt;
686     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
687       ResultPtr anObject = *aIt;
688       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
689         anObjects.append(anObject);
690       }
691     }
692   }
693   activateObjectsSelection(anObjects);
694 }
695
696
697 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
698 {
699   myModule->operationCommitted(theOperation);
700 }
701
702 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
703 {
704   myModule->operationAborted(theOperation);
705 }
706
707 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
708 {
709   ModuleBase_OperationFeature* aFOperation =
710     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
711   if (!aFOperation)
712     return;
713
714   QStringList aGrantedIds;
715   if (isSalomeMode()) {
716     const std::shared_ptr<Config_FeatureMessage>& anInfo =
717                          mySalomeConnector->featureInfo(theOperation->id());
718     if (anInfo.get())
719       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
720                                    .split(" ", QString::SkipEmptyParts);
721   }
722   else
723     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
724
725   ModuleBase_IModule* aModule = module();
726   if (aModule)
727     aModule->grantedOperationIds(theOperation, aGrantedIds);
728
729   aFOperation->setGrantedOperationIds(aGrantedIds);
730 }
731
732 //******************************************************
733 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
734 {
735   QApplication::restoreOverrideCursor();
736   SessionPtr aMgr = ModelAPI_Session::get();
737
738   std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
739   std::list<DocumentPtr>::const_iterator aIt;
740   for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
741     std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
742     (*aIt)->storeNodesState(aState);
743   }
744
745   aMgr->save(theName.toLatin1().constData(), theFileNames);
746
747   QApplication::restoreOverrideCursor();
748 }
749
750 //******************************************************
751 bool XGUI_Workshop::abortAllOperations()
752 {
753   return myOperationMgr->abortAllOperations();
754 }
755
756 //******************************************************
757 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
758 {
759   setGrantedFeatures(theOperation);
760   if (!theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
761     updateCommandStatus();
762   }
763   else {
764     myModule->operationStarted(theOperation);
765   }
766 }
767
768 //******************************************************
769 void XGUI_Workshop::onOpen()
770 {
771   if(!abortAllOperations())
772     return;
773   //save current file before close if modified
774   SessionPtr aSession = ModelAPI_Session::get();
775   if (aSession->isModified()) {
776     //TODO(sbh): re-launch the app?
777     int anAnswer = QMessageBox::question(
778         desktop(), tr("Save current file"),
779         tr("The document is modified, save before opening another?"),
780         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
781     if (anAnswer == QMessageBox::Save) {
782       onSave();
783     } else if (anAnswer == QMessageBox::Cancel) {
784       return;
785     }
786     myCurrentDir = "";
787   }
788
789   //show file dialog, check if readable and open
790   QString aDirectory = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
791   openDirectory(aDirectory);
792 }
793
794 //******************************************************
795 void XGUI_Workshop::openDirectory(const QString& theDirectory)
796 {
797   myCurrentDir = theDirectory;
798   if (myCurrentDir.isEmpty())
799     return;
800
801   QFileInfo aFileInfo(myCurrentDir);
802   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
803     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
804     myCurrentDir = "";
805     return;
806   }
807
808   QApplication::setOverrideCursor(Qt::WaitCursor);
809   module()->closeDocument();
810   SessionPtr aSession = ModelAPI_Session::get();
811   aSession->closeAll();
812   aSession->load(myCurrentDir.toLatin1().constData());
813   myObjectBrowser->rebuildDataTree();
814
815   // Open first level of data tree
816   DocumentPtr aRootDoc = aSession->moduleDocument();
817   std::list<bool> aStates;
818   aRootDoc->restoreNodesState(aStates);
819   myObjectBrowser->setStateForDoc(aRootDoc, aStates);
820
821   updateCommandStatus();
822 #ifndef HAVE_SALOME
823   myMainWindow->setCurrentDir(myCurrentDir, true);
824 #endif
825   QApplication::restoreOverrideCursor();
826 }
827
828 //******************************************************
829 void XGUI_Workshop::onNew()
830 {
831   QApplication::setOverrideCursor(Qt::WaitCursor);
832   if (objectBrowser() == 0) {
833     createDockWidgets();
834     mySelector->connectViewers();
835   }
836   myViewerProxy->connectToViewer();
837   showObjectBrowser();
838 #ifndef HAVE_SALOME
839   myMainWindow->showPythonConsole();
840   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
841   aWnd->showMaximized();
842   updateCommandStatus();
843 #endif
844   myContextMenuMgr->connectViewer();
845   QApplication::restoreOverrideCursor();
846 }
847
848 #ifndef HAVE_SALOME
849 //******************************************************
850 void XGUI_Workshop::onExit()
851 {
852   SessionPtr aMgr = ModelAPI_Session::get();
853   if (aMgr->isModified()) {
854     int anAnswer = QMessageBox::question(
855         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
856         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
857     if (anAnswer == QMessageBox::Save) {
858       bool saved = onSave();
859       if (!saved) {
860         return;
861       }
862     } else if (anAnswer == QMessageBox::Cancel) {
863       return;
864     }
865   }
866   qApp->exit();
867 }
868
869 //******************************************************
870 void XGUI_Workshop::onPreferences()
871 {
872   ModuleBase_Prefs aModif;
873   ModuleBase_Preferences::editPreferences(aModif);
874   if (aModif.size() > 0) {
875     QString aSection;
876     foreach (ModuleBase_Pref aPref, aModif)
877     {
878       aSection = aPref.first;
879       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
880         myMainWindow->viewer()->updateFromResources();
881       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
882         myMainWindow->menuObject()->updateFromResources();
883       }
884     }
885     displayer()->redisplayObjects();
886   }
887 }
888 #endif
889
890 //******************************************************
891 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
892 {
893   XGUI_Displayer* aDisplayer = displayer();
894   if (aDisplayer)
895     aDisplayer->displayTrihedron(theState);
896 }
897
898 //******************************************************
899 bool XGUI_Workshop::onSave()
900 {
901   if(!abortAllOperations())
902     return false;
903   if (myCurrentDir.isEmpty()) {
904     return onSaveAs();
905   }
906   std::list<std::string> aFiles;
907   saveDocument(myCurrentDir, aFiles);
908   updateCommandStatus();
909 #ifndef HAVE_SALOME
910     myMainWindow->setModifiedState(false);
911 #endif
912   return true;
913 }
914
915 //******************************************************
916 bool XGUI_Workshop::onSaveAs()
917 {
918   if(!abortAllOperations())
919     return false;
920   QFileDialog dialog(desktop());
921   dialog.setWindowTitle(tr("Select directory to save files..."));
922   dialog.setFileMode(QFileDialog::Directory);
923   dialog.setFilter(QDir::AllDirs);
924   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
925   dialog.setViewMode(QFileDialog::Detail);
926
927   if (!dialog.exec()) {
928     return false;
929   }
930
931   QString aTempDir = dialog.selectedFiles().first();
932   QDir aDir(aTempDir);
933   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
934     int answer = QMessageBox::question(
935         desktop(),
936         // Title of the dialog which asks user if he wants to save study
937         // in existing non-empty folder
938         tr("Save"),
939         tr("The directory already contains some files, save anyway?"),
940         QMessageBox::Save | QMessageBox::Cancel);
941     if (answer == QMessageBox::Cancel) {
942       return false;
943     }
944   }
945   myCurrentDir = aTempDir;
946 #ifndef HAVE_SALOME
947     myMainWindow->setCurrentDir(myCurrentDir, false);
948     myMainWindow->setModifiedState(false);
949 #endif
950   return onSave();
951 }
952
953 //******************************************************
954 void XGUI_Workshop::onUndo(int theTimes)
955 {
956   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
957   SessionPtr aMgr = ModelAPI_Session::get();
958   std::list<std::string> aUndoList = aMgr->undoList();
959   if (aMgr->isOperation()) {
960     /// this is important for nested operations
961     /// when sketch operation is active, this condition is false and
962     /// the sketch operation is not aborted
963     operationMgr()->onAbortOperation();
964   }
965   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
966   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
967     aMgr->undo();
968     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
969       myObjectBrowser->rebuildDataTree();
970   }
971
972   operationMgr()->updateApplyOfOperations();
973   updateCommandStatus();
974 }
975
976 //******************************************************
977 void XGUI_Workshop::onRedo(int theTimes)
978 {
979   // the viewer update should be blocked in order to avoid the features blinking. For the created
980   // feature a results are created, the flush of the created signal caused the viewer redisplay for
981   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
982   // until redo of all possible objects happens
983   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
984
985   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
986   SessionPtr aMgr = ModelAPI_Session::get();
987   std::list<std::string> aRedoList = aMgr->redoList();
988   if (aMgr->isOperation()) {
989     /// this is important for nested operations
990     /// when sketch operation is active, this condition is false and
991     /// the sketch operation is not aborted
992     operationMgr()->onAbortOperation();
993   }
994   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
995   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
996     aMgr->redo();
997     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
998       myObjectBrowser->rebuildDataTree();
999   }
1000   operationMgr()->updateApplyOfOperations();
1001   updateCommandStatus();
1002
1003   // unblock the viewer update functionality and make update on purpose
1004   myDisplayer->enableUpdateViewer(isUpdateEnabled);
1005   myDisplayer->updateViewer();
1006 }
1007
1008 //******************************************************
1009 //void XGUI_Workshop::onRebuild()
1010 //{
1011 //  SessionPtr aMgr = ModelAPI_Session::get();
1012 //  bool aWasOperation = aMgr->isOperation(); // keep this value
1013 //  if (!aWasOperation) {
1014 //    aMgr->startOperation("Rebuild");
1015 //  }
1016 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1017 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1018 //    new Events_Message(aRebuildEvent, this)));
1019 //  if (!aWasOperation) {
1020 //    aMgr->finishOperation();
1021 //  }
1022 //  updateCommandStatus();
1023 //}
1024
1025 //******************************************************
1026 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1027 {
1028   ModuleBase_ModelWidget* anActiveWidget = 0;
1029   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1030   if (anOperation) {
1031     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1032     if (aPanel)
1033       anActiveWidget = aPanel->activeWidget();
1034   }
1035   if (anActiveWidget)
1036     operationMgr()->onValidateOperation();
1037
1038   myModule->widgetStateChanged(thePreviousState);
1039 }
1040
1041 //******************************************************
1042 void XGUI_Workshop::onValuesChanged()
1043 {
1044   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1045   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1046     return;
1047
1048   ModuleBase_ModelWidget* anActiveWidget = 0;
1049   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1050   if (anOperation) {
1051     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1052     if (aPanel)
1053       anActiveWidget = aPanel->activeWidget();
1054   }
1055   if (anActiveWidget) {
1056     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1057                                                                            (anActiveWidget);
1058     if (aWidgetValidated)
1059       aWidgetValidated->clearValidatedCash();
1060   }
1061 }
1062
1063 void XGUI_Workshop::onWidgetObjectUpdated()
1064 {
1065   operationMgr()->onValidateOperation();
1066 }
1067
1068 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1069 {
1070   QString libName = QString::fromStdString(library(theModule.toStdString()));
1071   if (libName.isEmpty()) {
1072     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1073     return 0;
1074   }
1075
1076   QString err;
1077   CREATE_FUNC crtInst = 0;
1078
1079 #ifdef WIN32
1080   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1081   if (!modLib) {
1082     LPVOID lpMsgBuf;
1083     ::FormatMessage(
1084         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1085         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1086     QString aMsg((char*) &lpMsgBuf);
1087     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1088     ::LocalFree(lpMsgBuf);
1089   } else {
1090     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1091     if (!crtInst) {
1092       LPVOID lpMsgBuf;
1093       ::FormatMessage(
1094           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1095               | FORMAT_MESSAGE_IGNORE_INSERTS,
1096           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1097       QString aMsg((char*) &lpMsgBuf);
1098       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1099       ::LocalFree(lpMsgBuf);
1100     }
1101   }
1102 #else
1103   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1104   if ( !modLib ) {
1105     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1106   } else {
1107     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1108     if ( !crtInst ) {
1109       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1110     }
1111   }
1112 #endif
1113
1114   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1115
1116   if (!err.isEmpty()) {
1117     if (desktop()) {
1118       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1119     } else {
1120       qWarning(qPrintable(err));
1121     }
1122   }
1123   return aModule;
1124 }
1125
1126 //******************************************************
1127 bool XGUI_Workshop::createModule()
1128 {
1129   Config_ModuleReader aModuleReader;
1130   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1131   myModule = loadModule(moduleName);
1132   if (!myModule)
1133     return false;
1134
1135   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1136   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1137   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1138   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1139
1140   myModule->createFeatures();
1141 #ifdef HAVE_SALOME
1142   salomeConnector()->createFeatureActions();
1143 #endif
1144   //myActionsMgr->update();
1145   return true;
1146 }
1147
1148 //******************************************************
1149 void XGUI_Workshop::updateCommandStatus()
1150 {
1151   QList<QAction*> aCommands;
1152 #ifdef HAVE_SALOME
1153     aCommands = salomeConnector()->commandList();
1154 #else
1155     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1156     foreach (AppElements_Command* aCmd, aMenuBar->features())
1157       aCommands.append(aCmd);
1158 #endif
1159   SessionPtr aMgr = ModelAPI_Session::get();
1160   if (aMgr->hasModuleDocument()) {
1161     foreach(QAction* aCmd, aCommands) {
1162       QString aId = aCmd->data().toString();
1163       if (aId == "UNDO_CMD")
1164         aCmd->setEnabled(myModule->canUndo());
1165       else if (aId == "REDO_CMD")
1166         aCmd->setEnabled(myModule->canRedo());
1167       else
1168         // Enable all commands
1169         aCmd->setEnabled(true);
1170     }
1171     updateHistory();
1172   } else {
1173     foreach(QAction* aCmd, aCommands) {
1174       QString aId = aCmd->data().toString();
1175       if (aId == "NEW_CMD")
1176         aCmd->setEnabled(true);
1177       else if (aId == "EXIT_CMD")
1178         aCmd->setEnabled(true);
1179       else
1180         aCmd->setEnabled(false);
1181     }
1182   }
1183   myActionsMgr->updateCommandsStatus();
1184   emit commandStatusUpdated();
1185 }
1186
1187 void XGUI_Workshop::updateHistory()
1188 {
1189   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1190   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1191   emit updateUndoHistory(aUndoRes);
1192
1193   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1194   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1195   emit updateRedoHistory(aRedoRes);
1196 }
1197
1198 //******************************************************
1199 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1200 {
1201   QDockWidget* aObjDock = new QDockWidget(theParent);
1202   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1203                             Qt::RightDockWidgetArea |
1204                             Qt::BottomDockWidgetArea);
1205   aObjDock->setWindowTitle(tr("Object browser"));
1206   aObjDock->setStyleSheet(
1207       "::title { position: relative; padding-left: 5px; text-align: left center }");
1208   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1209   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1210   myModule->customizeObjectBrowser(myObjectBrowser);
1211   aObjDock->setWidget(myObjectBrowser);
1212
1213   myContextMenuMgr->connectObjectBrowser();
1214   return aObjDock;
1215 }
1216
1217 //******************************************************
1218 /*
1219  * Creates dock widgets, places them in corresponding area
1220  * and tabifies if necessary.
1221  */
1222 void XGUI_Workshop::createDockWidgets()
1223 {
1224   QMainWindow* aDesktop = desktop();
1225   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1226   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1227   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1228   myPropertyPanel->setupActions(myActionsMgr);
1229   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1230                                    Qt::RightDockWidgetArea |
1231                                    Qt::BottomDockWidgetArea);
1232   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1233   hidePropertyPanel();  ///<! Invisible by default
1234   hideObjectBrowser();
1235   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1236   myPropertyPanel->installEventFilter(myOperationMgr);
1237
1238   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1239   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1240
1241   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1242   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1243
1244   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1245   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1246
1247   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1248           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1249   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1250           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1251 }
1252
1253 //******************************************************
1254 void XGUI_Workshop::showPropertyPanel()
1255 {
1256   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1257   ///<! Restore ability to close panel from the window's menu
1258   aViewAct->setEnabled(true);
1259   myPropertyPanel->show();
1260   myPropertyPanel->raise();
1261
1262   // The next code is necessary to made the property panel the active window
1263   // in order to operation manager could process key events of the panel.
1264   // otherwise they are ignored. It happens only if the same(activateWindow) is
1265   // not happened by property panel activation(e.g. resume operation of Sketch)
1266   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1267   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1268 }
1269
1270 //******************************************************
1271 void XGUI_Workshop::hidePropertyPanel()
1272 {
1273   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1274   ///<! Do not allow to show empty property panel
1275   aViewAct->setEnabled(false);
1276   myPropertyPanel->hide();
1277
1278   // the property panel is active window of the desktop, when it is
1279   // hidden, it is undefined which window becomes active. By this reason
1280   // it is defined to perform the desktop as the active window.
1281   // in SALOME mode, workstack made the PyConsole the active window,
1282   // set the focus on it. As a result, shortcuts of the application, like
1283   // are processed by this console. For example Undo actions.
1284   // It is possible that this code is to be moved to SHAPER package
1285   QMainWindow* aDesktop = desktop();
1286   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1287   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1288 }
1289
1290 //******************************************************
1291 void XGUI_Workshop::showObjectBrowser()
1292 {
1293   if (!isSalomeMode())
1294     myObjectBrowser->parentWidget()->show();
1295 }
1296
1297 //******************************************************
1298 void XGUI_Workshop::hideObjectBrowser()
1299 {
1300   if (!isSalomeMode())
1301     myObjectBrowser->parentWidget()->hide();
1302 }
1303
1304 //******************************************************
1305 void XGUI_Workshop::salomeViewerSelectionChanged()
1306 {
1307   emit salomeViewerSelection();
1308 }
1309
1310 //**************************************************************
1311 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1312 {
1313   return mySalomeConnector->viewer();
1314 }
1315
1316 //**************************************************************
1317 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1318 {
1319   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1320   if (theId == "DELETE_CMD")
1321     deleteObjects();
1322   else if (theId == "CLEAN_HISTORY_CMD")
1323     cleanHistory();
1324   else if (theId == "MOVE_CMD")
1325     moveObjects();
1326   else if (theId == "COLOR_CMD")
1327     changeColor(aObjects);
1328   else if (theId == "DEFLECTION_CMD")
1329     changeDeflection(aObjects);
1330   else if (theId == "SHOW_CMD") {
1331     showObjects(aObjects, true);
1332     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1333     updateCommandStatus();
1334   }
1335   else if (theId == "HIDE_CMD") {
1336     showObjects(aObjects, false);
1337     updateCommandStatus();
1338   }
1339   else if (theId == "SHOW_ONLY_CMD") {
1340     showOnlyObjects(aObjects);
1341     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1342     updateCommandStatus();
1343   }
1344   else if (theId == "SHADING_CMD")
1345     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1346   else if (theId == "WIREFRAME_CMD")
1347     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1348   else if (theId == "HIDEALL_CMD") {
1349     QObjectPtrList aList = myDisplayer->displayedObjects();
1350     foreach (ObjectPtr aObj, aList) {
1351       if (module()->canEraseObject(aObj))
1352         aObj->setDisplayed(false);
1353     }
1354     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1355     updateCommandStatus();
1356   } else if (theId == "SELECT_VERTEX_CMD") {
1357     setViewerSelectionMode(TopAbs_VERTEX);
1358   } else if (theId == "SELECT_EDGE_CMD") {
1359     setViewerSelectionMode(TopAbs_EDGE);
1360   } else if (theId == "SELECT_FACE_CMD") {
1361     setViewerSelectionMode(TopAbs_FACE);
1362   } else if (theId == "SELECT_RESULT_CMD") {
1363     //setViewerSelectionMode(-1);
1364     //IMP: an attempt to use result selection with other selection modes
1365     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1366     setViewerSelectionMode(TopAbs_COMPSOLID);
1367   } else if (theId == "SHOW_RESULTS_CMD") {
1368     highlightResults(aObjects);
1369   } else if (theId == "SHOW_FEATURE_CMD") {
1370     highlightFeature(aObjects);
1371   }
1372 #ifdef VINSPECTOR
1373   else if (theId == "VINSPECTOR_VIEW") {
1374     displayer()->setVInspectorVisible(true);
1375   }
1376 #endif
1377 #ifdef DFBROWSER
1378   else if (theId == "DFBROWSER_VIEW") {
1379     if (DFBrowser_FirstCall) {
1380       Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1381       DFBrowserAPI_Communicator* aCommunicator =
1382                      DFBrowserAPI_Communicator::loadPluginLibrary("TKDFBrowser.dll");
1383       if (aCommunicator) {
1384         aCommunicator->setApplication(anApplication);
1385         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1386         if (aContext)
1387           aCommunicator->setContext(aContext);
1388       }
1389       DFBrowser_FirstCall = false;
1390     }
1391   }
1392 #endif
1393 }
1394
1395 //**************************************************************
1396 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1397 {
1398   if (theMode == -1)
1399     myViewerSelMode.clear();
1400   else {
1401     if (myViewerSelMode.contains(theMode))
1402       myViewerSelMode.removeAll(theMode);
1403     else
1404       myViewerSelMode.append(theMode);
1405   }
1406   activateObjectsSelection(myDisplayer->displayedObjects());
1407 }
1408
1409 //**************************************************************
1410 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1411 {
1412   QIntList aModes;
1413   module()->activeSelectionModes(aModes);
1414   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1415     aModes.append(myViewerSelMode);
1416   myDisplayer->activateObjects(aModes, theList);
1417 }
1418
1419 //**************************************************************
1420 void XGUI_Workshop::deleteObjects()
1421 {
1422   ModuleBase_IModule* aModule = module();
1423   // allow the module to delete objects, do nothing if it has succeed
1424   if (aModule->deleteObjects()) {
1425     updateCommandStatus();
1426     return;
1427   }
1428
1429   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1430   if (!abortAllOperations())
1431     return;
1432
1433   bool hasResult = false;
1434   bool hasFeature = false;
1435   bool hasParameter = false;
1436   bool hasCompositeOwner = false;
1437   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1438   if (!(hasFeature || hasParameter))
1439     return;
1440
1441   // delete objects
1442   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1443   std::set<FeaturePtr> aFeatures;
1444   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1445   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1446
1447   bool aDone = false;
1448   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1449   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1450   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1451
1452   operationMgr()->startOperation(anOpAction);
1453
1454   std::set<FeaturePtr> aFeatureRefsToDelete;
1455   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1456     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1457     // It is necessary to clear selection in order to avoid selection changed event during
1458     // deletion and negative consequences connected with processing of already deleted items
1459     mySelector->clearSelection();
1460
1461     if (!aFeatureRefsToDelete.empty())
1462       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1463     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1464   }
1465   if (aDone)
1466     operationMgr()->commitOperation();
1467   else
1468     operationMgr()->abortOperation(operationMgr()->currentOperation());
1469 }
1470
1471 //**************************************************************
1472 void addRefsToFeature(const FeaturePtr& theFeature,
1473                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1474                       std::set<FeaturePtr>& theReferences)
1475 {
1476   //if (theReferences.find(theFeature) != theReferences.end())
1477   //  return;
1478   if (theMainList.find(theFeature) == theMainList.end())
1479     return; // this feature is not in the selection list, so exists without references to it
1480   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1481
1482   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1483                                        aLast = aMainReferences.end();
1484   for (; anIt != aLast; anIt++) {
1485     FeaturePtr aRefFeature = *anIt;
1486     if (theReferences.find(aRefFeature) == theReferences.end())
1487       theReferences.insert(aRefFeature);
1488     addRefsToFeature(aRefFeature, theMainList, theReferences);
1489   }
1490 }
1491
1492 //**************************************************************
1493 void XGUI_Workshop::cleanHistory()
1494 {
1495   if (!abortAllOperations())
1496     return;
1497
1498   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1499   std::set<FeaturePtr> aFeatures;
1500   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1501
1502 #ifdef DEBUG_CLEAN_HISTORY
1503   QStringList anInfo;
1504   std::set<FeaturePtr>::const_iterator aFIt;
1505   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1506     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1507     anInfo.append(aFeature->name().c_str());
1508   }
1509   QString anInfoStr = anInfo.join(";\t");
1510   qDebug(QString("cleanHistory for: [%1] - %2").
1511     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1512 #endif
1513
1514   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1515   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1516   // find for each object whether all reference values are in the map as key, that means that there
1517   // is no other reference in the model to this object, so it might be removed by cleaning history
1518   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - cann't be deleted, dependency to bool_1
1519   // ext_1(bool_1, sk_3)  - cann't be deleted, dependency to bool_1
1520   // vertex_1()
1521   // sk_2(ext_2) + (bool_1)  - cann't be deleted, dependency to bool_1
1522   // ext_2(bool_1)  - cann't be deleted, dependency to bool_1
1523   // sk_3()
1524   // Information: bool_1 is not selected
1525   std::set<FeaturePtr> anUnusedObjects;
1526   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1527                                                               aMainLast = aReferences.end();
1528   for (; aMainIt != aMainLast; aMainIt++) {
1529     FeaturePtr aMainListFeature = aMainIt->first;
1530     std::set<FeaturePtr> aMainRefList = aMainIt->second;
1531     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
1532                                                   aRefLast = aMainRefList.end();
1533     bool aFeatureOutOfTheList = false;
1534     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1535       FeaturePtr aRefFeature = *aRefIt;
1536       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1537     }
1538     if (!aFeatureOutOfTheList)
1539       anUnusedObjects.insert(aMainListFeature);
1540   }
1541
1542 #ifdef DEBUG_CLEAN_HISTORY
1543   anInfo.clear();
1544   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1545     FeaturePtr aFeature = *aFIt;
1546     anInfo.append(aFeature->name().c_str());
1547   }
1548   qDebug(QString("unused objects: [%1] - %2").
1549     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1550 #endif
1551
1552   // warn about the references remove, break the delete operation if the user chose it
1553   if (!anUnusedObjects.empty()) {
1554     QStringList aNames;
1555     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1556       aNames.append(aFeature->name().c_str());
1557     }
1558     aNames.sort();
1559     QString anUnusedNames = aNames.join(", ");
1560
1561     QString anActionId = "CLEAN_HISTORY_CMD";
1562     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1563
1564     QMessageBox aMessageBox(desktop());
1565     aMessageBox.setWindowTitle(aDescription);
1566     aMessageBox.setIcon(QMessageBox::Warning);
1567     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1568     aMessageBox.setDefaultButton(QMessageBox::No);
1569
1570     const char* aKeyStr = "Unused features are the following: "
1571                           "%1.\nThese features will be deleted.\nWould you like to continue?";
1572     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
1573     aMessageBox.setText(aText);
1574     if (aMessageBox.exec() == QMessageBox::No)
1575       return;
1576
1577     // 1. start operation
1578     aDescription += "by deleting of " +
1579       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1580     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1581     operationMgr()->startOperation(anOpAction);
1582
1583     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1584     // It is necessary to clear selection in order to avoid selection changed event during
1585     // deletion and negative consequences connected with processing of already deleted items
1586     mySelector->clearSelection();
1587
1588     std::set<FeaturePtr> anIgnoredFeatures;
1589     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
1590       operationMgr()->commitOperation();
1591     }
1592     else {
1593       operationMgr()->abortOperation(operationMgr()->currentOperation());
1594     }
1595   }
1596   else {
1597     QString anActionId = "CLEAN_HISTORY_CMD";
1598     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1599
1600     QMessageBox aMessageBox(desktop());
1601     aMessageBox.setWindowTitle(aDescription);
1602     aMessageBox.setIcon(QMessageBox::Warning);
1603     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1604     aMessageBox.setDefaultButton(QMessageBox::No);
1605
1606     QString aText;
1607     aMessageBox.setStandardButtons(QMessageBox::Ok);
1608     aMessageBox.setDefaultButton(QMessageBox::Ok);
1609
1610     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1611     aMessageBox.setText(aText);
1612
1613     if (aMessageBox.exec() == QMessageBox::No)
1614       return;
1615   }
1616 }
1617
1618 //**************************************************************
1619 void XGUI_Workshop::moveObjects()
1620 {
1621   if (!abortAllOperations())
1622     return;
1623
1624   SessionPtr aMgr = ModelAPI_Session::get();
1625
1626   QString anActionId = "MOVE_CMD";
1627   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1628   aMgr->startOperation(aDescription.toStdString());
1629
1630   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1631   // It is necessary to clear selection in order to avoid selection changed event during
1632   // moving and negative consequences connected with processing of already moved items
1633   mySelector->clearSelection();
1634   // check whether the object can be moved. There should not be parts which are not loaded
1635   std::set<FeaturePtr> aFeatures;
1636   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1637   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
1638     return;
1639
1640   DocumentPtr anActiveDocument = aMgr->activeDocument();
1641   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1642   std::set<FeaturePtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1643   for (; anIt != aLast; anIt++) {
1644     FeaturePtr aFeature = *anIt;
1645     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
1646       continue;
1647
1648     anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1649     aCurrentFeature = anActiveDocument->currentFeature(true);
1650   }
1651   aMgr->finishOperation();
1652 }
1653
1654 //**************************************************************
1655 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
1656 {
1657   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1658   std::set<FeaturePtr> aFeatures;
1659   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
1660
1661   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
1662 }
1663
1664 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1665 {
1666   bool isFoundResultType = false;
1667   foreach(ObjectPtr anObj, theObjects)
1668   {
1669     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1670     if (aResult.get() == NULL)
1671       continue;
1672
1673     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1674     if (isFoundResultType)
1675       break;
1676   }
1677   return isFoundResultType;
1678 }
1679
1680 //**************************************************************
1681 // Returns the list of all features for theDocument and all features of
1682 // all nested parts.
1683 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1684 {
1685   std::list<FeaturePtr> aResultList;
1686   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1687   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1688     // The order of appending features of the part and the part itself is important
1689
1690     // Append features from a part feature
1691     std::list<ResultPtr> aResults;
1692     ModelAPI_Tools::allResults(aFeature, aResults);
1693     foreach (const ResultPtr& aResult, aResults) {
1694       ResultPartPtr aResultPart =
1695           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1696       if (aResultPart.get() && aResultPart->partDoc().get()) {
1697         // Recursion
1698         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1699         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1700       }
1701     }
1702
1703     aResultList.push_back(aFeature);
1704   }
1705   return aResultList;
1706 }
1707
1708 //**************************************************************
1709 // Returns the list of features placed between theObject and the current feature
1710 // in the same document. Excludes theObject, includes the current feature.
1711 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1712 {
1713   std::list<FeaturePtr> aResult;
1714   DocumentPtr aDocument = theObject->document();
1715   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1716   // find the object iterator
1717   std::list<FeaturePtr>::iterator aObjectIt =
1718     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1719   if (aObjectIt == anAllFeatures.end())
1720     return aResult;
1721   // find the current feature iterator
1722   std::list<FeaturePtr>::iterator aCurrentIt =
1723     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1724   if (aCurrentIt == anAllFeatures.end())
1725     return aResult;
1726   // check the right order
1727   if (std::distance(aObjectIt, anAllFeatures.end()) <=
1728       std::distance(aCurrentIt, anAllFeatures.end()))
1729     return aResult;
1730   // exclude the object
1731   std::advance(aObjectIt, 1);
1732   // include the current feature
1733   std::advance(aCurrentIt, 1);
1734   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1735 }
1736
1737 bool XGUI_Workshop::canMoveFeature()
1738 {
1739   QString anActionId = "MOVE_CMD";
1740
1741   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1742   QObjectPtrList aValidatedObjects;
1743   foreach (ObjectPtr aObject, aObjects) {
1744     if (!myModule->canApplyAction(aObject, anActionId))
1745       continue;
1746     // To be moved feature should be in active document
1747     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1748       continue;
1749     aValidatedObjects.append(aObject);
1750   }
1751   if (aValidatedObjects.size() != aObjects.size())
1752     aObjects = aValidatedObjects;
1753
1754   bool aCanMove = !aObjects.empty();
1755
1756   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1757   for (; anIt != aLast && aCanMove; anIt++) {
1758     ObjectPtr aObject = *anIt;
1759     // 1. Get features placed between selected and current in the document
1760     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1761     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1762     if (aFeaturesBetween.empty())
1763       aCanMove = false;
1764     else {
1765       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1766       // 2. Get all reference features to the selected object in the document
1767       std::set<FeaturePtr> aRefFeatures;
1768       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1769
1770       if (aRefFeatures.empty())
1771         continue;
1772       else {
1773         // 3. Find any placed features in all reference features
1774         std::set<FeaturePtr> aIntersectionFeatures;
1775         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1776                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1777                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1778         // 4. Return false if any reference feature is placed before current feature
1779         if (!aIntersectionFeatures.empty())
1780           aCanMove = false;
1781       }
1782     }
1783   }
1784   return aCanMove;
1785 }
1786
1787 //**************************************************************
1788 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1789 {
1790   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1791   if (!aCanBeShaded) {
1792     ResultCompSolidPtr aCompsolidResult =
1793                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1794     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1795       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1796         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1797     }
1798   }
1799   return aCanBeShaded;
1800 }
1801
1802 //**************************************************************
1803 bool XGUI_Workshop::canChangeColor() const
1804 {
1805   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1806
1807   std::set<std::string> aTypes;
1808   aTypes.insert(ModelAPI_ResultGroup::group());
1809   aTypes.insert(ModelAPI_ResultConstruction::group());
1810   aTypes.insert(ModelAPI_ResultBody::group());
1811   aTypes.insert(ModelAPI_ResultPart::group());
1812
1813   return hasResults(aObjects, aTypes);
1814 }
1815
1816 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1817 {
1818   if (!theResult.get())
1819     return;
1820
1821   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1822   if (aColorAttr.get() != NULL) {
1823     if (!aColorAttr->size()) {
1824       aColorAttr->setSize(3);
1825     }
1826     aColorAttr->setValue(0, theColor[0]);
1827     aColorAttr->setValue(1, theColor[1]);
1828     aColorAttr->setValue(2, theColor[2]);
1829   }
1830 }
1831
1832 //**************************************************************
1833 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1834 {
1835
1836   AttributeIntArrayPtr aColorAttr;
1837   // 1. find the current color of the object. This is a color of AIS presentation
1838   // The objects are iterated until a first valid color is found
1839   std::vector<int> aColor;
1840   foreach(ObjectPtr anObject, theObjects) {
1841     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1842     if (aResult.get()) {
1843       XGUI_CustomPrs::getResultColor(aResult, aColor);
1844     }
1845     else {
1846       // TODO: remove the obtaining a color from the AIS object
1847       // this does not happen never because:
1848       // 1. The color can be changed only on results
1849       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1850       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1851       if (anAISObj.get()) {
1852         aColor.resize(3);
1853         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1854       }
1855     }
1856     if (!aColor.empty())
1857       break;
1858   }
1859   if (aColor.size() != 3)
1860     return;
1861
1862   if (!abortAllOperations())
1863   return;
1864   // 2. show the dialog to change the value
1865   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1866   aDlg->setColor(aColor);
1867   aDlg->move(QCursor::pos());
1868   bool isDone = aDlg->exec() == QDialog::Accepted;
1869   if (!isDone)
1870     return;
1871
1872   bool isRandomColor = aDlg->isRandomColor();
1873
1874   // 3. abort the previous operation and start a new one
1875   SessionPtr aMgr = ModelAPI_Session::get();
1876   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1877   aMgr->startOperation(aDescription.toStdString());
1878
1879   // 4. set the value to all results
1880   std::vector<int> aColorResult = aDlg->getColor();
1881   foreach(ObjectPtr anObj, theObjects) {
1882     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1883     if (aResult.get() != NULL) {
1884       ResultCompSolidPtr aCompsolidResult =
1885         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1886       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1887         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1888           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult :
1889                                                                     aDlg->getRandomColor());
1890         }
1891       }
1892       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1893     }
1894   }
1895   aMgr->finishOperation();
1896   updateCommandStatus();
1897 }
1898
1899 //**************************************************************
1900 bool XGUI_Workshop::canChangeDeflection() const
1901 {
1902   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1903
1904   std::set<std::string> aTypes;
1905   aTypes.insert(ModelAPI_ResultGroup::group());
1906   aTypes.insert(ModelAPI_ResultConstruction::group());
1907   aTypes.insert(ModelAPI_ResultBody::group());
1908   aTypes.insert(ModelAPI_ResultPart::group());
1909
1910   return hasResults(aObjects, aTypes);
1911 }
1912
1913 void setDeflection(ResultPtr theResult, const double theDeflection)
1914 {
1915   if (!theResult.get())
1916     return;
1917
1918   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1919   if (aDeflectionAttr.get() != NULL)
1920     aDeflectionAttr->setValue(theDeflection);
1921 }
1922
1923
1924 //**************************************************************
1925 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
1926 {
1927   AttributeDoublePtr aDoubleAttr;
1928   // 1. find the current color of the object. This is a color of AIS presentation
1929   // The objects are iterated until a first valid color is found
1930   double aDeflection = -1;
1931   foreach(ObjectPtr anObject, theObjects) {
1932     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1933     if (aResult.get()) {
1934       aDeflection = XGUI_CustomPrs::getResultDeflection(aResult);
1935     }
1936     else {
1937       // TODO: remove the obtaining a color from the AIS object
1938       // this does not happen never because:
1939       // 1. The color can be changed only on results
1940       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1941       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1942       if (anAISObj.get()) {
1943         aDeflection = anAISObj->getDeflection();
1944       }
1945     }
1946     if (aDeflection > 0)
1947       break;
1948   }
1949   if (aDeflection < 0)
1950     return;
1951
1952   if (!abortAllOperations())
1953   return;
1954   // 2. show the dialog to change the value
1955   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
1956   aDlg->setDeflection(aDeflection);
1957   aDlg->move(QCursor::pos());
1958   bool isDone = aDlg->exec() == QDialog::Accepted;
1959   if (!isDone)
1960     return;
1961
1962   // 3. abort the previous operation and start a new one
1963   SessionPtr aMgr = ModelAPI_Session::get();
1964   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
1965   aMgr->startOperation(aDescription.toStdString());
1966
1967   // 4. set the value to all results
1968   aDeflection = aDlg->getDeflection();
1969   foreach(ObjectPtr anObj, theObjects) {
1970     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1971     if (aResult.get() != NULL) {
1972       ResultCompSolidPtr aCompsolidResult =
1973         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1974       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1975         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1976           setDeflection(aCompsolidResult->subResult(i), aDeflection);
1977         }
1978       }
1979       setDeflection(aResult, aDeflection);
1980     }
1981   }
1982   aMgr->finishOperation();
1983   updateCommandStatus();
1984 }
1985
1986 //**************************************************************
1987 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1988 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1989   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1990 }
1991 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1992 {
1993   foreach (ObjectPtr aObj, theList) {
1994     aObj->setDisplayed(isVisible);
1995   }
1996   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1997 }
1998
1999 //**************************************************************
2000 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2001 {
2002   // Hide all displayed objects
2003   QObjectPtrList aList = myDisplayer->displayedObjects();
2004   foreach (ObjectPtr aObj, aList) {
2005     if (module()->canEraseObject(aObj))
2006       aObj->setDisplayed(false);
2007   }
2008
2009   // Show only objects from the list
2010   foreach (ObjectPtr aObj, theList) {
2011     aObj->setDisplayed(true);
2012   }
2013   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2014 }
2015
2016
2017 //**************************************************************
2018 void XGUI_Workshop::registerValidators() const
2019 {
2020   SessionPtr aMgr = ModelAPI_Session::get();
2021   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2022 }
2023
2024 //**************************************************************
2025 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2026 {
2027   if (!theDoc)
2028     return;
2029   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2030   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2031 }
2032
2033 //**************************************************************
2034 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2035 {
2036   for (int i = 0; i < theDoc->size(theGroup); i++)
2037     theDoc->object(theGroup, i)->setDisplayed(true);
2038     //displayObject(theDoc->object(theGroup, i));
2039   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2040 }
2041
2042 //**************************************************************
2043 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2044 {
2045   foreach(ObjectPtr aObj, theList) {
2046     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
2047
2048     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
2049     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2050       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2051           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
2052                                       (XGUI_Displayer::DisplayMode)theMode, false);
2053       }
2054     }
2055   }
2056   if (theList.size() > 0)
2057     myDisplayer->updateViewer();
2058 }
2059
2060 //**************************************************************
2061 void XGUI_Workshop::closeDocument()
2062 {
2063   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2064   while (anOperation) {
2065     anOperation->abort();
2066     anOperation = operationMgr()->currentOperation();
2067   }
2068   //myDisplayer->closeLocalContexts();
2069   myDisplayer->eraseAll();
2070   objectBrowser()->clearContent();
2071
2072   module()->closeDocument();
2073
2074   // data model need not process the document's signals about objects modifications as
2075   // the document is closed
2076   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2077
2078   SessionPtr aMgr = ModelAPI_Session::get();
2079   aMgr->closeAll();
2080
2081   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2082 }
2083
2084 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2085 {
2086   XGUI_HistoryMenu* aMenu = NULL;
2087   if (isSalomeMode()) {
2088     QAction* anAction = qobject_cast<QAction*>(theObject);
2089     if (!anAction)
2090       return;
2091     aMenu = new XGUI_HistoryMenu(anAction);
2092   } else {
2093     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2094     aMenu = new XGUI_HistoryMenu(aButton);
2095   }
2096   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2097   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2098 }
2099
2100 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2101 {
2102   QList<ActionInfo> aResult;
2103   std::list<std::string>::const_iterator it = theList.cbegin();
2104   for (; it != theList.cend(); it++) {
2105     QString anId = QString::fromStdString(*it);
2106     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2107     if (isEditing) {
2108       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2109     }
2110     ActionInfo anInfo;
2111     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2112     if (aContextMenuAct) {
2113       anInfo.initFrom(aContextMenuAct);
2114     } else {
2115       anInfo = myActionsMgr->actionInfoById(anId);
2116     }
2117     if (isEditing) {
2118       anInfo.text = anInfo.text.prepend("Modify ");
2119     }
2120     aResult << anInfo;
2121   }
2122   return aResult;
2123 }
2124
2125 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2126 {
2127 #ifdef HAVE_SALOME
2128   salomeConnector()->putInfo(theMessage, -1);
2129 #else
2130   myMainWindow->putInfo(theMessage, -1);
2131 #endif
2132 }
2133
2134 void XGUI_Workshop::synchronizeViewer()
2135 {
2136   SessionPtr aMgr = ModelAPI_Session::get();
2137   DocumentPtr aDoc = aMgr->activeDocument();
2138
2139   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2140   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2141   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2142   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2143 }
2144
2145 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2146                                              const std::string& theGroup,
2147                                              bool theUpdateViewer)
2148 {
2149   ObjectPtr aObj;
2150   int aSize = theDoc->size(theGroup);
2151   for (int i = 0; i < aSize; i++) {
2152     aObj = theDoc->object(theGroup, i);
2153     if (aObj->isDisplayed()) {
2154       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2155       // be changed to the object becomes visible when the shape becomes not empty
2156       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2157       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2158         continue;
2159       myDisplayer->display(aObj, false);
2160     }
2161   }
2162   if (theUpdateViewer)
2163     myDisplayer->updateViewer();
2164 }
2165
2166 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2167 {
2168   FeaturePtr aFeature;
2169   QObjectPtrList aSelList = theObjects;
2170   bool aHasHidden = false;
2171   foreach(ObjectPtr aObj, theObjects) {
2172     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2173     if (aFeature.get()) {
2174       std::list<ResultPtr> aResults;
2175       ModelAPI_Tools::allResults(aFeature, aResults);
2176       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2177       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2178         aHasHidden |= (*aIt)->isConcealed();
2179         aSelList.append(*aIt);
2180       }
2181     }
2182   }
2183   if (aSelList.count() > theObjects.count()) {
2184     // if something was found
2185     bool aBlocked = objectBrowser()->blockSignals(true);
2186     objectBrowser()->setObjectsSelected(aSelList);
2187     objectBrowser()->blockSignals(aBlocked);
2188   }
2189   if (aHasHidden)
2190     QMessageBox::information(desktop(), tr("Find results"),
2191                              tr("Results not found"), QMessageBox::Ok);
2192 }
2193
2194 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2195 {
2196   ResultPtr aResult;
2197   QObjectPtrList aSelList = theObjects;
2198   FeaturePtr aFeature;
2199   foreach(ObjectPtr aObj, theObjects) {
2200     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2201     if (aResult.get()) {
2202       aFeature = ModelAPI_Feature::feature(aResult);
2203       if (aFeature.get()) {
2204         aSelList.append(aFeature);
2205       }
2206     }
2207   }
2208   if (aSelList.count() > theObjects.count()) {
2209     // if something was found
2210     bool aBlocked = objectBrowser()->blockSignals(true);
2211     objectBrowser()->setObjectsSelected(aSelList);
2212     objectBrowser()->blockSignals(aBlocked);
2213   }
2214 }