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