source: Sophya/trunk/SophyaPI/PIext/piacmd.cc@ 2203

Last change on this file since 2203 was 2203, checked in by cmv, 23 years ago

cshell command.... cmv 04/10/02

File size: 35.5 KB
Line 
1#include "piacmd.h"
2#include <stdio.h>
3#include <stdlib.h>
4#include <ctype.h>
5#include <math.h>
6
7#include "basexecut.h"
8
9#include "pdlmgr.h"
10#include "ctimer.h"
11// #include "dlftypes.h"
12
13#include "pistdimgapp.h"
14#include "nobjmgr.h"
15#include "piafitting.h"
16#include "pawexecut.h"
17#include "cxxexecutor.h"
18#include "cxxexecwin.h"
19#include "contmodex.h"
20#include "flowmodex.h"
21
22#include PISTDWDG_H
23#include PILIST_H
24
25// ------------------------------------------------------------
26// Gestion d'une fenetre d'aide interactive
27// Classe PIAHelpWind
28// ------------------------------------------------------------
29
30class PIAHelpWind : public PIWindow {
31public :
32 PIAHelpWind(PIStdImgApp* par, PIACmd* piacmd);
33 virtual ~PIAHelpWind();
34 virtual void Show();
35 virtual void Process(PIMessage msg, PIMsgHandler* sender, void* data=NULL);
36 inline void AddHelpGroup(const char * hgrp, int gid)
37 { hgrpom->AppendItem(hgrp, 20000+gid); }
38 inline void ClearHelpList()
39 { mNitem=0; hitemlist->DeleteAllItems(); }
40 inline void AddHelpItem(const char * hitem)
41 { mNitem++; hitemlist->AppendItem(hitem, 100+mNitem); }
42protected :
43 PIStdImgApp* dap;
44 PIACmd* piac;
45 int mNitem;
46 PIList* hitemlist;
47 PIOptMenu* hgrpom;
48 PIButton * mBut;
49 PILabel * mLab;
50 PIText* mTxt;
51};
52
53/* --Methode-- */
54PIAHelpWind::PIAHelpWind(PIStdImgApp *par, PIACmd* piacmd)
55 : PIWindow((PIMsgHandler *)par, "Help-PIApp", PIWK_normal, 400, 300, 100, 350)
56{
57dap = par;
58piac = piacmd;
59mNitem = 0;
60SetMsg(77);
61
62int bsx, bsy;
63int tsx, tsy;
64int spx, spy;
65PIApplicationPrefCompSize(bsx, bsy);
66spx = bsx/6; spy = bsy/6;
67tsx = 10*bsx+2*spx; tsy = 7*bsy+3*spy;
68SetSize(tsx,tsy);
69hgrpom = new PIOptMenu(this, "hgrpoptmen", bsx*2.0, bsy, spx/2, spy);
70hgrpom->SetBinding(PIBK_elastic,PIBK_elastic, PIBK_elastic,PIBK_elastic);
71hitemlist = new PIList(this, "hitemlist", bsx*2.0, tsy-3*spy-bsy, spx/2, 2*spy+bsy);
72hitemlist->SetBinding(PIBK_elastic,PIBK_elastic, PIBK_elastic,PIBK_elastic);
73// hitemlist->SetBorderWidth(2);
74mTxt = new PIText(this, "helptext", true, true, bsx*8.0, 6*bsy, bsx*2.0+1.5*spx, spy);
75// mTxt->SetMutiLineMode(true);
76mTxt->SetTextEditable(false);
77mTxt->SetText("");
78mTxt->SetBinding(PIBK_elastic,PIBK_elastic, PIBK_elastic,PIBK_elastic);
79mLab = new PILabel(this, "helpitem", bsx*4, bsy, bsx*2.5+2*spx, tsy-spy-bsy);
80mLab->SetBorderWidth(1);
81mLab->SetBinding(PIBK_elastic,PIBK_elastic, PIBK_elastic,PIBK_elastic);
82mLab->SetLabel("");
83mBut = new PIButton(this, "Close", 70, bsx, bsy, tsx-bsx*1.5-spx, tsy-spy-bsy);
84mBut->SetBinding(PIBK_elastic,PIBK_elastic, PIBK_elastic,PIBK_elastic);
85}
86
87/* --Methode-- */
88PIAHelpWind::~PIAHelpWind()
89{
90delete hgrpom;
91delete hitemlist;
92delete mTxt;
93delete mLab;
94delete mBut;
95}
96
97/* --Methode-- */
98void PIAHelpWind::Process(PIMessage msg, PIMsgHandler* sender, void* /*data*/)
99{
100PIMessage um = UserMsg(msg);
101if (((um == 77) && (ModMsg(msg) == PIMsg_Close)) || (um == 70) ) {
102 Hide();
103 return;
104 }
105else if ( (um >= 20000) && (sender == hgrpom)) { // Selection de groupe de Help
106 mTxt->SetText("");
107 mLab->SetLabel("");
108 piac->UpdateHelpList(this, um-20000);
109}
110else if ( (um > 100) && (sender == hitemlist) && (ModMsg(msg) == PIMsg_Select) ) {
111 string s = hitemlist->GetSelectionStr();
112 mTxt->SetText(piac->GetUsage(s));
113 mLab->SetLabel(s);
114 }
115}
116
117/* --Methode-- */
118void PIAHelpWind::Show()
119{
120hgrpom->SetValue(20000); // Groupe All
121mTxt->SetText("");
122mLab->SetLabel("");
123piac->UpdateHelpList(this, 0);
124PIWindow::Show();
125}
126
127// ------------------------------------------------------------
128// Bloc de commandes (Foreach, ...)
129// Classe PIACmdBloc
130// ------------------------------------------------------------
131
132class PIACmdBloc {
133public:
134 enum BType { BT_None, BT_ForeachList, BT_ForeachInt, BT_ForeachFloat };
135
136 PIACmdBloc(PIACmd* piac, PIACmdBloc* par, string& kw, vector<string>& args);
137 ~PIACmdBloc();
138 inline PIACmdBloc* Parent() { return(parent); }
139 inline bool CheckOK() { return blkok; }
140 inline void AddLine(string& line)
141 { lines.push_back(line); bloclineid.push_back(lines.size()); }
142 inline void AddBloc(PIACmdBloc* blk)
143 { blocs.push_back(blk); bloclineid.push_back(-blocs.size()); }
144 PIACmdBloc* Execute();
145protected:
146 PIACmd* piacmd;
147 PIACmdBloc* parent;
148 bool blkok; // true -> block OK
149 BType typ; // foreach , integer loop, float loop, test
150 string varname;
151 vector<string> strlist;
152 vector<string> lines;
153 vector<PIACmdBloc *> blocs;
154 vector<int> bloclineid;
155 int i1,i2,di;
156 float f1,f2,df;
157};
158
159/* --Methode-- */
160PIACmdBloc::PIACmdBloc(PIACmd* piac, PIACmdBloc* par, string& kw, vector<string>& args)
161{
162piacmd = piac;
163parent = par;
164blkok = false;
165typ = BT_None;
166i1 = 0; i2 = -1; di = 1;
167f1 = 0.; f2 = -1.; df = 1.;
168if ((args.size() < 2) || !isalpha((int)args[0][0]) ) return;
169if ((kw != "foreach") && (kw != "for")) return;
170varname = args[0]; // $CHECK$ Variable name should be checked
171//if (isalpha((int)args[1][0]) ) { This is a foreach bloc with string list
172if (kw == "foreach" ) { // This is a foreach bloc with string list
173 for(int kk=1; kk<args.size(); kk++) strlist.push_back(args[kk]);
174 typ = BT_ForeachList;
175 blkok = true;
176 }
177else { // This is an integer or float loop
178 size_t l = args[1].length();
179 size_t p = args[1].find(':');
180 size_t pp = args[1].find('.');
181 bool fl = (pp < l) ? true : false; // Float loop or integer loop
182 if (p >= l) return; // Syntaxe error
183 string a1 = args[1].substr(0, p);
184 string aa = args[1].substr(p+1);
185 p = aa.find(':');
186 string a2, a3;
187 bool hasa3 = false;
188 if (p < aa.length() ) {
189 a2 = aa.substr(0,p);
190 a3 = aa.substr(p+1);
191 hasa3 = true;
192 }
193 else a2 = aa;
194 if (fl) {
195 typ = BT_ForeachFloat;
196 blkok = true;
197 f1 = atof(a1.c_str());
198 f2 = atof(a2.c_str());
199 if (hasa3) df = atof(a3.c_str());
200 else df = 1.;
201 }
202 else {
203 typ = BT_ForeachInt;
204 blkok = true;
205 i1 = atoi(a1.c_str());
206 i2 = atoi(a2.c_str());
207 if (hasa3) di = atoi(a3.c_str());
208 else di = 1;
209 }
210 }
211}
212
213/* --Methode-- */
214PIACmdBloc::~PIACmdBloc()
215{
216for(int k=0; k<blocs.size(); k++) delete blocs[k];
217}
218
219/* --Methode-- */
220PIACmdBloc* PIACmdBloc::Execute()
221{
222// cout << " DBG * PIACmdBloc::Execute() " << typ << " - " << bloclineid.size() <<
223// " I1,I2=" << i1 << " , " << i2 << " , " << di << endl;
224string cmd;
225int k=0;
226int kj=0;
227int kk=0;
228char buff[32];
229if (typ == BT_ForeachList) // foreach string loop
230 for(k=0; k<strlist.size(); k++) {
231 cmd = "set " + varname + " '" + strlist[k] + "'";
232 piacmd->Interpret(cmd);
233 for(kj=0; kj<bloclineid.size(); kj++) {
234 kk = bloclineid[kj];
235 if (kk > 0) piacmd->Interpret(lines[kk-1]);
236 else blocs[-kk-1]->Execute();
237 }
238 }
239else if (typ == BT_ForeachInt) // Integer loop
240 for(int i=i1; i<i2; i+=di) {
241 k++;
242 if (++k > 9999) {
243 cout << ">>> Maximum PIACmdBloc loop limit (9999) -> break " << endl;
244 break;
245 }
246 sprintf(buff, " %d", i);
247 cmd = "set " + varname + buff;
248 piacmd->Interpret(cmd);
249 for(kj=0; kj<bloclineid.size(); kj++) {
250 kk = bloclineid[kj];
251 if (kk > 0) piacmd->Interpret(lines[kk-1]);
252 else blocs[-kk-1]->Execute();
253 }
254 }
255else if (typ == BT_ForeachFloat) // float loop
256 for(float f=f1; f<f2; f+=df) {
257 k++;
258 if (++k > 9999) {
259 cout << ">>> Maximum PIACmdBloc loop limit (9999) -> break " << endl;
260 break;
261 }
262 sprintf(buff, " %g", f);
263 cmd = "set " + varname + buff;
264 piacmd->Interpret(cmd);
265 for(kj=0; kj<bloclineid.size(); kj++) {
266 kk = bloclineid[kj];
267 if (kk > 0) piacmd->Interpret(lines[kk-1]);
268 else blocs[-kk-1]->Execute();
269 }
270 }
271
272return(parent);
273}
274
275// ------------------------------------------------------------
276// Classe PIACmd
277// ------------------------------------------------------------
278
279static PIACmd* curpiacmd = NULL;
280/* --Methode-- */
281PIACmd::PIACmd(NamedObjMgr* omg, PIStdImgApp* app)
282{
283mObjMgr = omg;
284mImgApp = app;
285system("cp history.pic hisold.pic");
286hist.open("history.pic");
287histon = true;
288trace = false; timing = false;
289gltimer = NULL;
290curblk = NULL;
291felevel = 0;
292mulinecmd = "";
293mulinefg = false;
294
295cmdhgrp["All"] = 0;
296cmdgrpid = 1;
297cmdhgrp["Commands"] = 1;
298helpwin = new PIAHelpWind(app, this);
299helpwin->AddHelpGroup("All", 0);
300helpwin->AddHelpGroup("Commands", 1);
301
302string kw = "piacmd";
303string usage;
304usage = ">>> (piacmd) Interpreter's keywords : \n";
305usage += " > set varname string # To set a variable, $varname \n";
306usage += " > get newvarname varname # To set a newvariable, equal to $varname \n";
307usage += " > setol varname patt # Fills varname with object list \n";
308usage += " > unset varname # clear variable definition \n";
309usage += " > echo string # output string \n";
310usage += " > alias name string # define a command alias \n";
311usage += " > readstdin varname # reads a line from stdin into $varname \n";
312usage += " > foreach varname string-list # Loop \n";
313usage += " > for varname i1:i2[:di] # Integer loop \n";
314usage += " > for varname f1:f2[:df] # Float loop \n";
315usage += " > end # end loops \n";
316usage += " > if test then # Conditional test : a == != < > <= >= b \n";
317usage += " > else # Conditional \n";
318usage += " > endif # End of conditional if bloc \n";
319usage += " > break # Delete (clears) all test and loop blocs \n";
320usage += " > return # Stops command execution from a file \n";
321usage += " > listvars # List of variable names and values \n";
322usage += " > listalias # List of alias names and values \n";
323usage += " > listcommands # List of all known commands \n";
324usage += " > exec filename # Execute commands from file \n";
325usage += " > help <command_name> # <command_name> usage info \n";
326usage += " > helpwindow # Displays help window \n";
327usage += " > timingon timingoff traceon traceoff \n";
328string grp = "Commands";
329RegisterHelp(kw, usage, grp);
330
331kw = "shell execute";
332usage = "> shell command_string # Execute shell command\n";
333usage += "> cshell command_string # Execute cshell command\n";
334usage += "---Exemples:\n";
335usage += " > shell ls\n";
336usage += " > cshell echo '$LD_LIBRARY_PATH'; map2cl -h; ls\n";
337usage += " > shell myfile.csh [arg1] [arg2] [...]\n";
338usage += " (where the first line of \"myfile.csh\" is \"#!/bin/csh\")\n";
339RegisterHelp(kw, usage, grp);
340
341basexec = new PIABaseExecutor(this, omg, app);
342fitexec = new PIAFitter(this, app);
343pawexec = new PAWExecutor(this, app);
344CxxExecutor * cxxe = new CxxExecutor(this, app);
345cxxexec = cxxe;
346
347ContModExecutor *cntxx = new ContModExecutor(this, app);//_OP_
348cntexec = cntxx; //_OP_
349FlowModExecutor *flwxx = new FlowModExecutor(this, app);//_OP_
350flwexec = flwxx; //_OP_
351
352cxxoptwin = new CxxOptionWind(app, cxxe);
353cxxexwin = new CxxExecWind(app, cxxe);
354
355AddInterpreter(this);
356curcmdi = this;
357}
358
359/* --Methode-- */
360PIACmd::~PIACmd()
361{
362hist.close();
363if (gltimer) { delete gltimer; gltimer = NULL; }
364Modmap::iterator it;
365for(it = modmap.begin(); it != modmap.end(); it++) {
366 string name = (*it).first + "_end";
367 DlModuleInitEndFunction fend = (*it).second->GetFunction(name);
368 if (fend) fend();
369 delete (*it).second;
370 }
371delete helpwin;
372delete cxxexwin;
373delete cxxoptwin;
374if (curpiacmd == this) curpiacmd = NULL;
375delete basexec;
376delete fitexec;
377delete pawexec;
378delete cxxexec;
379}
380
381/* --Methode-- */
382PIACmd* PIACmd::GetInterpreter()
383{
384return(curpiacmd);
385}
386
387/* --Methode-- */
388string PIACmd::Name()
389{
390return("piacmd");
391}
392
393/* --Methode-- */
394void PIACmd::RegisterCommand(string& keyw, string& usage, CmdExecutor * ce, string grp)
395{
396if (!ce) {
397 RegisterHelp(keyw, usage, grp);
398 return;
399 }
400int gid = CheckHelpGrp(grp);
401cmdex cme;
402cme.group = gid;
403cme.us = usage;
404cme.cex = ce;
405cmdexmap[keyw] = cme;
406}
407
408/* --Methode-- */
409void PIACmd::RegisterHelp(string& keyw, string& usage, string& grp)
410{
411int gid = CheckHelpGrp(grp);
412cmdex cme;
413cme.group = gid;
414cme.us = usage;
415cme.cex = NULL;
416helpexmap[keyw] = cme;
417}
418
419/* --Methode-- */
420int PIACmd::CheckHelpGrp(string& grp)
421{
422int gid=0;
423CmdHGroup::iterator it = cmdhgrp.find(grp);
424if (it == cmdhgrp.end()) {
425 cmdgrpid++; gid = cmdgrpid;
426 cmdhgrp[grp] = gid;
427 helpwin->AddHelpGroup(grp.c_str(), gid);
428 }
429else gid = (*it).second;
430return(gid);
431}
432
433/* --Methode-- */
434void PIACmd::UpdateHelpList(PIAHelpWind* hw, int gid)
435{
436helpwin->ClearHelpList();
437CmdExmap::iterator it;
438for(it = helpexmap.begin(); it != helpexmap.end(); it++) {
439 if ( (gid != 0) && ((*it).second.group != gid) ) continue;
440 helpwin->AddHelpItem((*it).first.c_str());
441 }
442for(it = cmdexmap.begin(); it != cmdexmap.end(); it++) {
443 if ( (gid != 0) && ((*it).second.group != gid) ) continue;
444 helpwin->AddHelpItem((*it).first.c_str());
445 }
446}
447
448/* --Methode-- */
449void PIACmd::LoadModule(string& fnameso, string& name)
450{
451PDynLinkMgr * dynlink = new PDynLinkMgr(fnameso, false);
452if (dynlink == NULL) {
453 cerr << "PIACmd/LoadModule_Error: Pb opening SO " << fnameso << endl;
454 return;
455 }
456string fname = name + "_init";
457DlModuleInitEndFunction finit = dynlink->GetFunction(fname);
458if (!finit) {
459 cerr << "PIACmd/LoadModule_Error: Pb linking " << fname << endl;
460 return;
461 }
462cout << "PIACmd/LoadModule_Info: Initialisation module" << name
463 << " " << fname << "() ..." << endl;
464finit();
465modmap[name] = dynlink;
466return;
467}
468
469/* --Methode-- */
470void PIACmd::AddInterpreter(CmdInterpreter * cl)
471{
472if (!cl) return;
473interpmap[cl->Name()] = cl;}
474
475/* --Methode-- */
476void PIACmd::SelInterpreter(string& name)
477{
478InterpMap::iterator it = interpmap.find(name);
479if (it == interpmap.end()) return;
480curcmdi = (*it).second;
481}
482
483
484
485/* Fonction */
486static string GetStringFrStdin(PIACmd* piac)
487{
488PIStdImgApp* piapp = piac->GetImgApp();
489if (piapp) {
490 PIBaseWdg* wdg = piapp->CurrentBaseWdg();
491 if (wdg) wdg->Refresh();
492#ifndef __mac__
493 /* On vide le buffer X-Window */
494 XSync(PIXDisplay(),False);
495#endif
496}
497char buff[128];
498fgets(buff, 128, stdin);
499buff[127] = '\0';
500return((string)buff);
501}
502
503/* --Methode-- */
504int PIACmd::Interpret(string& s)
505{
506int rc = 0;
507NamedObjMgr omg;
508
509// On saute de commandes vides
510size_t l;
511l = s.length();
512if (l < 1) return(0);
513
514// On enregistre les commandes
515if (histon) hist << s << endl;
516
517if (s[0] == '#') return(0); // si c'est un commentaire
518
519// Logique de gestion des lignes suite
520// un \ en derniere position indique la presence d'une ligne suite
521size_t lnb = s.find_last_not_of(' ');
522if (s[lnb] == '\\' ) { // Lignes suite ...
523 mulinefg = true;
524 mulinecmd += s.substr(0,lnb);
525 mImgApp->GetConsole()->SetPrompt("...? ");
526 return(0);
527}
528
529if (mulinefg) { // Il y avait des lignes suite
530 s = mulinecmd + s;
531 mulinecmd = "";
532 mulinefg = false;
533 const char * rprompt = (curblk == NULL) ? "Cmd> " : "for...? ";
534 mImgApp->GetConsole()->SetPrompt(rprompt);
535}
536
537// Removing leading blanks
538size_t p,q;
539
540p=s.find_first_not_of(" \t");
541if (p < l) s = s.substr(p);
542
543// >>>> Substitution d'alias (1er mot)
544CmdVarList::iterator it;
545p = 0;
546q = s.find_first_of(" \t");
547l = s.length();
548string w1 = (q < l) ? s.substr(p,q-p) : s.substr(p);
549it = mAliases.find(w1);
550if (it != mAliases.end()) {
551 s = (q < l) ? ((*it).second + s.substr(q)) : (*it).second ;
552 l = s.length();
553 p=s.find_first_not_of(" \t");
554 if (p < l) s = s.substr(p);
555 p = 0;
556 q = s.find_first_of(" ");
557 }
558
559// >>>> Separating keyword
560string toks,kw;
561if (q < l)
562 { kw = s.substr(p,q-p); toks = s.substr(q, l-q); }
563else { kw = s.substr(p,l-p); toks = ""; }
564
565// les mot-cle end else endif doivent etre le seul mot de la ligne
566if ( (kw == "end") || (kw == "else") || (kw == "endif") ) {
567 size_t ltk = toks.length();
568 if (toks.find_first_not_of(" \t") < ltk) {
569 cerr << "PIACmd::Interpret()/syntax error near end else endif \n"
570 << "line: " << s << endl;
571 return(1);
572 }
573}
574
575if (kw == "break") {
576 PIACmdBloc* curb = curblk;
577 while (curb) {
578 PIACmdBloc* dblk = curb;
579 curb = curb->Parent();
580 delete dblk;
581 }
582 testresult.clear();
583 return(0);
584}
585else if (kw == "return") return(77777);
586
587// On verifie si nous sommes dans un bloc (for , foreach)
588if (curblk != NULL) { // On est dans un bloc
589 if ( (kw == "for") || (kw == "foreach")) felevel++;
590 else if (kw == "end") felevel--;
591 if (felevel == 0) { // Il faut executer le bloc
592 PIACmdBloc* curb = curblk;
593 curblk = curb->Parent();
594 mImgApp->GetConsole()->SetPrompt("Cmd> ");
595 // cout << " *DBG* Executing bloc " << endl;
596 bool ohv = histon;
597 histon = false;
598 curb->Execute();
599 histon = ohv;
600 }
601 else curblk->AddLine(s);
602 return(0);
603}
604else if (kw == "end") {
605 cerr << "PIACmd::Interpret()/syntax error - end outside for/foreach bloc \n"
606 << "line: " << s << endl;
607 return(1);
608}
609
610// Sommes-nous dans un bloc de test if then else
611if (testresult.size() > 0) { // Nous sommes ds un bloc if
612 if (kw == "else") {
613 if ((*tresit) & 2) {
614 cerr << "PIACmd::Interpret()/syntax error - multiple else in if bloc \n"
615 << "line: " << s << endl;
616 return(1);
617 }
618 else {
619 const char * npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
620 mImgApp->GetConsole()->SetPrompt(npr);
621 (*tresit) |= 2;
622 return(0);
623 }
624 }
625 else if (kw == "endif") {
626 list<char>::iterator dbit = tresit;
627 tresit--;
628 testresult.erase(dbit);
629 const char * npr = "Cmd> ";
630 if (testresult.size() > 1) {
631 if (!((*tresit)&2))
632 npr = ((*tresit)&1) ? "if-T> " : "if-F> ";
633 else
634 npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
635 }
636 mImgApp->GetConsole()->SetPrompt(npr);
637 return(0);
638 }
639}
640else if ((kw == "else") || (kw == "endif")) {
641 cerr << "PIACmd::Interpret()/syntax error - else,endif outside if bloc \n"
642 << "line: " << s << endl;
643 return(1);
644}
645
646bool fgcont = true;
647if (testresult.size() > 0) { // Resultat de if ou else
648 list<char>::iterator it;
649 for(it=testresult.begin(); it!=testresult.end(); it++) {
650 // Si on n'est pas ds le else et le if est faux
651 if ( !((*it)&2) && !((*it)&1) ) fgcont = false;
652 // Si on est ds else et le if etait vrai !
653 if ( ((*it)&2) && ((*it)&1) ) fgcont = false;
654 if (!fgcont) break;
655 }
656}
657
658if ((!fgcont) && (kw != "if")) return(0);
659
660
661// Nous ne sommes donc pas dans un bloc .... Substitution de variables
662string s2;
663int rcs ;
664// Execution de code C++
665
666if (s[0] == '@') {
667 CxxExecutor * cxxe = dynamic_cast<CxxExecutor *>(cxxexec);
668 if (cxxe == NULL) {
669 cerr << "PIACmd::Interpret() - BUG !!! Not a CxxExecutor " << endl;
670 return(99);
671 }
672 // Sans substitution des variables $
673 if (s[1] == '@') return(cxxe->ExecuteCXX(s.substr(2)));
674 else { // AVEC substitution des variables $
675 rcs = SubstituteVars(s, s2);
676 if (rcs) return(rcs);
677 return(cxxe->ExecuteCXX(s2.substr(1)));
678 }
679}
680
681
682rcs = SubstituteVars(s, s2);
683if (rcs) return(rcs);
684
685// >>>> Separating keyword and tokens
686vector<string> tokens;
687
688q = s2.find(' ');
689l = s2.length();
690if (q < l)
691 { kw = s2.substr(0,q); toks = s2.substr(q, l-q); }
692else { kw = s2; toks = ""; }
693
694q = 0;
695while (q < l) {
696 p = toks.find_first_not_of(" \t",q+1); // au debut d'un token
697 if (p>=l) break;
698 if ( (toks[p] == '\'') || (toks[p] == '"') ) {
699 q = toks.find(toks[p],p+1);
700 if (q>=l) {
701 cerr << "PIACmd::Interpret()/Syntax Error - Unbalenced quotes " << toks[p] << '.' << endl;
702 return(2);
703 }
704 p++;
705 }
706 else {
707 q = toks.find_first_of(" \t",p); // la fin du token;
708 }
709 string token = toks.substr(p,q-p);
710 tokens.push_back(token);
711 }
712
713
714// Si c'est un for/foreach, on cree un nouveau bloc
715if ((kw == "foreach") || (kw == "for")) {
716 // cout << " *DBG* We got a foreach... " << endl;
717 PIACmdBloc* bloc = new PIACmdBloc(this, curblk, kw, tokens);
718 if (!bloc->CheckOK()) {
719 cerr << "PIACmd::Interpret() for/foreach syntax Error ! " << endl;
720 delete bloc;
721 return(1);
722 }
723 felevel++;
724 if (curblk) curblk->AddBloc(bloc);
725 else mImgApp->GetConsole()->SetPrompt("for...> ");
726 curblk = bloc;
727 // cout << " *DBG* New Bloc created ... " << endl;
728 return(0);
729 }
730else if (kw == "if") { // Un test if
731 bool restst = true;
732 int rct = EvaluateTest(tokens, s, restst);
733 if (rct) {
734 cerr << "PIACmd::Interpret() if syntax Error ! " << endl;
735 return(1);
736 }
737 char res_tst = (restst) ? 1 : 0;
738 testresult.push_back(res_tst);
739 if (testresult.size() == 1) tresit = testresult.begin();
740 else tresit++;
741 const char * npr = (restst) ? "if-T> " : "if-F> ";
742 mImgApp->GetConsole()->SetPrompt(npr);
743}
744// Execution de commandes
745else rc = ExecuteCommandLine(kw, tokens, toks);
746return(rc);
747
748// cout << "PIACmd::Do() DBG KeyW= " << kw << " NbArgs= " << tokens.size() << endl;
749// for(int ii=0; ii<tokens.size(); ii++)
750// cout << "arg[ " << ii << " ] : " << tokens[ii] << endl;
751
752}
753
754/* --Methode-- */
755int PIACmd::SubstituteVars(string & s, string & s2)
756// Variable substitution
757{
758NamedObjMgr omg;
759
760size_t p,q,q2,l;
761
762s2="";
763p = 0;
764l = s.length();
765string vn;
766while (p < l) {
767 q = s.find('$',p);
768 if (q > l) break;
769 q2 = s.find('\'',p);
770 if ((q2 < l) && (q2 < q)) { // On saute la chaine delimitee par ' '
771 q2 = s.find('\'',q2+1);
772 if (q2 >= l) {
773 cerr << " Syntax error - Unbalenced quotes !!! " << endl;
774 return(1);
775 }
776 s2 += s.substr(p, q2-p+1);
777 p = q2+1; continue;
778 }
779 // cout << "DBG: " << s2 << " p= " << p << " q= " << q << " L= " << l << endl;
780 if ((q>0) && (s[q-1] == '\\')) { // Escape character \$
781 s2 += (s.substr(p,q-1-p) + '$') ; p = q+1;
782 continue;
783 }
784 if (q >= l-1) {
785 cerr << " Syntax error - line ending with $ !!! " << endl;
786 return(2);
787 }
788 vn = "";
789 if ( s[q+1] == '{' ) { // Variable in the form ${name}
790 q2 = s.find('}',q+1);
791 if (q2 >= l) {
792 cerr << " Syntax error - Unbalenced brace {} !!! " << endl;
793 return(3);
794 }
795 vn = s.substr(q+2,q2-q-2);
796 q2++;
797 }
798 else if ( s[q+1] == '[' ) { // Variable in the form $[varname] -> This is $$varname
799 q2 = s.find(']',q+1);
800 if (q2 >= l) {
801 cerr << " Syntax error - Unbalenced brace [] !!! " << endl;
802 return(4);
803 }
804 vn = s.substr(q+2,q2-q-2);
805 if ( (vn.length() < 1) || (!omg.HasVar(vn)) ) {
806 cerr << " Error: Undefined variable " << vn << " ! " << endl;
807 return(5);
808 }
809 vn = omg.GetVar(vn);
810 q2++;
811 }
812 else {
813 q2 = s.find_first_of(" .:+-*/,[](){}&|!$\"'",q+1);
814 if (q2 > l) q2 = l;
815 vn = s.substr(q+1, q2-q-1);
816 }
817 if ( (vn.length() < 1) || (!omg.HasVar(vn)) ) {
818 cerr << " Error: Undefined variable " << vn << " ! " << endl;
819 return(5);
820 }
821 s2 += (s.substr(p, q-p) + omg.GetVar(vn));
822 p = q2;
823 }
824if (p < l) s2 += s.substr(p);
825
826p = s2.find_first_not_of(" \t");
827if (p < l) s2 = s2.substr(p);
828
829return(0);
830}
831
832/* --Methode-- */
833int PIACmd::EvaluateTest(vector<string> & args, string & line, bool & res)
834{
835 res = true;
836 if ((args.size() < 4) || (args[3] != "then")) return(1);
837 if (args[1] == "==") res = (args[0] == args[2]);
838 else if (args[1] == "!=") res = (args[0] != args[2]);
839 else if (args[1] == "<")
840 res = (atof(args[0].c_str()) < atof(args[2].c_str()));
841 else if (args[1] == ">")
842 res = (atof(args[0].c_str()) > atof(args[2].c_str()));
843 else if (args[1] == "<=")
844 res = (atof(args[0].c_str()) <= atof(args[2].c_str()));
845 else if (args[1] == ">=")
846 res = (atof(args[0].c_str()) >= atof(args[2].c_str()));
847 else return(2);
848 return(0);
849}
850
851/* --Methode-- */
852int PIACmd::ExecuteCommandLine(string & kw, vector<string> & tokens, string & toks)
853{
854int rc = 0;
855NamedObjMgr omg;
856
857// >>>>>>>>>>> Commande d'interpreteur
858if (kw == "helpwindow") ShowHelpWindow();
859else if (kw == "help") {
860 if (tokens.size() > 0) cout << GetUsage(tokens[0]) << endl;
861 else {
862 string kwh = "piacmd";
863 cout << GetUsage(kwh) << endl;
864 }
865 }
866
867else if (kw == "set") {
868 if (tokens.size() < 2) { cout << "PIACmd::Interpret() Usage: set varname string" << endl; return(0); }
869 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
870 cerr << "PIACmd::Interpret()/Error Variable name should start with alphabetic" << endl;
871 return(0);
872 }
873 // string xx = tokens[1];
874 // for (int kk=2; kk<tokens.size(); kk++) xx += (' ' + tokens[kk] );
875 omg.SetVar(tokens[0], tokens[1]);
876 }
877
878else if (kw == "getvar") {
879 if (tokens.size() < 2) { cout << "PIACmd::Interpret() Usage: getvar newvarname varname" << endl; return(0); }
880 if (!omg.HasVar(tokens[1])) {
881 cerr << "Error - No " << tokens[1] << " Variable " << endl;
882 return(0);
883 }
884 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
885 cerr << "PIACmd::Interpret()/Error Variable name should start with alphabetic" << endl;
886 return(0);
887 }
888 omg.SetVar(tokens[0], omg.GetVar(tokens[1]) );
889 }
890
891else if (kw == "alias") {
892 if (tokens.size() < 2) { cout << "PIACmd::Interpret() Usage: alias aliasname string" << endl; return(0); }
893 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
894 cerr << "PIACmd::Interpret()/Error alias name should start with alphabetic" << endl;
895 return(0);
896 }
897 string xx = tokens[1];
898 for (int kk=2; kk<tokens.size(); kk++) xx += (' ' + tokens[kk]);
899 mAliases[tokens[0]] = xx;
900 }
901
902else if (kw == "setol") {
903 if (tokens.size() < 2) { cout << "PIACmd::Interpret() Usage: setol varname objnamepattern" << endl; return(0); }
904 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
905 cerr << "PIACmd::Interpret()/Error Variable name should start with alphabetic" << endl;
906 return(0);
907 }
908 vector<string> ol;
909 mObjMgr->GetObjList(tokens[1], ol);
910 string vol;
911 if (ol.size() < 1) vol = "";
912 else {
913 vol = ol[0];
914 for (int kk=1; kk<ol.size(); kk++) vol += (' ' + ol[kk]);
915 }
916 omg.SetVar(tokens[0], vol);
917 }
918else if (kw == "unset") {
919 if (tokens.size() < 1) { cout << "PIACmd::Interpret() Usage: unset varname" << endl; return(0); }
920 if (omg.HasVar(tokens[0])) omg.DeleteVar(tokens[0]) ;
921 else cerr << "PIACmd::Interpret() No variable with name " << tokens[0] << endl;
922 }
923else if (kw == "echo") {
924 for (int ii=0; ii<tokens.size(); ii++)
925 cout << tokens[ii] << " " ;
926 cout << endl;
927 }
928else if (kw == "readstdin") {
929 if (tokens.size() < 1) { cout << "PIACmd::Interpret() Usage: readstdin varname" << endl; return(0); }
930 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
931 cerr << "PIACmd::Interpret()/Error Variable name should start with alphabetic" << endl;
932 return(0);
933 }
934 mImgApp->GetConsole()->AddStr(">>> Reading From StdIn \n", PIVA_Magenta);
935 cout << tokens[0] << " ? " << endl;
936 omg.SetVar(tokens[0], GetStringFrStdin(this) );
937 }
938
939else if (kw == "listvars") {
940 cout << "PIACmd::Interpret() Variable List , VarName = Value \n";
941 DVList& varlist = omg.GetVarList();
942 DVList::ValList::const_iterator it;
943 string value;
944 for(it = varlist.Begin(); it != varlist.End(); it++) {
945#ifdef SANS_EVOLPLANCK
946 MuTyV mtv = (*it).second;
947 value = (string)(mtv);
948#else
949 value = (string)((*it).second.elval);
950#endif
951 cout << (*it).first << " = " << value << "\n";
952 }
953 cout << endl;
954 }
955else if (kw == "listalias") {
956 cout << "PIACmd::Interpret() Alias List , AliasName = Value \n";
957 CmdVarList::iterator it;
958 for(it = mAliases.begin(); it != mAliases.end(); it++)
959 cout << (*it).first << " = " << (*it).second << "\n";
960 cout << endl;
961 }
962else if (kw == "listcommands") {
963 cout << "---- PIACmd::Interpret() Command Variable List ----- \n";
964 CmdExmap::iterator it;
965 int kc = 0;
966 for(it = cmdexmap.begin(); it != cmdexmap.end(); it++) {
967 cout << (*it).first << " ";
968 kc++;
969 if (kc >= 5) { cout << "\n"; kc = 0; }
970 }
971 cout << endl;
972 }
973else if (kw == "traceon") { cout << "PIACmd::Interpret() -> Trace ON mode " << endl; trace = true; }
974else if (kw == "traceoff") { cout << "PIACmd::Interpret() -> Trace OFF mode " << endl; trace = false; }
975else if (kw == "timingon") {
976 cout << "PIACmd::Interpret() -> Timing ON mode " << endl;
977 if (gltimer) delete gltimer; gltimer = new Timer("PIA-CmdInterpreter "); timing = true;
978 }
979else if (kw == "timingoff") {
980 cout << "PIACmd::Interpret() -> Timing OFF mode " << endl;
981 if (gltimer) delete gltimer; gltimer = NULL; timing = false;
982 }
983else if (kw == "exec") {
984 if (tokens.size() < 1) { cout << "PIACmd::Interpret() Usage: exec filename" << endl; return(0); }
985 ExecFile(tokens[0], tokens);
986 }
987else if (kw == "shell") {
988 if (tokens.size() < 1) { cout << "PIACmd::Interpret() Usage: shell cmdline" << endl; return(0); }
989 string cmd;
990 for (int ii=0; ii<tokens.size(); ii++)
991 cmd += (tokens[ii] + ' ');
992 system(cmd.c_str());
993 }
994else if (kw == "cshell") {
995 if(tokens.size()<1) {cout<<"PIACmd::Interpret() Usage: cshell cmdline"<<endl; return(0);}
996 string cmd="";
997 for(int ii=0;ii<tokens.size();ii++) cmd+=(tokens[ii]+' ');
998 CShellExecute(cmd);
999 }
1000
1001// Execution d'une commande enregistree
1002else rc = ExecuteCommand(kw, tokens, toks);
1003
1004if (timing) gltimer->Split();
1005return(rc);
1006}
1007
1008/* --Methode-- */
1009int PIACmd::ParseLineExecute(string& line)
1010{
1011vector<string> tokens;
1012
1013if (line.length() < 1) return(0);
1014
1015string toks,kw;
1016size_t p = line.find_first_not_of(" ");
1017line = line.substr(p);
1018p = 0;
1019size_t q = line.find_first_of(" ");
1020size_t l = line.length();
1021
1022if (q < l)
1023 { kw = line.substr(p,q-p); toks = line.substr(q, l-q); }
1024else { kw = line.substr(p,l-p); toks = ""; }
1025
1026q = 0;
1027while (q < l) {
1028 p = toks.find_first_not_of(" ",q+1); // au debut d'un token
1029 if (p>=l) break;
1030 q = toks.find_first_of(" ",p); // la fin du token;
1031 string token = toks.substr(p,q-p);
1032 tokens.push_back(token);
1033 }
1034
1035return(ExecuteCommand(kw, tokens, toks));
1036}
1037
1038/* --Methode-- */
1039int PIACmd::ExecuteCommand(string& keyw, vector<string>& args, string& toks)
1040{
1041 int rc = -1;
1042 CmdExmap::iterator it = cmdexmap.find(keyw);
1043 if (it == cmdexmap.end()) cout << "No such command : " << keyw << " ! " << endl;
1044 else {
1045 if ((*it).second.cex) rc = (*it).second.cex->Execute(keyw, args, toks);
1046 else cout << "Dont know how to execute " << keyw << " ? " << endl;
1047 }
1048 return(rc);
1049}
1050
1051/* --Methode-- */
1052int PIACmd::ExecFile(string& file, vector<string>& args)
1053{
1054char line_buff[512];
1055FILE *fip;
1056
1057if ( (fip = fopen(file.c_str(),"r")) == NULL ) {
1058 if (file.find('.') >= file.length()) {
1059 cout << "PIACmd::Exec(): Error opening file " << file << endl;
1060 file += ".pic";
1061 cout << " Trying file " << file << endl;
1062 fip = fopen(file.c_str(),"r");
1063 }
1064 }
1065
1066if(fip == NULL) {
1067 cerr << "PIACmd::Exec() Error opening file " << file << endl;
1068 hist << "##! PIACmd::Exec() Error opening file " << file << endl;
1069 return(0);
1070 }
1071
1072// hist << "### Executing commands from " << file << endl;
1073
1074// Setting $0 ... $99 variables
1075int k;
1076char buff[32];
1077// First, we clear all previous values
1078NamedObjMgr omg;
1079string vn="#";
1080omg.DeleteVar(vn);
1081for(k=0; k<99; k++) {
1082 sprintf(buff,"%d",k);
1083 vn = buff;
1084 omg.DeleteVar(vn);
1085 }
1086// We then set them
1087string vval;
1088vn="#";
1089sprintf(buff,"%d",(int)args.size());
1090omg.SetVar(vn, buff);
1091for(k=0; k<args.size(); k++) {
1092 sprintf(buff,"%d",k);
1093 vn = buff;
1094 omg.SetVar(vn, args[k]);
1095 }
1096
1097if (trace) {
1098 mImgApp->GetConsole()->AddStr("### Executing commands from ", PIVA_Magenta);
1099 mImgApp->GetConsole()->AddStr(file.c_str(), PIVA_Magenta);
1100 mImgApp->GetConsole()->AddStr("\n", PIVA_Magenta);
1101 }
1102
1103bool ohv = histon;
1104histon = false;
1105while (fgets(line_buff,511,fip) != NULL)
1106 {
1107 if (trace) mImgApp->GetConsole()->AddStr(line_buff, PIVA_Magenta);
1108 line_buff[strlen(line_buff)-1] = '\0'; /* LF/CR de la fin */
1109 string line(line_buff);
1110 if (Interpret(line) == 77777) break;
1111 }
1112histon = ohv;
1113
1114// hist << "### End of Exec( " << file << " ) " << endl;
1115if (trace) {
1116 mImgApp->GetConsole()->AddStr("### End of Exec( ", PIVA_Magenta);
1117 mImgApp->GetConsole()->AddStr(file.c_str(), PIVA_Magenta);
1118 mImgApp->GetConsole()->AddStr(" ) \n", PIVA_Magenta);
1119 }
1120
1121return(0);
1122}
1123
1124/* --Methode-- */
1125int PIACmd::CShellExecute(string cmd)
1126{
1127 if(cmd.size()<=0) return -1;
1128
1129 NamedObjMgr omg;
1130 string fname = omg.GetTmpDir(); fname += "cshell_exec_pia.csh";
1131
1132 string cmdrm = "rm -f " + fname;
1133 system(cmdrm.c_str());
1134
1135 FILE *fip = fopen(fname.c_str(),"w");
1136 if(fip==NULL) {
1137 cout << "PIACmd/CShellExecute_Error: fopen("<<fname<<") failed"<<endl;
1138 return -2;
1139 }
1140 fprintf(fip,"#!/bin/csh\n\n");
1141 fprintf(fip,"%s\n",cmd.c_str());
1142 fprintf(fip,"\nexit 0\n");
1143 fclose(fip);
1144
1145 cmd = "csh "; cmd += fname;
1146 system(cmd.c_str());
1147
1148 system(cmdrm.c_str());
1149
1150 return 0;
1151}
1152
1153static string* videstr = NULL;
1154/* --Methode-- */
1155string& PIACmd::GetUsage(const string& kw)
1156{
1157bool fndok = false;
1158CmdExmap::iterator it = cmdexmap.find(kw);
1159if (it == cmdexmap.end()) {
1160 it = helpexmap.find(kw);
1161 if (it != helpexmap.end()) fndok = true;
1162 }
1163 else fndok = true;
1164if (fndok) return( (*it).second.us );
1165// Keyword pas trouve
1166if (videstr == NULL) videstr = new string("");
1167*videstr = "Nothing known about " + kw + " ?? ";
1168return(*videstr);
1169
1170}
1171
1172/* --Methode-- */
1173void PIACmd::ShowHelpWindow()
1174{
1175helpwin->Show();
1176}
1177
1178/* --Methode-- */
1179void PIACmd::ShowCxxOptionWindow()
1180{
1181cxxoptwin->Show();
1182}
1183
1184/* --Methode-- */
1185void PIACmd::ShowCxxExecWindow()
1186{
1187cxxexwin->Show();
1188}
1189
1190/* --Methode-- */
1191void PIACmd::HelptoLaTex(string const & fname)
1192{
1193FILE *fip;
1194if ((fip = fopen(fname.c_str(), "w")) == NULL) {
1195 cout << "PIACmd::HelptoLaTex_Error: fopen( " << fname << endl;
1196 return;
1197 }
1198
1199fputs("% ----- Liste des groupes de Help ----- \n",fip);
1200fputs("List of {\\bf piapp} on-line Help groups: \n", fip);
1201fputs("\\begin{itemize} \n",fip);
1202CmdHGroup::iterator it;
1203for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++)
1204 fprintf(fip,"\\item {\\bf %s } (p. \\pageref{%s}) \n",
1205 (*it).first.c_str(), (*it).first.c_str());
1206
1207fputs("\\end{itemize} \n",fip);
1208
1209fputs("\\newpage \n",fip);
1210
1211CmdExmap::iterator ite;
1212fputs("% ----- Liste de toutes les commandes ----- \n",fip);
1213fputs("\\begin{center} \n ", fip);
1214fputs("\\rule{2cm}{1mm} List of {\\bf piapp} Help items \\rule{2cm}{1mm} \n", fip);
1215fputs("\n \n \\vspace{5mm} \n",fip);
1216fputs("\\begin{tabular}{llllll} \n", fip);
1217int kt = 0;
1218for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
1219 fprintf(fip,"%s & p. \\pageref{%s} ", (*ite).first.c_str(), (*ite).first.c_str() );
1220 kt++;
1221 if (kt < 3) fputs(" & ", fip);
1222 else { fputs(" \\\\ \n", fip); kt = 0; }
1223 }
1224if (kt == 1) fputs(" & & & \\\\ \n", fip);
1225else if (kt == 2) fputs(" & \\\\ \n", fip);
1226fputs("\\end{tabular} \n", fip);
1227fputs("\\end{center} \n", fip);
1228fputs("\n \n \\vspace{1cm} \n",fip);
1229
1230fputs("\\begin{center} \n ", fip);
1231fputs("\\rule{2cm}{1mm} List of {\\bf piapp} Commands \\rule{2cm}{1mm} \n", fip);
1232fputs("\n \n \\vspace{5mm} \n",fip);
1233fputs("\\begin{tabular}{llllll} \n", fip);
1234kt = 0;
1235for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
1236 fprintf(fip,"%s & p. \\pageref{%s} ", (*ite).first.c_str(), (*ite).first.c_str() );
1237 kt++;
1238 if (kt < 3) fputs(" & ", fip);
1239 else { fputs(" \\\\ \n", fip); kt = 0; }
1240 }
1241if (kt == 1) fputs(" & & & \\\\ \n", fip);
1242else if (kt == 2) fputs(" & \\\\ \n", fip);
1243fputs("\\end{tabular} \n", fip);
1244fputs("\\end{center} \n", fip);
1245// fputs("\\newline \n",fip);
1246
1247fputs("% ----- Liste des commandes dans chaque groupe ----- \n",fip);
1248fputs("\\newpage \n",fip);
1249int gid;
1250for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
1251 gid = (*it).second;
1252 if (gid == 0) continue;
1253 fprintf(fip,"\\subsection{%s} \\label{%s} \n",
1254 (*it).first.c_str(), (*it).first.c_str());
1255 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
1256 if ((*ite).second.group != gid) continue;
1257 fprintf(fip,"{ \\Large $ \\star \\star \\star $ } Help item {\\bf \\Large %s } \\label{%s} \n",
1258 (*ite).first.c_str(), (*ite).first.c_str());
1259 fputs("\\begin{verbatim} \n",fip);
1260 fprintf(fip,"%s\n", (*ite).second.us.c_str());
1261 fputs("\\end{verbatim} \n",fip);
1262 }
1263 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
1264 if ((*ite).second.group != gid) continue;
1265 fprintf(fip,"{ \\Large $ \\star \\star \\star $ } Command {\\bf \\Large %s } \\label{%s} \n",
1266 (*ite).first.c_str(), (*ite).first.c_str());
1267 fputs("\\begin{verbatim} \n",fip);
1268 fprintf(fip,"%s\n", (*ite).second.us.c_str());
1269 fputs("\\end{verbatim} \n",fip);
1270 }
1271}
1272
1273fclose(fip);
1274return;
1275}
1276
1277
1278
Note: See TracBrowser for help on using the repository browser.