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

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

Alignement des composants

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  globalParam->setMinimumSize(300,100);
237  return globalParam;
238}
239
240
241void PspaApplication::dialogOnGraphics()
242{
243  graphicsDialog_->show();
244}
245
246WContainerWidget* PspaApplication::createDrawingWidget()
247{
248  WGridLayout *glayout= new WGridLayout();
249  WContainerWidget* dessin = new WContainerWidget();
250  dessin->setLayout(glayout);
251
252  group_ = new Wt::WButtonGroup(this);
253 
254  /////////////////////////////////////////////////////////////////////
255       
256  choixEnveloppeDessin_ = new WComboBox();
257  choixEnveloppeDessin_->addItem("x");
258  // choixEnveloppeDessin_->addItem("y");
259  Wt::WRadioButton *button1= new WRadioButton(" enveloppe");
260  group_->addButton(button1,1);
261  glayout->addWidget(button1,0,1);
262  glayout->addWidget(choixEnveloppeDessin_,0,2);
263  /////////////////////////////////////////////////////////////////////
264
265  choixElementDessin_ = new WComboBox();
266  choixElementDessin_->setMinimumSize(50,10);
267  choixTypeDessinFaisceau_ = new WComboBox();
268  choixTypeDessinFaisceau_->addItem("courant_snyder");
269  choixTypeDessinFaisceau_->addItem("macroparticles");
270  Wt::WRadioButton *button2= new WRadioButton(" phase space after element");
271
272  choixAbsPhase_ = new WComboBox();
273  choixAbsPhase_->addItem("x");
274  choixAbsPhase_->addItem("y");
275  choixAbsPhase_->addItem("dz");
276  choixAbsPhase_->addItem("xp");
277  choixAbsPhase_->addItem("yp");
278  choixAbsPhase_->addItem("dE/E");
279  choixAbsPhase_->setCurrentIndex(0);
280 
281  choixOrdPhase_ = new WComboBox();
282  choixOrdPhase_->addItem("x");
283  choixOrdPhase_->addItem("y");
284  choixOrdPhase_->addItem("dz");
285  choixOrdPhase_->addItem("xp");
286  choixOrdPhase_->addItem("yp");
287  choixOrdPhase_->addItem("dE/E");
288  choixOrdPhase_->setCurrentIndex(3);
289 
290  group_->addButton(button2,2);
291  glayout->addWidget(button2,1,1);
292  glayout->addWidget(choixElementDessin_,1,2);
293  glayout->addWidget(choixTypeDessinFaisceau_,1,3);
294  //  glayout->addWidget(new WText("abs. :"),2,2);
295  glayout->addWidget(choixAbsPhase_,2,2);
296  //  glayout->addWidget(new WText("ord. :"),2,4);
297  glayout->addWidget(choixOrdPhase_,2,3);
298  /////////////////////////////////////////////////////////////////////
299
300  choixVariableHisto_= new WComboBox();
301  choixVariableHisto_->addItem("x");
302  choixVariableHisto_->addItem("y");
303  choixVariableHisto_->addItem("z");
304  choixVariableHisto_->addItem("xp");
305  choixVariableHisto_->addItem("yp");
306  choixVariableHisto_->addItem("dE/E");
307  choixVariableHisto_->setCurrentIndex(5);
308
309  choixHistoDessin_ = new WComboBox();
310  Wt::WRadioButton *button3= new WRadioButton(" histogram after element ");
311  group_->addButton(button3,3);
312
313  glayout->addWidget(button3,3,1);
314  glayout->addWidget(choixHistoDessin_,3,2);
315  glayout->addWidget(choixVariableHisto_,3,3);
316  /////////////////////////////////////////////////////////////////////
317 
318  WPushButton *close= new WPushButton("close"); 
319  glayout->addWidget(close,4,1);
320  close->clicked().connect(this,&PspaApplication::closeGraphicDialog);
321 
322  WPushButton *draw= new WPushButton("draw"); 
323  glayout->addWidget(draw,4,2,2,1);
324  draw->clicked().connect(this,&PspaApplication::dessiner);
325  /////////////////////////////////////////////////////////////////////
326
327  toto_ = new WContainerWidget();
328  dessin->addWidget(toto_);
329  return dessin;
330}
331
332void PspaApplication::closeGraphicDialog()
333{
334  cout << " close graphicsDialog_" << endl;
335  for(unsigned i = 0; i < eDialog_.size(); i++) eDialog_[i]->done(WDialog::Rejected);
336  eDialog_.clear();
337  graphicsDialog_->done(WDialog::Rejected);
338}
339
340void PspaApplication::dessiner()
341{
342  int k= group_->checkedId();
343  cout << "dessiner k= " << k << endl;
344
345  switch(k) {
346  case  1: 
347    dessinerEnveloppe();
348    break;
349  case 2:
350    dessinerPhaseSpace();
351    break;
352  case 3:
353    dessinerHistogramme();
354    break;
355  default:
356    GWt_dialog graphicalWarning("graphical analysis","select a button",GWt_dialog::Warning,false,true);
357    graphicalWarning.exec();
358    break;
359  }
360}
361
362
363void PspaApplication::sauver()
364{
365  cout << " on sauve " << endl;
366  console_->addConsoleMessage("sauvegarde");
367 
368  dialogSave_ = new WDialog("save");
369  new WText("name of case : ",dialogSave_->contents());
370  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
371  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
372  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
373  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
374  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
375  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone);
376  dialogSave_->show();
377}
378
379
380void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
381{
382    if ( code != Wt::WDialog::Accepted ) {
383        return;
384    }
385    nameOfCase_ = saveNameEdit_->text().toUTF8();
386    delete dialogSave_;
387    dialogSave_ = NULL;
388
389    GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
390    bibi->updateGlobals();
391    //  dtmanage_->saveConfiguration(nameOfCase_);
392    dtmanage_->saveConfiguration(sessionId(),nameOfCase_);
393}
394
395
396void PspaApplication::restaurer()
397{
398  GWt_serverFileSelector * fs = new GWt_serverFileSelector("Select a configuration file",workingDir_);
399  string fileName = fs->exec();
400  nameOfCase_ = fileName;
401  if (fileName == "") {
402    return;
403  }
404   
405  removePathFromConfigName(nameOfCase_ );
406  cout << " nom sans path " << nameOfCase_ << endl;
407  removeExtensionFromConfigName(nameOfCase_);
408  cout << " nom sans extension " << nameOfCase_ << endl;
409  if (nameOfCase_ == "")
410    return;
411  cout << " je restaure le fichier " << fileName << endl;
412  dialogSave_ = NULL;
413 
414  bool test = dtmanage_->restoreElements(fileName);
415  if ( !test ) {
416    GWt_dialog restoreWarning(" element restoring", "failure in restoring elements from file : " + fileName , GWt_dialog::Error, false,true);
417    restoreWarning.exec();
418  } else {
419    // Change the window title
420    unsigned long found = fileName.find_last_of("/");
421    setTitle(applicationDefaultTitle_+" : "+fileName.substr(found+1));
422  }
423 
424  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
425  bibi->renew();
426 
427  console_->addConsoleMessage(string("restauration terminee"));
428}
429
430void PspaApplication::openFileSelector()
431{
432   
433  WContainerWidget *result = new WContainerWidget();
434  WVBoxLayout* myLayout = new WVBoxLayout();
435   
436  uploadFileSelectorWidget_ = new WFileUpload();
437   
438  uploadFileSelectorWidget_->setFileTextSize(40);
439   
440  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
441  myLayout->addWidget(uploadFileSelectorWidget_);
442   
443  result->setLayout (myLayout);
444   
445  // Upload automatically when the user entered a file.
446  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
447 
448  // React to a succesfull upload.
449  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
450 
451  // React to a fileupload problem.
452  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
453 
454 
455  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
456 
457  fileSelectorDialog->exec();
458}
459
460void PspaApplication::chargerConfig()
461{
462  GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
463   
464  string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
465  cout << " fichier client : " << nomDuFichier << endl;
466  bool test = removeExtensionFromConfigName(nomDuFichier);
467  cout << " fichier client sans extension : " << nomDuFichier << endl;
468 
469  if ( test )
470    {
471      nameOfCase_ = nomDuFichier;
472      console_->addConsoleMessage(string("restauration..."));
473     
474      if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
475        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
476        restoreWarning.exec();
477      }
478     
479      GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
480      bibi->renew();
481     
482      console_->addConsoleMessage(string("rechargement de config termine"));
483      message->show();
484    }
485}
486
487void PspaApplication::fileTooLarge()
488{
489  std::stringstream stream;
490  stream << maximumRequestSize ();
491  std::string maxRequestSize(stream.str());
492 
493  std::string message = "This file is too large, please select a one\n";
494  message += "Maximum file size is "+ maxRequestSize;
495  message += " bytes\n";
496   
497  GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true);
498 
499  messageBox->show();
500}
501
502void PspaApplication::faireDessin()
503{
504  choixElementDessin_->clear();
505  choixHistoDessin_->clear();
506
507  int nombre = dtmanage_->getBeamLineSize(); 
508  for(int i = 1; i <= nombre; i++) {
509    abstractElement* elPtr = dtmanage_->getElementPointerFromNumero(i);
510    //    if(elPtr->getNomdElement().getElementType() == snapshot) continue;
511
512    choixElementDessin_->addItem(elPtr->getLabel());
513    choixHistoDessin_->addItem(elPtr->getLabel());
514  } 
515}
516
517void PspaApplication::dessinerPhaseSpace()
518{   
519   
520  int typeFaisceau = choixTypeDessinFaisceau_->currentIndex();
521  //  int index = choixElementDessin_->currentIndex();
522  string nameAbs = choixAbsPhase_->currentText().toUTF8();
523  string nameOrd = choixOrdPhase_->currentText().toUTF8();
524  if ( nameAbs == nameOrd ) {
525        GWt_dialog phaseSpaceError(" graphical analysis", "the beam coordinates must be different !", GWt_dialog::Error, false,true);
526        phaseSpaceError.exec();
527        return;
528  }
529  string elementLabel = choixElementDessin_->currentText().toUTF8();
530  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
531  //  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
532   
533  if ( beam == NULL ) {
534    GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
535    warningBeamState.exec();
536    return;
537  }
538   
539    toto_->clear();
540    faireDessinPhaseSpace(toto_, beam, nameAbs, nameOrd, typeFaisceau);
541
542  // if ( typeFaisceau == 0 )
543  //   {
544  //     if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
545  //     faireDessinTransport(toto_, beam, nameAbs, nameOrd );
546  //   }
547  // else if ( typeFaisceau == 1 )
548  //   {
549  //     if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam, nameAbs, nameOrd );
550  //     else {
551  //    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
552  //    warningBeamState.exec();
553  //     }
554  //   }
555  // else {
556  //   GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
557  //   warningTypeDrawing.exec();
558  // }
559}
560
561void PspaApplication::dessinerEnveloppe()
562{
563  toto_->clear();
564 
565  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
566  if ( typeEnveloppe == 0 )
567    {
568      faireDessinEnveloppe(toto_, "x");
569    }
570  else {
571    GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
572    warningTypeEnveloppe.exec();
573  }
574}
575
576void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
577{
578 
579  std::time_t result = std::time(NULL);
580 
581  GWt_dialog* envDialog = new GWt_dialog(WString("enveloppe&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto,false);
582  eDialog_.push_back(envDialog);
583  envDialog->setMinimumSize(400,400);
584  envDialog->setClosable(true);
585  envDialog->show();
586     
587  //  unsigned nbel = dtmanage_->getBeamLineSize();
588  vector<double> xcor;
589  vector<double> ycor;
590  string titre;
591  string legendx;
592  string legendy;
593  dtmanage_->donneesRmsEnveloppe(type,xcor,ycor,titre,legendx,legendy);
594
595  Wt::Chart::SeriesType seriesType = LineSeries;
596  Wt::Chart::FillRangeType fillRange = NoFill;
597  Wt::Chart::AxisValue location = ZeroValue;
598  bool isGridLinesEnabled = false; 
599  chartPlot2vec(envDialog->contents(),xcor,ycor,seriesType,fillRange,location,isGridLinesEnabled,titre,legendx,legendy,500,300);
600}
601
602void PspaApplication::faireDessinPhaseSpace(WContainerWidget* toto, particleBeam* beam, string namex, string namey, int typeFaisceau)
603{
604
605  vector<double> xcor;
606  vector<double> ycor;
607  vector<string> legende;
608  string titre;
609  Wt::Chart::SeriesType seriesType;
610 
611  if ( typeFaisceau == 0 ) {
612    seriesType = LineSeries;
613    titre = "phase space rms";
614    beam->donneesDessinEllipse(xcor,ycor,legende,namex,namey);
615  } else if (  typeFaisceau == 1 ) {
616    seriesType = PointSeries;
617    titre = " phase space ";
618    beam->particlesPhaseSpaceData(xcor,ycor,legende,namex,namey);
619  } else {
620    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
621    warningBeamState.exec();
622    return;
623  }
624 
625  std::time_t result = std::time(NULL);
626  GWt_dialog* phaseSpaceDialog = new GWt_dialog(WString("phase space&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto,false);
627  eDialog_.push_back(phaseSpaceDialog);
628  phaseSpaceDialog->setMinimumSize(400,400);
629  phaseSpaceDialog->setClosable(true);
630  new WText(nameOfCase_, phaseSpaceDialog->contents());
631
632  for (int k=0 ; k < legende.size(); k++) {
633    new WBreak(phaseSpaceDialog->contents());
634    new WText(legende.at(k), phaseSpaceDialog->contents());
635  }
636
637  Wt::Chart::FillRangeType fillRange = NoFill;
638  Wt::Chart::AxisValue location = ZeroValue;
639  bool isGridLinesEnabled = false; 
640  chartPlot2vec(phaseSpaceDialog->contents(),xcor,ycor,seriesType,fillRange,location,isGridLinesEnabled,titre,namex,namey,500,300);
641 
642  phaseSpaceDialog->show();
643}
644
645
646
647// void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam, string namex, string namey )
648// {
649//   cout << " faireDessinParmela " << endl;
650//   GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
651//   eDialog_.push_back(pointsDialog);
652//   pointsDialog->setMinimumSize(400,400);
653//   pointsDialog->setClosable(true);
654//   // pointsDialog->show();
655     
656//   new WText(nameOfCase_, pointsDialog->contents());
657
658
659//   vector<double> xcor;
660//   vector<double> ycor;
661//   vector<string> legende;
662//   beam->particlesPhaseSpaceData(xcor, ycor, legende, namex, namey);
663//   for (int k=0 ; k < legende.size(); k++) {
664//     new WBreak(pointsDialog->contents());
665//     new WText(legende.at(k), pointsDialog->contents());
666//   }
667//   string titre = " phase space ";
668//   chartPlot2vec(pointsDialog->contents(), xcor, ycor, true,titre,namex, namey,400,400);
669
670
671   
672//   pointsDialog->show();
673   
674//   //  chart->setMargin(10, Top | Bottom);            // add margin vertically
675//   //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
676// }
677
678// void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam, string namex, string namey)
679// {
680//   GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
681//   eDialog_.push_back(ellipseDialog);
682//   ellipseDialog->setMinimumSize(400,400);
683//   ellipseDialog->setClosable(true);
684//   ellipseDialog->show();
685//   new WText(nameOfCase_, ellipseDialog->contents());
686 
687//   vector<double> xcor;
688//   vector<double> ycor;
689//   vector<string> legende;
690//   beam->donneesDessinEllipse(xcor,ycor,legende, namex, namey);
691
692//   for (int k=0 ; k < legende.size(); k++) {
693//     new WBreak(ellipseDialog->contents());
694//     new WText(legende.at(k), ellipseDialog->contents());
695//   }
696//   string titre = "phase space rms";
697//   chartPlot2vec(ellipseDialog->contents(), xcor, ycor, false,titre, namex, namey,500,300);
698// }
699
700
701// parametre drawPoints : true = on trace des points (phase space) ; false = on trace des lignes (enveloppes...)
702void PspaApplication::chartPlot2vec(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor, bool drawPoints,string title,string legendx, string legendy,int width, int height, bool makeIcon)
703{
704    int nbpts = xcor.size();
705    cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
706    WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
707    for (int i = 0; i < nbpts; ++i) {
708        model->setData(i, 0, xcor.at(i));
709        model->setData(i, 1, ycor.at(i));
710        //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
711    }
712   
713    WCartesianChart *chart = new WCartesianChart(toto);
714    if (!makeIcon) {
715        chart->setTitle(title);
716    }
717    chart->initLayout();
718   
719    chart->setModel(model);        // set the model
720    chart->setXSeriesColumn(0);    // set the column that holds the X data
721    if (!makeIcon) {
722        chart->setLegendEnabled(true); // enable the legend
723    } else {
724        chart->setLegendEnabled(false); // enable the legend
725    }
726   
727    chart->setType(ScatterPlot);   // set type to ScatterPlot
728   
729    // Typically, for mathematical functions, you want the axes to cross
730    // at the 0 mark:
731    chart->axis(XAxis).setLocation(ZeroValue);
732    chart->axis(YAxis).setLocation(ZeroValue);
733
734    // Provide space for the X and Y axis and title.
735    chart->setPlotAreaPadding(80, Left);  // ?
736    chart->setPlotAreaPadding(40, Bottom);
737    chart->setPlotAreaPadding(60, Top);
738    if ( drawPoints ) {
739      WDataSeries s(1, PointSeries, Y1Axis);
740      chart->addSeries(s);   
741    } else {
742      WDataSeries s(1, LineSeries, Y1Axis);
743      chart->addSeries(s);   
744    }
745    chart->resize(width, height); // WPaintedWidget must be given explicit size
746   
747   
748    WAxis& axis = chart->axis(XAxis);
749    axis.setLabelFormat("%.3f");
750    //       axis.setGridLinesEnabled(true);
751    axis.setTitle(legendx);
752   
753    WAxis& axey = chart->axis(YAxis);
754    axey.setTitle(legendy);
755    // axis = chart->axis(YAxis);
756    // axis.setLabelFormat("%.3f");
757    // axis.setGridLinesEnabled(true);
758    // axis.setTitle(legendy);
759   
760    if (makeIcon) {
761      chart->setPlotAreaPadding(0);
762      chart->setAxisPadding(0);
763      WFont xAxisFont = chart->axis(XAxis).labelFont();
764      xAxisFont.setSize(8);
765      WFont yAxisFont = chart->axis(YAxis).labelFont();
766      yAxisFont.setSize(8);
767      chart->axis(XAxis).setLabelFont(xAxisFont);
768      chart->axis(YAxis).setLabelFont(yAxisFont);
769    }
770
771#ifdef HAS_IMAGEMAGIC
772    Wt::WRasterImage pngImage("png", 600, 600);
773    Wt::WPainter p(&pngImage);
774    chart->paint(p);
775    std::string name;
776    name = workingDir_ + "/chart-"+sessionId ()+".png";
777    std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
778    pngImage.write(f);   
779    new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
780   
781    Wt::WPdfImage pdfImage("30cm", "30cm");
782    Wt::WPainter p1(&pdfImage);
783    pdfImage.init();
784    chart->paint(p1);
785    name = workingDir_ + "/chart-"+sessionId ()+".pdf";
786    std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
787    pdfImage.write(f1);
788#endif
789}
790
791
792WText* PspaApplication::createTitle(const WString& title)
793{
794  WText *result = new WText(title);
795  result->setInline(false);
796  result->setStyleClass("title");
797  result->setMinimumSize(30,30);
798 
799  return result;
800}
801
802// void PspaApplication::addConsoleMessage(WString msg) {
803//   WText *w = new WText(console_);
804//   w->setTextFormat(PlainText);
805//   w->setText(msg);
806//   w->setInline(false);
807
808//   /*
809//    * Little javascript trick to make sure we scroll along with new content
810//    */
811//   WApplication *app = WApplication::instance();
812//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
813//                     + console_->jsRef() + ".scrollHeight;");
814
815// }
816
817bool PspaApplication::removePathFromConfigName(string& config) {
818  string toExtract = workingDir_ + "/";
819  string::size_type nn = config.find(toExtract);
820  if ( nn == string::npos ) {
821        GWt_dialog checkremovePath(" checking config file name", " failed to recognize path name for file  " + config, GWt_dialog::Error,true,true);
822        checkremovePath.exec();
823    return false;
824  }
825  config.replace(nn, toExtract.size(), "");
826  return true;
827}
828
829bool PspaApplication::removeExtensionFromConfigName(string& config)
830{
831    //  string configName;
832    string extension(".save");
833    bool test = true;
834    string::size_type nn = config.rfind('.');
835    if ( nn == string::npos )
836    {
837        // pas de point
838        test = false;
839    }
840    string fin = config.substr(nn);
841    if ( fin != extension )
842    {
843        // l'extension n'est pas la bonne
844        test = false;
845    }
846    if ( test )
847    {
848        string::size_type count = config.length() - extension.length();
849        config = config.substr(0, count);
850    }
851    else
852    {
853        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
854        checkConfigNameDialog.exec();
855    }
856    return test;
857}
858
859
860
861void PspaApplication::removeBeamLine() {
862  createBeamLine();
863  executeWidget_->updateSections();
864}
865
866void 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)
867{
868  int nbpts = xcor.size();
869  cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
870
871  WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
872  for (int i = 0; i < nbpts; ++i) {
873    model->setData(i, 0, xcor.at(i));
874    model->setData(i, 1, ycor.at(i));
875    //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
876  }
877   
878  WCartesianChart *chart = new WCartesianChart(toto);
879  if (!makeIcon) chart->setTitle(title);
880
881  chart->initLayout(); 
882  chart->setModel(model);        // set the model
883  chart->setXSeriesColumn(0);    // set the column that holds the X data
884 
885  chart->setType(ScatterPlot);   // set type to ScatterPlot
886  chart->setLegendEnabled(false); // enable the legend 
887
888  // Provide space for the X and Y axis and title.
889  chart->setPlotAreaPadding(80, Left); 
890  chart->setPlotAreaPadding(40, Bottom);
891  chart->setPlotAreaPadding(60, Top);
892 
893  // Typically, for mathematical functions, you want the axes to cross
894  // at the 0 mark (value= ZeroValue)
895  chart->axis(XAxis).setLocation(value);
896  chart->axis(YAxis).setLocation(value);
897 
898  WDataSeries s(1,seriesType);
899  s.setFillRange(fillRange);
900  chart->addSeries(s);
901 
902  WAxis& axis = chart->axis(XAxis);
903  axis.setLabelFormat("%.3f");
904  axis.setTitle(legendx);
905   
906  chart->axis(Y1Axis).setTitle(legendy);
907
908  if(isGridLinesEnables) {
909    axis.setGridLinesEnabled(true);
910    chart->axis(Y1Axis).setGridLinesEnabled(true);
911  }
912 
913  chart->resize(width,height); // WPaintedWidget must be given explicit size
914  chart->setMargin(10, Top | Bottom); // ?
915  chart->setMargin(WLength::Auto, Left | Right); //?
916
917  if (makeIcon) {
918    chart->setLegendEnabled(false); // enable the legend
919    chart->setPlotAreaPadding(0);
920    chart->setAxisPadding(0);
921    WFont xAxisFont = chart->axis(XAxis).labelFont();
922    xAxisFont.setSize(8);
923    WFont yAxisFont = chart->axis(YAxis).labelFont();
924    yAxisFont.setSize(8);
925    chart->axis(XAxis).setLabelFont(xAxisFont);
926    chart->axis(YAxis).setLabelFont(yAxisFont);
927  }
928 
929#ifdef HAS_IMAGEMAGIC
930  Wt::WRasterImage pngImage("png", 600, 600);
931  Wt::WPainter p(&pngImage);
932  chart->paint(p);
933  std::string name;
934  name = workingDir_ + "/chart-"+sessionId ()+".png";
935  std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
936  pngImage.write(f);   
937  new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
938 
939  Wt::WPdfImage pdfImage("30cm", "30cm");
940  Wt::WPainter p1(&pdfImage);
941  pdfImage.init();
942  chart->paint(p1);
943  name = workingDir_ + "/chart-"+sessionId ()+".pdf";
944  std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
945  pdfImage.write(f1);
946#endif
947}
948
949void PspaApplication::dessinerHistogramme()
950{
951  toto_->clear();
952 
953  std::time_t result = std::time(NULL);
954  GWt_dialog* histoDialog = new GWt_dialog(WString("histogramme&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto_,false);
955  eDialog_.push_back(histoDialog);
956  histoDialog->setMinimumSize(400,400);
957  histoDialog->setClosable(true);
958
959  string elementLabel = choixHistoDessin_->currentText().toUTF8();   
960  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
961  if (beam == NULL) {
962    GWt_dialog warningBeamState("histogram","the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
963    warningBeamState.exec();
964    return;
965  }
966 
967  if (!beam->particleRepresentationOk()) {
968    GWt_dialog warningBeamState("histogram", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
969    warningBeamState.exec();
970    return;
971  }
972
973  histoDialog->show();
974  vector<double> xcor;
975  vector<int> hist;
976  double out[3]= {0.0};
977  unsigned iabs= choixVariableHisto_->currentIndex(); 
978  beam->histogramme(iabs,xcor,hist,out);
979
980  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
981  //////////////////////////////////////////////////////////////////////////////////
982 
983  int n = hist.size();
984  vector<double> x;
985  x.resize(2*n+2);
986  vector<double> y;
987  y.resize(2*n+2);
988
989  int j= 0;
990  x.at(j)= xcor[0];
991  y.at(j)= 0.0;
992  j++;
993  x.at(j)= xcor[0];
994  y.at(j)= hist[0];
995  j++;
996 
997  for (int i = 1; i < n; ++i) {
998    x.at(j)= xcor[i];
999    y.at(j)= hist[i-1];
1000    j++;
1001    x.at(j)= xcor[i];
1002    y.at(j)= hist[i];
1003    j++;
1004  }
1005
1006  x.at(j)= xcor[n];
1007  y.at(j)= hist[n-1];
1008  j++;
1009  x.at(j)= xcor[n];
1010  y.at(j)= 0.0;
1011  //////////////////////////////////////////////////////////////////////////////////
1012
1013  WContainerWidget *w= histoDialog->contents();
1014
1015  // legendes
1016  string unites[2];
1017  if(iabs == 0 || iabs == 1 || iabs == 2) {
1018    unites[0]= unites[1]= " mm";
1019  }
1020  if(iabs == 3 || iabs == 4) {
1021    unites[0]= unites[1]= " mrad";
1022  }
1023  if(iabs == 5) {
1024    unites[0]= " MeV"; unites[1]= " KeV";
1025  }
1026
1027  new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
1028  new WBreak(w);
1029  new WText(" mean : "+ mixedTools::doubleToString(out[1])+unites[0],w);
1030  new WBreak(w);
1031  new WText(" sigma rms : "+ mixedTools::doubleToString(out[2])+unites[1],w);
1032  //////////////////////////////////////////////////////////////////////////////////
1033
1034  string titre;
1035  if(iabs == 0) titre="x-coordinate";
1036  if(iabs == 1) titre="y-coordinate";
1037  if(iabs == 2) titre="z-coordinate";
1038  if(iabs == 3) titre="xp-divergence";
1039  if(iabs == 4) titre="yp-devergence";
1040  if(iabs == 5) titre="kinetic energy";
1041
1042  string xname;
1043  if(iabs == 0) xname=" x (mm)";
1044  if(iabs == 1) xname=" y (mm)";
1045  if(iabs == 2) xname=" z (mm)";
1046  if(iabs == 3) xname=" xp (mrad)";
1047  if(iabs == 4) xname=" yp (mrad)";
1048  if(iabs == 5) xname=" dEcin/Ecin (%)";
1049
1050  string yname;
1051  Wt::Chart::SeriesType seriesType = LineSeries;
1052  Wt::Chart::FillRangeType fillRange = ZeroValueFill;
1053  Wt::Chart::AxisValue location = MinimumValue;
1054  bool isGridLinesEnabled = true; 
1055  chartPlot2vec(w,x,y,seriesType,fillRange,location,isGridLinesEnabled,titre,xname,yname,500,300);
1056}
Note: See TracBrowser for help on using the repository browser.