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