Salome HOME
Join modifications from branch OCC_development_for_3_2_0a2
[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 #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       unregisterGraph(aGraph);
379       SUPERV_Graph aDataFlow = aGraph->getDataflow();
380       if ( !SUPERV_isNull( aDataFlow ) ) {
381         if ( aDataFlow->IsExecuting() ) {
382           const int aMsgResult = QMessageBox::warning(application()->desktop(),
383                                                       tr("WARNING"),
384                                                       tr("MSG_DF_RUNNING"),
385                                                       tr("MSG_DF_EXECUTION"),
386                                                       tr("MSG_DF_KILL"));
387           if ( aMsgResult == 1 ) {
388             // KILL EXECUTION
389             if ( aDataFlow->Kill() ) {
390               // Kill() sends KillEvent and KillState to SUPERVGUI_Thread
391               // while sets myIsActive flag to false when it receives such event/state
392               // after myIsActive is false it calls QThread::exit() to terminate.
393
394               // why while() { qApp->processEvents() } ?
395               // because: SUPERVGUI_Thread::run() receives events, and calls myMain->execute()
396               // method using SALOME_Event paradigm, ProcessVoidEvent() function -
397               // it puts this event to the main application event loop, in which we are being now.
398               // So if we block main GUI application thread (by calling aGraph->getMyThread()->wait() here)
399               // then we will have a deadlock of 2 threads waiting for one another
400               while (aGraph->getMyThread()->running())
401                 qApp->processEvents();
402             }
403           }
404           else { // BACKGROUND EXECUTION
405             emit KillMainThread(true); // set SUPERVGUI_Thread::myIsActive to false
406             while ( aGraph->getMyThread()->running() )
407               qApp->processEvents();
408           }
409         }
410         else { // EXECUTION IS FINISHED, JUST DESTROY THE SUPERVGUI_Thread object and return.
411           emit KillMainThread(true);
412           while ( aGraph->getMyThread()->running() )
413             qApp->processEvents();
414         }
415       }
416     }
417   }
418   if ( myGraphList.isEmpty() ) {
419     myAllGraphsClosed = true;
420     myFirstActivation = true;
421     myInitialViewFrame = 0;
422     myIVFBackgroundColor = QColor();
423     main = 0;
424   }
425 }
426
427 void SUPERVGUI::setMain( SUIT_ViewWindow* w) {
428   main = 0;
429   if ( !w ) return;
430
431   study = w->getViewManager()->study();
432   if (!study)
433     return;
434
435   if(SUPERVGraph_ViewFrame* supervFrame = dynamic_cast<SUPERVGraph_ViewFrame*>(w)){
436     SUPERVGraph_View* view = supervFrame->getViewWidget();
437     if (view) {
438       main = dynamic_cast<SUPERVGUI_Main*>(view);
439       connect(this, SIGNAL(KillMainThread(bool)), main->getMyThread(), SLOT(KillThread(bool)));
440     }
441   }
442   Trace("SUPERVGUI::setMain - main: "<<main);
443 }
444
445 void SUPERVGUI::displayDataflow() {
446     Trace("SUPERVGUI::displayDataflow");
447     OB_Browser* aBrowser = (( SalomeApp_Application* )application())->objectBrowser();
448     SUPERV_Graph aDataFlow;
449     QString aIORName;
450
451     OB_ListItem* item = (OB_ListItem*)(aBrowser->listView()->currentItem());
452     _PTR(SObject) aObj
453       ( (( SalomeApp_Study* )(application()->activeStudy()))->studyDS()->FindObjectID(item->text(2).latin1()) );
454     _PTR(GenericAttribute) anAttr;
455     if (aObj->FindAttribute(anAttr, "AttributeIOR")) {
456       _PTR(AttributeIOR) anIOR ( anAttr );
457       aIORName = QString(anIOR->Value().c_str());
458       if (isContains(study, aIORName)) {
459         if (QMessageBox::warning(application()->desktop(), tr("WARNING"),
460                                  tr("MSG_GRAPH_DISPLAYED").arg(""),
461                                  QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
462           return;
463       }
464       //aDataFlow = engine->getStreamGraph(anIOR->Value().c_str());
465       aDataFlow = engine->getGraph(anIOR->Value().c_str());
466       if (SUPERV_isNull(aDataFlow)) {
467         QMessageBox::warning(0, tr("ERROR"), tr("MSG_ACCESS_BAD_IOR"));
468         return;
469       }
470       /* ASV: 20.10.04: fix for 6896
471       if (aDataFlow->IsStreamGraph()) {
472         SUPERV_StreamGraph aDataFlowStream = aDataFlow->ToStreamGraph();
473         if (SUPERV_isNull(aDataFlowStream)) {
474           QMessageBox::warning(0, tr("ERROR"), tr("MSG_ACCESS_BAD_IOR"));
475           return;
476         }
477         aDataFlow = aDataFlowStream;
478       }
479       */
480     }
481
482     SUPERVGraph_ViewFrame* aViewFrame;
483     if ( !myInitialViewFrame ) {
484       // first case : create a ViewFrame object
485       aViewFrame = dynamic_cast<SUPERVGraph_ViewFrame*>( createGraph() );
486     }
487     else {
488       // second case : get empty initial view frame as new ViewFrame object
489       aViewFrame = myInitialViewFrame;
490       // mkr : PAL8237 : remove first "gag" Main from children
491       aViewFrame->removeChild( aViewFrame->queryList("SUPERVGUI_Main")->first() );
492     }
493
494     if( aViewFrame ) {
495       main = new SUPERVGUI_Main( aViewFrame, application()->desktop(), aDataFlow );
496       registerGraph( aIORName, main );
497       aViewFrame->show();
498     }
499
500     if ( myInitialViewFrame ) {
501       myInitialViewFrame = 0;
502       myIVFBackgroundColor = QColor();
503     }
504 }
505
506
507 void SUPERVGUI::renameDataflow() {
508   SALOME_ListIO aList;
509   aList.Clear();
510   (( SalomeApp_Application* )application())->selectionMgr()->selectedObjects( aList );
511
512   SALOME_ListIteratorOfListIO It( aList );
513   for ( ; It.More(); It.Next() ) {
514     Handle(SALOME_InteractiveObject) IObject = It.Value();
515
516     _PTR(Study) aStudy = (( SalomeApp_Study* )study)->studyDS();
517     _PTR(SObject) obj ( aStudy->FindObjectID( IObject->getEntry() ) );
518     _PTR(GenericAttribute) anAttr;
519     if ( obj ) {
520       if ( obj->FindAttribute(anAttr, "AttributeName") ) {
521         _PTR(AttributeName) aName ( anAttr );
522         QString nm = QString( aName->Value().c_str() );
523         bool ok;
524         nm = QInputDialog::getText( tr( "Rename" ), tr( "Enter new name:" ), QLineEdit::Normal,
525                                     nm, &ok, application()->desktop() );
526         if ( ok && !nm.isEmpty() ) {
527           // sak : 24.11.04 : fix for PAL6898 : if rename fails (study locked),
528           // a message box is displayed, and cursor is "wait cursor".  We think that "wait cursor"
529           // is not neccessary here, because the rename operation is fast.
530           //QApplication::setOverrideCursor( Qt::waitCursor );
531           //study->renameIObject( IObject, nm );
532
533           //--->
534           aName->SetValue( nm.latin1() );
535           //rename Interactive object
536           IObject->setName( ( char* )nm.latin1() );
537           //<---
538
539           updateObjBrowser();
540           //QApplication::restoreOverrideCursor();
541         }
542       }
543     }
544   }
545 }
546
547 void SUPERVGUI::exportDataflow() {
548     Trace("SUPERVGUI::exportDataflow")
549     if ( main==0 ) {
550       QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_EXPORT"));
551     }
552     else if ( SUPERV_isNull( main->getDataflow() ) ) { // should not normally happen..
553       QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_EXPORT"));
554     }
555     else {
556       QString f = SUIT_FileDlg::getFileName(application()->desktop(),
557                                             "",
558                                             "*.xml",
559                                             tr("TTL_EXPORT_DATAFLOW"),
560                                             false);
561       if ( !f.isEmpty() ) {
562
563         // asv : bug [VSR Bugs and Improvements in Supervisor] 1.8 : when exporting a file,
564         // a backup copy of an existing file must be created (in case Export fails..)
565         QString aBackupFile = SUPERVGUI::createBackupFile( f );
566
567         if ( main->getDataflow()->Export(f.latin1()) ) {
568           // mkr : PAL8110 : if we re-register graph with its xml-file name the "Supervisor Warning"
569           //       after object browser popup "Display" item will not appear, it's an error,
570           //       because of this dataflow is already displayed.
571           //unregisterGraph(main);
572           //registerGraph(f, main);
573
574           // remove a backup file if export was successfull
575           if ( !aBackupFile.isNull() && !aBackupFile.isEmpty() )
576             QFile::remove( aBackupFile );
577         }
578         else {
579           QMessageBox::warning(application()->desktop(), tr("ERROR"), tr("MSG_BAD_WRITING").arg(aBackupFile));
580         }
581       }
582     }
583 }
584
585 /**
586  *If a file with theOriginalFileName exists, then the function tries to create
587  * its backup copy of it (the_name + ".bakX", X = 0,1,2,..,99).  Returns backup file's name
588  * If a file with theOriginalFileName does not exist, or creation fails - Return empty string.
589  */
590 QString SUPERVGUI::createBackupFile( const QString& theOriginalFileName ) {
591   QString theBackupFileName("");
592   if ( QFile::exists( theOriginalFileName ) ) {
593     // 1. construct a backup file name
594     int i = 0;
595     do {
596       theBackupFileName = theOriginalFileName;
597       theBackupFileName += ".bak";
598       theBackupFileName += QString::number(i++);
599     }
600     while ( QFile::exists( theBackupFileName ) && i < 100 ); // max 99 backup files
601     // if *.bak99 exists -- it will be overwritten
602
603     // 2. copy the original file to theBackupFileName
604     QString cmd( "cp \"");
605     cmd += theOriginalFileName;
606     cmd += "\" \"";
607     cmd += theBackupFileName;
608     cmd += "\"";
609     bool res = system( cmd.latin1() );
610     if ( res )
611       theBackupFileName = QString("");
612   }
613   return theBackupFileName;
614 }
615
616 void SUPERVGUI::windows( QMap<int, int>& mappa ) const
617 {
618   mappa.insert( SalomeApp_Application::WT_ObjectBrowser, Qt::DockLeft );
619   mappa.insert( SalomeApp_Application::WT_PyConsole, Qt::DockBottom );
620   mappa.insert( SalomeApp_Application::WT_LogWindow, Qt::DockBottom );
621 }
622
623 void SUPERVGUI::newDataflow() {
624   createDataflow( New );
625 }
626
627 void SUPERVGUI::importDataflow() {
628   createDataflow( Import );
629 }
630
631 void SUPERVGUI::modifyDataflow() {
632   createDataflow( Modify );
633 }
634
635 bool SUPERVGUI::createDataflow( const NEW_DF_MODE mode, bool theInitialDF ) {
636   Trace("SUPERVGUI::createDataflow, mode = " << mode );
637
638   // asv : 27.01.05 : fix for PAL7823 : if the study is locked - warn the user and return.
639   _PTR(Study) aStudy = (( SalomeApp_Study* )study)->studyDS();
640   if ( aStudy->GetProperties()->IsLocked() ) {
641     QMessageBox::warning(application()->desktop(), tr("WRN_WARNING"), tr("WRN_STUDY_LOCKED"));
642     return false;
643   }
644
645   SUPERV::Graph_var aGraph;
646
647   QString f; // file name.  declared here because may be used below in error msg construction..
648   if ( mode == Import || mode == Modify ) { // 0. import or modify existing dataflow - select XML file
649     QString title = QString( "TLT_CREATE_DF_%1" ).arg( mode );
650     f = SUIT_FileDlg::getFileName( application()->desktop(), "", "*.xml", tr( title ), true );
651     if ( f.isEmpty() ) // pressed Cancel in file select dialog
652       return false;
653
654     // check if study already contains a graph imported from the same file
655     if ( isContains( study, f ) ) {
656       if ( QMessageBox::warning( application()->desktop(), tr("WARNING"), tr("MSG_GRAPH_DISPLAYED").arg(f),
657                                  QMessageBox::Yes, QMessageBox::No) == QMessageBox::No )
658         return false;
659     }
660
661     // 1. create a graph
662     aGraph = ( mode == Import ) ? engine->StreamGraphE( f ) : engine->StreamGraph( f );
663   }
664   else
665     aGraph = engine->StreamGraph( MAIN_NEW );
666
667   if ( CORBA::is_nil( aGraph ) ) {
668     QString msg( mode == New ? tr("MSG_CANT_CREATE_DF") : tr("MSG_BAD_FILE").arg(f) );
669     SUIT_MessageBox::warn1( application()->desktop(), tr("ERROR"), tr(msg), tr("BUT_OK") );
670     return false;
671   }
672
673   SUPERVGraph_ViewFrame* aViewFrame;
674   if ( theInitialDF || !myInitialViewFrame ) {
675     // 2. create a ViewFrame object
676     aViewFrame = dynamic_cast<SUPERVGraph_ViewFrame*>( createGraph() );
677   }
678   else {
679     // 2. get empty initial view frame as new ViewFrame object
680     aViewFrame = myInitialViewFrame;
681     // mkr : PAL8237 : remove first "gag" Main from children
682     aViewFrame->removeChild( aViewFrame->queryList("SUPERVGUI_Main")->first() );
683   }
684
685   if ( aViewFrame ) {
686
687     // 3. bind Graph and ViewFrame == create SUPERVGUI_Main object
688     main = new SUPERVGUI_Main( aViewFrame, application()->desktop(), aGraph );
689     if ( mode == New ) {
690       if ( !theInitialDF )      
691         main->addNode();
692       else
693         myInitialViewFrame = aViewFrame;
694     }
695     // mkr : IPAL11550 : register graph not depend on creation mode
696     registerGraph( f, main );
697     main->resizeView( new QResizeEvent( aViewFrame->size(), aViewFrame->size() ) );
698     aViewFrame->show();
699     QFileInfo inf( f );
700     if( !f.isEmpty() )
701       aViewFrame->setCaption( inf.fileName() );
702   }
703
704   if ( !theInitialDF ) {
705     myInitialViewFrame = 0;
706     myIVFBackgroundColor = QColor();
707   }
708
709   return true;
710 }
711
712 void SUPERVGUI::reloadDataflow() {
713   Trace("SUPERVGUI::reloadDataflow");
714   if ( main )
715     main->sync();
716   else
717     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_RELOAD"));
718 }
719
720 void SUPERVGUI::runDataflow() {
721   Trace("SUPERVGUI::runDataflow");
722   if ( main )
723     main->run( /*andSuspend=*/false );
724   else
725     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_RUN"));
726 }
727
728 void SUPERVGUI::stepByStep() {
729   Trace("SUPERVGUI::stepByStep");
730   if ( main )
731     main->run( /*andSuspend=*/true );
732   else
733     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_RUN"));
734 }
735
736 void SUPERVGUI::killDataflow() {
737   Trace("SUPERVGUI::killDataflow");
738   if ( main )
739     main->kill();
740   else
741     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_KILL"));
742 }
743
744 void SUPERVGUI::suspendResumeDataflow() {
745   Trace("SUPERVGUI::suspendResumeDataflow");
746   if ( main )
747     main->suspendResume();
748   else
749     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_SUSPEND"));
750 }
751
752 void SUPERVGUI::showComponents() {
753   Trace("SUPERVGUI::showComponents");
754   if ( main ) {
755     if ( main->isEditable() )
756       main->addNode();
757     else
758       QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOTEDITABLE"));
759   }
760   else
761     QMessageBox::warning(application()->desktop(), tr("WARNING"), tr("MSG_NOWINDOW_TO_ADD"));
762
763 }
764
765
766 /*bool SUPERVGUI::CustomPopup(QPopupMenu* popup, const QString& theContext, const QString& theParent, const QString& theObject) {
767   Trace("SUPERVGUI::customPopup");
768   Supervision.init();
769   if(popup->count() > 3) {
770     // Temporary code: is to be deleted soon
771     popup->removeItem(QAD_Display_Popup_ID);
772     popup->removeItem(QAD_DisplayOnly_Popup_ID);
773     popup->removeItem(QAD_Erase_Popup_ID);
774     int id = popup->idAt(popup->count() - 1);
775     if (id < 0 && id != -1) popup->removeItem(id); // separator
776     // Temporary code end
777   }
778
779   SALOME_ListIO aList;
780   aList.Clear();
781   (( SalomeApp_Application* )application())->selectionMgr()->selectedObjects( aList );
782   if ( aList.Extent() == 0 ) return false;
783
784   if ( aList.Extent() == 1 ) {
785     Handle(SALOME_InteractiveObject) anIObj = aList.First();
786
787     // insert SUPERV-specific popup items here
788
789     bool isDataflow, ownObj;
790     whatIsSelected(anIObj, ownObj, isDataflow);
791
792     if (isDataflow) {
793       popup->insertItem(tr( "MSG_RENAME" ), this, SLOT(renameDataflow()));
794       popup->insertItem("Display", this, SLOT(displayDataflow()));
795       popup->insertSeparator();
796     }
797     if (ownObj)
798       popup->insertItem(tr("MSG_DELETE"), this, SLOT(deleteObject()));
799   }
800
801   if ( aList.Extent() > 1 ) {
802     int aIObjCount = 0;
803     SALOME_ListIteratorOfListIO It_forCheckOwner( aList );
804     for(;It_forCheckOwner.More();It_forCheckOwner.Next()) {
805       Handle(SALOME_InteractiveObject) anIObj = It_forCheckOwner.Value();
806       bool aIsOwner, aIsDataflow;
807       whatIsSelected(anIObj, aIsOwner, aIsDataflow);
808
809       if (aIsOwner) aIObjCount++;
810     }
811     if ( aIObjCount == aList.Extent() )  //all selected objects belong to Supervision
812       popup->insertItem(tr("MSG_DELETE"), this, SLOT(deleteObject()));
813   }
814
815   return(true);
816   }*/
817
818
819
820 /** Returns:
821     theIsOwner = true if Selected object belongs to Supervision.
822     theIsDataflow = true if Selected object is Dataflow
823 */
824 void SUPERVGUI::whatIsSelected(const _PTR(SObject)& theObj, bool& theIsOwner, bool& theIsDataflow) {
825   theIsOwner = false;
826   theIsDataflow = false;
827
828   if ( theObj ) {
829     _PTR(SComponent) comp ( theObj->GetFatherComponent() );
830     if ( comp ) {
831       _PTR(GenericAttribute) anAttr;
832       if (comp->FindAttribute(anAttr, "AttributeName")) {
833         _PTR(AttributeName) aName ( anAttr );
834         QString compName(aName->Value().c_str());
835         if ( compName.compare( moduleName() ) == 0 ) {
836           _PTR(GenericAttribute) anAttr;
837           if (theObj->FindAttribute(anAttr, "AttributeIOR")) {
838             _PTR(AttributeIOR) anIOR ( anAttr );
839             SUPERV_Graph aDataFlow = engine->getGraph(anIOR->Value().c_str());
840             if (!SUPERV_isNull(aDataFlow)) {
841               if (aDataFlow->IsStreamGraph()) {
842                 if (!SUPERV_isNull(aDataFlow->ToStreamGraph()))
843                   theIsDataflow = true;
844               }
845               else
846                 theIsDataflow = true;
847             }
848           }
849           CORBA::String_var anObjectID = theObj->GetID().c_str();
850           CORBA::String_var aComponentID = comp->GetID().c_str();
851           if (strcmp(anObjectID, aComponentID))
852             theIsOwner = true;
853         }
854       }
855     }
856   }
857 }
858
859 void SUPERVGUI::deleteObject() {
860   SALOME_ListIO aList;
861   aList.Clear();
862   (( SalomeApp_Application* )application())->selectionMgr()->selectedObjects( aList, QString::null, false );
863   if ( aList.Extent() == 0 ) return;
864
865   // sak : 24.11.04 : fix for PAL6899 : if the study is locked - warn the user and return.
866   _PTR(Study) aStudy = (( SalomeApp_Study* )study)->studyDS();
867   if ( aStudy->GetProperties()->IsLocked() ) {
868     QMessageBox::warning(application()->desktop(), tr("WRN_WARNING"), tr("WRN_STUDY_LOCKED"));
869     return;
870   }
871
872   // sak : 24.11.04 : fix for PAL6901 : Incorrect deletion of the objects : pressing ESC button
873   // emitted "YES" button click, now it is corrected, and treated as "NO" button click.
874   if (QMessageBox::warning(application()->desktop(),
875                            tr("WARNING"),
876                            tr("MSG_ASK_DELETE"),
877                            QMessageBox::No, QMessageBox::Yes) != QMessageBox::Yes)
878     return;
879
880   SALOME_ListIteratorOfListIO It( aList );
881   for(;It.More();It.Next()) {
882     Handle(SALOME_InteractiveObject) anIObj = It.Value();
883     //bool aIsOwner, aIsDataflow;
884     //whatIsSelected(anIObj, aIsOwner, aIsDataflow);
885
886     _PTR(SObject) aObj ( aStudy->FindObjectID( anIObj->getEntry() ) );
887     if ( aObj ) {
888       SUIT_Operation* op = new SalomeApp_ImportOperation( application() );
889       _PTR(StudyBuilder) aBuilder ( aStudy->NewBuilder() );
890       op->start();
891       aBuilder->RemoveObjectWithChildren( aObj );
892       op->commit();
893     }
894   }
895   (( SalomeApp_Application* )application())->selectionMgr()->clearSelected();
896   updateObjBrowser();
897 }
898
899 void SUPERVGUI::OnGUIEvent()
900 {
901   const QObject* obj = sender();
902   if ( !obj || !obj->inherits( "QAction" ) )
903     return;
904   int id = actionId((QAction*)obj);
905   if ( id != -1 )
906     OnGUIEvent( id );
907 }
908
909 bool SUPERVGUI::OnGUIEvent(int command) {
910   switch (command) {
911   case 301:
912     importDataflow();
913     return(false);
914
915   case 302:
916     exportDataflow();
917     return(false);
918
919   case 303:
920     newDataflow();
921     return(false);
922
923   case 304:
924     modifyDataflow();
925     return(false);
926
927   case 305:
928     reloadDataflow();
929     return(false);
930
931   case 306:
932     runDataflow();
933     return(false);
934
935   case 307:
936     killDataflow();
937     return(false);
938
939   case 308:
940     suspendResumeDataflow();
941     return(false);
942
943   case 309:
944     showComponents();
945     return(false);
946
947   case 310:
948     stepByStep();
949     return(false);
950
951   case 311:
952     renameDataflow();
953     return(false);
954
955   case 312:
956     displayDataflow();
957     return(false);
958
959   case 313:
960     deleteObject();
961     return(false);
962
963   default:
964     QMessageBox::warning(application()->desktop(), "Supervision Error", "Unknown Command From Salome");
965     return(false);
966   }
967 }
968
969 /*bool SUPERVGUI::SetSettings() {
970   Trace("SUPERVGUI::SetSettings");
971   Supervision.init();
972   return(true);
973   }*/
974
975 /*void SUPERVGUI::DefinePopup(QString& theContext, QString& theParent, QString& theObject) {
976   theObject  = "";
977   theContext = "";
978   }*/
979
980 bool SUPERVGUI::ActiveStudyChanged() {
981   Trace("SUPERVGUI::activeStudyChanged");
982   study = application()->activeStudy();
983   return true;
984 }
985
986 /*void SUPERVGUI::SupportedViewType (int* buffer, int bufferSize)
987 {
988   if (!buffer || !bufferSize) return;
989   buffer[0] = (int)VIEW_GRAPHSUPERV;
990 }*/
991
992 void SUPERVGUI::fillInterfaceNameMap() {
993   //fill map: interface_name <-> component_name for all
994   //interfaces of all loaded components, it is necessary
995   //for correct adding factory nodes from AddComponent,
996   //SubComponent, MulComponent, etc. components.
997   myInterfaceNameMap.clear();
998
999   //get naming service
1000   SALOME_NamingService* namingService = (( SalomeApp_Application* )application())->namingService();
1001   //get module catalog
1002   CORBA::Object_ptr obj  = namingService->Resolve("/Kernel/ModulCatalog");
1003   SALOME_ModuleCatalog::ModuleCatalog_var* aModuleCatalog = new SALOME_ModuleCatalog::ModuleCatalog_var;
1004   *aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
1005   if (!CORBA::is_nil(*aModuleCatalog)) {
1006     //get component list
1007     SALOME_ModuleCatalog::ListOfComponents_var aCompList = (*aModuleCatalog)->GetComponentList();
1008     for (int ind1 = 0; ind1 < aCompList->length(); ind1++) {
1009       //get component
1010       SALOME_ModuleCatalog::Acomponent_ptr aComponent = (*aModuleCatalog)->GetComponent(aCompList[ind1]);
1011       if ( aComponent != NULL ) {
1012         //get interface list
1013         SALOME_ModuleCatalog::ListOfInterfaces_var anIntList = aComponent->GetInterfaceList();
1014         for (int ind2 = 0; ind2 < anIntList->length(); ind2++) {
1015           const char* anIntName = anIntList[ind2];
1016           myInterfaceNameMap.insert(QString(anIntName), QString(aComponent->componentname()));
1017         }
1018       }
1019     }
1020   }
1021 }
1022
1023 QMap<QString, QString> SUPERVGUI::getInterfaceNameMap() const {
1024   return myInterfaceNameMap;
1025 }