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