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