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

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

preparation pour ajouter une maille FODO

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