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