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

Last change on this file since 386 was 386, checked in by lemeur, 11 years ago

amélioration fiabilité graphique

File size: 31.6 KB
Line 
1#include <stdio.h>
2#include <string.h>
3#include <vector>
4
5#include "GWt_pspaApplication.h"
6#include "GWt_ligneFaisceau.h"
7#include "GWt_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  string nameAbs = choixAbsPhase_->currentText().toUTF8();
515  string nameOrd = choixOrdPhase_->currentText().toUTF8();
516  if ( nameAbs == nameOrd ) {
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 elementLabel = choixElementDessin_->currentText().toUTF8();
522  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
523  //  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
524   
525  if ( beam == NULL ) {
526    GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
527    warningBeamState.exec();
528    return;
529  }
530   
531    toto_->clear();
532    faireDessinPhaseSpace(toto_, beam, nameAbs, nameOrd, typeFaisceau);
533
534  // if ( typeFaisceau == 0 )
535  //   {
536  //     if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
537  //     faireDessinTransport(toto_, beam, nameAbs, nameOrd );
538  //   }
539  // else if ( typeFaisceau == 1 )
540  //   {
541  //     if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam, nameAbs, nameOrd );
542  //     else {
543  //    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
544  //    warningBeamState.exec();
545  //     }
546  //   }
547  // else {
548  //   GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
549  //   warningTypeDrawing.exec();
550  // }
551}
552
553void PspaApplication::dessinerEnveloppe()
554{
555  toto_->clear();
556 
557  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
558  if ( typeEnveloppe == 0 )
559    {
560      faireDessinEnveloppe(toto_, "x");
561    }
562  else {
563    GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
564    warningTypeEnveloppe.exec();
565  }
566}
567
568void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
569{
570   
571  GWt_dialog* envDialog = new GWt_dialog("enveloppe",toto,false);
572  eDialog_.push_back(envDialog);
573  envDialog->setMinimumSize(400,400);
574  envDialog->setClosable(true);
575  envDialog->show();
576     
577  //  unsigned nbel = dtmanage_->getBeamLineSize();
578  vector<double> xcor;
579  vector<double> ycor;
580    string titre;
581    string legendx;
582    string legendy;
583    dtmanage_->donneesRmsEnveloppe(type,xcor,ycor, titre, legendx, legendy);
584    chartPlot2vec(envDialog->contents(), xcor, ycor, false,titre, legendx, legendy,500,300);
585
586}
587
588void PspaApplication::faireDessinPhaseSpace(WContainerWidget* toto, particleBeam* beam, string namex, string namey, int typeFaisceau)
589{
590
591  vector<double> xcor;
592  vector<double> ycor;
593  vector<string> legende;
594  string titre;
595  bool pointsDrawing;
596  if ( typeFaisceau == 0 ) {
597    pointsDrawing = false;
598    titre = "phase space rms";
599    beam->donneesDessinEllipse(xcor,ycor,legende, namex, namey);
600  } else if (  typeFaisceau == 1 ) {
601    pointsDrawing = true;
602    titre = " phase space ";
603    beam->particlesPhaseSpaceData(xcor, ycor, legende, namex, namey);
604  } else {
605        GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
606        warningBeamState.exec();
607        return;
608  }
609
610
611  GWt_dialog* phaseSpaceDialog = new GWt_dialog("phase space",toto,false);
612  eDialog_.push_back(phaseSpaceDialog);
613  phaseSpaceDialog->setMinimumSize(400,400);
614  phaseSpaceDialog->setClosable(true);
615  new WText(nameOfCase_, phaseSpaceDialog->contents());
616 
617
618  for (int k=0 ; k < legende.size(); k++) {
619    new WBreak(phaseSpaceDialog->contents());
620    new WText(legende.at(k), phaseSpaceDialog->contents());
621  }
622  chartPlot2vec(phaseSpaceDialog->contents(), xcor, ycor,pointsDrawing ,titre, namex, namey,500,300);
623  phaseSpaceDialog->show();
624
625}
626
627
628
629// void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam, string namex, string namey )
630// {
631//   cout << " faireDessinParmela " << endl;
632//   GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
633//   eDialog_.push_back(pointsDialog);
634//   pointsDialog->setMinimumSize(400,400);
635//   pointsDialog->setClosable(true);
636//   // pointsDialog->show();
637     
638//   new WText(nameOfCase_, pointsDialog->contents());
639
640
641//   vector<double> xcor;
642//   vector<double> ycor;
643//   vector<string> legende;
644//   beam->particlesPhaseSpaceData(xcor, ycor, legende, namex, namey);
645//   for (int k=0 ; k < legende.size(); k++) {
646//     new WBreak(pointsDialog->contents());
647//     new WText(legende.at(k), pointsDialog->contents());
648//   }
649//   string titre = " phase space ";
650//   chartPlot2vec(pointsDialog->contents(), xcor, ycor, true,titre,namex, namey,400,400);
651
652
653   
654//   pointsDialog->show();
655   
656//   //  chart->setMargin(10, Top | Bottom);            // add margin vertically
657//   //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
658// }
659
660// void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam, string namex, string namey)
661// {
662//   GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
663//   eDialog_.push_back(ellipseDialog);
664//   ellipseDialog->setMinimumSize(400,400);
665//   ellipseDialog->setClosable(true);
666//   ellipseDialog->show();
667//   new WText(nameOfCase_, ellipseDialog->contents());
668 
669//   vector<double> xcor;
670//   vector<double> ycor;
671//   vector<string> legende;
672//   beam->donneesDessinEllipse(xcor,ycor,legende, namex, namey);
673
674//   for (int k=0 ; k < legende.size(); k++) {
675//     new WBreak(ellipseDialog->contents());
676//     new WText(legende.at(k), ellipseDialog->contents());
677//   }
678//   string titre = "phase space rms";
679//   chartPlot2vec(ellipseDialog->contents(), xcor, ycor, false,titre, namex, namey,500,300);
680// }
681
682
683// parametre drawPoints : true = on trace des points (phase space) ; false = on trace des lignes (enveloppes...)
684void PspaApplication::chartPlot2vec(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor, bool drawPoints,string title,string legendx, string legendy,int width, int height, bool makeIcon)
685{
686    int nbpts = xcor.size();
687    cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
688    WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
689    for (int i = 0; i < nbpts; ++i) {
690        model->setData(i, 0, xcor.at(i));
691        model->setData(i, 1, ycor.at(i));
692        //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
693    }
694   
695    WCartesianChart *chart = new WCartesianChart(toto);
696    if (!makeIcon) {
697        chart->setTitle(title);
698    }
699    chart->initLayout();
700   
701    chart->setModel(model);        // set the model
702    chart->setXSeriesColumn(0);    // set the column that holds the X data
703    if (!makeIcon) {
704        chart->setLegendEnabled(true); // enable the legend
705    } else {
706        chart->setLegendEnabled(false); // enable the legend
707    }
708   
709    chart->setType(ScatterPlot);   // set type to ScatterPlot
710   
711    // Typically, for mathematical functions, you want the axes to cross
712    // at the 0 mark:
713    chart->axis(XAxis).setLocation(ZeroValue);
714    chart->axis(YAxis).setLocation(ZeroValue);
715
716    // Provide space for the X and Y axis and title.
717      chart->setPlotAreaPadding(80, Left);  // ?
718      chart->setPlotAreaPadding(40, Bottom);
719      chart->setPlotAreaPadding(60, Top);
720      if ( drawPoints ) {
721       WDataSeries s(1, PointSeries, Y1Axis);
722       chart->addSeries(s);   
723      } else {
724       WDataSeries s(1, LineSeries, Y1Axis);
725       chart->addSeries(s);   
726      }
727       chart->resize(width, height); // WPaintedWidget must be given explicit size
728
729
730       WAxis& axis = chart->axis(XAxis);
731       axis.setLabelFormat("%.3f");
732       //       axis.setGridLinesEnabled(true);
733       axis.setTitle(legendx);
734
735       WAxis& axey = chart->axis(YAxis);
736       axey.setTitle(legendy);
737       // axis = chart->axis(YAxis);
738       // axis.setLabelFormat("%.3f");
739       // axis.setGridLinesEnabled(true);
740       // axis.setTitle(legendy);
741
742    if (makeIcon) {
743        chart->setPlotAreaPadding(0);
744        chart->setAxisPadding(0);
745        WFont xAxisFont = chart->axis(XAxis).labelFont();
746        xAxisFont.setSize(8);
747        WFont yAxisFont = chart->axis(YAxis).labelFont();
748        yAxisFont.setSize(8);
749        chart->axis(XAxis).setLabelFont(xAxisFont);
750        chart->axis(YAxis).setLabelFont(yAxisFont);
751    }
752
753#ifdef HAS_IMAGEMAGIC
754    Wt::WRasterImage pngImage("png", 600, 600);
755    Wt::WPainter p(&pngImage);
756    chart->paint(p);
757    std::string name;
758    name = workingDir_ + "/chart-"+sessionId ()+".png";
759    std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
760    pngImage.write(f);   
761    new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
762   
763     Wt::WPdfImage pdfImage("30cm", "30cm");
764     Wt::WPainter p1(&pdfImage);
765    pdfImage.init();
766    chart->paint(p1);
767     name = workingDir_ + "/chart-"+sessionId ()+".pdf";
768     std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
769     pdfImage.write(f1);
770#endif
771}
772
773
774WText* PspaApplication::createTitle(const WString& title)
775{
776  WText *result = new WText(title);
777  result->setInline(false);
778  result->setStyleClass("title");
779  result->setMinimumSize(30,30);
780 
781  return result;
782}
783
784// void PspaApplication::addConsoleMessage(WString msg) {
785//   WText *w = new WText(console_);
786//   w->setTextFormat(PlainText);
787//   w->setText(msg);
788//   w->setInline(false);
789
790//   /*
791//    * Little javascript trick to make sure we scroll along with new content
792//    */
793//   WApplication *app = WApplication::instance();
794//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
795//                     + console_->jsRef() + ".scrollHeight;");
796
797// }
798
799bool PspaApplication::removePathFromConfigName(string& config) {
800  string toExtract = workingDir_ + "/";
801  string::size_type nn = config.find(toExtract);
802  if ( nn == string::npos ) {
803        GWt_dialog checkremovePath(" checking config file name", " failed to recognize path name for file  " + config, GWt_dialog::Error,true,true);
804        checkremovePath.exec();
805    return false;
806  }
807  config.replace(nn, toExtract.size(), "");
808  return true;
809}
810
811bool PspaApplication::removeExtensionFromConfigName(string& config)
812{
813    //  string configName;
814    string extension(".save");
815    bool test = true;
816    string::size_type nn = config.rfind('.');
817    if ( nn == string::npos )
818    {
819        // pas de point
820        test = false;
821    }
822    string fin = config.substr(nn);
823    if ( fin != extension )
824    {
825        // l'extension n'est pas la bonne
826        test = false;
827    }
828    if ( test )
829    {
830        string::size_type count = config.length() - extension.length();
831        config = config.substr(0, count);
832    }
833    else
834    {
835        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
836        checkConfigNameDialog.exec();
837    }
838    return test;
839}
840
841void PspaApplication::dessinerHistogramme()
842{
843  // pour mon test : histo en energie
844  toto_->clear();
845 
846  GWt_dialog* histoDialog = new GWt_dialog("histogramme",toto_,false);
847  eDialog_.push_back(histoDialog);
848  histoDialog->setMinimumSize(400,400);
849  histoDialog->setClosable(true);
850 
851  // int index = choixHistoDessin_->currentIndex();   
852  // particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
853   string elementLabel = choixHistoDessin_->currentText().toUTF8();   
854   particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
855  if (beam == NULL) {
856    GWt_dialog warningBeamState("histogram","the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
857    warningBeamState.exec();
858    return;
859  }
860 
861  if (!beam->particleRepresentationOk()) {
862    GWt_dialog warningBeamState("histogram", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
863    warningBeamState.exec();
864    return;
865  }
866
867  histoDialog->show();
868  vector<double> xcor;
869  vector<int> hist;
870  double out[3]= {0.0};
871
872  unsigned iabs= choixVariableHisto_->currentIndex(); 
873  beam->histogramme(iabs,xcor,hist,out);
874
875  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
876  //////////////////////////////////////////////////////////////////////////////////
877
878  WContainerWidget *w= histoDialog->contents();
879  int n = hist.size();
880  int nbpts= 2*(n+1);
881  WStandardItemModel *model = new WStandardItemModel(nbpts,2,w);
882
883  int j= 0;
884  model->setData(j,0,xcor[0]);
885  model->setData(j,1,0.0);
886  j++;
887  model->setData(j,0,xcor[0]);
888  model->setData(j,1,hist[0]);
889  j++;
890
891  for (int i = 1; i < n; ++i) {
892    model->setData(j,0,xcor[i]);
893    model->setData(j,1,hist[i-1]);
894    j++;
895    model->setData(j,0,xcor[i]);
896    model->setData(j,1,hist[i]);
897    j++;
898  }
899
900  model->setData(j,0,xcor[n]);
901  model->setData(j,1,hist[n-1]);
902  j++;
903  model->setData(j,0,xcor[n]);
904  model->setData(j,1,0.0);
905
906  // legendes
907  string unites[2];
908  if(iabs == 0 || iabs == 1 || iabs == 2) {
909    unites[0]= unites[1]= " mm";
910  }
911  if(iabs == 3 || iabs == 4) {
912    unites[0]= unites[1]= " mrad";
913  }
914  if(iabs == 5) {
915    unites[0]= " MeV"; unites[1]= " KeV";
916  }
917
918  new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
919  new WBreak(w);
920  new WText(" mean : "+ mixedTools::doubleToString(out[1])+unites[0],w);
921  new WBreak(w);
922  new WText(" sigma rms : "+ mixedTools::doubleToString(out[2])+unites[1],w);
923   
924  WCartesianChart *chart = new WCartesianChart(w);
925
926  if(iabs == 0) chart->setTitle("x-coordinate");
927  if(iabs == 1) chart->setTitle("y-coordinate");
928  if(iabs == 2) chart->setTitle("z-coordinate");
929  if(iabs == 3) chart->setTitle("xp-divergence");
930  if(iabs == 4) chart->setTitle("yp-devergence");
931  if(iabs == 5) chart->setTitle("kinetic energy");
932 
933  chart->setModel(model);        // set the model
934  chart->setXSeriesColumn(0);    // set the column that holds the categories
935  chart->setLegendEnabled(false); // enable the legend
936   
937  // Provide space for the X and Y axis and title.
938  chart->setPlotAreaPadding(200, Right);
939  chart->setPlotAreaPadding(80, Left);
940  chart->setPlotAreaPadding(40, Top | Bottom);
941   
942  chart->setType(ScatterPlot);
943   
944  WAxis& axis = chart->axis(XAxis);
945  axis.setLabelFormat("%.3f");
946  axis.setGridLinesEnabled(true);
947
948  if(iabs == 0) axis.setTitle(WString(" x (mm)"));
949  if(iabs == 1) axis.setTitle(WString(" y (mm)"));
950  if(iabs == 2) axis.setTitle(WString(" z (mm)"));
951  if(iabs == 3) axis.setTitle(WString(" xp (mrad)"));
952  if(iabs == 4) axis.setTitle(WString(" yp (mrad)"));
953  if(iabs == 5) axis.setTitle(WString(" dEcin/Ecin (%)"));
954 
955  chart->axis(Y1Axis).setGridLinesEnabled(true);
956  //chart->axis(Y1Axis).setTitle(WString("legende y"));
957   
958  WDataSeries s(1, LineSeries);
959  s.setFillRange(ZeroValueFill);
960  chart->addSeries(s);
961   
962  chart->resize(800, 400);
963  chart->setMargin(10, Top | Bottom);
964  chart->setMargin(WLength::Auto, Left | Right);
965   
966  LegendLocation location = LegendOutside;
967  Side side = Right;
968  AlignmentFlag alignment = AlignMiddle;
969  chart->setLegendLocation(location, side, alignment);
970  chart->setLegendStyle(chart->legendFont(), WPen(black), WBrush(WColor(0xFF, 0xFA, 0xE5)));
971}
972
973void PspaApplication::removeBeamLine() {
974  createBeamLine();
975}
Note: See TracBrowser for help on using the repository browser.