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

Last change on this file since 379 was 379, checked in by touze, 11 years ago

ajout d'une extension de fichier pour les cliches

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