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