source: PSPA/Interface_Web/trunk/pspaWT/src/GWt_pspaApplication.cc @ 256

Last change on this file since 256 was 256, checked in by garnier, 11 years ago

ajout de scrollbar en cours

File size: 36.7 KB
Line 
1#include <stdio.h>
2#include <string.h>
3#include <vector>
4
5#include "GWt_pspaApplication.h"
6#include "GWt_ligneFaisceau.h"
7#include "GWt_globalParameters.h"
8// #include "GWt_dialog.h"
9#include "GWt_draggableImage.h"
10#include "particleBeam.h"
11#include "bareParticle.h"
12#include "nomDeLogiciel.h"
13#include "mixedTools.h"
14#include "nomdElements.h"
15#include "environmentVariables.h"
16#include "GWt_console.h"
17#include "trivaluedBool.h"
18
19#include <Wt/WLineEdit>
20#include <Wt/WGridLayout>
21#include <Wt/WVBoxLayout>
22#include <Wt/WHBoxLayout>
23#include <Wt/WImage>
24#include <Wt/WMenu>
25#include <Wt/WStackedWidget>
26#include <Wt/WBreak>
27#include <Wt/WDialog>
28#include <Wt/WStandardItemModel>
29#include <Wt/WFileUpload>
30#include <Wt/WPainter>
31#include <Wt/WPdfImage>
32#include <Wt/WRasterImage>
33#include <Wt/WScrollArea>
34
35using namespace Wt::Chart;
36
37/*
38 * The env argument contains information about the new session, and
39 * the initial request. It must be passed to the WApplication
40 * constructor so it is typically also an argument for your custom
41 * application constructor.
42*/
43
44PspaApplication::PspaApplication(const WEnvironment& env) : WApplication(env)
45{
46
47  workingDir_ = WApplication::docRoot()+ "/"+WORKINGAREA;
48  nameOfCase_ = "pspa"; // default
49
50  setTitle("portail PSPA");                               // application title
51  if (!wApp->environment().javaScript()) {
52    new WText("<i>This examples requires that javascript support is enabled.</i>",root());
53  }
54 
55  // include the styleSheet
56  WContainerWidget *widroot = root();
57  useStyleSheet ("include/pspa.css");
58  dtmanage_ = new dataManager();
59
60  /*
61   * The main layout is a 3x2 grid layout.
62   */
63  WGridLayout *layout = new WGridLayout();
64//  layout->addWidget(createTitle("<a href='workingArea/parmin'> Menu (In future)</a>"), 0, 0, 1, 2);
65//  layout->addWidget(createTitle("Menu (In future)"), 0, 0, 1, 2);
66
67  WHBoxLayout *toolbarLayout = new WHBoxLayout();
68   
69  WPushButton* boutonSauve = new WPushButton();
70  WPushButton* boutonRestaure = new WPushButton();
71  WPushButton* boutonLoadNew = new WPushButton();
72  WPushButton* boutongraphicalAnalysis = new WPushButton();
73
74  boutonSauve->setStyleClass("saveButton");
75  boutonRestaure->setStyleClass("restoreButton");
76  boutonLoadNew->setStyleClass("loadNewButton");
77  boutongraphicalAnalysis->setStyleClass("histoButton");
78
79  boutonSauve->setToolTip ("sauvegarder la config");
80  boutonRestaure->setToolTip (" restaurer la config");
81  boutonLoadNew->setToolTip ("upload config");
82  boutongraphicalAnalysis->setToolTip ("analyse graphique");
83
84  boutonSauve->setMaximumSize(38,38);
85  boutonSauve->setMinimumSize(38,38);
86  boutonRestaure->setMaximumSize(38,38);
87  boutonRestaure->setMinimumSize(38,38);
88  boutonLoadNew->setMaximumSize(38,38);
89  boutonLoadNew->setMinimumSize(38,38);
90  boutongraphicalAnalysis->setMaximumSize(38,38);
91  boutongraphicalAnalysis->setMinimumSize(38,38);
92 
93  boutonSauve->clicked().connect(this, &PspaApplication::sauver);
94  boutonRestaure->clicked().connect(this, &PspaApplication::restaurer);
95  // Upload when the button is clicked.
96  // React to a succesfull upload.
97  boutonLoadNew->clicked().connect(this, &PspaApplication::openFileSelector);
98
99boutongraphicalAnalysis->clicked().connect(this, &PspaApplication::dialogOnGraphics);
100
101
102  toolbarLayout->addWidget(boutonSauve , 0,Wt::AlignMiddle);
103  toolbarLayout->addWidget(boutonRestaure , 0,Wt::AlignMiddle);
104  toolbarLayout->addWidget(boutonLoadNew , 0,Wt::AlignMiddle);
105  toolbarLayout->addWidget(boutongraphicalAnalysis , 0,Wt::AlignMiddle);
106  toolbarLayout->addWidget(new WText("") , 1,Wt::AlignMiddle);
107
108  WContainerWidget * layoutContainer = new WContainerWidget();
109  layoutContainer->setLayout(toolbarLayout);
110  layoutContainer->decorationStyle().setBackgroundImage ("/icons/fond_toolbar.png");
111  layout->addWidget(layoutContainer, 1, 0, 1, 2);
112  layout->addWidget(createPalette(), 2, 0, 4, 1);
113 
114  beamLine_ = createBeamLine();
115  WScrollArea* scroll = new  WScrollArea();
116  scroll->setWidget(beamLine_);
117  layout->addWidget(scroll, 2, 1, 1, 1);
118 
119
120  // console_ = new WContainerWidget();
121  // console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
122  // console_->setMaximumSize(600,200);
123  // layout->addWidget(console_, 3, 1);
124  // console_->setMinimumSize(300,100);
125  // console_->setOverflow(WContainerWidget::OverflowAuto); 
126
127
128  console_ = new GWt_console();
129  console_->clear();
130  console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
131  console_->setMaximumSize(600,200);
132  console_->setMinimumSize(300,100);
133  console_->setOverflow(WContainerWidget::OverflowAuto); 
134  layout->addWidget(console_, 3, 2);
135
136
137
138
139
140  //-----------
141  // A supprimer et a mettre en fenetre
142  globalParam_ = createGlobalParamWidget();
143  //  leDessin_ = new WContainerWidget();
144  //  leDessin_ = createDrawingWidget();
145  graphicsDialog_ = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
146  graphicsDialog_->setMinimumSize(400,400);
147  graphicsDialog_->setClosable(true);
148
149
150
151  WWidget* executeWidget = createExecuteWidget();
152
153  layout->addWidget( globalParam_, 3, 1);
154  //  layout->addWidget( leDessin_, 3, 2);
155  layout->addWidget( executeWidget , 4, 1);
156  //-----------
157 
158
159
160  layout->setColumnResizable(1);
161  layout->setRowResizable(2);
162  /*
163   * Let row 2 and column 1 take the excess space.
164   */
165  layout->setRowStretch(2, 1);
166  layout->setColumnStretch(1, 1);
167 
168  widroot->setLayout(layout); 
169}
170
171WWidget* PspaApplication::createPalette()
172{
173  WContainerWidget* palette=new WContainerWidget();
174  //  palette->setLayout(new WVBoxLayout());
175
176  // nomdElements *e= new nomdElements();
177  // int nElts= e->getNumberOfElements();
178  // delete e;
179  //  nomdElements bidon;
180  int nElts= nomdElements::getNumberOfElements(); 
181
182  for(int k = 0; k < nElts; k++) {
183    typedElement eType= (typedElement)k;
184    string image = nomdElements::getImageFromType(eType);
185    createDragImage(image.c_str(),
186                    image.c_str(),image.c_str(), palette,nomdElements::getLabelFromType(eType));
187  new WBreak(palette);
188  }
189
190
191  //  palette->setMinimumSize(100,300);
192  return palette;
193}
194
195void PspaApplication::createDragImage(const char *url,const char *smallurl,const char *mimeType,WContainerWidget *p,WString name)
196{
197  GWt_draggableImage *result = new GWt_draggableImage(url,p);
198  WImage *dragImage = new WImage(smallurl,p);
199
200  /*
201   * Set the image to be draggable, showing the other image (dragImage)
202   * to be used as the widget that is visually dragged.
203   */
204  cout << "createDragImage" << dragImage<<endl;
205  result->setDraggable(mimeType,dragImage,true);
206
207}
208
209WWidget* PspaApplication::createBeamLine()
210{
211  WContainerWidget* beamLine = new GWt_LigneFaisceau(this);
212  beamLine->setMinimumSize(300,100);
213  return beamLine;
214}
215
216WWidget* PspaApplication::createGlobalParamWidget()
217{
218  WContainerWidget* globalParam = new GWt_globalParameters(this);
219  globalParam->setMaximumSize(600,150);
220  globalParam->setMinimumSize(600,150);
221  return globalParam;
222}
223
224WWidget* PspaApplication::createExecuteWidget()
225{
226
227  WContainerWidget* executeW = new WContainerWidget();
228  executeW->setMaximumSize(600,150);
229  executeW->setMinimumSize(600,150);
230
231  // bouton execute
232  exec_go_ = new WPushButton("execute!");
233  //    exec_go_->setMinimumSize(300,300);
234  exec_go_->setDisabled(true);
235  exec_go_->clicked().connect(this, &PspaApplication::executer);
236
237  // preparation du bouton add
238  WPushButton* exec_add = new WPushButton("add");
239  exec_add->clicked().connect(this, &PspaApplication::addSectionToExecuteW);
240 
241  // preparation du bouton delete
242  WPushButton* exec_delete = new WPushButton("delete");
243  exec_delete->clicked().connect(this, &PspaApplication::deleteSectionToExecuteW);
244
245  // preparation du bouton push_ok
246  WPushButton* exec_ok = new WPushButton("check/ok");
247  exec_ok->clicked().connect(this, &PspaApplication::checkSectionSelection);
248 
249  // le panel
250  WPanel *panelLogiciels = new WPanel(executeW);
251  panelLogiciels->setTitle(" sections of beam Line for executing softwares ");
252
253  contenuSections_ = new WContainerWidget(); 
254  contenuSections_->addWidget(exec_add);
255  contenuSections_->addWidget(exec_delete);
256  contenuSections_->addWidget(exec_ok);
257  contenuSections_->addWidget(exec_go_);
258  contenuSections_->addWidget(new WBreak());
259  contenuSections_->addWidget(new WBreak());
260  addSectionToExecuteW();
261 
262  panelLogiciels->setCentralWidget(contenuSections_);
263  return executeW;
264}
265
266void PspaApplication::dialogOnGraphics()
267{
268  // GWt_dialog* graphicsDialog = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
269  // graphicsDialog->setMinimumSize(400,400);
270  // graphicsDialog->setClosable(true);
271
272
273    graphicsDialog_->show();
274
275}
276
277WContainerWidget* PspaApplication::createDrawingWidget()
278{
279  WContainerWidget* dessin = new WContainerWidget();
280
281
282
283
284  choixEnveloppeDessin_ = new WComboBox();
285  choixEnveloppeDessin_->addItem("x");
286  //  choixEnveloppeDessin_->addItem("y");
287  WPushButton* okEnv = new WPushButton("draw enveloppe");
288 okEnv->clicked().connect(this, &PspaApplication::dessinerEnveloppe);
289
290
291  dessin->addWidget(new WText(" enveloppe :  "));
292  dessin->addWidget(choixEnveloppeDessin_);
293  dessin->addWidget(okEnv);
294
295  dessin->addWidget(new WBreak());
296
297  choixElementDessin_ = new WComboBox();
298
299
300
301  choixTypeDessinFaisceau_ = new WComboBox();
302  choixTypeDessinFaisceau_->addItem("courant_snyder");
303  choixTypeDessinFaisceau_->addItem("macroparticles");
304  WPushButton* caroule = new WPushButton("dessiner");
305 caroule->clicked().connect(this, &PspaApplication::dessiner);
306
307  dessin->addWidget(new WText(" phase space after element :  "));
308  dessin->addWidget(choixElementDessin_);
309  dessin->addWidget(choixTypeDessinFaisceau_);
310 dessin->addWidget(caroule);
311  dessin->addWidget(new WBreak());
312
313
314
315
316 /////////////////////////////////////////////////////////////////////
317 dessin->addWidget(new WText(" histogramme :  "));
318 WPushButton* okHisto = new WPushButton("histogramme");
319 dessin->addWidget(okHisto);
320 okHisto->clicked().connect(this,&PspaApplication::dessinerHistogramme);
321 /////////////////////////////////////////////////////////////////////
322
323  toto_ = new WContainerWidget();
324  dessin->addWidget(toto_);
325  return dessin;
326}
327
328void PspaApplication::addSectionToExecuteW()
329{
330
331  disableSectionExecute();
332
333  string premierText, dernierText;
334  if(selectedSections_.size() == 0)
335    {
336      premierText = dtmanage_->getLabelFromElementNumero(1);
337
338      dernierText = dtmanage_->getLabelFromElementNumero(dtmanage_->beamLineSize());
339    }
340  else 
341    {
342      dernierText = selectedSections_.back()->fin->text().toUTF8();
343      int dernierNumero = dtmanage_->getCollection()->getNumeroFromLabel(dernierText);
344      dernierNumero++;
345      if ( dernierNumero <= dtmanage_->beamLineSize() )
346        {
347          premierText = dtmanage_->getLabelFromElementNumero(dernierNumero);
348        }
349      else 
350        {
351          premierText = dtmanage_->getLabelFromElementNumero(dtmanage_->beamLineSize());
352        }
353      dernierText = premierText;
354    }
355 
356  //  cout << "PspaApplication::addSectionToExecute() : " << premierText << " à  " << dernierText << endl;
357
358  WContainerWidget* newSection = new WContainerWidget;
359
360  selectedSections_.push_back(new GWt_sectionToExecute);
361  selectedSections_.back()->debut = new WLineEdit();
362  selectedSections_.back()->debut->setDisabled(true);
363  selectedSections_.back()->debut->setText(premierText);
364  selectedSections_.back()->fin = new WLineEdit();
365  selectedSections_.back()->fin->changed().connect(this,&PspaApplication::disableSectionExecute);
366  selectedSections_.back()->fin->setText(dernierText);
367  selectedSections_.back()->selection = new WComboBox();
368  selectedSections_.back()->ligneDeWidget = newSection;
369  newSection->addWidget(new WText(" from : "));
370  newSection->addWidget(selectedSections_.back()->debut);
371  newSection->addWidget(new WText(" to : "));
372  newSection->addWidget(selectedSections_.back()->fin);
373  newSection->addWidget(selectedSections_.back()->selection);
374
375  contenuSections_->addWidget(newSection);
376  unsigned nb = nomDeLogiciel::getNumberOfSoftwares();
377  unsigned k;
378  for(k = 0; k < nb; k++) {
379    selectedSections_.back()->selection->addItem(nomDeLogiciel(k).getString());
380  }
381}
382
383void PspaApplication::disableSectionExecute()
384{
385  exec_go_->setDisabled(true);
386}
387
388void PspaApplication::checkSectionSelection()
389{
390  if ( selectedSections_.empty() ) return;
391
392  // traitement de la premiere ligne
393  // on impose le depart du calcul au premier element
394  string premier = dtmanage_->getLabelFromElementNumero(1);
395  (*selectedSections_.begin())->debut->setText(premier);
396
397  string currentString =  (*selectedSections_.begin())->fin->text().toUTF8();
398  int current = dtmanage_->getCollection()->getNumeroFromLabel( currentString);
399
400  cout << " numero " << current << endl;
401  // si la fin est mal definie on prend toute la config par defaut
402  if ( current <= 0 || current > dtmanage_->beamLineSize() ) 
403    {
404      current = dtmanage_->beamLineSize();
405      currentString =  dtmanage_->getLabelFromElementNumero(current);
406      (*selectedSections_.begin())->fin->setText(currentString);
407    }
408  current++;
409  currentString = dtmanage_->getLabelFromElementNumero(current);
410   
411  // traitement des suivantes (on avance d'un cran dans la liste)
412  list<GWt_sectionToExecute*>::iterator itr, itr0;
413  itr0 = selectedSections_.begin();
414  itr0++;
415  for (itr = itr0; itr != selectedSections_.end(); itr++)
416    {
417      // debut
418      if ( current >= dtmanage_->beamLineSize() ) 
419        {
420          //      GWt_tools::addConsoleMessage(" bad section definition !  \n ");
421          GWt_dialog warningDialog("PSPA : Vérification des sections", " bad section definition !", GWt_dialog::Error,true,true);
422          warningDialog.exec();
423          return;
424        }
425
426      (*itr)->debut->setText(currentString);
427      // fin
428      string finString =  (*itr)->fin->text().toUTF8();
429
430      int numeroFin = dtmanage_->getCollection()->getNumeroFromLabel( finString);
431
432      if ( numeroFin <= current || numeroFin > dtmanage_->beamLineSize())
433        {
434          //      GWt_tools::addConsoleMessage(" bad section definition !  \n ");
435          GWt_dialog warningDialog("PSPA : Vérification des sections", " bad section definition !", GWt_dialog::Error, true,true);
436          warningDialog.exec();
437          return;
438        }
439
440      // preparation de la ligne suivante
441      current = numeroFin +1;
442      currentString = dtmanage_->getLabelFromElementNumero(current);
443    }
444
445  if (!areDataCoherent()) {
446    GWt_dialog warningDialog("PSPA : Vérification des sections", " donnees incoherentes !", GWt_dialog::Error,true,true);
447    warningDialog.exec();
448  }
449  else 
450    {
451      exec_go_->setDisabled(false);
452    }
453}
454
455bool PspaApplication::areDataCoherent() 
456{
457  bool caMarche = true;
458  dtmanage_->initializeExecution(workingDir_);
459 
460  list<GWt_sectionToExecute*>::iterator itr;
461  for(itr = selectedSections_.begin(); itr != selectedSections_.end(); itr++)
462    {
463      string debString = (*itr)->debut->text().toUTF8();
464      string finString = (*itr)->fin->text().toUTF8();
465
466
467      int debut = dtmanage_->getCollection()->getNumeroFromLabel(debString);
468      int fin = dtmanage_->getCollection()->getNumeroFromLabel(finString);
469      nomDeLogiciel prog = nomDeLogiciel ( (*itr)->selection->currentIndex() );
470      dtmanage_->addSectionToExecute(debut,fin,prog);
471    }
472
473  string diagnostic;
474  trivaluedBool essai = dtmanage_->checkExecute(diagnostic);
475  cout << " retour verif , essai = " << essai << endl;
476  if ( essai == error ) {
477    cout << " appli : erreur " << endl;
478    caMarche = false;   
479    GWt_dialog calculDialog("PSPA check execute : ERROR", diagnostic , GWt_dialog::Error,true,true);
480    calculDialog.exec();
481  } else if ( essai == warning )  {
482    cout << " appli : warnig " << endl;
483    caMarche = true;   
484    GWt_dialog calculDialog("PSPA check execute : warning ", diagnostic , GWt_dialog::Warning, false,true);
485    calculDialog.exec();
486  }
487
488  return caMarche;
489}
490
491void PspaApplication::deleteSectionToExecuteW()
492{
493  if ( selectedSections_.empty() ) return;
494  disableSectionExecute();
495  selectedSections_.back()->ligneDeWidget->clear();
496  delete selectedSections_.back()->ligneDeWidget;
497  selectedSections_.pop_back();
498}
499
500void PspaApplication::executer()
501{
502  console_->addConsoleMessage(string("on va peut etre y arriver"));
503   
504 
505  static_cast<GWt_globalParameters*>(globalParam_)->updateGlobals();
506
507  GWt_dialog calculDialog("Calcul en cours", "Veuillez patienter...", GWt_dialog::Wait, true,false);
508  calculDialog.show();
509
510  processEvents();     
511
512  string resultat;
513  if ( !dtmanage_->executeAll(workingDir_, resultat)) {
514    GWt_dialog warningDialog("PSPA : Echec", " echec lors de l'exécution !", GWt_dialog::Error, true,true);
515    warningDialog.exec();
516  }
517  //  cout << " PspaApplication : retour d'execution resultat =  " << resultat << endl;
518  console_->addConsoleMessage(resultat);
519  //  cout << " PspaApplication : affichage console termine  " << endl;
520
521  exec_go_->setDisabled(true);
522
523  calculDialog.hide();
524
525  faireDessin();
526}
527
528void PspaApplication::sauver()
529{
530  cout << " on sauve " << endl;
531  console_->addConsoleMessage("sauvegarde");
532
533  dialogSave_ = new WDialog("save");
534  new WText("name of case : ",dialogSave_->contents());
535  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
536  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
537  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
538  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
539  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
540  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone); 
541  dialogSave_->show();
542}
543
544void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
545{
546
547  if ( code != Wt::WDialog::Accepted ) { console_->addConsoleMessage(" pas de sauvegarde"); return;}
548  else { console_->addConsoleMessage("sauvegarde sur repertoire : " + workingDir_);}
549  nameOfCase_ = saveNameEdit_->text().toUTF8();
550  cout << " PspaApplication::dialogSaveDone() nameOfCase_= " << nameOfCase_ << endl;
551  delete dialogSave_;
552  dialogSave_ = NULL;
553  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
554  bibi->updateGlobals();
555  //  dtmanage_->saveConfiguration(nameOfCase_);
556  dtmanage_->saveConfiguration(workingDir_ ,  nameOfCase_);
557}
558
559
560
561void PspaApplication::restaurer()
562{
563  console_->addConsoleMessage(string("on va recharger..."));
564  dialogOpen_ = new WDialog("open");
565  new WText("name of case : ",dialogOpen_->contents());
566  openNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogOpen_->contents());
567  WPushButton *annule = new WPushButton("cancel",dialogOpen_->contents());
568  WPushButton *submit = new WPushButton("OK",dialogOpen_->contents());
569  annule->clicked().connect(dialogOpen_, &Wt::WDialog::reject);
570  submit->clicked().connect(dialogOpen_, &Wt::WDialog::accept);
571  dialogOpen_->finished().connect(this, &PspaApplication::dialogOpenDone); 
572  dialogOpen_->show();
573}
574
575void PspaApplication::dialogOpenDone(WDialog::DialogCode code)
576{
577
578  if ( code != Wt::WDialog::Accepted ) { console_->addConsoleMessage(" pas de restauration"); return;}
579  else { console_->addConsoleMessage("restauration depuis le repertoire " + workingDir_ );}
580
581  nameOfCase_ = openNameEdit_->text().toUTF8();
582  cout << " PspaApplication::dialogOpenDone() nameOfCase_= " << nameOfCase_ << endl;
583  delete dialogOpen_;
584  dialogSave_ = NULL;
585
586  bool test = dtmanage_->restoreElements(workingDir_,  nameOfCase_);
587  if ( !test ) {
588        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
589           restoreWarning.exec();
590  }
591
592  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
593  bibi->renew();
594
595  GWt_LigneFaisceau* bobo = static_cast<GWt_LigneFaisceau*>(beamLine_);
596  bobo->restoreElementCollection();
597
598  console_->addConsoleMessage(string("...terminee"));
599}
600
601
602void PspaApplication::openFileSelector()
603{
604
605  WContainerWidget *result = new WContainerWidget();
606  WVBoxLayout* myLayout = new WVBoxLayout();
607
608  uploadFileSelectorWidget_ = new WFileUpload();
609
610  uploadFileSelectorWidget_->setFileTextSize(40);
611 
612  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
613  myLayout->addWidget(uploadFileSelectorWidget_);
614
615  result->setLayout (myLayout);
616
617  // Upload automatically when the user entered a file.
618  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
619 
620  // React to a succesfull upload.
621  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
622 
623  // React to a fileupload problem.
624  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
625 
626 
627  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
628 
629  fileSelectorDialog->exec();
630}
631
632
633void PspaApplication::chargerConfig()
634{
635  GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
636
637  string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
638  cout << " fichier client : " << nomDuFichier << endl;
639  bool test = removeExtensionFromConfigName(nomDuFichier);
640  cout << " fichier client sans extension : " << nomDuFichier << endl;
641
642  if ( test )
643    {
644      nameOfCase_ = nomDuFichier;
645      console_->addConsoleMessage(string("restauration..."));
646
647      if ( !dtmanage_->restoreElements(workingDir_, uploadFileSelectorWidget_->spoolFileName()) ) {
648        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
649        restoreWarning.exec();
650      }
651
652      GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
653      bibi->renew();
654
655      GWt_LigneFaisceau* bobo = static_cast<GWt_LigneFaisceau*>(beamLine_);
656      bobo->restoreElementCollection();
657
658      console_->addConsoleMessage(string("...terminee"));
659      message->show();
660    }
661}
662
663
664void PspaApplication::fileTooLarge()
665{
666  std::stringstream stream;
667  stream << maximumRequestSize ();
668  std::string maxRequestSize(stream.str());
669
670  std::string message = "This file is too large, please select a one\n";
671  message += "Maximum file size is "+ maxRequestSize;
672  message += " bytes\n";
673
674  GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true);
675 
676  messageBox->show();
677}
678
679
680void PspaApplication::faireDessin()
681{
682  choixElementDessin_->clear();
683  int nombre = dtmanage_->beamLineSize();
684  for ( int numero =1; numero <= nombre; numero++)
685    {
686      choixElementDessin_->addItem(dtmanage_->getLabelFromElementNumero(numero));
687    }
688
689}
690
691void PspaApplication::dessiner()
692{
693 
694  toto_->clear();
695
696  int typeFaisceau = choixTypeDessinFaisceau_->currentIndex();
697
698  int index = choixElementDessin_->currentIndex();
699
700
701  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
702
703  if ( beam == NULL ) {
704        GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
705          warningBeamState.exec();
706          return;
707    }
708
709
710  if ( typeFaisceau == 0 ) 
711    {
712      if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
713      faireDessinTransport(toto_, beam);
714    }
715  else if ( typeFaisceau == 1 ) 
716    {
717      if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam);
718      else {
719        GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
720          warningBeamState.exec();
721      }
722    }
723  else {
724        GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
725           warningTypeDrawing.exec();
726 }
727  //////////////////////////////////////////
728}
729
730void PspaApplication::dessinerEnveloppe()
731{
732 
733  toto_->clear();
734
735  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
736  if ( typeEnveloppe == 0 ) 
737    {
738      faireDessinEnveloppe(toto_, "x");
739    }
740  else {
741        GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
742           warningTypeEnveloppe.exec();
743  }
744  //////////////////////////////////////////
745}
746
747void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
748{
749
750  GWt_dialog* envDialog = new GWt_dialog("enveloppe",toto_,false);
751  envDialog->setMinimumSize(400,400);
752  envDialog->setClosable(true);
753  envDialog->show();
754
755
756
757  //       new WText(nameOfCase_ + " : enveloppe", toto);
758        unsigned nbel = dtmanage_->beamLineSize();
759
760
761  vector<double> xcor;
762  vector<double> ycor;
763
764
765  dtmanage_->donneesRmsEnveloppe(type,1, nbel, xcor,ycor);
766
767  scatterPlot1D(envDialog->contents(),xcor,ycor);
768
769}
770
771void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam)
772{
773
774  GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
775  pointsDialog->setMinimumSize(400,400);
776  pointsDialog->setClosable(true);
777  // pointsDialog->show();
778
779
780
781  vector<bareParticle>& partic = beam->getParticleVector();
782  new WText(nameOfCase_ + " : espace de phase x,x' "+ " nb partic. "+ mixedTools::intToString(partic.size()), pointsDialog->contents());
783  WStandardItemModel *model = new WStandardItemModel(partic.size(), 3, pointsDialog->contents());
784  //    model->setHeaderData(0, WString("X"));
785  //   model->setHeaderData(1, WString("Y = sin(X)"));
786
787
788  for (unsigned i = 0; i < partic.size(); ++i) {
789    double x= partic.at(i).getPosition().getComponent(0);
790    double begamz = partic.at(i).getBetaGamma().getComponent(2);
791    double xp = partic.at(i).getBetaGamma().getComponent(0)/begamz;
792    //    cout << "x = " << x << " xp= " << xp << endl;
793    model->setData(i, 0, x);
794    model->setData(i, 1,1.e3*xp);
795    model->setData(i, 2,2.e3*xp);
796  }
797
798  WCartesianChart *chart = new WCartesianChart(pointsDialog->contents());
799  chart->setModel(model);        // set the model
800  chart->setXSeriesColumn(0);    // set the column that holds the X data
801  chart->setLegendEnabled(true); // enable the legend
802
803  chart->setType(ScatterPlot);   // set type to ScatterPlot
804
805  // Typically, for mathematical functions, you want the axes to cross
806  // at the 0 mark:
807   chart->axis(XAxis).setLocation(ZeroValue);
808   chart->axis(YAxis).setLocation(ZeroValue);
809
810  // Provide space for the X and Y axis and title.
811  chart->setPlotAreaPadding(80, Left);
812  chart->setPlotAreaPadding(40, Top | Bottom);
813  // Add the curves
814  WDataSeries s(1, PointSeries, Y1Axis);
815  //  s.setShadow(WShadow(3, 3, WColor(0, 0, 0, 127), 3));
816  //    s.setMarker(SquareMarker);
817  //  s.setMarkerSize(600.);
818  //  cout << "le marker est : " << s.marker() << endl;
819     chart->addSeries(s);
820
821  chart->resize(400, 400); // WPaintedWidget must be given explicit size
822 
823
824#ifdef HAS_IMAGEMAGIC
825 Wt::WRasterImage pngImage("png", 600, 600);
826 Wt::WPainter p(&pngImage);
827 chart->paint(p);
828 std::string name;
829 name = workingDir_ + "/chart-"+sessionId ()+".png";
830 std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
831 pngImage.write(f);
832 new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
833#endif
834
835  pointsDialog->show();
836
837  //  chart->setMargin(10, Top | Bottom);            // add margin vertically
838  //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
839}
840
841
842// void PspaApplication::addElemToGlobals()
843// {
844//   static_cast<GWt_globalParameters*>(globalParam_)->addElem();
845// }
846
847void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam)
848{
849  //  WContainerWidget* toto = static_cast<WContainerWidget*>(leDessin_);
850  //  toto->clear();
851
852  //  new WText(nameOfCase_ + " : espace de phase x,x' "+ " nb partic. "+ mixedTools::intToString(partic.size()), toto);
853
854  GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
855  ellipseDialog->setMinimumSize(400,400);
856  ellipseDialog->setClosable(true);
857  ellipseDialog->show();
858
859
860  new WText(nameOfCase_ + " : emittance x,x' " + mixedTools::doubleToString(beam->getUnnormalizedEmittanceX()) + " pi.mm.mrad" , ellipseDialog->contents());
861  new WBreak(ellipseDialog->contents());
862  new WText(" xmax = " + mixedTools::doubleToString(beam->getSigmaTransportij(1,1)) + " cm ", ellipseDialog->contents());
863  new WBreak(ellipseDialog->contents());
864  new WText(" x' max = " + mixedTools::doubleToString(beam->getSigmaTransportij(2,2)) + " mrad ", ellipseDialog->contents());
865  new WBreak(ellipseDialog->contents());
866  new WText(" corr. 12 = " + mixedTools::doubleToString(beam->getSigmaTransportij(2,1))  + " sqrt(cm.rad) ", ellipseDialog->contents());
867 
868  vector<double> xcor;
869  vector<double> ycor;
870  //  dtmanage_->getCurrentBeam()->donneesDessinEllipseXxp(xcor,ycor);
871  beam->donneesDessinEllipseXxp(xcor,ycor);
872  scatterPlot1D(ellipseDialog->contents(),xcor,ycor);
873
874}
875
876// void PspaApplication::scatterPlot1D(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor)
877// {
878//   int nbpts = xcor.size();
879//   cout << " PspaApplication::scatterPlot1D nbpts = " << nbpts << endl;
880//   WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
881//   for (int i = 0; i < nbpts; ++i) {
882//     model->setData(i, 0, xcor.at(i));
883//     model->setData(i, 1, ycor.at(i));
884//     //    cout << " PspaApplication::scatterPlot1D el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
885//   }
886
887//   WCartesianChart *chart = new WCartesianChart(toto);
888
889//   chart->initLayout();
890
891//   chart->setModel(model);        // set the model
892//   chart->setXSeriesColumn(0);    // set the column that holds the X data
893//   chart->setLegendEnabled(true); // enable the legend
894
895//   chart->setType(ScatterPlot);   // set type to ScatterPlot
896
897//   // Typically, for mathematical functions, you want the axes to cross
898//   // at the 0 mark:
899//    chart->axis(XAxis).setLocation(ZeroValue);
900//    chart->axis(YAxis).setLocation(ZeroValue);
901
902//   // Provide space for the X and Y axis and title.
903// //   chart->setPlotAreaPadding(80, Left);
904// //   chart->setPlotAreaPadding(40, Top | Bottom);
905//   // Add the curves
906//   WDataSeries s(1, CurveSeries, Y1Axis);
907//   chart->addSeries(s);
908
909//   // chart->setBackground (WBrush(WColor("blue")));
910//   chart->resize(300, 300); // WPaintedWidget must be given explicit size
911
912// #ifdef HAS_IMAGEMAGIC
913//  Wt::WRasterImage pngImage("png", 600, 600);
914//  Wt::WPainter p(&pngImage);
915
916//  chart->paint(p);
917//  std::string name;
918//  name = workingDir_ + "/chart-"+sessionId ()+".png";
919//  std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
920//  pngImage.write(f);
921
922//  new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
923
924//  /*
925//  Wt::WPdfImage pdfImage("30cm", "30cm");
926//  Wt::WPainter p1(&pdfImage);
927//  chart->paint(p1);
928//  std::ofstream f1("chart.pdf", std::ios::out | std::ios::binary);
929//  pdfImage.write(f1);
930//  */
931// #endif
932// }
933
934
935void PspaApplication::scatterPlot1D(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor)
936{
937  int nbpts = xcor.size();
938  cout << " PspaApplication::scatterPlot1D nbpts = " << nbpts << endl;
939  WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
940  for (int i = 0; i < nbpts; ++i) {
941    model->setData(i, 0, xcor.at(i));
942    model->setData(i, 1, ycor.at(i));
943    //    cout << " PspaApplication::scatterPlot1D el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
944  }
945
946WCartesianChart *chart = new WCartesianChart(toto);
947  chart->setTitle("titre");
948
949  //  chart->initLayout();
950
951  chart->setModel(model);        // set the model
952  chart->setXSeriesColumn(0);    // set the column that holds the X data
953  chart->setLegendEnabled(true); // enable the legend
954
955  chart->setType(ScatterPlot);   // set type to ScatterPlot
956
957  // Typically, for mathematical functions, you want the axes to cross
958  // at the 0 mark:
959   chart->axis(XAxis).setLocation(ZeroValue);
960   chart->axis(YAxis).setLocation(ZeroValue);
961
962  // Provide space for the X and Y axis and title.
963//   chart->setPlotAreaPadding(80, Left);
964//   chart->setPlotAreaPadding(40, Top | Bottom);
965  // Add the curves
966  WDataSeries s(1, LineSeries, Y1Axis);
967  chart->addSeries(s);
968
969  // chart->setBackground (WBrush(WColor("blue")));
970  chart->resize(500, 300); // WPaintedWidget must be given explicit size
971
972#ifdef HAS_IMAGEMAGIC
973 Wt::WRasterImage pngImage("png", 600, 600);
974 Wt::WPainter p(&pngImage);
975
976 chart->paint(p);
977 std::string name;
978 name = workingDir_ + "/chart-"+sessionId ()+".png";
979 std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
980 pngImage.write(f);
981
982 new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
983
984 /*
985 Wt::WPdfImage pdfImage("30cm", "30cm");
986 Wt::WPainter p1(&pdfImage);
987 chart->paint(p1);
988 std::ofstream f1("chart.pdf", std::ios::out | std::ios::binary);
989 pdfImage.write(f1);
990 */
991#endif
992}
993
994void PspaApplication::updateSelections()
995{
996  string premierText, dernierText;
997  if ( selectedSections_.size() > 0 )
998    {
999      premierText = dtmanage_->getLabelFromElementNumero(1);
1000      dernierText = dtmanage_->getLabelFromElementNumero( dtmanage_->beamLineSize() );
1001      (*selectedSections_.begin())->debut->setText(premierText);
1002      (*selectedSections_.begin())->fin->setText(dernierText);
1003    }
1004
1005  cout << "PspaApplication::updateSelections(): " << premierText << " à  " << dernierText << endl;
1006}
1007
1008string PspaApplication::getSelection()
1009{
1010  list<GWt_sectionToExecute*>::iterator itr = selectedSections_.begin();
1011  string str = (*itr)->fin->text().toUTF8();
1012  return str;
1013}
1014
1015WText* PspaApplication::createTitle(const WString& title) 
1016{
1017  WText *result = new WText(title);
1018  result->setInline(false);
1019  result->setStyleClass("title");
1020  result->setMinimumSize(30,30);
1021 
1022  return result;
1023}
1024
1025// void PspaApplication::addConsoleMessage(WString msg) {
1026//   WText *w = new WText(console_);
1027//   w->setTextFormat(PlainText);
1028//   w->setText(msg);
1029//   w->setInline(false);
1030 
1031//   /*
1032//    * Little javascript trick to make sure we scroll along with new content
1033//    */
1034//   WApplication *app = WApplication::instance();
1035//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
1036//                     + console_->jsRef() + ".scrollHeight;");
1037 
1038// }
1039
1040
1041bool PspaApplication::removeExtensionFromConfigName(string& config)
1042{
1043  //  string configName;
1044  string extension(".save");
1045  bool test = true;
1046    string::size_type nn = config.rfind('.');
1047    if ( nn == string::npos ) 
1048      {
1049        // pas de point
1050        test = false;
1051      }
1052    string fin = config.substr(nn);
1053    if ( fin != extension ) 
1054      {
1055        // l'extension n'est pas la bonne
1056        test = false;
1057      }
1058    if ( test )
1059      {
1060        string::size_type count = config.length() - extension.length();
1061        config = config.substr(0, count);
1062      }
1063    else
1064      {
1065          GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
1066          checkConfigNameDialog.exec();
1067      }
1068    return test;
1069}
1070
1071/////////////////////////
1072//   c'est un embryon d'histogramme
1073
1074void PspaApplication::dessinerHistogramme()
1075{
1076  // pour mon test : histo en energie
1077  toto_->clear();
1078
1079  GWt_dialog* pourVoir= new GWt_dialog("histogramme",toto_,false);
1080  pourVoir->setMinimumSize(400,400);
1081  pourVoir->setClosable(true);
1082  pourVoir->show();
1083
1084
1085  particleBeam* beam = dtmanage_->getDiagnosticBeam(1);
1086  vector<double> xcor;
1087  vector<int> hist;
1088  int cnts;
1089  beam->histogramme(xcor,hist,cnts);
1090
1091  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
1092
1093  //////////////////////////////////////////////////////////////////////////////////
1094
1095  WContainerWidget *w = toto_;
1096  int nbpts= xcor.size()+cnts+1;
1097  WStandardItemModel *model = new WStandardItemModel(nbpts,2,w);
1098  model->setHeaderData(1, WString("energie"));
1099
1100  int j= 0;
1101  if(hist[0] > 0) {
1102    model->setData(j,0,xcor[0]);
1103    model->setData(j,1,hist[0]);
1104    j++;
1105  } 
1106  model->setData(j,0,xcor[0]);
1107  model->setData(j,1,hist[0]);
1108  j++;
1109  for (int i = 1; i < nbpts; ++i) {
1110    if(hist[i] == 0) {
1111      if(hist[i-1] > 0) {
1112        model->setData(j,0,xcor[i]);
1113        model->setData(j,1,hist[i-1]);
1114        j++;
1115      }
1116      model->setData(j,0,xcor[i]);
1117      model->setData(j,1,hist[i]);
1118      j++;
1119    }
1120    if(hist[i] > 0) {
1121      model->setData(j,0,xcor[i]);
1122      model->setData(j,1,hist[i-1]);
1123      j++;
1124      model->setData(j,0,xcor[i]);
1125      model->setData(j,1,hist[i]);
1126      j++;
1127    } 
1128  }
1129 
1130  WCartesianChart *chart = new WCartesianChart(w);
1131  chart->setTitle("Histogramme");
1132  chart->setModel(model);        // set the model
1133  chart->setXSeriesColumn(0);    // set the column that holds the categories
1134  chart->setLegendEnabled(true); // enable the legend
1135
1136   // Provide space for the X and Y axis and title.
1137  chart->setPlotAreaPadding(200, Right);
1138  chart->setPlotAreaPadding(80, Left);
1139  chart->setPlotAreaPadding(40, Top | Bottom);
1140
1141  chart->setType(ScatterPlot);
1142 
1143  WAxis& axis = chart->axis(XAxis);
1144  axis.setLabelFormat("%.3f");
1145  axis.setGridLinesEnabled(true);
1146  chart->axis(Y1Axis).setGridLinesEnabled(true);
1147
1148  WDataSeries s(1, LineSeries);
1149  chart->addSeries(s);
1150 
1151
1152  chart->resize(800, 400);
1153
1154  chart->setMargin(10, Top | Bottom);
1155  chart->setMargin(WLength::Auto, Left | Right);
1156
1157  LegendLocation location = LegendOutside;
1158  Side side = Right;
1159  AlignmentFlag alignment = AlignMiddle;
1160  chart->setLegendLocation(location, side, alignment);
1161  chart->setLegendStyle(chart->legendFont(), WPen(black), WBrush(WColor(0xFF, 0xFA, 0xE5)));
1162 }
Note: See TracBrowser for help on using the repository browser.