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