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

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

Correction dans les comboBox

File size: 34.3 KB
Line 
1#include <stdio.h>
2#include <string.h>
3#include <vector>
4#include <ctime>
5
6#include "GWt_pspaApplication.h"
7#include "GWt_ligneFaisceau.h"
8#include "GWt_softwarePanel.h"
9#include "GWt_globalParameters.h"
10// #include "GWt_dialog.h"
11#include "GWt_draggableImage.h"
12#include "particleBeam.h"
13#include "bareParticle.h"
14#include "nomDeLogiciel.h"
15#include "mixedTools.h"
16#include "nomdElements.h"
17#include "environmentVariables.h"
18#include "GWt_console.h"
19#include "GWt_serverFileSelector.h"
20#include "trivaluedBool.h"
21
22#include <Wt/WGridLayout>
23#include <Wt/WVBoxLayout>
24#include <Wt/WHBoxLayout>
25#include <Wt/WImage>
26#include <Wt/WMenu>
27#include <Wt/WStackedWidget>
28#include <Wt/WBreak>
29#include <Wt/WDialog>
30#include <Wt/WStandardItemModel>
31#include <Wt/WFileUpload>
32#include <Wt/WPainter>
33#include <Wt/WPdfImage>
34#include <Wt/WRasterImage>
35#include <Wt/WScrollArea>
36#include <Wt/WLineEdit>
37#include <Wt/WRadioButton>
38
39using namespace Wt::Chart;
40
41/*
42 * The env argument contains information about the new session, and
43 * the initial request. It must be passed to the WApplication
44 * constructor so it is typically also an argument for your custom
45 * application constructor.
46 */
47
48PspaApplication::PspaApplication(const WEnvironment& env) : 
49  WApplication(env),
50  applicationDefaultTitle_("portail PSPA"),
51  beamLine_(NULL),
52  extensionFile_(0)
53{
54  workingDir_ = WApplication::docRoot()+ "/"+WORKINGAREA;
55  nameOfCase_ = "pspa"; // default
56   
57  setTitle(applicationDefaultTitle_);  // application title
58  if (!wApp->environment().javaScript()) {
59    new WText("<i>This examples requires that javascript support is enabled.</i>",root());
60  }
61   
62  // register the absractElementFactory
63  abstractElementFactory_ = new GWt_abstractElementFactory();
64  abstractElementFactory_->setRFGunEnable(true);
65  abstractElementFactory_->setDriftEnable(true);
66  abstractElementFactory_->setCellEnable(true);
67  abstractElementFactory_->setBendEnable(true);
68  abstractElementFactory_->setSolenoEnable(true);
69  abstractElementFactory_->setBeamEnable(true);
70  abstractElementFactory_->setFitEnable(true);
71  abstractElementFactory_->setSnapshotEnable(true);
72 
73  // include the styleSheet
74  WContainerWidget *widroot = root();
75  useStyleSheet("htdocs/pspa.css");
76  dtmanage_ = new dataManager(this);
77  //    dtmanage_->setWorkingDir(workingDir_);
78 
79  /*
80   * The main layout is a 4x3 grid layout.
81   */
82  WGridLayout *mainGridLayout = new WGridLayout();
83  //  layout->addWidget(createTitle("<a href='workingArea/parmin'> Menu (In future)</a>"), 0, 0, 1, 2);
84  //  layout->addWidget(createTitle("Menu (In future)"), 0, 0, 1, 2);
85 
86  WHBoxLayout *toolbarLayout = new WHBoxLayout();
87 
88  WPushButton* boutonSauve = new WPushButton();
89  WPushButton* boutonRestaure = new WPushButton();
90  WPushButton* boutonLoadNew = new WPushButton();
91  WPushButton* boutongraphicalAnalysis = new WPushButton();
92  WPushButton* boutonTrash = new WPushButton();
93 
94  boutonSauve->setStyleClass("saveButton");
95  boutonRestaure->setStyleClass("restoreButton");
96  boutonLoadNew->setStyleClass("loadNewButton");
97  boutongraphicalAnalysis->setStyleClass("histoButton");
98  boutonTrash->setStyleClass("trashButton");
99 
100  boutonSauve->setToolTip ("sauvegarder votre configuration");
101  boutonRestaure->setToolTip (" restaurer la configuration depuis le serveur");
102  boutonLoadNew->setToolTip ("charger une configuration");
103  boutongraphicalAnalysis->setToolTip ("analyse graphique");
104  boutonTrash->setToolTip ("tout effacer");
105 
106  boutonSauve->setMaximumSize(38,38);
107  boutonSauve->setMinimumSize(38,38);
108  boutonRestaure->setMaximumSize(38,38);
109  boutonRestaure->setMinimumSize(38,38);
110  boutonLoadNew->setMaximumSize(38,38);
111  boutonLoadNew->setMinimumSize(38,38);
112  boutongraphicalAnalysis->setMaximumSize(38,38);
113  boutongraphicalAnalysis->setMinimumSize(38,38);
114  boutonTrash->setMaximumSize(38,38);
115  boutonTrash->setMinimumSize(38,38);
116 
117  boutonSauve->clicked().connect(this, &PspaApplication::sauver);
118  boutonRestaure->clicked().connect(this, &PspaApplication::restaurer);
119  // Upload when the button is clicked.
120  // React to a succesfull upload.
121  boutonLoadNew->clicked().connect(this, &PspaApplication::openFileSelector);
122 
123  boutongraphicalAnalysis->clicked().connect(this, &PspaApplication::dialogOnGraphics);
124 
125  boutonTrash->clicked().connect(this, &PspaApplication::removeBeamLine);
126 
127  toolbarLayout->addWidget(boutonSauve , 0,Wt::AlignMiddle);
128  toolbarLayout->addWidget(boutonRestaure , 0,Wt::AlignMiddle);
129  toolbarLayout->addWidget(boutonLoadNew , 0,Wt::AlignMiddle);
130  toolbarLayout->addWidget(boutongraphicalAnalysis , 0,Wt::AlignMiddle);
131  toolbarLayout->addWidget(boutonTrash , 0,Wt::AlignMiddle);
132  toolbarLayout->addWidget(new WText("") , 1,Wt::AlignMiddle);
133 
134  WContainerWidget * toolbarLayoutContainer = new WContainerWidget();
135  toolbarLayoutContainer->setLayout(toolbarLayout);
136  toolbarLayoutContainer->decorationStyle().setBackgroundImage ("/htdocs/fond_toolbar.png");
137   
138  mainGridLayout->addWidget(toolbarLayoutContainer, 1, 0, 1, 3);
139  mainGridLayout->addWidget(createPalette(), 2, 0, 4, 1);
140
141 
142  WScrollArea* scroll = new  WScrollArea();
143  scroll->setWidget(createBeamLine());
144  scroll->setMinimumSize(300,150);
145
146  mainGridLayout->addWidget(scroll, 2, 1, 1, 2);
147 
148 
149  // console_ = new WContainerWidget();
150  // console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
151  // console_->setMaximumSize(600,200);
152  // layout->addWidget(console_, 3, 1);
153  // console_->setMinimumSize(300,100);
154  // console_->setOverflow(WContainerWidget::OverflowAuto);
155 
156 
157  //-----------
158  // A supprimer et a mettre en fenetre
159  globalParam_ = createGlobalParamWidget();
160  //  leDessin_ = new WContainerWidget();
161  //  leDessin_ = createDrawingWidget();
162  graphicsDialog_ = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
163  graphicsDialog_->setMinimumSize(400,400);
164  graphicsDialog_->setClosable(true);
165  graphicsDialog_->hide();
166 
167  executeWidget_ = new GWt_softwarePanel(dtmanage_,this);
168 
169  mainGridLayout->addWidget( globalParam_, 3, 1);
170  //  layout->addWidget( leDessin_, 3, 2);
171  mainGridLayout->addWidget( executeWidget_ , 4, 1);
172  //-----------
173 
174  console_ = new GWt_console();
175
176  // manage sizes
177  console_->setMinimumSize(300,100);
178  executeWidget_->setMinimumSize(400,100);
179
180  mainGridLayout->addWidget(console_, 3, 2,2,1);
181 
182 
183  /*
184   * Let row 2 and column 1 take the excess space.
185   */
186  mainGridLayout->setRowStretch(4, 1);
187  mainGridLayout->setColumnStretch(2, 1);
188 
189  widroot->setLayout(mainGridLayout);
190
191  // set auto scrollbar if needed
192  widroot->setOverflow(WContainerWidget::OverflowAuto);
193
194}
195
196WWidget* PspaApplication::createPalette()
197{
198  WContainerWidget* palette = new WContainerWidget();
199  vector <GWt_abstractElement*> elems = abstractElementFactory_->getAllElements();
200  for (unsigned a = 0; a < elems.size(); a++) {
201    elems[a]->createDragImage(palette);
202    new WBreak(palette);
203  }
204
205  return palette; 
206}
207
208void PspaApplication::createDragImage(const char *url,const char *smallurl,const char *mimeType,WContainerWidget *p,WString())
209{
210  GWt_draggableImage *result = new GWt_draggableImage(url,p);
211 
212  /*
213   * Set the image to be draggable, showing the other image (dragImage)
214   * to be used as the widget that is visually dragged.
215   */
216  result->setDraggable(mimeType,new WImage(smallurl,p),true);
217}
218
219Wt::WWidget* PspaApplication::createBeamLine()
220{
221  extensionFile_= 0;
222  if (!beamLine_) {
223    beamLine_ = new GWt_LigneFaisceau(this);
224  } else {
225    beamLine_->clear();
226  }
227  beamLine_->setMinimumSize(300,100);
228  setTitle(applicationDefaultTitle_);
229
230  return beamLine_;
231}
232
233WWidget* PspaApplication::createGlobalParamWidget()
234{
235    WContainerWidget* globalParam = new GWt_globalParameters(this);
236    return globalParam;
237}
238
239
240void PspaApplication::dialogOnGraphics()
241{
242  graphicsDialog_->show();
243}
244
245WContainerWidget* PspaApplication::createDrawingWidget()
246{
247  WGridLayout *glayout= new WGridLayout();
248  WContainerWidget* dessin = new WContainerWidget();
249  dessin->setLayout(glayout);
250
251  group_ = new Wt::WButtonGroup(this);
252 
253  /////////////////////////////////////////////////////////////////////
254       
255  choixEnveloppeDessin_ = new WComboBox();
256  choixEnveloppeDessin_->addItem("x");
257  // choixEnveloppeDessin_->addItem("y");
258  Wt::WRadioButton *button1= new WRadioButton(" enveloppe");
259  group_->addButton(button1,1);
260  glayout->addWidget(button1,0,1);
261  glayout->addWidget(choixEnveloppeDessin_,0,2);
262  /////////////////////////////////////////////////////////////////////
263
264  choixElementDessin_ = new WComboBox();
265  choixElementDessin_->setMinimumSize(50,10);
266  choixTypeDessinFaisceau_ = new WComboBox();
267  choixTypeDessinFaisceau_->addItem("courant_snyder");
268  choixTypeDessinFaisceau_->addItem("macroparticles");
269  Wt::WRadioButton *button2= new WRadioButton(" phase space after element");
270
271  choixAbsPhase_ = new WComboBox();
272  choixAbsPhase_->addItem("x");
273  choixAbsPhase_->addItem("y");
274  choixAbsPhase_->addItem("dz");
275  choixAbsPhase_->addItem("xp");
276  choixAbsPhase_->addItem("yp");
277  choixAbsPhase_->addItem("dE/E");
278  choixAbsPhase_->setCurrentIndex(0);
279 
280  choixOrdPhase_ = new WComboBox();
281  choixOrdPhase_->addItem("x");
282  choixOrdPhase_->addItem("y");
283  choixOrdPhase_->addItem("dz");
284  choixOrdPhase_->addItem("xp");
285  choixOrdPhase_->addItem("yp");
286  choixOrdPhase_->addItem("dE/E");
287  choixOrdPhase_->setCurrentIndex(3);
288 
289  group_->addButton(button2,2);
290  glayout->addWidget(button2,1,1);
291  glayout->addWidget(choixElementDessin_,1,2);
292  glayout->addWidget(choixTypeDessinFaisceau_,1,3);
293  //  glayout->addWidget(new WText("abs. :"),2,2);
294  glayout->addWidget(choixAbsPhase_,2,2);
295  //  glayout->addWidget(new WText("ord. :"),2,4);
296  glayout->addWidget(choixOrdPhase_,2,3);
297  /////////////////////////////////////////////////////////////////////
298
299  choixVariableHisto_= new WComboBox();
300  choixVariableHisto_->addItem("x");
301  choixVariableHisto_->addItem("y");
302  choixVariableHisto_->addItem("z");
303  choixVariableHisto_->addItem("xp");
304  choixVariableHisto_->addItem("yp");
305  choixVariableHisto_->addItem("dE/E");
306  choixVariableHisto_->setCurrentIndex(5);
307
308  choixHistoDessin_ = new WComboBox();
309  Wt::WRadioButton *button3= new WRadioButton(" histogram after element ");
310  group_->addButton(button3,3);
311
312  glayout->addWidget(button3,3,1);
313  glayout->addWidget(choixHistoDessin_,3,2);
314  glayout->addWidget(choixVariableHisto_,3,3);
315  /////////////////////////////////////////////////////////////////////
316 
317  WPushButton *close= new WPushButton("close"); 
318  glayout->addWidget(close,4,1);
319  close->clicked().connect(this,&PspaApplication::closeGraphicDialog);
320 
321  WPushButton *draw= new WPushButton("draw"); 
322  glayout->addWidget(draw,4,2,2,1);
323  draw->clicked().connect(this,&PspaApplication::dessiner);
324  /////////////////////////////////////////////////////////////////////
325
326  toto_ = new WContainerWidget();
327  dessin->addWidget(toto_);
328  return dessin;
329}
330
331void PspaApplication::closeGraphicDialog()
332{
333  cout << " close graphicsDialog_" << endl;
334  for(unsigned i = 0; i < eDialog_.size(); i++) eDialog_[i]->done(WDialog::Rejected);
335  eDialog_.clear();
336  graphicsDialog_->done(WDialog::Rejected);
337}
338
339void PspaApplication::dessiner()
340{
341  int k= group_->checkedId();
342  cout << "dessiner k= " << k << endl;
343
344  switch(k) {
345  case  1: 
346    dessinerEnveloppe();
347    break;
348  case 2:
349    dessinerPhaseSpace();
350    break;
351  case 3:
352    dessinerHistogramme();
353    break;
354  default:
355    GWt_dialog graphicalWarning("graphical analysis","select a button",GWt_dialog::Warning,false,true);
356    graphicalWarning.exec();
357    break;
358  }
359}
360
361
362void PspaApplication::sauver()
363{
364  cout << " on sauve " << endl;
365  console_->addConsoleMessage("sauvegarde");
366 
367  dialogSave_ = new WDialog("save");
368  new WText("name of case : ",dialogSave_->contents());
369  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
370  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
371  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
372  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
373  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
374  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone);
375  dialogSave_->show();
376}
377
378
379void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
380{
381    if ( code != Wt::WDialog::Accepted ) {
382        return;
383    }
384    nameOfCase_ = saveNameEdit_->text().toUTF8();
385    delete dialogSave_;
386    dialogSave_ = NULL;
387
388    GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
389    bibi->updateGlobals();
390    //  dtmanage_->saveConfiguration(nameOfCase_);
391    dtmanage_->saveConfiguration(sessionId(),nameOfCase_);
392}
393
394
395void PspaApplication::restaurer()
396{
397  GWt_serverFileSelector * fs = new GWt_serverFileSelector("Select a configuration file",workingDir_);
398  string fileName = fs->exec();
399  nameOfCase_ = fileName;
400  if (fileName == "") {
401    return;
402  }
403   
404  removePathFromConfigName(nameOfCase_ );
405  cout << " nom sans path " << nameOfCase_ << endl;
406  removeExtensionFromConfigName(nameOfCase_);
407  cout << " nom sans extension " << nameOfCase_ << endl;
408  if (nameOfCase_ == "")
409    return;
410  cout << " je restaure le fichier " << fileName << endl;
411  dialogSave_ = NULL;
412 
413  bool test = dtmanage_->restoreElements(fileName);
414  if ( !test ) {
415    GWt_dialog restoreWarning(" element restoring", "failure in restoring elements from file : " + fileName , GWt_dialog::Error, false,true);
416    restoreWarning.exec();
417  } else {
418    // Change the window title
419    unsigned long found = fileName.find_last_of("/");
420    setTitle(applicationDefaultTitle_+" : "+fileName.substr(found+1));
421  }
422 
423  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
424  bibi->renew();
425 
426  console_->addConsoleMessage(string("restauration terminee"));
427}
428
429void PspaApplication::openFileSelector()
430{
431   
432  WContainerWidget *result = new WContainerWidget();
433  WVBoxLayout* myLayout = new WVBoxLayout();
434   
435  uploadFileSelectorWidget_ = new WFileUpload();
436   
437  uploadFileSelectorWidget_->setFileTextSize(40);
438   
439  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
440  myLayout->addWidget(uploadFileSelectorWidget_);
441   
442  result->setLayout (myLayout);
443   
444  // Upload automatically when the user entered a file.
445  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
446 
447  // React to a succesfull upload.
448  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
449 
450  // React to a fileupload problem.
451  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
452 
453 
454  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
455 
456  fileSelectorDialog->exec();
457}
458
459void PspaApplication::chargerConfig()
460{
461  GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
462   
463  string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
464  cout << " fichier client : " << nomDuFichier << endl;
465  bool test = removeExtensionFromConfigName(nomDuFichier);
466  cout << " fichier client sans extension : " << nomDuFichier << endl;
467 
468  if ( test )
469    {
470      nameOfCase_ = nomDuFichier;
471      console_->addConsoleMessage(string("restauration..."));
472     
473      if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
474        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
475        restoreWarning.exec();
476      }
477     
478      GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
479      bibi->renew();
480     
481      console_->addConsoleMessage(string("rechargement de config termine"));
482      message->show();
483    }
484}
485
486void PspaApplication::fileTooLarge()
487{
488  std::stringstream stream;
489  stream << maximumRequestSize ();
490  std::string maxRequestSize(stream.str());
491 
492  std::string message = "This file is too large, please select a one\n";
493  message += "Maximum file size is "+ maxRequestSize;
494  message += " bytes\n";
495   
496  GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true);
497 
498  messageBox->show();
499}
500
501void PspaApplication::faireDessin()
502{
503  choixElementDessin_->clear();
504  choixHistoDessin_->clear();
505
506  int nombre = dtmanage_->getBeamLineSize(); 
507  for(int i = 1; i <= nombre; i++) {
508    abstractElement* elPtr = dtmanage_->getElementPointerFromNumero(i);
509    //    if(elPtr->getNomdElement().getElementType() == snapshot) continue;
510
511    choixElementDessin_->addItem(elPtr->getLabel());
512    choixHistoDessin_->addItem(elPtr->getLabel());
513  } 
514}
515
516void PspaApplication::dessinerPhaseSpace()
517{   
518   
519  int typeFaisceau = choixTypeDessinFaisceau_->currentIndex();
520  //  int index = choixElementDessin_->currentIndex();
521  string nameAbs = choixAbsPhase_->currentText().toUTF8();
522  string nameOrd = choixOrdPhase_->currentText().toUTF8();
523  if ( nameAbs == nameOrd ) {
524        GWt_dialog phaseSpaceError(" graphical analysis", "the beam coordinates must be different !", GWt_dialog::Error, false,true);
525        phaseSpaceError.exec();
526        return;
527  }
528  string elementLabel = choixElementDessin_->currentText().toUTF8();
529  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
530  //  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
531   
532  if ( beam == NULL ) {
533    GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
534    warningBeamState.exec();
535    return;
536  }
537   
538    toto_->clear();
539    faireDessinPhaseSpace(toto_, beam, nameAbs, nameOrd, typeFaisceau);
540
541  // if ( typeFaisceau == 0 )
542  //   {
543  //     if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
544  //     faireDessinTransport(toto_, beam, nameAbs, nameOrd );
545  //   }
546  // else if ( typeFaisceau == 1 )
547  //   {
548  //     if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam, nameAbs, nameOrd );
549  //     else {
550  //    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
551  //    warningBeamState.exec();
552  //     }
553  //   }
554  // else {
555  //   GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
556  //   warningTypeDrawing.exec();
557  // }
558}
559
560void PspaApplication::dessinerEnveloppe()
561{
562  toto_->clear();
563 
564  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
565  if ( typeEnveloppe == 0 )
566    {
567      faireDessinEnveloppe(toto_, "x");
568    }
569  else {
570    GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
571    warningTypeEnveloppe.exec();
572  }
573}
574
575void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
576{
577 
578  std::time_t result = std::time(NULL);
579 
580  GWt_dialog* envDialog = new GWt_dialog(WString("enveloppe&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto,false);
581  eDialog_.push_back(envDialog);
582  envDialog->setMinimumSize(400,400);
583  envDialog->setClosable(true);
584  envDialog->show();
585     
586  //  unsigned nbel = dtmanage_->getBeamLineSize();
587  vector<double> xcor;
588  vector<double> ycor;
589  string titre;
590  string legendx;
591  string legendy;
592  dtmanage_->donneesRmsEnveloppe(type,xcor,ycor,titre,legendx,legendy);
593
594  Wt::Chart::SeriesType seriesType = LineSeries;
595  Wt::Chart::FillRangeType fillRange = NoFill;
596  Wt::Chart::AxisValue location = ZeroValue;
597  bool isGridLinesEnabled = false; 
598  chartPlot2vec(envDialog->contents(),xcor,ycor,seriesType,fillRange,location,isGridLinesEnabled,titre,legendx,legendy,500,300);
599}
600
601void PspaApplication::faireDessinPhaseSpace(WContainerWidget* toto, particleBeam* beam, string namex, string namey, int typeFaisceau)
602{
603
604  vector<double> xcor;
605  vector<double> ycor;
606  vector<string> legende;
607  string titre;
608  Wt::Chart::SeriesType seriesType;
609 
610  if ( typeFaisceau == 0 ) {
611    seriesType = LineSeries;
612    titre = "phase space rms";
613    beam->donneesDessinEllipse(xcor,ycor,legende,namex,namey);
614  } else if (  typeFaisceau == 1 ) {
615    seriesType = PointSeries;
616    titre = " phase space ";
617    beam->particlesPhaseSpaceData(xcor,ycor,legende,namex,namey);
618  } else {
619    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
620    warningBeamState.exec();
621    return;
622  }
623 
624  std::time_t result = std::time(NULL);
625  GWt_dialog* phaseSpaceDialog = new GWt_dialog(WString("phase space&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto,false);
626  eDialog_.push_back(phaseSpaceDialog);
627  phaseSpaceDialog->setMinimumSize(400,400);
628  phaseSpaceDialog->setClosable(true);
629  new WText(nameOfCase_, phaseSpaceDialog->contents());
630
631  for (int k=0 ; k < legende.size(); k++) {
632    new WBreak(phaseSpaceDialog->contents());
633    new WText(legende.at(k), phaseSpaceDialog->contents());
634  }
635
636  Wt::Chart::FillRangeType fillRange = NoFill;
637  Wt::Chart::AxisValue location = ZeroValue;
638  bool isGridLinesEnabled = false; 
639  chartPlot2vec(phaseSpaceDialog->contents(),xcor,ycor,seriesType,fillRange,location,isGridLinesEnabled,titre,namex,namey,500,300);
640 
641  phaseSpaceDialog->show();
642}
643
644
645
646// void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam, string namex, string namey )
647// {
648//   cout << " faireDessinParmela " << endl;
649//   GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
650//   eDialog_.push_back(pointsDialog);
651//   pointsDialog->setMinimumSize(400,400);
652//   pointsDialog->setClosable(true);
653//   // pointsDialog->show();
654     
655//   new WText(nameOfCase_, pointsDialog->contents());
656
657
658//   vector<double> xcor;
659//   vector<double> ycor;
660//   vector<string> legende;
661//   beam->particlesPhaseSpaceData(xcor, ycor, legende, namex, namey);
662//   for (int k=0 ; k < legende.size(); k++) {
663//     new WBreak(pointsDialog->contents());
664//     new WText(legende.at(k), pointsDialog->contents());
665//   }
666//   string titre = " phase space ";
667//   chartPlot2vec(pointsDialog->contents(), xcor, ycor, true,titre,namex, namey,400,400);
668
669
670   
671//   pointsDialog->show();
672   
673//   //  chart->setMargin(10, Top | Bottom);            // add margin vertically
674//   //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
675// }
676
677// void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam, string namex, string namey)
678// {
679//   GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
680//   eDialog_.push_back(ellipseDialog);
681//   ellipseDialog->setMinimumSize(400,400);
682//   ellipseDialog->setClosable(true);
683//   ellipseDialog->show();
684//   new WText(nameOfCase_, ellipseDialog->contents());
685 
686//   vector<double> xcor;
687//   vector<double> ycor;
688//   vector<string> legende;
689//   beam->donneesDessinEllipse(xcor,ycor,legende, namex, namey);
690
691//   for (int k=0 ; k < legende.size(); k++) {
692//     new WBreak(ellipseDialog->contents());
693//     new WText(legende.at(k), ellipseDialog->contents());
694//   }
695//   string titre = "phase space rms";
696//   chartPlot2vec(ellipseDialog->contents(), xcor, ycor, false,titre, namex, namey,500,300);
697// }
698
699
700// parametre drawPoints : true = on trace des points (phase space) ; false = on trace des lignes (enveloppes...)
701void PspaApplication::chartPlot2vec(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor, bool drawPoints,string title,string legendx, string legendy,int width, int height, bool makeIcon)
702{
703    int nbpts = xcor.size();
704    cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
705    WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
706    for (int i = 0; i < nbpts; ++i) {
707        model->setData(i, 0, xcor.at(i));
708        model->setData(i, 1, ycor.at(i));
709        //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
710    }
711   
712    WCartesianChart *chart = new WCartesianChart(toto);
713    if (!makeIcon) {
714        chart->setTitle(title);
715    }
716    chart->initLayout();
717   
718    chart->setModel(model);        // set the model
719    chart->setXSeriesColumn(0);    // set the column that holds the X data
720    if (!makeIcon) {
721        chart->setLegendEnabled(true); // enable the legend
722    } else {
723        chart->setLegendEnabled(false); // enable the legend
724    }
725   
726    chart->setType(ScatterPlot);   // set type to ScatterPlot
727   
728    // Typically, for mathematical functions, you want the axes to cross
729    // at the 0 mark:
730    chart->axis(XAxis).setLocation(ZeroValue);
731    chart->axis(YAxis).setLocation(ZeroValue);
732
733    // Provide space for the X and Y axis and title.
734    chart->setPlotAreaPadding(80, Left);  // ?
735    chart->setPlotAreaPadding(40, Bottom);
736    chart->setPlotAreaPadding(60, Top);
737    if ( drawPoints ) {
738      WDataSeries s(1, PointSeries, Y1Axis);
739      chart->addSeries(s);   
740    } else {
741      WDataSeries s(1, LineSeries, Y1Axis);
742      chart->addSeries(s);   
743    }
744    chart->resize(width, height); // WPaintedWidget must be given explicit size
745   
746   
747    WAxis& axis = chart->axis(XAxis);
748    axis.setLabelFormat("%.3f");
749    //       axis.setGridLinesEnabled(true);
750    axis.setTitle(legendx);
751   
752    WAxis& axey = chart->axis(YAxis);
753    axey.setTitle(legendy);
754    // axis = chart->axis(YAxis);
755    // axis.setLabelFormat("%.3f");
756    // axis.setGridLinesEnabled(true);
757    // axis.setTitle(legendy);
758   
759    if (makeIcon) {
760      chart->setPlotAreaPadding(0);
761      chart->setAxisPadding(0);
762      WFont xAxisFont = chart->axis(XAxis).labelFont();
763      xAxisFont.setSize(8);
764      WFont yAxisFont = chart->axis(YAxis).labelFont();
765      yAxisFont.setSize(8);
766      chart->axis(XAxis).setLabelFont(xAxisFont);
767      chart->axis(YAxis).setLabelFont(yAxisFont);
768    }
769
770#ifdef HAS_IMAGEMAGIC
771    Wt::WRasterImage pngImage("png", 600, 600);
772    Wt::WPainter p(&pngImage);
773    chart->paint(p);
774    std::string name;
775    name = workingDir_ + "/chart-"+sessionId ()+".png";
776    std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
777    pngImage.write(f);   
778    new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
779   
780    Wt::WPdfImage pdfImage("30cm", "30cm");
781    Wt::WPainter p1(&pdfImage);
782    pdfImage.init();
783    chart->paint(p1);
784    name = workingDir_ + "/chart-"+sessionId ()+".pdf";
785    std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
786    pdfImage.write(f1);
787#endif
788}
789
790
791WText* PspaApplication::createTitle(const WString& title)
792{
793  WText *result = new WText(title);
794  result->setInline(false);
795  result->setStyleClass("title");
796  result->setMinimumSize(30,30);
797 
798  return result;
799}
800
801// void PspaApplication::addConsoleMessage(WString msg) {
802//   WText *w = new WText(console_);
803//   w->setTextFormat(PlainText);
804//   w->setText(msg);
805//   w->setInline(false);
806
807//   /*
808//    * Little javascript trick to make sure we scroll along with new content
809//    */
810//   WApplication *app = WApplication::instance();
811//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
812//                     + console_->jsRef() + ".scrollHeight;");
813
814// }
815
816bool PspaApplication::removePathFromConfigName(string& config) {
817  string toExtract = workingDir_ + "/";
818  string::size_type nn = config.find(toExtract);
819  if ( nn == string::npos ) {
820        GWt_dialog checkremovePath(" checking config file name", " failed to recognize path name for file  " + config, GWt_dialog::Error,true,true);
821        checkremovePath.exec();
822    return false;
823  }
824  config.replace(nn, toExtract.size(), "");
825  return true;
826}
827
828bool PspaApplication::removeExtensionFromConfigName(string& config)
829{
830    //  string configName;
831    string extension(".save");
832    bool test = true;
833    string::size_type nn = config.rfind('.');
834    if ( nn == string::npos )
835    {
836        // pas de point
837        test = false;
838    }
839    string fin = config.substr(nn);
840    if ( fin != extension )
841    {
842        // l'extension n'est pas la bonne
843        test = false;
844    }
845    if ( test )
846    {
847        string::size_type count = config.length() - extension.length();
848        config = config.substr(0, count);
849    }
850    else
851    {
852        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
853        checkConfigNameDialog.exec();
854    }
855    return test;
856}
857
858
859
860void PspaApplication::removeBeamLine() {
861  createBeamLine();
862  executeWidget_->updateSections();
863}
864
865void PspaApplication::chartPlot2vec(WContainerWidget* toto,vector<double>& xcor,vector<double>& ycor,SeriesType seriesType,FillRangeType fillRange,AxisValue value,bool isGridLinesEnables,string title,string legendx,string legendy,int width,int height,bool makeIcon)
866{
867  int nbpts = xcor.size();
868  cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
869
870  WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
871  for (int i = 0; i < nbpts; ++i) {
872    model->setData(i, 0, xcor.at(i));
873    model->setData(i, 1, ycor.at(i));
874    //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
875  }
876   
877  WCartesianChart *chart = new WCartesianChart(toto);
878  if (!makeIcon) chart->setTitle(title);
879
880  chart->initLayout(); 
881  chart->setModel(model);        // set the model
882  chart->setXSeriesColumn(0);    // set the column that holds the X data
883 
884  chart->setType(ScatterPlot);   // set type to ScatterPlot
885  chart->setLegendEnabled(false); // enable the legend 
886
887  // Provide space for the X and Y axis and title.
888  chart->setPlotAreaPadding(80, Left); 
889  chart->setPlotAreaPadding(40, Bottom);
890  chart->setPlotAreaPadding(60, Top);
891 
892  // Typically, for mathematical functions, you want the axes to cross
893  // at the 0 mark (value= ZeroValue)
894  chart->axis(XAxis).setLocation(value);
895  chart->axis(YAxis).setLocation(value);
896 
897  WDataSeries s(1,seriesType);
898  s.setFillRange(fillRange);
899  chart->addSeries(s);
900 
901  WAxis& axis = chart->axis(XAxis);
902  axis.setLabelFormat("%.3f");
903  axis.setTitle(legendx);
904   
905  chart->axis(Y1Axis).setTitle(legendy);
906
907  if(isGridLinesEnables) {
908    axis.setGridLinesEnabled(true);
909    chart->axis(Y1Axis).setGridLinesEnabled(true);
910  }
911 
912  chart->resize(width,height); // WPaintedWidget must be given explicit size
913  chart->setMargin(10, Top | Bottom); // ?
914  chart->setMargin(WLength::Auto, Left | Right); //?
915
916  if (makeIcon) {
917    chart->setLegendEnabled(false); // enable the legend
918    chart->setPlotAreaPadding(0);
919    chart->setAxisPadding(0);
920    WFont xAxisFont = chart->axis(XAxis).labelFont();
921    xAxisFont.setSize(8);
922    WFont yAxisFont = chart->axis(YAxis).labelFont();
923    yAxisFont.setSize(8);
924    chart->axis(XAxis).setLabelFont(xAxisFont);
925    chart->axis(YAxis).setLabelFont(yAxisFont);
926  }
927 
928#ifdef HAS_IMAGEMAGIC
929  Wt::WRasterImage pngImage("png", 600, 600);
930  Wt::WPainter p(&pngImage);
931  chart->paint(p);
932  std::string name;
933  name = workingDir_ + "/chart-"+sessionId ()+".png";
934  std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
935  pngImage.write(f);   
936  new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
937 
938  Wt::WPdfImage pdfImage("30cm", "30cm");
939  Wt::WPainter p1(&pdfImage);
940  pdfImage.init();
941  chart->paint(p1);
942  name = workingDir_ + "/chart-"+sessionId ()+".pdf";
943  std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
944  pdfImage.write(f1);
945#endif
946}
947
948void PspaApplication::dessinerHistogramme()
949{
950  toto_->clear();
951 
952  std::time_t result = std::time(NULL);
953  GWt_dialog* histoDialog = new GWt_dialog(WString("histogramme&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto_,false);
954  eDialog_.push_back(histoDialog);
955  histoDialog->setMinimumSize(400,400);
956  histoDialog->setClosable(true);
957
958  string elementLabel = choixHistoDessin_->currentText().toUTF8();   
959  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
960  if (beam == NULL) {
961    GWt_dialog warningBeamState("histogram","the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
962    warningBeamState.exec();
963    return;
964  }
965 
966  if (!beam->particleRepresentationOk()) {
967    GWt_dialog warningBeamState("histogram", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
968    warningBeamState.exec();
969    return;
970  }
971
972  histoDialog->show();
973  vector<double> xcor;
974  vector<int> hist;
975  double out[3]= {0.0};
976  unsigned iabs= choixVariableHisto_->currentIndex(); 
977  beam->histogramme(iabs,xcor,hist,out);
978
979  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
980  //////////////////////////////////////////////////////////////////////////////////
981 
982  int n = hist.size();
983  vector<double> x;
984  x.resize(2*n+2);
985  vector<double> y;
986  y.resize(2*n+2);
987
988  int j= 0;
989  x.at(j)= xcor[0];
990  y.at(j)= 0.0;
991  j++;
992  x.at(j)= xcor[0];
993  y.at(j)= hist[0];
994  j++;
995 
996  for (int i = 1; i < n; ++i) {
997    x.at(j)= xcor[i];
998    y.at(j)= hist[i-1];
999    j++;
1000    x.at(j)= xcor[i];
1001    y.at(j)= hist[i];
1002    j++;
1003  }
1004
1005  x.at(j)= xcor[n];
1006  y.at(j)= hist[n-1];
1007  j++;
1008  x.at(j)= xcor[n];
1009  y.at(j)= 0.0;
1010  //////////////////////////////////////////////////////////////////////////////////
1011
1012  WContainerWidget *w= histoDialog->contents();
1013
1014  // legendes
1015  string unites[2];
1016  if(iabs == 0 || iabs == 1 || iabs == 2) {
1017    unites[0]= unites[1]= " mm";
1018  }
1019  if(iabs == 3 || iabs == 4) {
1020    unites[0]= unites[1]= " mrad";
1021  }
1022  if(iabs == 5) {
1023    unites[0]= " MeV"; unites[1]= " KeV";
1024  }
1025
1026  new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
1027  new WBreak(w);
1028  new WText(" mean : "+ mixedTools::doubleToString(out[1])+unites[0],w);
1029  new WBreak(w);
1030  new WText(" sigma rms : "+ mixedTools::doubleToString(out[2])+unites[1],w);
1031  //////////////////////////////////////////////////////////////////////////////////
1032
1033  string titre;
1034  if(iabs == 0) titre="x-coordinate";
1035  if(iabs == 1) titre="y-coordinate";
1036  if(iabs == 2) titre="z-coordinate";
1037  if(iabs == 3) titre="xp-divergence";
1038  if(iabs == 4) titre="yp-devergence";
1039  if(iabs == 5) titre="kinetic energy";
1040
1041  string xname;
1042  if(iabs == 0) xname=" x (mm)";
1043  if(iabs == 1) xname=" y (mm)";
1044  if(iabs == 2) xname=" z (mm)";
1045  if(iabs == 3) xname=" xp (mrad)";
1046  if(iabs == 4) xname=" yp (mrad)";
1047  if(iabs == 5) xname=" dEcin/Ecin (%)";
1048
1049  string yname;
1050  Wt::Chart::SeriesType seriesType = LineSeries;
1051  Wt::Chart::FillRangeType fillRange = ZeroValueFill;
1052  Wt::Chart::AxisValue location = MinimumValue;
1053  bool isGridLinesEnabled = true; 
1054  chartPlot2vec(w,x,y,seriesType,fillRange,location,isGridLinesEnabled,titre,xname,yname,500,300);
1055}
Note: See TracBrowser for help on using the repository browser.