source: PSPA/Interface_Web/trunk/pspaWT/sources/userInterface/src/GWt_pspaApplication.cc @ 271

Last change on this file since 271 was 271, checked in by lemeur, 11 years ago

etiquettes par defaut

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