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