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