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