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