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