source: 3DVCSoftware/branches/HTM-DEV-0.3-dev0/source/Lib/TAppCommon/program_options_lite.cpp @ 491

Last change on this file since 491 was 491, checked in by tech, 11 years ago
  • Started integrating changes in decoding process
  • Fixed encoder help output
  • Property svn:eol-style set to native
File size: 15.1 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license. 
5 *
6 * Copyright (c) 2010-2013, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33#include <stdlib.h>
34#include <iostream>
35#include <fstream>
36#include <sstream>
37#include <string>
38#include <list>
39#include <map>
40#include "program_options_lite.h"
41#include  "../TLibCommon/TypeDef.h"
42using namespace std;
43
44//! \ingroup TAppCommon
45//! \{
46
47namespace df
48{
49  namespace program_options_lite
50  {
51   
52    Options::~Options()
53    {
54      for(Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); it++)
55      {
56        delete *it;
57      }
58    }
59   
60    void Options::addOption(OptionBase *opt)
61    {
62      Names* names = new Names();
63      names->opt = opt;
64      string& opt_string = opt->opt_string;
65     
66      size_t opt_start = 0;
67      for (size_t opt_end = 0; opt_end != string::npos;)
68      {
69        opt_end = opt_string.find_first_of(',', opt_start);
70        bool force_short = 0;
71        if (opt_string[opt_start] == '-')
72        {
73          opt_start++;
74          force_short = 1;
75        }
76        string opt_name = opt_string.substr(opt_start, opt_end - opt_start);
77        if (force_short || opt_name.size() == 1)
78        {
79          names->opt_short.push_back(opt_name);
80          opt_short_map[opt_name].push_back(names);
81        }
82        else
83        {
84          names->opt_long.push_back(opt_name);
85          opt_long_map[opt_name].push_back(names);
86        }
87        opt_start += opt_end + 1;
88      }
89      opt_list.push_back(names);
90    }
91
92    /* Helper method to initiate adding options to Options */
93    OptionSpecific Options::addOptions()
94    {
95      return OptionSpecific(*this);
96    }
97   
98    static void setOptions(Options::NamesPtrList& opt_list, const string& value)
99    {
100      /* multiple options may be registered for the same name:
101       *   allow each to parse value */
102      for (Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); ++it)
103      {
104        (*it)->opt->parse(value);
105      }
106    }
107
108    static const char spaces[41] = "                                        ";
109   
110    /* format help text for a single option:
111     * using the formatting: "-x, --long",
112     * if a short/long option isn't specified, it is not printed
113     */
114    static void doHelpOpt(ostream& out, const Options::Names& entry, unsigned pad_short = 0)
115    {
116      pad_short = min(pad_short, 8u);
117
118      if (!entry.opt_short.empty())
119      {
120        unsigned pad = max((int)pad_short - (int)entry.opt_short.front().size(), 0);
121        out << "-" << entry.opt_short.front();
122        if (!entry.opt_long.empty())
123        {
124          out << ", ";
125        }
126        out << &(spaces[40 - pad]);
127      }
128      else
129      {
130        out << "   ";
131        out << &(spaces[40 - pad_short]);
132      }
133
134      if (!entry.opt_long.empty())
135      {
136        out << "--" << entry.opt_long.front();
137      }
138    }
139   
140    /* format the help text */
141    void doHelp(ostream& out, Options& opts, unsigned columns)
142    {
143      const unsigned pad_short = 3;
144      /* first pass: work out the longest option name */
145      unsigned max_width = 0;
146      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
147      {
148#if H_MV
149        if  ( (*it)->opt->opt_duplicate ) continue; 
150#endif
151        ostringstream line(ios_base::out);
152        doHelpOpt(line, **it, pad_short);
153        max_width = max(max_width, (unsigned) line.tellp());
154      }
155
156      unsigned opt_width = min(max_width+2, 28u + pad_short) + 2;
157      unsigned desc_width = columns - opt_width;
158     
159      /* second pass: write out formatted option and help text.
160       *  - align start of help text to start at opt_width
161       *  - if the option text is longer than opt_width, place the help
162       *    text at opt_width on the next line.
163       */
164      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
165      {
166#if H_MV
167        if  ( (*it)->opt->opt_duplicate ) continue; 
168#endif
169
170        ostringstream line(ios_base::out);
171        line << "  ";
172        doHelpOpt(line, **it, pad_short);
173
174        const string& opt_desc = (*it)->opt->opt_desc;
175        if (opt_desc.empty())
176        {
177          /* no help text: output option, skip further processing */
178          cout << line.str() << endl;
179          continue;
180        }
181        size_t currlength = size_t(line.tellp());
182        if (currlength > opt_width)
183        {
184          /* if option text is too long (and would collide with the
185           * help text, split onto next line */
186          line << endl;
187          currlength = 0;
188        }
189        /* split up the help text, taking into account new lines,
190         *   (add opt_width of padding to each new line) */
191        for (size_t newline_pos = 0, cur_pos = 0; cur_pos != string::npos; currlength = 0)
192        {
193          /* print any required padding space for vertical alignment */
194          line << &(spaces[40 - opt_width + currlength]);
195          newline_pos = opt_desc.find_first_of('\n', newline_pos);
196          if (newline_pos != string::npos)
197          {
198            /* newline found, print substring (newline needn't be stripped) */
199            newline_pos++;
200            line << opt_desc.substr(cur_pos, newline_pos - cur_pos);
201            cur_pos = newline_pos;
202            continue;
203          }
204          if (cur_pos + desc_width > opt_desc.size())
205          {
206            /* no need to wrap text, remainder is less than avaliable width */
207            line << opt_desc.substr(cur_pos);
208            break;
209          }
210          /* find a suitable point to split text (avoid spliting in middle of word) */
211          size_t split_pos = opt_desc.find_last_of(' ', cur_pos + desc_width);
212          if (split_pos != string::npos)
213          {
214            /* eat up multiple space characters */
215            split_pos = opt_desc.find_last_not_of(' ', split_pos) + 1;
216          }
217         
218          /* bad split if no suitable space to split at.  fall back to width */
219          bool bad_split = split_pos == string::npos || split_pos <= cur_pos;
220          if (bad_split)
221          {
222            split_pos = cur_pos + desc_width;
223          }
224          line << opt_desc.substr(cur_pos, split_pos - cur_pos);
225         
226          /* eat up any space for the start of the next line */
227          if (!bad_split)
228          {
229            split_pos = opt_desc.find_first_not_of(' ', split_pos);
230          }
231          cur_pos = newline_pos = split_pos;
232         
233          if (cur_pos >= opt_desc.size())
234          {
235            break;
236          }
237          line << endl;
238        }
239
240        cout << line.str() << endl;
241      }
242    }
243   
244    bool storePair(Options& opts, bool allow_long, bool allow_short, const string& name, const string& value)
245    {
246      bool found = false;
247      Options::NamesMap::iterator opt_it;
248      if (allow_long)
249      {
250        opt_it = opts.opt_long_map.find(name);
251        if (opt_it != opts.opt_long_map.end())
252        {
253          found = true;
254        }
255      }
256     
257      /* check for the short list */
258      if (allow_short && !(found && allow_long))
259      {
260        opt_it = opts.opt_short_map.find(name);
261        if (opt_it != opts.opt_short_map.end())
262        {
263          found = true;
264        }
265      }
266
267      if (!found)
268      {
269        /* not found */
270        cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl;
271        return false;
272      }
273
274      setOptions((*opt_it).second, value);
275      return true;
276    }
277   
278    bool storePair(Options& opts, const string& name, const string& value)
279    {
280      return storePair(opts, true, true, name, value);
281    }
282   
283    /**
284     * returns number of extra arguments consumed
285     */
286    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[])
287    {
288      /* gnu style long options can take the forms:
289       *  --option=arg
290       *  --option arg
291       */
292      string arg(argv[0]);
293      size_t arg_opt_start = arg.find_first_not_of('-');
294      size_t arg_opt_sep = arg.find_first_of('=');
295      string option = arg.substr(arg_opt_start, arg_opt_sep - arg_opt_start);
296     
297      unsigned extra_argc_consumed = 0;
298      if (arg_opt_sep == string::npos)
299      {
300        /* no argument found => argument in argv[1] (maybe) */
301        /* xxx, need to handle case where option isn't required */
302#if 0
303        /* commented out, to return to true GNU style processing
304        * where longopts have to include an =, otherwise they are
305        * booleans */
306        if (argc == 1)
307          return 0; /* run out of argv for argument */
308        extra_argc_consumed = 1;
309#endif
310        if(!storePair(opts, true, false, option, "1"))
311        {
312          return 0;
313        }
314      }
315      else
316      {
317        /* argument occurs after option_sep */
318        string val = arg.substr(arg_opt_sep + 1);
319        storePair(opts, true, false, option, val);
320      }
321
322      return extra_argc_consumed;
323    }
324
325    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[])
326    {
327      /* short options can take the forms:
328       *  --option arg
329       *  -option arg
330       */
331      string arg(argv[0]);
332      size_t arg_opt_start = arg.find_first_not_of('-');
333      string option = arg.substr(arg_opt_start);
334      /* lookup option */
335
336      /* argument in argv[1] */
337      /* xxx, need to handle case where option isn't required */
338      if (argc == 1)
339      {
340        cerr << "Not processing option without argument `" << option << "'" << endl;
341        return 0; /* run out of argv for argument */
342      }
343      storePair(opts, false, true, option, string(argv[1]));
344
345      return 1;
346    }
347   
348    list<const char*>
349    scanArgv(Options& opts, unsigned argc, const char* argv[])
350    {
351      /* a list for anything that didn't get handled as an option */
352      list<const char*> non_option_arguments;
353
354      for(unsigned i = 1; i < argc; i++)
355      {
356        if (argv[i][0] != '-')
357        {
358          non_option_arguments.push_back(argv[i]);
359          continue;
360        }
361
362        if (argv[i][1] == 0)
363        {
364          /* a lone single dash is an argument (usually signifying stdin) */
365          non_option_arguments.push_back(argv[i]);
366          continue;
367        }
368
369        if (argv[i][1] != '-')
370        {
371          /* handle short (single dash) options */
372#if 0
373          i += parsePOSIX(opts, argc - i, &argv[i]);
374#else
375          i += parseSHORT(opts, argc - i, &argv[i]);
376#endif
377          continue;
378        }
379
380        if (argv[i][2] == 0)
381        {
382          /* a lone double dash ends option processing */
383          while (++i < argc)
384            non_option_arguments.push_back(argv[i]);
385          break;
386        }
387
388        /* handle long (double dash) options */
389        i += parseGNU(opts, argc - i, &argv[i]);
390      }
391
392      return non_option_arguments;
393    }
394   
395    void scanLine(Options& opts, string& line)
396    {
397      /* strip any leading whitespace */
398      size_t start = line.find_first_not_of(" \t\n\r");
399      if (start == string::npos)
400      {
401        /* blank line */
402        return;
403      }
404      if (line[start] == '#')
405      {
406        /* comment line */
407        return;
408      }
409      /* look for first whitespace or ':' after the option end */
410      size_t option_end = line.find_first_of(": \t\n\r",start);
411      string option = line.substr(start, option_end - start);
412
413      /* look for ':', eat up any whitespace first */
414      start = line.find_first_not_of(" \t\n\r", option_end);
415      if (start == string::npos)
416      {
417        /* error: badly formatted line */
418        return;
419      }
420      if (line[start] != ':')
421      {
422        /* error: badly formatted line */
423        return;
424      }
425
426      /* look for start of value string -- eat up any leading whitespace */
427      start = line.find_first_not_of(" \t\n\r", ++start);
428      if (start == string::npos)
429      {
430        /* error: badly formatted line */
431        return;
432      }
433
434      /* extract the value part, which may contain embedded spaces
435       * by searching for a word at a time, until we hit a comment or end of line */
436      size_t value_end = start;
437      do
438      {
439        if (line[value_end] == '#')
440        {
441          /* rest of line is a comment */
442          value_end--;
443          break;
444        }
445        value_end = line.find_first_of(" \t\n\r", value_end);
446        /* consume any white space, incase there is another word.
447         * any trailing whitespace will be removed shortly */
448        value_end = line.find_first_not_of(" \t\n\r", value_end);
449      }
450      while (value_end != string::npos);
451      /* strip any trailing space from value*/
452      value_end = line.find_last_not_of(" \t\n\r", value_end);
453
454      string value;
455      if (value_end >= start)
456      {
457        value = line.substr(start, value_end +1 - start);
458      }
459      else
460      {
461        /* error: no value */
462        return;
463      }
464
465      /* store the value in option */
466      storePair(opts, true, false, option, value);
467    }
468
469    void scanFile(Options& opts, istream& in)
470    {
471      do
472      {
473        string line;
474        getline(in, line);
475        scanLine(opts, line);
476      }
477      while(!!in);
478    }
479
480    /* for all options in opts, set their storage to their specified
481     * default value */
482    void setDefaults(Options& opts)
483    {
484      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
485      {
486        (*it)->opt->setDefault();
487      }
488    }
489
490    void parseConfigFile(Options& opts, const string& filename)
491    {
492      ifstream cfgstream(filename.c_str(), ifstream::in);
493      if (!cfgstream)
494      {
495        cerr << "Failed to open config file: `" << filename << "'" << endl;
496        exit(EXIT_FAILURE);
497      }
498      scanFile(opts, cfgstream);
499    }
500
501  };
502};
503
504//! \}
Note: See TracBrowser for help on using the repository browser.