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

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

sauver/restaurer une config ok

File size: 36.2 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  globalParam_ = new GWt_globalParameters(dtmanage_);
146  WWidget* dboard = createDashBoard();
147  dboard->setMinimumSize(300,100);
148  mainGridLayout->addWidget(dboard,3,1);
149  //-----------
150
151  graphicsDialog_ = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
152  graphicsDialog_->setMinimumSize(400,400);
153  graphicsDialog_->setClosable(true);
154  graphicsDialog_->hide();
155 
156  executeWidget_ = new GWt_softwarePanel(dtmanage_,this);
157  executeWidget_->setMinimumSize(400,100);
158  mainGridLayout->addWidget(executeWidget_,4,1);
159 
160  console_ = new GWt_console();
161  console_->setMinimumSize(300,100);
162  mainGridLayout->addWidget(console_,3,2,2,1);
163
164  // Let row 2 and column 1 take the excess space.
165  mainGridLayout->setRowStretch(4,1);
166  mainGridLayout->setColumnStretch(2,1);
167 
168  widroot->setLayout(mainGridLayout);
169  // set auto scrollbar if needed
170  widroot->setOverflow(WContainerWidget::OverflowAuto);
171}
172
173// WWidget* PspaApplication::createGlobalParamWidget()
174// {
175//   WContainerWidget* globalParam = new GWt_globalParameters(this);
176//   globalParam->setMinimumSize(300,100);
177//   return globalParam;
178// }
179
180WWidget* PspaApplication::createDashBoard()
181{
182  WContainerWidget *result = new WContainerWidget();
183 
184  WPanel *panel = new WPanel(result);
185  panel->setTitle("dashboard");
186 
187  WContainerWidget *textdiv;
188  textdiv = new WContainerWidget();
189  textdiv->setStyleClass("text");
190  globalParam_->setText(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
398void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
399{
400  if ( code != Wt::WDialog::Accepted ) {
401    return;
402  }
403  nameOfCase_ = saveNameEdit_->text().toUTF8();
404  delete dialogSave_;
405  dialogSave_ = NULL;
406
407  globalParam_->updateGlobals();
408
409  //  dtmanage_->saveConfiguration(nameOfCase_);
410  dtmanage_->saveConfiguration(sessionId(),nameOfCase_);
411
412  // en test: j'ajoute la sauvegarde sur .aml
413  dtmanage_->writeToAMLFile(nameOfCase_);
414}
415
416void PspaApplication::restaurer()
417{
418  GWt_serverFileSelector * fs = new GWt_serverFileSelector("Select a configuration file",workingDir_);
419  string fileName = fs->exec();
420  nameOfCase_ = fileName;
421  if (fileName == "") {
422    return;
423  }
424   
425  removePathFromConfigName(nameOfCase_ );
426  cout << " nom sans path " << nameOfCase_ << endl;
427  removeExtensionFromConfigName(nameOfCase_);
428  cout << " nom sans extension " << nameOfCase_ << endl;
429  if (nameOfCase_ == "")
430    return;
431  cout << " PspaApplication:: restaure le fichier " << fileName << endl;
432  dialogSave_ = NULL;
433 
434  bool test = dtmanage_->restoreElements(fileName);
435  if ( !test ) {
436    GWt_dialog restoreWarning(" element restoring", "failure in restoring elements from file : " + fileName , GWt_dialog::Error, false,true);
437    restoreWarning.exec();
438  } else {
439    // Change the window title
440    unsigned long found = fileName.find_last_of("/");
441    setTitle(applicationDefaultTitle_+" : "+fileName.substr(found+1));
442  }
443 
444  globalParam_->renew(); 
445  console_->addConsoleMessage(string("restauration terminee \n"));
446}
447
448void PspaApplication::openFileSelector()
449{
450   
451  WContainerWidget *result = new WContainerWidget();
452  WVBoxLayout* myLayout = new WVBoxLayout();
453   
454  uploadFileSelectorWidget_ = new WFileUpload();
455   
456  uploadFileSelectorWidget_->setFileTextSize(40);
457   
458  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
459  myLayout->addWidget(uploadFileSelectorWidget_);
460   
461  result->setLayout (myLayout);
462   
463  // Upload automatically when the user entered a file.
464  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
465 
466  // React to a succesfull upload.
467  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
468 
469  // React to a fileupload problem.
470  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
471 
472 
473  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
474 
475  fileSelectorDialog->exec();
476}
477
478void PspaApplication::chargerConfig()
479{
480  GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
481   
482  string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
483  cout << " fichier client : " << nomDuFichier << endl;
484  bool test = removeExtensionFromConfigName(nomDuFichier);
485  cout << " fichier client sans extension : " << nomDuFichier << endl;
486 
487  if ( test )
488    {
489      nameOfCase_ = nomDuFichier;
490      console_->addConsoleMessage(string("restauration..."));
491     
492      if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
493        GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
494        restoreWarning.exec();
495      }
496     
497      GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
498      bibi->renew();
499     
500      console_->addConsoleMessage(string("rechargement de config termine"));
501      message->show();
502    }
503}
504
505void PspaApplication::fileTooLarge()
506{
507  std::stringstream stream;
508  stream << maximumRequestSize ();
509  std::string maxRequestSize(stream.str());
510 
511  std::string message = "This file is too large, please select a one\n";
512  message += "Maximum file size is "+ maxRequestSize;
513  message += " bytes\n";
514   
515  GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true);
516 
517  messageBox->show();
518}
519
520void PspaApplication::faireDessin()
521{
522  choixElementDessin_->clear();
523  choixHistoDessin_->clear();
524
525  int nombre = dtmanage_->getBeamLineSize(); 
526  for(int i = 1; i <= nombre; i++) {
527    abstractElement* elPtr = dtmanage_->getElementPointerFromNumero(i);
528    //    if(elPtr->getNomdElement().getElementType() == snapshot) continue;
529
530    choixElementDessin_->addItem(elPtr->getLabel());
531    choixHistoDessin_->addItem(elPtr->getLabel());
532  } 
533}
534
535void PspaApplication::dessinerPhaseSpace()
536{   
537   
538  int typeFaisceau = choixTypeDessinFaisceau_->currentIndex();
539  //  int index = choixElementDessin_->currentIndex();
540  string nameAbs = choixAbsPhase_->currentText().toUTF8();
541  string nameOrd = choixOrdPhase_->currentText().toUTF8();
542  if ( nameAbs == nameOrd ) {
543        GWt_dialog phaseSpaceError(" graphical analysis", "the beam coordinates must be different !", GWt_dialog::Error, false,true);
544        phaseSpaceError.exec();
545        return;
546  }
547  string elementLabel = choixElementDessin_->currentText().toUTF8();
548  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
549  //  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
550   
551  if ( beam == NULL ) {
552    GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
553    warningBeamState.exec();
554    return;
555  }
556   
557    toto_->clear();
558    faireDessinPhaseSpace(toto_, beam, elementLabel, nameAbs, nameOrd, typeFaisceau);
559
560  // if ( typeFaisceau == 0 )
561  //   {
562  //     if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
563  //     faireDessinTransport(toto_, beam, nameAbs, nameOrd );
564  //   }
565  // else if ( typeFaisceau == 1 )
566  //   {
567  //     if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam, nameAbs, nameOrd );
568  //     else {
569  //    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
570  //    warningBeamState.exec();
571  //     }
572  //   }
573  // else {
574  //   GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
575  //   warningTypeDrawing.exec();
576  // }
577}
578
579void PspaApplication::dessinerEnveloppe()
580{
581  toto_->clear();
582 
583  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
584  if ( typeEnveloppe == 0 )
585    {
586      faireDessinEnveloppe(toto_, "x");
587    }
588  else {
589    GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
590    warningTypeEnveloppe.exec();
591  }
592}
593
594void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
595{
596 
597  std::time_t result = std::time(NULL);
598 
599  GWt_dialog* envDialog = new GWt_dialog(WString("enveloppe&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto,false);
600  eDialog_.push_back(envDialog);
601  envDialog->setMinimumSize(400,400);
602  envDialog->setClosable(true);
603  envDialog->show();
604     
605  //  unsigned nbel = dtmanage_->getBeamLineSize();
606  vector<double> xcor;
607  vector<double> ycor;
608  string titre;
609  string legendx;
610  string legendy;
611  dtmanage_->donneesRmsEnveloppe(type,xcor,ycor,titre,legendx,legendy);
612
613  Wt::Chart::SeriesType seriesType = LineSeries;
614  Wt::Chart::FillRangeType fillRange = NoFill;
615  Wt::Chart::AxisValue location = ZeroValue;
616  bool isGridLinesEnabled = false; 
617  chartPlot2vec(envDialog->contents(),xcor,ycor,seriesType,fillRange,location,isGridLinesEnabled,titre,legendx,legendy,500,300);
618}
619
620void PspaApplication::faireDessinPhaseSpace(WContainerWidget* toto, particleBeam* beam, string elementLabel, string namex, string namey, int typeFaisceau)
621{
622
623  vector<double> xcor;
624  vector<double> ycor;
625  vector<string> legende;
626  string titre;
627  Wt::Chart::SeriesType seriesType;
628 
629  if ( typeFaisceau == 0 ) {
630    seriesType = LineSeries;
631    titre = "phase space rms";
632    beam->donneesDessinEllipse(xcor,ycor,legende,namex,namey);
633  } else if (  typeFaisceau == 1 ) {
634    seriesType = PointSeries;
635    titre = " phase space ";
636    cout << " PspaApplication::faireDessinPhaseSpace APPEL " << endl;
637    beam->particlesPhaseSpaceData(xcor,ycor,legende,namex,namey);
638    cout << " PspaApplication::faireDessinPhaseSpace RETOUR " << endl;
639  } else {
640    GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
641    warningBeamState.exec();
642    return;
643  }
644 
645  std::time_t result = std::time(NULL);
646  GWt_dialog* phaseSpaceDialog = new GWt_dialog(WString("phase space&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto,false);
647  eDialog_.push_back(phaseSpaceDialog);
648  phaseSpaceDialog->setMinimumSize(400,400);
649  phaseSpaceDialog->setClosable(true);
650  new WText(" case : " + nameOfCase_, phaseSpaceDialog->contents());
651  new WBreak(phaseSpaceDialog->contents());
652  new WText(" after element :  " + elementLabel, phaseSpaceDialog->contents());
653
654  for (int k=0 ; k < (int)legende.size(); k++) {
655    new WBreak(phaseSpaceDialog->contents());
656    new WText(legende.at(k), phaseSpaceDialog->contents());
657  }
658
659  Wt::Chart::FillRangeType fillRange = NoFill;
660  Wt::Chart::AxisValue location = ZeroValue;
661  bool isGridLinesEnabled = false; 
662  chartPlot2vec(phaseSpaceDialog->contents(),xcor,ycor,seriesType,fillRange,location,isGridLinesEnabled,titre,namex,namey,500,300);
663 
664  phaseSpaceDialog->show();
665}
666
667
668
669// void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam, string namex, string namey )
670// {
671//   cout << " faireDessinParmela " << endl;
672//   GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
673//   eDialog_.push_back(pointsDialog);
674//   pointsDialog->setMinimumSize(400,400);
675//   pointsDialog->setClosable(true);
676//   // pointsDialog->show();
677     
678//   new WText(nameOfCase_, pointsDialog->contents());
679
680
681//   vector<double> xcor;
682//   vector<double> ycor;
683//   vector<string> legende;
684//   beam->particlesPhaseSpaceData(xcor, ycor, legende, namex, namey);
685//   for (int k=0 ; k < legende.size(); k++) {
686//     new WBreak(pointsDialog->contents());
687//     new WText(legende.at(k), pointsDialog->contents());
688//   }
689//   string titre = " phase space ";
690//   chartPlot2vec(pointsDialog->contents(), xcor, ycor, true,titre,namex, namey,400,400);
691
692
693   
694//   pointsDialog->show();
695   
696//   //  chart->setMargin(10, Top | Bottom);            // add margin vertically
697//   //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
698// }
699
700// void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam, string namex, string namey)
701// {
702//   GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
703//   eDialog_.push_back(ellipseDialog);
704//   ellipseDialog->setMinimumSize(400,400);
705//   ellipseDialog->setClosable(true);
706//   ellipseDialog->show();
707//   new WText(nameOfCase_, ellipseDialog->contents());
708 
709//   vector<double> xcor;
710//   vector<double> ycor;
711//   vector<string> legende;
712//   beam->donneesDessinEllipse(xcor,ycor,legende, namex, namey);
713
714//   for (int k=0 ; k < legende.size(); k++) {
715//     new WBreak(ellipseDialog->contents());
716//     new WText(legende.at(k), ellipseDialog->contents());
717//   }
718//   string titre = "phase space rms";
719//   chartPlot2vec(ellipseDialog->contents(), xcor, ycor, false,titre, namex, namey,500,300);
720// }
721
722
723// // parametre drawPoints : true = on trace des points (phase space) ; false = on trace des lignes (enveloppes...)
724// 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)
725// {
726//     int nbpts = xcor.size();
727//     cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
728//     WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
729//     for (int i = 0; i < nbpts; ++i) {
730//         model->setData(i, 0, xcor.at(i));
731//         model->setData(i, 1, ycor.at(i));
732//         //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
733//     }
734   
735//     WCartesianChart *chart = new WCartesianChart(toto);
736//     if (!makeIcon) {
737//         chart->setTitle(title);
738//     }
739//     chart->initLayout();
740   
741//     chart->setModel(model);        // set the model
742//     chart->setXSeriesColumn(0);    // set the column that holds the X data
743//     if (!makeIcon) {
744//         chart->setLegendEnabled(true); // enable the legend
745//     } else {
746//         chart->setLegendEnabled(false); // enable the legend
747//     }
748   
749//     chart->setType(ScatterPlot);   // set type to ScatterPlot
750   
751//     // Typically, for mathematical functions, you want the axes to cross
752//     // at the 0 mark:
753//     chart->axis(XAxis).setLocation(ZeroValue);
754//     chart->axis(YAxis).setLocation(ZeroValue);
755
756//     // Provide space for the X and Y axis and title.
757//     chart->setPlotAreaPadding(80, Left);  // ?
758//     chart->setPlotAreaPadding(40, Bottom);
759//     chart->setPlotAreaPadding(60, Top);
760//     if ( drawPoints ) {
761//       WDataSeries s(1, PointSeries, Y1Axis);
762//       chart->addSeries(s);   
763//     } else {
764//       WDataSeries s(1, LineSeries, Y1Axis);
765//       chart->addSeries(s);   
766//     }
767//     chart->resize(width, height); // WPaintedWidget must be given explicit size
768   
769   
770//     WAxis& axis = chart->axis(XAxis);
771//     axis.setLabelFormat("%.3f");
772//     //       axis.setGridLinesEnabled(true);
773//     axis.setTitle(legendx);
774   
775//     WAxis& axey = chart->axis(YAxis);
776//     axey.setTitle(legendy);
777//     // axis = chart->axis(YAxis);
778//     // axis.setLabelFormat("%.3f");
779//     // axis.setGridLinesEnabled(true);
780//     // axis.setTitle(legendy);
781   
782//     if (makeIcon) {
783//       chart->setPlotAreaPadding(0);
784//       chart->setAxisPadding(0);
785//       WFont xAxisFont = chart->axis(XAxis).labelFont();
786//       xAxisFont.setSize(8);
787//       WFont yAxisFont = chart->axis(YAxis).labelFont();
788//       yAxisFont.setSize(8);
789//       chart->axis(XAxis).setLabelFont(xAxisFont);
790//       chart->axis(YAxis).setLabelFont(yAxisFont);
791//     }
792
793// #ifdef HAS_IMAGEMAGIC
794// /*    Wt::WRasterImage pngImage("png", 600, 600);
795//     Wt::WPainter p(&pngImage);
796//     chart->paint(p);
797//     std::string name;
798//     name = workingDir_ + "/chart-"+sessionId ()+".png";
799//     std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
800//     pngImage.write(f);   
801//     new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
802   
803//   Wt::WPdfImage pdfImage("30cm", "30cm");
804//     Wt::WPainter p1(&pdfImage);
805//     pdfImage.init();
806//     chart->paint(p1);
807//     name = workingDir_ + "/chart-"+sessionId ()+".pdf";
808//     std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
809//     pdfImage.write(f1);
810//  */
811// #endif
812// }
813
814
815WText* PspaApplication::createTitle(const WString& title)
816{
817  WText *result = new WText(title);
818  result->setInline(false);
819  result->setStyleClass("title");
820  result->setMinimumSize(30,30);
821 
822  return result;
823}
824
825// void PspaApplication::addConsoleMessage(WString msg) {
826//   WText *w = new WText(console_);
827//   w->setTextFormat(PlainText);
828//   w->setText(msg);
829//   w->setInline(false);
830
831//   /*
832//    * Little javascript trick to make sure we scroll along with new content
833//    */
834//   WApplication *app = WApplication::instance();
835//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
836//                     + console_->jsRef() + ".scrollHeight;");
837
838// }
839
840bool PspaApplication::removePathFromConfigName(string& config) {
841  string toExtract = workingDir_ + "/";
842  string::size_type nn = config.find(toExtract);
843  if ( nn == string::npos ) {
844        GWt_dialog checkremovePath(" checking config file name", " failed to recognize path name for file  " + config, GWt_dialog::Error,true,true);
845        checkremovePath.exec();
846    return false;
847  }
848  config.replace(nn, toExtract.size(), "");
849  return true;
850}
851
852bool PspaApplication::removeExtensionFromConfigName(string& config)
853{
854    //  string configName;
855    string extension(".save");
856    bool test = true;
857    string::size_type nn = config.rfind('.');
858    if ( nn == string::npos )
859    {
860        // pas de point
861        test = false;
862    }
863    string fin = config.substr(nn);
864    if ( fin != extension )
865    {
866        // l'extension n'est pas la bonne
867        test = false;
868    }
869    if ( test )
870    {
871        string::size_type count = config.length() - extension.length();
872        config = config.substr(0, count);
873    }
874    else
875    {
876        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
877        checkConfigNameDialog.exec();
878    }
879    return test;
880}
881
882
883
884void PspaApplication::removeBeamLine() {
885  createBeamLine();
886  executeWidget_->updateSections();
887}
888
889void 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)
890{
891  int nbpts = xcor.size();
892  cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
893
894  WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
895  for (int i = 0; i < nbpts; ++i) {
896    model->setData(i, 0, xcor.at(i));
897    model->setData(i, 1, ycor.at(i));
898    //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
899  }
900   
901  WCartesianChart *chart = new WCartesianChart(toto);
902  if (!makeIcon) chart->setTitle(title);
903  chart->initLayout(); 
904  chart->setModel(model);        // set the model
905  chart->setXSeriesColumn(0);    // set the column that holds the X data
906 
907  chart->setType(ScatterPlot);   // set type to ScatterPlot
908  chart->setLegendEnabled(false); // enable the legend 
909
910  // Provide space for the X and Y axis and title.
911  chart->setPlotAreaPadding(80, Left); 
912  chart->setPlotAreaPadding(40, Bottom);
913  chart->setPlotAreaPadding(60, Top);
914 
915  // Typically, for mathematical functions, you want the axes to cross
916  // at the 0 mark (value= ZeroValue)
917  chart->axis(XAxis).setLocation(value);
918  chart->axis(YAxis).setLocation(value);
919 
920  WDataSeries s(1,seriesType);
921  s.setPen(WColor("red"));
922  s.setFillRange(fillRange);
923  chart->addSeries(s);
924 
925  WAxis& axis = chart->axis(XAxis);
926  axis.setLabelFormat("%.3f");
927  axis.setTitle(legendx);
928   
929  chart->axis(Y1Axis).setTitle(legendy);
930
931  if(isGridLinesEnables) {
932    axis.setGridLinesEnabled(true);
933    chart->axis(Y1Axis).setGridLinesEnabled(true);
934  }
935 
936  chart->resize(width,height); // WPaintedWidget must be given explicit size
937  chart->setMargin(10, Top | Bottom); // ?
938  chart->setMargin(WLength::Auto, Left | Right); //?
939
940  if (makeIcon) {
941    chart->setLegendEnabled(false); // enable the legend
942    chart->setPlotAreaPadding(0);
943    chart->setAxisPadding(0);
944    WFont xAxisFont = chart->axis(XAxis).labelFont();
945    xAxisFont.setSize(8);
946    WFont yAxisFont = chart->axis(YAxis).labelFont();
947    yAxisFont.setSize(8);
948    chart->axis(XAxis).setLabelFont(xAxisFont);
949    chart->axis(YAxis).setLabelFont(yAxisFont);
950  }
951
952#ifdef HAS_IMAGEMAGIC
953
954  // no background
955  chart->setBackground(WBrush(Wt::NoBrush));
956
957  // axis black
958  chart->axis(XAxis).setPen(WColor("black"));
959  chart->axis(YAxis).setPen(WColor("black"));
960   
961  std::string name;
962/*
963 Wt::WRasterImage pngImage("png", 1000, 1000);
964  Wt::WPainter p(&pngImage);
965  chart->paint(p);
966  name = workingDir_ + "/chart-"+sessionId ()+".png";
967  std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
968  pngImage.write(f);
969*/
970 
971
972  Wt::WPdfImage pdfImage("1000", "600");
973  {
974   Wt::WPainter p1(&pdfImage);
975    chart->paint(p1);
976  }
977
978  name = workingDir_ + "/chart-"+sessionId ()+".pdf";
979  std::ofstream f1(name.c_str(), std::ios::out | std::ios::binary);
980  pdfImage.write(f1);
981
982  new WText("<a href='workingArea/chart-"+sessionId ()+".pdf' target='_blank'>Sauvegarder l'image</a>",toto);
983
984#endif
985
986}
987
988void PspaApplication::dessinerHistogramme()
989{
990  toto_->clear();
991 
992  // std::time_t result = std::time(NULL);
993  // GWt_dialog* histoDialog = new GWt_dialog(WString("histogramme&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto_,false);
994  // eDialog_.push_back(histoDialog);
995  // histoDialog->setMinimumSize(400,400);
996  // histoDialog->setClosable(true);
997
998  string elementLabel = choixHistoDessin_->currentText().toUTF8();   
999  particleBeam* beam = dtmanage_->getDiagnosticBeam(elementLabel);
1000  if (beam == NULL) {
1001    GWt_dialog warningBeamState("histogram","the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
1002    warningBeamState.exec();
1003    return;
1004  }
1005 
1006  if (!beam->particleRepresentationOk()) {
1007    GWt_dialog warningBeamState("histogram", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
1008    warningBeamState.exec();
1009    return;
1010  }
1011
1012  unsigned iabs= choixVariableHisto_->currentIndex(); 
1013  vector<double> xcor;
1014  vector<int> hist;
1015  //  double out[3]= {0.0};
1016  vector<string> legende;
1017  beam->histogramme(iabs,xcor,hist,legende);
1018
1019  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
1020  //////////////////////////////////////////////////////////////////////////////////
1021 
1022  int n = hist.size();
1023  vector<double> x;
1024  x.resize(2*n+2);
1025  vector<double> y;
1026  y.resize(2*n+2);
1027
1028  int j= 0;
1029  x.at(j)= xcor[0];
1030  y.at(j)= 0.0;
1031  j++;
1032  x.at(j)= xcor[0];
1033  y.at(j)= hist[0];
1034  j++;
1035 
1036  for (int i = 1; i < n; ++i) {
1037    x.at(j)= xcor[i];
1038    y.at(j)= hist[i-1];
1039    j++;
1040    x.at(j)= xcor[i];
1041    y.at(j)= hist[i];
1042    j++;
1043  }
1044
1045  x.at(j)= xcor[n];
1046  y.at(j)= hist[n-1];
1047  j++;
1048  x.at(j)= xcor[n];
1049  y.at(j)= 0.0;
1050  //////////////////////////////////////////////////////////////////////////////////
1051  std::time_t result = std::time(NULL);
1052  GWt_dialog* histoDialog = new GWt_dialog(WString("histogramme&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(")+std::asctime(std::localtime(&result))+")",toto_,false);
1053  eDialog_.push_back(histoDialog);
1054  histoDialog->setMinimumSize(400,400);
1055  histoDialog->setClosable(true);
1056
1057  histoDialog->show();
1058
1059  WContainerWidget *w= histoDialog->contents();
1060
1061  // // legendes
1062  // string unites[2];
1063  // if(iabs == 0 || iabs == 1 || iabs == 2) {
1064  //   unites[0]= unites[1]= " mm";
1065  // }
1066  // if(iabs == 3 || iabs == 4) {
1067  //   unites[0]= unites[1]= " mrad";
1068  // }
1069  // if(iabs == 5) {
1070  //   unites[0]= " MeV"; unites[1]= " KeV";
1071  // }
1072
1073  new WText(" case : " + nameOfCase_, w);
1074  new WBreak(w);
1075  new WText(" after element :  " + elementLabel, w);
1076
1077  for (int k=0 ; k < (int)legende.size(); k++) {
1078    new WBreak(w);
1079    new WText(legende.at(k), w);
1080  }
1081
1082
1083  // new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
1084  // new WBreak(w);
1085  // new WText(" mean : "+ mixedTools::doubleToString(out[1])+unites[0],w);
1086  // new WBreak(w);
1087  // new WText(" sigma rms : "+ mixedTools::doubleToString(out[2])+unites[1],w);
1088  //////////////////////////////////////////////////////////////////////////////////
1089
1090  string titre;
1091  if(iabs == 0) titre="x-coordinate";
1092  if(iabs == 1) titre="y-coordinate";
1093  if(iabs == 2) titre="z-coordinate";
1094  if(iabs == 3) titre="xp-divergence";
1095  if(iabs == 4) titre="yp-devergence";
1096  if(iabs == 5) titre="kinetic energy";
1097
1098  string xname;
1099  if(iabs == 0) xname=" x (mm)";
1100  if(iabs == 1) xname=" y (mm)";
1101  if(iabs == 2) xname=" z (mm)";
1102  if(iabs == 3) xname=" xp (mrad)";
1103  if(iabs == 4) xname=" yp (mrad)";
1104  if(iabs == 5) xname=" dEcin/Ecin (%)";
1105
1106  string yname;
1107  Wt::Chart::SeriesType seriesType = LineSeries;
1108  Wt::Chart::FillRangeType fillRange = ZeroValueFill;
1109  Wt::Chart::AxisValue location = MinimumValue;
1110  bool isGridLinesEnabled = true; 
1111  chartPlot2vec(w,x,y,seriesType,fillRange,location,isGridLinesEnabled,titre,xname,yname,500,300);
1112}
1113
1114
Note: See TracBrowser for help on using the repository browser.