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