<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperCommandLineParser.h"

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperApplication.h"

#include <itksys/SystemTools.hxx>
#include <itksys/RegularExpression.hxx>
#include <string>
#include <iostream>

namespace otb
{
namespace Wrapper
{

CommandLineParser::CommandLineParser()
{
}

CommandLineParser::~CommandLineParser()
{
}

std::string
CommandLineParser::GetPathsAsString(const std::vector<std::string> & vexp )
{
  std::string res;
  std::vector<std::string> pathList;

  if (this->GetPaths(pathList,vexp) == OK)
    {
    std::vector<std::string>::iterator it;
    for (it=pathList.begin(); it!=pathList.end(); ++it)
      {
      if (!res.empty())
        {
        res.append(" ");
        }
      res.append(*it);
      }
    }
  return res;
}

std::string
CommandLineParser::GetPathsAsString( const std::string & exp )
{
  std::string res;
  // The first element must be the module path, non " -" allowed.
  // The module path list element are the strings between the first
  // element and the next key (ie. " -" string).
  std::string tempModPath = exp;

  if( exp.find(" -") != std::string::npos)
    {
    tempModPath = exp.substr( 0, exp.find(" -"));
    }

  // Get everything after the module path
  if( tempModPath.find(" ") != std::string::npos)
    {
    res = tempModPath.substr( tempModPath.find(" ")+1, tempModPath.size());
    }

  // Suppress possible multi space at the beginning of the string
  while (res.size()>0 && res[0]==' ')
    {
    res.erase(0, 1);
    }

  return res;
}

CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::vector<std::string> & exp )
{
  // The first element must be the module name, non " -" allowed.
  // The module path list elements are the strings between the first
  // element and the first key (ie. string which begins with "-").
  std::vector<std::string>::const_iterator it = exp.begin();
  ++it; // first element is module name

  std::string tmpPath;

  while (it != exp.end())
    {
    tmpPath = *it;
    // If this is the first key : exit loop
    if (tmpPath[0]=='-')
      {
      break;
      }
    // Add path to result
    std::string fullPath = itksys::SystemTools::CollapseFullPath(tmpPath.c_str());
    if( !itksys::SystemTools::FileIsDirectory(fullPath.c_str()) )
      {
      std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
      return INVALIDMODULEPATH;
      }
    paths.push_back(fullPath);
    ++it;
    }

  if (paths.empty())
    {
    return NOMODULEPATH;
    }

  return OK;
}

CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::string & exp )
{
  std::string pathsList = this->GetPathsAsString( exp );

  if( pathsList.size() == 0 )
    {
    return NOMODULEPATH;
    }

  std::string tempModPath = pathsList;
  // remove other key in the string if there's any
  if( pathsList.find(" -") != std::string::npos)
    {
    tempModPath = pathsList.substr( 0, pathsList.find(" -"));
    }

  if( tempModPath.size() > 0 )
    {
    std::vector<itksys::String> pathAttribut = itksys::SystemTools::SplitString(tempModPath.substr(0, tempModPath.size()).c_str(), ' ', false);

    // Remove " " string element
    for(unsigned int i=0; i<pathAttribut.size(); i++)
      {
      // Suppress possible multi space at the beginning of the string
      while (pathAttribut[i].size()>1 && pathAttribut[i][0]==' ')
      {
      pathAttribut[i].erase(0, 1);
      }

      std::string fullPath = itksys::SystemTools::CollapseFullPath(pathAttribut[i].c_str());

      if( !itksys::SystemTools::FileIsDirectory(fullPath.c_str()) )
        {
        std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
        return INVALIDMODULEPATH;
        }
      paths.push_back(fullPath);
      }
    }
  else
    {
    return NOMODULEPATH;
    }

  return OK;
}

CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::vector<std::string> & exp )
{
  itksys::RegularExpression reg;
  reg.compile("([^0-9a-zA-Z])");
  // The first element must be the module path, non " -" allowed.
  if( exp[0][0] == '-')
    {
    return NOMODULENAME;
    }

  // It must contain only alphanumerical character
  if(reg.find(exp[0]))
    {
    return INVALIDMODULENAME;
    }
  else
    {
    modName = exp[0];
    }

  return OK;
}

CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::string & exp )
{
  std::vector<itksys::String> spaceSplittedExp = itksys::SystemTools::SplitString(exp.c_str(), ' ', false);
  // if the chain is "  module", SplitString will return: [ ], [module]
  for(unsigned int i=0; i<spaceSplittedExp.size(); i++)
    {
    if( spaceSplittedExp[i] == " ")
      {
      spaceSplittedExp.erase(spaceSplittedExp.begin()+i);
      i--;
      }
    }

  // The SplitString keep the separator in the string.
  // If exists a space a the beginnig of the string, it will be interpreted...
  // We have to delete it
  if( spaceSplittedExp[0][0] == ' ' )
    {
    spaceSplittedExp[0].erase(spaceSplittedExp[0].begin());
    }

  itksys::RegularExpression reg;
  reg.compile("([^0-9a-zA-Z])");
  // The first element must be the module path, non " -" allowed.
  if( spaceSplittedExp[0].substr(0, 2) == " -" || spaceSplittedExp.size() == 0 )
    {
    return NOMODULENAME;
    }

  // It must contain only alphanumerical character
  if(reg.find(spaceSplittedExp[0]))
    {
    return INVALIDMODULENAME;
    }
  else
    {
    modName = spaceSplittedExp[0];
    }

  return OK;
}

std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::vector<std::string> & exp )
{
  std::vector<std::string> res;
  if (!this->IsAttributExists(key,exp))
    return res;

  bool foundKey=false;
  std::vector<std::string>::const_iterator it = exp.begin();
  while(it!=exp.end() )
    {
    if (foundKey)
      {
      if (it->find("-") == 0)
        {
        std::string tmpKey = it->substr(1,std::string::npos);
        if (this->IsAValidKey(tmpKey))
          {
          break;
          }
        else
          {
          res.push_back(*it);
          }
        }
      else
        res.push_back(*it);
      }
    else
      {
      if (it->compare(key) == 0)
        {
        foundKey=true;
        }
      }
    ++it;
    }
  return res;
}

std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::string & exp )
{
  std::vector<std::string> res;

  std::string keySpaced = key;
  keySpaced.append(" ");
  std::size_t found = std::string(exp).find(keySpaced);
  if( found == std::string::npos )
    {
    return res;
    }
  std::string expFromKey = std::string(exp).substr(found+key.size()+1, std::string(exp).size());

  if( expFromKey.size() == 0 )
    {
    return res;
    }
  std::string tempModKey = expFromKey;
  // remove other key in the string if there's any
  bool stop = false;
  std::size_t curPos = expFromKey.find(" -");
  std::size_t curPosOld = 0;

  while ( !stop && curPos != std::string::npos )
    {
    std::string tmp = expFromKey.substr(curPosOld, curPos);

    if( tmp.find(" ") != std::string::npos)
      {
      tmp = tmp.substr(0, tmp.find(" "));
      }

    if( this->IsAValidKey(tmp) )
      {
      tempModKey = expFromKey.substr(0, curPos);
      stop = true;
      }
    else
      {
      if( curPosOld>1 )
        {
        if( expFromKey[curPos] != '-' )
          {
          tempModKey = expFromKey.substr(0, curPos);
          stop = true;
          }
        }
      else
        {
        tempModKey = expFromKey.substr(0, curPos);
        stop = true;
        }
      }

    curPosOld = curPos;
    curPos = expFromKey.find(" -", curPos);
    if(curPos!=std::string::npos)
      curPos += 2;
    }

  // Only if the key has values associated
  if( tempModKey.size() > 0 )
    {
    std::vector<itksys::String> spaceSplitted = itksys::SystemTools::SplitString(tempModKey.substr(0, tempModKey.size()).c_str(), ' ', false);

    // Remove " " string element
    for(unsigned int i=0; i<spaceSplitted.size(); i++)
      {
      if( spaceSplitted[i] == " ")
        {
        spaceSplitted.erase(spaceSplitted.begin()+i);
        i--;
        }
      }

    // Remove space at the beginning of the string and cast into std::vector<std::string>
    for(unsigned int i=0; i<spaceSplitted.size(); i++)
      {
      while( spaceSplitted[i].size()>0  && spaceSplitted[i][0] == ' ' )
        {
        spaceSplitted[i] = spaceSplitted[i].substr(1, spaceSplitted[i].size());
        }

      res.push_back(spaceSplitted[i]);
      }
    }
  return res;
}

std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::vector<std::string> & exp )
{
  std::string res("");
  std::vector<std::string> values = this->GetAttribut( key, exp );

  if( values.size() == 0 )
    {
    return "";
    }
  else if( values.size() == 1 && values[0] == " " )
    {
    return "";
    }

  for( unsigned int i=0; i<values.size(); i++)
    {
    if( i<values.size()-1 )
      {
      res.append(values[i]);
      res.append(" ");
      }
    else
      {
      res.append(values[i]);
      }
    }
  return res;
}

std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::string & exp )
{
  std::string res("");
  std::vector<std::string> values = this->GetAttribut( key, exp );

  if( values.size() == 0 )
    {
    return "";
    }
  else if( values.size() == 1 && values[0] == " " )
    {
    return "";
    }

  for( unsigned int i=0; i<values.size(); i++)
    {
    if( i<values.size()-1 )
      {
      res.append(values[i]);
      res.append(" ");
      }
    else
      {
      res.append(values[i]);
      }
    }
  return res;
}

bool
CommandLineParser::IsAttributExists( const std::string key, const std::string & exp  )
{
  std::string keySpaced = key;
  std::string expSpaced = exp;
  // Add space to avoid troubles with key which starts by another one : -out and -outmax for example
  keySpaced.append(" ");
  expSpaced.append(" ");
  std::size_t found = expSpaced.find(keySpaced);
  return (found != std::string::npos);
}

bool
CommandLineParser::IsAttributExists( const std::string key, const std::vector<std::string> & exp  )
{
  for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
    {
    if (it->compare(key) == 0)
      return true;
    }
  return false;
}

std::vector<std::string>
CommandLineParser::GetKeyList( const std::vector<std::string> & exp  )
{
  std::vector<std::string> keyList;
  for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
    {
    if (it->find("-") == 0)
      {
      // Remove first character ('-')
      std::string key = it->substr(1,std::string::npos);
      if (this->IsAValidKey(key))
        {
        keyList.push_back(key);
        }
      }
    }

  return keyList;
}

std::vector<std::string>
CommandLineParser::GetKeyList( const std::string & exp  )
{
  std::vector<std::string> keyList;
  std::string cutExp(exp);
  std::size_t found = exp.find(" -");

  while( found != std::string::npos )
    {
    // Supress everything before the key
    cutExp = cutExp.substr(found+2, exp.size());
    // Search the end of the key (a space)
    std::size_t foundSpace = cutExp.find(" ");
    std::string tmpKey = cutExp;
    if( foundSpace != std::string::npos )
      {
      tmpKey = cutExp.substr(0, foundSpace);
      }

    if( this->IsAValidKey(tmpKey) )
      {
      keyList.push_back( tmpKey );
      }

    // Search the next key (ie. " -")
    found = cutExp.find(" -");
    }

  return keyList;
}

bool
CommandLineParser::IsAValidKey( const std::string & foundKey )
{
  bool res = false;
  std::string tmp = foundKey;
  // make sure the tested key ends with a dot.
  // the starting dash should be already removed
  tmp.append(".");

  // To be a key, the string must be a serie of groups separated by dots so that :
  // - each group begins with an lower case letter
  // - each group contains only alphanumeric characters (and lowercase)
  // This also implies that each group is not empty and that the key doesn't
  // start with a dot. These conditions shouldn't match any number even in
  // scientific notation.
  // The following regular expression says just that
  itksys::RegularExpression reg;
  reg.compile("^([a-z][a-z0-9]*\\.)+$");
  if( reg.find(tmp) )
    {
    res = true;
    }

  return res;
}

}
}

<commit_msg>ENH: allow application keys beginning with a number<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperCommandLineParser.h"

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperApplication.h"

#include <itksys/SystemTools.hxx>
#include <itksys/RegularExpression.hxx>
#include <string>
#include <iostream>

namespace otb
{
namespace Wrapper
{

CommandLineParser::CommandLineParser()
{
}

CommandLineParser::~CommandLineParser()
{
}

std::string
CommandLineParser::GetPathsAsString(const std::vector<std::string> & vexp )
{
  std::string res;
  std::vector<std::string> pathList;

  if (this->GetPaths(pathList,vexp) == OK)
    {
    std::vector<std::string>::iterator it;
    for (it=pathList.begin(); it!=pathList.end(); ++it)
      {
      if (!res.empty())
        {
        res.append(" ");
        }
      res.append(*it);
      }
    }
  return res;
}

std::string
CommandLineParser::GetPathsAsString( const std::string & exp )
{
  std::string res;
  // The first element must be the module path, non " -" allowed.
  // The module path list element are the strings between the first
  // element and the next key (ie. " -" string).
  std::string tempModPath = exp;

  if( exp.find(" -") != std::string::npos)
    {
    tempModPath = exp.substr( 0, exp.find(" -"));
    }

  // Get everything after the module path
  if( tempModPath.find(" ") != std::string::npos)
    {
    res = tempModPath.substr( tempModPath.find(" ")+1, tempModPath.size());
    }

  // Suppress possible multi space at the beginning of the string
  while (res.size()>0 && res[0]==' ')
    {
    res.erase(0, 1);
    }

  return res;
}

CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::vector<std::string> & exp )
{
  if (exp.empty())
    {
    return NOMODULEPATH;
    }

  // The first element must be the module name, non " -" allowed.
  // The module path list elements are the strings between the first
  // element and the first key (ie. string which begins with "-").
  std::vector<std::string>::const_iterator it = exp.begin();
  ++it; // first element is module name

  std::string tmpPath;

  while (it != exp.end())
    {
    tmpPath = *it;
    // If this is the first key : exit loop
    if (tmpPath[0]=='-')
      {
      break;
      }
    // Add path to result
    std::string fullPath = itksys::SystemTools::CollapseFullPath(tmpPath.c_str());
    if( !itksys::SystemTools::FileIsDirectory(fullPath.c_str()) )
      {
      std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
      return INVALIDMODULEPATH;
      }
    paths.push_back(fullPath);
    ++it;
    }

  if (paths.empty())
    {
    return NOMODULEPATH;
    }

  return OK;
}

CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::string & exp )
{
  std::string pathsList = this->GetPathsAsString( exp );

  if( pathsList.size() == 0 )
    {
    return NOMODULEPATH;
    }

  std::string tempModPath = pathsList;
  // remove other key in the string if there's any
  if( pathsList.find(" -") != std::string::npos)
    {
    tempModPath = pathsList.substr( 0, pathsList.find(" -"));
    }

  if( tempModPath.size() > 0 )
    {
    std::vector<itksys::String> pathAttribut = itksys::SystemTools::SplitString(tempModPath.substr(0, tempModPath.size()).c_str(), ' ', false);

    // Remove " " string element
    for(unsigned int i=0; i<pathAttribut.size(); i++)
      {
      // Suppress possible multi space at the beginning of the string
      while (pathAttribut[i].size()>1 && pathAttribut[i][0]==' ')
      {
      pathAttribut[i].erase(0, 1);
      }

      std::string fullPath = itksys::SystemTools::CollapseFullPath(pathAttribut[i].c_str());

      if( !itksys::SystemTools::FileIsDirectory(fullPath.c_str()) )
        {
        std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
        return INVALIDMODULEPATH;
        }
      paths.push_back(fullPath);
      }
    }
  else
    {
    return NOMODULEPATH;
    }

  return OK;
}

CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::vector<std::string> & exp )
{
  if (exp.empty())
    {
    return NOMODULENAME;
    }

  itksys::RegularExpression reg;
  reg.compile("([^0-9a-zA-Z])");
  // The first element must be the module path, non " -" allowed.
  if( exp[0][0] == '-')
    {
    return NOMODULENAME;
    }

  // It must contain only alphanumerical character
  if(reg.find(exp[0]))
    {
    return INVALIDMODULENAME;
    }
  else
    {
    modName = exp[0];
    }

  return OK;
}

CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::string & exp )
{
  std::vector<itksys::String> spaceSplittedExp = itksys::SystemTools::SplitString(exp.c_str(), ' ', false);
  // if the chain is "  module", SplitString will return: [ ], [module]
  for(unsigned int i=0; i<spaceSplittedExp.size(); i++)
    {
    if( spaceSplittedExp[i] == " ")
      {
      spaceSplittedExp.erase(spaceSplittedExp.begin()+i);
      i--;
      }
    }

  // The SplitString keep the separator in the string.
  // If exists a space a the beginnig of the string, it will be interpreted...
  // We have to delete it
  if( spaceSplittedExp[0][0] == ' ' )
    {
    spaceSplittedExp[0].erase(spaceSplittedExp[0].begin());
    }

  itksys::RegularExpression reg;
  reg.compile("([^0-9a-zA-Z])");
  // The first element must be the module path, non " -" allowed.
  if( spaceSplittedExp[0].substr(0, 2) == " -" || spaceSplittedExp.size() == 0 )
    {
    return NOMODULENAME;
    }

  // It must contain only alphanumerical character
  if(reg.find(spaceSplittedExp[0]))
    {
    return INVALIDMODULENAME;
    }
  else
    {
    modName = spaceSplittedExp[0];
    }

  return OK;
}

std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::vector<std::string> & exp )
{
  std::vector<std::string> res;
  if (!this->IsAttributExists(key,exp))
    return res;

  bool foundKey=false;
  std::vector<std::string>::const_iterator it = exp.begin();
  while(it!=exp.end() )
    {
    if (foundKey)
      {
      if (it->find("-") == 0)
        {
        std::string tmpKey = it->substr(1,std::string::npos);
        if (this->IsAValidKey(tmpKey))
          {
          break;
          }
        else
          {
          res.push_back(*it);
          }
        }
      else
        res.push_back(*it);
      }
    else
      {
      if (it->compare(key) == 0)
        {
        foundKey=true;
        }
      }
    ++it;
    }
  return res;
}

std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::string & exp )
{
  std::vector<std::string> res;

  std::string keySpaced = key;
  keySpaced.append(" ");
  std::size_t found = std::string(exp).find(keySpaced);
  if( found == std::string::npos )
    {
    return res;
    }
  std::string expFromKey = std::string(exp).substr(found+key.size()+1, std::string(exp).size());

  if( expFromKey.size() == 0 )
    {
    return res;
    }
  std::string tempModKey = expFromKey;
  // remove other key in the string if there's any
  bool stop = false;
  std::size_t curPos = expFromKey.find(" -");
  std::size_t curPosOld = 0;

  while ( !stop && curPos != std::string::npos )
    {
    std::string tmp = expFromKey.substr(curPosOld, curPos);

    if( tmp.find(" ") != std::string::npos)
      {
      tmp = tmp.substr(0, tmp.find(" "));
      }

    if( this->IsAValidKey(tmp) )
      {
      tempModKey = expFromKey.substr(0, curPos);
      stop = true;
      }
    else
      {
      if( curPosOld>1 )
        {
        if( expFromKey[curPos] != '-' )
          {
          tempModKey = expFromKey.substr(0, curPos);
          stop = true;
          }
        }
      else
        {
        tempModKey = expFromKey.substr(0, curPos);
        stop = true;
        }
      }

    curPosOld = curPos;
    curPos = expFromKey.find(" -", curPos);
    if(curPos!=std::string::npos)
      curPos += 2;
    }

  // Only if the key has values associated
  if( tempModKey.size() > 0 )
    {
    std::vector<itksys::String> spaceSplitted = itksys::SystemTools::SplitString(tempModKey.substr(0, tempModKey.size()).c_str(), ' ', false);

    // Remove " " string element
    for(unsigned int i=0; i<spaceSplitted.size(); i++)
      {
      if( spaceSplitted[i] == " ")
        {
        spaceSplitted.erase(spaceSplitted.begin()+i);
        i--;
        }
      }

    // Remove space at the beginning of the string and cast into std::vector<std::string>
    for(unsigned int i=0; i<spaceSplitted.size(); i++)
      {
      while( spaceSplitted[i].size()>0  && spaceSplitted[i][0] == ' ' )
        {
        spaceSplitted[i] = spaceSplitted[i].substr(1, spaceSplitted[i].size());
        }

      res.push_back(spaceSplitted[i]);
      }
    }
  return res;
}

std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::vector<std::string> & exp )
{
  std::string res("");
  std::vector<std::string> values = this->GetAttribut( key, exp );

  if( values.size() == 0 )
    {
    return "";
    }
  else if( values.size() == 1 && values[0] == " " )
    {
    return "";
    }

  for( unsigned int i=0; i<values.size(); i++)
    {
    if( i<values.size()-1 )
      {
      res.append(values[i]);
      res.append(" ");
      }
    else
      {
      res.append(values[i]);
      }
    }
  return res;
}

std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::string & exp )
{
  std::string res("");
  std::vector<std::string> values = this->GetAttribut( key, exp );

  if( values.size() == 0 )
    {
    return "";
    }
  else if( values.size() == 1 && values[0] == " " )
    {
    return "";
    }

  for( unsigned int i=0; i<values.size(); i++)
    {
    if( i<values.size()-1 )
      {
      res.append(values[i]);
      res.append(" ");
      }
    else
      {
      res.append(values[i]);
      }
    }
  return res;
}

bool
CommandLineParser::IsAttributExists( const std::string key, const std::string & exp  )
{
  std::string keySpaced = key;
  std::string expSpaced = exp;
  // Add space to avoid troubles with key which starts by another one : -out and -outmax for example
  keySpaced.append(" ");
  expSpaced.append(" ");
  std::size_t found = expSpaced.find(keySpaced);
  return (found != std::string::npos);
}

bool
CommandLineParser::IsAttributExists( const std::string key, const std::vector<std::string> & exp  )
{
  for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
    {
    if (it->compare(key) == 0)
      return true;
    }
  return false;
}

std::vector<std::string>
CommandLineParser::GetKeyList( const std::vector<std::string> & exp  )
{
  std::vector<std::string> keyList;
  for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
    {
    if (it->find("-") == 0)
      {
      // Remove first character ('-')
      std::string key = it->substr(1,std::string::npos);
      if (this->IsAValidKey(key))
        {
        keyList.push_back(key);
        }
      }
    }

  return keyList;
}

std::vector<std::string>
CommandLineParser::GetKeyList( const std::string & exp  )
{
  std::vector<std::string> keyList;
  std::string cutExp(exp);
  std::size_t found = exp.find(" -");

  while( found != std::string::npos )
    {
    // Supress everything before the key
    cutExp = cutExp.substr(found+2, exp.size());
    // Search the end of the key (a space)
    std::size_t foundSpace = cutExp.find(" ");
    std::string tmpKey = cutExp;
    if( foundSpace != std::string::npos )
      {
      tmpKey = cutExp.substr(0, foundSpace);
      }

    if( this->IsAValidKey(tmpKey) )
      {
      keyList.push_back( tmpKey );
      }

    // Search the next key (ie. " -")
    found = cutExp.find(" -");
    }

  return keyList;
}

bool
CommandLineParser::IsAValidKey( const std::string & foundKey )
{
  bool res = false;
  std::string tmp = foundKey;
  // make sure the tested key ends with a dot.
  // the starting dash should be already removed
  tmp.append(".");

  // To be a key, the string must be a serie of groups separated by dots so that :
  // - each group has at least one character
  // - each group contains only alphanumeric characters (and lowercase)
  // - there is at least one group
  // The following regular expression says just that
  itksys::RegularExpression reg;
  reg.compile("^([a-z0-9]+\\.)+$");
  if( reg.find(tmp) )
    {
    res = true;
    }

  // a second test is performed to detect negative numbers (even in
  // scientific notation). Any key that matches the search pattern for a
  // number is considered not valid.
  itksys::RegularExpression regNum;
  regNum.compile("^([0-9]+(\\.[0-9]*)?([eE][+-]?[0-9]+)?)$");
  if( regNum.find(foundKey) )
    {
    res = false;
    }

  return res;
}

}
}

<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2009 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
#include "OgreShaderProgramWriter.h"

#define ENDL "\n"

namespace Ogre {
namespace RTShader {

//-----------------------------------------------------------------------
void ProgramWriter::writeProgramTitle(StringSerialiser& os, Program* program)
{
	os << "//-----------------------------------------------------------------------------" << ENDL;
	os << "// Program Type: ";
	switch(program->getType())
	{
	case GPT_VERTEX_PROGRAM:
		os << "Vertex shader";
		break;
	case GPT_FRAGMENT_PROGRAM:
		os << "Fragment shader";
		break;
	case GPT_GEOMETRY_PROGRAM:
		os << "Geometry shader";
		break;
	default:
		break;
	}
	os << ENDL;
	os << "// Language: " <<  getTargetLanguage() << ENDL;
	os << "// Created by Ogre RT Shader Generator. All rights reserved." << ENDL;
	os << "//-----------------------------------------------------------------------------" << ENDL;
}

//-----------------------------------------------------------------------
void ProgramWriter::writeUniformParametersTitle(StringSerialiser& os, Program* program)
{
	os << "//-----------------------------------------------------------------------------" << ENDL;
	os << "//                         GLOBAL PARAMETERS" << ENDL;
	os << "//-----------------------------------------------------------------------------" << ENDL;
}
//-----------------------------------------------------------------------
void ProgramWriter::writeFunctionTitle(StringSerialiser& os, Function* function)
{
	os << "//-----------------------------------------------------------------------------" << ENDL;
	os << "// Function Name: " <<  function->getName() << ENDL;
	os << "// Function Desc: " <<  function->getDescription() << ENDL;
	os << "//-----------------------------------------------------------------------------" << ENDL;
}

}
}
<commit_msg>Added Guards so StringSerialiser is only used on Android.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2009 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
#include "OgreShaderProgramWriter.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
#	define ENDL "\n"
#else
#	define ENDL std::endl
#endif

namespace Ogre {
namespace RTShader {

//-----------------------------------------------------------------------
void ProgramWriter::writeProgramTitle(
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
	StringSerialiser& os,
#else
	std::ostream &os,
#endif
	Program* program)
{
	os << "//-----------------------------------------------------------------------------" << ENDL;
	os << "// Program Type: ";
	switch(program->getType())
	{
	case GPT_VERTEX_PROGRAM:
		os << "Vertex shader";
		break;
	case GPT_FRAGMENT_PROGRAM:
		os << "Fragment shader";
		break;
	case GPT_GEOMETRY_PROGRAM:
		os << "Geometry shader";
		break;
	default:
		break;
	}
	os << ENDL;
	os << "// Language: " <<  getTargetLanguage() << ENDL;
	os << "// Created by Ogre RT Shader Generator. All rights reserved." << ENDL;
	os << "//-----------------------------------------------------------------------------" << ENDL;
}

//-----------------------------------------------------------------------
void ProgramWriter::writeUniformParametersTitle(
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
	StringSerialiser& os,
#else
	std::ostream &os,
#endif
	Program* program)
{
	os << "//-----------------------------------------------------------------------------" << ENDL;
	os << "//                         GLOBAL PARAMETERS" << ENDL;
	os << "//-----------------------------------------------------------------------------" << ENDL;
}
//-----------------------------------------------------------------------
void ProgramWriter::writeFunctionTitle(
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
	StringSerialiser& os,
#else
	std::ostream &os,
#endif
	Function* function)
{
	os << "//-----------------------------------------------------------------------------" << ENDL;
	os << "// Function Name: " <<  function->getName() << ENDL;
	os << "// Function Desc: " <<  function->getDescription() << ENDL;
	os << "//-----------------------------------------------------------------------------" << ENDL;
}

}
}
<|endoftext|>


<commit_before>/*
 @ 0xCCCCCCCC
*/

#include <iostream>

#include <windows.h>
#include <winsock2.h>

#include "kbase/at_exit_manager.h"
#include "kbase/command_line.h"
#include "kbase/error_exception_util.h"
#include "kbase/os_info.h"
#include "kbase/scope_guard.h"
#include "kbase/scoped_handle.h"

#include "iocp_utils.h"
#include "scoped_socket.h"

namespace {

BOOL WINAPI ControlCtrlHandler(DWORD ctrl)
{
    switch (ctrl) {
        case CTRL_C_EVENT:
        case CTRL_BREAK_EVENT:
            return TRUE;

        default:
            return FALSE;
    }
}

void InitializeWinsock()
{
    WSADATA data {0};
    auto result_code = WSAStartup(MAKEWORD(2, 2), &data);
    ENSURE(THROW, result_code == 0)(result_code).Require();
    std::cout << "-*- Windows Socket Library Initialized -*-\n";
}

void CleanWinsock()
{
    WSACleanup();
    std::cout << "-*- Windows Socket Library Cleaned -*-\n";
}

ScopedSocketHandle CreateListener(unsigned short port, int max_pending_clients)
{
    ScopedSocketHandle listener(
        WSASocketW(AF_INET, SOCK_STREAM, 0, nullptr, 0, WSA_FLAG_OVERLAPPED));
    ENSURE(CHECK, !!listener).Require();

    sockaddr_in server_addr {0};
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(listener.get(), reinterpret_cast<sockaddr*>(&server_addr), sizeof(server_addr));

    listen(listener.get(), max_pending_clients);

    return listener;
}

}   // namespace

int main()
{
    kbase::CommandLine::Init(0, nullptr);
    kbase::AtExitManager exit_manager;

    InitializeWinsock();
    ON_SCOPE_EXIT { CleanWinsock(); };

    SetConsoleCtrlHandler(ControlCtrlHandler, TRUE);
    ON_SCOPE_EXIT { SetConsoleCtrlHandler(nullptr, FALSE); };

    auto listener = CreateListener(8088, 10);

    DWORD kConcurrentWorkers = kbase::OSInfo::GetInstance()->number_of_cores();
    auto io_port = utils::CreateNewIOCP(utils::CompletionKeyIO, kConcurrentWorkers);

    bool success = utils::AssociateDeviceWithIOCP(reinterpret_cast<HANDLE>(listener.get()),
                                                  io_port.get(),
                                                  utils::CompletionKeyIO);

    std::cin.get();

    return 0;
}
<commit_msg>Add slight modifications to make existing part more comprehensive<commit_after>/*
 @ 0xCCCCCCCC
*/

#include <iostream>

#include <windows.h>
#include <winsock2.h>

#include "kbase/at_exit_manager.h"
#include "kbase/command_line.h"
#include "kbase/error_exception_util.h"
#include "kbase/scope_guard.h"
#include "kbase/scoped_handle.h"

#include "iocp_utils.h"
#include "scoped_socket.h"

namespace {

BOOL WINAPI ControlCtrlHandler(DWORD ctrl)
{
    switch (ctrl) {
        case CTRL_C_EVENT:
        case CTRL_BREAK_EVENT:
            return TRUE;

        default:
            return FALSE;
    }
}

void InitializeWinsock()
{
    WSADATA data {0};
    auto result_code = WSAStartup(MAKEWORD(2, 2), &data);
    ENSURE(THROW, result_code == 0)(result_code).Require();
    std::cout << "-*- Windows Socket Library Initialized -*-\n";
}

void CleanWinsock()
{
    WSACleanup();
    std::cout << "-*- Windows Socket Library Cleaned -*-\n";
}

ScopedSocketHandle CreateListener(unsigned short port, int max_pending_clients)
{
    ScopedSocketHandle listener(
        WSASocketW(AF_INET, SOCK_STREAM, 0, nullptr, 0, WSA_FLAG_OVERLAPPED));
    ENSURE(CHECK, !!listener).Require();

    sockaddr_in server_addr {0};
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int rv = bind(listener.get(), reinterpret_cast<sockaddr*>(&server_addr), sizeof(server_addr));
    ENSURE(CHECK, rv == 0)(WSAGetLastError()).Require();

    rv = listen(listener.get(), max_pending_clients);
    ENSURE(CHECK, rv == 0)(WSAGetLastError()).Require();

    return listener;
}

}   // namespace

int main()
{
    kbase::CommandLine::Init(0, nullptr);
    kbase::AtExitManager exit_manager;

    InitializeWinsock();
    ON_SCOPE_EXIT { CleanWinsock(); };

    SetConsoleCtrlHandler(ControlCtrlHandler, TRUE);
    ON_SCOPE_EXIT { SetConsoleCtrlHandler(nullptr, FALSE); };

    constexpr unsigned short kPort = 8088;
    constexpr int kMaxPending = 10;

    auto listener = CreateListener(kPort, kMaxPending);

    // Default to number of cores in the system.
    auto io_port = utils::CreateNewIOCP(utils::CompletionKeyIO, 0);

    bool success = utils::AssociateDeviceWithIOCP(reinterpret_cast<HANDLE>(listener.get()),
                                                  io_port.get(),
                                                  utils::CompletionKeyIO);
    ENSURE(CHECK, success)(kbase::LastError()).Require();

    std::cin.get();

    return 0;
}
<|endoftext|>


<commit_before>/* Please refer to license.txt */

/*
 * Shamelessly taken from: http://www.cegui.org.uk/wiki/index.php/SFML_to_CEGUI_keytable :)
 * By the way, thanks a ton to whoever made that. SFML 0.8 documentation is severely lacking.
 */

namespace GEngine
{

#include "interface.hpp"

namespace mui
{

void Interface::mapSFMLKeysToCEGUI()
{
	sfml_cegui_keymap[sf::Keyboard::A]			= CEGUI::Key::A;
	sfml_cegui_keymap[sf::Keyboard::B]			= CEGUI::Key::B;
	sfml_cegui_keymap[sf::Keyboard::C]			= CEGUI::Key::C;
	sfml_cegui_keymap[sf::Keyboard::D]			= CEGUI::Key::D;
	sfml_cegui_keymap[sf::Keyboard::E]			= CEGUI::Key::E;
	sfml_cegui_keymap[sf::Keyboard::F]			= CEGUI::Key::F;
	sfml_cegui_keymap[sf::Keyboard::G]			= CEGUI::Key::G;
	sfml_cegui_keymap[sf::Keyboard::H]			= CEGUI::Key::H;
	sfml_cegui_keymap[sf::Keyboard::I]			= CEGUI::Key::I;
	sfml_cegui_keymap[sf::Keyboard::J]			= CEGUI::Key::J;
	sfml_cegui_keymap[sf::Keyboard::K]			= CEGUI::Key::K;
	sfml_cegui_keymap[sf::Keyboard::L]			= CEGUI::Key::L;
	sfml_cegui_keymap[sf::Keyboard::M]			= CEGUI::Key::M;
	sfml_cegui_keymap[sf::Keyboard::N]			= CEGUI::Key::N;
	sfml_cegui_keymap[sf::Keyboard::O]			= CEGUI::Key::O;
	sfml_cegui_keymap[sf::Keyboard::P]			= CEGUI::Key::P;
	sfml_cegui_keymap[sf::Keyboard::Q]			= CEGUI::Key::Q;
	sfml_cegui_keymap[sf::Keyboard::R]			= CEGUI::Key::R;
	sfml_cegui_keymap[sf::Keyboard::S]			= CEGUI::Key::S;
	sfml_cegui_keymap[sf::Keyboard::T]			= CEGUI::Key::T;
	sfml_cegui_keymap[sf::Keyboard::U]			= CEGUI::Key::U;
	sfml_cegui_keymap[sf::Keyboard::V]			= CEGUI::Key::V;
	sfml_cegui_keymap[sf::Keyboard::W]			= CEGUI::Key::W;
	sfml_cegui_keymap[sf::Keyboard::X]			= CEGUI::Key::X;
	sfml_cegui_keymap[sf::Keyboard::Y]			= CEGUI::Key::Y;
	sfml_cegui_keymap[sf::Keyboard::Z]			= CEGUI::Key::Z;
	sfml_cegui_keymap[sf::Keyboard::Num0]			= CEGUI::Key::Zero;
	sfml_cegui_keymap[sf::Keyboard::Num1]			= CEGUI::Key::One;
	sfml_cegui_keymap[sf::Keyboard::Num2]			= CEGUI::Key::Two;
	sfml_cegui_keymap[sf::Keyboard::Num3]			= CEGUI::Key::Three;
	sfml_cegui_keymap[sf::Keyboard::Num4]			= CEGUI::Key::Four;
	sfml_cegui_keymap[sf::Keyboard::Num5]			= CEGUI::Key::Five;
	sfml_cegui_keymap[sf::Keyboard::Num6]			= CEGUI::Key::Six;
	sfml_cegui_keymap[sf::Keyboard::Num7]			= CEGUI::Key::Seven;
	sfml_cegui_keymap[sf::Keyboard::Num8]			= CEGUI::Key::Eight;
	sfml_cegui_keymap[sf::Keyboard::Num9]			= CEGUI::Key::Nine;
	sfml_cegui_keymap[sf::Keyboard::Escape]			= CEGUI::Key::Escape;
	sfml_cegui_keymap[sf::Keyboard::LControl]		= CEGUI::Key::LeftControl;
	sfml_cegui_keymap[sf::Keyboard::LShift]			= CEGUI::Key::LeftShift;
	sfml_cegui_keymap[sf::Keyboard::LAlt]			= CEGUI::Key::LeftAlt;
	sfml_cegui_keymap[sf::Keyboard::LSystem]		= CEGUI::Key::LeftWindows;
	sfml_cegui_keymap[sf::Keyboard::RControl]		= CEGUI::Key::RightControl;
	sfml_cegui_keymap[sf::Keyboard::RShift]			= CEGUI::Key::RightShift;
	sfml_cegui_keymap[sf::Keyboard::RAlt]			= CEGUI::Key::RightAlt;
	sfml_cegui_keymap[sf::Keyboard::RSystem]		= CEGUI::Key::RightWindows;
	//sfml_cegui_keymap[sf::Keyboard::Menu]			= CEGUI::Key: --Dunno what this is
	sfml_cegui_keymap[sf::Keyboard::LBracket]		= CEGUI::Key::LeftBracket;
	sfml_cegui_keymap[sf::Keyboard::RBracket]		= CEGUI::Key::RightBracket;
	sfml_cegui_keymap[sf::Keyboard::SemiColon]		= CEGUI::Key::Semicolon;
	sfml_cegui_keymap[sf::Keyboard::Comma]			= CEGUI::Key::Comma;
	sfml_cegui_keymap[sf::Keyboard::Period]			= CEGUI::Key::Period;
	sfml_cegui_keymap[sf::Keyboard::Quote]			= CEGUI::Key::Apostrophe;
	sfml_cegui_keymap[sf::Keyboard::Slash]			= CEGUI::Key::Slash;
	sfml_cegui_keymap[sf::Keyboard::BackSlash]		= CEGUI::Key::Backslash;
	sfml_cegui_keymap[sf::Keyboard::Tilde]			= CEGUI::Key::Grave;
	sfml_cegui_keymap[sf::Keyboard::Equal]			= CEGUI::Key::Equals;
	sfml_cegui_keymap[sf::Keyboard::Dash]			= CEGUI::Key::Minus;
	sfml_cegui_keymap[sf::Keyboard::Space]			= CEGUI::Key::Space;
	sfml_cegui_keymap[sf::Keyboard::Return]			= CEGUI::Key::Return;
	sfml_cegui_keymap[sf::Keyboard::BackSpace]		= CEGUI::Key::Backspace;
	sfml_cegui_keymap[sf::Keyboard::Tab]			= CEGUI::Key::Tab;
	sfml_cegui_keymap[sf::Keyboard::PageUp]			= CEGUI::Key::PageUp;
	sfml_cegui_keymap[sf::Keyboard::PageDown]		= CEGUI::Key::PageDown;
	sfml_cegui_keymap[sf::Keyboard::End]			= CEGUI::Key::End;
	sfml_cegui_keymap[sf::Keyboard::Home]			= CEGUI::Key::Home;
	sfml_cegui_keymap[sf::Keyboard::Insert]			= CEGUI::Key::Insert;
	sfml_cegui_keymap[sf::Keyboard::Delete]			= CEGUI::Key::Delete;
	sfml_cegui_keymap[sf::Keyboard::Add]			= CEGUI::Key::Add;
	sfml_cegui_keymap[sf::Keyboard::Subtract]		= CEGUI::Key::Subtract;
	sfml_cegui_keymap[sf::Keyboard::Multiply]		= CEGUI::Key::Multiply;
	sfml_cegui_keymap[sf::Keyboard::Divide]			= CEGUI::Key::Divide;
	sfml_cegui_keymap[sf::Keyboard::Left]			= CEGUI::Key::ArrowLeft;
	sfml_cegui_keymap[sf::Keyboard::Right]			= CEGUI::Key::ArrowRight;
	sfml_cegui_keymap[sf::Keyboard::Up]			= CEGUI::Key::ArrowUp;
	sfml_cegui_keymap[sf::Keyboard::Down]			= CEGUI::Key::ArrowDown;
	sfml_cegui_keymap[sf::Keyboard::Numpad0] 		= CEGUI::Key::Numpad0;
	sfml_cegui_keymap[sf::Keyboard::Numpad1] 		= CEGUI::Key::Numpad1;
	sfml_cegui_keymap[sf::Keyboard::Numpad2] 		= CEGUI::Key::Numpad2;
	sfml_cegui_keymap[sf::Keyboard::Numpad3] 		= CEGUI::Key::Numpad3;
	sfml_cegui_keymap[sf::Keyboard::Numpad4] 		= CEGUI::Key::Numpad4;
	sfml_cegui_keymap[sf::Keyboard::Numpad5] 		= CEGUI::Key::Numpad5;
	sfml_cegui_keymap[sf::Keyboard::Numpad6] 		= CEGUI::Key::Numpad6;
	sfml_cegui_keymap[sf::Keyboard::Numpad7] 		= CEGUI::Key::Numpad7;
	sfml_cegui_keymap[sf::Keyboard::Numpad8] 		= CEGUI::Key::Numpad8;
	sfml_cegui_keymap[sf::Keyboard::Numpad9] 		= CEGUI::Key::Numpad9;
	sfml_cegui_keymap[sf::Keyboard::F1]			= CEGUI::Key::F1;
	sfml_cegui_keymap[sf::Keyboard::F2]			= CEGUI::Key::F2;
	sfml_cegui_keymap[sf::Keyboard::F3]			= CEGUI::Key::F3;
	sfml_cegui_keymap[sf::Keyboard::F4]			= CEGUI::Key::F4;
	sfml_cegui_keymap[sf::Keyboard::F5]			= CEGUI::Key::F5;
	sfml_cegui_keymap[sf::Keyboard::F6]			= CEGUI::Key::F6;
	sfml_cegui_keymap[sf::Keyboard::F7]			= CEGUI::Key::F7;
	sfml_cegui_keymap[sf::Keyboard::F8]			= CEGUI::Key::F8;
	sfml_cegui_keymap[sf::Keyboard::F9]			= CEGUI::Key::F9;
	sfml_cegui_keymap[sf::Keyboard::F10]			= CEGUI::Key::F10;
	sfml_cegui_keymap[sf::Keyboard::F11]			= CEGUI::Key::F11;
	sfml_cegui_keymap[sf::Keyboard::F12]			= CEGUI::Key::F12;
	sfml_cegui_keymap[sf::Keyboard::F13]			= CEGUI::Key::F13;
	sfml_cegui_keymap[sf::Keyboard::F14]			= CEGUI::Key::F14;
	sfml_cegui_keymap[sf::Keyboard::F15]			= CEGUI::Key::F15;
	sfml_cegui_keymap[sf::Keyboard::Pause]			= CEGUI::Key::Pause;
}

void Interface::mapSFMLMouseToCEGUI()
{
	sfml_cegui_mousemap[sf::Mouse::Left]			= CEGUI::LeftButton;
	sfml_cegui_mousemap[sf::Mouse::Right]			= CEGUI::RightButton;
	sfml_cegui_mousemap[sf::Mouse::Middle]			= CEGUI::MiddleButton;
	sfml_cegui_mousemap[sf::Mouse::XButton1]		= CEGUI::X1Button;
	sfml_cegui_mousemap[sf::Mouse::XButton2]		= CEGUI::X2Button;
}

} //namespace mui

} //namespace GEngine
<commit_msg>Fixed a namespace decleration in the interface module being in the wrong place and preventing compilation.<commit_after>/* Please refer to license.txt */

/*
 * Shamelessly taken from: http://www.cegui.org.uk/wiki/index.php/SFML_to_CEGUI_keytable :)
 * By the way, thanks a ton to whoever made that. SFML 0.8 documentation is severely lacking.
 */

#include "interface.hpp"

namespace GEngine
{

namespace mui
{

void Interface::mapSFMLKeysToCEGUI()
{
	sfml_cegui_keymap[sf::Keyboard::A]			= CEGUI::Key::A;
	sfml_cegui_keymap[sf::Keyboard::B]			= CEGUI::Key::B;
	sfml_cegui_keymap[sf::Keyboard::C]			= CEGUI::Key::C;
	sfml_cegui_keymap[sf::Keyboard::D]			= CEGUI::Key::D;
	sfml_cegui_keymap[sf::Keyboard::E]			= CEGUI::Key::E;
	sfml_cegui_keymap[sf::Keyboard::F]			= CEGUI::Key::F;
	sfml_cegui_keymap[sf::Keyboard::G]			= CEGUI::Key::G;
	sfml_cegui_keymap[sf::Keyboard::H]			= CEGUI::Key::H;
	sfml_cegui_keymap[sf::Keyboard::I]			= CEGUI::Key::I;
	sfml_cegui_keymap[sf::Keyboard::J]			= CEGUI::Key::J;
	sfml_cegui_keymap[sf::Keyboard::K]			= CEGUI::Key::K;
	sfml_cegui_keymap[sf::Keyboard::L]			= CEGUI::Key::L;
	sfml_cegui_keymap[sf::Keyboard::M]			= CEGUI::Key::M;
	sfml_cegui_keymap[sf::Keyboard::N]			= CEGUI::Key::N;
	sfml_cegui_keymap[sf::Keyboard::O]			= CEGUI::Key::O;
	sfml_cegui_keymap[sf::Keyboard::P]			= CEGUI::Key::P;
	sfml_cegui_keymap[sf::Keyboard::Q]			= CEGUI::Key::Q;
	sfml_cegui_keymap[sf::Keyboard::R]			= CEGUI::Key::R;
	sfml_cegui_keymap[sf::Keyboard::S]			= CEGUI::Key::S;
	sfml_cegui_keymap[sf::Keyboard::T]			= CEGUI::Key::T;
	sfml_cegui_keymap[sf::Keyboard::U]			= CEGUI::Key::U;
	sfml_cegui_keymap[sf::Keyboard::V]			= CEGUI::Key::V;
	sfml_cegui_keymap[sf::Keyboard::W]			= CEGUI::Key::W;
	sfml_cegui_keymap[sf::Keyboard::X]			= CEGUI::Key::X;
	sfml_cegui_keymap[sf::Keyboard::Y]			= CEGUI::Key::Y;
	sfml_cegui_keymap[sf::Keyboard::Z]			= CEGUI::Key::Z;
	sfml_cegui_keymap[sf::Keyboard::Num0]			= CEGUI::Key::Zero;
	sfml_cegui_keymap[sf::Keyboard::Num1]			= CEGUI::Key::One;
	sfml_cegui_keymap[sf::Keyboard::Num2]			= CEGUI::Key::Two;
	sfml_cegui_keymap[sf::Keyboard::Num3]			= CEGUI::Key::Three;
	sfml_cegui_keymap[sf::Keyboard::Num4]			= CEGUI::Key::Four;
	sfml_cegui_keymap[sf::Keyboard::Num5]			= CEGUI::Key::Five;
	sfml_cegui_keymap[sf::Keyboard::Num6]			= CEGUI::Key::Six;
	sfml_cegui_keymap[sf::Keyboard::Num7]			= CEGUI::Key::Seven;
	sfml_cegui_keymap[sf::Keyboard::Num8]			= CEGUI::Key::Eight;
	sfml_cegui_keymap[sf::Keyboard::Num9]			= CEGUI::Key::Nine;
	sfml_cegui_keymap[sf::Keyboard::Escape]			= CEGUI::Key::Escape;
	sfml_cegui_keymap[sf::Keyboard::LControl]		= CEGUI::Key::LeftControl;
	sfml_cegui_keymap[sf::Keyboard::LShift]			= CEGUI::Key::LeftShift;
	sfml_cegui_keymap[sf::Keyboard::LAlt]			= CEGUI::Key::LeftAlt;
	sfml_cegui_keymap[sf::Keyboard::LSystem]		= CEGUI::Key::LeftWindows;
	sfml_cegui_keymap[sf::Keyboard::RControl]		= CEGUI::Key::RightControl;
	sfml_cegui_keymap[sf::Keyboard::RShift]			= CEGUI::Key::RightShift;
	sfml_cegui_keymap[sf::Keyboard::RAlt]			= CEGUI::Key::RightAlt;
	sfml_cegui_keymap[sf::Keyboard::RSystem]		= CEGUI::Key::RightWindows;
	//sfml_cegui_keymap[sf::Keyboard::Menu]			= CEGUI::Key: --Dunno what this is
	sfml_cegui_keymap[sf::Keyboard::LBracket]		= CEGUI::Key::LeftBracket;
	sfml_cegui_keymap[sf::Keyboard::RBracket]		= CEGUI::Key::RightBracket;
	sfml_cegui_keymap[sf::Keyboard::SemiColon]		= CEGUI::Key::Semicolon;
	sfml_cegui_keymap[sf::Keyboard::Comma]			= CEGUI::Key::Comma;
	sfml_cegui_keymap[sf::Keyboard::Period]			= CEGUI::Key::Period;
	sfml_cegui_keymap[sf::Keyboard::Quote]			= CEGUI::Key::Apostrophe;
	sfml_cegui_keymap[sf::Keyboard::Slash]			= CEGUI::Key::Slash;
	sfml_cegui_keymap[sf::Keyboard::BackSlash]		= CEGUI::Key::Backslash;
	sfml_cegui_keymap[sf::Keyboard::Tilde]			= CEGUI::Key::Grave;
	sfml_cegui_keymap[sf::Keyboard::Equal]			= CEGUI::Key::Equals;
	sfml_cegui_keymap[sf::Keyboard::Dash]			= CEGUI::Key::Minus;
	sfml_cegui_keymap[sf::Keyboard::Space]			= CEGUI::Key::Space;
	sfml_cegui_keymap[sf::Keyboard::Return]			= CEGUI::Key::Return;
	sfml_cegui_keymap[sf::Keyboard::BackSpace]		= CEGUI::Key::Backspace;
	sfml_cegui_keymap[sf::Keyboard::Tab]			= CEGUI::Key::Tab;
	sfml_cegui_keymap[sf::Keyboard::PageUp]			= CEGUI::Key::PageUp;
	sfml_cegui_keymap[sf::Keyboard::PageDown]		= CEGUI::Key::PageDown;
	sfml_cegui_keymap[sf::Keyboard::End]			= CEGUI::Key::End;
	sfml_cegui_keymap[sf::Keyboard::Home]			= CEGUI::Key::Home;
	sfml_cegui_keymap[sf::Keyboard::Insert]			= CEGUI::Key::Insert;
	sfml_cegui_keymap[sf::Keyboard::Delete]			= CEGUI::Key::Delete;
	sfml_cegui_keymap[sf::Keyboard::Add]			= CEGUI::Key::Add;
	sfml_cegui_keymap[sf::Keyboard::Subtract]		= CEGUI::Key::Subtract;
	sfml_cegui_keymap[sf::Keyboard::Multiply]		= CEGUI::Key::Multiply;
	sfml_cegui_keymap[sf::Keyboard::Divide]			= CEGUI::Key::Divide;
	sfml_cegui_keymap[sf::Keyboard::Left]			= CEGUI::Key::ArrowLeft;
	sfml_cegui_keymap[sf::Keyboard::Right]			= CEGUI::Key::ArrowRight;
	sfml_cegui_keymap[sf::Keyboard::Up]			= CEGUI::Key::ArrowUp;
	sfml_cegui_keymap[sf::Keyboard::Down]			= CEGUI::Key::ArrowDown;
	sfml_cegui_keymap[sf::Keyboard::Numpad0] 		= CEGUI::Key::Numpad0;
	sfml_cegui_keymap[sf::Keyboard::Numpad1] 		= CEGUI::Key::Numpad1;
	sfml_cegui_keymap[sf::Keyboard::Numpad2] 		= CEGUI::Key::Numpad2;
	sfml_cegui_keymap[sf::Keyboard::Numpad3] 		= CEGUI::Key::Numpad3;
	sfml_cegui_keymap[sf::Keyboard::Numpad4] 		= CEGUI::Key::Numpad4;
	sfml_cegui_keymap[sf::Keyboard::Numpad5] 		= CEGUI::Key::Numpad5;
	sfml_cegui_keymap[sf::Keyboard::Numpad6] 		= CEGUI::Key::Numpad6;
	sfml_cegui_keymap[sf::Keyboard::Numpad7] 		= CEGUI::Key::Numpad7;
	sfml_cegui_keymap[sf::Keyboard::Numpad8] 		= CEGUI::Key::Numpad8;
	sfml_cegui_keymap[sf::Keyboard::Numpad9] 		= CEGUI::Key::Numpad9;
	sfml_cegui_keymap[sf::Keyboard::F1]			= CEGUI::Key::F1;
	sfml_cegui_keymap[sf::Keyboard::F2]			= CEGUI::Key::F2;
	sfml_cegui_keymap[sf::Keyboard::F3]			= CEGUI::Key::F3;
	sfml_cegui_keymap[sf::Keyboard::F4]			= CEGUI::Key::F4;
	sfml_cegui_keymap[sf::Keyboard::F5]			= CEGUI::Key::F5;
	sfml_cegui_keymap[sf::Keyboard::F6]			= CEGUI::Key::F6;
	sfml_cegui_keymap[sf::Keyboard::F7]			= CEGUI::Key::F7;
	sfml_cegui_keymap[sf::Keyboard::F8]			= CEGUI::Key::F8;
	sfml_cegui_keymap[sf::Keyboard::F9]			= CEGUI::Key::F9;
	sfml_cegui_keymap[sf::Keyboard::F10]			= CEGUI::Key::F10;
	sfml_cegui_keymap[sf::Keyboard::F11]			= CEGUI::Key::F11;
	sfml_cegui_keymap[sf::Keyboard::F12]			= CEGUI::Key::F12;
	sfml_cegui_keymap[sf::Keyboard::F13]			= CEGUI::Key::F13;
	sfml_cegui_keymap[sf::Keyboard::F14]			= CEGUI::Key::F14;
	sfml_cegui_keymap[sf::Keyboard::F15]			= CEGUI::Key::F15;
	sfml_cegui_keymap[sf::Keyboard::Pause]			= CEGUI::Key::Pause;
}

void Interface::mapSFMLMouseToCEGUI()
{
	sfml_cegui_mousemap[sf::Mouse::Left]			= CEGUI::LeftButton;
	sfml_cegui_mousemap[sf::Mouse::Right]			= CEGUI::RightButton;
	sfml_cegui_mousemap[sf::Mouse::Middle]			= CEGUI::MiddleButton;
	sfml_cegui_mousemap[sf::Mouse::XButton1]		= CEGUI::X1Button;
	sfml_cegui_mousemap[sf::Mouse::XButton2]		= CEGUI::X2Button;
}

} //namespace mui

} //namespace GEngine
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <stout/check.hpp>

#include "internal/devolve.hpp"

using std::string;

using google::protobuf::RepeatedPtrField;

namespace mesos {
namespace internal {

template <typename T>
static T devolve(const google::protobuf::Message& message)
{
  T t;

  string data;

  // NOTE: We need to use 'SerializePartialToString' instead of
  // 'SerializeToString' because some required fields might not be set
  // and we don't want an exception to get thrown.
  CHECK(message.SerializePartialToString(&data))
    << "Failed to serialize " << message.GetTypeName()
    << " while devolving to " << t.GetTypeName();

  // NOTE: We need to use 'ParsePartialFromString' instead of
  // 'ParseFromString' because some required fields might not
  // be set and we don't want an exception to get thrown.
  CHECK(t.ParsePartialFromString(data))
    << "Failed to parse " << t.GetTypeName()
    << " while devolving from " << message.GetTypeName();

  return t;
}

CommandInfo devolve(const v1::CommandInfo& command)
{
  return devolve<CommandInfo>(command);
}

ContainerID devolve(const v1::ContainerID& containerId)
{
  return devolve<ContainerID>(containerId);
}

Credential devolve(const v1::Credential& credential)
{
  return devolve<Credential>(credential);
}

ExecutorID devolve(const v1::ExecutorID& executorId)
{
  return devolve<ExecutorID>(executorId);
}

FrameworkID devolve(const v1::FrameworkID& frameworkId)
{
  return devolve<FrameworkID>(frameworkId);
}

FrameworkInfo devolve(const v1::FrameworkInfo& frameworkInfo)
{
  return devolve<FrameworkInfo>(frameworkInfo);
}

HealthCheck devolve(const v1::HealthCheck& check)
{
  return devolve<HealthCheck>(check);
}

InverseOffer devolve(const v1::InverseOffer& inverseOffer)
{
  return devolve<InverseOffer>(inverseOffer);
}

Offer devolve(const v1::Offer& offer)
{
  return devolve<Offer>(offer);
}

OperationStatus devolve(const v1::OperationStatus& status)
{
  return devolve<OperationStatus>(status);
}

Resource devolve(const v1::Resource& resource)
{
  return devolve<Resource>(resource);
}

ResourceProviderID devolve(const v1::ResourceProviderID& resourceProviderId)
{
  // NOTE: We do not use the common 'devolve' call for performance.
  ResourceProviderID id;
  id.set_value(resourceProviderId.value());
  return id;
}

Resources devolve(const v1::Resources& resources)
{
  return devolve<Resource>(
      static_cast<const RepeatedPtrField<v1::Resource>&>(resources));
}

SlaveID devolve(const v1::AgentID& agentId)
{
  // NOTE: Not using 'devolve<v1::AgentID, SlaveID>(agentId)' since
  // this will be a common 'devolve' call and we wanted to speed up
  // performance.

  SlaveID id;
  id.set_value(agentId.value());
  return id;
}

SlaveInfo devolve(const v1::AgentInfo& agentInfo)
{
  SlaveInfo info = devolve<SlaveInfo>(agentInfo);

  // We set 'checkpoint' to 'true' since the v1::AgentInfo doesn't
  // have 'checkpoint' but all "agents" were checkpointing by default
  // when v1::AgentInfo was introduced. See MESOS-2317.
  info.set_checkpoint(true);

  return info;
}

TaskID devolve(const v1::TaskID& taskId)
{
  return devolve<TaskID>(taskId);
}

TaskStatus devolve(const v1::TaskStatus& status)
{
  return devolve<TaskStatus>(status);
}

executor::Call devolve(const v1::executor::Call& call)
{
  return devolve<executor::Call>(call);
}

executor::Event devolve(const v1::executor::Event& event)
{
  return devolve<executor::Event>(event);
}

mesos::resource_provider::Call devolve(const v1::resource_provider::Call& call)
{
  return devolve<mesos::resource_provider::Call>(call);
}

mesos::resource_provider::Event devolve(
    const v1::resource_provider::Event& event)
{
  return devolve<mesos::resource_provider::Event>(event);
}

scheduler::Call devolve(const v1::scheduler::Call& call)
{
  scheduler::Call _call = devolve<scheduler::Call>(call);

  // Certain conversions require special handling.
  if (_call.type() == scheduler::Call::SUBSCRIBE) {
    // v1 Subscribe.suppressed_roles cannot be automatically converted
    // because its tag is used by another field in the internal Subscribe.
    *(_call.mutable_subscribe()->mutable_suppressed_roles()) =
      call.subscribe().suppressed_roles();
  }

  return _call;
}

scheduler::Event devolve(const v1::scheduler::Event& event)
{
  return devolve<scheduler::Event>(event);
}

mesos::agent::Call devolve(const v1::agent::Call& call)
{
  return devolve<mesos::agent::Call>(call);
}

mesos::master::Call devolve(const v1::master::Call& call)
{
  return devolve<mesos::master::Call>(call);
}

} // namespace internal {
} // namespace mesos {
<commit_msg>Made devolving `v1::scheduler::Call::SUBSCRIBE` more robust.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <stout/check.hpp>

#include "internal/devolve.hpp"

using std::string;

using google::protobuf::RepeatedPtrField;

namespace mesos {
namespace internal {

template <typename T>
static T devolve(const google::protobuf::Message& message)
{
  T t;

  string data;

  // NOTE: We need to use 'SerializePartialToString' instead of
  // 'SerializeToString' because some required fields might not be set
  // and we don't want an exception to get thrown.
  CHECK(message.SerializePartialToString(&data))
    << "Failed to serialize " << message.GetTypeName()
    << " while devolving to " << t.GetTypeName();

  // NOTE: We need to use 'ParsePartialFromString' instead of
  // 'ParseFromString' because some required fields might not
  // be set and we don't want an exception to get thrown.
  CHECK(t.ParsePartialFromString(data))
    << "Failed to parse " << t.GetTypeName()
    << " while devolving from " << message.GetTypeName();

  return t;
}

CommandInfo devolve(const v1::CommandInfo& command)
{
  return devolve<CommandInfo>(command);
}

ContainerID devolve(const v1::ContainerID& containerId)
{
  return devolve<ContainerID>(containerId);
}

Credential devolve(const v1::Credential& credential)
{
  return devolve<Credential>(credential);
}

ExecutorID devolve(const v1::ExecutorID& executorId)
{
  return devolve<ExecutorID>(executorId);
}

FrameworkID devolve(const v1::FrameworkID& frameworkId)
{
  return devolve<FrameworkID>(frameworkId);
}

FrameworkInfo devolve(const v1::FrameworkInfo& frameworkInfo)
{
  return devolve<FrameworkInfo>(frameworkInfo);
}

HealthCheck devolve(const v1::HealthCheck& check)
{
  return devolve<HealthCheck>(check);
}

InverseOffer devolve(const v1::InverseOffer& inverseOffer)
{
  return devolve<InverseOffer>(inverseOffer);
}

Offer devolve(const v1::Offer& offer)
{
  return devolve<Offer>(offer);
}

OperationStatus devolve(const v1::OperationStatus& status)
{
  return devolve<OperationStatus>(status);
}

Resource devolve(const v1::Resource& resource)
{
  return devolve<Resource>(resource);
}

ResourceProviderID devolve(const v1::ResourceProviderID& resourceProviderId)
{
  // NOTE: We do not use the common 'devolve' call for performance.
  ResourceProviderID id;
  id.set_value(resourceProviderId.value());
  return id;
}

Resources devolve(const v1::Resources& resources)
{
  return devolve<Resource>(
      static_cast<const RepeatedPtrField<v1::Resource>&>(resources));
}

SlaveID devolve(const v1::AgentID& agentId)
{
  // NOTE: Not using 'devolve<v1::AgentID, SlaveID>(agentId)' since
  // this will be a common 'devolve' call and we wanted to speed up
  // performance.

  SlaveID id;
  id.set_value(agentId.value());
  return id;
}

SlaveInfo devolve(const v1::AgentInfo& agentInfo)
{
  SlaveInfo info = devolve<SlaveInfo>(agentInfo);

  // We set 'checkpoint' to 'true' since the v1::AgentInfo doesn't
  // have 'checkpoint' but all "agents" were checkpointing by default
  // when v1::AgentInfo was introduced. See MESOS-2317.
  info.set_checkpoint(true);

  return info;
}

TaskID devolve(const v1::TaskID& taskId)
{
  return devolve<TaskID>(taskId);
}

TaskStatus devolve(const v1::TaskStatus& status)
{
  return devolve<TaskStatus>(status);
}

executor::Call devolve(const v1::executor::Call& call)
{
  return devolve<executor::Call>(call);
}

executor::Event devolve(const v1::executor::Event& event)
{
  return devolve<executor::Event>(event);
}

mesos::resource_provider::Call devolve(const v1::resource_provider::Call& call)
{
  return devolve<mesos::resource_provider::Call>(call);
}

mesos::resource_provider::Event devolve(
    const v1::resource_provider::Event& event)
{
  return devolve<mesos::resource_provider::Event>(event);
}

scheduler::Call devolve(const v1::scheduler::Call& call)
{
  scheduler::Call _call = devolve<scheduler::Call>(call);

  // Certain conversions require special handling.
  if (call.type() == v1::scheduler::Call::SUBSCRIBE &&
      call.has_subscribe()) {
    // v1 Subscribe.suppressed_roles cannot be automatically converted
    // because its tag is used by another field in the internal Subscribe.
    *(_call.mutable_subscribe()->mutable_suppressed_roles()) =
      call.subscribe().suppressed_roles();
  }

  return _call;
}

scheduler::Event devolve(const v1::scheduler::Event& event)
{
  return devolve<scheduler::Event>(event);
}

mesos::agent::Call devolve(const v1::agent::Call& call)
{
  return devolve<mesos::agent::Call>(call);
}

mesos::master::Call devolve(const v1::master::Call& call)
{
  return devolve<mesos::master::Call>(call);
}

} // namespace internal {
} // namespace mesos {
<|endoftext|>


<commit_before>/*
Copyright (C) 2007 <SWGEmu>

This File is part of Core3.

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/

#include "ServerCore.h"

#include "db/ServerDatabase.h"
#include "db/ForumsDatabase.h"

#include "chat/ChatManager.h"

#include "login/LoginServer.h"

#include "features/Features.h"

#include "ping/PingServer.h"

//#include "status/StatusServer.h"

#include "zone/ZoneServer.h"

#include "zone/managers/object/ObjectManager.h"

#include "zone/objects/creature/CreatureObject.h"

class TestManager : public ThreadLocal<ZoneServer> {
public:
	ZoneServer* initValue() {
		return new ZoneServer(0, 0);
	}
};

ManagedReference<ZoneServer*> ServerCore::zoneServerRef = NULL;

ServerCore::ServerCore() : Core("log/core3.log"), Logger("Core") {
	orb = NULL;

	loginServer = NULL;
	zoneServerRef = NULL;
	//statusServer = NULL;
	pingServer = NULL;
	forumDatabase = NULL;
	database = NULL;

	configManager = ConfigManager::instance();

	features = NULL;
}

void ServerCore::init() {
	info("starting up server..");

	processConfig();

	try {
		database = new ServerDatabase(configManager);

		if (configManager->getUseVBIngeration() == 1)
			forumDatabase = new ForumsDatabase(configManager);

		String& orbaddr = configManager->getORBNamingDirectoryAddress();
		orb = DistributedObjectBroker::initialize(orbaddr, 44434);

		orb->setCustomObjectManager(ObjectManager::instance());

		if (configManager->getMakeLogin()) {
			loginServer = new LoginServer(configManager);
		}

		if (configManager->getMakeZone()) {
			ZoneServer* zoneServer = new ZoneServer(configManager->getZoneProcessingThreads(), configManager->getZoneGalaxyID());
			zoneServer->deploy("ZoneServer");

			zoneServerRef = zoneServer;
		}

		if (configManager->getMakePing()) {
			pingServer = new PingServer();
		}
	} catch (ServiceException& e) {
		shutdown();
	} catch (DatabaseException& e) {
		info(e.getMessage());

		exit(1);
	}
}

void ServerCore::run() {
	ZoneServer* zoneServer = zoneServerRef.get();

	if (loginServer != NULL) {
		int loginPort = configManager->getLoginPort();
		int loginAllowedConnections = configManager->getLoginAllowedConnections();

		loginServer->start(loginPort, loginAllowedConnections);
	}

	if (zoneServer != NULL) {
		int zoneAllowedConnections = configManager->getZoneAllowedConnections();

		ObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance();
		dbManager->loadDatabases();

		zoneServer->start(44463, zoneAllowedConnections);
	}

	/*if (statusServer != NULL) {
		int statusPort = configManager->getStatusPort();
		int statusAllowedConnections = configManager->getStatusAllowedConnections();

		statusServer->start(statusPort);
	}*/

	if (pingServer != NULL) {
		int pingPort = configManager->getPingPort();
		int pingAllowedConnections = configManager->getPingAllowedConnections();

		pingServer->start(pingPort, pingAllowedConnections);
	}

	Core::initialize();

	info("initialized", true);

	handleCommands();

	shutdown();
}

void ServerCore::shutdown() {
	info("shutting down server..");

	/*if (statusServer != NULL) {
		statusServer->stop();

		delete statusServer;
		statusServer = NULL;
	}*/

	ZoneServer* zoneServer = zoneServerRef.getForUpdate();

	if (zoneServer != NULL) {
		zoneServer->stop();
		zoneServer->finalize();

		zoneServer = NULL;
	}

	if (loginServer != NULL) {
		loginServer->stop();

		delete loginServer;
		loginServer = NULL;
	}

	if (pingServer != NULL) {
		pingServer->stop();

		delete pingServer;
		pingServer = NULL;
	}

	if (forumDatabase != NULL) {
		delete forumDatabase;
		forumDatabase = NULL;
	}

	if (features != NULL) {
		delete features;
		features = NULL;
	}

	if (database != NULL) {
		delete database;
		database = NULL;
	}

	ObjectManager::instance()->savePersistentObjects();

	ObjectManager::finalize();

	DistributedObjectBroker::finalize();

	info("server closed");

	//exit(1);
}

void ServerCore::handleCommands() {
	while (true) {
		try {
			String command;

			Thread::sleep(500);

			System::out << "> ";

			char line[256];
			fgets(line, sizeof(line), stdin);

			command = line;
			command = command.replaceFirst("\n", "");

			ZoneServer* zoneServer = zoneServerRef.get();

			if (command == "exit") {
				if (zoneServer != NULL) {
					ChatManager* chatManager = zoneServer->getChatManager();
					chatManager->broadcastGalaxy(NULL, "Server is shutting down NOW!");
				}

				return;
			} else if (command == "dumpmem") {
				#ifdef DEBUG_MEMORY
					DumpUnfreed(TRUE);
				#endif
			} else if (command == "logQuadTree") {
				QuadTree::setLogging(!QuadTree::doLog());
			} else if (command == "info") {
				//TaskManager::instance()->printInfo();

				if (loginServer != NULL)
					loginServer->printInfo();

				if (zoneServer != NULL)
					zoneServer->printInfo(true);

				if (pingServer != NULL)
					pingServer->printInfo();
			} else if (command == "lock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateLocked();
			} else if (command == "unlock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateOnline();
			} else if (command == "icap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(50);
			} else if (command == "dcap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(-50);
			} else if (command == "fixQueue") {
				if (zoneServer != NULL)
					zoneServer->fixScheduler();
			} else if (command == "crash") {
				zoneServer = NULL;

				zoneServer->fixScheduler();
			} else if (command == "help") {
				System::out << "available commands:\n";
				System::out << "\texit, logQuadTree, info, icap, dcap, fixQueue, crash, about.\n";
			} else if (command == "about") {
				System::out << "Core3 Uber Edition. Ultyma pwns you.\n";
			} else
				System::out << "unknown command (" << command << ")\n";
		} catch (SocketException& e) {
			System::out << "[ServerCore] " << e.getMessage();
		} catch (ArrayIndexOutOfBoundsException& e) {
			System::out << "[ServerCore] " << e.getMessage() << "\n";
		} catch (...) {
			System::out << "[ServerCore] unreported Exception caught\n";
		}
	}
}

void ServerCore::processConfig() {
	if (!configManager->loadConfigData())
		info("missing config file.. loading default values\n");

	//if (!features->loadFeatures())
		//info("Problem occurred trying to load features.lua");
}
<commit_msg>[Fixed] Compile issue in ServerCore.cpp<commit_after>/*
Copyright (C) 2007 <SWGEmu>

This File is part of Core3.

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/

#include "ServerCore.h"

#include "db/ServerDatabase.h"
#include "db/ForumsDatabase.h"

#include "chat/ChatManager.h"

#include "login/LoginServer.h"

#include "features/Features.h"

#include "ping/PingServer.h"

//#include "status/StatusServer.h"

#include "zone/ZoneServer.h"

#include "zone/managers/object/ObjectManager.h"

#include "zone/objects/creature/CreatureObject.h"

class TestManager : public ThreadLocal<ZoneServer> {
public:
	ZoneServer* initValue() {
		return new ZoneServer(0, 0);
	}
};

ManagedReference<ZoneServer*> ServerCore::zoneServerRef = NULL;

ServerCore::ServerCore() : Core("log/core3.log"), Logger("Core") {
	orb = NULL;

	loginServer = NULL;
	zoneServerRef = NULL;
	//statusServer = NULL;
	pingServer = NULL;
	forumDatabase = NULL;
	database = NULL;

	configManager = ConfigManager::instance();

	features = NULL;
}

void ServerCore::init() {
	info("starting up server..");

	processConfig();

	try {
		database = new ServerDatabase(configManager);

		if (configManager->getUseVBIngeration() == 1)
			forumDatabase = new ForumsDatabase(configManager);

		String& orbaddr = configManager->getORBNamingDirectoryAddress();
		orb = DistributedObjectBroker::initialize(orbaddr, 44434);

		orb->setCustomObjectManager(ObjectManager::instance());

		if (configManager->getMakeLogin()) {
			loginServer = new LoginServer(configManager);
		}

		if (configManager->getMakeZone()) {
			ZoneServer* zoneServer = new ZoneServer(configManager->getZoneProcessingThreads(), configManager->getZoneGalaxyID());
			zoneServer->deploy("ZoneServer");

			zoneServerRef = zoneServer;
		}

		if (configManager->getMakePing()) {
			pingServer = new PingServer();
		}
	} catch (ServiceException& e) {
		shutdown();
	} catch (DatabaseException& e) {
		info(e.getMessage());

		exit(1);
	}
}

void ServerCore::run() {
	ZoneServer* zoneServer = zoneServerRef.get();

	if (loginServer != NULL) {
		int loginPort = configManager->getLoginPort();
		int loginAllowedConnections = configManager->getLoginAllowedConnections();

		loginServer->start(loginPort, loginAllowedConnections);
	}

	if (zoneServer != NULL) {
		int zoneAllowedConnections = configManager->getZoneAllowedConnections();

		ObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance();
		dbManager->loadDatabases();

		zoneServer->start(44463, zoneAllowedConnections);
	}

	/*if (statusServer != NULL) {
		int statusPort = configManager->getStatusPort();
		int statusAllowedConnections = configManager->getStatusAllowedConnections();

		statusServer->start(statusPort);
	}*/

	if (pingServer != NULL) {
		int pingPort = configManager->getPingPort();
		int pingAllowedConnections = configManager->getPingAllowedConnections();

		pingServer->start(pingPort, pingAllowedConnections);
	}

	Core::initialize();

	info("initialized", true);

	handleCommands();

	shutdown();
}

void ServerCore::shutdown() {
	info("shutting down server..");

	/*if (statusServer != NULL) {
		statusServer->stop();

		delete statusServer;
		statusServer = NULL;
	}*/

	ZoneServer* zoneServer = zoneServerRef.get();

	if (zoneServer != NULL) {
		zoneServer->stop();
		zoneServer->finalize();

		zoneServer = NULL;
	}

	if (loginServer != NULL) {
		loginServer->stop();

		delete loginServer;
		loginServer = NULL;
	}

	if (pingServer != NULL) {
		pingServer->stop();

		delete pingServer;
		pingServer = NULL;
	}

	if (forumDatabase != NULL) {
		delete forumDatabase;
		forumDatabase = NULL;
	}

	if (features != NULL) {
		delete features;
		features = NULL;
	}

	if (database != NULL) {
		delete database;
		database = NULL;
	}

	ObjectManager::instance()->savePersistentObjects();

	ObjectManager::finalize();

	DistributedObjectBroker::finalize();

	info("server closed");

	//exit(1);
}

void ServerCore::handleCommands() {
	while (true) {
		try {
			String command;

			Thread::sleep(500);

			System::out << "> ";

			char line[256];
			fgets(line, sizeof(line), stdin);

			command = line;
			command = command.replaceFirst("\n", "");

			ZoneServer* zoneServer = zoneServerRef.get();

			if (command == "exit") {
				if (zoneServer != NULL) {
					ChatManager* chatManager = zoneServer->getChatManager();
					chatManager->broadcastGalaxy(NULL, "Server is shutting down NOW!");
				}

				return;
			} else if (command == "dumpmem") {
				#ifdef DEBUG_MEMORY
					DumpUnfreed(TRUE);
				#endif
			} else if (command == "logQuadTree") {
				QuadTree::setLogging(!QuadTree::doLog());
			} else if (command == "info") {
				//TaskManager::instance()->printInfo();

				if (loginServer != NULL)
					loginServer->printInfo();

				if (zoneServer != NULL)
					zoneServer->printInfo(true);

				if (pingServer != NULL)
					pingServer->printInfo();
			} else if (command == "lock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateLocked();
			} else if (command == "unlock") {
				if (zoneServer != NULL)
					zoneServer->setServerStateOnline();
			} else if (command == "icap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(50);
			} else if (command == "dcap") {
				if (zoneServer != NULL)
					zoneServer->changeUserCap(-50);
			} else if (command == "fixQueue") {
				if (zoneServer != NULL)
					zoneServer->fixScheduler();
			} else if (command == "crash") {
				zoneServer = NULL;

				zoneServer->fixScheduler();
			} else if (command == "help") {
				System::out << "available commands:\n";
				System::out << "\texit, logQuadTree, info, icap, dcap, fixQueue, crash, about.\n";
			} else if (command == "about") {
				System::out << "Core3 Uber Edition. Ultyma pwns you.\n";
			} else
				System::out << "unknown command (" << command << ")\n";
		} catch (SocketException& e) {
			System::out << "[ServerCore] " << e.getMessage();
		} catch (ArrayIndexOutOfBoundsException& e) {
			System::out << "[ServerCore] " << e.getMessage() << "\n";
		} catch (...) {
			System::out << "[ServerCore] unreported Exception caught\n";
		}
	}
}

void ServerCore::processConfig() {
	if (!configManager->loadConfigData())
		info("missing config file.. loading default values\n");

	//if (!features->loadFeatures())
		//info("Problem occurred trying to load features.lua");
}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     pluginmanager.cpp
 * @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
 *           Lorenz Esch <lesch@mgh.harvard.edu>;
 *           Lars Debor <Lars.Debor@tu-ilmenau.de>;
 *           Simon Heinke <Simon.Heinke@tu-ilmenau.de>
 * @since    0.1.0
 * @date     February, 2017
 *
 * @section  LICENSE
 *
Copyright (C) 2017, Christoph Dinh, Lars Debor, Simon Heinke and Matti Hamalainen. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief    Definition of the PluginManager class.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "pluginmanager.h"
#include "../Plugins/abstractplugin.h"
#include "communicator.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDir>
#include <QDebug>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace ANSHAREDLIB;

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

PluginManager::PluginManager(QObject *parent)
: QPluginLoader(parent)
{

}

//=============================================================================================================

PluginManager::~PluginManager()
{
    for(AbstractPlugin* plugin : m_qVecPlugins)
    {
        delete plugin;
    }
}

//=============================================================================================================

void PluginManager::loadPluginsFromDirectory(const QString& dir)
{
#ifdef STATICBUILD
    Q_UNUSED(dir);

    const auto staticInstances = QPluginLoader::staticInstances();
    for(QObject *plugin : staticInstances) {
        // AbstractPlugin
        if(AbstractPlugin* pPlugin = qobject_cast<AbstractPlugin*>(plugin)) {
            m_qVecPlugins.push_back(qobject_cast<AbstractPlugin*>(pPlugin));
        }
    }
#else
    QDir pluginsDir(dir);

    foreach(const QString &file, pluginsDir.entryList(QDir::Files)) {
        // Exclude .exp and .lib files (only relevant for windows builds)
        if(!file.contains(".exp") && !file.contains(".lib")) {
            this->setFileName(pluginsDir.absoluteFilePath(file));
            QObject *pPlugin = this->instance();

            // AbstractPlugin
            if(pPlugin) {
                qDebug() << "[PluginManager::loadPlugin] Loading Plugin" << file.toUtf8().constData() << "succeeded.";
                m_qVecPlugins.push_back(qobject_cast<AbstractPlugin*>(pPlugin));
            } else {
                qDebug() << "[PluginManager::loadPlugin] Loading Plugin" << file.toUtf8().constData() << "failed.";
            }
        }
    }
#endif
}

//=============================================================================================================

void PluginManager::initPlugins(QSharedPointer<AnalyzeData> data)
{
    for(AbstractPlugin* plugin : m_qVecPlugins)
    {
        plugin->setGlobalData(data);
        plugin->init();
    }

    // tell everyone that INIT-phase is finished
    Communicator con;
    con.publishEvent(EVENT_TYPE::PLUGIN_INIT_FINISHED);
}

//=============================================================================================================

int PluginManager::findByName(const QString& name)
{
    QVector<AbstractPlugin*>::const_iterator it = m_qVecPlugins.begin();
    for(int i = 0; it != m_qVecPlugins.end(); ++i, ++it)
        if((*it)->getName() == name)
            return i;

    return -1;
}

//=============================================================================================================

void PluginManager::shutdown()
{
    for(AbstractPlugin* plugin : m_qVecPlugins)
    {
        plugin->unload();
    }
}
<commit_msg>use constant iterators<commit_after>//=============================================================================================================
/**
 * @file     pluginmanager.cpp
 * @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
 *           Lorenz Esch <lesch@mgh.harvard.edu>;
 *           Lars Debor <Lars.Debor@tu-ilmenau.de>;
 *           Simon Heinke <Simon.Heinke@tu-ilmenau.de>
 * @since    0.1.0
 * @date     February, 2017
 *
 * @section  LICENSE
 *
Copyright (C) 2017, Christoph Dinh, Lars Debor, Simon Heinke and Matti Hamalainen. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief    Definition of the PluginManager class.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "pluginmanager.h"
#include "../Plugins/abstractplugin.h"
#include "communicator.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDir>
#include <QDebug>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace ANSHAREDLIB;

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

PluginManager::PluginManager(QObject *parent)
: QPluginLoader(parent)
{

}

//=============================================================================================================

PluginManager::~PluginManager()
{
    for(AbstractPlugin* plugin : m_qVecPlugins)
    {
        delete plugin;
    }
}

//=============================================================================================================

void PluginManager::loadPluginsFromDirectory(const QString& dir)
{
#ifdef STATICBUILD
    Q_UNUSED(dir);

    const auto staticInstances = QPluginLoader::staticInstances();
    for(QObject *plugin : staticInstances) {
        // AbstractPlugin
        if(AbstractPlugin* pPlugin = qobject_cast<AbstractPlugin*>(plugin)) {
            m_qVecPlugins.push_back(qobject_cast<AbstractPlugin*>(pPlugin));
        }
    }
#else
    QDir pluginsDir(dir);

    foreach(const QString &file, pluginsDir.entryList(QDir::Files)) {
        // Exclude .exp and .lib files (only relevant for windows builds)
        if(!file.contains(".exp") && !file.contains(".lib")) {
            this->setFileName(pluginsDir.absoluteFilePath(file));
            QObject *pPlugin = this->instance();

            // AbstractPlugin
            if(pPlugin) {
                qDebug() << "[PluginManager::loadPlugin] Loading Plugin" << file.toUtf8().constData() << "succeeded.";
                m_qVecPlugins.push_back(qobject_cast<AbstractPlugin*>(pPlugin));
            } else {
                qDebug() << "[PluginManager::loadPlugin] Loading Plugin" << file.toUtf8().constData() << "failed.";
            }
        }
    }
#endif
}

//=============================================================================================================

void PluginManager::initPlugins(QSharedPointer<AnalyzeData> data)
{
    for(AbstractPlugin* plugin : m_qVecPlugins)
    {
        plugin->setGlobalData(data);
        plugin->init();
    }

    // tell everyone that INIT-phase is finished
    Communicator con;
    con.publishEvent(EVENT_TYPE::PLUGIN_INIT_FINISHED);
}

//=============================================================================================================

int PluginManager::findByName(const QString& name)
{
    QVector<AbstractPlugin*>::const_iterator it = m_qVecPlugins.cbegin();
    for(int i = 0; it != m_qVecPlugins.cend(); ++i, ++it)
    {
        if((*it)->getName() == name)
        {
            return i;
        }
    }
    return -1;
}

//=============================================================================================================

void PluginManager::shutdown()
{
    for(AbstractPlugin* plugin : m_qVecPlugins)
    {
        plugin->unload();
    }
}
<|endoftext|>


<commit_before>// @(#)root/proofx:$Id$
// Author: Gerardo Ganis  12/12/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TXSocketHandler                                                      //
//                                                                      //
// Input handler for xproofd sockets. These sockets cannot be directly  //
// monitored on their descriptor, because the reading activity goes via //
// the reader thread. This class allows to handle this problem.         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TMonitor.h"
#include "TProof.h"
#include "TSlave.h"
#include "TXSocketHandler.h"
#include "TXHandler.h"
#include "TList.h"

ClassImp(TXSocketHandler)

// Unique instance of the socket input handler
TXSocketHandler *TXSocketHandler::fgSocketHandler = 0;

//______________________________________________________________________________
Bool_t TXSocketHandler::Notify()
{
   // Set readiness on the monitor

   if (gDebug > 2)
      TXSocket::fgPipe.DumpReadySock();

   // Get the socket
   TXSocket *s = TXSocket::fgPipe.GetLastReady();
   if (gDebug > 2)
      Info("Notify", "ready socket %p (%s) (input socket: %p)",
                     s, (s ? s->GetTitle() : "***undef***"), fInputSock);

   // If empty, nothing to do
   if (!s) {
      Warning("Notify","socket-ready list is empty!");
      return kTRUE;
   }

   // Handle this input
   s->fHandler->HandleInput();

   // We are done
   return kTRUE;
}

//_______________________________________________________________________
TXSocketHandler *TXSocketHandler::GetSocketHandler(TFileHandler *h, TSocket *s)
{
   // Get an instance of the input socket handler with 'h' as handler,
   // connected to socket 's'.
   // Create the instance, if not already existing

   if (!fgSocketHandler)
      fgSocketHandler = new TXSocketHandler(h, s);
   else
      if (h && s)
         fgSocketHandler->SetHandler(h, s);

   return fgSocketHandler;
}
<commit_msg>Add file descriptor number in debug statement<commit_after>// @(#)root/proofx:$Id$
// Author: Gerardo Ganis  12/12/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TXSocketHandler                                                      //
//                                                                      //
// Input handler for xproofd sockets. These sockets cannot be directly  //
// monitored on their descriptor, because the reading activity goes via //
// the reader thread. This class allows to handle this problem.         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TMonitor.h"
#include "TProof.h"
#include "TSlave.h"
#include "TXSocketHandler.h"
#include "TXHandler.h"
#include "TList.h"

ClassImp(TXSocketHandler)

// Unique instance of the socket input handler
TXSocketHandler *TXSocketHandler::fgSocketHandler = 0;

//______________________________________________________________________________
Bool_t TXSocketHandler::Notify()
{
   // Set readiness on the monitor

   if (gDebug > 2)
      TXSocket::fgPipe.DumpReadySock();

   // Get the socket
   TXSocket *s = TXSocket::fgPipe.GetLastReady();
   if (gDebug > 2)
      Info("Notify", "ready socket %p (%s) (input socket: %p) (fFileNum: %d)",
                     s, (s ? s->GetTitle() : "***undef***"), fInputSock, fFileNum);

   // If empty, nothing to do
   if (!s) {
      Warning("Notify","socket-ready list is empty!");
      return kTRUE;
   }

   // Handle this input
   s->fHandler->HandleInput();

   // We are done
   return kTRUE;
}

//_______________________________________________________________________
TXSocketHandler *TXSocketHandler::GetSocketHandler(TFileHandler *h, TSocket *s)
{
   // Get an instance of the input socket handler with 'h' as handler,
   // connected to socket 's'.
   // Create the instance, if not already existing

   if (!fgSocketHandler)
      fgSocketHandler = new TXSocketHandler(h, s);
   else
      if (h && s)
         fgSocketHandler->SetHandler(h, s);

   return fgSocketHandler;
}
<|endoftext|>