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

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

Ameliorations pour la sauvegarde des fichiers et autres

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