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