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