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