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