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

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

Grosse modifications pour une meilleur gestion des drag & drop (a terminer)

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