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