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

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

Generation de fichiers PDF pour les graphiques en cours (ca marche)

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