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