]> SALOME platform Git repositories - modules/gui.git/blob - src/SalomeApp/SalomeApp_Application.cxx
Salome HOME
9d17c32e6698289e45101a2b21f39c04f07036c6
[modules/gui.git] / src / SalomeApp / SalomeApp_Application.cxx
1 // File:      SalomeApp_Application.cxx
2 // Created:   10/22/2004 3:23:45 PM
3 // Author:    Sergey LITONIN
4 // Copyright (C) CEA 2004
5
6 #include "SalomeApp_PyInterp.h" // WARNING! This include must be the first!
7
8 #include "SalomeApp_Application.h"
9
10 #include "SalomeApp_Study.h"
11 #include "SalomeApp_DataModel.h"
12 #include "SalomeApp_DataObject.h"
13 #include "SalomeApp_EventFilter.h"
14 #include "SalomeApp_VisualState.h"
15
16 #include "SalomeApp_StudyPropertiesDlg.h"
17
18 #include "LightApp_Application.h"
19 #include "LightApp_Preferences.h"
20 #include "LightApp_WidgetContainer.h"
21 #include "LightApp_SelectionMgr.h"
22 #include "LightApp_NameDlg.h"
23
24 #include "STD_LoadStudiesDlg.h"
25
26 #include <SUIT_Tools.h>
27 #include <SUIT_Session.h>
28
29 #include <QtxMRUAction.h>
30
31 #include <OB_Browser.h>
32 #include <OB_ListItem.h>
33
34 #include <PythonConsole_PyConsole.h>
35
36 #include <SUIT_FileDlg.h>
37 #include <SUIT_MessageBox.h>
38 #include <SUIT_ResourceMgr.h>
39 #include <SUIT_ActionOperation.h>
40
41 #include <Utils_ORB_INIT.hxx>
42 #include <Utils_SINGLETON.hxx>
43 #include <SALOME_ModuleCatalog_impl.hxx>
44 #include <SALOME_LifeCycleCORBA.hxx>
45
46 #include <qmap.h>
47 #include <qaction.h>
48 #include <qcombobox.h>
49 #include <qlistbox.h>
50 #include <qregexp.h>
51 #include <qcheckbox.h>
52 #include <qpushbutton.h>
53 #include <qlabel.h>
54
55 #include "SALOMEDS_StudyManager.hxx"
56 #include "SALOMEDS_SObject.hxx"
57 #include "SALOMEDS_IParameters.hxx"
58
59 #include "SALOME_ListIteratorOfListIO.hxx"
60 #include "SALOME_ListIO.hxx"
61
62 #include "ToolsGUI_CatalogGeneratorDlg.h"
63 #include "ToolsGUI_RegWidget.h"
64
65 #include <SALOMEDSClient_ClientFactory.hxx>
66
67 /*!Create new instance of SalomeApp_Application.*/
68 extern "C" SALOMEAPP_EXPORT SUIT_Application* createApplication()
69 {
70   return new SalomeApp_Application();
71 }
72
73 /*
74   Class       : SalomeApp_Application
75   Description : Application containing SalomeApp module or LightApp module
76 */
77
78 /*!Constructor.*/
79 SalomeApp_Application::SalomeApp_Application()
80 : LightApp_Application()
81 {
82 }
83
84 /*!Destructor.
85  *\li Destroy event filter.
86  */
87 SalomeApp_Application::~SalomeApp_Application()
88 {
89   // Do not destroy. It's a singleton !
90   //SalomeApp_EventFilter::Destroy();
91 }
92
93 /*!Start application.*/
94 void SalomeApp_Application::start()
95 {
96   LightApp_Application::start();
97
98   SalomeApp_EventFilter::Init();
99 }
100
101 /*!Create actions:*/
102 void SalomeApp_Application::createActions()
103 {
104   LightApp_Application::createActions();
105
106   SUIT_Desktop* desk = desktop();
107   
108   //! Save GUI state
109   createAction( SaveGUIStateId, tr( "TOT_DESK_FILE_SAVE_GUI_STATE" ), QIconSet(),
110                 tr( "MEN_DESK_FILE_SAVE_GUI_STATE" ), tr( "PRP_DESK_FILE_SAVE_GUI_STATE" ),
111                 0, desk, false, this, SLOT( onSaveGUIState() ) );
112
113   //! Dump study
114   createAction( DumpStudyId, tr( "TOT_DESK_FILE_DUMP_STUDY" ), QIconSet(),
115                 tr( "MEN_DESK_FILE_DUMP_STUDY" ), tr( "PRP_DESK_FILE_DUMP_STUDY" ),
116                 CTRL+Key_D, desk, false, this, SLOT( onDumpStudy() ) );
117     
118   //! Load script
119   createAction( LoadScriptId, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), QIconSet(),
120                 tr( "MEN_DESK_FILE_LOAD_SCRIPT" ), tr( "PRP_DESK_FILE_LOAD_SCRIPT" ),
121                 CTRL+Key_T, desk, false, this, SLOT( onLoadScript() ) );
122
123   //! Properties
124   createAction( PropertiesId, tr( "TOT_DESK_PROPERTIES" ), QIconSet(),
125                 tr( "MEN_DESK_PROPERTIES" ), tr( "PRP_DESK_PROPERTIES" ),
126                 CTRL+Key_P, desk, false, this, SLOT( onProperties() ) );
127
128   //! Catalog Generator
129   createAction( CatalogGenId, tr( "TOT_DESK_CATALOG_GENERATOR" ),  QIconSet(),
130                 tr( "MEN_DESK_CATALOG_GENERATOR" ), tr( "PRP_DESK_CATALOG_GENERATOR" ),
131                 SHIFT+Key_G, desk, false, this, SLOT( onCatalogGen() ) );
132
133   //! Registry Display
134   createAction( RegDisplayId, tr( "TOT_DESK_REGISTRY_DISPLAY" ),  QIconSet(),
135                 tr( "MEN_DESK_REGISTRY_DISPLAY" ), tr( "PRP_DESK_REGISTRY_DISPLAY" ),
136                 /*SHIFT+Key_D*/0, desk, false, this, SLOT( onRegDisplay() ) );
137
138   int fileMenu = createMenu( tr( "MEN_DESK_FILE" ), -1 );
139
140   createMenu( SaveGUIStateId, fileMenu, 10, -1 );
141   createMenu( DumpStudyId, fileMenu, 10, -1 );
142   createMenu( separator(), fileMenu, -1, 15, -1 );
143   createMenu( LoadScriptId, fileMenu, 10, -1 );
144   createMenu( separator(), fileMenu, -1, 15, -1 );
145   createMenu( PropertiesId, fileMenu, 10, -1 );
146   createMenu( separator(), fileMenu, -1, 15, -1 );
147
148   int toolsMenu = createMenu( tr( "MEN_DESK_TOOLS" ), -1, MenuToolsId, 50 );
149   createMenu( CatalogGenId, toolsMenu, 10, -1 );
150   createMenu( RegDisplayId, toolsMenu, 10, -1 );
151   createMenu( separator(), toolsMenu, -1, 15, -1 );
152 }
153
154 /*! Purpose : SLOT. Open new document with \a aName.*/
155 bool SalomeApp_Application::onOpenDoc( const QString& aName )
156 {
157   bool res = false, toOpen = true, isAlreadyOpen = false;
158
159   // Look among opened studies
160   if (activeStudy()) { // at least one study is opened
161     SUIT_Session* aSession = SUIT_Session::session();
162     QPtrList<SUIT_Application> aAppList = aSession->applications();
163     QPtrListIterator<SUIT_Application> it (aAppList);
164     SUIT_Application* aApp = 0;
165     // iterate on all applications
166     for (; (aApp = it.current()) && !isAlreadyOpen; ++it) {
167       if (aApp->activeStudy()->studyName() == aName) {
168         isAlreadyOpen = true; // Already opened, ask user what to do
169
170         // The document ... is already open.
171         // Do you want to reload it?
172         int aAnswer = SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
173                                              tr("QUE_DOC_ALREADYOPEN").arg(aName),
174                                              tr("BUT_YES"), tr("BUT_NO"), 1, 2, 2);
175         if (aAnswer == 1) { // reload
176           if (activeStudy()->studyName() == aName && aAppList.count() > 1) {
177             // Opened in THIS (active) application.
178             STD_Application* app1 = (STD_Application*)aAppList.at(0);
179             STD_Application* app2 = (STD_Application*)aAppList.at(1);
180             if (!app1 || !app2) {
181               // Error
182               return false;
183             }
184             if (app1->activeStudy()->studyName() == aName) {
185               // app1 is this application, we need another one
186               app1 = app2;
187             }
188             // Close document of this application. This application will be destroyed.
189             onCloseDoc(/*ask = */false);
190             // Open the file with another application, as this one will be destroyed.
191             return app1->onOpenDoc(aName);
192           } else {
193             // Opened in another application.
194             STD_Application* app = (STD_Application*)aApp;
195             if (app)
196               app->onCloseDoc(/*ask = */false);
197           }
198         } else { // do not reload
199           // OK, the study will not be reloaded, but we call
200           // CAM_Application::onOpenDoc( aName ) all the same.
201           // It will activate a desktop of the study <aName>.
202         }
203       }
204     }
205   }
206
207   // Look among unloaded studies
208   if (!isAlreadyOpen) {
209     std::vector<std::string> List = studyMgr()->GetOpenStudies();
210
211     QString studyName;
212     for (unsigned int ind = 0; ind < List.size() && !isAlreadyOpen; ind++) {
213       studyName = List[ind].c_str();
214       if (aName == studyName) {
215         // Already exists unloaded, ask user what to do
216         isAlreadyOpen = true;
217
218         // The document ... already exists in the study manager.
219         // Do you want to reload it?
220         int aAnswer = SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
221                                              tr("QUE_DOC_ALREADYEXIST").arg(aName),
222                                              tr("BUT_YES"), tr("BUT_NO"), 1, 2, 2);
223         if (aAnswer == 1) {
224           _PTR(Study) aStudy = studyMgr()->GetStudyByName(aName.latin1());
225           if (aStudy)
226             studyMgr()->Close(aStudy);
227         } else {
228           toOpen = false;
229         }
230       }
231     }
232   }
233
234   if (toOpen)
235     res = CAM_Application::onOpenDoc( aName );
236
237   QAction* a = action( MRUId );
238   if ( a && a->inherits( "QtxMRUAction" ) )
239   {
240     QtxMRUAction* mru = (QtxMRUAction*)a;
241     if ( res )
242       mru->insert( aName );
243     else
244       mru->remove( aName );
245   }
246   return res;
247 }
248
249 /*!SLOT. Load document.*/
250 void SalomeApp_Application::onLoadDoc()
251 {
252   QString name, studyname, ext;
253
254   STD_LoadStudiesDlg aDlg( desktop(), TRUE);
255
256   std::vector<std::string> List = studyMgr()->GetOpenStudies();
257
258   SUIT_Session* aSession = SUIT_Session::session();
259   QPtrList<SUIT_Application> aAppList = aSession->applications();
260   SUIT_Application* aApp = 0;
261
262   for (unsigned int ind = 0; ind < List.size(); ind++) {
263      studyname = List[ind].c_str();
264      //Add to list only unloaded studies
265      bool isAlreadyOpen = false;
266      for ( QPtrListIterator<SUIT_Application> it( aAppList ); it.current() && !isAlreadyOpen; ++it )
267        {
268          aApp = it.current();
269          if(!aApp || !aApp->activeStudy()) continue;
270          if ( aApp->activeStudy()->studyName() == studyname ) isAlreadyOpen = true;
271        }
272
273      if ( !isAlreadyOpen ) aDlg.ListComponent->insertItem( studyname );
274   }
275
276   int retVal = aDlg.exec();
277   studyname = aDlg.ListComponent->currentText();
278
279   if (retVal == QDialog::Rejected)
280     return;
281
282   if ( studyname.isNull() || studyname.isEmpty() )
283     return;
284
285   name = studyname;
286   name.replace( QRegExp(":"), "/" );
287
288   if( LightApp_Application::onLoadDoc( name ) )
289   {
290      updateWindows();
291      updateViewManagers();
292      updateObjectBrowser(true);
293   }
294 }
295
296
297 /*!SLOT. Load document with \a aName.*/
298 bool SalomeApp_Application::onLoadDoc( const QString& aName )
299 {
300   return LightApp_Application::onLoadDoc( aName );
301 }
302
303 /*!SLOT. Copy objects to study maneger from selection maneger..*/
304 void SalomeApp_Application::onCopy()
305 {
306   SALOME_ListIO list;
307   LightApp_SelectionMgr* mgr = selectionMgr();
308   mgr->selectedObjects(list);
309   
310   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
311   if(study == NULL) return;
312   
313   _PTR(Study) stdDS = study->studyDS();
314   if(!stdDS) return;
315
316   SALOME_ListIteratorOfListIO it( list );
317   if(it.More())
318     {
319       _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
320       try {
321         studyMgr()->Copy(so);
322         onSelectionChanged();
323       }
324       catch(...) {
325       }
326     }
327 }
328
329 /*!SLOT. Paste objects to study maneger from selection manager.*/
330 void SalomeApp_Application::onPaste()
331 {
332   SALOME_ListIO list;
333   LightApp_SelectionMgr* mgr = selectionMgr();
334   mgr->selectedObjects(list);
335
336   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
337   if(study == NULL) return;
338
339   _PTR(Study) stdDS = study->studyDS();
340   if(!stdDS) return;
341
342   SALOME_ListIteratorOfListIO it( list );
343   if(it.More())
344     {
345       _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
346       try {
347         studyMgr()->Paste(so);
348         updateObjectBrowser( true );
349         updateActions(); //SRN: BugID IPAL9377, case 3
350       }
351       catch(...) {
352       }
353     }
354 }
355
356 /*!Sets enable or disable some actions on selection changed.*/
357 void SalomeApp_Application::onSelectionChanged()
358 {
359    SALOME_ListIO list;
360    LightApp_SelectionMgr* mgr = selectionMgr();
361    mgr->selectedObjects(list);
362
363    bool canCopy  = false;
364    bool canPaste = false;
365
366    SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
367    if (study != NULL) {
368      _PTR(Study) stdDS = study->studyDS();
369
370      if (stdDS) {
371        SALOME_ListIteratorOfListIO it ( list );
372
373        if (it.More() && list.Extent() == 1) {
374          _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
375
376          if ( so ) {
377            SALOMEDS_SObject* aSO = dynamic_cast<SALOMEDS_SObject*>(so.get());
378
379            if ( aSO ) {
380              canCopy = studyMgr()->CanCopy(so);
381              canPaste = studyMgr()->CanPaste(so);
382            }
383          }
384        }
385      }
386    }
387
388    action(EditCopyId)->setEnabled(canCopy);
389    action(EditPasteId)->setEnabled(canPaste);
390 }
391
392 /*!Delete references.*/
393 void SalomeApp_Application::onDeleteInvalidReferences()
394 {
395   SALOME_ListIO aList;
396   LightApp_SelectionMgr* mgr = selectionMgr();
397   mgr->selectedObjects( aList, QString::null, false );
398
399   if( aList.IsEmpty() )
400     return;
401
402   SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(activeStudy());
403   _PTR(Study) aStudyDS = aStudy->studyDS();
404   _PTR(StudyBuilder) aStudyBuilder = aStudyDS->NewBuilder();
405   _PTR(SObject) anObj;
406
407   for( SALOME_ListIteratorOfListIO it( aList ); it.More(); it.Next() )
408     if ( it.Value()->hasEntry() )
409     {
410       _PTR(SObject) aSObject = aStudyDS->FindObjectID( it.Value()->getEntry() ), aRefObj = aSObject;
411       while( aRefObj && aRefObj->ReferencedObject( anObj ) )
412         aRefObj = anObj;
413
414       if( aRefObj && aRefObj!=aSObject && QString( aRefObj->GetName().c_str() ).isEmpty() )
415          aStudyBuilder->RemoveReference( aSObject );
416     }
417   updateObjectBrowser();
418 }
419
420 /*!Private SLOT. */
421 void SalomeApp_Application::onOpenWith()
422 {
423   QApplication::setOverrideCursor( Qt::waitCursor );
424   SALOME_ListIO aList;
425   LightApp_SelectionMgr* mgr = selectionMgr();
426   mgr->selectedObjects(aList);
427   if (aList.Extent() != 1)
428     {
429       QApplication::restoreOverrideCursor();
430       return;
431     }
432   Handle(SALOME_InteractiveObject) aIObj = aList.First();
433   QString aModuleName(aIObj->getComponentDataType());
434   QString aModuleTitle = moduleTitle(aModuleName);
435   activateModule(aModuleTitle);
436   QApplication::restoreOverrideCursor();
437 }
438
439 //=======================================================================
440 // name    : createNewStudy
441 /*! Purpose : Create new study*/
442 //=======================================================================
443 SUIT_Study* SalomeApp_Application::createNewStudy()
444 {
445   SalomeApp_Study* aStudy = new SalomeApp_Study( this );
446
447   // Set up processing of major study-related events
448   connect( aStudy, SIGNAL( created( SUIT_Study* ) ), this, SLOT( onStudyCreated( SUIT_Study* ) ) );
449   connect( aStudy, SIGNAL( opened ( SUIT_Study* ) ), this, SLOT( onStudyOpened ( SUIT_Study* ) ) );
450   connect( aStudy, SIGNAL( saved  ( SUIT_Study* ) ), this, SLOT( onStudySaved  ( SUIT_Study* ) ) );
451   connect( aStudy, SIGNAL( closed ( SUIT_Study* ) ), this, SLOT( onStudyClosed ( SUIT_Study* ) ) );
452
453   return aStudy;
454 }
455
456 //=======================================================================
457 // name    : updateCommandsStatus
458 /*! Purpose : Enable/Disable menu items and toolbar buttons. Rebuild menu*/
459 //=======================================================================
460 void SalomeApp_Application::updateCommandsStatus()
461 {
462   LightApp_Application::updateCommandsStatus();
463
464   // Dump study menu
465   QAction* a = action( DumpStudyId );
466   if ( a )
467     a->setEnabled( activeStudy() );
468
469   // Load script menu
470   a = action( LoadScriptId );
471   if ( a )
472     a->setEnabled( activeStudy() );
473
474   // Properties menu
475   a = action( PropertiesId );
476   if( a )
477     a->setEnabled( activeStudy() );
478
479   // Save GUI state menu
480   a = action( SaveGUIStateId );
481   if( a )
482     a->setEnabled( activeStudy() );
483
484   // update state of Copy/Paste menu items
485   onSelectionChanged();
486 }
487
488 /*
489   Class       : DumpStudyFileDlg
490   Description : Private class used in Dump Study operation.  Consists 2 check boxes: 
491                 "Publish in study" and "Save GUI parameters"
492 */
493 class DumpStudyFileDlg : public SUIT_FileDlg
494 {
495 public:
496   DumpStudyFileDlg( QWidget* parent ) : SUIT_FileDlg( parent, false, true, true ) 
497   {
498     QHBox* hB = new QHBox( this );
499     myPublishChk = new QCheckBox( tr("PUBLISH_IN_STUDY"), hB );
500     mySaveGUIChk = new QCheckBox( tr("SAVE_GUI_STATE"), hB );
501     QPushButton* pb = new QPushButton(this);      
502     addWidgets( new QLabel("", this), hB, pb );
503     pb->hide();    
504   }
505   QCheckBox* myPublishChk;
506   QCheckBox* mySaveGUIChk;
507 };
508
509 /*!Private SLOT. On dump study.*/
510 void SalomeApp_Application::onDumpStudy( )
511 {
512   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
513   if ( !appStudy ) return;
514   _PTR(Study) aStudy = appStudy->studyDS();
515
516   QStringList aFilters;
517   aFilters.append( tr( "PYTHON_FILES_FILTER" ) );
518
519   DumpStudyFileDlg* fd = new DumpStudyFileDlg( desktop() );
520   fd->setCaption( tr( "TOT_DESK_FILE_DUMP_STUDY" ) );
521   fd->setFilters( aFilters );
522   fd->myPublishChk->setChecked( true );
523   fd->mySaveGUIChk->setChecked( true );
524   fd->exec();
525   QString aFileName = fd->selectedFile();
526   bool toPublish = fd->myPublishChk->isChecked();
527   bool toSaveGUI = fd->mySaveGUIChk->isChecked();
528   delete fd;
529
530   if ( !aFileName.isEmpty() ) {
531     QFileInfo aFileInfo(aFileName);
532     int savePoint;
533     if ( toSaveGUI ) { //SRN: Store a visual state of the study at the save point for DumpStudy method
534       SALOMEDS_IParameters::setDumpPython(appStudy->studyDS());
535       savePoint = SalomeApp_VisualState( this ).storeState(); //SRN: create a temporary save point
536       //prefix = SALOMEDS_IParameters::getStudyScript(appStudy->studyDS(), appStudy->getVisualComponentName(), savePoint);
537       
538     }
539     bool res = aStudy->DumpStudy( aFileInfo.dirPath( true ).latin1(), aFileInfo.baseName().latin1(), toPublish);
540     if ( toSaveGUI ) 
541       appStudy->removeSavePoint(savePoint); //SRN: remove the created temporary save point.
542     if ( !res )
543       SUIT_MessageBox::warn1 ( desktop(),
544                                QObject::tr("WRN_WARNING"),
545                                tr("WRN_DUMP_STUDY_FAILED"),
546                                QObject::tr("BUT_OK") );
547   }
548 }
549
550 /*!Private SLOT. On load script.*/
551 void SalomeApp_Application::onLoadScript( )
552 {
553   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
554   if ( !appStudy ) return;
555   _PTR(Study) aStudy = appStudy->studyDS();
556
557   if ( aStudy->GetProperties()->IsLocked() ) {
558     SUIT_MessageBox::warn1 ( desktop(),
559                              QObject::tr("WRN_WARNING"),
560                              QObject::tr("WRN_STUDY_LOCKED"),
561                              QObject::tr("BUT_OK") );
562     return;
563   }
564
565   QStringList filtersList;
566   filtersList.append(tr("PYTHON_FILES_FILTER"));
567   filtersList.append(tr("ALL_FILES_FILTER"));
568
569   QString aFile = SUIT_FileDlg::getFileName( desktop(), "", filtersList, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), true, true );
570
571   if ( !aFile.isEmpty() )
572   {
573     QString command = QString("execfile(\"%1\")").arg(aFile);
574
575     PythonConsole* pyConsole = pythonConsole();
576
577     if ( pyConsole )
578       pyConsole->exec( command );
579   }
580 }
581
582 /*!Private SLOT. On save GUI state.*/
583 void SalomeApp_Application::onSaveGUIState()
584 {
585   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
586   if ( study ) {
587     SalomeApp_VisualState( this ).storeState();
588     updateSavePointDataObjects( study );
589     objectBrowser()->updateTree( study->root() );
590   }
591 }
592
593 /*!Gets file filter.
594  *\retval QString "(*.hdf)"
595  */
596 QString SalomeApp_Application::getFileFilter() const
597 {
598   return "(*.hdf)";
599 }
600
601 /*!Create window.*/
602 QWidget* SalomeApp_Application::createWindow( const int flag )
603 {
604   QWidget* wid = 0;
605   if ( flag != WT_PyConsole ) wid = LightApp_Application::createWindow(flag);
606
607   SUIT_ResourceMgr* resMgr = resourceMgr();
608
609   if ( flag == WT_ObjectBrowser )
610   {
611     OB_Browser* ob = (OB_Browser*)wid;
612     connect( ob->listView(), SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( onDblClick( QListViewItem* ) ) );
613     bool autoSize = resMgr->booleanValue( "ObjectBrowser", "auto_size", false ),
614          autoSizeFirst = resMgr->booleanValue( "ObjectBrowser", "auto_size_first", true );
615     for ( int i = SalomeApp_DataObject::CT_Value; i <= SalomeApp_DataObject::CT_RefEntry; i++ )
616     {
617       ob->addColumn( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), i );
618       ob->setColumnShown( i, resMgr->booleanValue( "ObjectBrowser",
619                                                    QString().sprintf( "visibility_column_%d", i ), true ) );
620     }
621     ob->setWidthMode( autoSize ? QListView::Maximum : QListView::Manual );
622     ob->listView()->setColumnWidthMode( 0, autoSizeFirst ? QListView::Maximum : QListView::Manual );
623     ob->resize( desktop()->width()/3, ob->height() );
624   }
625   else if ( flag == WT_PyConsole )
626   {
627     PythonConsole* pyCons = new PythonConsole( desktop(), new SalomeApp_PyInterp() );
628     pyCons->setCaption( tr( "PYTHON_CONSOLE" ) );
629     wid = pyCons;
630     pyCons->resize( pyCons->width(), desktop()->height()/4 );
631     //pyCons->connectPopupRequest(this, SLOT(onConnectPopupRequest(SUIT_PopupClient*, QContextMenuEvent*)));
632   }
633   return wid;
634 }
635
636 /*!Create preferences.*/
637 void SalomeApp_Application::createPreferences( LightApp_Preferences* pref )
638 {
639   LightApp_Application::createPreferences(pref);
640
641   if ( !pref )
642     return;
643
644   int salomeCat = pref->addPreference( tr( "PREF_CATEGORY_SALOME" ) );
645   int obTab = pref->addPreference( tr( "PREF_TAB_OBJBROWSER" ), salomeCat );
646   int defCols = pref->addPreference( tr( "PREF_GROUP_DEF_COLUMNS" ), obTab );
647   for ( int i = SalomeApp_DataObject::CT_Value; i <= SalomeApp_DataObject::CT_RefEntry; i++ )
648   {
649     pref->addPreference( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), defCols,
650                          LightApp_Preferences::Bool, "ObjectBrowser", QString().sprintf( "visibility_column_%d", i ) );
651   }
652   pref->setItemProperty( defCols, "columns", 1 );
653
654   // adding preference to LightApp_Application handled preferences..  a bit of hacking with resources..
655   int genTab = pref->addPreference( LightApp_Application::tr( "PREF_TAB_GENERAL" ), salomeCat );
656   int studyGroup = pref->addPreference( LightApp_Application::tr( "PREF_GROUP_STUDY" ), genTab );
657   pref->addPreference( tr( "PREF_STORE_VISUAL_STATE" ), studyGroup, LightApp_Preferences::Bool, "Study", "store_visual_state" );
658 }
659
660 /*!Update desktop title.*/
661 void SalomeApp_Application::updateDesktopTitle() {
662   QString aTitle = applicationName();
663   QString aVer = applicationVersion();
664   if ( !aVer.isEmpty() )
665     aTitle += QString( " " ) + aVer;
666
667   if ( activeStudy() )
668   {
669     QString sName = SUIT_Tools::file( activeStudy()->studyName().stripWhiteSpace(), false );
670     if ( !sName.isEmpty() ) {
671       SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
672       if ( study ) {
673         _PTR(Study) stdDS = study->studyDS();
674         if(stdDS) {
675           if ( stdDS->GetProperties()->IsLocked() ) {
676             aTitle += QString( " - [%1 (%2)]").arg( sName ).arg( tr( "STUDY_LOCKED" ) );
677           } else {
678             aTitle += QString( " - [%1]" ).arg( sName );
679           }
680         }
681       }
682     }
683   }
684
685   desktop()->setCaption( aTitle );
686 }
687
688 /*!Gets CORBA::ORB_var*/
689 CORBA::ORB_var SalomeApp_Application::orb()
690 {
691   ORB_INIT& init = *SINGLETON_<ORB_INIT>::Instance();
692   static CORBA::ORB_var _orb = init( qApp->argc(), qApp->argv() );
693   return _orb;
694 }
695
696 /*!Create and return SALOMEDS_StudyManager.*/
697 SALOMEDSClient_StudyManager* SalomeApp_Application::studyMgr()
698 {
699   static _PTR(StudyManager) _sm;
700   if(!_sm) _sm = ClientFactory::StudyManager();
701   return _sm.get();
702 }
703
704 /*!Create and return SALOME_NamingService.*/
705 SALOME_NamingService* SalomeApp_Application::namingService()
706 {
707   static SALOME_NamingService* _ns = new SALOME_NamingService( orb() );
708   return _ns;
709 }
710
711 /*!Create and return SALOME_LifeCycleCORBA.*/
712 SALOME_LifeCycleCORBA* SalomeApp_Application::lcc()
713 {
714   static SALOME_LifeCycleCORBA* _lcc = new SALOME_LifeCycleCORBA( namingService() );
715   return _lcc;
716 }
717
718 /*!Return default engine IOR for light modules*/
719 QString SalomeApp_Application::defaultEngineIOR()
720 {
721   /// Look for a default module engine (needed for CORBAless modules to use SALOMEDS persistence)
722   QString anIOR( "" );
723   CORBA::Object_ptr anEngine = namingService()->Resolve( "/SalomeAppEngine" );
724   if ( !CORBA::is_nil( anEngine ) )
725     anIOR = orb()->object_to_string( anEngine );
726   return anIOR;
727 }
728
729 /*!Private SLOT. On preferences.*/
730 void SalomeApp_Application::onProperties()
731 {
732   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
733   if( !study )
734     return;
735
736   _PTR(StudyBuilder) SB = study->studyDS()->NewBuilder();
737   SB->NewCommand();
738
739   SalomeApp_StudyPropertiesDlg aDlg( desktop() );
740   int res = aDlg.exec();
741   if( res==QDialog::Accepted && aDlg.isChanged() )
742     SB->CommitCommand();
743   else
744     SB->AbortCommand();
745
746   //study->updateCaptions();
747   updateDesktopTitle();
748   updateActions();
749 }
750
751 /*!Insert items in popup, which necessary for current application*/
752 void SalomeApp_Application::contextMenuPopup( const QString& type, QPopupMenu* thePopup, QString& title )
753 {
754   LightApp_Application::contextMenuPopup( type, thePopup, title );
755
756   OB_Browser* ob = objectBrowser();
757   if ( !ob || type != ob->popupClientType() )
758     return;
759
760   // Get selected objects
761   SALOME_ListIO aList;
762   LightApp_SelectionMgr* mgr = selectionMgr();
763   mgr->selectedObjects( aList, QString::null, false );
764
765   // add GUI state commands: restore, rename
766   if ( aList.Extent() == 1 && aList.First()->hasEntry() && 
767        QString( aList.First()->getEntry() ).startsWith( tr( "SAVE_POINT_DEF_NAME" ) ) ) {
768     thePopup->insertSeparator();
769     thePopup->insertItem( tr( "MEN_RESTORE_VS" ), this, SLOT( onRestoreGUIState() ) );
770     thePopup->insertItem( tr( "MEN_RENAME_VS" ),  this, SLOT( onRenameGUIState() ) );
771     thePopup->insertItem( tr( "MEN_DELETE_VS" ),  this, SLOT( onDeleteGUIState() ) );
772   }
773
774   // "Delete reference" item should appear only for invalid references
775
776   // isInvalidRefs will be true, if at least one of selected objects is invalid reference
777   bool isInvalidRefs = false;
778   SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(activeStudy());
779   _PTR(Study) aStudyDS = aStudy->studyDS();
780   _PTR(SObject) anObj;
781
782   for( SALOME_ListIteratorOfListIO it( aList ); it.More() && !isInvalidRefs; it.Next() )
783     if( it.Value()->hasEntry() )
784     {
785       _PTR(SObject) aSObject = aStudyDS->FindObjectID( it.Value()->getEntry() ), aRefObj = aSObject;
786       while( aRefObj && aRefObj->ReferencedObject( anObj ) )
787         aRefObj = anObj;
788
789       if( aRefObj && aRefObj!=aSObject && QString( aRefObj->GetName().c_str() ).isEmpty() )
790         isInvalidRefs = true;
791     }
792
793   // Add "Delete reference" item to popup
794   if ( isInvalidRefs )
795   {
796     thePopup->insertSeparator();
797     thePopup->insertItem( tr( "MEN_DELETE_INVALID_REFERENCE" ), this, SLOT( onDeleteInvalidReferences() ) );
798     return;
799   }
800
801   aList.Clear();
802   mgr->selectedObjects( aList );
803
804   // "Activate module" item should appear only if it's necessary
805   if (aList.Extent() != 1)
806     return;
807   Handle(SALOME_InteractiveObject) aIObj = aList.First();
808   // check if item is a "GUI state" item (also a first level object)
809   QString entry( aIObj->getEntry() );
810   if ( entry.startsWith( tr( "SAVE_POINT_DEF_NAME" ) ) )
811     return;
812   QString aModuleName(aIObj->getComponentDataType());
813   QString aModuleTitle = moduleTitle(aModuleName);
814   CAM_Module* currentModule = activeModule();
815   if (currentModule && currentModule->moduleName() == aModuleTitle)
816     return;
817   thePopup->insertItem( tr( "MEN_OPENWITH" ), this, SLOT( onOpenWith() ) );
818 }
819
820 /*!Update obect browser:
821  1.if 'updateModels' true, update existing data models;
822  2. update "non-existing" (not loaded yet) data models;
823  3. update object browser if it exists */
824 void SalomeApp_Application::updateObjectBrowser( const bool updateModels )
825 {
826   // update "non-existing" (not loaded yet) data models
827   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
828   if ( study )
829   {
830     _PTR(Study) stdDS = study->studyDS();
831     if( stdDS )
832     {
833       for ( _PTR(SComponentIterator) it ( stdDS->NewComponentIterator() ); it->More(); it->Next() ) 
834       {
835         _PTR(SComponent) aComponent ( it->Value() );
836
837         if ( aComponent->ComponentDataType() == "Interface Applicative" )
838           continue; // skip the magic "Interface Applicative" component
839
840         OB_Browser* ob = static_cast<OB_Browser*>( getWindow( WT_ObjectBrowser ));
841         const bool isAutoUpdate = ob->isAutoUpdate();
842         ob->setAutoUpdate( false );
843         SalomeApp_DataModel::synchronize( aComponent, study );
844         ob->setAutoUpdate( isAutoUpdate );
845         //SalomeApp_DataModel::BuildTree( aComponent, study->root(), study, /*skipExisitng=*/true );
846       }
847     }
848     // create data objects that correspond to GUI state save points
849     updateSavePointDataObjects( study );
850   }
851
852   // update existing data models (already loaded SComponents)
853   LightApp_Application::updateObjectBrowser( updateModels );
854
855   // -- debug -- 
856   //  if ( study && study->root() )
857   //    study->root()->dump();
858 }
859
860 /*!Display Catalog Genenerator dialog */
861 void SalomeApp_Application::onCatalogGen()
862 {
863   ToolsGUI_CatalogGeneratorDlg aDlg( desktop() );
864   aDlg.exec();
865 }
866
867 /*!Display Registry Display dialog */
868 void SalomeApp_Application::onRegDisplay()
869 {
870   CORBA::ORB_var anOrb = orb();
871   ToolsGUI_RegWidget* regWnd = ToolsGUI_RegWidget::GetRegWidget( anOrb, desktop(), "Registry" );
872   regWnd->show();
873   regWnd->raise();
874   regWnd->setActiveWindow();
875 }
876
877 /*!find original object by double click on item */
878 void SalomeApp_Application::onDblClick( QListViewItem* it )
879 {
880   OB_ListItem* item = dynamic_cast<OB_ListItem*>( it );
881   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
882
883   if( study && item )
884   {
885     SalomeApp_DataObject* obj = dynamic_cast<SalomeApp_DataObject*>( item->dataObject() );
886     if( !obj )
887       return;
888
889     QString entry = obj->entry();
890     _PTR(SObject) sobj = study->studyDS()->FindObjectID( entry.latin1() ), ref;
891
892     if( sobj && sobj->ReferencedObject( ref ) )
893     {
894       entry = ref->GetID().c_str();
895       QListViewItemIterator anIt( item->listView() );
896       for( ; anIt.current(); anIt++ )
897       {
898         OB_ListItem* item = dynamic_cast<OB_ListItem*>( anIt.current() );
899         if( !item )
900           continue;
901
902         SalomeApp_DataObject* original = dynamic_cast<SalomeApp_DataObject*>( item->dataObject() );
903         if( original->entry()!=entry )
904           continue;
905
906         OB_Browser* br = objectBrowser();
907         br->setSelected( original );
908         SUIT_DataObject* p = original->parent();
909         while( p )
910         {
911           br->setOpen( p );
912           p = p->parent();
913         }
914         break;
915       }
916     }
917   }
918 }
919
920 SUIT_ViewManager* SalomeApp_Application::newViewManager(const QString& type)
921 {
922   return createViewManager(type);
923 }
924
925
926 /*!Global utility funciton, returns selected GUI Save point object's ID */
927 int getSelectedSavePoint( const LightApp_SelectionMgr* selMgr )
928 {
929   SALOME_ListIO aList;
930   selMgr->selectedObjects( aList );
931   Handle(SALOME_InteractiveObject) aIObj = aList.First();
932   QString entry( aIObj->getEntry() );
933   QString startStr = QObject::tr( "SAVE_POINT_DEF_NAME" );
934   if ( !entry.startsWith( startStr ) ) // it's a "GUI state" object
935     return -1;
936   bool ok; // conversion to integer is ok?
937   int savePoint = entry.right( entry.length() - startStr.length() ).toInt( &ok );
938   return ok ? savePoint : -1;
939 }
940
941 /*!Called on Restore GUI State popup command*/
942 void SalomeApp_Application::onRestoreGUIState()
943 {
944   int savePoint = ::getSelectedSavePoint( selectionMgr() );
945   if ( savePoint == -1 ) 
946     return;  
947   SalomeApp_VisualState( this ).restoreState( savePoint );
948 }
949
950 /*!Called on Rename GUI State popup command*/
951 void SalomeApp_Application::onRenameGUIState()
952 {
953   int savePoint = ::getSelectedSavePoint( selectionMgr() );
954   if ( savePoint == -1 ) 
955     return;  
956   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
957   if ( !study ) 
958     return;
959
960   QString newName = LightApp_NameDlg::getName( desktop(), study->getNameOfSavePoint( savePoint ) );
961   if ( !newName.isNull() && !newName.isEmpty() ) {
962     study->setNameOfSavePoint( savePoint, newName );
963     updateSavePointDataObjects( study );
964   }
965 }
966
967
968 /*!Called on Delete GUI State popup command*/
969 void SalomeApp_Application::onDeleteGUIState()
970 {
971   int savePoint = ::getSelectedSavePoint( selectionMgr() );
972   if ( savePoint == -1 ) 
973     return;  
974   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
975   if ( !study ) 
976     return;
977   
978   study->removeSavePoint( savePoint );
979   updateSavePointDataObjects( study );
980 }
981
982 /*!Called on Save study operation*/
983 void SalomeApp_Application::onStudySaved( SUIT_Study* study )
984 {
985   LightApp_Application::onStudySaved( study );
986
987   if ( objectBrowser() ) {
988     updateSavePointDataObjects( dynamic_cast<SalomeApp_Study*>( study ) );
989     objectBrowser()->updateTree( study->root() );
990   }
991 }
992
993 /*!Called on Open study operation*/
994 void SalomeApp_Application::onStudyOpened( SUIT_Study* study )
995 {
996   LightApp_Application::onStudyOpened( study );
997
998   if ( objectBrowser() ) {
999     updateSavePointDataObjects( dynamic_cast<SalomeApp_Study*>( study ) );
1000     objectBrowser()->updateTree( study->root() );
1001   }
1002 }
1003
1004 /*! utility function.  returns true if list view item that correspond to given SUIT_DataObject is open.
1005  only first level items are traversed */
1006 bool isListViewItemOpen( QListView* lv, const SUIT_DataObject* dobj )
1007 {
1008   if ( !lv || !dobj )
1009     return false;
1010
1011   QListViewItem* item = lv->firstChild();
1012   while ( item ) {
1013     OB_ListItem* ob_item = dynamic_cast<OB_ListItem*>( item );
1014     if ( ob_item && ob_item->dataObject() == dobj )
1015       return ob_item->isOpen();
1016     item = item->nextSibling();
1017   }
1018   return false;
1019 }
1020
1021 /*! updateSavePointDataObjects: syncronize data objects that correspond to save points (gui states)*/
1022 void SalomeApp_Application::updateSavePointDataObjects( SalomeApp_Study* study )
1023 {
1024   OB_Browser* ob = objectBrowser();
1025
1026   if ( !study || !ob )
1027     return;
1028
1029   // find GUI states root object
1030   SUIT_DataObject* guiRootObj = 0;
1031   DataObjectList ch; 
1032   study->root()->children( ch ); 
1033   DataObjectList::const_iterator it = ch.begin(), last = ch.end();
1034   for ( ; it != last ; ++it ) {
1035     if ( dynamic_cast<SalomeApp_SavePointRootObject*>( *it ) ) {
1036       guiRootObj = *it;
1037       break;
1038     }
1039   }
1040   std::vector<int> savePoints = study->getSavePoints();
1041   // case 1: no more save points but they existed in study's tree
1042   if ( savePoints.empty() && guiRootObj ) {
1043     delete guiRootObj;
1044     return;
1045   }
1046   // case 2: no more save points but root does not exist either
1047   if ( savePoints.empty() && !guiRootObj )
1048     return;
1049   // case 3: save points but no root for them - create it
1050   if ( !savePoints.empty() && !guiRootObj )
1051     guiRootObj = new SalomeApp_SavePointRootObject( study->root() );
1052   // case 4: everything already exists.. here may be a problem: we want "GUI states" root object
1053   // to be always the last one in the tree.  Here we check - if it is not the last one - remove and
1054   // re-create it.
1055   bool isOpen( false );
1056   if ( guiRootObj->nextBrother() ) {
1057     isOpen = isListViewItemOpen( ob->listView(), guiRootObj );
1058     delete guiRootObj;
1059     guiRootObj = new SalomeApp_SavePointRootObject( study->root() );
1060   }
1061
1062   // store data objects in a map id-to-DataObject
1063   QMap<int,SalomeApp_SavePointObject*> mapDO;
1064   ch.clear(); 
1065   guiRootObj->children( ch ); 
1066   for( it = ch.begin(), last = ch.end(); it != last ; ++it ) {
1067     SalomeApp_SavePointObject* dobj = dynamic_cast<SalomeApp_SavePointObject*>( *it );
1068     if ( dobj )
1069       mapDO[dobj->getId()] = dobj;
1070   }
1071
1072   // iterate new save points.  if DataObject with such ID not found in map - create DataObject
1073   // if in the map - remove it from map.  
1074   for ( int i = 0; i < savePoints.size(); i++ )
1075     if ( !mapDO.contains( savePoints[i] ) )
1076       new SalomeApp_SavePointObject( guiRootObj, savePoints[i], study );
1077     else {
1078       ob->updateTree( mapDO[ savePoints[i] ] );
1079       mapDO.remove( savePoints[i] );
1080     }
1081   // delete DataObjects that are still in the map -- their IDs were not found in data model
1082   for ( QMap<int,SalomeApp_SavePointObject*>::Iterator it = mapDO.begin(); it != mapDO.end(); ++it )
1083     delete it.data();
1084
1085   if ( isOpen ) // set open if we recreated guiRootObj and it was previously open..
1086     guiRootObj->setOpen( true );
1087 }
1088