File: Scripting.cpp

package info (click to toggle)
imagevis3d 2.0.1-5
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 7,872 kB
  • sloc: cpp: 53,586; sh: 788; ansic: 292; xml: 258; python: 35; makefile: 16
file content (432 lines) | stat: -rw-r--r-- 13,450 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.


   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/


//!    File   : Scripting.cpp
//!    Author : Jens Krueger
//!             SCI Institute
//!             University of Utah
//!    Date   : January 2009
//
//!    Copyright (C) 2009 SCI Institute

#include "StdTuvokDefines.h"
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <limits>
#ifndef TUVOK_NO_QT
# include <QtCore/QTime>
# include <QtCore/QDate>
#endif
#include "Scripting.h"

#include "Basics/SysTools.h"
#include "Controller/Controller.h"

using namespace std;
using namespace tuvok;

ScriptableListElement::ScriptableListElement(Scriptable* source,
                                             const std::string& strCommand,
                                             const std::string& strParameters,
                                             std::string strDescription) :
      m_source(source),
      m_strCommand(strCommand),
      m_strDescription(strDescription)
{
  m_vParameters = SysTools::Tokenize(strParameters, false);

  m_iMaxParam = UINT32(m_vParameters.size());
  m_iMinParam = 0;

  bool bFoundOptional = false;
  for (UINT32 i = 0;i<m_vParameters.size();i++) {
    if (m_vParameters[i] == "...") {
      m_iMaxParam = numeric_limits<UINT32>::max();
    } else {
      if (m_vParameters[i][0] == '[' && 
          m_vParameters[i][m_vParameters[i].size()-1] == ']') {
        bFoundOptional = true;
        m_vParameters[i] = string(m_vParameters[i].begin()+1,
                           m_vParameters[i].end()-1);
      } else {
        if (!bFoundOptional)
          m_iMinParam++;
        // else // this else would be an syntax error case but lets just
                // assume all parameters after the first optional parameter
                // are also optional
      }
    }
  }
}


Scripting::Scripting() :
  m_bSorted(false),
  m_bEcho(false),
  m_bDontStoreInHistory(false)
{
  RegisterCalls(this);
}

template<class T> static void Delete(T* t) { delete t; }

Scripting::~Scripting() {
  std::for_each(m_ScriptableList.begin(), m_ScriptableList.end(),
                Delete<ScriptableListElement>);
}


bool Scripting::RegisterCommand(Scriptable* source,
                                const std::string& strCommand,
                                const std::string& strParameters,
                                std::string strDescription) {
  // commands may not contain whitespaces
  vector<string> strTest = SysTools::Tokenize(strCommand, false);
  if (strTest.size() != 1) return false;

  // commands must be unique
  for(ScriptList::const_iterator iter = m_ScriptableList.begin();
      iter != m_ScriptableList.end(); ++iter) {
    if((*iter)->m_strCommand == strCommand) {
      WARNING("Command '%s' is not unique, ignoring.", strCommand.c_str());
      return false;
    }
  }

  // ok, all seems fine: add the command to the list
  ScriptableListElement* elem = new ScriptableListElement(source, strCommand,
                                                          strParameters,
                                                          strDescription);
  m_bSorted = false;
  m_ScriptableList.push_front(elem);
  return true;
}


bool Scripting::ParseLine(const string& strLine) {
  // tokenize string
  vector<string> vParameters = SysTools::Tokenize(strLine);
  if(vParameters.empty()) { return true; }

  string strMessage = "";
  bool bResult = ParseCommand(vParameters, strMessage);

  if (!bResult) {
    if (strMessage == "") {
      std::ostringstream badinput;
      badinput << "Input '" << strLine << "' not understood; try 'help'!";
      Controller::Debug::Out().printf(badinput.str().c_str());
    }
    else
      Controller::Debug::Out().printf(strMessage.c_str());
  } else {

    if (m_bDontStoreInHistory) 
      m_bDontStoreInHistory = false;
    else
      m_vHistory.push_back(strLine);

    if (m_bEcho) {
      std::ostringstream ok;
      ok << "OK (" << strLine << ")";
      Controller::Debug::Out().printf(ok.str().c_str());
    }
  }

  return bResult;
}

struct CmpByCmdName: public std::binary_function<bool, ScriptableListElement*,
                                                 ScriptableListElement*> {
  bool operator()(const ScriptableListElement* a,
                  const ScriptableListElement* b) const {
    return a->m_strCommand <= b->m_strCommand;
  }
};

bool Scripting::ParseCommand(const vector<string>& strTokenized,
                             string& strMessage) {

  if (strTokenized.empty()) return false;
  string strCommand = strTokenized[0];
  vector<string> strParams(strTokenized.begin()+1, strTokenized.end());

  if(!m_bSorted) {
    m_ScriptableList.sort(CmpByCmdName());
    m_bSorted = true;
  }

  strMessage = "";
  for(ScriptList::const_iterator cmd = m_ScriptableList.begin();
      cmd != m_ScriptableList.end(); ++cmd) {
    if((*cmd)->m_strCommand == strCommand) {
      if (strParams.size() >= (*cmd)->m_iMinParam &&
          strParams.size() <= (*cmd)->m_iMaxParam) {
        return (*cmd)->m_source->Execute(strCommand, strParams, strMessage);
      } else {
         strMessage = "Parameter mismatch for command \""+strCommand+"\"";
         return false;
      }
    }
  }

  return false;
}

bool Scripting::ParseFile(const std::string& strFilename) {
  string line;
  std::ifstream fileData(strFilename.c_str());

  UINT32 iLine=0;
  if (fileData.is_open())
  {
    while (! fileData.eof() )
    {
      getline (fileData,line);
      iLine++;
      line = SysTools::TrimStrLeft(line);
      if (line.empty()) continue;         // skip empty lines
      if (line[0] == '#') continue;       // skip comments

      if (!ParseLine(line)) {
        T_ERROR("Error executing line %i in file %s (%s)", iLine,
                strFilename.c_str(), line.c_str());
        fileData.close();
        return false;
      }
    }
  } else {
    T_ERROR("Error opening script file %s", strFilename.c_str());
    return false;
  }

  fileData.close();
  return true;
}

void Scripting::RegisterCalls(Scripting* pScriptEngine) {
  pScriptEngine->RegisterCommand(this, "help",
    "",
    "show all commands");
  pScriptEngine->RegisterCommand(this, "execute",
    "filename",
    "run the script saved as 'filename'");
  pScriptEngine->RegisterCommand(this, "l",
    "",
    "re-execute last command");
  pScriptEngine->RegisterCommand(this, "echo",
    "on/off",
    "turn feedback on successful command execution on or off");
  pScriptEngine->RegisterCommand(this, "time",
    "",
    "print out the current time");
  pScriptEngine->RegisterCommand(this, "date",
    "",
    "print out the current date");
  pScriptEngine->RegisterCommand(this, "write",
    "test",
    "print out 'text'");
  pScriptEngine->RegisterCommand(this, "clearhistory",
    "",
    "purge the command history");
  pScriptEngine->RegisterCommand(this, "printhistory",
    "",
    "display the command history");
  pScriptEngine->RegisterCommand(this, "exechistory",
    "[a] [b]",
    "execute line a to line b of the command history, "
    "if both parameters are ommited the entire history is processed");
  pScriptEngine->RegisterCommand(this, "storehistory",
    "filename [a] [b]",
    "store line a to line b of the command history to file 'filename', "
    "if both parameters are ommited the entire history is processed");
}


bool Scripting::Execute(const std::string& strCommand, 
                        const std::vector< std::string >& strParams, 
                        std::string& strMessage) {
  strMessage = "";
  if (strCommand == "echo") {
    m_bEcho = SysTools::ToLowerCase(strParams[0]) == "on";
    return true;
  } else
  if (strCommand == "execute") {
    return ParseFile(strParams[0]);
  } else
  if (strCommand == "help") {
    m_bDontStoreInHistory = true;
    Controller::Debug::Out().printf("Command Listing:");
    for(ScriptList::const_iterator cmd = m_ScriptableList.begin();
        cmd != m_ScriptableList.end(); ++cmd) {
      string strParams = "";
      UINT32 iMin = (*cmd)->m_iMinParam;
      for (size_t j = 0; j < (*cmd)->m_vParameters.size(); j++) {
        if (j < iMin) {
          if ((*cmd)->m_vParameters[j] == "...") iMin++;
          strParams = strParams + (*cmd)->m_vParameters[j];
        } else {
          strParams = strParams + "[" + (*cmd)->m_vParameters[j]+  "]";
        }
        if (j != (*cmd)->m_vParameters.size()-1) strParams = strParams + " ";
      }

      std::ostringstream echo;
      echo << "'" << (*cmd)->m_strCommand << "' " << strParams << ": "
           << (*cmd)->m_strDescription;
      Controller::Debug::Out().printf(echo.str().c_str());
    }
    return true;
  } else
  if (strCommand == "time") {
#ifndef TUVOK_NO_QT
    static QTime qt;
    if(!qt.isNull() && qt.secsTo(QTime::currentTime()) < 1) {
      Controller::Debug::Out().printf("To get a watch!");
    } else {
      qt = QTime::currentTime();
      std::string strTime(qt.toString().toAscii());
      Controller::Debug::Out().printf(strTime.c_str());
    }
#endif
    return true;
  } else
  if (strCommand == "date") {
#ifndef TUVOK_NO_QT
    string strDate(QDate::currentDate().toString().toAscii());
    Controller::Debug::Out().printf(strDate.c_str());
#endif
    return true;
  } else
  if (strCommand == "write") {
    Controller::Debug::Out().printf(strParams[0].c_str());
    return true;
  } else
  if (strCommand == "l") {
    if (m_vHistory.size() > 0) {
      bool bResult = ParseLine(m_vHistory[0]);
      m_bDontStoreInHistory = true;
      return bResult;
    } else {
      strMessage = "History is empty.";
      return false;
    }
  } else
  if (strCommand == "clearhistory") {
    m_vHistory.clear();
    m_bDontStoreInHistory = true;
    return true;
  } else
  if (strCommand == "printhistory") {
    for (size_t i = 0;i<m_vHistory.size();i++) {
      std::ostringstream msg;
      msg << setw( 3 ) << i << " : " << m_vHistory[i];
      Controller::Debug::Out().printf(msg.str().c_str());
    }
    m_bDontStoreInHistory = true;
    return true;
  } else
  if (strCommand == "exechistory") {
    size_t p0, p1;
    if (strParams.size() == 3) { 
      int i0, i1;
      SysTools::FromString(i0, strParams[0]);
      SysTools::FromString(i1, strParams[1]);
      const int int_sz = static_cast<int>(m_vHistory.size());
      p0 = (i0 < 0) ? 0 
                    : ((i0 >= int_sz) ? m_vHistory.size()-1 
                                      : static_cast<size_t>(i0));
      p1 = (i1 < 0) ? 0 
                    : ((i1 >= int_sz) ? m_vHistory.size()-1 
                                      : static_cast<size_t>(i1));
      if (p1 > p0) { p0 = p1; }
    } else {
      if (!strParams.empty()) { 
        strMessage = "Either specify both boundaries or none.";
        return false;
      }
      p0 = 0;
      p1 = m_vHistory.size()-1;
    }

    std::vector<std::string> vOldHist(m_vHistory);
    for (size_t i = p0;i<=p1;i++) {
      if (!ParseLine(vOldHist[i])) {
        m_vHistory = vOldHist;
        return false;
      }
    }

    m_vHistory = vOldHist;
    m_bDontStoreInHistory = true;
    return true;
  } else
  if (strCommand == "storehistory") {
    size_t p0, p1;
    if (strParams.size() == 3) { 
      int i0, i1;
      SysTools::FromString(i0, strParams[1]);
      SysTools::FromString(i1, strParams[2]);
      const int int_sz = static_cast<int>(m_vHistory.size());
      p0 = (i0 < 0) ? 0 
                    : ((i0 >= int_sz) ? m_vHistory.size()-1 
                                      : static_cast<size_t>(i0));
      p1 = (i1 < 0) ? 0 
                    : ((i1 >= int_sz) ? m_vHistory.size()-1 
                                      : static_cast<size_t>(i1));

      if (p1 > p0) { p0 = p1; }
    } else {
      if (strParams.size() != 1) { 
        strMessage = "Either specify both boundaries or none.";
        return false;
      }
      p0 = 0;
      p1 = m_vHistory.size()-1;
    }

    ofstream historyFile(strParams[0].c_str());
    if (!historyFile.is_open()) {
      strMessage = "Unable to create history file.";
      return false;
    }
    for (size_t i = p0;i<=p1;i++) {
      std::ostringstream msg;
      historyFile << m_vHistory[i] << endl;
    }
    historyFile.close();
    m_bDontStoreInHistory = true;

    return true;
  }

  return false;

}