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

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

correction du bug #36

File size: 33.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,applicationDefaultTitle_("portail PSPA")
49,beamLine_(NULL)
50{
51   
52    workingDir_ = WApplication::docRoot()+ "/"+WORKINGAREA;
53    nameOfCase_ = "pspa"; // default
54   
55    setTitle(applicationDefaultTitle_);                               // application title
56    if (!wApp->environment().javaScript()) {
57        new WText("<i>This examples requires that javascript support is enabled.</i>",root());
58    }
59   
60    // register the absractElementFactory
61    abstractElementFactory_ = new GWt_abstractElementFactory();
62    abstractElementFactory_->setRFGunEnable(true);
63    abstractElementFactory_->setDriftEnable(true);
64    abstractElementFactory_->setCellEnable(true);
65    abstractElementFactory_->setBendEnable(true);
66    abstractElementFactory_->setSolenoEnable(true);
67    abstractElementFactory_->setBeamEnable(true);
68    abstractElementFactory_->setFitEnable(true);
69    abstractElementFactory_->setSnapshotEnable(true);
70   
71    // include the styleSheet
72    WContainerWidget *widroot = root();
73    useStyleSheet       ("htdocs/pspa.css");
74    dtmanage_ = new dataManager(this);
75    //    dtmanage_->setWorkingDir(workingDir_);
76
77    /*
78     * The main layout is a 3x2 grid layout.
79     */
80    WGridLayout *layout = new WGridLayout();
81    //  layout->addWidget(createTitle("<a href='workingArea/parmin'> Menu (In future)</a>"), 0, 0, 1, 2);
82    //  layout->addWidget(createTitle("Menu (In future)"), 0, 0, 1, 2);
83   
84    WHBoxLayout *toolbarLayout = new WHBoxLayout();
85   
86    WPushButton* boutonSauve = new WPushButton();
87    WPushButton* boutonRestaure = new WPushButton();
88    WPushButton* boutonLoadNew = new WPushButton();
89    WPushButton* boutongraphicalAnalysis = new WPushButton();
90    WPushButton* boutonTrash = new WPushButton();
91   
92    boutonSauve->setStyleClass("saveButton");
93    boutonRestaure->setStyleClass("restoreButton");
94    boutonLoadNew->setStyleClass("loadNewButton");
95    boutongraphicalAnalysis->setStyleClass("histoButton");
96    boutonTrash->setStyleClass("trashButton");
97   
98    boutonSauve->setToolTip ("sauvegarder votre configuration");
99    boutonRestaure->setToolTip (" restaurer la configuration depuis le serveur");
100    boutonLoadNew->setToolTip ("charger une configuration");
101    boutongraphicalAnalysis->setToolTip ("analyse graphique");
102    boutonTrash->setToolTip ("tout effacer");
103   
104    boutonSauve->setMaximumSize(38,38);
105    boutonSauve->setMinimumSize(38,38);
106    boutonRestaure->setMaximumSize(38,38);
107    boutonRestaure->setMinimumSize(38,38);
108    boutonLoadNew->setMaximumSize(38,38);
109    boutonLoadNew->setMinimumSize(38,38);
110    boutongraphicalAnalysis->setMaximumSize(38,38);
111    boutongraphicalAnalysis->setMinimumSize(38,38);
112    boutonTrash->setMaximumSize(38,38);
113    boutonTrash->setMinimumSize(38,38);
114   
115    boutonSauve->clicked().connect(this, &PspaApplication::sauver);
116    boutonRestaure->clicked().connect(this, &PspaApplication::restaurer);
117    // Upload when the button is clicked.
118    // React to a succesfull upload.
119    boutonLoadNew->clicked().connect(this, &PspaApplication::openFileSelector);
120   
121    boutongraphicalAnalysis->clicked().connect(this, &PspaApplication::dialogOnGraphics);
122   
123    boutonTrash->clicked().connect(this, &PspaApplication::removeBeamLine);
124
125    toolbarLayout->addWidget(boutonSauve , 0,Wt::AlignMiddle);
126    toolbarLayout->addWidget(boutonRestaure , 0,Wt::AlignMiddle);
127    toolbarLayout->addWidget(boutonLoadNew , 0,Wt::AlignMiddle);
128    toolbarLayout->addWidget(boutongraphicalAnalysis , 0,Wt::AlignMiddle);
129    toolbarLayout->addWidget(boutonTrash , 0,Wt::AlignMiddle);
130    toolbarLayout->addWidget(new WText("") , 1,Wt::AlignMiddle);
131   
132    WContainerWidget * layoutContainer = new WContainerWidget();
133    layoutContainer->setLayout(toolbarLayout);
134    layoutContainer->decorationStyle().setBackgroundImage ("/htdocs/fond_toolbar.png");
135    layout->addWidget(layoutContainer, 1, 0, 1, 2);
136    layout->addWidget(createPalette(), 2, 0, 4, 1);
137   
138    createBeamLine();
139   
140    WScrollArea* scroll = new  WScrollArea();
141    scroll->setWidget(beamLine_);
142    layout->addWidget(scroll, 2, 1, 1, 1);
143   
144   
145    // console_ = new WContainerWidget();
146    // console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
147    // console_->setMaximumSize(600,200);
148    // layout->addWidget(console_, 3, 1);
149    // console_->setMinimumSize(300,100);
150    // console_->setOverflow(WContainerWidget::OverflowAuto);
151   
152   
153    console_ = new GWt_console();
154    console_->clear();
155    console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
156    console_->setMaximumSize(600,200);
157    console_->setMinimumSize(300,100);
158    console_->setOverflow(WContainerWidget::OverflowAuto);
159    layout->addWidget(console_, 3, 2);
160   
161    //-----------
162    // A supprimer et a mettre en fenetre
163    globalParam_ = createGlobalParamWidget();
164    //  leDessin_ = new WContainerWidget();
165    //  leDessin_ = createDrawingWidget();
166    graphicsDialog_ = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
167    graphicsDialog_->setMinimumSize(400,400);
168    graphicsDialog_->setClosable(true);
169   
170    executeWidget_ = new GWt_softwarePanel(dtmanage_,this);
171   
172    layout->addWidget( globalParam_, 3, 1);
173    //  layout->addWidget( leDessin_, 3, 2);
174    layout->addWidget( executeWidget_ , 4, 1);
175    //-----------
176     
177    layout->setColumnResizable(1);
178    layout->setRowResizable(2);
179    /*
180     * Let row 2 and column 1 take the excess space.
181     */
182    layout->setRowStretch(2, 1);
183    layout->setColumnStretch(1, 1);
184   
185    widroot->setLayout(layout);
186}
187
188WWidget* PspaApplication::createPalette()
189{
190  WContainerWidget* palette = new WContainerWidget();
191  vector <GWt_abstractElement*> elems = abstractElementFactory_->getAllElements();
192  for (unsigned a = 0; a < elems.size(); a++) {
193    elems[a]->createDragImage(palette);
194    new WBreak(palette);
195  }
196
197  return palette; 
198}
199
200void PspaApplication::createDragImage(const char *url,const char *smallurl,const char *mimeType,WContainerWidget *p,WString())
201{
202  GWt_draggableImage *result = new GWt_draggableImage(url,p);
203 
204  /*
205   * Set the image to be draggable, showing the other image (dragImage)
206   * to be used as the widget that is visually dragged.
207   */
208  result->setDraggable(mimeType,new WImage(smallurl,p),true);
209}
210
211void PspaApplication::createBeamLine()
212{
213    if (!beamLine_) {
214        beamLine_ = new GWt_LigneFaisceau(this);
215    } else {
216        beamLine_->clear();
217    }
218    beamLine_->setMinimumSize(300,100);
219    setTitle(applicationDefaultTitle_);
220}
221
222WWidget* PspaApplication::createGlobalParamWidget()
223{
224    WContainerWidget* globalParam = new GWt_globalParameters(this);
225    globalParam->setMaximumSize(600,150);
226    globalParam->setMinimumSize(600,150);
227    return globalParam;
228}
229
230
231void PspaApplication::dialogOnGraphics()
232{
233  graphicsDialog_->show();
234}
235
236WContainerWidget* PspaApplication::createDrawingWidget()
237{
238  WGridLayout *glayout= new WGridLayout();
239  WContainerWidget* dessin = new WContainerWidget();
240  dessin->setLayout(glayout);
241
242  group_ = new Wt::WButtonGroup(this);
243 
244  /////////////////////////////////////////////////////////////////////
245       
246  choixEnveloppeDessin_ = new WComboBox();
247  choixEnveloppeDessin_->addItem("x");
248  // choixEnveloppeDessin_->addItem("y");
249  Wt::WRadioButton *button1= new WRadioButton(" enveloppe");
250  group_->addButton(button1,1);
251  glayout->addWidget(button1,0,1);
252  glayout->addWidget(choixEnveloppeDessin_,0,2);
253  /////////////////////////////////////////////////////////////////////
254
255  choixElementDessin_ = new WComboBox();
256  choixElementDessin_->setMinimumSize(50,10);
257  choixTypeDessinFaisceau_ = new WComboBox();
258  choixTypeDessinFaisceau_->addItem("courant_snyder");
259  choixTypeDessinFaisceau_->addItem("macroparticles");
260  Wt::WRadioButton *button2= new WRadioButton(" phase space after element");
261
262  choixAbsPhase_ = new WComboBox();
263  choixAbsPhase_->addItem("x");
264  choixAbsPhase_->addItem("y");
265  choixAbsPhase_->addItem("dz");
266  choixAbsPhase_->addItem("xp");
267  choixAbsPhase_->addItem("yp");
268  choixAbsPhase_->addItem("dE/E");
269  choixAbsPhase_->setCurrentIndex(0);
270 
271  choixOrdPhase_ = new WComboBox();
272  choixOrdPhase_->addItem("x");
273  choixOrdPhase_->addItem("y");
274  choixOrdPhase_->addItem("dz");
275  choixOrdPhase_->addItem("xp");
276  choixOrdPhase_->addItem("yp");
277  choixOrdPhase_->addItem("dE/E");
278  choixOrdPhase_->setCurrentIndex(3);
279 
280  group_->addButton(button2,2);
281  glayout->addWidget(button2,1,1);
282  glayout->addWidget(choixElementDessin_,1,2);
283  glayout->addWidget(choixTypeDessinFaisceau_,1,3);
284  //  glayout->addWidget(new WText("abs. :"),2,2);
285  glayout->addWidget(choixAbsPhase_,2,2);
286  //  glayout->addWidget(new WText("ord. :"),2,4);
287  glayout->addWidget(choixOrdPhase_,2,3);
288  /////////////////////////////////////////////////////////////////////
289
290  choixVariableHisto_= new WComboBox();
291  choixVariableHisto_->addItem("x");
292  choixVariableHisto_->addItem("y");
293  choixVariableHisto_->addItem("z");
294  choixVariableHisto_->addItem("xp");
295  choixVariableHisto_->addItem("yp");
296  choixVariableHisto_->addItem("dE/E");
297  choixVariableHisto_->setCurrentIndex(5);
298
299  choixHistoDessin_ = new WComboBox();
300  Wt::WRadioButton *button3= new WRadioButton(" histogram after element ");
301  group_->addButton(button3,3);
302
303  glayout->addWidget(button3,3,1);
304  glayout->addWidget(choixHistoDessin_,3,2);
305  glayout->addWidget(choixVariableHisto_,3,3);
306  /////////////////////////////////////////////////////////////////////
307 
308  WPushButton *close= new WPushButton("close"); 
309  glayout->addWidget(close,4,1);
310  close->clicked().connect(this,&PspaApplication::closeGraphicDialog);
311 
312  WPushButton *draw= new WPushButton("draw"); 
313  glayout->addWidget(draw,4,2,2,1);
314  draw->clicked().connect(this,&PspaApplication::dessiner);
315  /////////////////////////////////////////////////////////////////////
316
317  toto_ = new WContainerWidget();
318  dessin->addWidget(toto_);
319  return dessin;
320}
321
322void PspaApplication::closeGraphicDialog()
323{
324  cout << " close graphicsDialog_" << endl;
325  for(unsigned i = 0; i < eDialog_.size(); i++) eDialog_[i]->done(WDialog::Rejected);
326  eDialog_.clear();
327  graphicsDialog_->done(WDialog::Rejected);
328}
329
330void PspaApplication::dessiner()
331{
332  int k= group_->checkedId();
333  cout << "dessiner k= " << k << endl;
334
335  switch(k) {
336  case  1: 
337    dessinerEnveloppe();
338    break;
339  case 2:
340    dessinerPhaseSpace();
341    break;
342  case 3:
343    dessinerHistogramme();
344    break;
345  default:
346    GWt_dialog graphicalWarning("graphical analysis","select a button",GWt_dialog::Warning,false,true);
347    graphicalWarning.exec();
348    break;
349  }
350}
351
352
353void PspaApplication::sauver()
354{
355  cout << " on sauve " << endl;
356  console_->addConsoleMessage("sauvegarde");
357 
358  dialogSave_ = new WDialog("save");
359  new WText("name of case : ",dialogSave_->contents());
360  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
361  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
362  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
363  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
364  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
365  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone);
366  dialogSave_->show();
367}
368
369
370void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
371{
372    if ( code != Wt::WDialog::Accepted ) {
373        return;
374    }
375    nameOfCase_ = saveNameEdit_->text().toUTF8();
376    delete dialogSave_;
377    dialogSave_ = NULL;
378
379    GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
380    bibi->updateGlobals();
381    //  dtmanage_->saveConfiguration(nameOfCase_);
382    dtmanage_->saveConfiguration(sessionId(),nameOfCase_);
383}
384
385
386void PspaApplication::restaurer()
387{
388    GWt_serverFileSelector * fs = new GWt_serverFileSelector("Select a configuration file",workingDir_);
389    string fileName = fs->exec();
390     nameOfCase_ = fileName;
391    if (fileName == "") {
392        return;
393    }
394   
395    removePathFromConfigName(nameOfCase_ );
396    cout << " nom sans path " << nameOfCase_ << endl;
397    removeExtensionFromConfigName(nameOfCase_);
398    cout << " nom sans extension " << nameOfCase_ << endl;
399    if (nameOfCase_ == "")
400        return;
401    cout << " je restaure le fichier " << fileName << endl;
402    dialogSave_ = NULL;
403   
404    bool test = dtmanage_->restoreElements(fileName);
405    if ( !test ) {
406        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements from file : " + fileName , GWt_dialog::Error, false,true);
407        restoreWarning.exec();
408    } else {
409        // Change the window title
410        unsigned long found = fileName.find_last_of("/");
411        setTitle(applicationDefaultTitle_+" : "+fileName.substr(found+1));
412    }
413   
414    GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
415    bibi->renew();
416   
417    console_->addConsoleMessage(string("...terminee"));
418}
419
420
421void PspaApplication::openFileSelector()
422{
423   
424  WContainerWidget *result = new WContainerWidget();
425  WVBoxLayout* myLayout = new WVBoxLayout();
426   
427  uploadFileSelectorWidget_ = new WFileUpload();
428   
429  uploadFileSelectorWidget_->setFileTextSize(40);
430   
431  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
432  myLayout->addWidget(uploadFileSelectorWidget_);
433   
434  result->setLayout (myLayout);
435   
436  // Upload automatically when the user entered a file.
437  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
438 
439  // React to a succesfull upload.
440  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
441 
442  // React to a fileupload problem.
443  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
444 
445 
446  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
447 
448  fileSelectorDialog->exec();
449}
450
451void PspaApplication::chargerConfig()
452{
453    GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
454   
455    string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
456    cout << " fichier client : " << nomDuFichier << endl;
457    bool test = removeExtensionFromConfigName(nomDuFichier);
458    cout << " fichier client sans extension : " << nomDuFichier << endl;
459   
460    if ( test )
461    {
462        nameOfCase_ = nomDuFichier;
463        console_->addConsoleMessage(string("restauration..."));
464       
465        if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
466            GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
467            restoreWarning.exec();
468        }
469       
470        GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
471        bibi->renew();
472               
473        console_->addConsoleMessage(string("...terminee"));
474        message->show();
475    }
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
876  // int nbpts= xcor.size()+cnts+1;
877  // WStandardItemModel *model = new WStandardItemModel(nbpts,2,w);
878  // //model->setHeaderData(1, WString("energie"));
879 
880  // int j= 0;
881  // if(hist[0] > 0) {
882  //   model->setData(j,0,xcor[0]);
883  //   model->setData(j,1,hist[0]);
884  //   j++;
885  // }
886  // model->setData(j,0,xcor[0]);
887  // model->setData(j,1,hist[0]);
888  // j++;
889  // for (int i = 1; i < nbpts; ++i) {
890  //   if(hist[i] == 0) {
891  //     if(hist[i-1] > 0) {
892  //    model->setData(j,0,xcor[i]);
893  //    model->setData(j,1,hist[i-1]);
894  //    j++;
895  //     }
896  //     model->setData(j,0,xcor[i]);
897  //     model->setData(j,1,hist[i]);
898  //     j++;
899  //   }
900  //   if(hist[i] > 0) {
901  //     model->setData(j,0,xcor[i]);
902  //     model->setData(j,1,hist[i-1]);
903  //     j++;
904  //     model->setData(j,0,xcor[i]);
905  //     model->setData(j,1,hist[i]);
906  //     j++;
907  //   }
908  // }
909
910  int n = hist.size();
911  int nbpts= 2*(n+1);
912  cout << " nbre de points nbpts= " << nbpts << endl;
913  WStandardItemModel *model = new WStandardItemModel(nbpts,2,w);
914   
915  int j= 0;
916  model->setData(j,0,xcor[0]);
917  model->setData(j,1,0.0);
918  j++;
919  model->setData(j,0,xcor[0]);
920  model->setData(j,1,hist[0]);
921  j++;
922  for (int i = 1; i < n; ++i) {
923    model->setData(j,0,xcor[i]);
924    model->setData(j,1,hist[i-1]);
925    j++;
926    model->setData(j,0,xcor[i]);
927    model->setData(j,1,hist[i]);
928    j++;
929  }
930 
931  model->setData(j,0,xcor[n]);
932  model->setData(j,1,hist[n-1]);
933  j++;
934  model->setData(j,0,xcor[n]);
935  model->setData(j,1,0.0);
936 
937  // legendes
938  string unites[2];
939  if(iabs == 0 || iabs == 1 || iabs == 2) {
940    unites[0]= " m"; unites[1]= " mm";
941  }
942  if(iabs == 3 || iabs == 4) {
943    unites[0]= unites[1]= " pi.mm.mrad";
944  }
945  if(iabs == 5) {
946    unites[0]= " MeV"; unites[1]= " KeV";
947  }
948
949  new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
950  new WBreak(w);
951  new WText(" mean : "+ mixedTools::doubleToString(out[1])+unites[0],w);
952  new WBreak(w);
953  new WText(" sigma rms : "+ mixedTools::doubleToString(out[2])+unites[1],w);
954   
955  WCartesianChart *chart = new WCartesianChart(w);
956
957  if(iabs == 0) chart->setTitle("Histogram of x-coordinate");
958  if(iabs == 1) chart->setTitle("Histogram of y-coordinate");
959  if(iabs == 2) chart->setTitle("Histogram of z-coordinate");
960  if(iabs == 3) chart->setTitle("Histogram of xp- ??? ");
961  if(iabs == 4) chart->setTitle("Histogram of yp- ???");
962  if(iabs == 5) chart->setTitle("Histogram of kinetic energy");
963 
964  chart->setModel(model);        // set the model
965  chart->setXSeriesColumn(0);    // set the column that holds the categories
966  chart->setLegendEnabled(false); // enable the legend
967   
968  // Provide space for the X and Y axis and title.
969  chart->setPlotAreaPadding(200, Right);
970  chart->setPlotAreaPadding(80, Left);
971  chart->setPlotAreaPadding(40, Top | Bottom);
972   
973  chart->setType(ScatterPlot);
974   
975  WAxis& axis = chart->axis(XAxis);
976  axis.setLabelFormat("%.3f");
977  axis.setGridLinesEnabled(true);
978
979  if(iabs < 5) {
980    axis.setTitle(WString(" ???"));
981  } else {
982    axis.setTitle(WString(" dEcin/Ecin (%)"));
983  }
984
985  chart->axis(Y1Axis).setGridLinesEnabled(true);
986  //chart->axis(Y1Axis).setTitle(WString("legende y"));
987   
988  WDataSeries s(1, LineSeries);
989  s.setFillRange(ZeroValueFill);
990  chart->addSeries(s);
991   
992  chart->resize(800, 400);
993  chart->setMargin(10, Top | Bottom);
994  chart->setMargin(WLength::Auto, Left | Right);
995   
996  LegendLocation location = LegendOutside;
997  Side side = Right;
998  AlignmentFlag alignment = AlignMiddle;
999  chart->setLegendLocation(location, side, alignment);
1000  chart->setLegendStyle(chart->legendFont(), WPen(black), WBrush(WColor(0xFF, 0xFA, 0xE5)));
1001}
1002
1003void PspaApplication::removeBeamLine() {
1004    createBeamLine();
1005}
Note: See TracBrowser for help on using the repository browser.