source: Sophya/trunk/SophyaLib/SysTools/commander.cc@ 2914

Last change on this file since 2914 was 2914, checked in by cmv, 20 years ago

add listvar==listvars pour back-compat + erreur dans help cmv 17/02/06

File size: 63.6 KB
Line 
1#include "sopnamsp.h"
2#include "commander.h"
3#include <stdio.h>
4#include <stdlib.h>
5#include <unistd.h>
6#include <ctype.h>
7#include <math.h>
8
9#include "strutil.h"
10#include "strutilxx.h"
11#include "cexpre.h"
12#include "rpneval.h"
13#include "srandgen.h"
14#include "zthread.h"
15
16
17namespace SOPHYA {
18
19// Differents code de retour specifiques
20#define CMD_RETURN_RC 99900
21#define CMD_BREAK_RC 99990
22#define CMD_BREAKEXE_RC 99999
23
24// ------------------------------------------------------------
25// Bloc de commandes (Foreach, ...)
26// Classe CommanderBloc
27// ------------------------------------------------------------
28/*!
29 \internal
30 \class SOPHYA::CommanderBloc
31 \ingroup SysTools
32 Class for internal use by class Commander to handle loops
33*/
34class CommanderBloc {
35public:
36 enum BType { BT_None, BT_ForeachList, BT_ForeachInt, BT_ForeachFloat,
37 BT_ForeachLineInFile };
38
39 CommanderBloc(Commander* piac, CommanderBloc* par, string& kw, vector<string>& args);
40 ~CommanderBloc();
41 inline CommanderBloc* Parent() { return(parent); }
42 inline bool CheckOK() { return blkok; }
43 inline void AddLine(string& line)
44 { lines.push_back(line); bloclineid.push_back(lines.size()); }
45 void AddLine(string& line, string& kw);
46 inline void AddBloc(CommanderBloc* blk)
47 { blocs.push_back(blk); bloclineid.push_back(-blocs.size()); }
48
49 // Execution complete du bloc (boucle)
50 int Execute();
51 // Execution pour un element de bloc
52 int ExecuteOnce(string& lvv);
53
54 inline int& TestLevel() { return testlevel; }
55 inline int& LoopLevel() { return looplevel; }
56 inline bool CheckBloc()
57 { return ((testlevel == 0)&&(looplevel == 0)&&(!scrdef)); }
58
59protected:
60 Commander* _commander;
61 CommanderBloc* parent;
62 bool blkok; // true -> block OK
63 BType typ; // foreach , integer loop, float loop, test
64 string varname;
65 string filename; // forinfile bloc
66 vector<string> strlist;
67 vector<string> lines;
68 vector<CommanderBloc *> blocs;
69 vector<int> bloclineid;
70 int i1,i2,di;
71 float f1,f2,df;
72 int testlevel; // niveau d'imbrication des if
73 int looplevel; // niveau d'imbrication des for/foreach
74 bool scrdef; // true -> commande defscript ds for/foreach
75};
76
77/* --Methode-- */
78CommanderBloc::CommanderBloc(Commander* piac, CommanderBloc* par, string& kw, vector<string>& args)
79{
80_commander = piac;
81parent = par;
82blkok = false;
83typ = BT_None;
84i1 = 0; i2 = -1; di = 1;
85f1 = 0.; f2 = -1.; df = 1.;
86testlevel = looplevel = 0;
87scrdef = false;
88
89if ((args.size() < 2) || !isalpha((int)args[0][0]) ) return;
90if ((kw != "foreach") && (kw != "for") && (kw != "forinfile")) return;
91if (!piac->CheckVarName(args[0])) return;
92varname = args[0];
93
94//if (isalpha((int)args[1][0]) ) { This is a foreach bloc with string list
95if (kw == "forinfile") {
96 filename = args[1];
97 typ = BT_ForeachLineInFile;
98 blkok = true;
99}
100else if (kw == "foreach" ) { // This is a foreach bloc with string list
101 if ( (args[1] == "(") && (args[args.size()-1] == ")") ) {
102 // foreach varname ( w1 w2 w3 ... )
103 for(int kk=2; kk<args.size()-1; kk++) strlist.push_back(args[kk]);
104 }
105 else {
106 // foreach varname WordVectorName
107 if (!piac->GetVar(args[1], strlist)) return;
108 }
109 if (strlist.size() < 1) return;
110 typ = BT_ForeachList;
111 blkok = true;
112}
113else { // This is an integer or float loop
114 size_t l = args[1].length();
115 size_t p = args[1].find(':');
116 size_t pp = args[1].find('.');
117 bool fl = (pp < l) ? true : false; // Float loop or integer loop
118 if (p >= l) return; // Syntaxe error
119 string a1 = args[1].substr(0, p);
120 string aa = args[1].substr(p+1);
121 p = aa.find(':');
122 string a2, a3;
123 bool hasa3 = false;
124 if (p < aa.length() ) {
125 a2 = aa.substr(0,p);
126 a3 = aa.substr(p+1);
127 hasa3 = true;
128 }
129 else a2 = aa;
130 if (fl) {
131 typ = BT_ForeachFloat;
132 blkok = true;
133 f1 = atof(a1.c_str());
134 f2 = atof(a2.c_str());
135 if (hasa3) df = atof(a3.c_str());
136 else df = 1.;
137 }
138 else {
139 typ = BT_ForeachInt;
140 blkok = true;
141 i1 = atoi(a1.c_str());
142 i2 = atoi(a2.c_str());
143 if (hasa3) di = atoi(a3.c_str());
144 else di = 1;
145 }
146 }
147}
148
149/* --Methode-- */
150CommanderBloc::~CommanderBloc()
151{
152for(int k=0; k<blocs.size(); k++) delete blocs[k];
153}
154
155/* --Methode-- */
156void CommanderBloc::AddLine(string& line, string& kw)
157{
158 AddLine(line);
159 if (kw == "if") testlevel++;
160 else if (kw == "endif") testlevel--;
161 else if ((kw == "for") || (kw == "foreach")) looplevel++;
162 else if (kw == "end") looplevel--;
163 else if (kw == "defscript") scrdef = true;
164}
165
166/* --Methode-- */
167int CommanderBloc::Execute()
168{
169int k=0;
170char buff[32];
171int rcc = 0;
172
173int mxloop = _commander->GetMaxLoopLimit();
174
175if (typ == BT_ForeachLineInFile) { // foreach line in file loop
176 ifstream is(filename.c_str());
177 char buff[256];
178 string line;
179 while (!is.eof()) {
180 /* Reza, Juin 2005 : Remplace par getline(istream, string) - plus sur
181 is.getline(buff, 256); line += buff; */
182 rcc = 0;
183 line = "";
184 getline(is,line);
185 if (is.good() || is.eof()) {
186 rcc = ExecuteOnce(line);
187 if (rcc == CMD_BREAKEXE_RC) return rcc;
188 else if (rcc == CMD_BREAK_RC) break;
189 }
190 }
191}
192else if (typ == BT_ForeachList) { // foreach string loop
193 for(k=0; k<strlist.size(); k++) {
194 rcc = ExecuteOnce(strlist[k]);
195 if (rcc == CMD_BREAKEXE_RC) return rcc;
196 else if (rcc == CMD_BREAK_RC) break;
197 }
198}
199else if (typ == BT_ForeachInt) { // Integer loop
200 for(int i=i1; i<i2; i+=di) {
201 k++;
202 if ((mxloop>0) && (k > mxloop)) {
203 cout << ">>> Maximum CommanderBloc loop limit ("<< mxloop << ") -> break " << endl;
204 break;
205 }
206 sprintf(buff, "%d", i);
207 string lvv = buff;
208 rcc = ExecuteOnce(lvv);
209 if (rcc == CMD_BREAKEXE_RC) return rcc;
210 else if (rcc == CMD_BREAK_RC) break;
211 }
212}
213else if (typ == BT_ForeachFloat) { // float loop
214 for(double f=f1; f<f2; f+=df) {
215 k++;
216 if ((mxloop>0) && (k > mxloop)) {
217 cout << ">>> Maximum CommanderBloc loop limit ("<< mxloop << ") -> break " << endl;
218 break;
219 }
220 sprintf(buff, "%g", f);
221 string lvv = buff;
222 rcc = ExecuteOnce(lvv);
223 if (rcc == CMD_BREAKEXE_RC) return rcc;
224 else if (rcc == CMD_BREAK_RC) break;
225 }
226}
227return(rcc);
228}
229
230/* --Methode-- */
231int CommanderBloc::ExecuteOnce(string& lvv)
232{
233 int kj=0;
234 int kk=0;
235 int rcc = 0;
236 _commander->SetVar(varname, lvv);
237 for(kj=0; kj<bloclineid.size(); kj++) {
238 rcc = 0;
239 kk = bloclineid[kj];
240 if (kk > 0)
241 rcc = _commander->Interpret(lines[kk-1]);
242 else
243 rcc = blocs[-kk-1]->Execute();
244 if (rcc == CMD_BREAKEXE_RC) return (rcc);
245 if (rcc == CMD_BREAK_RC) break;
246 }
247 return rcc;
248}
249
250// ---------------------------------------------------------------
251// Classe CommanderScript
252// Definition et execution d'un script de Commander
253// script : Une liste de commande Commander - Lors de l'execution,
254// les variables-argument $# $0 $1 sont definies.
255// ---------------------------------------------------------------
256
257/*!
258 \internal
259 \class SOPHYA::CommanderScript
260 \ingroup SysTools
261 Class for internal use by class Commander to handle functions
262 or scripts
263*/
264
265class CommanderScript {
266public:
267 CommanderScript(Commander* piac, string const& name, string const& comm);
268 virtual ~CommanderScript();
269
270 void AddLine(string& line, string& kw);
271 virtual int Execute(vector<string>& args);
272
273 inline string& Name() { return mName; }
274 inline string& Comment() { return mComm; }
275 inline int& TestLevel() { return testlevel; }
276 inline int& LoopLevel() { return looplevel; }
277 inline bool CheckScript()
278 { return ((testlevel == 0)&&(looplevel == 0)&&(!scrdef)&&fgok); }
279
280protected:
281 Commander* _commander;
282 string mName;
283 string mComm;
284 vector<string> lines;
285 int testlevel; // niveau d'imbrication des if
286 int looplevel; // niveau d'imbrication des for/foreach
287 bool scrdef; // true -> commande defscript ds for/foreach
288 bool fgok; // Script name OK
289
290};
291
292/* --Methode-- */
293CommanderScript::CommanderScript(Commander* piac, string const& name,
294 string const& comm)
295{
296_commander = piac;
297testlevel = looplevel = 0;
298scrdef = false;
299mName = name;
300if (!isalpha(name[0])) fgok = false;
301else fgok = true;
302mComm = comm;
303}
304
305/* --Methode-- */
306CommanderScript::~CommanderScript()
307{
308}
309
310/* --Methode-- */
311void CommanderScript::AddLine(string& line, string& kw)
312{
313 if (kw == "if") testlevel++;
314 else if (kw == "endif") testlevel--;
315 else if ((kw == "for") || (kw == "foreach")) looplevel++;
316 else if (kw == "end") looplevel--;
317 else if (kw == "defscript") scrdef = true;
318 lines.push_back(line);
319}
320
321/* --Methode-- */
322int CommanderScript::Execute(vector<string>& args)
323{
324 int rcc;
325 if (!CheckScript()) return(-1);
326 cout << " CommanderScript::Execute() - Executing script " << Name() << endl;
327 for(int k=0; k<lines.size(); k++) {
328 rcc = _commander->Interpret(lines[k]);
329 if ( (rcc == CMD_BREAKEXE_RC) || (rcc == CMD_RETURN_RC) ) break;
330 }
331 return(rcc);
332}
333
334
335// ------------------------------------------------------------
336// Classe CommandExeThr
337// ------------------------------------------------------------
338/*!
339 \internal
340 \class SOPHYA::CommandExeThr
341 \ingroup SysTools
342 Class for internal use by class Commander for command execution in separate threads.
343*/
344class CommandExeThr : public ZThread {
345public:
346 CommandExeThr(uint_8 id, CmdExecutor * cmdex, string& keyw,
347 vector<string>& args, string& toks);
348 virtual void run();
349 inline uint_8 Id() { return _id; }
350 inline bool IfDone() { return _fgdone; }
351 inline string& Tokens() { return _toks; }
352 inline string& Keyword() { return _keyw; }
353protected:
354 uint_8 _id;
355 CmdExecutor * _cmdex;
356 string _keyw, _toks;
357 vector<string> _args;
358 bool _fgdone;
359};
360
361/* --Methode-- */
362CommandExeThr::CommandExeThr(uint_8 id, CmdExecutor * cmdex, string& keyw,
363 vector<string>& args, string& toks)
364{
365 _id = id;
366 _cmdex = cmdex;
367 _keyw = keyw;
368 if (args.size() > 1)
369 for(size_t k=0; k<args.size()-1; k++) _args.push_back(args[k]);
370 _toks = toks;
371 for(size_t k=_toks.size()-1; k>0; k--)
372 if (_toks[k] == '&') { _toks[k] = ' '; break; }
373 _fgdone = false;
374}
375
376/* --Methode-- */
377void CommandExeThr::run()
378{
379 int rc = _cmdex->Execute(_keyw, _args, _toks);
380 _fgdone = true;
381 setRC(rc);
382}
383
384// ------------------------------------------------------------
385// Classe Commander
386// ------------------------------------------------------------
387typedef void (* DlModuleInitEndFunction) ();
388
389/*!
390 \class Commander
391 \ingroup SysTools
392 \brief Simple command interpreter
393
394 This Simple command interpreter with c-shell like syntax
395 can be used to add scripting capabilities
396 to applications.
397
398 Although the interpreter has many limitations compared to
399 c-shell, or Tcl , it provides some interesting possibilities:
400
401 - Extended arithmetic operations (c-like and RPN)
402 - Simple and vector variables
403 - Script definition
404 - Dynamic Load
405
406 \sa CmdExecutor CExpressionEvaluator RPNExpressionEvaluator
407
408 Usage example:
409 \code
410 #include "commander.h"
411 ...
412 Commander cmd;
413 char* ss[3] = {"foreach f ( AA bbb CCCC ddddd )", "echo $f" , "end"};
414 for(int k=0; k<3; k++) {
415 string line = ss[k];
416 cmd.Interpret(line);
417 }
418 \endcode
419*/
420
421#define _MAGENTA_ 1
422
423static Commander* cur_commander = NULL;
424/* --Methode-- */
425//! Default constructor. Initializes variable list and copies \c history.pic to \c hisold.pic
426Commander::Commander()
427{
428system("cp history.pic hisold.pic");
429hist.open("history.pic");
430histon = true;
431trace = false; timing = false;
432gltimer = NULL;
433felevel = 0;
434
435mulinecmd = "";
436mulinefg = false;
437spromptmul = "Cmd> ";
438SetCurrentPrompt(spromptmul);
439SetDefaultPrompt(spromptmul);
440curscript = NULL;
441
442_xstatus = 0;
443 _retstr = "";
444
445// Controle du flot d'execution
446 fgexebrk = false;
447
448CmdBlks.push(NULL);
449list<char> xtx;
450TestsStack.push(xtx);
451curtestresult = true;
452
453// Pour la numerotation et l'identification des threads
454ThrId = 0;
455
456// Numero de help-groupe courant - Le premier groupe ajoute aura un gid = 1
457// gid = 0 n'existe pas : c'est le groupe de toutes les commandes
458cmdgrpid = 0;
459
460string grp = "Commander";
461string gdesc = "Basic (generic) interpreter (class SOPHYA::Commander) builtin commands";
462AddHelpGroup(grp, gdesc);
463
464string kw = "Commander";
465string usage;
466usage = ">>> (Commander) Interpreter's keywords : \n";
467usage += " > set varname string # To set a variable, $varname \n";
468usage += " > unset varname # clear variable definition \n";
469usage += " > rpneval varname RPNExpression # Reverse Polish Notation evaluation \n";
470usage += " > varname = ArithmeticExpression # C-like Expression evaluation \n";
471usage += " > varname = 'String' # Set variable vname \n";
472usage += " > var2words varname wordvarname [sep] # to break varname into words \n";
473usage += " > echo string # output string \n";
474usage += " > echo2file filename string # Append the string to the specified file \n";
475usage += " > alias name string # define a command alias \n";
476usage += " > foreach varname ( string-list ) # Loop \n";
477usage += " > for varname i1:i2[:di] # Integer loop \n";
478usage += " > for varname f1:f2[:df] # Float loop \n";
479usage += " > forinfile varname FileName # Loop over lines in file \n";
480usage += " > end # end loops \n";
481usage += " > if ( test ) then # Conditional test : a == != < > <= >= b \n";
482usage += " > else # Conditional \n";
483usage += " > endif # End of conditional if bloc \n";
484usage += " > break # Delete (clears) all test and loop blocs \n";
485usage += " > return # Stops command execution from a file \n";
486usage += " > defscript endscript # Command script definition \n";
487usage += " > listvars # List of variable names and values \n";
488usage += " > listalias # List of alias names and values \n";
489usage += " > listcommands # List of all known commands \n";
490usage += " > listscripts # List of all known scripts \n";
491usage += " > clearcript # Clear a script definition \n";
492usage += " > thrlist # List of command execution threads (& as the last character) \n";
493usage += " > clearthrlist # Removes finished threads from the list \n";
494usage += " > cancelthr Id # Cancel a given thread (ThrId=id) \n";
495usage += " > waitthr # Waits until all active threads have finished (join()) \n";
496usage += " > exec filename # Execute commands from file \n";
497usage += " > help <command_name> # <command_name> usage info \n";
498usage += " > sleep nsec # sleep nsec seconds \n";
499usage += " > readstdin varname # reads a line from stdin into $varname \n";
500usage += " > timingon timingoff traceon traceoff \n";
501RegisterHelp(kw, usage, grp);
502
503kw = "RPNEvaluator";
504usage = " Reverse Polish Notation (HP calculator like) expression evaluation \n";
505usage += " >> Stack: \n";
506usage += " ... (4) (3) z=(2) y=(1) x=(0)=Stack.Top() \n";
507usage += " >> Examples: \n";
508usage += " - sin(PI/6): pi 6 / sin \n";
509usage += " - 1*2*...*5: 1 2 3 4 5 product \n";
510usage += " - x=x+y: x = $x $y * \n";
511usage += " >>> Stack operations : \n";
512usage += " print x<>y pop push (duplicate x) \n";
513usage += " >>> Constants (Cst pushed to stack): \n";
514usage += " pi e \n";
515usage += " >>> Arithmetic operators (x,y) --> x@y \n";
516usage += " + - * / % ( (int)y % (int)x )\n";
517usage += " >>> F(X): x --> F(x) \n";
518usage += " chs sqrt sq log log10 exp \n";
519usage += " fabs floor ceil \n";
520usage += " cos sin tan acos asin atan deg2rad rad2deg \n";
521usage += " >>> F(X,Y): (x,y) --> F(x,y) \n";
522usage += " pow atan2 \n";
523usage += " >>> F(): random number generators \n";
524usage += " rand (flat 0..1) norand (normal/gaussian) \n";
525usage += " >>> Stack sum/product/mean/sigma/sigma^2 \n";
526usage += " sum product mean sigma sigma2 sigmean (y->sigma x->mean) \n";
527RegisterHelp(kw, usage, grp);
528
529kw = "autoiniranf";
530usage = "> Automatic random number generator initialisation\n";
531usage += " by Auto_Ini_Ranf(int lp) \n";
532usage += " Usage: autoiniranf";
533RegisterCommand(kw, usage, NULL, grp);
534
535kw = "CExpEvaluator";
536usage = "> Evaluation of C-like expression (used in V = C-like-Expression) \n";
537usage += " >>> Arithmetic operators, parenthesis ( + - * / ) \n";
538usage += " >>> Functions : sqrt fabs floor hypot \n";
539usage += " ... exp log log10 pow ; sinh cosh tanh \n";
540usage += " ... sin cos tan asin acos atan atan2 \n";
541usage += " ... rand01() randpm1() gaurand() \n";
542usage += " >>> Constants : Pi = M_PI E = M_E \n";
543usage += " Example: x = 5.*(2.+sin(0.3*Pi))";
544RegisterCommand(kw, usage, NULL, grp);
545
546kw = "shell execute";
547usage = "> shell command_string # Execute shell command\n";
548usage += "> cshell command_string # Execute cshell command\n";
549usage += "---Examples:\n";
550usage += " > shell ls\n";
551usage += " > cshell echo '$LD_LIBRARY_PATH'; map2cl -h; ls\n";
552usage += " > shell myfile.csh [arg1] [arg2] [...]\n";
553usage += " (where the first line of \"myfile.csh\" is \"#!/bin/csh\")\n";
554RegisterCommand(kw, usage, NULL, grp);
555
556
557AddInterpreter(this);
558curcmdi = this;
559}
560
561/* --Methode-- */
562Commander::~Commander()
563{
564hist.close();
565if (gltimer) { delete gltimer; gltimer = NULL; }
566Modmap::iterator it;
567for(it = modmap.begin(); it != modmap.end(); it++) {
568 string name = (*it).first + "_end";
569 DlModuleInitEndFunction fend = (*it).second->GetFunction(name);
570 if (fend) fend();
571 delete (*it).second;
572 }
573
574for(ScriptList::iterator sit = mScripts.begin();
575 sit != mScripts.end(); sit++) delete (*sit).second;
576
577if (cur_commander == this) cur_commander = NULL;
578}
579
580/* --Methode-- */
581Commander* Commander::GetInterpreter()
582{
583return(cur_commander);
584}
585
586/* --Methode-- */
587//! Returns the string \c Commander as the interpreter's name.
588string Commander::Name()
589{
590return("Commander");
591}
592
593/* --Methode-- */
594//! Add the \b grp help group with description \b desc.
595void Commander::AddHelpGroup(string& grp, string& desc)
596{
597 int gid;
598 CheckHelpGrp(grp, gid, desc);
599}
600
601/* --Methode-- */
602/*!
603 \brief Register a command executor associated with a given keyword.
604 \param keyw : keyword identifying the command
605 \param usage : the command help and usage information
606 \param ce : CmdExecutor pointer for this a command. The same object can be registered
607 multiple time for different commands.
608 \param grp : The help group corresponding to this command.
609*/
610void Commander::RegisterCommand(string& keyw, string& usage, CmdExecutor * ce, string& grp)
611{
612if (!ce) {
613 RegisterHelp(keyw, usage, grp);
614 return;
615 }
616int gid;
617CheckHelpGrp(grp,gid);
618cmdex cme;
619cme.group = gid;
620cme.us = usage;
621cme.cex = ce;
622cmdexmap[keyw] = cme;
623}
624
625/* --Methode-- */
626/*!
627 \brief Register a help text.
628 \param keyw : help keyword
629 \param usage : help text
630 \param grp : help group
631*/
632void Commander::RegisterHelp(string& keyw, string& usage, string& grp)
633{
634int gid;
635CheckHelpGrp(grp,gid);
636cmdex cme;
637cme.group = gid;
638cme.us = usage;
639cme.cex = NULL;
640helpexmap[keyw] = cme;
641}
642
643/* --Methode-- */
644bool Commander::CheckHelpGrp(string& grp, int& gid, string& desc)
645{
646gid = 0;
647CmdHGroup::iterator it = cmdhgrp.find(grp);
648if (it == cmdhgrp.end()) {
649 cmdgrpid++; gid = cmdgrpid;
650 hgrpst hgs; hgs.gid = gid; hgs.desc = desc;
651 cmdhgrp[grp] = hgs;
652 return true;
653 }
654else {
655 if (desc.length() > 0) (*it).second.desc = desc;
656 gid = (*it).second.gid;
657 return false;
658}
659}
660
661
662/* --Methode-- */
663/*!
664 \brief Dynamic loader for modules
665
666 A module is a shared library extending the application functionalities.
667 Typically, a module adds new commands to the interpreter. Once loaded,
668 the module is activated (initialized) by calling a function with the
669 name \b modulename_init . This function should be declared extern C
670 to avoid C++ name mangling. A cleanup function \b modulename_end
671 is called by the Commander destructor.
672
673 \param fnameso : Shared library name containing the module functions
674 and classes.
675 \param name : Module name. This string is used to form module
676 initializer and cleanup function name \c name_init \c name_end
677*/
678void Commander::LoadModule(string& fnameso, string& name)
679{
680PDynLinkMgr * dynlink = new PDynLinkMgr(fnameso, false);
681if (dynlink == NULL) {
682 cerr << "Commander/LoadModule_Error: Pb opening SO " << fnameso << endl;
683 return;
684 }
685string fname = name + "_init";
686DlModuleInitEndFunction finit = dynlink->GetFunction(fname);
687if (!finit) {
688 cerr << "Commander/LoadModule_Error: Pb linking " << fname << endl;
689 return;
690 }
691cout << "Commander/LoadModule_Info: Initialisation module" << name
692 << " " << fname << "() ..." << endl;
693finit();
694modmap[name] = dynlink;
695return;
696}
697
698/* --Methode-- */
699//! Declare a new interpreter
700void Commander::AddInterpreter(CmdInterpreter * cl)
701{
702if (!cl) return;
703interpmap[cl->Name()] = cl;}
704
705/* --Methode-- */
706//! Select an interpreter by its name. The corresponding Interpret method is then called
707void Commander::SelInterpreter(string& name)
708{
709InterpMap::iterator it = interpmap.find(name);
710if (it == interpmap.end()) return;
711curcmdi = (*it).second;
712}
713
714
715
716/* Fonction */
717static string GetStringFrStdin(Commander* piac)
718{
719char buff[128];
720fgets(buff, 128, stdin);
721buff[127] = '\0';
722return((string)buff);
723}
724
725/* --Methode-- */
726/*!
727 \brief Method which has to be invoked to interpret a given command line or string.
728*/
729int Commander::Interpret(string& s)
730{
731int rc = 0;
732ScriptList::iterator sit;
733
734// Si le flag d'arret d'execution a ete positionne on returne avec le code
735// de BREAKEXECUTION
736if (fgexebrk) {
737 cout << " ===> Commander::Interpret() - STOP Execution (CMD_BREAKEXE_RC)" << endl;
738 fgexebrk = false; return CMD_BREAKEXE_RC;
739}
740
741// On saute de commandes vides
742size_t l;
743l = s.length();
744if (!mulinefg && (l < 1)) return(0);
745
746// On enregistre les commandes
747if (histon) hist << s << endl;
748
749if (s[0] == '#') return(0); // si c'est un commentaire
750
751// Logique de gestion des lignes suite
752// un \ en derniere position indique la presence d'une ligne suite
753size_t lnb = s.find_last_not_of(' ');
754if (s[lnb] == '\\' ) { // Lignes suite ...
755 mulinecmd += s.substr(0,lnb);
756 if (!mulinefg) {
757 spromptmul = GetCurrentPrompt();
758 SetCurrentPrompt("...? ");
759 mulinefg = true;
760 }
761 return(0);
762}
763
764if (mulinefg) { // Il y avait des lignes suite
765 s = mulinecmd + s;
766 l = s.length();
767 mulinecmd = "";
768 mulinefg = false;
769 SetCurrentPrompt(spromptmul);
770}
771
772// Removing leading blanks
773size_t p,q;
774
775// On enleve le dernier caractere, si celui-ci est \n
776if (s[l-1] == '\n') s[l-1] = '\0';
777p=s.find_first_not_of(" \t");
778if (p < l) s = s.substr(p);
779// >>>> Substitution d'alias (1er mot)
780CmdStrList::iterator it;
781p = 0;
782q = s.find_first_of(" \t");
783l = s.length();
784string w1 = (q < l) ? s.substr(p,q-p) : s.substr(p);
785it = mAliases.find(w1);
786if (it != mAliases.end()) {
787 s = (q < l) ? ((*it).second + s.substr(q)) : (*it).second ;
788 l = s.length();
789 p=s.find_first_not_of(" \t");
790 if (p < l) s = s.substr(p);
791 p = 0;
792 q = s.find_first_of(" ");
793 }
794
795// >>>> Separating keyword
796string toks,kw;
797if (q < l)
798 { kw = s.substr(p,q-p); toks = s.substr(q, l-q); }
799else { kw = s.substr(p,l-p); toks = ""; }
800
801// les mot-cle end else endif doivent etre le seul mot de la ligne
802if ( (kw == "end") || (kw == "else") || (kw == "endif") || (kw == "endscript") ) {
803 size_t ltk = toks.length();
804 if (toks.find_first_not_of(" \t") < ltk) {
805 cerr << "Commander::Interpret()/syntax error near end else endif endscript \n"
806 << "line: " << s << endl;
807 _xstatus = 91;
808 return(91);
809 }
810}
811
812// On verifie si on est en train de definir un script
813if (curscript) {
814 if (kw == "endscript") {
815 if (curscript->CheckScript()) {
816 sit = mScripts.find(curscript->Name());
817 if (sit != mScripts.end()) {
818 cout << "Commander::Interpret() replacing script "
819 << curscript->Name() << endl;
820 CommanderScript* scr = mScripts[curscript->Name()];
821 mScripts.erase(sit);
822 delete scr;
823 }
824 cout << "Commander::Interpret() Script " << curscript->Name()
825 << " defined successfully" << endl;
826 mScripts[curscript->Name()] = curscript;
827 SetCurrentPrompt("Cmd> ");
828 curscript = NULL;
829 _xstatus = 0;
830 return(0);
831 }
832 else {
833 cout << "Commander::Interpret() Error in Script " << curscript->Name()
834 << " definition " << endl;
835 SetCurrentPrompt("Cmd> ");
836 curscript = NULL;
837 _xstatus = 92;
838 return(92);
839 }
840 }
841 else curscript->AddLine(s, kw);
842 _xstatus = 0;
843 return(0);
844}
845// On verifie si nous sommes dans un bloc (for , foreach)
846if (CmdBlks.top() != NULL) { // On est dans un bloc
847 if ( (kw == "for") || (kw == "foreach") || (kw == "forinfile") ) felevel++;
848 else if (kw == "end") felevel--;
849
850 int rcbex = 0;
851 if (felevel == 0) { // Il faut executer le bloc
852 CommanderBloc* curb = CmdBlks.top();
853 CmdBlks.top() = curb->Parent();
854 SetCurrentPrompt("Cmd> ");
855 if (!curb->CheckBloc()) {
856 cerr << "Commander::Interpret()/syntax error - unbalenced if ... endif"
857 << " within for/foreach/forinfile bloc ! " << endl;
858 delete curb;
859 _xstatus = 93;
860 return(93);
861 }
862 // cout << " *DBG* Executing bloc " << endl;
863 bool ohv = histon;
864 histon = false;
865 if (curtestresult) {
866 // We push also CommanderBloc and testresult on the stack
867 CmdBlks.push(NULL);
868 list<char> xtx;
869 TestsStack.push(xtx);
870 rcbex = curb->Execute();
871 // And CommanderBloc and TestResult from the corresponding stacks
872 PopStack(false);
873 }
874 SetCurrentPrompt(defprompt);
875 delete curb;
876 histon = ohv;
877 }
878 else CmdBlks.top()->AddLine(s, kw);
879 _xstatus = rcbex;
880 return(rcbex);
881}
882else if (kw == "end") {
883 cerr << "Commander::Interpret()/syntax error - end outside for/foreach/forinfile bloc \n"
884 << "line: " << s << endl;
885 _xstatus = 94;
886 return(94);
887}
888
889// Sommes-nous dans un bloc de test if then else
890if (TestsStack.top().size() > 0) { // Nous sommes ds un bloc if
891 if (kw == "else") {
892 if ((*tresit) & 2) {
893 cerr << "Commander::Interpret()/syntax error - multiple else in if bloc \n"
894 << "line: " << s << endl;
895 _xstatus = 95;
896 return(95);
897 }
898 else {
899 const char * npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
900 if ((*tresit)&1) curtestresult = false;
901 SetCurrentPrompt(npr);
902 (*tresit) |= 2;
903 _xstatus = 0;
904 return(0);
905 }
906 }
907 else if (kw == "endif") {
908 list<char>::iterator dbit = tresit;
909 tresit--;
910 TestsStack.top().erase(dbit);
911 const char * npr = "Cmd> ";
912 if (TestsStack.top().size() > 1) {
913 curtestresult = true;
914 list<char>::iterator it;
915 for(it=TestsStack.top().begin(); it!=TestsStack.top().end(); it++) {
916 // Si on n'est pas ds le else et le if est faux
917 if ( !((*it)&2) && !((*it)&1) ) curtestresult = false;
918 // Si on est ds else et le if etait vrai !
919 if ( ((*it)&2) && ((*it)&1) ) curtestresult = false;
920 if (!curtestresult) break;
921 }
922
923 if (!((*tresit)&2))
924 npr = ((*tresit)&1) ? "if-T> " : "if-F> ";
925 else
926 npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
927 }
928 else curtestresult = true;
929 SetCurrentPrompt(npr);
930 _xstatus = 0;
931 return(0);
932 }
933}
934else if ((kw == "else") || (kw == "endif")) {
935 cerr << "Commander::Interpret()/syntax error - else,endif outside if bloc \n"
936 << "line: " << s << endl;
937 _xstatus = 91;
938 return(91);
939}
940
941bool fgcont = true;
942if (TestsStack.top().size() > 0) { // Resultat de if ou else
943 list<char>::iterator it;
944 for(it=TestsStack.top().begin(); it!=TestsStack.top().end(); it++) {
945 // Si on n'est pas ds le else et le if est faux
946 if ( !((*it)&2) && !((*it)&1) ) fgcont = false;
947 // Si on est ds else et le if etait vrai !
948 if ( ((*it)&2) && ((*it)&1) ) fgcont = false;
949 if (!fgcont) break;
950 }
951}
952
953if ((!fgcont) && (kw != "if")) {
954 _xstatus = 0;
955 return(0);
956}
957
958
959// Les mots cles break et return peuvent de sortir de boucles/scripts/execfile
960if (kw == "break") return CMD_BREAK_RC;
961else if (kw == "return") {
962 _retstr = toks;
963 return CMD_RETURN_RC;
964}
965
966// Nous ne sommes donc pas dans un bloc .... Substitution de variables
967string s2;
968int rcs ;
969
970rcs = SubstituteVars(s, s2);
971if (rcs) {
972 cerr << "Commander::Interpret()/syntax error in SubstituteVars() \n"
973 << "line: " << s << endl;
974 _xstatus = 99;
975 return(99);
976}
977// >>>> Separating keyword and tokens
978vector<string> tokens;
979vector<bool> qottoks;
980/* decoupage en mots */
981LineToWords(s2, kw, tokens, qottoks, toks, true);
982
983// Si c'est un for/foreach, on cree un nouveau bloc
984if ((kw == "foreach") || (kw == "for") || (kw == "forinfile") ) {
985 // cout << " *DBG* We got a foreach... " << endl;
986 CommanderBloc* bloc = new CommanderBloc(this, CmdBlks.top(), kw, tokens);
987 if (!bloc->CheckOK()) {
988 cerr << "Commander::Interpret() for/foreach syntax Error ! " << endl;
989 delete bloc;
990 _xstatus = 91;
991 return(91);
992 }
993 felevel++;
994 if (CmdBlks.top()) CmdBlks.top()->AddBloc(bloc);
995 else SetCurrentPrompt("for...> ");
996 CmdBlks.top() = bloc;
997 // cout << " *DBG* New Bloc created ... " << endl;
998 return(0);
999 }
1000else if (kw == "if") { // Un test if
1001 bool restst = true;
1002 int rct = EvaluateTest(tokens, s, restst);
1003 if (rct) {
1004 cerr << "Commander::Interpret() if syntax Error ! " << "line: " << s << endl;
1005 _xstatus = 91;
1006 return(91);
1007 }
1008 char res_tst = (restst) ? 1 : 0;
1009 TestsStack.top().push_back(res_tst);
1010 if (TestsStack.top().size() == 1) tresit = TestsStack.top().begin();
1011 else tresit++;
1012 const char * npr = (restst) ? "if-T> " : "if-F> ";
1013 SetCurrentPrompt(npr);
1014}
1015else if ((tokens.size() > 0) && (tokens[0] == "=")) {
1016 // x = Expression
1017 if (qottoks[1]) { // decodage sous forme de chaine
1018 SetVariable(kw, tokens[1]);
1019 }
1020 else {
1021 try {
1022 double res = 0.;
1023 if (tokens.size() > 2) {
1024 string sex = tokens[1];
1025 for(int js=2; js<tokens.size(); js++) sex += tokens[js];
1026 CExpressionEvaluator cex(sex);
1027 res = cex.Value();
1028 }
1029 else {
1030 CExpressionEvaluator cex(tokens[1]);
1031 res = cex.Value();
1032 }
1033 char cbuff[64];
1034 sprintf(cbuff,"%g",res);
1035 string vv = cbuff;
1036 SetVariable(kw, vv);
1037 }
1038 catch (CExprException& cexerr) {
1039 cerr << "Commander::Interpret() evaluation Error : \n " << "line: " << s
1040 << " \n Msg=" << cexerr.Msg() << endl;
1041 _xstatus = 98;
1042 return(98);
1043 }
1044 }
1045}
1046else if (kw == "defscript") { // definition de script
1047 if (tokens.size() > 0) {
1048 if (tokens.size() < 2) tokens.push_back("");
1049 curscript = new CommanderScript(this, tokens[0], tokens[1]);
1050 SetCurrentPrompt("Script...> ");
1051 return(0);
1052 }
1053 else {
1054 cerr << "Commander::Interpret() No script name in defscript" << "line: " << s << endl;
1055 _xstatus = 91;
1056 return(91);
1057 }
1058}
1059else {
1060 // Si c'est le nom d'un script
1061 sit = mScripts.find(kw);
1062 if (sit != mScripts.end()) {
1063 bool ohv = histon;
1064 histon = false;
1065 tokens.insert(tokens.begin(), kw);
1066 PushStack(tokens);
1067 (*sit).second->Execute(tokens);
1068 PopStack(true);
1069 histon = ohv;
1070 }
1071 // Execution de commandes
1072 else rc = ExecuteCommandLine(kw, tokens, toks);
1073 _xstatus = rc;
1074 return(rc);
1075}
1076// cout << "Commander::Do() DBG KeyW= " << kw << " NbArgs= " << tokens.size() << endl;
1077// for(int ii=0; ii<tokens.size(); ii++)
1078// cout << "arg[ " << ii << " ] : " << tokens[ii] << endl;
1079
1080return(0);
1081}
1082
1083void Commander::StopExecution()
1084{
1085 fgexebrk = true;
1086}
1087
1088
1089/* --Methode-- */
1090int Commander::LineToWords(string& line, string& kw, vector<string>& tokens,
1091 vector<bool>& qottoks, string& toks, bool uq)
1092{
1093if (line.length() < 1) return(0);
1094int nw = 1;
1095size_t p = line.find_first_not_of(" ");
1096line = line.substr(p);
1097p = 0;
1098size_t q = line.find_first_of(" ");
1099size_t l = line.length();
1100
1101if (q < l)
1102 { kw = line.substr(p,q-p); toks = line.substr(q, l-q); }
1103else { kw = line.substr(p,l-p); toks = ""; }
1104
1105q = 0;
1106while (q < l) {
1107 bool swq = false; // true -> chaine delimite par ' ou "
1108 p = toks.find_first_not_of(" \t",q+1); // au debut d'un token
1109 if (p>=l) break;
1110 if ( uq && ((toks[p] == '\'') || (toks[p] == '"')) ) {
1111 q = toks.find(toks[p],p+1);
1112 if (q>=l) {
1113 cerr << "Commander::LineToWords/Syntax Error - Unbalenced quotes " << toks[p] << '.' << endl;
1114 return(-1);
1115 }
1116 p++; swq = true;
1117 }
1118 else {
1119 q = toks.find_first_of(" \t",p); // la fin du token;
1120 }
1121 string token = toks.substr(p,q-p);
1122 tokens.push_back(token);
1123 qottoks.push_back(swq);
1124 nw++;
1125 }
1126
1127return(nw);
1128}
1129
1130/* --Methode-- */
1131int Commander::SubstituteVars(string & s, string & s2)
1132// Variable substitution
1133{
1134
1135int iarr = -1; // index d'element de tableau
1136size_t p,q,q2,q3,l;
1137
1138s2="";
1139p = 0;
1140l = s.length();
1141string vn, vv;
1142while (p < l) {
1143 iarr = -1;
1144 q = s.find('$',p);
1145 if (q > l) break;
1146 q2 = s.find('\'',p);
1147 if ((q2 < l) && (q2 < q)) { // On saute la chaine delimitee par ' '
1148 q2 = s.find('\'',q2+1);
1149 if (q2 >= l) {
1150 cerr << " Syntax error - Unbalenced quotes !!! " << endl;
1151 return(1);
1152 }
1153 s2 += s.substr(p, q2-p+1);
1154 p = q2+1; continue;
1155 }
1156 // cout << "DBG: " << s2 << " p= " << p << " q= " << q << " L= " << l << endl;
1157 if ((q>0) && (s[q-1] == '\\')) { // Escape character \$
1158 s2 += (s.substr(p,q-1-p) + '$') ; p = q+1;
1159 continue;
1160 }
1161 if (q >= l-1) {
1162 cerr << " Syntax error - line ending with $ !!! " << endl;
1163 return(2);
1164 }
1165 vn = "";
1166 if ( s[q+1] == '{' ) { // Variable in the form ${name}
1167 q2 = s.find('}',q+1);
1168 if (q2 >= l) {
1169 cerr << " Syntax error - Unbalenced brace {} !!! " << endl;
1170 return(3);
1171 }
1172 vn = s.substr(q+2,q2-q-2);
1173 q2++;
1174 }
1175 else if ( s[q+1] == '(' ) { // Variable in the form $(name)
1176 q2 = s.find(')',q+1);
1177 if (q2 >= l) {
1178 cerr << " Syntax error - Unbalenced parenthesis () !!! " << endl;
1179 return(3);
1180 }
1181 vn = s.substr(q+2,q2-q-2);
1182 q2++;
1183 }
1184 else if ( s[q+1] == '[' ) { // Variable in the form $[varname] -> This is $$varname
1185 q2 = s.find(']',q+1);
1186 if (q2 >= l) {
1187 cerr << " Syntax error - Unbalenced brace [] !!! " << endl;
1188 return(4);
1189 }
1190 vn = s.substr(q+2,q2-q-2);
1191 if (!Var2Str(vn, vv)) return(5);
1192 vn = vv;
1193 q2++;
1194 }
1195 else {
1196 if (s[q+1] == '#' ) q3 = q+2; // Variable in the form $#varname
1197 else q3 = q+1;
1198 q2 = s.find_first_of(" .:+-*/,[](){}&|!$\"'<>^%=#@\\",q3);
1199 if (q2 > l) q2 = l;
1200 q3 = q2;
1201 vn = s.substr(q+1, q2-q-1);
1202 // Si variable de type $varname[index] : element de tableau
1203 if ((q2 < l) && (s[q2] == '[') ) {
1204 q3 = s.find_first_of("]",q2+1);
1205 string sia = s.substr(q2+1, q3-q2-1);
1206 if (sia.length() < 1) {
1207 cerr << " Syntax error - in $varname[index] : $"
1208 << vn << "[" << sia <<"]" << endl;
1209 return(4);
1210 }
1211 if (isalpha(sia[0])) {
1212 string sia2;
1213 if (!Var2Str(sia, sia2) || (sia2.length() < 1)) {
1214 cerr << " Syntax error - in $varname[index] : $"
1215 << vn << "[" << sia <<"]" << endl;
1216 return(4);
1217 }
1218 sia = sia2;
1219 }
1220 int rcdia = ctoi(sia.c_str(), &iarr);
1221 if (rcdia < 0) {
1222 cerr << " Syntax error - in $varname[iarr] : $"
1223 << vn << "[" << sia <<"]" << endl;
1224 return(4);
1225 }
1226 }
1227 }
1228 if (iarr < 0) {
1229 if (!Var2Str(vn, vv)) return(5);
1230 s2 += (s.substr(p, q-p) + vv);
1231 p = q2;
1232 }
1233 else {
1234 if (! Var2Str(vn, iarr, vv) ) {
1235 cerr << " Substitution error - word index out of range in "
1236 << "$varname[iarr] : $" << vn << "[" << iarr <<"]" << endl;
1237 return(4);
1238 }
1239 else s2 += (s.substr(p, q-p) + vv);
1240 p = q3+1;
1241 }
1242}
1243if (p < l) s2 += s.substr(p);
1244
1245p = s2.find_first_not_of(" \t");
1246if (p < l) s2 = s2.substr(p);
1247
1248return(0);
1249}
1250
1251/* --Methode-- */
1252bool Commander::Var2Str(string const & vn, string & vv)
1253{
1254if (vn.length() < 1) {
1255 cerr << " Commander::Var2Str/Error: length(varname=" << vn << ")<1 !" << endl;
1256 vv = ""; return(false);
1257}
1258// Variable de type $# $0 $1 ... (argument de .pic ou de script)
1259int ka = 0;
1260char buff[32];
1261
1262if (vn == "#") {
1263 if (ArgsStack.empty()) {
1264 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1265 << " ($" << vn << ")" << endl;
1266 vv = ""; return(false);
1267 }
1268 char buff[32];
1269 long an = ArgsStack.top().size();
1270 if (an > 0) an--; // Pour se conformer a l'usage de csh : Nb args sans le $0
1271 sprintf(buff,"%ld", an);
1272 vv = buff; return(true);
1273}
1274else if (vn == "*") {
1275 if (ArgsStack.empty()) {
1276 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1277 << " ($" << vn << ")" << endl;
1278 vv = ""; return(false);
1279 }
1280 vv = ArgsStack.top()[0];
1281 for(int ssk=1; ssk<ArgsStack.top().size(); ssk++) vv += ArgsStack.top()[ssk];
1282 return(true);
1283}
1284else if (ctoi(vn.c_str(), &ka) > 0) { // $0 $1 $2 ...
1285 if (ArgsStack.empty()) {
1286 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1287 << " ($" << vn << ")" << endl;
1288 vv = ""; return(false);
1289 }
1290 if ( (ka < 0) || (ka >= ArgsStack.top().size()) ) {
1291 cerr << " Commander::Var2Str/Error: ArgsStack index <0 or >=args.size() ! "
1292 << " ($" << vn << ")" << endl;
1293 vv = ""; return(false);
1294 }
1295 vv = ArgsStack.top()[ka]; return(true);
1296}
1297else if (vn[0] == '#') { // Variable de type $#vname --> size(vname)
1298 CmdVarList::iterator it = variables.find(vn.substr(1));
1299 if (it == variables.end()) {
1300 cerr << " Commander::Var2Str/Error #vname Undefined variable "
1301 << vn << " ! " << endl;
1302 vv = ""; return(false);
1303 }
1304 sprintf(buff,"%d", (int)(*it).second.size());
1305 vv = buff; return(true);
1306}
1307else if (vn == "status") {
1308 sprintf(buff,"%d", _xstatus);
1309 vv = buff;
1310 return true;
1311}
1312else if ((vn == "retstr") || (vn == "retval")) {
1313 vv = _retstr;
1314 return true;
1315}
1316else { // Variable de l'interpreteur, ou de l'environnement application , env. global
1317 if (GetVar(vn, vv)) return true;
1318 else if (GetVarApp(vn, vv)) return true;
1319 else if (GetVarEnv(vn, vv)) return true;
1320 else {
1321 cerr << " Commander::Var2Str/Error Undefined variable "
1322 << vn << " ! " << endl;
1323 vv = ""; return false;
1324 }
1325}
1326
1327return false;
1328}
1329
1330/* --Methode-- */
1331bool Commander::SetVariable(string const & vn, string const & vv)
1332{
1333 // On verifie si le nom est de type vname[idx]
1334 size_t p,q,l;
1335 l = vn.length();
1336 p = vn.find('[');
1337 if (p < l) {
1338 q = vn.find(']');
1339 if (q != (l-1)) {
1340 cout << "Commander::Str2Var/SetVar() - Bad varname with []: "
1341 << vn << endl;
1342 return false;
1343 }
1344 string vna = vn.substr(0, p);
1345 string sia = vn.substr(p+1, q-(p+1));
1346 if (isalpha(sia[0])) {
1347 string sia2;
1348 if (!Var2Str(sia, sia2) || (sia2.length() < 1)) {
1349 cerr << "Commander::Str2Var/SetVar() Syntax error- varname[index]:"
1350 << vn << endl;
1351 return false;
1352 }
1353 sia = sia2;
1354 }
1355 int iarr;
1356 int rcdia = ctoi(sia.c_str(), &iarr);
1357 if (rcdia < 0) {
1358 cerr << "Commander::Str2Var/SetVar() Syntax error- varname[iarr]: "
1359 << vn << endl;
1360 return false;
1361 }
1362 return SetVar(vna, iarr, vv);
1363 }
1364 else {
1365 if (vn == "status") {
1366 _xstatus = atoi(vv.c_str());
1367 return true;
1368 }
1369 else if (vn == "retstr") {
1370 _retstr = vv;
1371 return true;
1372 }
1373 else return SetVar(vn, vv);
1374 }
1375}
1376
1377/* --Methode-- */
1378bool Commander::GetVar(string const & vn, string & vv)
1379{
1380 CmdVarList::iterator it = variables.find(vn);
1381 if (it == variables.end()) {
1382 vv = "";
1383 return false;
1384 }
1385 vv = (*it).second[0];
1386 if ((*it).second.size() > 1) {
1387 for(int k=1; k<(*it).second.size(); k++) {
1388 vv += ' '; vv += (*it).second[k];
1389 }
1390 }
1391 return true;
1392}
1393
1394/* --Methode-- */
1395bool Commander::GetVar(string const & vn, int idx, string & vv)
1396{
1397 vv = "";
1398 CmdVarList::iterator it = variables.find(vn);
1399 if (it == variables.end()) return false;
1400 if ((idx < 0) || (idx > (*it).second.size()-1))
1401 return false;
1402 vv = (*it).second[idx];
1403 return true;
1404}
1405
1406/* --Methode-- */
1407bool Commander::GetVar(string const & vn, vector<string> & vv)
1408{
1409 vv.clear();
1410 // vv.erase(vv.begin(),vv.end());
1411 CmdVarList::iterator it = variables.find(vn);
1412 if (it == variables.end()) return false;
1413 vv = (*it).second;
1414 return true;
1415}
1416
1417/* --Methode-- */
1418bool Commander::SetVar(string const & vn, string const & val)
1419{
1420 if ( !CheckVarName(vn) ) {
1421 cerr << "Commander::SetVar( " << vn << " ...) Bad VarName " << endl;
1422 return(false);
1423 }
1424 bool fg = false;
1425 vector<string> nouv;
1426 nouv.push_back(val);
1427 CmdVarList::iterator it = variables.find(vn);
1428 if (it == variables.end()) variables[vn] = nouv;
1429 else {
1430 (*it).second = nouv;
1431 fg = true;
1432 }
1433 return fg;
1434}
1435
1436/* --Methode-- */
1437bool Commander::SetVar(string const & vn, int idx, string const & val)
1438{
1439 if ( !CheckVarName(vn) ) {
1440 cerr << "Commander::SetVar( " << vn << " ,idx, ...) Bad VarName " << endl;
1441 return(false);
1442 }
1443 if ((vn == "status") || (vn == "retstr")) {
1444 cerr << "Commander::SetVar(vn,idx,val) ERROR - special var status/retstr "
1445 << endl;
1446 return(false);
1447 }
1448 if (idx < 0) {
1449 cout << "Commander::SetVar(vn," << idx << ",...) Error idx < 0" << endl;
1450 return(false);
1451 }
1452 bool fg = false;
1453 CmdVarList::iterator it = variables.find(vn);
1454 if (it == variables.end()) {
1455 vector<string> nouv;
1456 for(int j=0; j<idx; j++) nouv.push_back("");
1457 nouv.push_back(val);
1458 variables[vn] = nouv;
1459 }
1460 else {
1461 if (idx >= (*it).second.size())
1462 for(int j=(*it).second.size(); j<=idx; j++) (*it).second.push_back("");
1463 (*it).second[idx] = val;
1464 fg = true;
1465 }
1466 return fg;
1467}
1468
1469/* --Methode-- */
1470bool Commander::SetVar(string const & vn, vector<string> const & val)
1471{
1472 if ( !CheckVarName(vn) ) {
1473 cerr << "Commander::SetVar( " << vn << " ...) Bad VarName " << endl;
1474 return(false);
1475 }
1476 if ((vn == "status") || (vn == "retstr")) {
1477 cerr << "Commander::SetVar(vn, vector<string>) ERROR - special var status/retstr "
1478 << endl;
1479 return(false);
1480 }
1481 bool fg = false;
1482 CmdVarList::iterator it = variables.find(vn);
1483 if (it == variables.end()) variables[vn] = val;
1484 else {
1485 (*it).second = val;
1486 fg = true;
1487 }
1488 return fg;
1489}
1490
1491/* --Methode-- */
1492bool Commander::CheckVarName(string const & vn)
1493{
1494 size_t l,k;
1495 l = vn.length();
1496 if (l < 1) return false;
1497 if (!isalpha(vn[0])) return false;
1498 for(k=1; k<l; k++)
1499 if ((!isalnum(vn[k])) && (vn[k] != '_')) return false;
1500 return true;
1501}
1502
1503/* --Methode-- */
1504bool Commander::DeleteVar(string const & vn)
1505{
1506 CmdVarList::iterator it = variables.find(vn);
1507 if (it == variables.end()) {
1508 cerr << "Commander::DeleteVar() Var " << vn << " undefined!" << endl;
1509 return false;
1510 }
1511 variables.erase(it);
1512 return true;
1513}
1514
1515/* --Methode-- */
1516void Commander::ListVar()
1517{
1518 cout << " ---- Commander::ListVar() List of defined variables ---- "
1519 << endl;
1520 CmdVarList::iterator it;
1521 for(it = variables.begin(); it != variables.end(); it++) {
1522 string vn = (*it).first;
1523 int vs = (*it).second.size();
1524 cout << vn << " -> Size= " << vs << endl;
1525 }
1526 cout << "---------------------------------------------------------- "
1527 << endl;
1528}
1529
1530/* --Methode-- */
1531bool Commander::GetVarApp(string const & vn, string & vv)
1532{
1533 vv = "";
1534 // cout << " Commander::GetVarApp() Not available ! " << endl;
1535 return false;
1536}
1537
1538/* --Methode-- */
1539bool Commander::SetVarApp(string const & vn, string const & vv)
1540{
1541 // cout << " Commander::SetVarApp() Not available ! " << endl;
1542 return false;
1543}
1544
1545/* --Methode-- */
1546bool Commander::DeleteVarApp(string const & vn)
1547{
1548 // cout << " Commander::DeleteVarApp() Not available ! " << endl;
1549 return false;
1550}
1551
1552/* --Methode-- */
1553void Commander::ListVarApp()
1554{
1555 // cout << " Commander::ListVarApp() Not available ! " << endl;
1556 return;
1557}
1558
1559
1560/* --Methode-- */
1561bool Commander::GetVarEnv(string const & vn, string & vv)
1562{
1563 char* vev = getenv(vn.c_str());
1564 if (vev) {
1565 vv = vev;
1566 return true;
1567 }
1568 else {
1569 vv = "";
1570 return false;
1571 }
1572}
1573
1574/* --Methode-- */
1575bool Commander::SetVarEnv(string const & vn, string const & vv)
1576{
1577 string pev = vn;
1578 pev += '=';
1579 pev += vv;
1580// if defined(Linux) || defined(AIX)
1581// Reza - 28/04/2004
1582// putenv de Linux ne declare pas la variable char *string const
1583// On ne doit meme pas utiliser une variable automatique
1584// J'alloue donc un nouveau tableau - mais qui va le liberer ?
1585// Idem AIX , Reza Dec 2005
1586// Pb apparu avec g++ 4 sur darwin (Mac) - Jan 2006
1587// Je fais copie pour tout le monde
1588 char* bev = new char[pev.size()+1];
1589 strcpy(bev, pev.c_str());
1590 if (putenv(bev) == 0) return true;
1591// else
1592// if (putenv(pev.c_str()) == 0) return true;
1593// endif
1594 else return false;
1595}
1596
1597/* --Methode-- */
1598bool Commander::DeleteVarEnv(string const & vn)
1599{
1600 // cout << " Commander::DeleteVarEnv() Not available ! " << endl;
1601 return false;
1602}
1603
1604/* --Methode-- */
1605void Commander::ListVarEnv()
1606{
1607 cout << " Commander::ListVarEnv() Not available ! " << endl;
1608 return;
1609}
1610
1611
1612/* --Methode-- */
1613string Commander::GetTmpDir()
1614{
1615 return("/tmp");
1616}
1617
1618/* --Methode-- */
1619void Commander::SetCurrentPrompt(const char* pr)
1620{
1621 curprompt = pr;
1622}
1623
1624/* --Methode-- */
1625void Commander::ShowMessage(const char * msg, int att)
1626{
1627 cout << msg ;
1628}
1629
1630
1631
1632/* --Methode-- */
1633int Commander::EvaluateTest(vector<string> & args, string & line, bool & res)
1634{
1635 res = true;
1636 if ((args.size() != 6) || (args[5] != "then") ||
1637 (args[0] != "(") || (args[4] != ")") ) return(1);
1638 if (args[2] == "==") res = (args[1] == args[3]);
1639 else if (args[2] == "!=") res = (args[1] != args[3]);
1640 else if (args[2] == "<")
1641 res = (atof(args[1].c_str()) < atof(args[3].c_str()));
1642 else if (args[2] == ">")
1643 res = (atof(args[1].c_str()) > atof(args[3].c_str()));
1644 else if (args[2] == "<=")
1645 res = (atof(args[1].c_str()) <= atof(args[3].c_str()));
1646 else if (args[2] == ">=")
1647 res = (atof(args[1].c_str()) >= atof(args[3].c_str()));
1648 else return(2);
1649 return(0);
1650}
1651
1652
1653/* --Methode-- */
1654int Commander::EvalRPNExpr(vector<string> & args, string & line)
1655{
1656 // A virer - Reza 15/03/2004
1657 return(0);
1658}
1659
1660/* --Methode-- */
1661void Commander::PushStack(vector<string>& args)
1662{
1663 // We push the argument list (args) on the stack
1664 ArgsStack.push(args);
1665 // We push also CommanderBloc and testresult on the stack
1666 CmdBlks.push(NULL);
1667 list<char> xtx;
1668 TestsStack.push(xtx);
1669
1670}
1671
1672/* --Methode-- */
1673void Commander::PopStack(bool psta)
1674{
1675 // We remove the argument list (args) from the stack
1676 if (psta) ArgsStack.pop();
1677 // And CommanderBloc and TestResult from the corresponding stacks
1678 CommanderBloc* curb = CmdBlks.top();
1679 while (curb != NULL) {
1680 CommanderBloc* parb = curb->Parent();
1681 delete curb; curb = parb;
1682 }
1683 CmdBlks.pop();
1684 TestsStack.pop();
1685}
1686
1687/* --Methode-- */
1688int Commander::ExecuteCommandLine(string & kw, vector<string> & tokens, string & toks)
1689{
1690int rc = 0;
1691
1692// >>>>>>>>>>> Commande d'interpreteur
1693if (kw == "help") {
1694 if (tokens.size() > 0) cout << GetUsage(tokens[0]) << endl;
1695 else {
1696 string kwh = "Commander";
1697 cout << GetUsage(kwh) << endl;
1698 }
1699 }
1700else if (kw == "sleep") {
1701 if (tokens.size() < 1) {
1702 cout << "Commander::Interpret() Usage: sleep nsec " << endl;
1703 return(1);
1704 }
1705 int nsec = atoi(tokens[0].c_str());
1706 cout << "Commander::Interpret() sleep " << nsec << " seconds" << endl;
1707 sleep(nsec);
1708}
1709
1710else if (kw == "set") {
1711 if (tokens.size() < 2) {
1712 cout << "Commander::Interpret() Usage: set varname value or set vecvar ( w1 w2 ... ) " << endl;
1713 return(1);
1714 }
1715
1716 if (tokens.size() == 2)
1717 SetVariable(tokens[0], tokens[1]);
1718 else {
1719 if ( (tokens[1] != "(") || (tokens[tokens.size()-1] != ")") ) {
1720 cout << "Commander::Interpret() Usage: set vecvar ( w1 w2 ... ) " << endl;
1721 return(1);
1722 }
1723 string vname = tokens[0];
1724 vector<string>::iterator vit;
1725 vit = tokens.begin(); tokens.erase(vit);
1726 vit = tokens.begin(); tokens.erase(vit);
1727 tokens.pop_back();
1728 SetVar(vname, tokens);
1729 }
1730 return 0;
1731}
1732else if (kw == "var2words") {
1733 if (tokens.size() < 2) {
1734 cout << "Commander::Interpret() Usage: var2words varname wordvarname [sep]" << endl;
1735 return(1);
1736 }
1737 char sep = ' ';
1738 if (tokens.size() > 2) sep = tokens[2][0];
1739 string vv;
1740 if (!GetVar(tokens[0], vv)) {
1741 cout << "Commander::Interpret() var2words/Error No variable with name " << tokens[0] << endl;
1742 return 2;
1743 }
1744 vector<string> vs;
1745 FillVStringFrString(vv, vs, sep);
1746 SetVar(tokens[1], vs);
1747}
1748else if (kw == "alias") {
1749 if (tokens.size() < 2) { cout << "Commander::Interpret() Usage: alias aliasname string" << endl; return(0); }
1750 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
1751 cerr << "Commander::Interpret()/Error alias name should start with alphabetic" << endl;
1752 return(1);
1753 }
1754 string xx = tokens[1];
1755 for (int kk=2; kk<tokens.size(); kk++) xx += (' ' + tokens[kk]);
1756 mAliases[tokens[0]] = xx;
1757}
1758
1759else if ( (kw == "unset") || (kw == "clearvar") ) {
1760 if (tokens.size() < 1) {
1761 cout << "Commander::Interpret() Usage: unset/clearvar varname" << endl;
1762 return(1);
1763 }
1764 else DeleteVar(tokens[0]);
1765}
1766// Evaluation d'expression en notation polonaise inverse
1767else if (kw == "rpneval") {
1768 try {
1769 RPNExpressionEvaluator rpn(tokens, 1);
1770 double res = rpn.Value();
1771 char cbuff[64];
1772 sprintf(cbuff,"%g",res);
1773 string vv = cbuff;
1774 SetVariable(tokens[0],vv);
1775 return 0;
1776 }
1777 catch (RPNExprException& rpnerr) {
1778 cerr << " rpneval: Syntax error - Msg=" << rpnerr.Msg()
1779 << " \n Line=" << toks << endl;
1780 return 98;
1781 }
1782}
1783else if (kw == "echo") {
1784 for (int ii=0; ii<tokens.size(); ii++)
1785 cout << tokens[ii] << " " ;
1786 cout << endl;
1787 }
1788else if (kw == "echo2file") {
1789 if (tokens.size() < 1) {
1790 cout << "Commander::Interpret() Usage: echo2file filename [string ] " << endl;
1791 return(1);
1792 }
1793 ofstream ofs(tokens[0].c_str(), ios::app);
1794 for (int ii=1; ii<tokens.size(); ii++)
1795 ofs << tokens[ii] << " " ;
1796 ofs << endl;
1797 }
1798else if (kw == "readstdin") {
1799 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: readstdin varname" << endl; return(0); }
1800 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
1801 cerr << "Commander::Interpret()/Error Variable name should start with alphabetic" << endl;
1802 return(0);
1803 }
1804 ShowMessage(">>> Reading From StdIn \n", _MAGENTA_);
1805 cout << tokens[0] << " ? " << endl;
1806 SetVar(tokens[0], GetStringFrStdin(this) );
1807 }
1808
1809else if (kw == "listvars" || kw == "listvar") ListVar();
1810else if (kw == "listalias") {
1811 cout << "Commander::Interpret() Alias List , AliasName = Value \n";
1812 CmdStrList::iterator it;
1813 for(it = mAliases.begin(); it != mAliases.end(); it++)
1814 cout << (*it).first << " = " << (*it).second << "\n";
1815 cout << endl;
1816 }
1817else if (kw == "listcommands") {
1818 cout << "---- Commander::Interpret() Command List ----- \n";
1819 CmdExmap::iterator it;
1820 int kc = 0;
1821 for(it = cmdexmap.begin(); it != cmdexmap.end(); it++) {
1822 cout << (*it).first << " ";
1823 kc++;
1824 if (kc >= 5) { cout << "\n"; kc = 0; }
1825 }
1826 cout << endl;
1827 }
1828else if (kw == "listscripts") {
1829 cout << "---- Commander::Interpret() Script List ----- \n";
1830 for(ScriptList::iterator sit = mScripts.begin();
1831 sit != mScripts.end(); sit++)
1832 cout << " Script: " << (*sit).second->Name() << " - "
1833 << (*sit).second->Comment() << endl;
1834}
1835else if (kw == "clearscript") {
1836 if (tokens.size() < 1) {
1837 cout << "Commander::Interpret() Usage: clearscript scriptname" << endl;
1838 return(0);
1839 }
1840 ScriptList::iterator sit = mScripts.find(tokens[0]);
1841 if (sit == mScripts.end()) {
1842 cout << "Commander::Interpret() No script with name" << tokens[0] << endl;
1843 return(0);
1844 }
1845 else {
1846 delete (*sit).second;
1847 mScripts.erase(sit);
1848 cout << "Commander::Interpret() script " << tokens[0] << " cleared" << endl;
1849 return(0);
1850 }
1851}
1852//---------------------------------------------
1853//--- Commandes de gestion des threads ------
1854//---------------------------------------------
1855else if (kw == "thrlist") {
1856 ListThreads();
1857 return(0);
1858}
1859else if (kw == "cancelthr") {
1860 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: cancelthr thrid" << endl; return(0); }
1861 uint_8 id = atol(tokens[0].c_str());
1862 CancelThr(id);
1863 return (0);
1864}
1865else if (kw == "waitthr") {
1866 WaitThreads();
1867 return (0);
1868}
1869else if (kw == "cleanthrlist") {
1870 CleanThrList();
1871 return (0);
1872}
1873
1874else if (kw == "traceon") { cout << "Commander::Interpret() -> Trace ON mode " << endl; trace = true; }
1875else if (kw == "traceoff") { cout << "Commander::Interpret() -> Trace OFF mode " << endl; trace = false; }
1876else if (kw == "timingon") {
1877 cout << "Commander::Interpret() -> Timing ON mode " << endl;
1878 if (gltimer) delete gltimer; gltimer = new Timer("PIA-CmdInterpreter "); timing = true;
1879 }
1880else if (kw == "timingoff") {
1881 cout << "Commander::Interpret() -> Timing OFF mode " << endl;
1882 if (gltimer) delete gltimer; gltimer = NULL; timing = false;
1883 }
1884else if (kw == "exec") {
1885 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: exec filename" << endl; return(0); }
1886 ExecFile(tokens[0], tokens);
1887 }
1888else if (kw == "autoiniranf") {
1889 Auto_Ini_Ranf(1);
1890 return(0);
1891}
1892else if (kw == "shell") {
1893 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: shell cmdline" << endl; return(0); }
1894 string cmd;
1895 for (int ii=0; ii<tokens.size(); ii++)
1896 cmd += (tokens[ii] + ' ');
1897 system(cmd.c_str());
1898 }
1899else if (kw == "cshell") {
1900 if(tokens.size()<1) {cout<<"Commander::Interpret() Usage: cshell cmdline"<<endl; return(0);}
1901 string cmd="";
1902 for(int ii=0;ii<tokens.size();ii++) cmd+=(tokens[ii]+' ');
1903 CShellExecute(cmd);
1904 }
1905
1906// Execution d'une commande enregistree
1907else rc = ExecuteCommand(kw, tokens, toks);
1908
1909if (timing) gltimer->Split();
1910return(rc);
1911}
1912
1913/* --Methode-- */
1914int Commander::ParseLineExecute(string& line, bool qw)
1915 // Si qw == true, on decoupe entre '' ou "" ou espaces
1916{
1917vector<string> tokens;
1918vector<bool> qottoks;
1919string kw, toks;
1920if (line.length() < 1) return(0);
1921LineToWords(line, kw, tokens, qottoks, toks, qw);
1922return(ExecuteCommand(kw, tokens, toks));
1923}
1924
1925/* --Methode-- */
1926int Commander::ExecuteCommand(string& keyw, vector<string>& args, string& toks)
1927{
1928 int rc = -1;
1929 CmdExmap::iterator it = cmdexmap.find(keyw);
1930 if (it == cmdexmap.end()) cout << "No such command : " << keyw << " ! " << endl;
1931 else {
1932 if ((*it).second.cex) {
1933 // Doit-on l'executer sous forme de thread separe ?
1934 if ( (args.size()>0) && (args[args.size()-1] == "&") &&
1935 ((*it).second.cex->IsThreadable(keyw)) ) {
1936 ThrId++;
1937 CommandExeThr * thr = new CommandExeThr(ThrId, (*it).second.cex, keyw, args, toks);
1938 CmdThrExeList.push_back(thr);
1939 cout << " Commander::ExecuteCommand() : Thread execution of command " << keyw << endl;
1940 thr->start();
1941 rc = 0;
1942 }
1943 else rc = (*it).second.cex->Execute(keyw, args, toks);
1944 }
1945 else cout << "Dont know how to execute " << keyw << " ? " << endl;
1946 }
1947 return(rc);
1948}
1949
1950/* --Methode-- */
1951int Commander::ExecFile(string& file, vector<string>& args)
1952{
1953char line_buff[1024];
1954FILE *fip;
1955int rcc = 0;
1956if ( (fip = fopen(file.c_str(),"r")) == NULL ) {
1957 if (file.find('.') >= file.length()) {
1958 cout << "Commander::Exec(): Error opening file " << file << endl;
1959 file += ".pic";
1960 cout << " Trying file " << file << endl;
1961 fip = fopen(file.c_str(),"r");
1962 }
1963 }
1964
1965if(fip == NULL) {
1966 cerr << "Commander::Exec() Error opening file " << file << endl;
1967 hist << "##! Commander::Exec() Error opening file " << file << endl;
1968 return(0);
1969 }
1970
1971// hist << "### Executing commands from " << file << endl;
1972PushStack(args);
1973if (trace) {
1974 ShowMessage("### Executing commands from ", _MAGENTA_);
1975 ShowMessage(file.c_str(), _MAGENTA_);
1976 ShowMessage("\n", _MAGENTA_);
1977 }
1978
1979bool ohv = histon;
1980histon = false;
1981while (fgets(line_buff,1023,fip) != NULL)
1982 {
1983 if (trace) ShowMessage(line_buff, _MAGENTA_);
1984 line_buff[strlen(line_buff)-1] = '\0'; /* LF/CR de la fin */
1985 string line(line_buff);
1986 rcc = Interpret(line);
1987 if ((rcc == CMD_RETURN_RC) || (rcc == CMD_BREAKEXE_RC)) break;
1988 }
1989histon = ohv;
1990
1991// hist << "### End of Exec( " << file << " ) " << endl;
1992if (trace) {
1993 ShowMessage("### End of Exec( ", _MAGENTA_);
1994 ShowMessage(file.c_str(), _MAGENTA_);
1995 ShowMessage(" ) \n", _MAGENTA_);
1996 }
1997
1998PopStack(true);
1999
2000return(0);
2001}
2002
2003/* --Methode-- */
2004void Commander::ListThreads()
2005{
2006 cout << "---- Commander::ListThreads() List of separate execution threads NThread="
2007 << CmdThrExeList.size() << " ----- " << endl;
2008 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2009 tit != CmdThrExeList.end(); tit++) {
2010 cout << "Id=" << (*tit)->Id();
2011 if ( (*tit)->IfDone() ) cout << " Finished , Rc= " << (*tit)->getRC();
2012 else cout << " Executing";
2013 cout << " (Cmd= " << (*tit)->Keyword() << " " << (*tit)->Tokens() << " )" << endl;
2014 }
2015}
2016/* --Methode-- */
2017void Commander::CancelThr(uint_8 id)
2018{
2019 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2020 tit != CmdThrExeList.end(); tit++) {
2021 if ((*tit)->Id() == id) {
2022 (*tit)->cancel();
2023 cout << "Commander::CancelThr() Thread Id= " << id << " cancelled" << endl;
2024 return;
2025 }
2026 }
2027 cout << "Commander::CancelThr()/Error: No thread with Id= " << id << endl;
2028}
2029
2030/* --Methode-- */
2031void Commander::CleanThrList()
2032{
2033 cout << "---- Commander::CleanThrList() Cleaning thrlist ----- \n";
2034 list<CommandExeThr *> thrcopie;
2035 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2036 tit != CmdThrExeList.end(); tit++) {
2037 if ( (*tit)->IfDone() ) {
2038 cout << " Thread Id= " << (*tit)->Id() << " rc= " << (*tit)->getRC() << " Cleaned" << endl;
2039 delete (*tit);
2040 }
2041 else thrcopie.push_back((*tit));
2042 }
2043 CmdThrExeList = thrcopie;
2044 cout << " ... " << CmdThrExeList.size() << " threads still active " << endl;
2045}
2046
2047/* --Methode-- */
2048void Commander::WaitThreads()
2049{
2050 cout << "---- Commander::WaitThreads() Wait/Join command execution threads - NThread="
2051 << CmdThrExeList.size() << " ----- " << endl;
2052 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2053 tit != CmdThrExeList.end(); tit++) {
2054 try {
2055 if (! (*tit)->IfDone()) (*tit)->join();
2056 }
2057 catch (std::exception & e) {
2058 cout << " Commander::WaitThreads()/Exception msg= " << e.what() << endl;
2059 }
2060 cout << " Joined thread Id= " << (*tit)->Id() << " rc= " << (*tit)->getRC() << endl;
2061 delete (*tit);
2062 }
2063 CmdThrExeList.erase(CmdThrExeList.begin(), CmdThrExeList.end());
2064}
2065
2066/* --Methode-- */
2067int Commander::CShellExecute(string cmd)
2068{
2069 if(cmd.size()<=0) return -1;
2070
2071 string fname = GetTmpDir(); fname += "cshell_exec_pia.csh";
2072
2073 string cmdrm = "rm -f " + fname;
2074 system(cmdrm.c_str());
2075
2076 FILE *fip = fopen(fname.c_str(),"w");
2077 if(fip==NULL) {
2078 cout << "Commander/CShellExecute_Error: fopen("<<fname<<") failed"<<endl;
2079 return -2;
2080 }
2081 fprintf(fip,"#!/bin/csh\n\n");
2082 fprintf(fip,"%s\n",cmd.c_str());
2083 fprintf(fip,"\nexit 0\n");
2084 fclose(fip);
2085
2086 cmd = "csh "; cmd += fname;
2087 system(cmd.c_str());
2088
2089 system(cmdrm.c_str());
2090
2091 return 0;
2092}
2093
2094static string* videstr = NULL;
2095/* --Methode-- */
2096string& Commander::GetUsage(const string& kw)
2097{
2098bool fndok = false;
2099CmdExmap::iterator it = cmdexmap.find(kw);
2100if (it == cmdexmap.end()) {
2101 it = helpexmap.find(kw);
2102 if (it != helpexmap.end()) fndok = true;
2103 }
2104 else fndok = true;
2105if (fndok) return( (*it).second.us );
2106// Keyword pas trouve
2107if (videstr == NULL) videstr = new string("");
2108*videstr = "Nothing known about " + kw + " ?? ";
2109return(*videstr);
2110
2111}
2112
2113
2114/* Les definitions suivantes doivent se trouver ds l'en-tete du fichier LaTeX
2115 \newcommand{\piacommand}[1]{
2116 \framebox{\bf \Large #1 } \index{#1} % (Command)
2117 }
2118
2119 \newcommand{\piahelpitem}[1]{
2120 \framebox{\bf \Large #1 } \index{#1} (Help item)
2121 }
2122
2123 \newcommand{\myppageref}[1]{ (p. \pageref{#1} ) }
2124*/
2125
2126// Fonction qui remplace tout caractere non alphanumerique en Z
2127static void check_latex_reflabel(string & prl)
2128{
2129 for(int k=0; k<prl.length(); k++)
2130 if (! isalnum(prl[k]) ) prl[k] = 'Z';
2131}
2132
2133// Fonction qui remplace _ en \_
2134static string check_latex_underscore(string const & mot)
2135{
2136 string rs;
2137 for(int k=0; k<mot.length(); k++) {
2138 if (mot[k] == '_') rs += "\\_";
2139 else rs += mot[k];
2140 }
2141 return rs;
2142}
2143
2144/* --Methode-- */
2145//! Produces a LaTeX file containing the registered command helps
2146void Commander::HelptoLaTeX(string const & fname)
2147{
2148FILE *fip;
2149if ((fip = fopen(fname.c_str(), "w")) == NULL) {
2150 cout << "Commander::HelptoLaTex_Error: fopen( " << fname << endl;
2151 return;
2152 }
2153
2154fputs("% ----- Liste des groupes de Help ----- \n",fip);
2155fputs("List of {\\bf piapp} on-line Help groups: \n", fip);
2156fputs("\\begin{itemize} \n",fip);
2157string prl;
2158string mol;
2159CmdHGroup::iterator it;
2160for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
2161 if ((*it).first == "All") continue;
2162 prl = (*it).first; check_latex_reflabel(prl);
2163 mol = check_latex_underscore((*it).first);
2164 fprintf(fip,"\\item {\\bf %s } (p. \\pageref{%s}) \n",
2165 mol.c_str(), prl.c_str());
2166}
2167
2168fputs("\\end{itemize} \n",fip);
2169
2170fputs("\\vspace*{10mm} \n",fip);
2171
2172CmdExmap::iterator ite;
2173fputs("% ----- Liste de toutes les commandes et help item ----- \n",fip);
2174fputs("\\vspace{5mm} \n",fip);
2175// fputs("\\begin{table}[h!] \n", fip);
2176fputs("\\begin{center} \n ", fip);
2177fputs("\\rule{2cm}{1mm} List of {\\bf piapp} Help items \\rule{2cm}{1mm} \\\\ \n", fip);
2178fputs("\\vspace{3mm} \n",fip);
2179fputs("\\begin{tabular}{llllll} \n", fip);
2180int kt = 0;
2181for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
2182 prl = (*ite).first; check_latex_reflabel(prl);
2183 mol = check_latex_underscore((*ite).first);
2184 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
2185 kt++;
2186 if (kt < 3) fputs(" & ", fip);
2187 else { fputs(" \\\\ \n", fip); kt = 0; }
2188 }
2189if (kt == 1) fputs(" & & & \\\\ \n", fip);
2190else if (kt == 2) fputs(" & \\\\ \n", fip);
2191fputs("\\end{tabular} \n", fip);
2192fputs("\\end{center} \n", fip);
2193//fputs("\\end{table} \n", fip);
2194fputs("\\newpage \n",fip);
2195
2196int gid;
2197for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
2198 gid = (*it).second.gid;
2199 if (gid == 0) continue;
2200 // fputs("\\begin{table}[h!] \n",fip);
2201 fputs("\\vspace{6mm} \n",fip);
2202 fputs("\\begin{center} \n ", fip);
2203 fprintf(fip, "\\rule{2cm}{0.5mm} \\makebox[60mm]{{ \\bf %s } help group} \\rule{2cm}{0.5mm} \\\\ \n",
2204 (*it).first.c_str());
2205 fputs("\\vspace{3mm} \n",fip);
2206 fputs("\\begin{tabular}{llllll} \n", fip);
2207 kt = 0;
2208 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
2209 if ((*ite).second.group != gid) continue;
2210 prl = (*ite).first; check_latex_reflabel(prl);
2211 mol = check_latex_underscore((*ite).first);
2212 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
2213 kt++;
2214 if (kt < 3) fputs(" & ", fip);
2215 else { fputs(" \\\\ \n", fip); kt = 0; }
2216 }
2217 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
2218 if ((*ite).second.group != gid) continue;
2219 prl = (*ite).first; check_latex_reflabel(prl);
2220 mol = check_latex_underscore((*ite).first);
2221 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
2222 kt++;
2223 if (kt < 3) fputs(" & ", fip);
2224 else { fputs(" \\\\ \n", fip); kt = 0; }
2225 }
2226 if (kt == 1) fputs(" & & & \\\\ \n", fip);
2227 else if (kt == 2) fputs(" & \\\\ \n", fip);
2228 fputs("\\end{tabular} \n", fip);
2229 fputs("\\end{center} \n", fip);
2230 // fputs("\\end{table} \n",fip);
2231 // fputs("\\vspace{5mm} \n",fip);
2232}
2233// fputs("\\newline \n",fip);
2234
2235fputs("% ----- Liste des commandes dans chaque groupe ----- \n",fip);
2236fputs("\\newpage \n",fip);
2237
2238for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
2239 gid = (*it).second.gid;
2240 if (gid == 0) continue;
2241 prl = (*it).first; check_latex_reflabel(prl);
2242 fprintf(fip,"\\subsection{%s} \\label{%s} \n",
2243 (*it).first.c_str(), prl.c_str());
2244 if ((*it).second.desc.length() > 0)
2245 fprintf(fip,"%s \n \\\\[2mm] ", (*it).second.desc.c_str());
2246 fprintf(fip,"\\noindent \n");
2247 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
2248 if ((*ite).second.group != gid) continue;
2249 prl = (*ite).first; check_latex_reflabel(prl);
2250 mol = check_latex_underscore((*ite).first);
2251 fprintf(fip,"\\piahelpitem{%s} \\label{%s} \n",
2252 mol.c_str(), prl.c_str());
2253 fputs("\\begin{verbatim} \n",fip);
2254 fprintf(fip,"%s\n", (*ite).second.us.c_str());
2255 fputs("\\end{verbatim} \n",fip);
2256 }
2257 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
2258 if ((*ite).second.group != gid) continue;
2259 prl = (*ite).first; check_latex_reflabel(prl);
2260 mol = check_latex_underscore((*ite).first);
2261 fprintf(fip,"\\piacommand{%s} \\label{%s} \n",
2262 mol.c_str(), prl.c_str());
2263 fputs("\\begin{verbatim} \n",fip);
2264 fprintf(fip,"%s\n", (*ite).second.us.c_str());
2265 fputs("\\end{verbatim} \n",fip);
2266 }
2267}
2268
2269fclose(fip);
2270cout << " Commander::HelptoLaTeX() - LaTeX format help written to file " << fname << endl;
2271
2272return;
2273}
2274
2275
2276} // End of namespace SOPHYA
2277
Note: See TracBrowser for help on using the repository browser.