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

Last change on this file since 2796 was 2796, checked in by ansari, 20 years ago

Remplacement is.getline(...) par getline(istream,string) - CxxCompilerLinker: ajout flag -pthread pour cxx et commandes pour icc (Intel) - Reza 3 Juin 2005

File size: 63.4 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 if (felevel == 0) { // Il faut executer le bloc
850 CommanderBloc* curb = CmdBlks.top();
851 CmdBlks.top() = curb->Parent();
852 SetCurrentPrompt("Cmd> ");
853 if (!curb->CheckBloc()) {
854 cerr << "Commander::Interpret()/syntax error - unbalenced if ... endif"
855 << " within for/foreach/forinfile bloc ! " << endl;
856 delete curb;
857 _xstatus = 93;
858 return(93);
859 }
860 // cout << " *DBG* Executing bloc " << endl;
861 bool ohv = histon;
862 histon = false;
863 if (curtestresult) {
864 // We push also CommanderBloc and testresult on the stack
865 CmdBlks.push(NULL);
866 list<char> xtx;
867 TestsStack.push(xtx);
868 curb->Execute();
869 // And CommanderBloc and TestResult from the corresponding stacks
870 PopStack(false);
871 }
872 SetCurrentPrompt(defprompt);
873 delete curb;
874 histon = ohv;
875 }
876 else CmdBlks.top()->AddLine(s, kw);
877 _xstatus = 0;
878 return(0);
879}
880else if (kw == "end") {
881 cerr << "Commander::Interpret()/syntax error - end outside for/foreach/forinfile bloc \n"
882 << "line: " << s << endl;
883 _xstatus = 94;
884 return(94);
885}
886
887// Sommes-nous dans un bloc de test if then else
888if (TestsStack.top().size() > 0) { // Nous sommes ds un bloc if
889 if (kw == "else") {
890 if ((*tresit) & 2) {
891 cerr << "Commander::Interpret()/syntax error - multiple else in if bloc \n"
892 << "line: " << s << endl;
893 _xstatus = 95;
894 return(95);
895 }
896 else {
897 const char * npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
898 if ((*tresit)&1) curtestresult = false;
899 SetCurrentPrompt(npr);
900 (*tresit) |= 2;
901 _xstatus = 0;
902 return(0);
903 }
904 }
905 else if (kw == "endif") {
906 list<char>::iterator dbit = tresit;
907 tresit--;
908 TestsStack.top().erase(dbit);
909 const char * npr = "Cmd> ";
910 if (TestsStack.top().size() > 1) {
911 curtestresult = true;
912 list<char>::iterator it;
913 for(it=TestsStack.top().begin(); it!=TestsStack.top().end(); it++) {
914 // Si on n'est pas ds le else et le if est faux
915 if ( !((*it)&2) && !((*it)&1) ) curtestresult = false;
916 // Si on est ds else et le if etait vrai !
917 if ( ((*it)&2) && ((*it)&1) ) curtestresult = false;
918 if (!curtestresult) break;
919 }
920
921 if (!((*tresit)&2))
922 npr = ((*tresit)&1) ? "if-T> " : "if-F> ";
923 else
924 npr = ((*tresit)&1) ? "else-F> " : "else-T> ";
925 }
926 else curtestresult = true;
927 SetCurrentPrompt(npr);
928 _xstatus = 0;
929 return(0);
930 }
931}
932else if ((kw == "else") || (kw == "endif")) {
933 cerr << "Commander::Interpret()/syntax error - else,endif outside if bloc \n"
934 << "line: " << s << endl;
935 _xstatus = 91;
936 return(91);
937}
938
939bool fgcont = true;
940if (TestsStack.top().size() > 0) { // Resultat de if ou else
941 list<char>::iterator it;
942 for(it=TestsStack.top().begin(); it!=TestsStack.top().end(); it++) {
943 // Si on n'est pas ds le else et le if est faux
944 if ( !((*it)&2) && !((*it)&1) ) fgcont = false;
945 // Si on est ds else et le if etait vrai !
946 if ( ((*it)&2) && ((*it)&1) ) fgcont = false;
947 if (!fgcont) break;
948 }
949}
950
951if ((!fgcont) && (kw != "if")) {
952 _xstatus = 0;
953 return(0);
954}
955
956
957// Les mots cles break et return peuvent de sortir de boucles/scripts/execfile
958if (kw == "break") return CMD_BREAK_RC;
959else if (kw == "return") {
960 _retstr = toks;
961 return CMD_RETURN_RC;
962}
963
964// Nous ne sommes donc pas dans un bloc .... Substitution de variables
965string s2;
966int rcs ;
967
968rcs = SubstituteVars(s, s2);
969if (rcs) {
970 cerr << "Commander::Interpret()/syntax error in SubstituteVars() \n"
971 << "line: " << s << endl;
972 _xstatus = 99;
973 return(99);
974}
975// >>>> Separating keyword and tokens
976vector<string> tokens;
977vector<bool> qottoks;
978/* decoupage en mots */
979LineToWords(s2, kw, tokens, qottoks, toks, true);
980
981// Si c'est un for/foreach, on cree un nouveau bloc
982if ((kw == "foreach") || (kw == "for") || (kw == "forinfile") ) {
983 // cout << " *DBG* We got a foreach... " << endl;
984 CommanderBloc* bloc = new CommanderBloc(this, CmdBlks.top(), kw, tokens);
985 if (!bloc->CheckOK()) {
986 cerr << "Commander::Interpret() for/foreach syntax Error ! " << endl;
987 delete bloc;
988 _xstatus = 91;
989 return(91);
990 }
991 felevel++;
992 if (CmdBlks.top()) CmdBlks.top()->AddBloc(bloc);
993 else SetCurrentPrompt("for...> ");
994 CmdBlks.top() = bloc;
995 // cout << " *DBG* New Bloc created ... " << endl;
996 return(0);
997 }
998else if (kw == "if") { // Un test if
999 bool restst = true;
1000 int rct = EvaluateTest(tokens, s, restst);
1001 if (rct) {
1002 cerr << "Commander::Interpret() if syntax Error ! " << "line: " << s << endl;
1003 _xstatus = 91;
1004 return(91);
1005 }
1006 char res_tst = (restst) ? 1 : 0;
1007 TestsStack.top().push_back(res_tst);
1008 if (TestsStack.top().size() == 1) tresit = TestsStack.top().begin();
1009 else tresit++;
1010 const char * npr = (restst) ? "if-T> " : "if-F> ";
1011 SetCurrentPrompt(npr);
1012}
1013else if ((tokens.size() > 0) && (tokens[0] == "=")) {
1014 // x = Expression
1015 if (qottoks[1]) { // decodage sous forme de chaine
1016 SetVariable(kw, tokens[1]);
1017 }
1018 else {
1019 try {
1020 double res = 0.;
1021 if (tokens.size() > 2) {
1022 string sex = tokens[1];
1023 for(int js=2; js<tokens.size(); js++) sex += tokens[js];
1024 CExpressionEvaluator cex(sex);
1025 res = cex.Value();
1026 }
1027 else {
1028 CExpressionEvaluator cex(tokens[1]);
1029 res = cex.Value();
1030 }
1031 char cbuff[64];
1032 sprintf(cbuff,"%g",res);
1033 string vv = cbuff;
1034 SetVariable(kw, vv);
1035 }
1036 catch (CExprException& cexerr) {
1037 cerr << "Commander::Interpret() evaluation Error : \n " << "line: " << s
1038 << " \n Msg=" << cexerr.Msg() << endl;
1039 _xstatus = 98;
1040 return(98);
1041 }
1042 }
1043}
1044else if (kw == "defscript") { // definition de script
1045 if (tokens.size() > 0) {
1046 if (tokens.size() < 2) tokens.push_back("");
1047 curscript = new CommanderScript(this, tokens[0], tokens[1]);
1048 SetCurrentPrompt("Script...> ");
1049 return(0);
1050 }
1051 else {
1052 cerr << "Commander::Interpret() No script name in defscript" << "line: " << s << endl;
1053 _xstatus = 91;
1054 return(91);
1055 }
1056}
1057else {
1058 // Si c'est le nom d'un script
1059 sit = mScripts.find(kw);
1060 if (sit != mScripts.end()) {
1061 bool ohv = histon;
1062 histon = false;
1063 tokens.insert(tokens.begin(), kw);
1064 PushStack(tokens);
1065 (*sit).second->Execute(tokens);
1066 PopStack(true);
1067 histon = ohv;
1068 }
1069 // Execution de commandes
1070 else rc = ExecuteCommandLine(kw, tokens, toks);
1071 _xstatus = rc;
1072 return(rc);
1073}
1074// cout << "Commander::Do() DBG KeyW= " << kw << " NbArgs= " << tokens.size() << endl;
1075// for(int ii=0; ii<tokens.size(); ii++)
1076// cout << "arg[ " << ii << " ] : " << tokens[ii] << endl;
1077
1078return(0);
1079}
1080
1081void Commander::StopExecution()
1082{
1083 fgexebrk = true;
1084}
1085
1086
1087/* --Methode-- */
1088int Commander::LineToWords(string& line, string& kw, vector<string>& tokens,
1089 vector<bool>& qottoks, string& toks, bool uq)
1090{
1091if (line.length() < 1) return(0);
1092int nw = 1;
1093size_t p = line.find_first_not_of(" ");
1094line = line.substr(p);
1095p = 0;
1096size_t q = line.find_first_of(" ");
1097size_t l = line.length();
1098
1099if (q < l)
1100 { kw = line.substr(p,q-p); toks = line.substr(q, l-q); }
1101else { kw = line.substr(p,l-p); toks = ""; }
1102
1103q = 0;
1104while (q < l) {
1105 bool swq = false; // true -> chaine delimite par ' ou "
1106 p = toks.find_first_not_of(" \t",q+1); // au debut d'un token
1107 if (p>=l) break;
1108 if ( uq && ((toks[p] == '\'') || (toks[p] == '"')) ) {
1109 q = toks.find(toks[p],p+1);
1110 if (q>=l) {
1111 cerr << "Commander::LineToWords/Syntax Error - Unbalenced quotes " << toks[p] << '.' << endl;
1112 return(-1);
1113 }
1114 p++; swq = true;
1115 }
1116 else {
1117 q = toks.find_first_of(" \t",p); // la fin du token;
1118 }
1119 string token = toks.substr(p,q-p);
1120 tokens.push_back(token);
1121 qottoks.push_back(swq);
1122 nw++;
1123 }
1124
1125return(nw);
1126}
1127
1128/* --Methode-- */
1129int Commander::SubstituteVars(string & s, string & s2)
1130// Variable substitution
1131{
1132
1133int iarr = -1; // index d'element de tableau
1134size_t p,q,q2,q3,l;
1135
1136s2="";
1137p = 0;
1138l = s.length();
1139string vn, vv;
1140while (p < l) {
1141 iarr = -1;
1142 q = s.find('$',p);
1143 if (q > l) break;
1144 q2 = s.find('\'',p);
1145 if ((q2 < l) && (q2 < q)) { // On saute la chaine delimitee par ' '
1146 q2 = s.find('\'',q2+1);
1147 if (q2 >= l) {
1148 cerr << " Syntax error - Unbalenced quotes !!! " << endl;
1149 return(1);
1150 }
1151 s2 += s.substr(p, q2-p+1);
1152 p = q2+1; continue;
1153 }
1154 // cout << "DBG: " << s2 << " p= " << p << " q= " << q << " L= " << l << endl;
1155 if ((q>0) && (s[q-1] == '\\')) { // Escape character \$
1156 s2 += (s.substr(p,q-1-p) + '$') ; p = q+1;
1157 continue;
1158 }
1159 if (q >= l-1) {
1160 cerr << " Syntax error - line ending with $ !!! " << endl;
1161 return(2);
1162 }
1163 vn = "";
1164 if ( s[q+1] == '{' ) { // Variable in the form ${name}
1165 q2 = s.find('}',q+1);
1166 if (q2 >= l) {
1167 cerr << " Syntax error - Unbalenced brace {} !!! " << endl;
1168 return(3);
1169 }
1170 vn = s.substr(q+2,q2-q-2);
1171 q2++;
1172 }
1173 else if ( s[q+1] == '(' ) { // Variable in the form $(name)
1174 q2 = s.find(')',q+1);
1175 if (q2 >= l) {
1176 cerr << " Syntax error - Unbalenced parenthesis () !!! " << endl;
1177 return(3);
1178 }
1179 vn = s.substr(q+2,q2-q-2);
1180 q2++;
1181 }
1182 else if ( s[q+1] == '[' ) { // Variable in the form $[varname] -> This is $$varname
1183 q2 = s.find(']',q+1);
1184 if (q2 >= l) {
1185 cerr << " Syntax error - Unbalenced brace [] !!! " << endl;
1186 return(4);
1187 }
1188 vn = s.substr(q+2,q2-q-2);
1189 if (!Var2Str(vn, vv)) return(5);
1190 vn = vv;
1191 q2++;
1192 }
1193 else {
1194 if (s[q+1] == '#' ) q3 = q+2; // Variable in the form $#varname
1195 else q3 = q+1;
1196 q2 = s.find_first_of(" .:+-*/,[](){}&|!$\"'<>^%=#@\\",q3);
1197 if (q2 > l) q2 = l;
1198 q3 = q2;
1199 vn = s.substr(q+1, q2-q-1);
1200 // Si variable de type $varname[index] : element de tableau
1201 if ((q2 < l) && (s[q2] == '[') ) {
1202 q3 = s.find_first_of("]",q2+1);
1203 string sia = s.substr(q2+1, q3-q2-1);
1204 if (sia.length() < 1) {
1205 cerr << " Syntax error - in $varname[index] : $"
1206 << vn << "[" << sia <<"]" << endl;
1207 return(4);
1208 }
1209 if (isalpha(sia[0])) {
1210 string sia2;
1211 if (!Var2Str(sia, sia2) || (sia2.length() < 1)) {
1212 cerr << " Syntax error - in $varname[index] : $"
1213 << vn << "[" << sia <<"]" << endl;
1214 return(4);
1215 }
1216 sia = sia2;
1217 }
1218 int rcdia = ctoi(sia.c_str(), &iarr);
1219 if (rcdia < 0) {
1220 cerr << " Syntax error - in $varname[iarr] : $"
1221 << vn << "[" << sia <<"]" << endl;
1222 return(4);
1223 }
1224 }
1225 }
1226 if (iarr < 0) {
1227 if (!Var2Str(vn, vv)) return(5);
1228 s2 += (s.substr(p, q-p) + vv);
1229 p = q2;
1230 }
1231 else {
1232 if (! Var2Str(vn, iarr, vv) ) {
1233 cerr << " Substitution error - word index out of range in "
1234 << "$varname[iarr] : $" << vn << "[" << iarr <<"]" << endl;
1235 return(4);
1236 }
1237 else s2 += (s.substr(p, q-p) + vv);
1238 p = q3+1;
1239 }
1240}
1241if (p < l) s2 += s.substr(p);
1242
1243p = s2.find_first_not_of(" \t");
1244if (p < l) s2 = s2.substr(p);
1245
1246return(0);
1247}
1248
1249/* --Methode-- */
1250bool Commander::Var2Str(string const & vn, string & vv)
1251{
1252if (vn.length() < 1) {
1253 cerr << " Commander::Var2Str/Error: length(varname=" << vn << ")<1 !" << endl;
1254 vv = ""; return(false);
1255}
1256// Variable de type $# $0 $1 ... (argument de .pic ou de script)
1257int ka = 0;
1258char buff[32];
1259
1260if (vn == "#") {
1261 if (ArgsStack.empty()) {
1262 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1263 << " ($" << vn << ")" << endl;
1264 vv = ""; return(false);
1265 }
1266 char buff[32];
1267 long an = ArgsStack.top().size();
1268 if (an > 0) an--; // Pour se conformer a l'usage de csh : Nb args sans le $0
1269 sprintf(buff,"%ld", an);
1270 vv = buff; return(true);
1271}
1272else if (vn == "*") {
1273 if (ArgsStack.empty()) {
1274 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1275 << " ($" << vn << ")" << endl;
1276 vv = ""; return(false);
1277 }
1278 vv = ArgsStack.top()[0];
1279 for(int ssk=1; ssk<ArgsStack.top().size(); ssk++) vv += ArgsStack.top()[ssk];
1280 return(true);
1281}
1282else if (ctoi(vn.c_str(), &ka) > 0) { // $0 $1 $2 ...
1283 if (ArgsStack.empty()) {
1284 cerr << " Commander::Var2Str/Error: ArgsStack empty ! "
1285 << " ($" << vn << ")" << endl;
1286 vv = ""; return(false);
1287 }
1288 if ( (ka < 0) || (ka >= ArgsStack.top().size()) ) {
1289 cerr << " Commander::Var2Str/Error: ArgsStack index <0 or >=args.size() ! "
1290 << " ($" << vn << ")" << endl;
1291 vv = ""; return(false);
1292 }
1293 vv = ArgsStack.top()[ka]; return(true);
1294}
1295else if (vn[0] == '#') { // Variable de type $#vname --> size(vname)
1296 CmdVarList::iterator it = variables.find(vn.substr(1));
1297 if (it == variables.end()) {
1298 cerr << " Commander::Var2Str/Error #vname Undefined variable "
1299 << vn << " ! " << endl;
1300 vv = ""; return(false);
1301 }
1302 sprintf(buff,"%d", (int)(*it).second.size());
1303 vv = buff; return(true);
1304}
1305else if (vn == "status") {
1306 sprintf(buff,"%d", _xstatus);
1307 vv = buff;
1308 return true;
1309}
1310else if ((vn == "retstr") || (vn == "retval")) {
1311 vv = _retstr;
1312 return true;
1313}
1314else { // Variable de l'interpreteur, ou de l'environnement application , env. global
1315 if (GetVar(vn, vv)) return true;
1316 else if (GetVarApp(vn, vv)) return true;
1317 else if (GetVarEnv(vn, vv)) return true;
1318 else {
1319 cerr << " Commander::Var2Str/Error Undefined variable "
1320 << vn << " ! " << endl;
1321 vv = ""; return false;
1322 }
1323}
1324
1325return false;
1326}
1327
1328/* --Methode-- */
1329bool Commander::SetVariable(string const & vn, string const & vv)
1330{
1331 // On verifie si le nom est de type vname[idx]
1332 size_t p,q,l;
1333 l = vn.length();
1334 p = vn.find('[');
1335 if (p < l) {
1336 q = vn.find(']');
1337 if (q != (l-1)) {
1338 cout << "Commander::Str2Var/SetVar() - Bad varname with []: "
1339 << vn << endl;
1340 return false;
1341 }
1342 string vna = vn.substr(0, p);
1343 string sia = vn.substr(p+1, q-(p+1));
1344 if (isalpha(sia[0])) {
1345 string sia2;
1346 if (!Var2Str(sia, sia2) || (sia2.length() < 1)) {
1347 cerr << "Commander::Str2Var/SetVar() Syntax error- varname[index]:"
1348 << vn << endl;
1349 return false;
1350 }
1351 sia = sia2;
1352 }
1353 int iarr;
1354 int rcdia = ctoi(sia.c_str(), &iarr);
1355 if (rcdia < 0) {
1356 cerr << "Commander::Str2Var/SetVar() Syntax error- varname[iarr]: "
1357 << vn << endl;
1358 return false;
1359 }
1360 return SetVar(vna, iarr, vv);
1361 }
1362 else {
1363 if (vn == "status") {
1364 _xstatus = atoi(vv.c_str());
1365 return true;
1366 }
1367 else if (vn == "retstr") {
1368 _retstr = vv;
1369 return true;
1370 }
1371 else return SetVar(vn, vv);
1372 }
1373}
1374
1375/* --Methode-- */
1376bool Commander::GetVar(string const & vn, string & vv)
1377{
1378 CmdVarList::iterator it = variables.find(vn);
1379 if (it == variables.end()) {
1380 vv = "";
1381 return false;
1382 }
1383 vv = (*it).second[0];
1384 if ((*it).second.size() > 1) {
1385 for(int k=1; k<(*it).second.size(); k++) {
1386 vv += ' '; vv += (*it).second[k];
1387 }
1388 }
1389 return true;
1390}
1391
1392/* --Methode-- */
1393bool Commander::GetVar(string const & vn, int idx, string & vv)
1394{
1395 vv = "";
1396 CmdVarList::iterator it = variables.find(vn);
1397 if (it == variables.end()) return false;
1398 if ((idx < 0) || (idx > (*it).second.size()-1))
1399 return false;
1400 vv = (*it).second[idx];
1401 return true;
1402}
1403
1404/* --Methode-- */
1405bool Commander::GetVar(string const & vn, vector<string> & vv)
1406{
1407 vv.clear();
1408 // vv.erase(vv.begin(),vv.end());
1409 CmdVarList::iterator it = variables.find(vn);
1410 if (it == variables.end()) return false;
1411 vv = (*it).second;
1412 return true;
1413}
1414
1415/* --Methode-- */
1416bool Commander::SetVar(string const & vn, string const & val)
1417{
1418 if ( !CheckVarName(vn) ) {
1419 cerr << "Commander::SetVar( " << vn << " ...) Bad VarName " << endl;
1420 return(false);
1421 }
1422 bool fg = false;
1423 vector<string> nouv;
1424 nouv.push_back(val);
1425 CmdVarList::iterator it = variables.find(vn);
1426 if (it == variables.end()) variables[vn] = nouv;
1427 else {
1428 (*it).second = nouv;
1429 fg = true;
1430 }
1431 return fg;
1432}
1433
1434/* --Methode-- */
1435bool Commander::SetVar(string const & vn, int idx, string const & val)
1436{
1437 if ( !CheckVarName(vn) ) {
1438 cerr << "Commander::SetVar( " << vn << " ,idx, ...) Bad VarName " << endl;
1439 return(false);
1440 }
1441 if ((vn == "status") || (vn == "retstr")) {
1442 cerr << "Commander::SetVar(vn,idx,val) ERROR - special var status/retstr "
1443 << endl;
1444 return(false);
1445 }
1446 if (idx < 0) {
1447 cout << "Commander::SetVar(vn," << idx << ",...) Error idx < 0" << endl;
1448 return(false);
1449 }
1450 bool fg = false;
1451 CmdVarList::iterator it = variables.find(vn);
1452 if (it == variables.end()) {
1453 vector<string> nouv;
1454 for(int j=0; j<idx; j++) nouv.push_back("");
1455 nouv.push_back(val);
1456 variables[vn] = nouv;
1457 }
1458 else {
1459 if (idx >= (*it).second.size())
1460 for(int j=(*it).second.size(); j<=idx; j++) (*it).second.push_back("");
1461 (*it).second[idx] = val;
1462 fg = true;
1463 }
1464 return fg;
1465}
1466
1467/* --Methode-- */
1468bool Commander::SetVar(string const & vn, vector<string> const & val)
1469{
1470 if ( !CheckVarName(vn) ) {
1471 cerr << "Commander::SetVar( " << vn << " ...) Bad VarName " << endl;
1472 return(false);
1473 }
1474 if ((vn == "status") || (vn == "retstr")) {
1475 cerr << "Commander::SetVar(vn, vector<string>) ERROR - special var status/retstr "
1476 << endl;
1477 return(false);
1478 }
1479 bool fg = false;
1480 CmdVarList::iterator it = variables.find(vn);
1481 if (it == variables.end()) variables[vn] = val;
1482 else {
1483 (*it).second = val;
1484 fg = true;
1485 }
1486 return fg;
1487}
1488
1489/* --Methode-- */
1490bool Commander::CheckVarName(string const & vn)
1491{
1492 size_t l,k;
1493 l = vn.length();
1494 if (l < 1) return false;
1495 if (!isalpha(vn[0])) return false;
1496 for(k=1; k<l; k++)
1497 if ((!isalnum(vn[k])) && (vn[k] != '_')) return false;
1498 return true;
1499}
1500
1501/* --Methode-- */
1502bool Commander::DeleteVar(string const & vn)
1503{
1504 CmdVarList::iterator it = variables.find(vn);
1505 if (it == variables.end()) {
1506 cerr << "Commander::DeleteVar() Var " << vn << " undefined!" << endl;
1507 return false;
1508 }
1509 variables.erase(it);
1510 return true;
1511}
1512
1513/* --Methode-- */
1514void Commander::ListVar()
1515{
1516 cout << " ---- Commander::ListVar() List of defined variables ---- "
1517 << endl;
1518 CmdVarList::iterator it;
1519 for(it = variables.begin(); it != variables.end(); it++) {
1520 string vn = (*it).first;
1521 int vs = (*it).second.size();
1522 cout << vn << " -> Size= " << vs << endl;
1523 }
1524 cout << "---------------------------------------------------------- "
1525 << endl;
1526}
1527
1528/* --Methode-- */
1529bool Commander::GetVarApp(string const & vn, string & vv)
1530{
1531 vv = "";
1532 // cout << " Commander::GetVarApp() Not available ! " << endl;
1533 return false;
1534}
1535
1536/* --Methode-- */
1537bool Commander::SetVarApp(string const & vn, string const & vv)
1538{
1539 // cout << " Commander::SetVarApp() Not available ! " << endl;
1540 return false;
1541}
1542
1543/* --Methode-- */
1544bool Commander::DeleteVarApp(string const & vn)
1545{
1546 // cout << " Commander::DeleteVarApp() Not available ! " << endl;
1547 return false;
1548}
1549
1550/* --Methode-- */
1551void Commander::ListVarApp()
1552{
1553 // cout << " Commander::ListVarApp() Not available ! " << endl;
1554 return;
1555}
1556
1557
1558/* --Methode-- */
1559bool Commander::GetVarEnv(string const & vn, string & vv)
1560{
1561 char* vev = getenv(vn.c_str());
1562 if (vev) {
1563 vv = vev;
1564 return true;
1565 }
1566 else {
1567 vv = "";
1568 return false;
1569 }
1570}
1571
1572/* --Methode-- */
1573bool Commander::SetVarEnv(string const & vn, string const & vv)
1574{
1575 string pev = vn;
1576 pev += '=';
1577 pev += vv;
1578#if defined(Linux)
1579// Reza - 28/04/2004
1580// putenv de Linux ne declare pas la variable char *string const
1581// On ne doit meme pas utiliser une variable automatique
1582// J'alloue donc un nouveau tableau - mais qui va le liberer ?
1583 char* bev = new char[pev.size()+1];
1584 strcpy(bev, pev.c_str());
1585 if (putenv(bev) == 0) return true;
1586#else
1587 if (putenv(pev.c_str()) == 0) return true;
1588#endif
1589 else return false;
1590}
1591
1592/* --Methode-- */
1593bool Commander::DeleteVarEnv(string const & vn)
1594{
1595 // cout << " Commander::DeleteVarEnv() Not available ! " << endl;
1596 return false;
1597}
1598
1599/* --Methode-- */
1600void Commander::ListVarEnv()
1601{
1602 cout << " Commander::ListVarEnv() Not available ! " << endl;
1603 return;
1604}
1605
1606
1607/* --Methode-- */
1608string Commander::GetTmpDir()
1609{
1610 return("/tmp");
1611}
1612
1613/* --Methode-- */
1614void Commander::SetCurrentPrompt(const char* pr)
1615{
1616 curprompt = pr;
1617}
1618
1619/* --Methode-- */
1620void Commander::ShowMessage(const char * msg, int att)
1621{
1622 cout << msg ;
1623}
1624
1625
1626
1627/* --Methode-- */
1628int Commander::EvaluateTest(vector<string> & args, string & line, bool & res)
1629{
1630 res = true;
1631 if ((args.size() != 6) || (args[5] != "then") ||
1632 (args[0] != "(") || (args[4] != ")") ) return(1);
1633 if (args[2] == "==") res = (args[1] == args[3]);
1634 else if (args[2] == "!=") res = (args[1] != args[3]);
1635 else if (args[2] == "<")
1636 res = (atof(args[1].c_str()) < atof(args[3].c_str()));
1637 else if (args[2] == ">")
1638 res = (atof(args[1].c_str()) > atof(args[3].c_str()));
1639 else if (args[2] == "<=")
1640 res = (atof(args[1].c_str()) <= atof(args[3].c_str()));
1641 else if (args[2] == ">=")
1642 res = (atof(args[1].c_str()) >= atof(args[3].c_str()));
1643 else return(2);
1644 return(0);
1645}
1646
1647
1648/* --Methode-- */
1649int Commander::EvalRPNExpr(vector<string> & args, string & line)
1650{
1651 // A virer - Reza 15/03/2004
1652 return(0);
1653}
1654
1655/* --Methode-- */
1656void Commander::PushStack(vector<string>& args)
1657{
1658 // We push the argument list (args) on the stack
1659 ArgsStack.push(args);
1660 // We push also CommanderBloc and testresult on the stack
1661 CmdBlks.push(NULL);
1662 list<char> xtx;
1663 TestsStack.push(xtx);
1664
1665}
1666
1667/* --Methode-- */
1668void Commander::PopStack(bool psta)
1669{
1670 // We remove the argument list (args) from the stack
1671 if (psta) ArgsStack.pop();
1672 // And CommanderBloc and TestResult from the corresponding stacks
1673 CommanderBloc* curb = CmdBlks.top();
1674 while (curb != NULL) {
1675 CommanderBloc* parb = curb->Parent();
1676 delete curb; curb = parb;
1677 }
1678 CmdBlks.pop();
1679 TestsStack.pop();
1680}
1681
1682/* --Methode-- */
1683int Commander::ExecuteCommandLine(string & kw, vector<string> & tokens, string & toks)
1684{
1685int rc = 0;
1686
1687// >>>>>>>>>>> Commande d'interpreteur
1688if (kw == "help") {
1689 if (tokens.size() > 0) cout << GetUsage(tokens[0]) << endl;
1690 else {
1691 string kwh = "Commander";
1692 cout << GetUsage(kwh) << endl;
1693 }
1694 }
1695else if (kw == "sleep") {
1696 if (tokens.size() < 1) {
1697 cout << "Commander::Interpret() Usage: sleep nsec " << endl;
1698 return(1);
1699 }
1700 int nsec = atoi(tokens[0].c_str());
1701 cout << "Commander::Interpret() sleep " << nsec << " seconds" << endl;
1702 sleep(nsec);
1703}
1704
1705else if (kw == "set") {
1706 if (tokens.size() < 2) {
1707 cout << "Commander::Interpret() Usage: set varname value or set vecvar ( w1 w2 ... ) " << endl;
1708 return(1);
1709 }
1710
1711 if (tokens.size() == 2)
1712 SetVariable(tokens[0], tokens[1]);
1713 else {
1714 if ( (tokens[1] != "(") || (tokens[tokens.size()-1] != ")") ) {
1715 cout << "Commander::Interpret() Usage: set vecvar ( w1 w2 ... ) " << endl;
1716 return(1);
1717 }
1718 string vname = tokens[0];
1719 vector<string>::iterator vit;
1720 vit = tokens.begin(); tokens.erase(vit);
1721 vit = tokens.begin(); tokens.erase(vit);
1722 tokens.pop_back();
1723 SetVar(vname, tokens);
1724 }
1725 return 0;
1726}
1727else if (kw == "var2words") {
1728 if (tokens.size() < 2) {
1729 cout << "Commander::Interpret() Usage: var2words varname wordvarname [sep]" << endl;
1730 return(1);
1731 }
1732 char sep = ' ';
1733 if (tokens.size() > 2) sep = tokens[2][0];
1734 string vv;
1735 if (!GetVar(tokens[0], vv)) {
1736 cout << "Commander::Interpret() var2words/Error No variable with name " << tokens[0] << endl;
1737 return 2;
1738 }
1739 vector<string> vs;
1740 FillVStringFrString(vv, vs, sep);
1741 SetVar(tokens[1], vs);
1742}
1743else if (kw == "alias") {
1744 if (tokens.size() < 2) { cout << "Commander::Interpret() Usage: alias aliasname string" << endl; return(0); }
1745 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
1746 cerr << "Commander::Interpret()/Error alias name should start with alphabetic" << endl;
1747 return(1);
1748 }
1749 string xx = tokens[1];
1750 for (int kk=2; kk<tokens.size(); kk++) xx += (' ' + tokens[kk]);
1751 mAliases[tokens[0]] = xx;
1752}
1753
1754else if ( (kw == "unset") || (kw == "clearvar") ) {
1755 if (tokens.size() < 1) {
1756 cout << "Commander::Interpret() Usage: unset/clearvar varname" << endl;
1757 return(1);
1758 }
1759 else DeleteVar(tokens[0]);
1760}
1761// Evaluation d'expression en notation polonaise inverse
1762else if (kw == "rpneval") {
1763 try {
1764 RPNExpressionEvaluator rpn(tokens, 1);
1765 double res = rpn.Value();
1766 char cbuff[64];
1767 sprintf(cbuff,"%g",res);
1768 string vv = cbuff;
1769 SetVariable(tokens[0],vv);
1770 return 0;
1771 }
1772 catch (RPNExprException& rpnerr) {
1773 cerr << " rpneval: Syntax error - Msg=" << rpnerr.Msg()
1774 << " \n Line=" << toks << endl;
1775 return 98;
1776 }
1777}
1778else if (kw == "echo") {
1779 for (int ii=0; ii<tokens.size(); ii++)
1780 cout << tokens[ii] << " " ;
1781 cout << endl;
1782 }
1783else if (kw == "echo2file") {
1784 if (tokens.size() < 1) {
1785 cout << "Commander::Interpret() Usage: echo2file filename [string ] " << endl;
1786 return(1);
1787 }
1788 ofstream ofs(tokens[0].c_str(), ios::app);
1789 for (int ii=1; ii<tokens.size(); ii++)
1790 ofs << tokens[ii] << " " ;
1791 ofs << endl;
1792 }
1793else if (kw == "readstdin") {
1794 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: readstdin varname" << endl; return(0); }
1795 if ((tokens[0].length() < 1) || !isalpha((int)tokens[0][0]) ) {
1796 cerr << "Commander::Interpret()/Error Variable name should start with alphabetic" << endl;
1797 return(0);
1798 }
1799 ShowMessage(">>> Reading From StdIn \n", _MAGENTA_);
1800 cout << tokens[0] << " ? " << endl;
1801 SetVar(tokens[0], GetStringFrStdin(this) );
1802 }
1803
1804else if (kw == "listvar") ListVar();
1805else if (kw == "listalias") {
1806 cout << "Commander::Interpret() Alias List , AliasName = Value \n";
1807 CmdStrList::iterator it;
1808 for(it = mAliases.begin(); it != mAliases.end(); it++)
1809 cout << (*it).first << " = " << (*it).second << "\n";
1810 cout << endl;
1811 }
1812else if (kw == "listcommands") {
1813 cout << "---- Commander::Interpret() Command List ----- \n";
1814 CmdExmap::iterator it;
1815 int kc = 0;
1816 for(it = cmdexmap.begin(); it != cmdexmap.end(); it++) {
1817 cout << (*it).first << " ";
1818 kc++;
1819 if (kc >= 5) { cout << "\n"; kc = 0; }
1820 }
1821 cout << endl;
1822 }
1823else if (kw == "listscripts") {
1824 cout << "---- Commander::Interpret() Script List ----- \n";
1825 for(ScriptList::iterator sit = mScripts.begin();
1826 sit != mScripts.end(); sit++)
1827 cout << " Script: " << (*sit).second->Name() << " - "
1828 << (*sit).second->Comment() << endl;
1829}
1830else if (kw == "clearscript") {
1831 if (tokens.size() < 1) {
1832 cout << "Commander::Interpret() Usage: clearscript scriptname" << endl;
1833 return(0);
1834 }
1835 ScriptList::iterator sit = mScripts.find(tokens[0]);
1836 if (sit == mScripts.end()) {
1837 cout << "Commander::Interpret() No script with name" << tokens[0] << endl;
1838 return(0);
1839 }
1840 else {
1841 delete (*sit).second;
1842 mScripts.erase(sit);
1843 cout << "Commander::Interpret() script " << tokens[0] << " cleared" << endl;
1844 return(0);
1845 }
1846}
1847//---------------------------------------------
1848//--- Commandes de gestion des threads ------
1849//---------------------------------------------
1850else if (kw == "thrlist") {
1851 ListThreads();
1852 return(0);
1853}
1854else if (kw == "cancelthr") {
1855 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: cancelthr thrid" << endl; return(0); }
1856 uint_8 id = atol(tokens[0].c_str());
1857 CancelThr(id);
1858 return (0);
1859}
1860else if (kw == "waitthr") {
1861 WaitThreads();
1862 return (0);
1863}
1864else if (kw == "cleanthrlist") {
1865 CleanThrList();
1866 return (0);
1867}
1868
1869else if (kw == "traceon") { cout << "Commander::Interpret() -> Trace ON mode " << endl; trace = true; }
1870else if (kw == "traceoff") { cout << "Commander::Interpret() -> Trace OFF mode " << endl; trace = false; }
1871else if (kw == "timingon") {
1872 cout << "Commander::Interpret() -> Timing ON mode " << endl;
1873 if (gltimer) delete gltimer; gltimer = new Timer("PIA-CmdInterpreter "); timing = true;
1874 }
1875else if (kw == "timingoff") {
1876 cout << "Commander::Interpret() -> Timing OFF mode " << endl;
1877 if (gltimer) delete gltimer; gltimer = NULL; timing = false;
1878 }
1879else if (kw == "exec") {
1880 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: exec filename" << endl; return(0); }
1881 ExecFile(tokens[0], tokens);
1882 }
1883else if (kw == "autoiniranf") {
1884 Auto_Ini_Ranf(1);
1885 return(0);
1886}
1887else if (kw == "shell") {
1888 if (tokens.size() < 1) { cout << "Commander::Interpret() Usage: shell cmdline" << endl; return(0); }
1889 string cmd;
1890 for (int ii=0; ii<tokens.size(); ii++)
1891 cmd += (tokens[ii] + ' ');
1892 system(cmd.c_str());
1893 }
1894else if (kw == "cshell") {
1895 if(tokens.size()<1) {cout<<"Commander::Interpret() Usage: cshell cmdline"<<endl; return(0);}
1896 string cmd="";
1897 for(int ii=0;ii<tokens.size();ii++) cmd+=(tokens[ii]+' ');
1898 CShellExecute(cmd);
1899 }
1900
1901// Execution d'une commande enregistree
1902else rc = ExecuteCommand(kw, tokens, toks);
1903
1904if (timing) gltimer->Split();
1905return(rc);
1906}
1907
1908/* --Methode-- */
1909int Commander::ParseLineExecute(string& line, bool qw)
1910 // Si qw == true, on decoupe entre '' ou "" ou espaces
1911{
1912vector<string> tokens;
1913vector<bool> qottoks;
1914string kw, toks;
1915if (line.length() < 1) return(0);
1916LineToWords(line, kw, tokens, qottoks, toks, qw);
1917return(ExecuteCommand(kw, tokens, toks));
1918}
1919
1920/* --Methode-- */
1921int Commander::ExecuteCommand(string& keyw, vector<string>& args, string& toks)
1922{
1923 int rc = -1;
1924 CmdExmap::iterator it = cmdexmap.find(keyw);
1925 if (it == cmdexmap.end()) cout << "No such command : " << keyw << " ! " << endl;
1926 else {
1927 if ((*it).second.cex) {
1928 // Doit-on l'executer sous forme de thread separe ?
1929 if ( (args.size()>0) && (args[args.size()-1] == "&") &&
1930 ((*it).second.cex->IsThreadable(keyw)) ) {
1931 ThrId++;
1932 CommandExeThr * thr = new CommandExeThr(ThrId, (*it).second.cex, keyw, args, toks);
1933 CmdThrExeList.push_back(thr);
1934 cout << " Commander::ExecuteCommand() : Thread execution of command " << keyw << endl;
1935 thr->start();
1936 rc = 0;
1937 }
1938 else rc = (*it).second.cex->Execute(keyw, args, toks);
1939 }
1940 else cout << "Dont know how to execute " << keyw << " ? " << endl;
1941 }
1942 return(rc);
1943}
1944
1945/* --Methode-- */
1946int Commander::ExecFile(string& file, vector<string>& args)
1947{
1948char line_buff[512];
1949FILE *fip;
1950int rcc = 0;
1951if ( (fip = fopen(file.c_str(),"r")) == NULL ) {
1952 if (file.find('.') >= file.length()) {
1953 cout << "Commander::Exec(): Error opening file " << file << endl;
1954 file += ".pic";
1955 cout << " Trying file " << file << endl;
1956 fip = fopen(file.c_str(),"r");
1957 }
1958 }
1959
1960if(fip == NULL) {
1961 cerr << "Commander::Exec() Error opening file " << file << endl;
1962 hist << "##! Commander::Exec() Error opening file " << file << endl;
1963 return(0);
1964 }
1965
1966// hist << "### Executing commands from " << file << endl;
1967PushStack(args);
1968if (trace) {
1969 ShowMessage("### Executing commands from ", _MAGENTA_);
1970 ShowMessage(file.c_str(), _MAGENTA_);
1971 ShowMessage("\n", _MAGENTA_);
1972 }
1973
1974bool ohv = histon;
1975histon = false;
1976while (fgets(line_buff,511,fip) != NULL)
1977 {
1978 if (trace) ShowMessage(line_buff, _MAGENTA_);
1979 line_buff[strlen(line_buff)-1] = '\0'; /* LF/CR de la fin */
1980 string line(line_buff);
1981 rcc = Interpret(line);
1982 if ((rcc == CMD_RETURN_RC) || (rcc == CMD_BREAKEXE_RC)) break;
1983 }
1984histon = ohv;
1985
1986// hist << "### End of Exec( " << file << " ) " << endl;
1987if (trace) {
1988 ShowMessage("### End of Exec( ", _MAGENTA_);
1989 ShowMessage(file.c_str(), _MAGENTA_);
1990 ShowMessage(" ) \n", _MAGENTA_);
1991 }
1992
1993PopStack(true);
1994
1995return(0);
1996}
1997
1998/* --Methode-- */
1999void Commander::ListThreads()
2000{
2001 cout << "---- Commander::ListThreads() List of separate execution threads NThread="
2002 << CmdThrExeList.size() << " ----- " << endl;
2003 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2004 tit != CmdThrExeList.end(); tit++) {
2005 cout << "Id=" << (*tit)->Id();
2006 if ( (*tit)->IfDone() ) cout << " Finished , Rc= " << (*tit)->getRC();
2007 else cout << " Executing";
2008 cout << " (Cmd= " << (*tit)->Keyword() << " " << (*tit)->Tokens() << " )" << endl;
2009 }
2010}
2011/* --Methode-- */
2012void Commander::CancelThr(uint_8 id)
2013{
2014 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2015 tit != CmdThrExeList.end(); tit++) {
2016 if ((*tit)->Id() == id) {
2017 (*tit)->cancel();
2018 cout << "Commander::CancelThr() Thread Id= " << id << " cancelled" << endl;
2019 return;
2020 }
2021 }
2022 cout << "Commander::CancelThr()/Error: No thread with Id= " << id << endl;
2023}
2024
2025/* --Methode-- */
2026void Commander::CleanThrList()
2027{
2028 cout << "---- Commander::CleanThrList() Cleaning thrlist ----- \n";
2029 list<CommandExeThr *> thrcopie;
2030 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2031 tit != CmdThrExeList.end(); tit++) {
2032 if ( (*tit)->IfDone() ) {
2033 cout << " Thread Id= " << (*tit)->Id() << " rc= " << (*tit)->getRC() << " Cleaned" << endl;
2034 delete (*tit);
2035 }
2036 else thrcopie.push_back((*tit));
2037 }
2038 CmdThrExeList = thrcopie;
2039 cout << " ... " << CmdThrExeList.size() << " threads still active " << endl;
2040}
2041
2042/* --Methode-- */
2043void Commander::WaitThreads()
2044{
2045 cout << "---- Commander::WaitThreads() Wait/Join command execution threads - NThread="
2046 << CmdThrExeList.size() << " ----- " << endl;
2047 for(list<CommandExeThr *>::iterator tit = CmdThrExeList.begin();
2048 tit != CmdThrExeList.end(); tit++) {
2049 try {
2050 if (! (*tit)->IfDone()) (*tit)->join();
2051 }
2052 catch (std::exception & e) {
2053 cout << " Commander::WaitThreads()/Exception msg= " << e.what() << endl;
2054 }
2055 cout << " Joined thread Id= " << (*tit)->Id() << " rc= " << (*tit)->getRC() << endl;
2056 delete (*tit);
2057 }
2058 CmdThrExeList.erase(CmdThrExeList.begin(), CmdThrExeList.end());
2059}
2060
2061/* --Methode-- */
2062int Commander::CShellExecute(string cmd)
2063{
2064 if(cmd.size()<=0) return -1;
2065
2066 string fname = GetTmpDir(); fname += "cshell_exec_pia.csh";
2067
2068 string cmdrm = "rm -f " + fname;
2069 system(cmdrm.c_str());
2070
2071 FILE *fip = fopen(fname.c_str(),"w");
2072 if(fip==NULL) {
2073 cout << "Commander/CShellExecute_Error: fopen("<<fname<<") failed"<<endl;
2074 return -2;
2075 }
2076 fprintf(fip,"#!/bin/csh\n\n");
2077 fprintf(fip,"%s\n",cmd.c_str());
2078 fprintf(fip,"\nexit 0\n");
2079 fclose(fip);
2080
2081 cmd = "csh "; cmd += fname;
2082 system(cmd.c_str());
2083
2084 system(cmdrm.c_str());
2085
2086 return 0;
2087}
2088
2089static string* videstr = NULL;
2090/* --Methode-- */
2091string& Commander::GetUsage(const string& kw)
2092{
2093bool fndok = false;
2094CmdExmap::iterator it = cmdexmap.find(kw);
2095if (it == cmdexmap.end()) {
2096 it = helpexmap.find(kw);
2097 if (it != helpexmap.end()) fndok = true;
2098 }
2099 else fndok = true;
2100if (fndok) return( (*it).second.us );
2101// Keyword pas trouve
2102if (videstr == NULL) videstr = new string("");
2103*videstr = "Nothing known about " + kw + " ?? ";
2104return(*videstr);
2105
2106}
2107
2108
2109/* Les definitions suivantes doivent se trouver ds l'en-tete du fichier LaTeX
2110 \newcommand{\piacommand}[1]{
2111 \framebox{\bf \Large #1 } \index{#1} % (Command)
2112 }
2113
2114 \newcommand{\piahelpitem}[1]{
2115 \framebox{\bf \Large #1 } \index{#1} (Help item)
2116 }
2117
2118 \newcommand{\myppageref}[1]{ (p. \pageref{#1} ) }
2119*/
2120
2121// Fonction qui remplace tout caractere non alphanumerique en Z
2122static void check_latex_reflabel(string & prl)
2123{
2124 for(int k=0; k<prl.length(); k++)
2125 if (! isalnum(prl[k]) ) prl[k] = 'Z';
2126}
2127
2128// Fonction qui remplace _ en \_
2129static string check_latex_underscore(string const & mot)
2130{
2131 string rs;
2132 for(int k=0; k<mot.length(); k++) {
2133 if (mot[k] == '_') rs += "\\_";
2134 else rs += mot[k];
2135 }
2136 return rs;
2137}
2138
2139/* --Methode-- */
2140//! Produces a LaTeX file containing the registered command helps
2141void Commander::HelptoLaTeX(string const & fname)
2142{
2143FILE *fip;
2144if ((fip = fopen(fname.c_str(), "w")) == NULL) {
2145 cout << "Commander::HelptoLaTex_Error: fopen( " << fname << endl;
2146 return;
2147 }
2148
2149fputs("% ----- Liste des groupes de Help ----- \n",fip);
2150fputs("List of {\\bf piapp} on-line Help groups: \n", fip);
2151fputs("\\begin{itemize} \n",fip);
2152string prl;
2153string mol;
2154CmdHGroup::iterator it;
2155for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
2156 if ((*it).first == "All") continue;
2157 prl = (*it).first; check_latex_reflabel(prl);
2158 mol = check_latex_underscore((*it).first);
2159 fprintf(fip,"\\item {\\bf %s } (p. \\pageref{%s}) \n",
2160 mol.c_str(), prl.c_str());
2161}
2162
2163fputs("\\end{itemize} \n",fip);
2164
2165fputs("\\vspace*{10mm} \n",fip);
2166
2167CmdExmap::iterator ite;
2168fputs("% ----- Liste de toutes les commandes et help item ----- \n",fip);
2169fputs("\\vspace{5mm} \n",fip);
2170// fputs("\\begin{table}[h!] \n", fip);
2171fputs("\\begin{center} \n ", fip);
2172fputs("\\rule{2cm}{1mm} List of {\\bf piapp} Help items \\rule{2cm}{1mm} \\\\ \n", fip);
2173fputs("\\vspace{3mm} \n",fip);
2174fputs("\\begin{tabular}{llllll} \n", fip);
2175int kt = 0;
2176for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
2177 prl = (*ite).first; check_latex_reflabel(prl);
2178 mol = check_latex_underscore((*ite).first);
2179 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
2180 kt++;
2181 if (kt < 3) fputs(" & ", fip);
2182 else { fputs(" \\\\ \n", fip); kt = 0; }
2183 }
2184if (kt == 1) fputs(" & & & \\\\ \n", fip);
2185else if (kt == 2) fputs(" & \\\\ \n", fip);
2186fputs("\\end{tabular} \n", fip);
2187fputs("\\end{center} \n", fip);
2188//fputs("\\end{table} \n", fip);
2189fputs("\\newpage \n",fip);
2190
2191int gid;
2192for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
2193 gid = (*it).second.gid;
2194 if (gid == 0) continue;
2195 // fputs("\\begin{table}[h!] \n",fip);
2196 fputs("\\vspace{6mm} \n",fip);
2197 fputs("\\begin{center} \n ", fip);
2198 fprintf(fip, "\\rule{2cm}{0.5mm} \\makebox[60mm]{{ \\bf %s } help group} \\rule{2cm}{0.5mm} \\\\ \n",
2199 (*it).first.c_str());
2200 fputs("\\vspace{3mm} \n",fip);
2201 fputs("\\begin{tabular}{llllll} \n", fip);
2202 kt = 0;
2203 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
2204 if ((*ite).second.group != gid) continue;
2205 prl = (*ite).first; check_latex_reflabel(prl);
2206 mol = check_latex_underscore((*ite).first);
2207 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
2208 kt++;
2209 if (kt < 3) fputs(" & ", fip);
2210 else { fputs(" \\\\ \n", fip); kt = 0; }
2211 }
2212 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
2213 if ((*ite).second.group != gid) continue;
2214 prl = (*ite).first; check_latex_reflabel(prl);
2215 mol = check_latex_underscore((*ite).first);
2216 fprintf(fip,"%s & p. \\pageref{%s} ", mol.c_str(), prl.c_str() );
2217 kt++;
2218 if (kt < 3) fputs(" & ", fip);
2219 else { fputs(" \\\\ \n", fip); kt = 0; }
2220 }
2221 if (kt == 1) fputs(" & & & \\\\ \n", fip);
2222 else if (kt == 2) fputs(" & \\\\ \n", fip);
2223 fputs("\\end{tabular} \n", fip);
2224 fputs("\\end{center} \n", fip);
2225 // fputs("\\end{table} \n",fip);
2226 // fputs("\\vspace{5mm} \n",fip);
2227}
2228// fputs("\\newline \n",fip);
2229
2230fputs("% ----- Liste des commandes dans chaque groupe ----- \n",fip);
2231fputs("\\newpage \n",fip);
2232
2233for(it = cmdhgrp.begin(); it != cmdhgrp.end(); it++) {
2234 gid = (*it).second.gid;
2235 if (gid == 0) continue;
2236 prl = (*it).first; check_latex_reflabel(prl);
2237 fprintf(fip,"\\subsection{%s} \\label{%s} \n",
2238 (*it).first.c_str(), prl.c_str());
2239 if ((*it).second.desc.length() > 0)
2240 fprintf(fip,"%s \n \\\\[2mm] ", (*it).second.desc.c_str());
2241 fprintf(fip,"\\noindent \n");
2242 for(ite = helpexmap.begin(); ite != helpexmap.end(); ite++) {
2243 if ((*ite).second.group != gid) continue;
2244 prl = (*ite).first; check_latex_reflabel(prl);
2245 mol = check_latex_underscore((*ite).first);
2246 fprintf(fip,"\\piahelpitem{%s} \\label{%s} \n",
2247 mol.c_str(), prl.c_str());
2248 fputs("\\begin{verbatim} \n",fip);
2249 fprintf(fip,"%s\n", (*ite).second.us.c_str());
2250 fputs("\\end{verbatim} \n",fip);
2251 }
2252 for(ite = cmdexmap.begin(); ite != cmdexmap.end(); ite++) {
2253 if ((*ite).second.group != gid) continue;
2254 prl = (*ite).first; check_latex_reflabel(prl);
2255 mol = check_latex_underscore((*ite).first);
2256 fprintf(fip,"\\piacommand{%s} \\label{%s} \n",
2257 mol.c_str(), prl.c_str());
2258 fputs("\\begin{verbatim} \n",fip);
2259 fprintf(fip,"%s\n", (*ite).second.us.c_str());
2260 fputs("\\end{verbatim} \n",fip);
2261 }
2262}
2263
2264fclose(fip);
2265cout << " Commander::HelptoLaTeX() - LaTeX format help written to file " << fname << endl;
2266
2267return;
2268}
2269
2270
2271} // End of namespace SOPHYA
2272
Note: See TracBrowser for help on using the repository browser.