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