Salome HOME
Fix for bug IPAL9190 : 3.0.0: SIGSEGV appears at attempt to run dataflow when it...
[modules/superv.git] / src / SUPERVGUI / SUPERVGUI.cxx
1 //  SUPERV SUPERVGUI : GUI for Supervisor component
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 //  File   : SUPERVGUI.cxx
25 //  Author : Francis KLOSS
26 //  Module : SUPERV
27
28 using namespace std;
29 #include "SUPERVGUI.h"
30 #include "SUPERVGUI_DataModel.h"
31 #include "SUPERVGUI_Selection.h"
32
33 #include "SALOMEDSClient.hxx"
34 #include <boost/shared_ptr.hpp>
35 using namespace boost;
36
37 #include "CAM_Application.h"
38 #include "OB_Browser.h"
39 #include "OB_ListItem.h"
40 #include "SalomeApp_Application.h"
41 #include "SalomeApp_ImportOperation.h"
42 #include "SalomeApp_NameDlg.h"
43 #include "SalomeApp_SelectionMgr.h"
44 #include "SalomeApp_Study.h"
45 #include "SUIT_Desktop.h"
46 #include "SUIT_FileDlg.h"
47 #include "SUIT_MessageBox.h"
48 #include "SUIT_Operation.h"
49 #include "SUIT_ResourceMgr.h"
50 #include "SUIT_Session.h"
51 #include "SUIT_Study.h"
52
53 #include "SUPERVGraph_ViewManager.h"
54
55 #include "SALOME_ListIO.hxx"
56 #include "SALOME_ListIteratorOfListIO.hxx"
57 #include "SALOME_InteractiveObject.hxx"
58 #include "Utils_ORB_INIT.hxx"
59
60 #include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
61
62 #include <qmenubar.h>
63
64 int SUPERVGUI::factory = 0;
65
66 extern "C" {
67   Standard_EXPORT CAM_Module* createModule() {
68     return new SUPERVGUI();
69   }
70 }
71
72
73 SUPERVGUI::SUPERVGUI()
74      : SalomeApp_Module( "SUPERV" ),
75        study(0),
76        browser(0),
77        myFirstActivation(true),
78        myAllGraphsClosed(false),
79        myInitialViewFrame(0)
80   //info(0)
81 {
82     Trace("SUPERVGUI::SUPERVGUI")
83     if (factory==0) {
84         factory = 1;
85         MESSAGE("SUPERVGUI Info : factory build");
86     } else {
87         MESSAGE("SUPERVGUI Error : another call to factory constructor");
88     };
89 }
90
91 SUPERVGUI::~SUPERVGUI() {
92     Trace("SUPERVGUI::~SUPERVGUI")
93     if (factory==1) {
94         factory = 0;
95         //if (!engine->_is_nil()) CORBA::release(engine);         
96         //info->close();
97         if (browser) {
98           if (browser->isVisible())
99             browser->close();
100           delete browser;
101         }
102         MESSAGE("SUPERVGUI Info : factory destroy");
103     } else {
104         MESSAGE("SUPERVGUI Error : another call to factory destructor");
105     };
106 }
107
108 SUPERVGUI* SUPERVGUI::Supervision() {
109   CAM_Application* anApp = dynamic_cast<CAM_Application*>( SUIT_Session::session()->activeApplication() );
110   if ( anApp ) {
111     SUPERVGUI* aSupervModule = dynamic_cast<SUPERVGUI*>( anApp->activeModule() );
112     return aSupervModule;
113   }
114   return NULL;
115 }
116
117 void SUPERVGUI::createSupervAction( const int id, const QString& po_id, const QString& icon_id, const int key, const bool toggle  )
118 {
119   QIconSet icon;
120   QWidget* parent = application()->desktop();
121   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
122   QPixmap pix;
123   if ( icon_id.length() ) 
124     pix = resMgr->loadPixmap( "SUPERV", tr( icon_id ) );
125   else
126     pix = resMgr->loadPixmap( "SUPERV", tr( QString( "ICO_" )+po_id ) );
127   if ( !pix.isNull() )
128     icon = QIconSet( pix );
129
130   QString tooltip    = tr( QString( "TOP_" )+po_id ),
131           menu       = tr( QString( "MEN_" )+po_id ),
132           status_bar = tr( QString( "STB_" )+po_id );
133
134   createAction( id, tooltip, icon, menu, status_bar, key, parent, toggle, this, SLOT( OnGUIEvent() )  );
135 }
136
137 void SUPERVGUI::initialize( CAM_Application* app )
138 {
139   SalomeApp_Module::initialize( app );
140
141   SALOME_NamingService* namingService = (( SalomeApp_Application* )application())->namingService();
142   loadEngine(namingService);
143
144   browser = new SUPERVGUI_Service(namingService);
145   //info    = new SUPERVGUI_Information();
146   cursor  = application()->desktop()->cursor();
147
148   fillInterfaceNameMap();
149
150   // ----- create actions --------------
151   createSupervAction( 301, "IMPORT" );
152   createSupervAction( 302, "EXPORT" );
153
154   createSupervAction( 303, "NEW" );
155   createSupervAction( 304, "MODIFY" );
156
157   createSupervAction( 305, "RELOAD" );
158   createSupervAction( 306, "RUN" );
159   createSupervAction( 307, "KILL" );
160   createSupervAction( 308, "SUSPEND/RESUME" );
161   createSupervAction( 309, "ADDNODE" );
162   createSupervAction( 310, "STEPBYSTEP" );
163
164   createSupervAction( 311, "POP_RENAME" );
165   createSupervAction( 312, "POP_DISPLAY" );
166   createSupervAction( 313, "POP_DELETE" );
167
168   // ----- create menu -----------------
169   int fileId = createMenu( tr( "MEN_FILE" ), -1, -1 );
170   createMenu( 301, fileId, 10 );
171   createMenu( 302, fileId, 10 );
172   createMenu( separator(), fileId, 10 );
173
174   int editId = createMenu( tr( "MEN_EDIT" ), -1, -1 );
175   createMenu( separator(), fileId, 7 );
176   createMenu( 303, editId, -1 );
177   createMenu( 304, editId, -1 );
178
179   int supervId = createMenu( tr( "MEN_SUPERV" ), -1, -1, 10/*, 300*/ );
180   createMenu( 305, supervId, -1 );
181   createMenu( 309, supervId, -1 );
182   createMenu( separator(), fileId, 3 );
183   createMenu( 306, supervId, -1 );
184   createMenu( 310, supervId, -1 );
185   createMenu( 307, supervId, -1 );
186   createMenu( 308, supervId, -1 );     
187
188   // ----- create toolbars -------------
189   int supervisorId = createTool( tr( "TOOL_SUPERVISOR" ) );
190   createTool( 301, supervisorId );
191   createTool( 302, supervisorId );
192   createTool( 303, supervisorId );
193   createTool( 304, supervisorId );
194   createTool( 305, supervisorId );
195   createTool( 309, supervisorId );
196
197   int executionId = createTool( tr( "TOOL_EXECUTION" ) );
198   createTool( 306, executionId );
199   createTool( 310, executionId );
200   createTool( 307, executionId );
201   createTool( 308, executionId );
202
203   // ----- create popup for object browser items -------------
204   QtxPopupMgr* mgr = popupMgr();
205   mgr->insert( action(  311 ), -1, -1 ); // rename dataflow
206   mgr->setRule( action( 311 ), "$type in {'Dataflow'} and selcount=1", true );
207   mgr->insert( action(  312 ), -1, -1 ); // display dataflow
208   mgr->setRule( action( 312 ), "$type in {'Dataflow'} and selcount=1", true );
209   mgr->insert( separator(), -1, -1 ); // -----------
210   mgr->insert( action(  313 ), -1, -1 ); // delete object
211   mgr->setRule( action( 313 ), "$client in {'ObjectBrowser'} and $type in {'Dataflow' 'SupervisorObject'} and selcount>0", true );
212 }
213
214 bool SUPERVGUI::activateModule( SUIT_Study* theStudy )
215 {
216   if ( CORBA::is_nil( engine ) )
217     return false;
218
219   if ( !SalomeApp_Module::activateModule( theStudy ) )
220     return false;
221
222
223
224   //---------------------------------------
225   setMenuShown( true );
226   setToolShown( true );
227
228   study = application()->activeStudy();
229
230   connect( application()->desktop(), SIGNAL( windowActivated( SUIT_ViewWindow* ) ), 
231            this, SLOT( setMain( SUIT_ViewWindow* ) ) );
232
233   if ( myFirstActivation ) {
234     myAllGraphsClosed = false;
235     // create new empty dataflow
236     createDataflow( New, true );
237   }
238   
239   return true;
240 }
241
242 QString SUPERVGUI::engineIOR() const 
243 {
244  if ( !CORBA::is_nil( engine ) )
245     return QString( getApp()->orb()->object_to_string( engine));
246   return QString( "" );
247 }
248
249 bool SUPERVGUI::deactivateModule( SUIT_Study* theStudy )
250 {
251   setMenuShown( false );
252   setToolShown( false );
253
254   disconnect( application()->desktop(), SIGNAL( windowActivated( SUIT_ViewWindow* ) ), 
255               this, SLOT( setMain( SUIT_ViewWindow* ) ) );
256   //---------------------------------------
257   
258   if ( !myAllGraphsClosed )
259     myFirstActivation = false;
260
261   return SalomeApp_Module::deactivateModule( theStudy );
262 }
263
264 CAM_DataModel* SUPERVGUI::createDataModel()
265 {
266   return new SUPERVGUI_DataModel( this );
267 }
268
269 SalomeApp_Selection* SUPERVGUI::createSelection() const
270 {
271   return new SUPERVGUI_Selection();
272 }
273
274 SUIT_ViewWindow* SUPERVGUI::createGraph() {
275   SUPERVGraph_ViewManager* aVM = new SUPERVGraph_ViewManager( study, application()->desktop(), new SUPERVGraph_Viewer() );
276   (( SalomeApp_Application* )application())->addViewManager( aVM );
277   SUIT_ViewWindow* aVW = aVM->createViewWindow();
278   if ( aVW ) {
279     connect( aVM, 
280              SIGNAL( deleteView( SUIT_ViewWindow* ) ),
281              this,
282              SLOT( onGraphClosed( SUIT_ViewWindow* ) ) );
283   }
284   return aVW;
285 }
286
287
288
289 void SUPERVGUI::loadEngine(SALOME_NamingService* namingService) {
290     Trace("SUPERVGUI::loadEngine")
291     SALOME_LifeCycleCORBA LCC(namingService);
292     Engines::Component_var objComponent = LCC.FindOrLoad_Component("SuperVisionContainer", "SUPERV");
293     if (CORBA::is_nil(objComponent)) {
294         QMessageBox::warning(application()->desktop(), tr("ERROR"), tr("MSG_CANT_LOAD_SUPERV"));
295         return;
296     };
297
298     SUPERV::SuperG_var aSuperVisionComponent;
299     aSuperVisionComponent = SUPERV::SuperG::_narrow(objComponent);
300     if (CORBA::is_nil(aSuperVisionComponent)) {
301         QMessageBox::warning(application()->desktop(), tr("ERROR"), tr("MSG_CANT_NARROW_SUPERV"));
302         return;
303     };
304
305     //    engine  = new SUPERV::SuperG_var;
306     engine = aSuperVisionComponent;
307 }
308
309 /*
310 bool SUPERVGUI::information(SUPERV_CNode node, bool isReadOnly) {
311     Trace("SUPERVGUI::information")
312     return(info->run(node, isReadOnly));
313 }
314 */
315 void SUPERVGUI::putInfo(const char* mess) {
316     Trace("SUPERVGUI::putInfo")
317     application()->putInfo(mess);
318 }
319
320 SUPERV_Engine SUPERVGUI::getEngine() {
321     Trace("SUPERVGUI::getEngine")
322     return(engine);
323 }
324
325 SUPERVGUI_Service* SUPERVGUI::getBrowser() {
326     Trace("SUPERVGUI::getBrowser")
327     return(browser);
328 }
329
330 QCursor SUPERVGUI::getCursor() {
331     Trace("SUPERVGUI::getCursor")
332     return(cursor);
333 }
334
335 SUPERVGUI_Main* SUPERVGUI::getMain() {
336     Trace("SUPERVGUI::getMain")
337     return main;
338 }
339
340
341 void SUPERVGUI::registerGraph(QString theName, SUPERVGUI_Main* theGraph){
342   theGraph->setHashCode(theName);
343   myGraphList.append(theGraph);
344 }
345
346
347 void SUPERVGUI::unregisterGraph(SUPERVGUI_Main* theGraph) {
348   SUPERVGUI_Main* aMain;
349   for (aMain = myGraphList.first(); aMain; aMain = myGraphList.next()) {
350     if (aMain == theGraph)
351       myGraphList.remove(aMain);
352   }
353 }
354
355
356 bool SUPERVGUI::isContains(SUIT_Study* theStudy, const QString theKey) {
357   SUPERVGUI_Main* aMain;
358   for (aMain = myGraphList.first(); aMain; aMain = myGraphList.next()) {
359     if ((aMain->getStudy() == theStudy) && (aMain->getHashCode() == theKey))
360       return true;
361   }
362   return false;
363 }
364
365
366 void SUPERVGUI::onGraphClosed(SUIT_ViewWindow* theViewWindow) {
367   if( SUPERVGraph_ViewFrame* supervFrame = dynamic_cast<SUPERVGraph_ViewFrame*>(theViewWindow) ) {
368     disconnect(supervFrame->getViewManager(), 0 , this, 0);
369     SUPERVGraph_View* view = supervFrame->getViewWidget();
370     SUPERVGUI_Main* aGraph = dynamic_cast<SUPERVGUI_Main*>(view);
371     if ( aGraph ) {
372       unregisterGraph(aGraph);
373       SUPERV_Graph aDataFlow = aGraph->getDataflow();
374       if ( !SUPERV_isNull( aDataFlow ) ) {
375         if ( aDataFlow->IsExecuting() ) {
376           const int aMsgResult = QMessageBox::warning(application()->desktop(),
377                                                       tr("WARNING"), 
378                                                       tr("MSG_DF_RUNNING"), 
379                                                       tr("MSG_DF_EXECUTION"), 
380                                                       tr("MSG_DF_KILL"));
381           if ( aMsgResult == 1 ) {
382             // KILL EXECUTION
383             if ( aDataFlow->Kill() ) {
384               // Kill() sends KillEvent and KillState to SUPERVGUI_Thread
385               // while sets myIsActive flag to false when it receives such event/state
386               // after myIsActive is false it calls QThread::exit() to terminate.
387
388               // why while() { qApp->processEvents() } ?
389               // because: SUPERVGUI_Thread::run() receives events, and calls myMain->execute()
390               // method using SALOME_Event paradigm, ProcessVoidEvent() function - 
391               // it puts this event to the main application event loop, in which we are being now.
392               // So if we block main GUI application thread (by calling aGraph->getMyThread()->wait() here)
393               // then we will have a deadlock of 2 threads waiting for one another 
394               while (aGraph->getMyThread()->running()) 
395                 qApp->processEvents();
396             }
397           }
398           else { // BACKGROUND EXECUTION
399             emit KillMainThread(true); // set SUPERVGUI_Thread::myIsActive to false
400             while ( aGraph->getMyThread()->running() )
401               qApp->processEvents();
402           }
403         }
404         else { // EXECUTION IS FINISHED, JUST DESTROY THE SUPERVGUI_Thread object and return.
405           emit KillMainThread(true);
406           while ( aGraph->getMyThread()->running() ) 
407             qApp->processEvents();
408         }
409       }
410     }
411   }
412   if ( myGraphList.isEmpty() ) {
413     myAllGraphsClosed = true;
414     myFirstActivation = true;
415     myInitialViewFrame = 0;
416     main = 0;
417   }
418 }
419
420 void SUPERVGUI::setMain( SUIT_ViewWindow* w) {
421   main = 0;
422   if ( !w ) return;
423
424   study = w->getViewManager()->study();
425   if (!study)
426     return;
427
428   if(SUPERVGraph_ViewFrame* supervFrame = dynamic_cast<SUPERVGraph_ViewFrame*>(w)){
429     SUPERVGraph_View* view = supervFrame->getViewWidget();
430     if (view) {
431       main = dynamic_cast<SUPERVGUI_Main*>(view);
432       connect(this, SIGNAL(KillMainThread(bool)), main->getMyThread(), SLOT(KillThread(bool)));
433     }
434   }
435   Trace("SUPERVGUI::setMain - main: "<<main);
436 }
437
438 void SUPERVGUI::displayDataflow() {
439     Trace("SUPERVGUI::displayDataflow");
440     OB_Browser* aBrowser = (( SalomeApp_Application* )application())->objectBrowser();
441     SUPERV_Graph aDataFlow;
442     QString aIORName;
443
444     OB_ListItem* item = (OB_ListItem*)(aBrowser->listView()->currentItem());
445     _PTR(SObject) aObj 
446       ( (( SalomeApp_Study* )(application()->activeStudy()))->studyDS()->FindObjectID(item->text(2).latin1()) );
447     _PTR(GenericAttribute) anAttr;
448     if (aObj->FindAttribute(anAttr, "AttributeIOR")) {
449       _PTR(AttributeIOR) anIOR ( anAttr );
450       aIORName = QString(anIOR->Value().c_str());
451       if (isContains(study, aIORName)) {
452         if (QMessageBox::warning(application()->desktop(), tr("WARNING"), 
453                                  tr("MSG_GRAPH_DISPLAYED").arg(""), 
454                                  QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
455           return;
456       }
457       //aDataFlow = engine->getStreamGraph(anIOR->Value().c_str());
458       aDataFlow = engine->getGraph(anIOR->Value().c_str());
459       if (SUPERV_isNull(aDataFlow)) {
460         QMessageBox::warning(0, tr("ERROR"), tr("MSG_ACCESS_BAD_IOR"));
461         return;
462       }
463       /* ASV: 20.10.04: fix for 6896
464       if (aDataFlow->IsStreamGraph()) {
465         SUPERV_StreamGraph aDataFlowStream = aDataFlow->ToStreamGraph();
466         if (SUPERV_isNull(aDataFlowStream)) {
467           QMessageBox::warning(0, tr("ERROR"), tr("MSG_ACCESS_BAD_IOR"));
468           return;
469         }
470         aDataFlow = aDataFlowStream;
471       }
472       */
473     }
474     SUPERVGraph_ViewFrame* aViewFrame = dynamic_cast<SUPERVGraph_ViewFrame*>( createGraph() );
475     if( aViewFrame ) {
476       main = new SUPERVGUI_Main( aViewFrame, application()->desktop(), aDataFlow );
477       registerGraph( aIORName, main );
478       aViewFrame->show();
479     }
480 }
481
482
483 void SUPERVGUI::renameDataflow() {
484   SALOME_ListIO aList;
485   aList.Clear();
486   (( SalomeApp_Application* )application())->selectionMgr()->selectedObjects( aList );
487
488   SALOME_ListIteratorOfListIO It( aList );
489   for ( ; It.More(); It.Next() ) {
490     Handle(SALOME_InteractiveObject) IObject = It.Value();
491     
492     _PTR(Study) aStudy = (( SalomeApp_Study* )study)->studyDS();
493     _PTR(SObject) obj ( aStudy->FindObjectID( IObject->getEntry() ) );
494     _PTR(GenericAttribute) anAttr;
495     if ( obj ) {
496       if ( obj->FindAttribute(anAttr, "AttributeName") ) {
497         _PTR(AttributeName) aName ( anAttr );
498         QString nm = QString( aName->Value().c_str() );
499         nm = SalomeApp_NameDlg::getName( application()->desktop(), nm );
500         if ( !nm.isEmpty() ) {
501           // sak : 24.11.04 : fix for PAL6898 : if rename fails (study locked), 
502           // a message box is displayed, and cursor is "wait cursor".  We think that "wait cursor"
503           // is not neccessary here, because the rename operation is fast.
504           //QApplication::setOverrideCursor( Qt::waitCursor );
505           //study->renameIObject( IObject, nm );
506
507           //--->
508           aName->SetValue( nm.latin1() );
509           //rename Interactive object 
510           IObject->setName( ( char* )nm.latin1() );
511           //<---
512
513           updateObjBrowser();
514           //QApplication::restoreOverrideCursor();
515         }
516       }
517     }
518   }
519 }
520
521 void SUPERVGUI::exportDataflow() {
522     Trace("SUPERVGUI::exportDataflow")
523     if ( main==0 ) {
524       QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_EXPORT"));
525     } 
526     else if ( SUPERV_isNull( main->getDataflow() ) ) { // should not normally happen..
527       QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_EXPORT"));
528     } 
529     else {
530       QString f = SUIT_FileDlg::getFileName(application()->desktop(),
531                                             "",
532                                             "*.xml",
533                                             tr("TTL_EXPORT_DATAFLOW"),
534                                             false);
535       if ( !f.isEmpty() ) {
536         
537         // asv : bug [VSR Bugs and Improvements in Supervisor] 1.8 : when exporting a file, 
538         // a backup copy of an existing file must be created (in case Export fails..)
539         QString aBackupFile = SUPERVGUI::createBackupFile( f );
540
541         if ( main->getDataflow()->Export(f.latin1()) ) {
542           unregisterGraph(main);
543           registerGraph(f, main);
544
545           // remove a backup file if export was successfull
546           if ( !aBackupFile.isNull() && !aBackupFile.isEmpty() )
547             QFile::remove( aBackupFile );
548         }
549         else {
550           QMessageBox::warning(application()->desktop(), tr("ERROR"), tr("MSG_BAD_WRITING").arg(aBackupFile));
551         }
552       }
553     }
554 }
555
556 /** 
557  *If a file with theOriginalFileName exists, then the function tries to create 
558  * its backup copy of it (the_name + ".bakX", X = 0,1,2,..,99).  Returns backup file's name
559  * If a file with theOriginalFileName does not exist, or creation fails - Return empty string.
560  */
561 QString SUPERVGUI::createBackupFile( const QString& theOriginalFileName ) {
562   QString theBackupFileName("");
563   if ( QFile::exists( theOriginalFileName ) ) {
564     // 1. construct a backup file name
565     int i = 0;
566     do {
567       theBackupFileName = theOriginalFileName;
568       theBackupFileName += ".bak";
569       theBackupFileName += QString::number(i++);
570     } 
571     while ( QFile::exists( theBackupFileName ) && i < 100 ); // max 99 backup files
572     // if *.bak99 exists -- it will be overwritten 
573     
574     // 2. copy the original file to theBackupFileName
575     QString cmd( "cp \"");
576     cmd += theOriginalFileName;
577     cmd += "\" \"";
578     cmd += theBackupFileName;
579     cmd += "\"";
580     bool res = system( cmd.latin1() );
581     if ( res ) 
582       theBackupFileName = QString("");
583   }
584   return theBackupFileName;
585 }
586
587 void SUPERVGUI::windows( QMap<int, int>& mappa ) const
588 {
589   mappa.insert( SalomeApp_Application::WT_ObjectBrowser, Qt::DockLeft );
590   mappa.insert( SalomeApp_Application::WT_PyConsole, Qt::DockBottom );
591   mappa.insert( SalomeApp_Application::WT_LogWindow, Qt::DockBottom );
592 }
593
594 void SUPERVGUI::newDataflow() {
595   createDataflow( New );
596 }
597
598 void SUPERVGUI::importDataflow() {
599   createDataflow( Import );
600 }
601
602 void SUPERVGUI::modifyDataflow() {
603   createDataflow( Modify );
604 }
605
606 bool SUPERVGUI::createDataflow( const NEW_DF_MODE mode, bool theInitialDF ) {
607   Trace("SUPERVGUI::createDataflow, mode = " << mode );
608
609   // asv : 27.01.05 : fix for PAL7823 : if the study is locked - warn the user and return.
610   _PTR(Study) aStudy = (( SalomeApp_Study* )study)->studyDS();
611   if ( aStudy->GetProperties()->IsLocked() ) {
612     QMessageBox::warning(application()->desktop(), tr("WRN_WARNING"), tr("WRN_STUDY_LOCKED"));
613     return false;
614   }
615
616   SUPERV::Graph_var aGraph;
617
618   QString f; // file name.  declared here because may be used below in error msg construction..
619   if ( mode == Import || mode == Modify ) { // 0. import or modify existing dataflow - select XML file
620     QString title = QString( "TLT_CREATE_DF_%1" ).arg( mode );
621     f = SUIT_FileDlg::getFileName( application()->desktop(), "", "*.xml", tr( title ), true );
622     if ( f.isEmpty() ) // pressed Cancel in file select dialog
623       return false;
624     
625     // check if study already contains a graph imported from the same file
626     if ( isContains( study, f ) ) {
627       if ( QMessageBox::warning( application()->desktop(), tr("WARNING"), tr("MSG_GRAPH_DISPLAYED").arg(f), 
628                                  QMessageBox::Yes, QMessageBox::No) == QMessageBox::No )
629         return false;
630     }
631     
632     // 1. create a graph
633     aGraph = ( mode == Import ) ? engine->StreamGraphE( f ) : engine->StreamGraph( f );        
634   }
635   else
636     aGraph = engine->StreamGraph( MAIN_NEW );
637
638   if ( CORBA::is_nil( aGraph ) ) {
639     QString msg( mode == New ? tr("MSG_CANT_CREATE_DF") : tr("MSG_BAD_FILE").arg(f) );
640     SUIT_MessageBox::warn1( application()->desktop(), tr("ERROR"), tr(msg), tr("BUT_OK") );
641     return false;
642   }
643
644   SUPERVGraph_ViewFrame* aViewFrame; 
645   if ( theInitialDF || !myInitialViewFrame ) {
646     // 2. create a ViewFrame object
647     aViewFrame = dynamic_cast<SUPERVGraph_ViewFrame*>( createGraph() );
648   }
649   else {
650     // 2. get empty initial view frame as new ViewFrame object
651     aViewFrame = myInitialViewFrame;
652     myInitialViewFrame = 0;
653   }
654
655   if ( aViewFrame ) {
656
657     // 3. bind Graph and ViewFrame == create SUPERVGUI_Main object
658     main = new SUPERVGUI_Main( aViewFrame, application()->desktop(), aGraph );
659     if ( mode == New ) {
660       if ( !theInitialDF )
661         main->addNode();
662       else
663         myInitialViewFrame = aViewFrame;
664     }
665     else
666       registerGraph( f, main );
667     aViewFrame->show();
668   }
669
670   return true;
671 }
672
673 void SUPERVGUI::reloadDataflow() {
674   Trace("SUPERVGUI::reloadDataflow");
675   if ( main )  
676     main->sync();
677   else 
678     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_RELOAD"));
679 }
680
681 void SUPERVGUI::runDataflow() {
682   Trace("SUPERVGUI::runDataflow");
683   if ( main )
684     main->run( /*andSuspend=*/false );
685   else
686     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_RUN"));
687 }
688
689 void SUPERVGUI::stepByStep() {
690   Trace("SUPERVGUI::stepByStep");
691   if ( main )
692     main->run( /*andSuspend=*/true );
693   else
694     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_RUN"));
695 }
696
697 void SUPERVGUI::killDataflow() {
698   Trace("SUPERVGUI::killDataflow");
699   if ( main )
700     main->kill();
701   else
702     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_KILL"));
703 }
704
705 void SUPERVGUI::suspendResumeDataflow() {
706   Trace("SUPERVGUI::suspendResumeDataflow");
707   if ( main )
708     main->suspendResume();
709   else
710     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_SUSPEND"));
711 }
712
713 void SUPERVGUI::showComponents() {
714   Trace("SUPERVGUI::showComponents");
715   if ( main ) {
716     if ( main->isEditable() )
717       main->addNode();
718     else
719       QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOTEDITABLE"));
720   }
721   else
722     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_ADD"));
723
724 }
725
726
727 /*bool SUPERVGUI::CustomPopup(QPopupMenu* popup, const QString& theContext, const QString& theParent, const QString& theObject) {
728   Trace("SUPERVGUI::customPopup");
729   Supervision.init();
730   if(popup->count() > 3) {
731     // Temporary code: is to be deleted soon
732     popup->removeItem(QAD_Display_Popup_ID);
733     popup->removeItem(QAD_DisplayOnly_Popup_ID);
734     popup->removeItem(QAD_Erase_Popup_ID);
735     int id = popup->idAt(popup->count() - 1);
736     if (id < 0 && id != -1) popup->removeItem(id); // separator
737     // Temporary code end
738   }
739   
740   SALOME_ListIO aList;
741   aList.Clear();
742   (( SalomeApp_Application* )application())->selectionMgr()->selectedObjects( aList );
743   if ( aList.Extent() == 0 ) return false;
744   
745   if ( aList.Extent() == 1 ) {
746     Handle(SALOME_InteractiveObject) anIObj = aList.First();
747     
748     // insert SUPERV-specific popup items here
749     
750     bool isDataflow, ownObj;
751     whatIsSelected(anIObj, ownObj, isDataflow);
752     
753     if (isDataflow) {
754       popup->insertItem(tr( "MSG_RENAME" ), this, SLOT(renameDataflow()));
755       popup->insertItem("Display", this, SLOT(displayDataflow()));
756       popup->insertSeparator();
757     }
758     if (ownObj)
759       popup->insertItem(tr("MSG_DELETE"), this, SLOT(deleteObject()));
760   }
761
762   if ( aList.Extent() > 1 ) {
763     int aIObjCount = 0;
764     SALOME_ListIteratorOfListIO It_forCheckOwner( aList );
765     for(;It_forCheckOwner.More();It_forCheckOwner.Next()) {
766       Handle(SALOME_InteractiveObject) anIObj = It_forCheckOwner.Value();
767       bool aIsOwner, aIsDataflow;
768       whatIsSelected(anIObj, aIsOwner, aIsDataflow);
769       
770       if (aIsOwner) aIObjCount++;
771     }
772     if ( aIObjCount == aList.Extent() )  //all selected objects belong to Supervision
773       popup->insertItem(tr("MSG_DELETE"), this, SLOT(deleteObject()));
774   }
775
776   return(true);
777   }*/
778
779  
780
781 /** Returns:
782     theIsOwner = true if Selected object belongs to Supervision.
783     theIsDataflow = true if Selected object is Dataflow
784 */
785 void SUPERVGUI::whatIsSelected(const _PTR(SObject)& theObj, bool& theIsOwner, bool& theIsDataflow) {
786   theIsOwner = false;
787   theIsDataflow = false;
788
789   if ( theObj ) {
790     _PTR(SComponent) comp ( theObj->GetFatherComponent() );
791     if ( comp ) {
792       _PTR(GenericAttribute) anAttr;
793       if (comp->FindAttribute(anAttr, "AttributeName")) {
794         _PTR(AttributeName) aName ( anAttr );
795         QString compName(aName->Value().c_str());
796         if ( compName.compare( moduleName() ) == 0 ) {
797           _PTR(GenericAttribute) anAttr;
798           if (theObj->FindAttribute(anAttr, "AttributeIOR")) {
799             _PTR(AttributeIOR) anIOR ( anAttr );
800             SUPERV_Graph aDataFlow = engine->getGraph(anIOR->Value().c_str());
801             if (!SUPERV_isNull(aDataFlow)) {
802               if (aDataFlow->IsStreamGraph()) {
803                 if (!SUPERV_isNull(aDataFlow->ToStreamGraph()))
804                   theIsDataflow = true;
805               }
806               else
807                 theIsDataflow = true;
808             }
809           }
810           CORBA::String_var anObjectID = theObj->GetID().c_str();
811           CORBA::String_var aComponentID = comp->GetID().c_str();
812           if (strcmp(anObjectID, aComponentID))
813             theIsOwner = true;      
814         }
815       }
816     }
817   }
818 }
819
820 void SUPERVGUI::deleteObject() {
821   SALOME_ListIO aList;
822   aList.Clear();
823   (( SalomeApp_Application* )application())->selectionMgr()->selectedObjects( aList );
824   if ( aList.Extent() == 0 ) return;
825    
826   // sak : 24.11.04 : fix for PAL6899 : if the study is locked - warn the user and return.
827   _PTR(Study) aStudy = (( SalomeApp_Study* )study)->studyDS();
828   if ( aStudy->GetProperties()->IsLocked() ) {
829     QMessageBox::warning(application()->desktop(), tr("WRN_WARNING"), tr("WRN_STUDY_LOCKED"));
830     return;
831   }
832
833   // sak : 24.11.04 : fix for PAL6901 : Incorrect deletion of the objects : pressing ESC button
834   // emitted "YES" button click, now it is corrected, and treated as "NO" button click.
835   if (QMessageBox::warning(application()->desktop(),
836                            tr("WARNING"),
837                            tr("MSG_ASK_DELETE"),
838                            QMessageBox::No, QMessageBox::Yes) != QMessageBox::Yes)
839     return;
840    
841   SALOME_ListIteratorOfListIO It( aList );
842   for(;It.More();It.Next()) {
843     Handle(SALOME_InteractiveObject) anIObj = It.Value();
844     //bool aIsOwner, aIsDataflow;
845     //whatIsSelected(anIObj, aIsOwner, aIsDataflow);
846     
847     _PTR(SObject) aObj ( aStudy->FindObjectID( anIObj->getEntry() ) );
848     if ( aObj ) {
849       SUIT_Operation* op = new SalomeApp_ImportOperation( application() );
850       _PTR(StudyBuilder) aBuilder ( aStudy->NewBuilder() );
851       op->start();
852       aBuilder->RemoveObjectWithChildren( aObj );
853       op->commit();
854     }
855   }
856   (( SalomeApp_Application* )application())->selectionMgr()->clearSelected();
857   updateObjBrowser();
858 }
859
860 void SUPERVGUI::OnGUIEvent()
861 {
862   const QObject* obj = sender();
863   if ( !obj || !obj->inherits( "QAction" ) )
864     return;
865   int id = actionId((QAction*)obj);
866   if ( id != -1 )
867     OnGUIEvent( id );
868 }
869
870 bool SUPERVGUI::OnGUIEvent(int command) {
871   switch (command) {
872   case 301: 
873     importDataflow();
874     return(false);
875     
876   case 302: 
877     exportDataflow();
878     return(false);
879     
880   case 303: 
881     newDataflow();
882     return(false);
883     
884   case 304: 
885     modifyDataflow();
886     return(false);
887     
888   case 305:
889     reloadDataflow();
890     return(false);
891     
892   case 306:
893     runDataflow();
894     return(false);
895     
896   case 307: 
897     killDataflow();
898     return(false);
899     
900   case 308:
901     suspendResumeDataflow();
902     return(false);
903     
904   case 309: 
905     showComponents();
906     return(false);
907     
908   case 310: 
909     stepByStep();
910     return(false);
911
912   case 311:
913     renameDataflow();
914     return(false);
915
916   case 312:
917     displayDataflow();
918     return(false);
919
920   case 313:
921     deleteObject();
922     return(false);
923
924   default: 
925     QMessageBox::warning(application()->desktop(), "Supervision Error", "Unknown Command From Salome");
926     return(false);
927   }
928 }
929
930 /*bool SUPERVGUI::SetSettings() {
931   Trace("SUPERVGUI::SetSettings");
932   Supervision.init();
933   return(true);
934   }*/
935
936 /*void SUPERVGUI::DefinePopup(QString& theContext, QString& theParent, QString& theObject) {
937   theObject  = "";
938   theContext = "";
939   }*/
940
941 bool SUPERVGUI::ActiveStudyChanged() {
942   Trace("SUPERVGUI::activeStudyChanged");
943   study = application()->activeStudy();
944   return true;
945 }
946
947 /*void SUPERVGUI::SupportedViewType (int* buffer, int bufferSize)
948 {
949   if (!buffer || !bufferSize) return;
950   buffer[0] = (int)VIEW_GRAPHSUPERV;
951 }*/
952
953 void SUPERVGUI::fillInterfaceNameMap() {
954   //fill map: interface_name <-> component_name for all
955   //interfaces of all loaded components, it is necessary
956   //for correct adding factory nodes from AddComponent,
957   //SubComponent, MulComponent, etc. components.
958   myInterfaceNameMap.clear();
959
960   //get naming service
961   SALOME_NamingService* namingService = (( SalomeApp_Application* )application())->namingService();
962   //get module catalog
963   CORBA::Object_ptr obj  = namingService->Resolve("/Kernel/ModulCatalog");
964   SALOME_ModuleCatalog::ModuleCatalog_var* aModuleCatalog = new SALOME_ModuleCatalog::ModuleCatalog_var;
965   *aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
966   if (!CORBA::is_nil(*aModuleCatalog)) {
967     //get component list
968     SALOME_ModuleCatalog::ListOfComponents_var aCompList = (*aModuleCatalog)->GetComponentList();
969     for (int ind1 = 0; ind1 < aCompList->length(); ind1++) {
970       //get component
971       SALOME_ModuleCatalog::Acomponent_ptr aComponent = (*aModuleCatalog)->GetComponent(aCompList[ind1]);
972       if ( aComponent != NULL ) {
973         //get interface list 
974         SALOME_ModuleCatalog::ListOfInterfaces_var anIntList = aComponent->GetInterfaceList();
975         for (int ind2 = 0; ind2 < anIntList->length(); ind2++) {
976           const char* anIntName = anIntList[ind2];
977           myInterfaceNameMap.insert(QString(anIntName), QString(aComponent->componentname()));
978         }
979       }
980     }
981   }
982 }
983
984 QMap<QString, QString> SUPERVGUI::getInterfaceNameMap() const {
985   return myInterfaceNameMap;
986 }