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

Last change on this file since 455 was 455, checked in by garnier, 10 years ago

grosse modification pour intégrer les sections

File size: 20.2 KB
Line 
1#include <stdio.h>
2#include <ctime>
3
4#include "GWt_pspaApplication.h"
5#include "GWt_draggableImage.h"
6#include "GWt_abstractElementFactory.h"
7#include "GWt_serverFileSelector.h"
8#include "GWt_accelerator.h"
9#include "particleBeam.h"
10#include "bareParticle.h"
11#include "nomDeLogiciel.h"
12#include "mixedTools.h"
13#include "nomdElements.h"
14#include "environmentVariables.h"
15#include "trivaluedBool.h"
16
17#include <Wt/WGridLayout>
18#include <Wt/WVBoxLayout>
19#include <Wt/WHBoxLayout>
20#include <Wt/WImage>
21#include <Wt/WMenu>
22#include <Wt/WStackedWidget>
23#include <Wt/WBreak>
24#include <Wt/WStandardItemModel>
25#include <Wt/WFileUpload>
26#include <Wt/WPainter>
27#include <Wt/WScrollArea>
28#include <Wt/WRadioButton>
29#include <Wt/WMessageBox>
30#include <Wt/WScrollArea>
31#include <Wt/WLabel>
32
33#define HAS_IMAGEMAGIC 1
34
35using namespace Wt::Chart;
36
37/*
38 * The env argument contains information about the new session, and
39 * the initial request. It must be passed to the WApplication
40 * constructor so it is typically also an argument for your custom
41 * application constructor.
42 */
43
44PspaApplication::PspaApplication(const WEnvironment& env) : 
45  WApplication(env),
46  applicationDefaultTitle_("portail PSPA"),
47  extensionFile_(0)
48{
49  workingDir_ = WApplication::docRoot()+ "/"+WORKINGAREA;
50  nameOfCase_ = "pspa"; // default
51   
52  setTitle(applicationDefaultTitle_);  // application title
53  if (!wApp->environment().javaScript()) {
54    new WText("<i>This examples requires that javascript support is enabled.</i>",root());
55  }
56   
57  // register the absractElementFactory
58  abstractElementFactory_ = new GWt_abstractElementFactory();
59  abstractElementFactory_->setRFGunEnable(true);
60  abstractElementFactory_->setDriftEnable(true);
61  abstractElementFactory_->setCellEnable(true);
62  abstractElementFactory_->setBendEnable(true);
63  abstractElementFactory_->setSolenoEnable(true);
64  abstractElementFactory_->setBeamEnable(true);
65  abstractElementFactory_->setFitEnable(true);
66  abstractElementFactory_->setSnapshotEnable(true);
67  abstractElementFactory_->setMPoleEnable(true);
68 
69  // include the styleSheetcd
70  WContainerWidget *mainContainerWidget = root();
71  useStyleSheet("htdocs/pspa.css");
72  dtmanage_ = new dataManager(this);
73
74  // The main layout is a 4x3 grid layout.
75  WHBoxLayout *toolbarLayout = new WHBoxLayout();
76 
77  WPushButton* boutonSauve = new WPushButton();
78  WPushButton* boutonRestaure = new WPushButton();
79  WPushButton* boutonLoadNew = new WPushButton();
80  WPushButton* boutonTrash = new WPushButton();
81 
82  boutonSauve->setStyleClass("saveButton");
83  boutonRestaure->setStyleClass("restoreButton");
84  boutonLoadNew->setStyleClass("loadNewButton");
85  boutonTrash->setStyleClass("trashButton");
86 
87  boutonSauve->setToolTip ("sauvegarder votre configuration");
88  boutonRestaure->setToolTip ("restaurer la configuration depuis le serveur");
89  boutonLoadNew->setToolTip ("charger une configuration");
90  boutonTrash->setToolTip ("supprimer l'accélerateur"); // FIXME ! a terminer
91 
92  boutonSauve->setMaximumSize(38,38);
93  boutonSauve->setMinimumSize(38,38);
94  boutonRestaure->setMaximumSize(38,38);
95  boutonRestaure->setMinimumSize(38,38);
96  boutonLoadNew->setMaximumSize(38,38);
97  boutonLoadNew->setMinimumSize(38,38);
98  boutonTrash->setMaximumSize(38,38);
99  boutonTrash->setMinimumSize(38,38);
100 
101  boutonSauve->clicked().connect(this, &PspaApplication::sauver);
102  boutonRestaure->clicked().connect(this, &PspaApplication::restaurer);
103  // Upload when the button is clicked. React to a succesfull upload.
104  boutonLoadNew->clicked().connect(this, &PspaApplication::openFileSelector);
105  toolbarLayout->addWidget(boutonSauve , 0,Wt::AlignMiddle);
106  toolbarLayout->addWidget(boutonRestaure , 0,Wt::AlignMiddle);
107  toolbarLayout->addWidget(boutonLoadNew , 0,Wt::AlignMiddle);
108  toolbarLayout->addWidget(boutonTrash , 0,Wt::AlignMiddle);
109  toolbarLayout->addWidget(new WText("") , 1,Wt::AlignMiddle);
110 
111  WGridLayout* gridLayout = new WGridLayout(mainContainerWidget);
112
113  WContainerWidget * toolbarLayoutContainer = new WContainerWidget();
114  toolbarLayoutContainer->setLayout(toolbarLayout);
115  toolbarLayoutContainer->decorationStyle().setBackgroundImage ("/htdocs/fond_toolbar.png");
116  // menu menu on the top
117  gridLayout->addWidget(toolbarLayoutContainer, 1,0,1,2);
118  // palette on the left
119  gridLayout->addWidget(createPalette(mainContainerWidget), 2, 0);
120 
121  // create accelerator main widget
122  WContainerWidget* acceleratorContainerWidget = new WContainerWidget();
123  gridLayout->addWidget(acceleratorContainerWidget, 2, 1);
124
125  // Let column 2 take the excess space.
126  gridLayout->setColumnStretch(1,1);
127  // Let row 1 take the excess space.
128  gridLayout->setRowStretch(2,1);
129
130 
131  new GWt_accelerator(acceleratorContainerWidget,dtmanage_);
132  new WBreak(acceleratorContainerWidget);
133
134
135  // ---------------------------------------------------------------
136  // ********************* Ancien code : A supprimer ***************
137  // ---------------------------------------------------------------
138  beamLine_deprecated_ = NULL;
139  /*
140   WScrollArea* scroll = new  WScrollArea(acceleratorContainerWidget);
141   scroll->setWidget(createBeamLine__deprecated());
142   scroll->setMinimumSize(300,150);
143   */
144 
145  new WBreak(acceleratorContainerWidget);
146  //-----------
147
148  // A supprimer et a mettre en fenetre
149  // xx globalParam_ = createGlobalParamWidget();
150  // xx mainGridLayout->addWidget(globalParam_,3,1);
151
152  globalParam_ = new GWt_globalParameters(dtmanage_);
153  sectorParam_ = new GWt_sectorParameters();
154  WWidget* dboard = createDashBoard(acceleratorContainerWidget);
155  dboard->setMinimumSize(300,100);
156
157  new WBreak(acceleratorContainerWidget);
158
159  //-----------
160
161 
162  new WBreak(acceleratorContainerWidget);
163 
164  console_ = new GWt_console(acceleratorContainerWidget);
165  console_->setMinimumSize(300,100);
166
167 
168  // set auto scrollbar if needed
169  mainContainerWidget->setOverflow(WContainerWidget::OverflowAuto);
170}
171
172WWidget* PspaApplication::createDashBoard(WContainerWidget* parent)
173{
174  WContainerWidget *wt= new WContainerWidget();
175  wt->setStyleClass("text");
176  WText *st= new WText("Go ahead...",wt); 
177
178  WContainerWidget *buttons = new WContainerWidget();
179  buttons->setStyleClass("buttons");
180  WPushButton *button;
181  button = new WPushButton("globalParameters",buttons);
182  button->clicked().connect(this, &PspaApplication::messageBox1);
183  button = new WPushButton("sectors", buttons);
184  button->clicked().connect(this, &PspaApplication::messageBox2);
185 
186  styleSheet().addRule(".buttons","padding: 5px;");
187  styleSheet().addRule(".text", "padding: 4px 8px");
188  styleSheet().addRule("body", "margin: 0px;");
189
190  WContainerWidget *cnt = new WContainerWidget();
191  cnt->addWidget(buttons);
192  cnt->addWidget(wt);
193
194  WContainerWidget *result = new WContainerWidget(parent);
195  WPanel *panel = new WPanel(result);
196  panel->setTitle("dashboard");
197  panel->setCentralWidget(cnt);
198
199  globalParam_->setText(st);
200  sectorParam_->setText(st);
201  return result;
202}
203
204void PspaApplication::messageBox1()
205{
206  globalParam_->initilializeDialog();
207  return;
208}
209
210void PspaApplication::messageBox2()
211{
212  sectorParam_->execDialog_deprecated();
213  return;
214}
215
216WWidget* PspaApplication::createPalette(WContainerWidget* parent)
217{
218  WContainerWidget* palette = new WContainerWidget(parent);
219  vector <GWt_abstractElement*> elems = abstractElementFactory_->getAllElements();
220  for (unsigned a = 0; a < elems.size(); a++) {
221    elems[a]->createDragImage(palette);
222    new WBreak(palette);
223  }
224  return palette; 
225}
226
227void PspaApplication::createDragImage(const char *url,const char *smallurl,const char *mimeType,WContainerWidget *p,WString())
228{
229  GWt_draggableImage *result = new GWt_draggableImage(url,p);
230 
231  /*
232   * Set the image to be draggable, showing the other image (dragImage)
233   * to be used as the widget that is visually dragged.
234   */
235  result->setDraggable(mimeType,new WImage(smallurl,p),true);
236}
237
238/*Wt::WWidget* PspaApplication::createBeamLine__deprecated()
239{
240  extensionFile_= 0;
241  if (!beamLine__deprecated_) {
242    // FIXME : get the one of the first app/sector for the moment
243    beamLine__deprecated_ = accel_toBeRenameAsLocal->firstSector__deprecated()->getUIBeamLine ?
244  } else {
245    beamLine_->clear();
246  }
247  beamLine_->setMinimumSize(300,100);
248  setTitle(applicationDefaultTitle_);
249
250  return beamLine__deprecated_;
251}
252*/
253
254void PspaApplication::sauver()
255{
256  cout << "***********************************" << endl;
257  cout << " on sauve " << endl<<endl;
258 
259  console_->addConsoleMessage("sauvegarde \n"); 
260  dialogSave_ = new WDialog("save");
261  new WText("name of case : ",dialogSave_->contents());
262  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
263  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
264  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
265  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
266  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
267  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone);
268  dialogSave_->show();
269}
270
271void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
272{
273  if ( code != Wt::WDialog::Accepted ) {
274    return;
275  }
276  nameOfCase_ = saveNameEdit_->text().toUTF8();
277  delete dialogSave_;
278  dialogSave_ = NULL;
279
280  //globalParam_->updateGlobals();
281
282  //  dtmanage_->saveConfiguration(nameOfCase_);
283  dtmanage_->saveConfiguration(sessionId(),nameOfCase_);
284
285  // en test: j'ajoute la sauvegarde sur .aml
286  dtmanage_->writeToAMLFile(nameOfCase_);
287}
288
289void PspaApplication::restaurer()
290{
291  cout << "***********************************" << endl;
292  cout << " on restaure " << endl<<endl;
293
294  GWt_serverFileSelector * fs = new GWt_serverFileSelector("Select a configuration file",workingDir_);
295  string fileName = fs->exec();
296  nameOfCase_ = fileName;
297  if (fileName == "") {
298    return;
299  }
300   
301  removePathFromConfigName(nameOfCase_);
302  cout << " nom sans path " << nameOfCase_ << endl;
303  removeExtensionFromConfigName(nameOfCase_);
304  cout << " nom sans extension " << nameOfCase_ << endl;
305  if (nameOfCase_ == "") return;
306  cout << " PspaApplication::restaure le fichier   : " << fileName << endl;
307  dialogSave_ = NULL;
308 
309  bool test = dtmanage_->restoreElements(fileName);
310  if ( !test ) {
311    GWt_dialog restoreWarning(" element restoring", "failure in restoring elements from file : " + fileName , GWt_dialog::Error, false,true);
312    restoreWarning.exec();
313  } else {
314    // Change the window title
315    unsigned long found = fileName.find_last_of("/");
316    setTitle(applicationDefaultTitle_+" : "+fileName.substr(found+1));
317  }
318 
319  globalParam_->renew(); 
320  //sectorParam_->renew();
321  console_->addConsoleMessage(string("restauration terminee \n"));
322}
323
324void PspaApplication::openFileSelector()
325{
326  WContainerWidget *result = new WContainerWidget();
327  WVBoxLayout* myLayout = new WVBoxLayout(); 
328  uploadFileSelectorWidget_ = new WFileUpload();
329  uploadFileSelectorWidget_->setFileTextSize(40);
330  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
331  myLayout->addWidget(uploadFileSelectorWidget_);
332  result->setLayout (myLayout);
333   
334  // Upload automatically when the user entered a file.
335  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
336 
337  // React to a succesfull upload.
338  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
339 
340  // React to a fileupload problem.
341  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
342 
343  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
344  fileSelectorDialog->exec();
345}
346
347void PspaApplication::chargerConfig()
348{
349  GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
350   
351  string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
352  cout << " fichier client : " << nomDuFichier << endl;
353  bool test = removeExtensionFromConfigName(nomDuFichier);
354  cout << " fichier client sans extension : " << nomDuFichier << endl;
355 
356  if ( test ) {
357    nameOfCase_ = nomDuFichier;
358    console_->addConsoleMessage(string("restauration..."));
359     
360    if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
361      GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
362      restoreWarning.exec();
363    }
364     
365    globalParam_->renew(); 
366    //sectorParam_->renew();
367    console_->addConsoleMessage(string("rechargement de la config termine"));
368    message->show();
369  }
370}
371
372void PspaApplication::fileTooLarge()
373{
374  std::stringstream stream;
375  stream << maximumRequestSize ();
376  std::string maxRequestSize(stream.str());
377 
378  std::string message = "This file is too large, please select a one\n";
379  message += "Maximum file size is "+ maxRequestSize;
380  message += " bytes\n";
381   
382  GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true); 
383  messageBox->show();
384}
385
386
387
388// void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam, string namex, string namey )
389// {
390//   cout << " faireDessinParmela " << endl;
391//   GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
392//   eDialog_.push_back(pointsDialog);
393//   pointsDialog->setMinimumSize(400,400);
394//   pointsDialog->setClosable(true);
395//   // pointsDialog->show();
396     
397//   new WText(nameOfCase_, pointsDialog->contents());
398
399
400//   vector<double> xcor;
401//   vector<double> ycor;
402//   vector<string> legende;
403//   beam->particlesPhaseSpaceData(xcor, ycor, legende, namex, namey);
404//   for (int k=0 ; k < legende.size(); k++) {
405//     new WBreak(pointsDialog->contents());
406//     new WText(legende.at(k), pointsDialog->contents());
407//   }
408//   string titre = " phase space ";
409//   chartPlot2vec(pointsDialog->contents(), xcor, ycor, true,titre,namex, namey,400,400);
410
411
412   
413//   pointsDialog->show();
414   
415//   //  chart->setMargin(10, Top | Bottom);            // add margin vertically
416//   //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
417// }
418
419// void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam, string namex, string namey)
420// {
421//   GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
422//   eDialog_.push_back(ellipseDialog);
423//   ellipseDialog->setMinimumSize(400,400);
424//   ellipseDialog->setClosable(true);
425//   ellipseDialog->show();
426//   new WText(nameOfCase_, ellipseDialog->contents());
427 
428//   vector<double> xcor;
429//   vector<double> ycor;
430//   vector<string> legende;
431//   beam->donneesDessinEllipse(xcor,ycor,legende, namex, namey);
432
433//   for (int k=0 ; k < legende.size(); k++) {
434//     new WBreak(ellipseDialog->contents());
435//     new WText(legende.at(k), ellipseDialog->contents());
436//   }
437//   string titre = "phase space rms";
438//   chartPlot2vec(ellipseDialog->contents(), xcor, ycor, false,titre, namex, namey,500,300);
439// }
440
441
442// // parametre drawPoints : true = on trace des points (phase space) ; false = on trace des lignes (enveloppes...)
443// 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)
444// {
445//     int nbpts = xcor.size();
446//     cout << " PspaApplication::chartPlot2vec nbpts = " << nbpts << endl;
447//     WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
448//     for (int i = 0; i < nbpts; ++i) {
449//         model->setData(i, 0, xcor.at(i));
450//         model->setData(i, 1, ycor.at(i));
451//         //    cout << " PspaApplication::chartPlot2vec el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
452//     }
453   
454//     WCartesianChart *chart = new WCartesianChart(toto);
455//     if (!makeIcon) {
456//         chart->setTitle(title);
457//     }
458//     chart->initLayout();
459   
460//     chart->setModel(model);        // set the model
461//     chart->setXSeriesColumn(0);    // set the column that holds the X data
462//     if (!makeIcon) {
463//         chart->setLegendEnabled(true); // enable the legend
464//     } else {
465//         chart->setLegendEnabled(false); // enable the legend
466//     }
467   
468//     chart->setType(ScatterPlot);   // set type to ScatterPlot
469   
470//     // Typically, for mathematical functions, you want the axes to cross
471//     // at the 0 mark:
472//     chart->axis(XAxis).setLocation(ZeroValue);
473//     chart->axis(YAxis).setLocation(ZeroValue);
474
475//     // Provide space for the X and Y axis and title.
476//     chart->setPlotAreaPadding(80, Left);  // ?
477//     chart->setPlotAreaPadding(40, Bottom);
478//     chart->setPlotAreaPadding(60, Top);
479//     if ( drawPoints ) {
480//       WDataSeries s(1, PointSeries, Y1Axis);
481//       chart->addSeries(s);   
482//     } else {
483//       WDataSeries s(1, LineSeries, Y1Axis);
484//       chart->addSeries(s);   
485//     }
486//     chart->resize(width, height); // WPaintedWidget must be given explicit size
487   
488   
489//     WAxis& axis = chart->axis(XAxis);
490//     axis.setLabelFormat("%.3f");
491//     //       axis.setGridLinesEnabled(true);
492//     axis.setTitle(legendx);
493   
494//     WAxis& axey = chart->axis(YAxis);
495//     axey.setTitle(legendy);
496//     // axis = chart->axis(YAxis);
497//     // axis.setLabelFormat("%.3f");
498//     // axis.setGridLinesEnabled(true);
499//     // axis.setTitle(legendy);
500   
501//     if (makeIcon) {
502//       chart->setPlotAreaPadding(0);
503//       chart->setAxisPadding(0);
504//       WFont xAxisFont = chart->axis(XAxis).labelFont();
505//       xAxisFont.setSize(8);
506//       WFont yAxisFont = chart->axis(YAxis).labelFont();
507//       yAxisFont.setSize(8);
508//       chart->axis(XAxis).setLabelFont(xAxisFont);
509//       chart->axis(YAxis).setLabelFont(yAxisFont);
510//     }
511
512// #ifdef HAS_IMAGEMAGIC
513// /*    Wt::WRasterImage pngImage("png", 600, 600);
514//     Wt::WPainter p(&pngImage);
515//     chart->paint(p);
516//     std::string name;
517//     name = workingDir_ + "/chart-"+sessionId ()+".png";
518//     std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
519//     pngImage.write(f);   
520//     new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
521   
522//   Wt::WPdfImage pdfImage("30cm", "30cm");
523//     Wt::WPainter p1(&pdfImage);
524//     pdfImage.init();
525//     chart->paint(p1);
526//     name = workingDir_ + "/chart-"+sessionId ()+".pdf";
527//     std::ofstream f1(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
528//     pdfImage.write(f1);
529//  */
530// #endif
531// }
532
533
534WText* PspaApplication::createTitle(const WString& title)
535{
536  WText *result = new WText(title);
537  result->setInline(false);
538  result->setStyleClass("title");
539  result->setMinimumSize(30,30);
540 
541  return result;
542}
543
544// void PspaApplication::addConsoleMessage(WString msg) {
545//   WText *w = new WText(console_);
546//   w->setTextFormat(PlainText);
547//   w->setText(msg);
548//   w->setInline(false);
549
550//   /*
551//    * Little javascript trick to make sure we scroll along with new content
552//    */
553//   WApplication *app = WApplication::instance();
554//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
555//                     + console_->jsRef() + ".scrollHeight;");
556
557// }
558
559bool PspaApplication::removePathFromConfigName(string& config) {
560  string toExtract = workingDir_ + "/";
561  string::size_type nn = config.find(toExtract);
562  if ( nn == string::npos ) {
563        GWt_dialog checkremovePath(" checking config file name", " failed to recognize path name for file  " + config, GWt_dialog::Error,true,true);
564        checkremovePath.exec();
565    return false;
566  }
567  config.replace(nn, toExtract.size(), "");
568  return true;
569}
570
571bool PspaApplication::removeExtensionFromConfigName(string& config)
572{
573    //  string configName;
574    string extension(".save");
575    bool test = true;
576    string::size_type nn = config.rfind('.');
577    if ( nn == string::npos )
578    {
579        // pas de point
580        test = false;
581    }
582    string fin = config.substr(nn);
583    if ( fin != extension )
584    {
585        // l'extension n'est pas la bonne
586        test = false;
587    }
588    if ( test )
589    {
590        string::size_type count = config.length() - extension.length();
591        config = config.substr(0, count);
592    }
593    else
594    {
595        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
596        checkConfigNameDialog.exec();
597    }
598    return test;
599}
600
601
602/*
603void PspaApplication::removeBeamLine() {
604  createBeamLine__deprecated();
605  executeWidget_->updateSections();
606}
607*/
608
Note: See TracBrowser for help on using the repository browser.