Salome HOME
Remove French translations
[modules/shaper.git] / src / XGUI / XGUI_Workshop.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "XGUI_Workshop.h"
21
22 #include "XGUI_ActionsMgr.h"
23 #include "XGUI_ActiveControlMgr.h"
24 #include "XGUI_ActiveControlSelector.h"
25 #include "XGUI_MenuMgr.h"
26 #include "XGUI_ColorDialog.h"
27 #include "XGUI_DeflectionDialog.h"
28 #include "XGUI_TransparencyWidget.h"
29 #include "XGUI_ContextMenuMgr.h"
30 #include "XGUI_Displayer.h"
31 #include "XGUI_ErrorDialog.h"
32 #include "XGUI_ErrorMgr.h"
33 #include "XGUI_FacesPanel.h"
34 #include "XGUI_FacesPanelSelector.h"
35 #include "XGUI_ModuleConnector.h"
36 #include "XGUI_ObjectsBrowser.h"
37 #include "XGUI_OperationMgr.h"
38 #include "XGUI_PropertyPanel.h"
39 #include "XGUI_PropertyPanelSelector.h"
40 #include "XGUI_PropertyDialog.h"
41 #include "XGUI_SalomeConnector.h"
42 #include "XGUI_Selection.h"
43 #include "XGUI_SelectionActivate.h"
44 #include "XGUI_SelectionMgr.h"
45 #include "XGUI_Tools.h"
46 #include "XGUI_ViewerProxy.h"
47 #include "XGUI_WorkshopListener.h"
48 #include <XGUI_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   myDisplayer->displayTrihedron(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(ModuleBase_Tools::translate("workshop",
756     theOperation->getDescription()->description().toStdString()));
757 #else
758   std::string aFeatureName = aFeature->name();
759   myPropertyPanel->setWindowTitle(QString("%1: %2")
760     .arg(translate(theOperation->getDescription()->description()))
761     .arg(translate(aFeatureName.c_str())));
762 #endif
763
764   myErrorMgr->setPropertyPanel(myPropertyPanel);
765 }
766
767 //******************************************************
768 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
769 {
770   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
771   if (aPropertyPanel) {
772     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
773     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
774        myModule->connectToPropertyPanel(aWidget, isToConnect);
775        if (isToConnect) {
776         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
777         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
778         connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
779        }
780       else {
781         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
782         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
783         disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
784       }
785     }
786   }
787 }
788
789 //******************************************************
790 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
791 {
792   setGrantedFeatures(theOperation);
793
794   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
795     fillPropertyPanel(theOperation);
796     connectToPropertyPanel(true);
797     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
798       (theOperation);
799     if (aFOperation)
800       myPropertyPanel->updateApplyPlusButton(aFOperation->feature());
801     else
802       myPropertyPanel->updateApplyPlusButton(FeaturePtr());
803   }
804   updateCommandStatus();
805
806   myModule->operationResumed(theOperation);
807 }
808
809 //******************************************************
810 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
811 {
812   updateCommandStatus();
813
814   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
815                                                                         (theOperation);
816   if (!aFOperation)
817     return;
818
819   ModuleBase_ISelection* aSel = mySelector->selection();
820   QObjectPtrList aObj = aSel->selectedPresentations();
821   //!< No need for property panel
822   hidePanel(myPropertyPanel);
823   myPropertyPanel->cleanContent();
824
825   connectToPropertyPanel(false);
826   myModule->operationStopped(aFOperation);
827
828   // the deactivated objects of the current operation should be activated back.
829   // They were deactivated on operation start or an object redisplay
830   QObjectPtrList anObjects;
831   FeaturePtr aFeature = aFOperation->feature();
832   if (aFeature.get()) { // feature may be not created (plugin load fail)
833     if (myDisplayer->isVisible(aFeature) && !selectionActivate()->isActive(aFeature))
834       anObjects.append(aFeature);
835     std::list<ResultPtr> aResults;
836     ModelAPI_Tools::allResults(aFeature, aResults);
837     std::list<ResultPtr>::const_iterator aIt;
838     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
839       ResultPtr anObject = *aIt;
840       if (myDisplayer->isVisible(anObject) && !selectionActivate()->isActive(anObject)) {
841         anObjects.append(anObject);
842       }
843     }
844   }
845   activateObjectsSelection(anObjects);
846 }
847
848 //******************************************************
849 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
850 {
851   myModule->operationCommitted(theOperation);
852 }
853
854 //******************************************************
855 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
856 {
857   myModule->operationAborted(theOperation);
858 }
859
860 //******************************************************
861 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
862 {
863   ModuleBase_OperationFeature* aFOperation =
864     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
865   if (!aFOperation)
866     return;
867
868   QStringList aGrantedIds;
869   if (isSalomeMode()) {
870     const std::shared_ptr<Config_FeatureMessage>& anInfo =
871                          mySalomeConnector->featureInfo(theOperation->id());
872     if (anInfo.get())
873       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
874                                    .split(" ", QString::SkipEmptyParts);
875   }
876   else
877     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
878
879   ModuleBase_IModule* aModule = module();
880   if (aModule)
881     aModule->grantedOperationIds(theOperation, aGrantedIds);
882
883   aFOperation->setGrantedOperationIds(aGrantedIds);
884 }
885
886 //******************************************************
887 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
888 {
889   QApplication::restoreOverrideCursor();
890   SessionPtr aMgr = ModelAPI_Session::get();
891
892   std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
893   std::list<DocumentPtr>::const_iterator aIt;
894   for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
895     std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
896     (*aIt)->storeNodesState(aState);
897   }
898
899   aMgr->save(theName.toLatin1().constData(), theFileNames);
900
901   QApplication::restoreOverrideCursor();
902 }
903
904 //******************************************************
905 bool XGUI_Workshop::abortAllOperations()
906 {
907   return myOperationMgr->abortAllOperations();
908 }
909
910 //******************************************************
911 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
912 {
913   setGrantedFeatures(theOperation);
914   if (!theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
915     updateCommandStatus();
916   }
917   else {
918     myModule->operationStarted(theOperation);
919   }
920 }
921
922 //******************************************************
923 void XGUI_Workshop::onOpen()
924 {
925   if(!abortAllOperations())
926     return;
927   //save current file before close if modified
928   SessionPtr aSession = ModelAPI_Session::get();
929   if (aSession->isModified()) {
930     int anAnswer = QMessageBox::question(
931         desktop(), tr("Save current file"),
932         tr("The document is modified, save before opening another?"),
933         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
934     if (anAnswer == QMessageBox::Save) {
935       onSave();
936     } else if (anAnswer == QMessageBox::Cancel) {
937       return;
938     }
939     myCurrentFile = QString();
940   }
941
942   //show file dialog, check if readable and open
943   qreal aRatio = ModuleBase_Tools::currentPixelRatio();
944   // If the ratio is > 1 (HD screen) then QT has a bug in
945   // displaying of system open file dialog (too small)
946   QString aFile = QFileDialog::getOpenFileName(desktop(), tr("Open file"), QString(), MyFilter,
947     Q_NULLPTR, ((aRatio > 1)? QFileDialog::DontUseNativeDialog : QFileDialog::Options()));
948   if (!aFile.isNull())
949     openFile(aFile);
950 }
951
952 //******************************************************
953 void XGUI_Workshop::openFile(const QString& theDirectory)
954 {
955   myCurrentFile = theDirectory;
956   if (myCurrentFile.isEmpty())
957     return;
958
959   QFileInfo aFileInfo(myCurrentFile);
960   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
961     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
962     myCurrentFile = QString();
963     return;
964   }
965
966   QApplication::setOverrideCursor(Qt::WaitCursor);
967   module()->closeDocument();
968   SessionPtr aSession = ModelAPI_Session::get();
969   aSession->closeAll();
970
971   clearTemporaryDir();
972   if (!XGUI_CompressFiles::uncompress(myCurrentFile, myTmpDir.path()))
973     return;
974
975   aSession->load(myTmpDir.path().toLatin1().constData());
976   myObjectBrowser->rebuildDataTree();
977
978   // Open first level of data tree
979   DocumentPtr aRootDoc = aSession->moduleDocument();
980   std::list<bool> aStates;
981   aRootDoc->restoreNodesState(aStates);
982   myObjectBrowser->setStateForDoc(aRootDoc, aStates);
983
984   updateCommandStatus();
985 #ifndef HAVE_SALOME
986   myMainWindow->setCurrentDir(myCurrentFile, true);
987 #endif
988
989 #ifdef _DEBUG
990   bool aNewPart = Config_PropManager::boolean("Plugins", "create_part_by_start");
991   if (aNewPart) {
992
993     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
994     int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
995     if (aSize > 0 ) {
996       ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), 0);
997       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
998       if (aPart.get())
999         aPart->activate();
1000     }
1001   }
1002 #endif
1003
1004   QApplication::restoreOverrideCursor();
1005 }
1006
1007 //******************************************************
1008 void XGUI_Workshop::onNew()
1009 {
1010   QApplication::setOverrideCursor(Qt::WaitCursor);
1011   if (objectBrowser() == 0) {
1012     createDockWidgets();
1013     mySelector->connectViewers();
1014   }
1015   myViewerProxy->connectToViewer();
1016   showObjectBrowser();
1017 #ifndef HAVE_SALOME
1018   myMainWindow->showPythonConsole();
1019   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
1020   aWnd->showMaximized();
1021   updateCommandStatus();
1022 #endif
1023   myContextMenuMgr->connectViewer();
1024   QApplication::restoreOverrideCursor();
1025 }
1026
1027 #ifndef HAVE_SALOME
1028 //******************************************************
1029 void XGUI_Workshop::onExit()
1030 {
1031   SessionPtr aMgr = ModelAPI_Session::get();
1032   if (aMgr->isModified()) {
1033     int anAnswer = QMessageBox::question(
1034         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
1035         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
1036     if (anAnswer == QMessageBox::Save) {
1037       bool saved = onSave();
1038       if (!saved) {
1039         return;
1040       }
1041     } else if (anAnswer == QMessageBox::Cancel) {
1042       return;
1043     }
1044   }
1045   qApp->exit();
1046 }
1047
1048 //******************************************************
1049 void XGUI_Workshop::onPreferences()
1050 {
1051   ModuleBase_Prefs aModif;
1052   ModuleBase_Preferences::editPreferences(aModif);
1053   if (aModif.size() > 0) {
1054     QString aSection;
1055     foreach (ModuleBase_Pref aPref, aModif)
1056     {
1057       aSection = aPref.first;
1058       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1059         myMainWindow->viewer()->updateFromResources();
1060       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1061         myMainWindow->menuObject()->updateFromResources();
1062       }
1063     }
1064     displayer()->redisplayObjects();
1065   }
1066 }
1067 #endif
1068
1069 //******************************************************
1070 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
1071 {
1072   XGUI_Displayer* aDisplayer = displayer();
1073   if (aDisplayer) {
1074     aDisplayer->displayTrihedron(theState);
1075     aDisplayer->updateViewer();
1076   }
1077 }
1078
1079 //******************************************************
1080 bool XGUI_Workshop::onSave()
1081 {
1082   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
1083     return false;
1084   if (myCurrentFile.isEmpty()) {
1085     return onSaveAs();
1086   }
1087   SessionPtr aMgr = ModelAPI_Session::get();
1088   if (aMgr->isAutoUpdateBlocked())
1089     aMgr->blockAutoUpdate(false);
1090
1091   std::list<std::string> aFiles;
1092   // issue #2899: create a temporary directory, save and then remove it
1093 #ifdef HAVE_SALOME
1094   std::string aTmpDir = XGUI_Tools::getTmpDirByEnv("SALOME_TMP_DIR");
1095 #else
1096   std::string aTmpDir = XGUI_Tools::getTmpDirByEnv("");
1097 #endif
1098   saveDocument(QString(aTmpDir.c_str()), aFiles);
1099   bool aResult = XGUI_CompressFiles::compress(myCurrentFile, aFiles);
1100   XGUI_Tools::removeTemporaryFiles(aTmpDir, aFiles);
1101
1102   if (aResult) {
1103     updateCommandStatus();
1104 #ifndef HAVE_SALOME
1105     myMainWindow->setModifiedState(false);
1106 #endif
1107   }
1108   return aResult;
1109 }
1110
1111 //******************************************************
1112 bool XGUI_Workshop::onSaveAs()
1113 {
1114   if(!myOperationMgr->abortAllOperations(XGUI_OperationMgr::XGUI_InformationMessage))
1115     return false;
1116   qreal aRatio = ModuleBase_Tools::currentPixelRatio();
1117   myCurrentFile = QFileDialog::getSaveFileName(desktop(), tr("Select name to save file..."),
1118     QString(), MyFilter2,
1119     Q_NULLPTR, ((aRatio > 1) ? QFileDialog::DontUseNativeDialog : QFileDialog::Options()));
1120   if (!myCurrentFile.isNull()) {
1121     if (!myCurrentFile.endsWith(MyExtension)) {
1122       myCurrentFile += MyExtension;
1123     }
1124   }
1125   else
1126     return false;
1127 #ifndef HAVE_SALOME
1128     myMainWindow->setCurrentDir(myCurrentFile, false);
1129     myMainWindow->setModifiedState(false);
1130 #endif
1131   return onSave();
1132 }
1133
1134 //******************************************************
1135 void XGUI_Workshop::onUndo(int theTimes)
1136 {
1137   processUndoRedo(ActionUndo, theTimes);
1138   myObjectBrowser->updateAllIndexes(1);
1139 }
1140
1141 //******************************************************
1142 void XGUI_Workshop::onRedo(int theTimes)
1143 {
1144   processUndoRedo(ActionRedo, theTimes);
1145   myObjectBrowser->updateAllIndexes(1);
1146 }
1147
1148 //******************************************************
1149 void XGUI_Workshop::processUndoRedo(const ModuleBase_ActionType theActionType, int theTimes)
1150 {
1151   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1152   if (anActiveWidget) {
1153     ActionIntParamPtr aParam(new ModuleBase_ActionIntParameter(theTimes));
1154     if (anActiveWidget->processAction(theActionType, aParam))
1155       return;
1156   }
1157   // the viewer update should be blocked in order to avoid the features blinking. For the created
1158   // feature a results are created, the flush of the created signal caused the viewer redisplay for
1159   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
1160   // until redo of all possible objects happens
1161   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1162
1163   SessionPtr aMgr = ModelAPI_Session::get();
1164   if (aMgr->isOperation()) {
1165     XGUI_OperationMgr* aOpMgr = operationMgr();
1166     /// this is important for nested operations
1167     /// when sketch operation is active, this condition is false and
1168     /// the sketch operation is not aborted
1169     if (aOpMgr->canStopOperation(aOpMgr->currentOperation()))
1170       aOpMgr->abortOperation(aOpMgr->currentOperation());
1171     else
1172     {
1173       myDisplayer->enableUpdateViewer(isUpdateEnabled);
1174       return;
1175     }
1176   }
1177   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1178   std::list<std::string> anActionList = theActionType == ActionUndo ? aMgr->undoList()
1179     : aMgr->redoList();
1180   std::list<std::string>::const_iterator aIt = anActionList.cbegin();
1181   for (int i = 0; (i < theTimes) && (aIt != anActionList.cend()); ++i, ++aIt) {
1182     if (theActionType == ActionUndo)
1183       aMgr->undo();
1184     else
1185       aMgr->redo();
1186
1187     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1188       myObjectBrowser->rebuildDataTree();
1189   }
1190   operationMgr()->updateApplyOfOperations();
1191   facesPanel()->reset(true);
1192   updateCommandStatus();
1193
1194   // unblock the viewer update functionality and make update on purpose
1195   myDisplayer->enableUpdateViewer(isUpdateEnabled);
1196   myDisplayer->updateViewer();
1197   // Clear messages in status bar from previous operations if exists
1198   setStatusBarMessage("");
1199 }
1200
1201 //******************************************************
1202 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1203 {
1204   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1205   //ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1206   //if (anOperation) {
1207   //  ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1208   //  if (aPanel)
1209   //    anActiveWidget = aPanel->activeWidget();
1210   //}
1211   if (anActiveWidget)
1212     operationMgr()->onValidateOperation();
1213
1214   myModule->widgetStateChanged(thePreviousState);
1215 }
1216
1217 //******************************************************
1218 void XGUI_Workshop::onValuesChanged()
1219 {
1220   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1221   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1222     return;
1223
1224   ModuleBase_ModelWidget* anActiveWidget = 0;
1225   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1226   if (anOperation) {
1227     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1228     if (aPanel)
1229       anActiveWidget = aPanel->activeWidget();
1230   }
1231   if (anActiveWidget) {
1232     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1233                                                                            (anActiveWidget);
1234     if (aWidgetValidated)
1235       aWidgetValidated->clearValidatedCash();
1236   }
1237 }
1238
1239 //******************************************************
1240 void XGUI_Workshop::onWidgetObjectUpdated()
1241 {
1242   operationMgr()->onValidateOperation();
1243   myDisplayer->updateViewer();
1244 }
1245
1246 //******************************************************
1247 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1248 {
1249   QString libName = QString::fromStdString(library(theModule.toStdString()));
1250   if (libName.isEmpty()) {
1251     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1252     return 0;
1253   }
1254
1255   QString err;
1256   CREATE_FUNC crtInst = 0;
1257
1258 #ifdef WIN32
1259   HINSTANCE modLib = ::LoadLibraryA(qPrintable(libName));
1260   if (!modLib) {
1261     LPVOID lpMsgBuf;
1262     ::FormatMessage(
1263         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1264         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1265     QString aMsg((char*) &lpMsgBuf);
1266     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1267     ::LocalFree(lpMsgBuf);
1268   } else {
1269     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1270     if (!crtInst) {
1271       LPVOID lpMsgBuf;
1272       ::FormatMessage(
1273           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1274               | FORMAT_MESSAGE_IGNORE_INSERTS,
1275           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1276       QString aMsg((char*) &lpMsgBuf);
1277       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1278       ::LocalFree(lpMsgBuf);
1279     }
1280   }
1281 #else
1282   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1283   if ( !modLib ) {
1284     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1285   } else {
1286     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1287     if ( !crtInst ) {
1288       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1289     }
1290   }
1291 #endif
1292
1293   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1294
1295   if (!err.isEmpty()) {
1296     if (desktop()) {
1297       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1298     } else {
1299       qWarning(qPrintable(err));
1300     }
1301   }
1302   return aModule;
1303 }
1304
1305 //******************************************************
1306 bool XGUI_Workshop::createModule()
1307 {
1308   Config_ModuleReader aModuleReader;
1309   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1310   myModule = loadModule(moduleName);
1311   if (!myModule)
1312     return false;
1313
1314   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1315   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1316   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1317   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1318
1319   myModule->createFeatures();
1320 #ifdef HAVE_SALOME
1321   salomeConnector()->createFeatureActions();
1322 #endif
1323   //myActionsMgr->update();
1324   return true;
1325 }
1326
1327 //******************************************************
1328 void XGUI_Workshop::updateCommandStatus()
1329 {
1330   QList<QAction*> aCommands;
1331 #ifdef HAVE_SALOME
1332     aCommands = salomeConnector()->commandList();
1333 #else
1334     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1335     foreach (AppElements_Command* aCmd, aMenuBar->features())
1336       aCommands.append(aCmd);
1337 #endif
1338   SessionPtr aMgr = ModelAPI_Session::get();
1339   if (aMgr->hasModuleDocument()) {
1340     foreach(QAction* aCmd, aCommands) {
1341       QString aId = aCmd->data().toString();
1342       if (aId == "UNDO_CMD") {
1343         bool isActionEnabled = false;
1344         // if ultimate is true -> using result of operation only, or using OR combination
1345         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1346         if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled))
1347           aCmd->setEnabled(isActionEnabled);
1348         else
1349           aCmd->setEnabled(myModule->canUndo());
1350       }
1351       else if (aId == "REDO_CMD") {
1352         bool isActionEnabled = false;
1353         // if ultimate is true -> using result of operation only, or using OR combination
1354         ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1355         if (anActiveWidget && anActiveWidget->canProcessAction(ActionRedo, isActionEnabled))
1356           aCmd->setEnabled(isActionEnabled);
1357         else
1358           aCmd->setEnabled(myModule->canRedo());
1359       }
1360       else if (aId == "AUTOCOMPUTE_CMD") {
1361         aCmd->setIcon(aMgr->isAutoUpdateBlocked() ?
1362           QIcon(":pictures/autoapply_stop.png") :
1363           QIcon(":pictures/autoapply_start.png"));
1364       }
1365       else
1366         // Enable all commands
1367         aCmd->setEnabled(true);
1368     }
1369     updateHistory();
1370   } else {
1371     foreach(QAction* aCmd, aCommands) {
1372       QString aId = aCmd->data().toString();
1373       if (aId == "NEW_CMD")
1374         aCmd->setEnabled(true);
1375       else if (aId == "EXIT_CMD")
1376         aCmd->setEnabled(true);
1377       else
1378         aCmd->setEnabled(false);
1379     }
1380   }
1381   myActionsMgr->updateCommandsStatus();
1382   emit commandStatusUpdated();
1383 }
1384
1385 //******************************************************
1386 void XGUI_Workshop::updateHistory()
1387 {
1388   bool isActionEnabled = false;
1389   ModuleBase_ModelWidget* anActiveWidget = myOperationMgr->activeWidget();
1390   QList<ActionInfo> aUndoRes;
1391   QList<ActionInfo> aRedoRes;
1392   if (anActiveWidget && anActiveWidget->canProcessAction(ActionUndo, isActionEnabled)) {
1393     aUndoRes = anActiveWidget->actionsList(ActionUndo);
1394     aRedoRes = anActiveWidget->actionsList(ActionRedo);
1395   } else {
1396     std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1397     aUndoRes = processHistoryList(aUndoList);
1398
1399     std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1400     aRedoRes = processHistoryList(aRedoList);
1401   }
1402   emit updateUndoHistory(aUndoRes);
1403   emit updateRedoHistory(aRedoRes);
1404 }
1405
1406 //******************************************************
1407 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1408 {
1409   QDockWidget* aObjDock = new QDockWidget(theParent);
1410   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1411                             Qt::RightDockWidgetArea);
1412   aObjDock->setWindowTitle(tr("Object browser"));
1413   aObjDock->setStyleSheet(
1414       "::title { position: relative; padding-left: 5px; text-align: left center }");
1415   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock, this);
1416   myObjectBrowser->initialize(myModule->rootNode());
1417   myModule->customizeObjectBrowser(myObjectBrowser);
1418   aObjDock->setWidget(myObjectBrowser);
1419
1420   connect(myObjectBrowser, SIGNAL(sizeChanged()), SLOT(onDockSizeChanged()));
1421
1422   myContextMenuMgr->connectObjectBrowser();
1423   return aObjDock;
1424 }
1425
1426 //******************************************************
1427 /*
1428  * Creates dock widgets, places them in corresponding area
1429  * and tabifies if necessary.
1430  */
1431 void XGUI_Workshop::createDockWidgets()
1432 {
1433   QMainWindow* aDesktop = desktop();
1434   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1435   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1436   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1437   myActiveControlMgr->addSelector(new XGUI_PropertyPanelSelector(myPropertyPanel));
1438
1439   myPropertyPanel->setupActions(myActionsMgr);
1440   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1441                                    Qt::RightDockWidgetArea);
1442   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1443
1444   hidePanel(myPropertyPanel);  ///<! Invisible by default
1445
1446   myFacesPanel = new XGUI_FacesPanel(aDesktop, myModuleConnector);
1447   myActiveControlMgr->addSelector(new XGUI_FacesPanelSelector(myFacesPanel));
1448   myFacesPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1449                                 Qt::RightDockWidgetArea |
1450                                 Qt::BottomDockWidgetArea);
1451   connect(myFacesPanel, SIGNAL(closed()), myFacesPanel, SLOT(onClosed()));
1452
1453   myInspectionPanel = new XGUI_InspectionPanel(aDesktop, mySelector);
1454   myInspectionPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1455     Qt::RightDockWidgetArea);
1456   aDesktop->addDockWidget(Qt::RightDockWidgetArea, myInspectionPanel);
1457
1458   myInspectionPanel->hide();
1459
1460   aDesktop->addDockWidget(
1461 #ifdef HAVE_SALOME
1462     Qt::RightDockWidgetArea,
1463 #else
1464     Qt::LeftDockWidgetArea,
1465 #endif
1466     myFacesPanel);
1467   hidePanel(myFacesPanel);  ///<! Invisible by default
1468
1469 #ifdef _DEBUG
1470   bool aShowOnTheRight = Config_PropManager::boolean("Plugins", "show_hide_faces");
1471   if (aShowOnTheRight) {
1472     aDesktop->addDockWidget(Qt::RightDockWidgetArea, myFacesPanel);
1473     showPanel(myFacesPanel);
1474   }
1475 #endif
1476   hideObjectBrowser();
1477
1478 #ifndef HAVE_SALOME
1479 #ifdef _DEBUG
1480   if (!aShowOnTheRight)
1481   {
1482 #endif // _DEBUG
1483   aDesktop->tabifyDockWidget(myFacesPanel, aObjDock);
1484 #ifdef _DEBUG
1485   }
1486 #endif // _DEBUG
1487
1488 #endif // HAVE_SALOME
1489
1490   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1491   myPropertyPanel->installEventFilter(myOperationMgr);
1492
1493   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1494   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1495
1496   QAction* aOkContAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptPlus);
1497   connect(aOkContAct, SIGNAL(triggered()), this, SLOT(onAcceptPlusActionClicked()));
1498
1499   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1500   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1501
1502   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1503   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1504
1505   QAction* aHelpAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Help);
1506   connect(aHelpAct, SIGNAL(triggered()), this, SLOT(onHelpActionClicked()));
1507
1508   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1509           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1510   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1511           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1512 }
1513
1514 //******************************************************
1515 void XGUI_Workshop::showPanel(QDockWidget* theDockWidget)
1516 {
1517   if (theDockWidget == myPropertyPanel) {
1518     QAction* aViewAct = myPropertyPanel->toggleViewAction();
1519     ///<! Restore ability to close panel from the window's menu
1520     aViewAct->setEnabled(true);
1521   }
1522   theDockWidget->show();
1523   theDockWidget->raise();
1524
1525   // The next code is necessary to made the property panel the active window
1526   // in order to operation manager could process key events of the panel.
1527   // otherwise they are ignored. It happens only if the same(activateWindow) is
1528   // not happened by property panel activation(e.g. resume operation of Sketch)
1529   ModuleBase_Tools::setFocus(theDockWidget, "XGUI_Workshop::showPanel()");
1530 }
1531
1532 //******************************************************
1533 void XGUI_Workshop::hidePanel(QDockWidget* theDockWidget)
1534 {
1535   if (theDockWidget && theDockWidget == myPropertyPanel) {
1536     QAction* aViewAct = theDockWidget->toggleViewAction();
1537     ///<! Do not allow to show empty property panel
1538     aViewAct->setEnabled(false);
1539   }
1540   theDockWidget->hide();
1541
1542   // the property panel is active window of the desktop, when it is
1543   // hidden, it is undefined which window becomes active. By this reason
1544   // it is defined to perform the desktop as the active window.
1545   // in SALOME mode, work-stack made the PyConsole the active window,
1546   // set the focus on it. As a result, shortcuts of the application, like
1547   // are processed by this console. For example Undo actions.
1548   // It is possible that this code is to be moved to SHAPER package
1549   QMainWindow* aDesktop = desktop();
1550   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::hidePanel()");
1551 }
1552
1553 //******************************************************
1554 void XGUI_Workshop::showObjectBrowser()
1555 {
1556   if (!isSalomeMode()) {
1557     myObjectBrowser->parentWidget()->show();
1558   }
1559 }
1560
1561 //******************************************************
1562 void XGUI_Workshop::hideObjectBrowser()
1563 {
1564   if (!isSalomeMode())
1565     myObjectBrowser->parentWidget()->hide();
1566 }
1567
1568 //******************************************************
1569 void XGUI_Workshop::salomeViewerSelectionChanged()
1570 {
1571   emit salomeViewerSelection();
1572 }
1573
1574 //**************************************************************
1575 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1576 {
1577   return mySalomeConnector->viewer();
1578 }
1579
1580 //**************************************************************
1581 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1582 {
1583   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1584   if (theId == "DELETE_CMD")
1585     deleteObjects();
1586   else if (theId == "CLEAN_HISTORY_CMD")
1587     cleanHistory();
1588   else if (theId == "MOVE_CMD")
1589     moveObjects();
1590   else if (theId == "COLOR_CMD")
1591     changeColor(aObjects);
1592   else if (theId == "DEFLECTION_CMD")
1593     changeDeflection(aObjects);
1594   else if (theId == "TRANSPARENCY_CMD")
1595     changeTransparency(aObjects);
1596   else if (theId == "SHOW_CMD") {
1597     showObjects(aObjects, true);
1598     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1599     updateCommandStatus();
1600   }
1601   else if (theId == "HIDE_CMD") {
1602     showObjects(aObjects, false);
1603     updateCommandStatus();
1604   }
1605   else if (theId == "SHOW_ONLY_CMD") {
1606     showOnlyObjects(aObjects);
1607     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1608     updateCommandStatus();
1609   }
1610   else if (theId == "SHADING_CMD")
1611     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1612   else if (theId == "WIREFRAME_CMD")
1613     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1614   else if (theId == "HIDEALL_CMD") {
1615     QObjectPtrList aList = myDisplayer->displayedObjects();
1616     foreach (ObjectPtr aObj, aList) {
1617       if (module()->canEraseObject(aObj))
1618         aObj->setDisplayed(false);
1619     }
1620     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1621 #ifdef HAVE_SALOME
1622     //issue #2159 Hide all incomplete behavior
1623     viewer()->eraseAll();
1624 #endif
1625     updateCommandStatus();
1626     // Necessary for update icons in ObjectBrowser on Linux
1627     myObjectBrowser->updateAllIndexes();
1628   } else if (theId == "SELECT_VERTEX_CMD") {
1629     setViewerSelectionMode(TopAbs_VERTEX);
1630   } else if (theId == "SELECT_EDGE_CMD") {
1631     setViewerSelectionMode(TopAbs_EDGE);
1632   } else if (theId == "SELECT_FACE_CMD") {
1633     setViewerSelectionMode(TopAbs_FACE);
1634   } else if (theId == "INSERT_FOLDER_CMD") {
1635     insertFeatureFolder();
1636   } else if (theId == "ADD_TO_FOLDER_BEFORE_CMD") {
1637     insertToFolder(true);
1638   } else if (theId == "ADD_TO_FOLDER_AFTER_CMD") {
1639     insertToFolder(false);
1640   } else if (theId == "ADD_OUT_FOLDER_BEFORE_CMD") {
1641     moveOutFolder(true);
1642   } else if (theId == "ADD_OUT_FOLDER_AFTER_CMD") {
1643     moveOutFolder(false);
1644   } else if (theId == "SELECT_RESULT_CMD") {
1645     //setViewerSelectionMode(-1);
1646     //IMP: an attempt to use result selection with other selection modes
1647     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1648     setViewerSelectionMode(TopAbs_COMPSOLID);
1649   } else if (theId == "SHOW_RESULTS_CMD") {
1650     highlightResults(aObjects);
1651   } else if (theId == "SHOW_FEATURE_CMD") {
1652     highlightFeature(aObjects);
1653   } else if (theId == "SET_VIEW_NORMAL_CMD") {
1654     setNormalView();
1655   } else if (theId == "SET_VIEW_INVERTEDNORMAL_CMD") {
1656     setNormalView(true);
1657   }
1658 #ifdef TINSPECTOR
1659   else if (theId == "TINSPECTOR_VIEW") {
1660     Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1661     if (!anApplication.IsNull())
1662     {
1663       if (!MyTCommunicator)
1664       {
1665         MyTCommunicator = new TInspector_Communicator();
1666
1667         NCollection_List<Handle(Standard_Transient)> aParameters;
1668         aParameters.Append(anApplication);
1669         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1670         if (!aContext.IsNull())
1671           aParameters.Append(aContext);
1672
1673 #ifdef DEBUG_WITH_MESSAGE_REPORT
1674         Handle(Message_Report) aContextReport = aContext->GetReport();
1675         aContext->SetReportActive (Standard_True);
1676         aContextReport->SetLimit (1000);
1677         if (!aContextReport.IsNull())
1678           aParameters.Append(aContextReport);
1679 #endif
1680         MyVCallBack = new VInspector_CallBack();
1681         myDisplayer->setCallBack(MyVCallBack);
1682         #ifndef HAVE_SALOME
1683         AppElements_Viewer* aViewer = mainWindow()->viewer();
1684         if (aViewer)
1685           aViewer->setCallBack(MyVCallBack);
1686         #endif
1687         aParameters.Append(MyVCallBack);
1688
1689         MyTCommunicator->RegisterPlugin("TKDFBrowser");
1690         MyTCommunicator->RegisterPlugin("TKShapeView");
1691         MyTCommunicator->RegisterPlugin("TKVInspector");
1692 #ifdef DEBUG_WITH_MESSAGE_REPORT
1693         MyTCommunicator->RegisterPlugin("TKMessageView");
1694 #endif
1695         //MyTCommunicator->RegisterPlugin("SMBrowser"); // custom plugin to view ModelAPI
1696         //MyTCommunicator->RegisterPlugin("TKSMBrowser"); // custom plugin to view ModelAPI
1697
1698         MyTCommunicator->Init(aParameters);
1699         MyTCommunicator->Activate("TKSMBrowser"); // to have button in TInspector
1700 #ifndef DEBUG_WITH_MESSAGE_REPORT
1701         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1702 #endif
1703         MyTCommunicator->Activate("TKDFBrowser");
1704
1705 #ifdef DEBUG_WITH_MESSAGE_REPORT
1706         MyTCommunicator->Activate("TKMessageView"); // temporary
1707         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1708 #endif
1709       }
1710       MyTCommunicator->SetVisible(true);
1711     }
1712   }
1713 #endif
1714 }
1715
1716 //**************************************************************
1717 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1718 {
1719   if (theMode == -1)
1720     myViewerSelMode.clear();
1721   else {
1722     if (myViewerSelMode.contains(theMode))
1723       myViewerSelMode.removeAll(theMode);
1724     else
1725       myViewerSelMode.append(theMode);
1726   }
1727   selectionActivate()->updateSelectionModes();
1728 }
1729
1730 //**************************************************************
1731 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1732 {
1733   QIntList aModes;
1734   module()->activeSelectionModes(aModes);
1735   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1736     aModes.append(myViewerSelMode);
1737   selectionActivate()->activateObjects(aModes, theList);
1738 }
1739
1740 //**************************************************************
1741 bool XGUI_Workshop::prepareForDisplay(const std::set<ObjectPtr>& theObjects) const
1742 {
1743   if (facesPanel()->isEmpty())
1744     return true;
1745
1746   // generate container of objects taking into account sub elments of compsolid
1747   std::set<ObjectPtr> anAllProcessedObjects;
1748   for (std::set<ObjectPtr>::const_iterator anObjectsIt = theObjects.begin();
1749     anObjectsIt != theObjects.end(); anObjectsIt++) {
1750     ObjectPtr anObject = *anObjectsIt;
1751     ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObject);
1752     if (aCompRes.get()) {
1753       std::list<ResultPtr> allRes;
1754       ModelAPI_Tools::allSubs(aCompRes, allRes);
1755       if (allRes.empty()) {
1756         anAllProcessedObjects.insert(anObject);
1757       } else {
1758         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1759           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1760           if (aBody.get() && aBody->numberOfSubs() == 0)
1761             anAllProcessedObjects.insert(aBody);
1762         }
1763       }
1764     } else
1765       anAllProcessedObjects.insert(anObject);
1766   }
1767
1768   // find hidden objects in faces panel
1769   std::set<ObjectPtr> aHiddenObjects;
1770   QStringList aHiddenObjectNames;
1771   for (std::set<ObjectPtr>::const_iterator anObjectsIt = anAllProcessedObjects.begin();
1772        anObjectsIt != anAllProcessedObjects.end(); anObjectsIt++) {
1773     if (!facesPanel()->isObjectHiddenByPanel(*anObjectsIt))
1774       continue;
1775     aHiddenObjects.insert(*anObjectsIt);
1776     aHiddenObjectNames.append((*anObjectsIt)->data()->name().c_str());
1777   }
1778   if (aHiddenObjects.empty()) // in parameter objects there are no hidden objects in hide face
1779     return true;
1780
1781   int anAnswer = QMessageBox::question(
1782         desktop(), tr("Show object"),
1783         tr("'%1'\n are hidden by %2:\nRemove objects from the panel to be displayed?")
1784         .arg(aHiddenObjectNames.join(", ")).arg(facesPanel()->windowTitle()),
1785         QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
1786
1787   bool aToBeDisplayed = anAnswer == QMessageBox::Yes;
1788   if (aToBeDisplayed)
1789     facesPanel()->restoreObjects(aHiddenObjects);
1790
1791   return aToBeDisplayed;
1792 }
1793
1794 //**************************************************************
1795 void XGUI_Workshop::deleteObjects()
1796 {
1797   ModuleBase_IModule* aModule = module();
1798   // allow the module to delete objects, do nothing if it has succeed
1799   if (aModule->deleteObjects()) {
1800     updateCommandStatus();
1801     return;
1802   }
1803
1804   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1805   if (!abortAllOperations())
1806     return;
1807
1808   bool hasResult = false;
1809   bool hasFeature = false;
1810   bool hasParameter = false;
1811   bool hasCompositeOwner = false;
1812   bool hasResultInHistory = false;
1813   bool hasFolder = false;
1814   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner,
1815                                  hasResultInHistory, hasFolder);
1816   if (!(hasResult || hasFeature || hasParameter || hasFolder))
1817     return;
1818
1819   // Remove from the list non-deletable objects: infinite constuctions which are not in history
1820   bool notDelete = true;
1821   QObjectPtrList::iterator aIt;
1822   for (aIt = anObjects.begin(); aIt != anObjects.end(); aIt++) {
1823     ObjectPtr aObj = (*aIt);
1824     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
1825     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1826     notDelete = (!aFeature->isInHistory()) && aConstr->isInfinite();
1827     if (notDelete) {
1828       anObjects.removeAll(aObj);
1829       aIt--;
1830     }
1831   }
1832   // delete objects
1833   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1834   std::set<FeaturePtr> aFeatures;
1835   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1836   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1837
1838   std::set<FolderPtr> aFolders;
1839   ModuleBase_Tools::convertToFolders(anObjects, aFolders);
1840
1841   bool aDone = false;
1842   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1843   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1844   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1845
1846   operationMgr()->startOperation(anOpAction);
1847
1848   std::set<FeaturePtr> aFeatureRefsToDelete;
1849   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1850     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1851     // It is necessary to clear selection in order to avoid selection changed event during
1852     // deletion and negative consequences connected with processing of already deleted items
1853     mySelector->clearSelection();
1854
1855     if (!aFeatureRefsToDelete.empty())
1856       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1857     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1858   }
1859   if (aFolders.size() > 0) {
1860     std::set<FolderPtr>::const_iterator anIt = aFolders.begin(),
1861                                          aLast = aFolders.end();
1862     for (; anIt != aLast; anIt++) {
1863       FolderPtr aFolder = *anIt;
1864       if (aFolder.get()) {
1865         DocumentPtr aDoc = aFolder->document();
1866         aDoc->removeFolder(aFolder);
1867       }
1868     }
1869   }
1870   // remove results selected
1871   std::list<ResultPtr> aResults;
1872   for(QObjectPtrList::const_iterator anIt = anObjects.begin(); anIt != anObjects.end(); anIt++) {
1873     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anIt);
1874     if (aRes.get() && aRes->data()->isValid() && !aRes->data()->isDeleted() &&
1875         aRes->groupName() != ModelAPI_ResultGroup::group() && // don't remove groups and fields
1876         aRes->groupName() != ModelAPI_ResultField::group()) // because they are badly selected
1877       aResults.push_back(aRes);
1878   }
1879   if (!aResults.empty()) {
1880     ModelAPI_Tools::removeResults(aResults);
1881   }
1882
1883   if (aDone)
1884     operationMgr()->commitOperation();
1885   else
1886     operationMgr()->abortOperation(operationMgr()->currentOperation());
1887
1888   myDisplayer->updateViewer();
1889 }
1890
1891 //**************************************************************
1892 void addRefsToFeature(const FeaturePtr& theFeature,
1893                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1894                       std::set<FeaturePtr>& theReferences)
1895 {
1896   //if (theReferences.find(theFeature) != theReferences.end())
1897   //  return;
1898   if (theMainList.find(theFeature) == theMainList.end())
1899     return; // this feature is not in the selection list, so exists without references to it
1900   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1901
1902   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1903                                        aLast = aMainReferences.end();
1904   for (; anIt != aLast; anIt++) {
1905     FeaturePtr aRefFeature = *anIt;
1906     if (theReferences.find(aRefFeature) == theReferences.end())
1907       theReferences.insert(aRefFeature);
1908     addRefsToFeature(aRefFeature, theMainList, theReferences);
1909   }
1910 }
1911
1912 //**************************************************************
1913 void XGUI_Workshop::cleanHistory()
1914 {
1915   if (!abortAllOperations())
1916     return;
1917
1918   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1919   std::set<FeaturePtr> aFeatures;
1920   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1921
1922 #ifdef DEBUG_CLEAN_HISTORY
1923   QStringList anInfo;
1924   std::set<FeaturePtr>::const_iterator aFIt;
1925   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1926     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1927     anInfo.append(aFeature->name().c_str());
1928   }
1929   QString anInfoStr = anInfo.join(";\t");
1930   qDebug(QString("cleanHistory for: [%1] - %2").
1931     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1932 #endif
1933
1934   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1935   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1936   // find for each object whether all reference values are in the map as key, that means that there
1937   // is no other reference in the model to this object, so it might be removed by cleaning history
1938   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - can't be deleted, dependency to bool_1
1939   // ext_1(bool_1, sk_3)  - can't be deleted, dependency to bool_1
1940   // vertex_1()
1941   // sk_2(ext_2) + (bool_1)  - can't be deleted, dependency to bool_1
1942   // ext_2(bool_1)  - can't be deleted, dependency to bool_1
1943   // sk_3()
1944   // Information: bool_1 is not selected
1945   std::set<FeaturePtr> anUnusedObjects;
1946   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1947                                                               aMainLast = aReferences.end();
1948   for (; aMainIt != aMainLast; aMainIt++) {
1949     FeaturePtr aMainListFeature = aMainIt->first;
1950     std::set<FeaturePtr> aMainRefList = aMainIt->second;
1951     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
1952                                                   aRefLast = aMainRefList.end();
1953     bool aFeatureOutOfTheList = false;
1954     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1955       FeaturePtr aRefFeature = *aRefIt;
1956       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1957     }
1958     if (!aFeatureOutOfTheList)
1959       anUnusedObjects.insert(aMainListFeature);
1960   }
1961
1962 #ifdef DEBUG_CLEAN_HISTORY
1963   anInfo.clear();
1964   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1965     FeaturePtr aFeature = *aFIt;
1966     anInfo.append(aFeature->name().c_str());
1967   }
1968   qDebug(QString("unused objects: [%1] - %2").
1969     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1970 #endif
1971
1972   // warn about the references remove, break the delete operation if the user chose it
1973   if (!anUnusedObjects.empty()) {
1974     QStringList aNames;
1975     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1976       aNames.append(aFeature->name().c_str());
1977     }
1978     aNames.sort();
1979     QString anUnusedNames = aNames.join(", ");
1980
1981     QString anActionId = "CLEAN_HISTORY_CMD";
1982     QString aDescription = ModuleBase_Tools::translate("workshop",
1983         contextMenuMgr()->action(anActionId)->text().toStdString());
1984
1985     QMessageBox aMessageBox(desktop());
1986     aMessageBox.setWindowTitle(aDescription);
1987     aMessageBox.setIcon(QMessageBox::Warning);
1988     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1989     aMessageBox.setDefaultButton(QMessageBox::No);
1990
1991     const char* aKeyStr = "Unused features are the following: "
1992                           "%1.\nThese features will be deleted.\nWould you like to continue?";
1993     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
1994     aMessageBox.setText(aText);
1995     if (aMessageBox.exec() == QMessageBox::No)
1996       return;
1997
1998     // 1. start operation
1999     aDescription += "by deleting of " +
2000       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
2001     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
2002     operationMgr()->startOperation(anOpAction);
2003
2004     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
2005     // It is necessary to clear selection in order to avoid selection changed event during
2006     // deletion and negative consequences connected with processing of already deleted items
2007     mySelector->clearSelection();
2008
2009     std::set<FeaturePtr> anIgnoredFeatures;
2010     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
2011       operationMgr()->commitOperation();
2012     }
2013     else {
2014       operationMgr()->abortOperation(operationMgr()->currentOperation());
2015     }
2016   }
2017   else {
2018     QString anActionId = "CLEAN_HISTORY_CMD";
2019     QString aDescription = contextMenuMgr()->action(anActionId)->text();
2020
2021     QMessageBox aMessageBox(desktop());
2022     aMessageBox.setWindowTitle(aDescription);
2023     aMessageBox.setIcon(QMessageBox::Warning);
2024     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
2025     aMessageBox.setDefaultButton(QMessageBox::No);
2026
2027     QString aText;
2028     aMessageBox.setStandardButtons(QMessageBox::Ok);
2029     aMessageBox.setDefaultButton(QMessageBox::Ok);
2030
2031     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
2032     aMessageBox.setText(aText);
2033
2034     if (aMessageBox.exec() == QMessageBox::No)
2035       return;
2036   }
2037 }
2038
2039 //**************************************************************
2040 bool compareFeature(const FeaturePtr& theF1, const FeaturePtr& theF2) {
2041   DocumentPtr aDoc = theF1->document();
2042   return aDoc->index(theF1) < aDoc->index(theF2);
2043 }
2044 void XGUI_Workshop::moveObjects()
2045 {
2046   if (!abortAllOperations())
2047     return;
2048
2049   SessionPtr aMgr = ModelAPI_Session::get();
2050
2051   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2052   // It is necessary to clear selection in order to avoid selection changed event during
2053   // moving and negative consequences connected with processing of already moved items
2054   mySelector->clearSelection();
2055   // check whether the object can be moved. There should not be parts which are not loaded
2056   std::set<FeaturePtr> aFeatures;
2057   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
2058   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
2059     return;
2060
2061   QString anActionId = "MOVE_CMD";
2062   QString aDescription = contextMenuMgr()->action(anActionId)->text();
2063   aMgr->startOperation(aDescription.toStdString());
2064
2065   // Sort features by index in document
2066   std::list<FeaturePtr> aFList(aFeatures.begin(), aFeatures.end());
2067   aFList.sort(compareFeature);
2068
2069   DocumentPtr anActiveDocument = aMgr->activeDocument();
2070   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
2071   std::list<FeaturePtr>::const_iterator anIt = aFList.begin(), aLast = aFList.end();
2072   for (; anIt != aLast; anIt++) {
2073     FeaturePtr aFeature = *anIt;
2074     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
2075       continue;
2076
2077     anActiveDocument->moveFeature(aFeature, aCurrentFeature);
2078     aCurrentFeature = anActiveDocument->currentFeature(true);
2079   }
2080   aMgr->finishOperation();
2081   updateCommandStatus();
2082 }
2083
2084 //**************************************************************
2085 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
2086 {
2087   std::set<FeaturePtr> aFeatures;
2088   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
2089
2090   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
2091 }
2092
2093 //******************************************************
2094 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
2095 {
2096   bool isFoundResultType = false;
2097   foreach(ObjectPtr anObj, theObjects)
2098   {
2099     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2100     if (aResult.get() == NULL)
2101       continue;
2102
2103     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
2104     if (isFoundResultType)
2105       break;
2106   }
2107   return isFoundResultType;
2108 }
2109
2110 //**************************************************************
2111 // Returns the list of all features for theDocument and all features of
2112 // all nested parts.
2113 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
2114 {
2115   std::list<FeaturePtr> aResultList;
2116   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
2117   foreach (const FeaturePtr& aFeature, anAllFeatures) {
2118     // The order of appending features of the part and the part itself is important
2119
2120     // Append features from a part feature
2121     std::list<ResultPtr> aResults;
2122     ModelAPI_Tools::allResults(aFeature, aResults);
2123     foreach (const ResultPtr& aResult, aResults) {
2124       ResultPartPtr aResultPart =
2125           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
2126       if (aResultPart.get() && aResultPart->partDoc().get()) {
2127         // Recursion
2128         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
2129         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
2130       }
2131     }
2132
2133     aResultList.push_back(aFeature);
2134   }
2135   return aResultList;
2136 }
2137
2138 //**************************************************************
2139 // Returns the list of features placed between theObject and the current feature
2140 // in the same document. Excludes theObject, includes the current feature.
2141 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
2142 {
2143   std::list<FeaturePtr> aResult;
2144   DocumentPtr aDocument = theObject->document();
2145   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
2146   // find the object iterator
2147   std::list<FeaturePtr>::iterator aObjectIt =
2148     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
2149   if (aObjectIt == anAllFeatures.end())
2150     return aResult;
2151   // find the current feature iterator
2152   std::list<FeaturePtr>::iterator aCurrentIt =
2153     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
2154   if (aCurrentIt == anAllFeatures.end())
2155     return aResult;
2156   // check the right order
2157   if (std::distance(aObjectIt, anAllFeatures.end()) <=
2158       std::distance(aCurrentIt, anAllFeatures.end()))
2159     return aResult;
2160   // exclude the object
2161   std::advance(aObjectIt, 1);
2162   // include the current feature
2163   std::advance(aCurrentIt, 1);
2164   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
2165 }
2166
2167 //******************************************************
2168 bool XGUI_Workshop::canMoveFeature()
2169 {
2170   QString anActionId = "MOVE_CMD";
2171
2172   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2173   QObjectPtrList aValidatedObjects;
2174   foreach (ObjectPtr aObject, aObjects) {
2175     if (!myModule->canApplyAction(aObject, anActionId))
2176       continue;
2177     // To be moved feature should be in active document
2178     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
2179       continue;
2180     aValidatedObjects.append(aObject);
2181   }
2182   if (aValidatedObjects.size() != aObjects.size())
2183     aObjects = aValidatedObjects;
2184
2185   bool aCanMove = !aObjects.empty();
2186
2187   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
2188   for (; anIt != aLast && aCanMove; anIt++) {
2189     ObjectPtr aObject = *anIt;
2190     if (!aObject.get() || !aObject->data().get() || !aObject->data()->isValid()) {
2191       aCanMove = false;
2192       break;
2193     }
2194     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
2195     // only groups can be moved to the end for now (#2451)
2196     if (aFeat.get() && aFeat->getKind() != "Group") {
2197       aCanMove = false;
2198       break;
2199     }
2200
2201     // 1. Get features placed between selected and current in the document
2202     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
2203     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
2204     if (aFeaturesBetween.empty())
2205       aCanMove = false;
2206     else {
2207       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
2208       // 2. Get all reference features to the selected object in the document
2209       std::set<FeaturePtr> aRefFeatures;
2210       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
2211
2212       if (aRefFeatures.empty())
2213         continue;
2214       else {
2215         // 3. Find any placed features in all reference features
2216         std::set<FeaturePtr> aIntersectionFeatures;
2217         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
2218                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
2219                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
2220         // 4. Return false if any reference feature is placed before current feature
2221         if (!aIntersectionFeatures.empty())
2222           aCanMove = false;
2223       }
2224     }
2225   }
2226   return aCanMove;
2227 }
2228
2229 //**************************************************************
2230 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
2231 {
2232   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
2233   if (!aCanBeShaded) {
2234     ResultBodyPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
2235     if (aCompRes.get() != NULL) { // change colors for all sub-solids
2236       std::list<ResultPtr> allRes;
2237       ModelAPI_Tools::allSubs(aCompRes, allRes);
2238       std::list<ResultPtr>::iterator aRes = allRes.begin();
2239       for(; aRes != allRes.end() && !aCanBeShaded; aRes++) {
2240         aCanBeShaded = myDisplayer->canBeShaded(*aRes);
2241       }
2242     }
2243   }
2244   return aCanBeShaded;
2245 }
2246
2247 //**************************************************************
2248 bool XGUI_Workshop::canChangeProperty(const QString& theActionName) const
2249 {
2250   if (theActionName == "COLOR_CMD" ||
2251       theActionName == "DEFLECTION_CMD" ||
2252       theActionName == "TRANSPARENCY_CMD") {
2253     QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2254
2255     std::set<std::string> aTypes;
2256     aTypes.insert(ModelAPI_ResultGroup::group());
2257     aTypes.insert(ModelAPI_ResultConstruction::group());
2258     aTypes.insert(ModelAPI_ResultBody::group());
2259     aTypes.insert(ModelAPI_ResultPart::group());
2260
2261     return hasResults(aObjects, aTypes);
2262   }
2263   return false;
2264 }
2265
2266 //******************************************************
2267 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
2268 {
2269   if (!theResult.get())
2270     return;
2271
2272   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
2273   if (aColorAttr.get() != NULL) {
2274     if (!aColorAttr->size()) {
2275       aColorAttr->setSize(3);
2276     }
2277     aColorAttr->setValue(0, theColor[0]);
2278     aColorAttr->setValue(1, theColor[1]);
2279     aColorAttr->setValue(2, theColor[2]);
2280   }
2281   static const Events_ID kRedisplayEvent =
2282     Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2283   ModelAPI_EventCreator::get()->sendUpdated(theResult, kRedisplayEvent);
2284 }
2285
2286 //**************************************************************
2287 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
2288 {
2289
2290   AttributeIntArrayPtr aColorAttr;
2291   // 1. find the current color of the object. This is a color of AIS presentation
2292   // The objects are iterated until a first valid color is found
2293   std::vector<int> aColor;
2294   foreach(ObjectPtr anObject, theObjects) {
2295     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2296     if (aResult.get()) {
2297       XGUI_CustomPrs::getResultColor(aResult, aColor);
2298     }
2299     else {
2300       // TODO: remove the obtaining a color from the AIS object
2301       // this does not happen never because:
2302       // 1. The color can be changed only on results
2303       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2304       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2305       if (anAISObj.get()) {
2306         aColor.resize(3);
2307         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
2308       }
2309     }
2310     if (!aColor.empty())
2311       break;
2312   }
2313   if (aColor.size() != 3)
2314     return;
2315
2316   if (!abortAllOperations())
2317   return;
2318   // 2. show the dialog to change the value
2319   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
2320   aDlg->setColor(aColor);
2321   aDlg->move(QCursor::pos());
2322   bool isDone = aDlg->exec() == QDialog::Accepted;
2323   if (!isDone)
2324     return;
2325
2326   bool isRandomColor = aDlg->isRandomColor();
2327
2328   // 3. abort the previous operation and start a new one
2329   SessionPtr aMgr = ModelAPI_Session::get();
2330   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
2331   aMgr->startOperation(aDescription.toStdString());
2332
2333   // 4. set the value to all results
2334   std::vector<int> aColorResult = aDlg->getColor();
2335   foreach(ObjectPtr anObj, theObjects) {
2336     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2337     if (aResult.get() != NULL) {
2338       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2339       if (aBodyResult.get() != NULL) { // change colors for all sub-solids
2340         std::list<ResultPtr> allRes;
2341         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2342         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2343           setColor(*aRes, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2344         }
2345       }
2346       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
2347     }
2348   }
2349   aMgr->finishOperation();
2350   updateCommandStatus();
2351 }
2352
2353 //**************************************************************
2354 void setDeflection(ResultPtr theResult, const double theDeflection)
2355 {
2356   if (!theResult.get())
2357     return;
2358
2359   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
2360   if (aDeflectionAttr.get() != NULL)
2361     aDeflectionAttr->setValue(theDeflection);
2362   static const Events_ID kRedisplayEvent =
2363     Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2364   ModelAPI_EventCreator::get()->sendUpdated(theResult, kRedisplayEvent);
2365 }
2366
2367 //**************************************************************
2368 void setTransparency(ResultPtr theResult, double theTransparency)
2369 {
2370   if (!theResult.get())
2371     return;
2372
2373   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
2374   if (anAttribute.get() != NULL)
2375     anAttribute->setValue(theTransparency);
2376   static const Events_ID kRedisplayEvent =
2377     Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2378   ModelAPI_EventCreator::get()->sendUpdated(theResult, kRedisplayEvent);
2379 }
2380
2381 //**************************************************************
2382 void setTransparency(double theTransparency, const QObjectPtrList& theObjects)
2383 {
2384   foreach(ObjectPtr anObj, theObjects) {
2385     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2386     if (aResult.get() != NULL) {
2387       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2388       if (aBodyResult.get() != NULL) { // change property for all sub-solids
2389         std::list<ResultPtr> allRes;
2390         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2391         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2392           setTransparency(*aRes, theTransparency);
2393         }
2394       }
2395       setTransparency(aResult, theTransparency);
2396     }
2397   }
2398 }
2399
2400 //**************************************************************
2401 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
2402 {
2403   AttributeDoublePtr aDoubleAttr;
2404   // 1. find the current property of the object. This is a property of AIS presentation
2405   // The objects are iterated until a first valid property is found
2406   double aDeflection = -1;
2407   foreach(ObjectPtr anObject, theObjects) {
2408     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2409     if (aResult.get()) {
2410       aDeflection = XGUI_CustomPrs::getResultDeflection(aResult);
2411     }
2412     else {
2413       // TODO: remove the obtaining a property from the AIS object
2414       // this does not happen never because:
2415       // 1. The property can be changed only on results
2416       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
2417       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
2418       if (anAISObj.get()) {
2419         aDeflection = anAISObj->getDeflection();
2420       }
2421     }
2422     if (aDeflection > 0)
2423       break;
2424   }
2425   if (aDeflection < 0)
2426     return;
2427
2428   if (!abortAllOperations())
2429   return;
2430   // 2. show the dialog to change the value
2431   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
2432   aDlg->setDeflection(aDeflection);
2433   aDlg->move(QCursor::pos());
2434   bool isDone = aDlg->exec() == QDialog::Accepted;
2435   if (!isDone)
2436     return;
2437
2438   // 3. abort the previous operation and start a new one
2439   SessionPtr aMgr = ModelAPI_Session::get();
2440   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
2441   aMgr->startOperation(aDescription.toStdString());
2442
2443   // 4. set the value to all results
2444   aDeflection = aDlg->getDeflection();
2445   foreach(ObjectPtr anObj, theObjects) {
2446     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
2447     if (aResult.get() != NULL) {
2448       ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2449       if (aBodyResult.get() != NULL) { // change property for all sub-solids
2450         std::list<ResultPtr> allRes;
2451         ModelAPI_Tools::allSubs(aBodyResult, allRes);
2452         for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2453           setDeflection(*aRes, aDeflection);
2454         }
2455       }
2456       setDeflection(aResult, aDeflection);
2457     }
2458   }
2459   aMgr->finishOperation();
2460   updateCommandStatus();
2461 }
2462
2463 //**************************************************************
2464 void XGUI_Workshop::changeTransparency(const QObjectPtrList& theObjects)
2465 {
2466   AttributeDoublePtr aDoubleAttr;
2467   // 1. find the current property of the object. This is a property of AIS presentation
2468   // The objects are iterated until a first valid property is found
2469   double aCurrentValue = -1;
2470   foreach(ObjectPtr anObject, theObjects) {
2471     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
2472     if (aResult.get()) {
2473       aCurrentValue = XGUI_CustomPrs::getResultTransparency(aResult);
2474     }
2475     if (aCurrentValue > 0)
2476       break;
2477   }
2478   if (aCurrentValue < 0)
2479     return;
2480
2481   if (!abortAllOperations())
2482     return;
2483
2484   // 2. show the dialog to change the value
2485   XGUI_PropertyDialog* aDlg = new XGUI_PropertyDialog(desktop());
2486   aDlg->setWindowTitle(tr("Transparency"));
2487   XGUI_TransparencyWidget* aTransparencyWidget = new XGUI_TransparencyWidget(aDlg);
2488   connect(aTransparencyWidget, SIGNAL(transparencyValueChanged()),
2489           this, SLOT(onTransparencyValueChanged()));
2490   aDlg->setContent(aTransparencyWidget);
2491   aTransparencyWidget->setValue(aCurrentValue);
2492
2493   // 3. abort the previous operation and start a new one
2494   SessionPtr aMgr = ModelAPI_Session::get();
2495   QString aDescription = contextMenuMgr()->action("TRANSPARENCY_CMD")->text();
2496   aMgr->startOperation(aDescription.toStdString());
2497
2498   if (aDlg->exec() == QDialog::Accepted) {
2499     // 4. set the value to all results
2500     aCurrentValue = aTransparencyWidget->getValue();
2501     setTransparency(aCurrentValue, theObjects);
2502     aMgr->finishOperation();
2503   } else {
2504     aMgr->abortOperation();
2505     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2506   }
2507
2508   updateCommandStatus();
2509 }
2510
2511 //**************************************************************
2512 void XGUI_Workshop::onTransparencyValueChanged()
2513 {
2514   XGUI_TransparencyWidget* aTransparencyWidget = (XGUI_TransparencyWidget*)sender();
2515   if (!aTransparencyWidget)
2516     return;
2517
2518   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
2519   setTransparency(aTransparencyWidget->getValue(), anObjects);
2520   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2521 }
2522
2523
2524 //******************************************************
2525 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2526 {
2527   if (isVisible) {
2528     std::set<ObjectPtr> anObjects;
2529     foreach (ObjectPtr aObj, theList) {
2530       anObjects.insert(aObj);
2531     }
2532     if (!prepareForDisplay(anObjects))
2533       return;
2534   }
2535
2536   foreach (ObjectPtr aObj, theList) {
2537     aObj->setDisplayed(isVisible);
2538   }
2539   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2540   myObjectBrowser->updateAllIndexes();
2541
2542   updateColorScaleVisibility();
2543 }
2544
2545 //**************************************************************
2546 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2547 {
2548   QObjectPtrList aSrcList = theList;
2549   // Hide all displayed objects
2550   QObjectPtrList aList = myDisplayer->displayedObjects();
2551   foreach (ObjectPtr aObj, aList) {
2552     if ((!aSrcList.contains(aObj)) && (module()->canEraseObject(aObj)))
2553       aObj->setDisplayed(false);
2554     else
2555       aSrcList.removeAll(aObj);
2556   }
2557   //Do not use eraseAll if you didn't send Redisplay event:
2558   //all objects are erased from viewer, but considered as displayed in displayer
2559   // Problem in bug 2218
2560   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2561 #ifdef HAVE_SALOME
2562     //issue #2159 Hide all incomplete behavior
2563     viewer()->eraseAll();
2564 #endif
2565
2566   std::set<ObjectPtr> anObjects;
2567   foreach (ObjectPtr aObj, aSrcList) {
2568     anObjects.insert(aObj);
2569   }
2570
2571   if (!prepareForDisplay(anObjects))
2572     return;
2573
2574   // Show only objects from the list
2575   foreach (ObjectPtr aObj, aSrcList) {
2576     aObj->setDisplayed(true);
2577   }
2578   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2579
2580   // Necessary for update icons in ObjectBrowser on Linux
2581   myObjectBrowser->updateAllIndexes();
2582   updateColorScaleVisibility();
2583 }
2584
2585
2586 //**************************************************************
2587 void XGUI_Workshop::updateColorScaleVisibility()
2588 {
2589   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2590   viewer()->setColorScaleShown(false);
2591   if (aObjects.size() == 1) {
2592     FieldStepPtr aStep =
2593       std::dynamic_pointer_cast<ModelAPI_ResultField::ModelAPI_FieldStep>(aObjects.first());
2594     if (aStep.get() && myDisplayer->isVisible(aStep)) {
2595       AISObjectPtr aAisPtr = myDisplayer->getAISObject(aStep);
2596       Handle(AIS_InteractiveObject) aIO = aAisPtr->impl<Handle(AIS_InteractiveObject)>();
2597       ModuleBase_IStepPrs* aPrs = dynamic_cast<ModuleBase_IStepPrs*>(aIO.get());
2598       if (aPrs) {
2599         ModelAPI_AttributeTables::ValueType aType = aPrs->dataType();
2600         if ((aType == ModelAPI_AttributeTables::DOUBLE) ||
2601           (aType == ModelAPI_AttributeTables::INTEGER) ||
2602           (aType == ModelAPI_AttributeTables::BOOLEAN)) {
2603           myViewerProxy->setupColorScale();
2604           if (aType == ModelAPI_AttributeTables::BOOLEAN) {
2605             myViewerProxy->setColorScaleIntervals(2);
2606             myViewerProxy->setColorScaleRange(0., 1.);
2607           }
2608           else {
2609             double aMin, aMax;
2610             aPrs->dataRange(aMin, aMax);
2611             myViewerProxy->setColorScaleRange(aMin, aMax);
2612           }
2613           myViewerProxy->setColorScaleTitle(aStep->name().c_str());
2614           myViewerProxy->setColorScaleShown(true);
2615         }
2616       }
2617     }
2618   }
2619 }
2620
2621
2622 //**************************************************************
2623 void XGUI_Workshop::setNormalView(bool toInvert)
2624 {
2625   QList<ModuleBase_ViewerPrsPtr> aPrsList =
2626     mySelector->selection()->getSelected(ModuleBase_ISelection::Viewer);
2627   GeomShapePtr aPlanarFace;
2628   foreach(ModuleBase_ViewerPrsPtr aPrs, aPrsList) {
2629     GeomShapePtr aShape = aPrs->shape();
2630     if (aShape.get() && aShape->isPlanar()) {
2631       aPlanarFace = aShape;
2632       break;
2633     }
2634   }
2635   if (aPlanarFace.get()) {
2636     GeomFacePtr aFace(new GeomAPI_Face(aPlanarFace));
2637     GeomPlanePtr aPlane = aFace->getPlane();
2638     GeomDirPtr aNormal = aPlane->direction();
2639     if (toInvert)
2640       aNormal->reverse();
2641     GeomPointPtr aPos = aPlane->location();
2642
2643     double aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2644     aFace->computeSize(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2645
2646     Handle(V3d_View) aView = myViewerProxy->activeView();
2647     double aScale = aView->Scale();
2648     aView->SetAt(aPos->x(), aPos->y(), aPos->z());
2649     aView->SetProj(aNormal->x(), aNormal->y(), aNormal->z());
2650     Bnd_Box aBox;
2651     aBox.Update(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2652     aView->FitAll(aBox);
2653   }
2654 }
2655
2656 //**************************************************************
2657 void XGUI_Workshop::registerValidators() const
2658 {
2659   SessionPtr aMgr = ModelAPI_Session::get();
2660   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2661 }
2662
2663 //**************************************************************
2664 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2665 {
2666   if (!theDoc)
2667     return;
2668   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2669   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2670 }
2671
2672 //**************************************************************
2673 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2674 {
2675   for (int i = 0; i < theDoc->size(theGroup); i++)
2676     theDoc->object(theGroup, i)->setDisplayed(true);
2677     //displayObject(theDoc->object(theGroup, i));
2678   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2679 }
2680
2681 //**************************************************************
2682 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2683 {
2684   foreach(ObjectPtr anObj, theList) {
2685     myDisplayer->setDisplayMode(anObj, (XGUI_Displayer::DisplayMode)theMode, false);
2686
2687     ResultBodyPtr aBodyResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anObj);
2688     if (aBodyResult.get() != NULL) { // change display mode for all sub-solids
2689       std::list<ResultPtr> allRes;
2690       ModelAPI_Tools::allSubs(aBodyResult, allRes);
2691       for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
2692         myDisplayer->setDisplayMode(*aRes, (XGUI_Displayer::DisplayMode)theMode, false);
2693       }
2694     }
2695   }
2696   if (theList.size() > 0)
2697     myDisplayer->updateViewer();
2698 }
2699
2700 //**************************************************************
2701 void XGUI_Workshop::closeDocument()
2702 {
2703   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2704   while (anOperation) {
2705     anOperation->abort();
2706     anOperation = operationMgr()->currentOperation();
2707   }
2708   //myDisplayer->closeLocalContexts();
2709   myDisplayer->eraseAll();
2710   objectBrowser()->clearContent();
2711
2712   module()->closeDocument();
2713   // we need to clear viewer (with created filters) to do not have problems in 2nd SALOME study
2714   module()->clearViewer();
2715
2716
2717   // data model need not process the document's signals about objects modifications as
2718   // the document is closed
2719   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2720
2721   SessionPtr aMgr = ModelAPI_Session::get();
2722   aMgr->closeAll();
2723
2724   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2725 }
2726
2727 //******************************************************
2728 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2729 {
2730   XGUI_HistoryMenu* aMenu = NULL;
2731   if (isSalomeMode()) {
2732     QAction* anAction = qobject_cast<QAction*>(theObject);
2733     if (!anAction)
2734       return;
2735     aMenu = new XGUI_HistoryMenu(anAction);
2736   } else {
2737     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2738     aMenu = new XGUI_HistoryMenu(aButton);
2739   }
2740   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2741   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2742 }
2743
2744 //******************************************************
2745 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2746 {
2747   QList<ActionInfo> aResult;
2748   std::list<std::string>::const_iterator it = theList.cbegin();
2749   for (; it != theList.cend(); it++) {
2750     QString anId = QString::fromStdString(*it);
2751     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2752     if (isEditing) {
2753       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2754     }
2755     ActionInfo anInfo;
2756     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2757     if (aContextMenuAct) {
2758       anInfo.initFrom(aContextMenuAct);
2759     } else {
2760       anInfo = myActionsMgr->actionInfoById(anId);
2761     }
2762     if (isEditing) {
2763       anInfo.text = anInfo.text.prepend("Modify ");
2764     }
2765     aResult << anInfo;
2766   }
2767   return aResult;
2768 }
2769
2770 //******************************************************
2771 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2772 {
2773 #ifdef HAVE_SALOME
2774   salomeConnector()->putInfo(theMessage, -1);
2775 #else
2776   myMainWindow->putInfo(theMessage, -1);
2777 #endif
2778 }
2779
2780 #ifdef HAVE_SALOME
2781 //******************************************************
2782 void XGUI_Workshop::synchronizeViewer()
2783 {
2784   SessionPtr aMgr = ModelAPI_Session::get();
2785   QList<DocumentPtr> aDocs;
2786   aDocs.append(aMgr->activeDocument());
2787   aDocs.append(aMgr->moduleDocument());
2788
2789   foreach(DocumentPtr aDoc, aDocs) {
2790     synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2791     synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2792     synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2793     synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2794   }
2795 }
2796
2797 //******************************************************
2798 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2799                                              const std::string& theGroup,
2800                                              bool theUpdateViewer)
2801 {
2802   ObjectPtr aObj;
2803   int aSize = theDoc->size(theGroup);
2804   for (int i = 0; i < aSize; i++) {
2805     aObj = theDoc->object(theGroup, i);
2806     if (aObj->isDisplayed()) {
2807       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2808       // be changed to the object becomes visible when the shape becomes not empty
2809       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2810       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2811         continue;
2812       ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObj);
2813       if (aResBody.get())
2814         synchronizeResultTree(aResBody, false);
2815       else
2816         myDisplayer->display(aObj, false);
2817     }
2818   }
2819   if (theUpdateViewer)
2820     myDisplayer->updateViewer();
2821 }
2822
2823 void XGUI_Workshop::synchronizeResultTree(const ResultBodyPtr& theRes, bool theUpdateViewer)
2824 {
2825   if (theRes->numberOfSubs() > 0)
2826     for (int i = 0; i < theRes->numberOfSubs(); i++) {
2827       ResultBodyPtr aRes = theRes->subResult(i);
2828       if (aRes.get())
2829         synchronizeResultTree(aRes, theUpdateViewer);
2830     }
2831   else {
2832     if (theRes->isDisplayed())
2833       myDisplayer->display(theRes, theUpdateViewer);
2834     else
2835       myDisplayer->erase(theRes, theUpdateViewer);
2836   }
2837 }
2838 #endif
2839
2840 //******************************************************
2841 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2842 {
2843   FeaturePtr aFeature;
2844   QObjectPtrList aSelList = theObjects;
2845   QObjectPtrList aNewSel;
2846   bool aHasHidden = false;
2847   foreach(ObjectPtr aObj, theObjects) {
2848     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2849     if (aFeature.get()) {
2850       std::list<ResultPtr> aResults;
2851       ModelAPI_Tools::allResults(aFeature, aResults);
2852       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2853       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2854         aHasHidden |= (*aIt)->isConcealed();
2855         aSelList.append(*aIt);
2856         aNewSel.append(*aIt);
2857       }
2858     }
2859   }
2860   if (aSelList.count() > theObjects.count()) {
2861     // if something was found
2862     objectBrowser()->setObjectsSelected(aSelList);
2863     objectBrowser()->ensureVisible(aNewSel.first());
2864   }
2865   if (aHasHidden)
2866     QMessageBox::information(desktop(), tr("Find results"),
2867                              tr("Results not found"), QMessageBox::Ok);
2868 }
2869
2870 //******************************************************
2871 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2872 {
2873   ResultPtr aResult;
2874   QObjectPtrList aSelList = theObjects;
2875   QObjectPtrList aNewSel;
2876   FeaturePtr aFeature;
2877   foreach(ObjectPtr aObj, theObjects) {
2878     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2879     if (aResult.get()) {
2880       aFeature = ModelAPI_Feature::feature(aResult);
2881       if (aFeature.get()) {
2882         aSelList.append(aFeature);
2883         aNewSel.append(aFeature);
2884       }
2885     }
2886   }
2887   if (aSelList.count() > theObjects.count()) {
2888     // if something was found
2889     objectBrowser()->setObjectsSelected(aSelList);
2890     objectBrowser()->ensureVisible(aNewSel.first());
2891   }
2892 }
2893
2894 void XGUI_Workshop::insertFeatureFolder()
2895 {
2896   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
2897   if (aObjects.isEmpty())
2898     return;
2899   ObjectPtr aObj = aObjects.first();
2900   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2901   if (aFeature.get() == NULL)
2902     return;
2903   SessionPtr aMgr = ModelAPI_Session::get();
2904   DocumentPtr aDoc = aMgr->activeDocument();
2905
2906   QString aDescription = contextMenuMgr()->action("INSERT_FOLDER_CMD")->text();
2907
2908   aMgr->startOperation(aDescription.toStdString());
2909   aDoc->addFolder(aFeature);
2910   aMgr->finishOperation();
2911
2912   updateCommandStatus();
2913 }
2914
2915
2916 void XGUI_Workshop::insertToFolder(bool isBefore)
2917 {
2918   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2919   if (aFeatures.empty())
2920     return;
2921
2922   SessionPtr aMgr = ModelAPI_Session::get();
2923   DocumentPtr aDoc = aMgr->activeDocument();
2924
2925   FolderPtr aFolder = isBefore? aDoc->findFolderAbove(aFeatures):
2926                                 aDoc->findFolderBelow(aFeatures);
2927   if (!aFolder.get())
2928     return;
2929
2930   QString aDescription = contextMenuMgr()->action(
2931     isBefore ? "ADD_TO_FOLDER_BEFORE_CMD" : "ADD_TO_FOLDER_AFTER_CMD")->text();
2932
2933   QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
2934
2935   aMgr->startOperation(aDescription.toStdString());
2936   aDoc->moveToFolder(aFeatures, aFolder);
2937   aMgr->finishOperation();
2938
2939   myObjectBrowser->setFoldersState(aStates);
2940
2941   updateCommandStatus();
2942 }
2943
2944 void XGUI_Workshop::moveOutFolder(bool isBefore)
2945 {
2946   std::list<FeaturePtr> aFeatures = mySelector->getSelectedFeatures();
2947   if (aFeatures.empty())
2948     return;
2949
2950   SessionPtr aMgr = ModelAPI_Session::get();
2951   DocumentPtr aDoc = aMgr->activeDocument();
2952
2953   QString aDescription = contextMenuMgr()->action(
2954     isBefore ? "ADD_OUT_FOLDER_BEFORE_CMD" : "ADD_OUT_FOLDER_AFTER_CMD")->text();
2955
2956   QMap<ObjectPtr, bool> aStates = myObjectBrowser->getFoldersState(aDoc);
2957
2958   aMgr->startOperation(aDescription.toStdString());
2959   aDoc->removeFromFolder(aFeatures, isBefore);
2960   aMgr->finishOperation();
2961
2962   myObjectBrowser->setFoldersState(aStates);
2963
2964   updateCommandStatus();
2965 }
2966
2967 void XGUI_Workshop::onAutoApply()
2968 {
2969   SessionPtr aMgr = ModelAPI_Session::get();
2970   bool isBlocked = aMgr->isAutoUpdateBlocked();
2971   aMgr->blockAutoUpdate(!isBlocked);
2972 }
2973
2974 void XGUI_Workshop::updateAutoComputeState()
2975 {
2976   SessionPtr aMgr = ModelAPI_Session::get();
2977   bool isComputeBlocked = aMgr->isAutoUpdateBlocked();
2978 #ifdef HAVE_SALOME
2979 //  QAction* aUpdateCmd;
2980 //  QList<QAction*> aCommands = mySalomeConnector->commandList();
2981 //  foreach(QAction* aCmd, aCommands) {
2982 //    if (aCmd->data().toString() == "AUTOCOMPUTE_CMD") {
2983 //      aUpdateCmd = aCmd;
2984 //      break;
2985 //    }
2986 //  }
2987 //  aUpdateCmd->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
2988 //    QIcon(":pictures/autoapply_start.png"));
2989 #else
2990   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
2991   AppElements_Command* aUpdateCmd = aMenuBar->feature("AUTOCOMPUTE_CMD");
2992   aUpdateCmd->button()->setIcon(isComputeBlocked? QIcon(":pictures/autoapply_stop.png") :
2993     QIcon(":pictures/autoapply_start.png"));
2994 #endif
2995 }
2996
2997
2998 void XGUI_Workshop::clearTemporaryDir()
2999 {
3000   QDir aDir(myTmpDir.path());
3001   if (!aDir.isEmpty()) {
3002     QStringList aEntries;
3003     aDir.entryList(aEntries);
3004     foreach(QString aFile, aEntries) {
3005       aDir.remove(aFile);
3006     }
3007   }
3008 }
3009
3010
3011 void XGUI_Workshop::onDockSizeChanged()
3012 {
3013   QDockWidget* aDockWgt = dynamic_cast<QDockWidget*>(myObjectBrowser->parentWidget());
3014   int aObWidth = aDockWgt->size().width();
3015   if (myPropertyPanel->width() != aObWidth) {
3016     QList<QDockWidget*> aWgtList;
3017     aWgtList << myPropertyPanel << aDockWgt;
3018     QList<int> aSizeList;
3019     aSizeList << aObWidth << aObWidth;
3020     desktop()->resizeDocks(aWgtList, aSizeList, Qt::Horizontal);
3021     disconnect(myObjectBrowser, SIGNAL(sizeChanged()), this, SLOT(onDockSizeChanged()));
3022   }
3023 }
3024
3025 void XGUI_Workshop::deactivateCurrentSelector()
3026 {
3027   myActiveControlMgr->deactivateSelector(myActiveControlMgr->activeSelector());
3028 }