Beispiel #1
0
TEST(OptionsTest, test_option_writing)
{
    std::ostringstream ostr_i;
    const std::string ref_i = xml_header + xml_int_ref;
    std::ostringstream ostr_s;
    const std::string ref_s = xml_header + xml_str_ref;

    const Option option_i("my_int", (uint16_t)17,
        "This is my integral option.");
    EXPECT_TRUE(option_i.getName() == "my_int");
    EXPECT_TRUE(option_i.getDescription() == "This is my integral option.");
    EXPECT_TRUE(option_i.getValue<uint16_t>() == 17);
    EXPECT_TRUE(option_i.getValue<std::string>() == "17");

    const Option option_s("my_string", "Yow.", "This is my stringy option.");
    EXPECT_TRUE(option_s.getName() == "my_string");
    EXPECT_TRUE(option_s.getDescription() == "This is my stringy option.");
    EXPECT_TRUE(option_s.getValue<std::string>() == "Yow.");
    EXPECT_TRUE(option_s.getValue<std::string>() == "Yow.");

//     const pdalboost::property_tree::ptree tree_i = Utils::toPTree(option_i);
//     pdalboost::property_tree::xml_parser::write_xml(ostr_i, tree_i);
//     const std::string str_i = ostr_i.str();
//     EXPECT_TRUE(str_i == ref_i);
//
//     const pdalboost::property_tree::ptree tree_s = Utils::toPTree(option_s);
//     pdalboost::property_tree::xml_parser::write_xml(ostr_s, tree_s);
//     const std::string str_s = ostr_s.str();
//     EXPECT_TRUE(str_s == ref_s);
}
Beispiel #2
0
/*********************************************************************
 ** METHOD  :
 ** PURPOSE :
 ** INPUT   :
 ** OUTPUT  :
 ** RETURN  :
 ** REMARKS :
 *********************************************************************/
void OptionsHelpVisitor::visitOption (Option& object, size_t depth)
{
    if (!object.getName().empty() && object.isVisible())
    {
        if (object.getNbArgs() > 0)
        {
            indent(os,depth) << Stringify::format ("    %-*s (%d arg) :    %s",
                (int)nameMaxLen,
                object.getName().c_str(),
                (int)object.getNbArgs(),
                object.getHelp().c_str(),
                object.getDefaultValue().c_str()
            );

            if (object.isMandatory()==false)  {  os << Stringify::format ("  [default '%s']", object.getDefaultValue().c_str());  }

            os << endl;
        }
        else
        {
            indent(os,depth) << Stringify::format ("    %-*s (%d arg) :    %s\n",
                (int)nameMaxLen,
                object.getName().c_str(),
                (int)object.getNbArgs(),
                object.getHelp().c_str()
            );
        }
    }
}
Beispiel #3
0
TEST(OptionsTest, test_option_writing)
{
    const Option option_i("my_int", (uint16_t)17);
    EXPECT_TRUE(option_i.getName() == "my_int");
    EXPECT_TRUE(option_i.getValue() == "17");

    const Option option_s("my_string", "Yow.");
    EXPECT_TRUE(option_s.getName() == "my_string");
    EXPECT_TRUE(option_s.getValue() == "Yow.");
    EXPECT_TRUE(option_s.getValue() == "Yow.");
}
Beispiel #4
0
void InputDialog::initializeControl(Option const& opt, QRadioButton* radio) 
{
   connectControl(opt, radio);
   radio->setToolTip(prependRemName(opt.getName(), opt.getDescription()));

   Action* action = new Action(
      boost::bind(&QRadioButton::setChecked, radio, opt.getDefaultIndex()) );
   m_resetActions.push_back(action);

   Update* update = new Update(
      boost::bind( 
         static_cast<void(*)(QRadioButton*, QString const&)>(SetControl), radio, _1));
   QString name = opt.getName();
   m_setUpdates[name] = update;
}
Beispiel #5
0
/// @name Equality
    /// Equality
    bool equals(const Option& rhs) const
    {
        return (m_name == rhs.getName() &&
            m_value == rhs.getValue<std::string>() &&
            m_description == rhs.getDescription() &&
            m_options == rhs.m_options);
    }
Beispiel #6
0
TEST(OptionsTest, test_option_writing)
{
    std::ostringstream ostr_i;
    const std::string ref_i = xml_header + xml_int_ref;
    std::ostringstream ostr_s;
    const std::string ref_s = xml_header + xml_str_ref;

    const Option option_i("my_int", (uint16_t)17);
    EXPECT_TRUE(option_i.getName() == "my_int");
    EXPECT_TRUE(option_i.getValue() == "17");

    const Option option_s("my_string", "Yow.");
    EXPECT_TRUE(option_s.getName() == "my_string");
    EXPECT_TRUE(option_s.getValue() == "Yow.");
    EXPECT_TRUE(option_s.getValue() == "Yow.");
}
Beispiel #7
0
void InputDialog::initializeControl(Option const& opt, QDoubleSpinBox* dspin) 
{
   connectControl(opt, dspin);
   dspin->setToolTip(prependRemName(opt.getName(), opt.getDescription()));
   dspin->setRange(opt.doubleMin(), opt.doubleMax());  
   dspin->setSingleStep(opt.doubleStep());  

   Action* action = new Action(
      boost::bind(&QDoubleSpinBox::setValue, dspin, opt.doubleDefault()) );
   m_resetActions.push_back(action);

   Update* update = new Update(
      boost::bind( 
         static_cast<void(*)(QDoubleSpinBox*, QString const&)>(SetControl), dspin, _1));
   QString name = opt.getName();
   m_setUpdates[name] = update;
}
bool Option::operator<(Option &aOther)
{
  if (name_ == 0 && aOther.getName() != 0)
    return false;
  else if (name_ != 0 && aOther.getName() == 0)
    return true;
  else if (name_ == 0 && aOther.getName() == 0)
  {
    if (order_ == -1)
      return false;
    if (aOther.getOrder() == -1)
      return true;
    
    return order_ < aOther.getOrder();
  }
  
  return strcmp(name_, aOther.getName()) < 0;
}
Stage *PipelineReaderXML::parseElement_Writer(const ptree& tree)
{
    Options options;
    StageParserContext context;
    std::string filename;

    map_t attrs;
    collect_attributes(attrs, tree);

    std::vector<Stage *> prevStages;
    for (auto iter = tree.begin(); iter != tree.end(); ++iter)
    {
        const std::string& name = iter->first;
        const ptree& subtree = iter->second;

        if (name == "<xmlattr>")
        {
            // already parsed -- ignore it
        }
        else if (name == "Option")
        {
            Option option = parseElement_Option(subtree);
            if (option.getName() == "filename")
                filename = option.getValue();
            options.add(option);
        }
        else if (name == "Metadata")
        {
            // ignored
        }
        else if (name == "Filter" || name == "Reader")
        {
            context.addStage();
            prevStages.push_back(parseElement_anystage(name, subtree));
        }
        else
        {
            context.addUnknown(name);
        }
    }

    std::string type;
    if (attrs.count("type"))
    {
        type = attrs["type"];
        context.addType();
    }

    context.validate();
    Stage& writer = m_manager.makeWriter(filename, type);
    for (auto sp : prevStages)
        writer.setInput(*sp);
    writer.removeOptions(options);
    writer.addOptions(options);
    return &writer;
}
Beispiel #10
0
//! The connectControl routines make the necessary signal-slot connections
//! between the control, the current Job and Nodes in the OptionRegister (for
//! program logic purposes).
void InputDialog::connectControl(Option const& opt, QComboBox* combo) {
   QString name = opt.getName();

   connect(combo, SIGNAL(currentIndexChanged(const QString&)),
      this, SLOT(widgetChanged(const QString&)));

   if (combo->isEditable()) {
      connect(combo, SIGNAL(editTextChanged(const QString&)),
         this, SLOT(widgetChanged(const QString&)));
   }
Beispiel #11
0
//! The (overloaded) initializeControl routine is responsible for the following
//! tasks:
//!  - Ensuring the control displays the appropriate options based on the
//!    contents of the OptionDatabase.
//!  - Adding the ToolTip documentation found in the database.
//!  - Adding connections (signals & slots) between the Nodes in the
//!    OptionRegister and the control.  This allows for synchronization of the
//!    logic in InitializeQChemLogic and initializeQuiLogic.
//!  - Binding an Action to enable the control to be reset to the default value.
//!  - Binding an Update to enable the control to be reset to a string value.
void InputDialog::initializeControl(Option const& opt, QComboBox* combo) {

   QString name = opt.getName();
   QStringList opts = opt.getOptions();
   QStringList split;

   // This allows for ad hoc text replacements.  This is useful so that more
   // informative text can be presented to the user which is then obfiscated
   // before being passed to QChem.  The replacements should be set in the
   // option database and have the form text//replacement.
   for (int i = 0; i < opts.size(); ++i) {
       split = opts[i].split("//");

       if (split.size() == 1) {
          opts[i] = split[0];
       }else if (split.size() == 2) {
          opts[i] = split[0];
          QString key(name.toUpper() + "::" + split[0]);
          //Job::addAdHoc(key,split[1]);
          RemSection::addAdHoc(name, split[0], split[1]);
       }else {
          qDebug() << "InputDialog::initialiseComboBox:\n"
                   << " replacement for option" << name << "is invalid:" << opts[i];
       }
   }

   combo->clear();
   combo->addItems(opts);

#if QT_VERSION >= 0x040400
   // This just allows us to add some spacers to the lists
   bool keepLooking(true);
   while (keepLooking) {
      int i = combo->findText("---", Qt::MatchStartsWith);
      if (i > 0) {
         combo->removeItem(i);
         combo->insertSeparator(i);
      }else {
         keepLooking = false;
      }
   }
#endif

   connectControl(opt, combo);
   combo->setToolTip(opt.getDescription());

   Action* action = new Action(
      boost::bind(&QComboBox::setCurrentIndex, combo, opt.getDefaultIndex()) );
   m_resetActions.push_back(action);

   Update* update = new Update(
      boost::bind(
         static_cast<void(*)(QComboBox*, QString const&)>(SetControl), combo, _1));
   m_setUpdates[name] = update;
}
Stage *PipelineReaderXML::parseElement_Reader(const ptree& tree)
{
    Options options;
    StageParserContext context;
    std::string filename;
    context.setCardinality(StageParserContext::None);

    map_t attrs;
    collect_attributes(attrs, tree);

    auto iter = tree.begin();
    while (iter != tree.end())
    {
        const std::string& name = iter->first;
        const ptree& subtree = iter->second;

        if (name == "<xmlattr>")
        {
            // already parsed
        }
        else if (name == "Option")
        {
            Option option = parseElement_Option(subtree);
            if (option.getName() == "filename")
                filename = option.getValue();
            options.add(option);
        }
        else if (name == "Metadata")
        {
            // ignored for now
        }
        else
        {
            context.addUnknown(name);
        }
        ++iter;
    }

    std::string type;
    if (attrs.count("type"))
    {
        type = attrs["type"];
    }

    Stage& reader = m_manager.makeReader(filename, type);
    reader.removeOptions(options);
    reader.addOptions(options);

    context.addType();
    context.validate();
    return &reader;
}
Beispiel #13
0
int OptionContainer::findOption(Option o) {
    int i=0;
    for ( OptionVectorIterator it = m_Options.begin();
      it != m_Options.end();
      ++it )
    {
        if((*it).getName() == o.getName()) {
            return i;
        }
        i++;
    }
    return -1;
}
Beispiel #14
0
void InputDialog::initializeControl(Option const& opt, QLineEdit* edit) 
{
   connectControl(opt, edit);
   edit->setToolTip(prependRemName(opt.getName(), opt.getDescription()));

   Action* action = new Action(
      boost::bind(&QLineEdit::setText, edit, opt.getOptionString()) );
   m_resetActions.push_back(action);

   Update* update = new Update(
      boost::bind( 
         static_cast<void(*)(QLineEdit*, QString const&)>(SetControl), edit, _1));
   QString name = opt.getName();
   m_setUpdates[name] = update;

   if (opt.getType() == Option::Type_Array) {
      QRegExp rx("^\\[(\\d+,?)+\\]$");
      QValidator* validator(new QRegExpValidator(rx, this));
      edit->setValidator(validator);
      //edit->setMask("");
   }
}
Beispiel #15
0
void InputDialog::initializeControl(Option const& opt, QCheckBox* check) {
   connectControl(opt, check);
   check->setToolTip(opt.getDescription());

   Action* action = new Action(
      boost::bind(&QCheckBox::setChecked, check, opt.getDefaultIndex()) );
   m_resetActions.push_back(action);

   Update* update = new Update(
      boost::bind(
         static_cast<void(*)(QCheckBox*, QString const&)>(SetControl), check, _1));
   QString name = opt.getName();
   m_setUpdates[name] = update;
}
Beispiel #16
0
void InputDialog::initializeControl(Option const& opt, QLineEdit* edit) {
   connectControl(opt, edit);
   edit->setToolTip(opt.getDescription());

   Action* action = new Action(
      boost::bind(&QLineEdit::setText, edit, opt.getOptionString()) );
   m_resetActions.push_back(action);

   Update* update = new Update(
      boost::bind(
         static_cast<void(*)(QLineEdit*, QString const&)>(SetControl), edit, _1));
   QString name = opt.getName();
   m_setUpdates[name] = update;
}
Beispiel #17
0
//! Inserts an Option into the database, overwriting the record if the
//! option name already exists.  The user is prompted if an overwrite will
//! occur and if \var promptOnOverwrite is set to true.
bool OptionDatabase::insert(Option const& opt, bool const promptOnOverwrite)
{
    Option tmp;
    QString name(opt.getName());

    if ( get(name, tmp) ) {
        if (promptOnOverwrite) {
            QString msg("Option name ");
            msg += name;
            msg += " already exists in database, overwrite?";
            int ret = QMsgBox::question(0, "Option Exists",msg,
                                        QMessageBox::Ok | QMessageBox::Cancel);
            if (ret == QMessageBox::Cancel) {
                return false;
            }
        }
        remove(name,false);
    }

    QString buf("insert into options( 'Name', 'Type', 'Default', 'Options', "
                "'Description', 'Implementation' ) values ( '");
    buf += opt.getName() + "', ";
    buf += QString::number(opt.getType()) + ", ";
    buf += QString::number(opt.getDefaultIndex()) + ", '";
    buf += opt.getOptionString() + "', ";   // No quote!

    QSqlField desc("Description", QVariant::String);
    desc.setValue(opt.getDescription());
    buf += QSqlDatabase::database("QChem").driver()->formatValue(desc);
    buf += ", ";
    buf += QString::number(opt.getImplementation()) + ");";

    qDebug() << "Database insert: " << buf;

    return execute(buf);
}
Beispiel #18
0
TEST(OptionsTest, json)
{
    // Test that a JSON option will be stringified into the option's underlying
    // value.
    Json::Value inJson;
    inJson["key"] = 42;
    const Option option_j("my_json", inJson);
    EXPECT_TRUE(option_j.getName() == "my_json");

    // Don't string-compare, test JSON-equality, since we don't care exactly
    // how it's stringified.
    Json::Value outJson;
    Json::Reader().parse(option_j.getValue(), outJson);

    EXPECT_EQ(inJson, outJson) << inJson << " != " << outJson;
}
Beispiel #19
0
inline ptree toPTree(const Option& option)
{
    ptree t;
    t.put("Name", option.getName());
    t.put("Value", option.getValue<std::string>());
    if (option.getDescription() != "")
    {
        t.put("Description", option.getDescription());
    }
    boost::optional<Options const&> options = option.getOptions();

    if (options != boost::none)
    {
        t.add_child("Options", toPTree(*options));
    }
    return t;
}
void ConfTool::do_opts (bool annotated, bool changed) {
  (void)annotated;(void)changed;
  std::vector<const char*>* opts = ConfigManager::getOptions();
  size_t i;
  buffer_t value, valid;
  const char* name, *init, *type;

  if (!opts)
    return;

  buffer_init(&value);
  buffer_init(&valid);

  for (i = 0; i < opts->size(); i++) {
    buffer_shrink(&value,0);
    buffer_shrink(&valid,0);
    Option* opt = ConfigManager::get(opts->at(i));
    name = opt->getName();
    type = opt->getType();
    init = opt->getInit();
    opt->query(&value);
    if (!opt->validity(&valid))
      buffer_shrink(&valid,0);
    int eq = buffer_equal1 (&value,init,-1);
    Option::prettyValue(&value);
    if (changed && eq)
      continue;
    cout << name << " = \"" << (NONULL(value.str)) << "\"";
    if (annotated) {
      cout << " #";
      if (!eq)
        cout << " (default: \"" << (NONULL(init)) << "\")";
      cout << " (type: " << (NONULL(type)) << ")";
      if (valid.len)
        cout << " (validity: " << valid.str << ")";
    }
    cout << endl;
  }

  delete opts;
  buffer_free (&value);
  buffer_free (&valid);
}
Beispiel #21
0
 /// Equality operator
 bool operator==(const Option& rhs) const
 {
     return (m_name == rhs.getName() &&
         m_value == rhs.getValue<std::string>() &&
         m_description == rhs.getDescription());
 }
Beispiel #22
0
void Options::add(const Option& option)
{
    m_options[option.getName()] = option;
}
Beispiel #23
0
/*********************************************************************
 ** METHOD  :
 ** PURPOSE :
 ** INPUT   :
 ** OUTPUT  :
 ** RETURN  :
 ** REMARKS :
 *********************************************************************/
void VisibilityOptionsVisitor::visitOption (Option& object, size_t depth)
{
    if (_names.find(object.getName()) != _names.end())  { object.setVisible(_visibility); }
}
Beispiel #24
0
void Options::add(const Option& option)
{
    m_options.insert(std::pair<std::string, Option>(option.getName(), option));
    // m_options[option.getName()] = option;
}
void OptionsList::usage()
{
  size_t len;
  char buffer[1024], *cp;

  cp = buffer;
  len = sprintf(buffer, "Usage: %s ", program_);
  cp += len;

  bool hasSimpleFlags = false;
	
  for (list<Option>::iterator iter = begin(); iter != end(); iter++)
  {
    Option *opt = &(*iter);
    if (opt->getName() != NULL &&
        !opt->hasArgument() &&
        (len = strlen(opt->getName())) == 1)
    {
      hasSimpleFlags = true;
      break;
    }
  }

  if (hasSimpleFlags)
  {
    *cp++ = '[';
    *cp++ = '-';
		
    for (list<Option>::iterator iter = begin(); iter != end(); iter++)
    {
      Option *opt = &(*iter);
      if (opt->getName() != NULL &&
          !opt->hasArgument() &&
          (len = strlen(opt->getName())) == 1)
      {
	strcpy(cp, opt->getName());
	cp += len;
      }
    }
		
    *cp++ = ']';
  }

  char staging[128], *cp2;
  for (list<Option>::iterator iter = begin(); iter != end(); iter++)
  {
    Option *opt = &(*iter);

    if (opt->getName() != NULL && !opt->hasArgument() && (len = strlen(opt->getName())) == 1)
      continue;
		
    *cp++ = ' ';

    cp2 = staging;
    if (!opt->isRequired())
    {
      *cp2++ = '[';
    }

    if (opt->getType() == Option::eList)
    {
      *cp2++ = '{';
    }
				
    if (opt->getName() != NULL && !opt->hasArgument() && strlen(opt->getName()) > 1)
    {
      len = sprintf(cp2, "-%s", opt->getName());
      cp2 += len;
    }
    else if (opt->getName() != NULL && opt->hasArgument())
    {
      len = sprintf(cp2, "-%s <%s>", opt->getName(), opt->getArgDesc());
      cp2 += len;
    }
    else if (opt->getName() == NULL)
    {
      len = sprintf(cp2, "<%s>", opt->getArgDesc());
      cp2 += len;
    }
		
    if (opt->getType() == Option::eList)
    {
      *cp2++ = '}';
      *cp2++ = '.';
      *cp2++ = '.';
      *cp2++ = '.';
    }
				
    if (!opt->isRequired())
    {
      *cp2++ = ']';
    }

    *cp2 = '\0';
		
    if (((cp2 - staging) + (cp - buffer)) > 79)
    {
      *cp++ = '\n';
      *cp = '\0';
			
      fputs(buffer, stderr);
      strcpy(buffer, "        ");
      cp = buffer + 8;
    }
		
    strcpy(cp, staging);
    cp += cp2 - staging;
  }

  *cp++ = '\n';
  *cp = '\0';
  fputs(buffer, stderr);
	

  for (list<Option>::iterator iter = begin(); iter != end(); iter++)
  {
    Option *opt = &(*iter);
    if (opt->getName() != NULL)
    {
      if (opt->hasArgument())
	sprintf(buffer, "-%-2.2s <%s>", opt->getName(), opt->getArgDesc());
      else
	sprintf(buffer, "-%-6.6s", opt->getName());
    }
    else if (opt->getOrder() >= 0)
    {
      sprintf(buffer, "<%s>", opt->getArgDesc());
    }
    else
    {
      sprintf(buffer, "<%s>...", opt->getArgDesc());
    }
		
    fprintf(stderr, "    %-20.20s : ", buffer);
    const char *cp = opt->getUsage();
    while (*cp != '\0')
    {
      if (*cp == '\n')
      {
	fputc(*cp, stderr);
	int count = 4 + 20 + 1;
	while (count--)
	  fputc(' ', stderr);
				
	fputc('>', stderr);
	fputc(' ', stderr);
      }
      else
      {
	fputc(*cp, stderr);
      }
			
      cp++;
    }
    fputc('\n', stderr);
  }

  exit(256);
}
int OptionsList::parse(int &aArgc, const char **aArgv)
{
  sort();
  
  // This assumes that the first option (app name) has already been removed.
  
  int order = 0, count = 0;

  program_ = "agent";
	
  Option *opt;
  const char **argp = aArgv;
  const char *cp;
	
  while (aArgc > 0)
  {
    if (**argp == '-')
    {
      cp = (*argp) + 1;
      bool next = false;

      while (*cp != 0 && !next)
      {
	if (find(cp, opt))
	{
	  count++;

	  if (opt->hasArgument())
	  {
	    getArg(argp, aArgc, opt, cp);
	    next = true;
	  }
	  else
	  {
	    if (opt->type_ != Option::eBoolean)
	    {
	      cerr << "Bad argument definition: " << opt->getName() << endl;
	    }
	    else if (opt->isSet_)
	    {
	      cerr << "Option " << opt->getName() << " is already specified" << endl;
	      usage();
	    }
	    else
	    {
	      *(opt->boolPtr_) = true;
	    }
						
	    cp += strlen(opt->getName());
	  }

	  opt->isSet_ = true;
	}
	else
	{
	  cerr << "Bad argument:" << *argp << endl;
	  usage();
	}
      }
    }
    else
    {
      if (find(order, opt))
      {
	if (!opt->setValue(*argp))
	  usage();

	count++;
      }
      else if (find(-1, opt))
      {
	if (!opt->setValue(*argp))
	  usage();

	count++;
      }

      order++;
    }
		
    argp++;
    aArgc--;
  }

  for (list<Option>::iterator iter = begin(); iter != end(); iter++)
  {
    opt = &(*iter);
    if (opt->isRequired() && !opt->isSet())
    {
      if (opt->getName() != NULL)
      	cerr << "Required option -" << opt->getName() << " is not specified" << endl;
      else
      	cerr << "Required option <" << opt->getArgDesc() << "> is not specified" << endl;
      usage();
    }
  }
  
  
  return count;
}