<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 "otbWrapperApplicationHtmlDocGenerator.h"

#include <stdio.h>
#include "otbMacro.h"
#include "otbWrapperParameterGroup.h"
#include "otbWrapperChoiceParameter.h"

namespace otb
{
namespace Wrapper
{

#define otbDocHtmlTitleMacro( value )                                       \
  oss << "</style>
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlTitle1Macro( value )                                  \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlTitle2Macro( value )                                  \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlBodyMacro( value )                                         \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlBodyCodeMacro( value )                                         \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlParamMacro( type, param )                             \
  oss << "
"; \
  oss << "["<<type<<"] "<< param->GetName() <<": ";                     \
  oss << "";                                                     \
  if( std::string(param->GetDescription()).size()!=0 )                  \
    {                                                                   \
    oss << param->GetDescription();                                     \
    }                                                                   \
  oss << "
";

ApplicationHtmlDocGenerator::ApplicationHtmlDocGenerator()
{
}

ApplicationHtmlDocGenerator::~ApplicationHtmlDocGenerator()
{
}

void
ApplicationHtmlDocGenerator::GenerateDoc( const Application::Pointer app, std::string & val )
{
  itk::OStringStream oss;

  oss << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd\">";
  oss << "<meta name=\"qrichtext\" content=\"1\" />";

  otbDocHtmlTitleMacro( app->GetDocName() );

  otbDocHtmlTitle1Macro( "Brief Description" );
  otbDocHtmlBodyMacro( app->GetDescription() );

  otbDocHtmlTitle1Macro( "Tags" );
  std::string tagList;
  if ( app->GetDocTags().size() > 0 )
    {
    for (unsigned int i = 0; i < app->GetDocTags().size() - 1; i++)
      {
      tagList.append( app->GetDocTags()[i] ).append(", ");
      }
    tagList.append( app->GetDocTags()[app->GetDocTags().size() - 1]);
    otbDocHtmlBodyMacro( tagList );
    }
  else
    {
    otbDocHtmlBodyMacro( "None" );
    }

  otbDocHtmlTitle1Macro("Long Description");
  otbDocHtmlBodyMacro( app->GetDocLongDescription() );

  otbDocHtmlTitle1Macro("Parameters");
  oss << "
";
  std::string paramDocs("");
  ApplicationHtmlDocGenerator::GetDocParameters( app, paramDocs );
  oss<<paramDocs;
  oss<<"
";

  otbDocHtmlTitle1Macro( "Limitations");
  otbDocHtmlBodyMacro( app->GetDocLimitations() );

  otbDocHtmlTitle1Macro( "Authors" );
  otbDocHtmlBodyMacro( app->GetDocAuthors() );

  otbDocHtmlTitle1Macro( "See also" );
  otbDocHtmlBodyMacro( app->GetDocSeeAlso() );

  otbDocHtmlTitle1Macro( "Command line example" );
  otbDocHtmlBodyCodeMacro( app->GetDocCLExample() );

  oss << "";

  val = oss.str();
}

void
ApplicationHtmlDocGenerator::GenerateDoc(const Application::Pointer app, const std::string& filename)
{
  std::string doc;

  ApplicationHtmlDocGenerator::GenerateDoc( app, doc );

  FILE *file = fopen(filename.c_str(), "w");
  if (file == NULL)
    {
    fprintf(stderr, "Error, can't open file");
    itkGenericExceptionMacro( << "Error, can't open file "<<filename<<".");
    }
  fprintf(file, "%s", doc.c_str());
  fclose(file);

}

void ApplicationHtmlDocGenerator::GetDocParameters( const Application::Pointer app, std::string & val)
{
  itk::OStringStream oss;
  const std::vector<std::string> appKeyList = app->GetParametersKeys( false );
  const unsigned int nbOfParam = appKeyList.size();

  std::string paramDocs("");
  if( nbOfParam == 0)
    {
    val = "None";
    }
  else
    {
   for( unsigned int i=0; i<nbOfParam; i++ )
     {
     const std::string key(appKeyList[i]);
     Parameter::Pointer param =  app->GetParameterByKey( key );
     if( app->GetParameterType(key) ==  ParameterType_Group)
       {
       oss << "
";
       otbDocHtmlParamMacro( "group", param);
       std::string grDoc;
       ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, key );
       oss<<grDoc;
       oss<<"

";
       }
     else if( app->GetParameterType(key) ==  ParameterType_Choice )
       {
       oss << "
";
       otbDocHtmlParamMacro( "choice", param);
       std::string grDoc;
       ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, key);
       oss<<grDoc;
       oss<<"

";
       }
     else
       {
       oss << "
";
       otbDocHtmlParamMacro("param", param);
       oss << "
";
       }
     }
    }

   val = oss.str();
}

void ApplicationHtmlDocGenerator::GetDocParameterGroup( const Application::Pointer app, std::string & val, const std::string & key )
{
  Parameter * paramGr  = app->GetParameterByKey( key );
  if( !dynamic_cast<ParameterGroup *>(paramGr))
    {
    itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ParameterGroup...");
    }

  ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr);
  const std::vector<std::string> appKeyList = group->GetParametersKeys( false );
  unsigned int nbOfParam = appKeyList.size();
  itk::OStringStream oss;
  oss<<"
";

  for( unsigned int i=0; i<nbOfParam; i++ )
    {
    const std::string fullKey(std::string(key).append(".").append(appKeyList[i]));
    Parameter::Pointer param =  app->GetParameterByKey( fullKey );
    if( app->GetParameterType(fullKey) ==  ParameterType_Group)
      {
      oss<<"
";
       otbDocHtmlParamMacro( "group", param);
      std::string grDoc;
      ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey );
      oss<<grDoc;
      oss<<"
";
      }
    else if( app->GetParameterType(fullKey) ==  ParameterType_Choice )
      {
      oss<<"
";
      otbDocHtmlParamMacro( "choice", param);
      std::string grDoc;
      ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, fullKey );
      oss<<grDoc;
      oss<<"
";
      }
    else
      {
      oss << "
";
      otbDocHtmlParamMacro( "param", param );
      oss <<"
";
      }
    }
  oss<<"
";
  val.append(oss.str());
}

void ApplicationHtmlDocGenerator::GetDocParameterChoice( const Application::Pointer app, std::string & val, const std::string & key )
{
  Parameter * paramCh  = app->GetParameterByKey( key );
  if( !dynamic_cast<ChoiceParameter *>(paramCh))
    {
    itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ChoiceParameter...");
    }
  ChoiceParameter * choice = dynamic_cast<ChoiceParameter *>(paramCh);
  const std::vector<std::string> appKeyList = choice->GetChoiceKeys();
  unsigned int nbOfParam = choice->GetNbChoices();
  itk::OStringStream oss;
  oss<<"
";

  for( unsigned int i=0; i<nbOfParam; i++ )
    {
    const std::string fullKey(std::string(key).append(".").append(appKeyList[i]));
    ParameterGroup * group = choice->GetChoiceParameterGroupByIndex(i);
    std::string grDoc;

    oss << "
";
    otbDocHtmlParamMacro( "group", group);
    ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey );
    oss<<grDoc;
    oss<<"
";
    }
  oss<<"
";
  val.append(oss.str());
}

}
}

<commit_msg>WRG: fix wrg (format not a string literal and no format arguments)<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 "otbWrapperApplicationHtmlDocGenerator.h"

#include <stdio.h>
#include "otbMacro.h"
#include "otbWrapperParameterGroup.h"
#include "otbWrapperChoiceParameter.h"

namespace otb
{
namespace Wrapper
{

#define otbDocHtmlTitleMacro( value )                                       \
  oss << "</style>
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlTitle1Macro( value )                                  \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlTitle2Macro( value )                                  \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlBodyMacro( value )                                         \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlBodyCodeMacro( value )                                         \
  oss << "
"; \
  oss << value;                                                         \
  oss << "
";

#define otbDocHtmlParamMacro( type, param )                             \
  oss << "
"; \
  oss << "["<<type<<"] "<< param->GetName() <<": ";                     \
  oss << "";                                                     \
  if( std::string(param->GetDescription()).size()!=0 )                  \
    {                                                                   \
    oss << param->GetDescription();                                     \
    }                                                                   \
  oss << "
";

ApplicationHtmlDocGenerator::ApplicationHtmlDocGenerator()
{
}

ApplicationHtmlDocGenerator::~ApplicationHtmlDocGenerator()
{
}

void
ApplicationHtmlDocGenerator::GenerateDoc( const Application::Pointer app, std::string & val )
{
  itk::OStringStream oss;

  oss << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd\">";
  oss << "<meta name=\"qrichtext\" content=\"1\" />";

  otbDocHtmlTitleMacro( app->GetDocName() );

  otbDocHtmlTitle1Macro( "Brief Description" );
  otbDocHtmlBodyMacro( app->GetDescription() );

  otbDocHtmlTitle1Macro( "Tags" );
  std::string tagList;
  if ( app->GetDocTags().size() > 0 )
    {
    for (unsigned int i = 0; i < app->GetDocTags().size() - 1; i++)
      {
      tagList.append( app->GetDocTags()[i] ).append(", ");
      }
    tagList.append( app->GetDocTags()[app->GetDocTags().size() - 1]);
    otbDocHtmlBodyMacro( tagList );
    }
  else
    {
    otbDocHtmlBodyMacro( "None" );
    }

  otbDocHtmlTitle1Macro("Long Description");
  otbDocHtmlBodyMacro( app->GetDocLongDescription() );

  otbDocHtmlTitle1Macro("Parameters");
  oss << "
";
  std::string paramDocs("");
  ApplicationHtmlDocGenerator::GetDocParameters( app, paramDocs );
  oss<<paramDocs;
  oss<<"
";

  otbDocHtmlTitle1Macro( "Limitations");
  otbDocHtmlBodyMacro( app->GetDocLimitations() );

  otbDocHtmlTitle1Macro( "Authors" );
  otbDocHtmlBodyMacro( app->GetDocAuthors() );

  otbDocHtmlTitle1Macro( "See also" );
  otbDocHtmlBodyMacro( app->GetDocSeeAlso() );

  otbDocHtmlTitle1Macro( "Command line example" );
  otbDocHtmlBodyCodeMacro( app->GetDocCLExample() );

  oss << "";

  val = oss.str();
}

void
ApplicationHtmlDocGenerator::GenerateDoc(const Application::Pointer app, const std::string& filename)
{
  std::string doc;

  ApplicationHtmlDocGenerator::GenerateDoc( app, doc );

  std::ofstream ofs(filename.c_str());
  if (!ofs.is_open())
    {
    fprintf(stderr, "Error, can't open file");
    itkGenericExceptionMacro( << "Error, can't open file "<<filename<<".");
    }
  ofs << doc;
  ofs.close();
}

void ApplicationHtmlDocGenerator::GetDocParameters( const Application::Pointer app, std::string & val)
{
  itk::OStringStream oss;
  const std::vector<std::string> appKeyList = app->GetParametersKeys( false );
  const unsigned int nbOfParam = appKeyList.size();

  std::string paramDocs("");
  if( nbOfParam == 0)
    {
    val = "None";
    }
  else
    {
   for( unsigned int i=0; i<nbOfParam; i++ )
     {
     const std::string key(appKeyList[i]);
     Parameter::Pointer param =  app->GetParameterByKey( key );
     if( app->GetParameterType(key) ==  ParameterType_Group)
       {
       oss << "
";
       otbDocHtmlParamMacro( "group", param);
       std::string grDoc;
       ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, key );
       oss<<grDoc;
       oss<<"

";
       }
     else if( app->GetParameterType(key) ==  ParameterType_Choice )
       {
       oss << "
";
       otbDocHtmlParamMacro( "choice", param);
       std::string grDoc;
       ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, key);
       oss<<grDoc;
       oss<<"

";
       }
     else
       {
       oss << "
";
       otbDocHtmlParamMacro("param", param);
       oss << "
";
       }
     }
    }

   val = oss.str();
}

void ApplicationHtmlDocGenerator::GetDocParameterGroup( const Application::Pointer app, std::string & val, const std::string & key )
{
  Parameter * paramGr  = app->GetParameterByKey( key );
  if( !dynamic_cast<ParameterGroup *>(paramGr))
    {
    itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ParameterGroup...");
    }

  ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr);
  const std::vector<std::string> appKeyList = group->GetParametersKeys( false );
  unsigned int nbOfParam = appKeyList.size();
  itk::OStringStream oss;
  oss<<"
";

  for( unsigned int i=0; i<nbOfParam; i++ )
    {
    const std::string fullKey(std::string(key).append(".").append(appKeyList[i]));
    Parameter::Pointer param =  app->GetParameterByKey( fullKey );
    if( app->GetParameterType(fullKey) ==  ParameterType_Group)
      {
      oss<<"
";
       otbDocHtmlParamMacro( "group", param);
      std::string grDoc;
      ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey );
      oss<<grDoc;
      oss<<"
";
      }
    else if( app->GetParameterType(fullKey) ==  ParameterType_Choice )
      {
      oss<<"
";
      otbDocHtmlParamMacro( "choice", param);
      std::string grDoc;
      ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, fullKey );
      oss<<grDoc;
      oss<<"
";
      }
    else
      {
      oss << "
";
      otbDocHtmlParamMacro( "param", param );
      oss <<"
";
      }
    }
  oss<<"
";
  val.append(oss.str());
}

void ApplicationHtmlDocGenerator::GetDocParameterChoice( const Application::Pointer app, std::string & val, const std::string & key )
{
  Parameter * paramCh  = app->GetParameterByKey( key );
  if( !dynamic_cast<ChoiceParameter *>(paramCh))
    {
    itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ChoiceParameter...");
    }
  ChoiceParameter * choice = dynamic_cast<ChoiceParameter *>(paramCh);
  const std::vector<std::string> appKeyList = choice->GetChoiceKeys();
  unsigned int nbOfParam = choice->GetNbChoices();
  itk::OStringStream oss;
  oss<<"
";

  for( unsigned int i=0; i<nbOfParam; i++ )
    {
    const std::string fullKey(std::string(key).append(".").append(appKeyList[i]));
    ParameterGroup * group = choice->GetChoiceParameterGroupByIndex(i);
    std::string grDoc;

    oss << "
";
    otbDocHtmlParamMacro( "group", group);
    ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey );
    oss<<grDoc;
    oss<<"
";
    }
  oss<<"
";
  val.append(oss.str());
}

}
}

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Configuration_Enumeration_inl_
#define _Stroika_Foundation_Configuration_Enumeration_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include <wchar.h>

#include "../Debug/Assertions.h"

namespace Stroika::Foundation::Configuration {

    /*
     ********************************************************************************
     ******************************** Configuration::Inc ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr ENUM Inc (ENUM e)
    {
        return ToEnum<ENUM> (ToInt (e) + 1);
    }

    /*
     ********************************************************************************
     ****************************** Configuration::ToInt ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e)
    {
        // https://stroika.atlassian.net/browse/STK-549
        //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND);
        return static_cast<typename underlying_type<ENUM>::type> (e);
    }

    /*
     ********************************************************************************
     ********************* Configuration::GetDistanceSpanned ************************
     ********************************************************************************
     */
    template <typename ENUM>
    constexpr make_unsigned_t<typename underlying_type<ENUM>::type> GetDistanceSpanned ()
    {
        return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ENUM::eCOUNT);
    }

    /*
     ********************************************************************************
     ***************************** Configuration::ToEnum ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e)
    {
        // https://stroika.atlassian.net/browse/STK-549
        //static_assert (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND);
        return static_cast<ENUM> (e);
    }

    /*
     ********************************************************************************
     ******************** Configuration::OffsetFromStart ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> OffsetFromStart (ENUM e)
    {
        // https://stroika.atlassian.net/browse/STK-549
        //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND);
        return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ToInt (e) - ToInt (ENUM::eSTART));
    }
    template <typename ENUM>
    inline constexpr ENUM OffsetFromStart (make_unsigned_t<typename underlying_type<ENUM>::type> offset)
    {
        return ToEnum<ENUM> (offset + ENUM::eSTART);
    }

    /*
     ********************************************************************************
     ************************** Configuration::EnumNames ****************************
     ********************************************************************************
     */
    template <typename ENUM_TYPE>
    inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames)
#if 0
        : fEnumNames_{origEnumNames}
#endif
    {
#if 1
        // @todo find some way to INITIALZIE the static array.... - needed for constexpr function!
        // @see qCANNOT_FIGURE_OUT_HOW_TO_INIT_STD_ARRAY_FROM_STD_INITIALIZER_
        //
        // Tried fEnumNames_{origEnumNames} and tried template <typename... E> CTOR
        auto oi = fEnumNames_.begin ();
        for (EnumName<ENUM_TYPE> i : origEnumNames) {
            Require (oi != fEnumNames_.end ());
            *oi = i;
            ++oi;
        }
#endif
        RequireItemsOrderedByEnumValue_ ();
    }
    template <typename ENUM_TYPE>
    constexpr EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init)
        : fEnumNames_{init}
    {
        RequireItemsOrderedByEnumValue_ ();
    }
    template <typename ENUM_TYPE>
    template <size_t N>
    constexpr EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N])
        : fEnumNames_{origEnumNames}
    {
        RequireItemsOrderedByEnumValue_ ();
    }
    template <typename ENUM_TYPE>
    inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const
    {
        return fEnumNames_;
    }
    template <typename ENUM_TYPE>
    inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const
    {
        return fEnumNames_.begin ();
    }
    template <typename ENUM_TYPE>
    inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const
    {
        return fEnumNames_.end ();
    }
    template <typename ENUM_TYPE>
    constexpr size_t EnumNames<ENUM_TYPE>::size () const
    {
        return fEnumNames_.size ();
    }
    template <typename ENUM_TYPE>
    constexpr const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const
    {
        if (e == ENUM_TYPE::eEND) {
            return nullptr;
        }
#if qDebug
        Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ());
        auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* {
            for (auto i : fEnumNames_) {
                if (i.first == e) {
                    return i.second;
                }
            }
            return nullptr;
        };
        Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second);
#endif
        return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second;
    }
    template <typename ENUM_TYPE>
    inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const
    {
        auto tmp = PeekName (e);
        RequireNotNull (tmp);
        return tmp;
    }
    template <typename ENUM_TYPE>
    optional<ENUM_TYPE> EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const
    {
        /*
         *  NB: this is only safe returning an internal pointer, because the pointer is internal to
         *  static, immudatable data - the basic_array associated with this EnumNames<> structure.
         */
        RequireNotNull (name);
        for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) {
            if (::wcscmp (i->second, name) == 0) {
                return &i->first;
            }
        }
        return nullopt;
    }
    template <typename ENUM_TYPE>
    inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const
    {
        optional<ENUM_TYPE> tmp = PeekValue (name);
        Require (tmp.has_value ());
        return *tmp;
    }
    template <typename ENUM_TYPE>
    template <typename NOT_FOUND_EXCEPTION>
    inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const
    {
        RequireNotNull (name);
        optional<ENUM_TYPE> tmp = PeekValue (name);
        if (!tmp) [[UNLIKELY_ATTR]] {
            //Execution::Throw (notFoundException);
            throw (notFoundException);
        }
        return *tmp;
    }
    template <typename ENUM_TYPE>
    constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const
    {
        Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ());
        using IndexType = make_unsigned_t<typename underlying_type<ENUM_TYPE>::type>;
        for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) {
            Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i);
        }
    }

    /*
     ********************************************************************************
     ************************** Configuration::DefaultNames *************************
     ********************************************************************************
     */
    template <typename ENUM_TYPE>
    constexpr DefaultNames<ENUM_TYPE>::DefaultNames ()
        : EnumNames<ENUM_TYPE> (k)
    {
    }

}
#endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/
<commit_msg>fixed typo<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Configuration_Enumeration_inl_
#define _Stroika_Foundation_Configuration_Enumeration_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include <wchar.h>

#include "../Debug/Assertions.h"

namespace Stroika::Foundation::Configuration {

    /*
     ********************************************************************************
     ******************************** Configuration::Inc ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr ENUM Inc (ENUM e)
    {
        return ToEnum<ENUM> (ToInt (e) + 1);
    }

    /*
     ********************************************************************************
     ****************************** Configuration::ToInt ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e)
    {
        // https://stroika.atlassian.net/browse/STK-549
        //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND);
        return static_cast<typename underlying_type<ENUM>::type> (e);
    }

    /*
     ********************************************************************************
     ********************* Configuration::GetDistanceSpanned ************************
     ********************************************************************************
     */
    template <typename ENUM>
    constexpr make_unsigned_t<typename underlying_type<ENUM>::type> GetDistanceSpanned ()
    {
        return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ENUM::eCOUNT);
    }

    /*
     ********************************************************************************
     ***************************** Configuration::ToEnum ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e)
    {
        // https://stroika.atlassian.net/browse/STK-549
        //static_assert (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND);
        return static_cast<ENUM> (e);
    }

    /*
     ********************************************************************************
     ******************** Configuration::OffsetFromStart ****************************
     ********************************************************************************
     */
    template <typename ENUM>
    inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> OffsetFromStart (ENUM e)
    {
        // https://stroika.atlassian.net/browse/STK-549
        //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND);
        return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ToInt (e) - ToInt (ENUM::eSTART));
    }
    template <typename ENUM>
    inline constexpr ENUM OffsetFromStart (make_unsigned_t<typename underlying_type<ENUM>::type> offset)
    {
        return ToEnum<ENUM> (offset + ENUM::eSTART);
    }

    /*
     ********************************************************************************
     ************************** Configuration::EnumNames ****************************
     ********************************************************************************
     */
    template <typename ENUM_TYPE>
    inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames)
#if 0
        : fEnumNames_{origEnumNames}
#endif
    {
#if 1
        // @todo find some way to INITIALZIE the static array.... - needed for constexpr function!
        // @see qCANNOT_FIGURE_OUT_HOW_TO_INIT_STD_ARRAY_FROM_STD_INITIALIZER_
        //
        // Tried fEnumNames_{origEnumNames} and tried template <typename... E> CTOR
        auto oi = fEnumNames_.begin ();
        for (EnumName<ENUM_TYPE> i : origEnumNames) {
            Require (oi != fEnumNames_.end ());
            *oi = i;
            ++oi;
        }
#endif
        RequireItemsOrderedByEnumValue_ ();
    }
    template <typename ENUM_TYPE>
    constexpr EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init)
        : fEnumNames_{init}
    {
        RequireItemsOrderedByEnumValue_ ();
    }
    template <typename ENUM_TYPE>
    template <size_t N>
    constexpr EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N])
        : fEnumNames_{origEnumNames}
    {
        RequireItemsOrderedByEnumValue_ ();
    }
    template <typename ENUM_TYPE>
    inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const
    {
        return fEnumNames_;
    }
    template <typename ENUM_TYPE>
    inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const
    {
        return fEnumNames_.begin ();
    }
    template <typename ENUM_TYPE>
    inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const
    {
        return fEnumNames_.end ();
    }
    template <typename ENUM_TYPE>
    constexpr size_t EnumNames<ENUM_TYPE>::size () const
    {
        return fEnumNames_.size ();
    }
    template <typename ENUM_TYPE>
    constexpr const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const
    {
        if (e == ENUM_TYPE::eEND) {
            return nullptr;
        }
#if qDebug
        Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ());
        auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* {
            for (auto i : fEnumNames_) {
                if (i.first == e) {
                    return i.second;
                }
            }
            return nullptr;
        };
        Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second);
#endif
        return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second;
    }
    template <typename ENUM_TYPE>
    inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const
    {
        auto tmp = PeekName (e);
        RequireNotNull (tmp);
        return tmp;
    }
    template <typename ENUM_TYPE>
    optional<ENUM_TYPE> EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const
    {
        /*
         *  NB: this is only safe returning an internal pointer, because the pointer is internal to
         *  static, immudatable data - the basic_array associated with this EnumNames<> structure.
         */
        RequireNotNull (name);
        for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) {
            if (::wcscmp (i->second, name) == 0) {
                return i->first;
            }
        }
        return nullopt;
    }
    template <typename ENUM_TYPE>
    inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const
    {
        optional<ENUM_TYPE> tmp = PeekValue (name);
        Require (tmp.has_value ());
        return *tmp;
    }
    template <typename ENUM_TYPE>
    template <typename NOT_FOUND_EXCEPTION>
    inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const
    {
        RequireNotNull (name);
        optional<ENUM_TYPE> tmp = PeekValue (name);
        if (!tmp) [[UNLIKELY_ATTR]] {
            //Execution::Throw (notFoundException);
            throw (notFoundException);
        }
        return *tmp;
    }
    template <typename ENUM_TYPE>
    constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const
    {
        Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ());
        using IndexType = make_unsigned_t<typename underlying_type<ENUM_TYPE>::type>;
        for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) {
            Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i);
        }
    }

    /*
     ********************************************************************************
     ************************** Configuration::DefaultNames *************************
     ********************************************************************************
     */
    template <typename ENUM_TYPE>
    constexpr DefaultNames<ENUM_TYPE>::DefaultNames ()
        : EnumNames<ENUM_TYPE>{k}
    {
    }

}
#endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/
<|endoftext|>


<commit_before><commit_msg>revert gamut::name<commit_after><|endoftext|>


<commit_before>#include "SequenceVectorizer.h"
#include "Opts.h"
#include "ClusterAnalysis.h"
#include "Logger.h"
#include "TarjansAlgorithm.h"
#include "BarnesHutSNEAdapter.h"
#include "KrakenAdapter.h"
#include "RnammerAdapter.h"
#include "ResultIO.h"
#include "IOUtil.h"
#include "MLUtil.h"
#include "HierarchicalClustering.h"

#include <boost/filesystem.hpp>
#include <string>
#include <fstream>
#include <streambuf>
#include <future>
#include <map>

#include <Eigen/Dense>
#include "MatrixUtil.h"

int main(int argc, char *argv[])
{
	std::string banner = "";

	// build program arguments

	try
	{
		Opts::initializeOnce(argc, argv);

		std::ifstream ifs(Opts::sharePath() + "/banner.txt");
		banner = std::string((std::istreambuf_iterator<char>(ifs)),
		                 std::istreambuf_iterator<char>());
	}
	catch(const std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return EXIT_FAILURE;
	}

	// show help

	if (Opts::needsHelp())
	{
		std::cout << banner << std::endl;
		std::cout << Opts::helpDesc() << std::endl;
		return EXIT_SUCCESS;
	}

	// configure logger

	switch (Opts::logLevel())
	{
		case -1: Logger::getInstance().setLevel(Off); break;
		case 0: Logger::getInstance().setLevel(Error); break;
		case 1: Logger::getInstance().setLevel(Info); break;
		case 2: Logger::getInstance().setLevel(Verbose); break;
		case 3: Logger::getInstance().setLevel(Debug); break;
		default: throw std::runtime_error("Loglevel undefined!");
	}

	// check for input files

	if (Opts::inputFASTAs().empty())
	{
		ELOG << "No input FASTA file(s) given (--input-fasta,-i)." << std::endl;
		return EXIT_FAILURE;
	}

	// setup Kraken

	KrakenAdapter krk;
	bool krakenExists = krk.krakenExists();
	if (!krakenExists)
	{
		ELOG << "Kraken not found! It will be disabled.\n- Please make sure that the folders containing the 'kraken' and 'kraken-translate' executables is in your $PATH.\n- Please make sure to supply a database using the --kraken-db switch." << std::endl;
	}

	// setup Rnammer
	bool rmrExists = RnammerAdapter::rnammerExists();
	if (!rmrExists)
	{
		ELOG << "Rnammer not found! It will be disabled.\n- Please make sure that the folders containing the 'rnammer' executable is in your $PATH." << std::endl;
	}

    // create output / export directory

	boost::filesystem::path exportPath (Opts::outputDir() + "/export");
	boost::system::error_code returnedError;
	boost::filesystem::create_directories(exportPath, returnedError);
	if (returnedError)
	{
		ELOG << "Could not create output/export directory, aborting." << std::endl;
		return EXIT_FAILURE;
	}

	// copy result assets

	try
	{
		IOUtil::copyDir(boost::filesystem::path(Opts::sharePath() + "/assets"), Opts::outputDir(), true);
	} catch(const boost::filesystem::filesystem_error & e)
	{
		ELOG << e.what() << std::endl;
		return EXIT_FAILURE;
	}

	// remove old data.js file if necessary

	std::string dataFile = Opts::outputDir() + "/data.js";
	if (boost::filesystem::exists(boost::filesystem::path(dataFile)))
	{
		std::remove(dataFile.c_str());
	}

    // process files

	ResultIO rio(Opts::outputDir(), krakenExists);
	unsigned idCnt = 1;

	for (const auto & fasta : Opts::inputFASTAs())
	{
		if (!boost::filesystem::is_regular_file(boost::filesystem::path(fasta)))
		{
			ELOG << "File '" << fasta << "' does not exist or is not a regular file! Skipping..." << std::endl;
			continue;
		}

		ILOG << "Processing file: " << fasta << std::endl;
		ResultContainer result;

		result.id = idCnt++;
		result.fasta = fasta;

		try
		{
			if (krakenExists)
			{
				ILOG << "Running Kraken..." << std::endl;
				try
				{

				} catch(const std::exception & e)
				{
					result.kraken = krk.runKraken(fasta);
					ELOG << e.what() << std::endl;
					ELOG << "Kraken will be disabled." << std::endl;
					krakenExists = false;
				}
			}

            result.stats = SequenceUtil::calculateStats(fasta, Opts::minContigLength());

			ILOG << "Vectorizing contigs..." << std::endl;
			SequenceVectorizer sv(fasta);
			auto svr = sv.vectorize();
			result.fastaLabels = svr.contigs;

			if (rmrExists)
			{
				ILOG << "Running Rnammer..." << std::endl;

				try
				{
					result._16S = RnammerAdapter::find16S(fasta, svr);
				} catch(const std::exception & e)
				{
					ELOG << e.what() << std::endl;
					ELOG << "16S highlighting will be disabled." << std::endl;
					rmrExists = false;
				}
			}

			ILOG << "Clustering..." << std::endl;
			result.bootstraps = ClusterAnalysis::analyzeBootstraps(svr);
			result.oneshot = result.bootstraps.at(0);
			result.bootstraps.erase(result.bootstraps.begin());

			rio.processResult(result);
		} catch(const std::exception & e)
		{
			ELOG << "An error occurred processing this file: " << e.what() << std::endl;
		}
	}

	return EXIT_SUCCESS;
}
<commit_msg>fixed a mistake where kraken didn't run at all<commit_after>#include "SequenceVectorizer.h"
#include "Opts.h"
#include "ClusterAnalysis.h"
#include "Logger.h"
#include "TarjansAlgorithm.h"
#include "BarnesHutSNEAdapter.h"
#include "KrakenAdapter.h"
#include "RnammerAdapter.h"
#include "ResultIO.h"
#include "IOUtil.h"
#include "MLUtil.h"
#include "HierarchicalClustering.h"

#include <boost/filesystem.hpp>
#include <string>
#include <fstream>
#include <streambuf>
#include <future>
#include <map>

#include <Eigen/Dense>
#include "MatrixUtil.h"

int main(int argc, char *argv[])
{
	std::string banner = "";

	// build program arguments

	try
	{
		Opts::initializeOnce(argc, argv);

		std::ifstream ifs(Opts::sharePath() + "/banner.txt");
		banner = std::string((std::istreambuf_iterator<char>(ifs)),
		                 std::istreambuf_iterator<char>());
	}
	catch(const std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return EXIT_FAILURE;
	}

	// show help

	if (Opts::needsHelp())
	{
		std::cout << banner << std::endl;
		std::cout << Opts::helpDesc() << std::endl;
		return EXIT_SUCCESS;
	}

	// configure logger

	switch (Opts::logLevel())
	{
		case -1: Logger::getInstance().setLevel(Off); break;
		case 0: Logger::getInstance().setLevel(Error); break;
		case 1: Logger::getInstance().setLevel(Info); break;
		case 2: Logger::getInstance().setLevel(Verbose); break;
		case 3: Logger::getInstance().setLevel(Debug); break;
		default: throw std::runtime_error("Loglevel undefined!");
	}

	// check for input files

	if (Opts::inputFASTAs().empty())
	{
		ELOG << "No input FASTA file(s) given (--input-fasta,-i)." << std::endl;
		return EXIT_FAILURE;
	}

	// setup Kraken

	KrakenAdapter krk;
	bool krakenExists = krk.krakenExists();
	if (!krakenExists)
	{
		ELOG << "Kraken not found! It will be disabled.\n- Please make sure that the folders containing the 'kraken' and 'kraken-translate' executables is in your $PATH.\n- Please make sure to supply a database using the --kraken-db switch." << std::endl;
	}

	// setup Rnammer
	bool rmrExists = RnammerAdapter::rnammerExists();
	if (!rmrExists)
	{
		ELOG << "Rnammer not found! It will be disabled.\n- Please make sure that the folders containing the 'rnammer' executable is in your $PATH." << std::endl;
	}

    // create output / export directory

	boost::filesystem::path exportPath (Opts::outputDir() + "/export");
	boost::system::error_code returnedError;
	boost::filesystem::create_directories(exportPath, returnedError);
	if (returnedError)
	{
		ELOG << "Could not create output/export directory, aborting." << std::endl;
		return EXIT_FAILURE;
	}

	// copy result assets

	try
	{
		IOUtil::copyDir(boost::filesystem::path(Opts::sharePath() + "/assets"), Opts::outputDir(), true);
	} catch(const boost::filesystem::filesystem_error & e)
	{
		ELOG << e.what() << std::endl;
		return EXIT_FAILURE;
	}

	// remove old data.js file if necessary

	std::string dataFile = Opts::outputDir() + "/data.js";
	if (boost::filesystem::exists(boost::filesystem::path(dataFile)))
	{
		std::remove(dataFile.c_str());
	}

    // process files

	ResultIO rio(Opts::outputDir(), krakenExists);
	unsigned idCnt = 1;

	for (const auto & fasta : Opts::inputFASTAs())
	{
		if (!boost::filesystem::is_regular_file(boost::filesystem::path(fasta)))
		{
			ELOG << "File '" << fasta << "' does not exist or is not a regular file! Skipping..." << std::endl;
			continue;
		}

		ILOG << "Processing file: " << fasta << std::endl;
		ResultContainer result;

		result.id = idCnt++;
		result.fasta = fasta;

		try
		{
			if (krakenExists)
			{
				ILOG << "Running Kraken..." << std::endl;
				try
				{
					result.kraken = krk.runKraken(fasta);
				} catch(const std::exception & e)
				{
					ELOG << e.what() << std::endl;
					ELOG << "Kraken will be disabled." << std::endl;
					krakenExists = false;
				}
			}

            result.stats = SequenceUtil::calculateStats(fasta, Opts::minContigLength());

			ILOG << "Vectorizing contigs..." << std::endl;
			SequenceVectorizer sv(fasta);
			auto svr = sv.vectorize();
			result.fastaLabels = svr.contigs;

			if (rmrExists)
			{
				ILOG << "Running Rnammer..." << std::endl;

				try
				{
					result._16S = RnammerAdapter::find16S(fasta, svr);
				} catch(const std::exception & e)
				{
					ELOG << e.what() << std::endl;
					ELOG << "16S highlighting will be disabled." << std::endl;
					rmrExists = false;
				}
			}

			ILOG << "Clustering..." << std::endl;
			result.bootstraps = ClusterAnalysis::analyzeBootstraps(svr);
			result.oneshot = result.bootstraps.at(0);
			result.bootstraps.erase(result.bootstraps.begin());

			rio.processResult(result);
		} catch(const std::exception & e)
		{
			ELOG << "An error occurred processing this file: " << e.what() << std::endl;
		}
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#ifndef _Stroika_Foundation_Configuration_Enumeration_inl_
#define _Stroika_Foundation_Configuration_Enumeration_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../Debug/Assertions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Configuration {

            /*
             ********************************************************************************
             ******************************** Configuration::Inc ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline  constexpr   ENUM    Inc (ENUM e)
            {
                return ToEnum<ENUM> (ToInt (e) + 1);
            }

            /*
             ********************************************************************************
             ****************************** Configuration::ToInt ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline  constexpr   typename underlying_type<ENUM>::type    ToInt (ENUM e)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (ENUM::eSTART <= e and e <= ENUM::eEND);
#endif
                return static_cast<typename underlying_type<ENUM>::type> (e);
            }

            /*
             ********************************************************************************
             ***************************** Configuration::ToEnum ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline   constexpr  ENUM   ToEnum (typename underlying_type<ENUM>::type e)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND);
#endif
                return static_cast<ENUM> (e);
            }

            /*
             ********************************************************************************
             ******************** Configuration::OffsetFromStart ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline  constexpr   typename make_unsigned<typename underlying_type<ENUM>::type>::type    OffsetFromStart (ENUM e)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (ENUM::eSTART <= e and e <= ENUM::eEND);
#endif
                return static_cast<typename make_unsigned<typename underlying_type<ENUM>::type>::type> (ToInt (e) - ToInt (ENUM::eSTART));
            }
            template    <typename   ENUM>
            inline  constexpr   ENUM                                                                OffsetFromStart (typename make_unsigned<typename underlying_type<ENUM>::type>::type offset)
            {
                return ToEnum<ENUM> (offset + ENUM::eSTART);
            }

            /*
             ********************************************************************************
             ************************** Configuration::EnumNames ****************************
             ********************************************************************************
             */
            template     <typename ENUM_TYPE>
            inline  EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames)
                : fEnumNames_ ()
            {
                // @todo find some way to INITIALZIE the static array.... - needed for constexpr function!
                auto oi = fEnumNames_.begin ();
                for (EnumName<ENUM_TYPE> i : origEnumNames) {
                    Require (oi != fEnumNames_.end ());
                    *oi = i;
                    ++oi;
                }
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                RequireItemsOrderedByEnumValue_ ();
#endif
            }
            template     <typename ENUM_TYPE>
            inline
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init)
                : fEnumNames_ (init)
            {
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                RequireItemsOrderedByEnumValue_ ();
#endif
            }
            template     <typename ENUM_TYPE>
            template     <size_t N>
            inline
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N])
                : fEnumNames_ (origEnumNames)
            {
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                RequireItemsOrderedByEnumValue_ ();
#endif
            }
            template     <typename ENUM_TYPE>
            inline  EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const
            {
                return fEnumNames_;
            }
            template     <typename ENUM_TYPE>
            inline  typename EnumNames<ENUM_TYPE>::const_iterator  EnumNames<ENUM_TYPE>::begin () const
            {
                return fEnumNames_.begin ();
            }
            template     <typename ENUM_TYPE>
            inline  typename EnumNames<ENUM_TYPE>::const_iterator  EnumNames<ENUM_TYPE>::end () const
            {
                return fEnumNames_.end ();
            }
            template     <typename ENUM_TYPE>
            inline  constexpr   size_t  EnumNames<ENUM_TYPE>::size () const
            {
                return fEnumNames_.size ();
            }
            template     <typename ENUM_TYPE>
            inline  const wchar_t*  EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const
            {
                if (e == ENUM_TYPE::eEND) {
                    return nullptr;
                }
#if     qDebug
//#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ());
                auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* {
                    for (auto i : fEnumNames_) {
                        if (i.first == e) {
                            return i.second;
                        }
                    }
                    return nullptr;
                };
                Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second);
#endif
                return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second;
            }
            template     <typename ENUM_TYPE>
            inline  const wchar_t*  EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const
            {
                auto tmp = PeekName (e);
                RequireNotNull (tmp);
                return tmp;
            }
            template     <typename ENUM_TYPE>
            const ENUM_TYPE*  EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const
            {
                /*
                 *  NB: this is only safe returning an internal pointer, because the pointer is internal to
                 *  static, immudatable data - the basic_array associated with this EnumNames<> structure.
                 */
                RequireNotNull (name);
                for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) {
                    if (::wcscmp (i->second, name) == 0) {
                        return &i->first;
                    }
                }
                return nullptr;
            }
            template     <typename ENUM_TYPE>
            inline  ENUM_TYPE  EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const
            {
                const ENUM_TYPE* tmp = PeekValue (name);
                RequireNotNull (tmp);
                return *tmp;
            }
            template     <typename ENUM_TYPE>
            template    <typename   NOT_FOUND_EXCEPTION>
            inline  ENUM_TYPE  EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const
            {
                RequireNotNull (name);
                const ENUM_TYPE* tmp = PeekValue (name);
                if (tmp == nullptr) {
                    //Execution::Throw (notFoundException);
                    throw (notFoundException);
                }
                return *tmp;
            }
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
            template     <typename ENUM_TYPE>
            inline  constexpr   void    EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const
            {
                Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ());
                using IndexType = typename make_unsigned<typename underlying_type<ENUM_TYPE>::type>::type;
                for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) {
                    Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i);
                }
            }
#endif

        }
    }
}
#endif  /*_Stroika_Foundation_Configuration_Enumeration_inl_*/
<commit_msg>DefaultNames<ENUM_TYPE>::DefaultNames<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#ifndef _Stroika_Foundation_Configuration_Enumeration_inl_
#define _Stroika_Foundation_Configuration_Enumeration_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../Debug/Assertions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Configuration {

            /*
             ********************************************************************************
             ******************************** Configuration::Inc ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline  constexpr   ENUM    Inc (ENUM e)
            {
                return ToEnum<ENUM> (ToInt (e) + 1);
            }

            /*
             ********************************************************************************
             ****************************** Configuration::ToInt ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline  constexpr   typename underlying_type<ENUM>::type    ToInt (ENUM e)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (ENUM::eSTART <= e and e <= ENUM::eEND);
#endif
                return static_cast<typename underlying_type<ENUM>::type> (e);
            }

            /*
             ********************************************************************************
             ***************************** Configuration::ToEnum ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline   constexpr  ENUM   ToEnum (typename underlying_type<ENUM>::type e)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND);
#endif
                return static_cast<ENUM> (e);
            }

            /*
             ********************************************************************************
             ******************** Configuration::OffsetFromStart ****************************
             ********************************************************************************
             */
            template    <typename   ENUM>
            inline  constexpr   typename make_unsigned<typename underlying_type<ENUM>::type>::type    OffsetFromStart (ENUM e)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (ENUM::eSTART <= e and e <= ENUM::eEND);
#endif
                return static_cast<typename make_unsigned<typename underlying_type<ENUM>::type>::type> (ToInt (e) - ToInt (ENUM::eSTART));
            }
            template    <typename   ENUM>
            inline  constexpr   ENUM                                                                OffsetFromStart (typename make_unsigned<typename underlying_type<ENUM>::type>::type offset)
            {
                return ToEnum<ENUM> (offset + ENUM::eSTART);
            }

            /*
             ********************************************************************************
             ************************** Configuration::EnumNames ****************************
             ********************************************************************************
             */
            template     <typename ENUM_TYPE>
            inline  EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames)
                : fEnumNames_ ()
            {
                // @todo find some way to INITIALZIE the static array.... - needed for constexpr function!
                auto oi = fEnumNames_.begin ();
                for (EnumName<ENUM_TYPE> i : origEnumNames) {
                    Require (oi != fEnumNames_.end ());
                    *oi = i;
                    ++oi;
                }
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                RequireItemsOrderedByEnumValue_ ();
#endif
            }
            template     <typename ENUM_TYPE>
            inline
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init)
                : fEnumNames_ (init)
            {
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                RequireItemsOrderedByEnumValue_ ();
#endif
            }
            template     <typename ENUM_TYPE>
            template     <size_t N>
            inline
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N])
                : fEnumNames_ (origEnumNames)
            {
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                RequireItemsOrderedByEnumValue_ ();
#endif
            }
            template     <typename ENUM_TYPE>
            inline  EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const
            {
                return fEnumNames_;
            }
            template     <typename ENUM_TYPE>
            inline  typename EnumNames<ENUM_TYPE>::const_iterator  EnumNames<ENUM_TYPE>::begin () const
            {
                return fEnumNames_.begin ();
            }
            template     <typename ENUM_TYPE>
            inline  typename EnumNames<ENUM_TYPE>::const_iterator  EnumNames<ENUM_TYPE>::end () const
            {
                return fEnumNames_.end ();
            }
            template     <typename ENUM_TYPE>
            inline  constexpr   size_t  EnumNames<ENUM_TYPE>::size () const
            {
                return fEnumNames_.size ();
            }
            template     <typename ENUM_TYPE>
            inline  const wchar_t*  EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const
            {
                if (e == ENUM_TYPE::eEND) {
                    return nullptr;
                }
#if     qDebug
//#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
                Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ());
                auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* {
                    for (auto i : fEnumNames_) {
                        if (i.first == e) {
                            return i.second;
                        }
                    }
                    return nullptr;
                };
                Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second);
#endif
                return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second;
            }
            template     <typename ENUM_TYPE>
            inline  const wchar_t*  EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const
            {
                auto tmp = PeekName (e);
                RequireNotNull (tmp);
                return tmp;
            }
            template     <typename ENUM_TYPE>
            const ENUM_TYPE*  EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const
            {
                /*
                 *  NB: this is only safe returning an internal pointer, because the pointer is internal to
                 *  static, immudatable data - the basic_array associated with this EnumNames<> structure.
                 */
                RequireNotNull (name);
                for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) {
                    if (::wcscmp (i->second, name) == 0) {
                        return &i->first;
                    }
                }
                return nullptr;
            }
            template     <typename ENUM_TYPE>
            inline  ENUM_TYPE  EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const
            {
                const ENUM_TYPE* tmp = PeekValue (name);
                RequireNotNull (tmp);
                return *tmp;
            }
            template     <typename ENUM_TYPE>
            template    <typename   NOT_FOUND_EXCEPTION>
            inline  ENUM_TYPE  EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const
            {
                RequireNotNull (name);
                const ENUM_TYPE* tmp = PeekValue (name);
                if (tmp == nullptr) {
                    //Execution::Throw (notFoundException);
                    throw (notFoundException);
                }
                return *tmp;
            }
#if     qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy)
            template     <typename ENUM_TYPE>
            inline  constexpr   void    EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const
            {
                Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ());
                using IndexType = typename make_unsigned<typename underlying_type<ENUM_TYPE>::type>::type;
                for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) {
                    Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i);
                }
            }
#endif

            /*
             ********************************************************************************
             ************************** Configuration::DefaultNames *************************
             ********************************************************************************
             */
            template <typename ENUM_TYPE>
            inline  DefaultNames<ENUM_TYPE>::DefaultNames ()
                : EnumNames<ENUM_TYPE> (k)
            {
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Configuration_Enumeration_inl_*/
<|endoftext|>


<commit_before><commit_msg>Fix argument of write with rvalue reference<commit_after><|endoftext|>


<commit_before>//
// Created by ariel on 10/30/16.
//
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

#include "Tower/Tower.h"
#include "Tower/TowerMan.h"
#include "Location/TileUtil.h"
#include "State/StateManager.h"

using std::cout;
using std::endl;

using Towers::Tower;
using Towers::TowerType;
using Towers::TowerMan;

using Monsters::MonsterMan;

using Location::TileUtil;

int main () {
    // Breaks on 4:3, large screen sizes, but is an acceptable scaling solution for now
    double scale = sf::VideoMode::getDesktopMode().height / 1080;
    sf::RenderWindow window(sf::VideoMode(1000, 1000, 32), "Tower Defense", sf::Style::Close);

    TileUtil::init(1000, 1000);
    TileUtil::loadMap("Resources/Maps/TestMap.json");

	StateManager *stateManager = new StateManager;
    UIManager uiManager(window, *stateManager);
    MonsterMan monstMan(window, uiManager, *stateManager);
    TowerMan towerMan(window, monstMan);

    window.setFramerateLimit(240);
    sf::SoundBuffer fireSound;
    fireSound.loadFromFile("Resources/Sounds/TowerFireSound-1.wav");
    sf::Sound sound;
    sound.setBuffer(fireSound);
    //sound1.play();

    while (window.isOpen()) {
        sf::Event event;
        while(window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            } else if (event.type == sf::Event::MouseButtonReleased) {
				if (stateManager->removeCoins(100)) {
					towerMan.createTower(TowerType::SHORT_RANGE, sf::Mouse::getPosition(window).x,
                                     sf::Mouse::getPosition(window).y);
				} else {
					cout << "Insufficient funds" << endl;
					// This should be an onscreen/audio error
				}
            }
		}

		window.clear(sf::Color::Black);

        TileUtil::render(window);

        towerMan.update();
        towerMan.render();

		monstMan.update();
		monstMan.render();

		uiManager.update();
		uiManager.render();

		window.display();
	}

    return 0;
}
<commit_msg>Updated main<commit_after>//
// Created by ariel on 10/30/16.
//
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

#include "Tower/Tower.h"
#include "Tower/TowerMan.h"
#include "Location/TileUtil.h"

using std::cout;
using std::endl;

using Towers::Tower;
using Towers::TowerType;
using Towers::TowerMan;

using Monsters::MonsterMan;

using Location::TileUtil;

int main () {
    // Breaks on 4:3, large screen sizes, but is an acceptable scaling solution for now
    double scale = sf::VideoMode::getDesktopMode().height / 1080;
    sf::RenderWindow window(sf::VideoMode(1000, 1000, 32), "Tower Defense", sf::Style::Close);

    TileUtil::init(1000, 1000);
    TileUtil::loadMap("Resources/Maps/TestMap.json");

	StateManager *stateManager = new StateManager;
    UIManager uiManager(window, *stateManager);
    MonsterMan monstMan(window, uiManager, *stateManager);
    TowerMan towerMan(window, monstMan);
    monstMan.createMonster();

    window.setFramerateLimit(240);
    sf::SoundBuffer fireSound;
    fireSound.loadFromFile("Resources/Sounds/TowerFireSound-1.wav");
    sf::Sound sound;
    sound.setBuffer(fireSound);
    //sound1.play();

    while (window.isOpen()) {
        sf::Event event;
        while(window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            } else if (event.type == sf::Event::MouseButtonReleased) {
				if (stateManager->removeCoins(100)) {
					towerMan.createTower(TowerType::SHORT_RANGE, sf::Mouse::getPosition(window).x,
                                     sf::Mouse::getPosition(window).y);
				} else {
					cout << "Insufficient funds" << endl;
					// This should be an onscreen/audio error
				}
            }
		}

        TileUtil::render(window);

        towerMan.update();
        towerMan.render();

		monstMan.update();
		monstMan.render();

		uiManager.update();
		uiManager.render();

		window.display();
	}

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>automated merge<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed 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.
 */

// #define VERBOSE_DEBUG

#define LOG_TAG "Minikin"
#include <cutils/log.h>

#include "MinikinInternal.h"
#include <minikin/CmapCoverage.h>
#include <minikin/FontCollection.h>

using std::vector;

namespace android {

template <typename T>
static inline T max(T a, T b) {
    return a>b ? a : b;
}

uint32_t FontCollection::sNextId = 0;

FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
    mMaxChar(0) {
    AutoMutex _l(gMinikinLock);
    mId = sNextId++;
    vector<uint32_t> lastChar;
    size_t nTypefaces = typefaces.size();
#ifdef VERBOSE_DEBUG
    ALOGD("nTypefaces = %d\n", nTypefaces);
#endif
    const FontStyle defaultStyle;
    for (size_t i = 0; i < nTypefaces; i++) {
        FontFamily* family = typefaces[i];
        family->RefLocked();
        FontInstance dummy;
        mInstances.push_back(dummy);  // emplace_back would be better
        FontInstance* instance = &mInstances.back();
        instance->mFamily = family;
        instance->mCoverage = new SparseBitSet;
        MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
        if (typeface == NULL) {
            ALOGE("FontCollection: closest match was null");
            // TODO: we shouldn't hit this, as there should be more robust
            // checks upstream to prevent empty/invalid FontFamily objects
            continue;
        }
#ifdef VERBOSE_DEBUG
        ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts());
#endif
        const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p');
        size_t cmapSize = 0;
        bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize);
        UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]);
        ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize);
        CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize);
#ifdef VERBOSE_DEBUG
        ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(),
                instance->mCoverage->nextSetBit(0));
#endif
        mMaxChar = max(mMaxChar, instance->mCoverage->length());
        lastChar.push_back(instance->mCoverage->nextSetBit(0));
    }
    size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
    size_t offset = 0;
    for (size_t i = 0; i < nPages; i++) {
        Range dummy;
        mRanges.push_back(dummy);
        Range* range = &mRanges.back();
#ifdef VERBOSE_DEBUG
        ALOGD("i=%d: range start = %d\n", i, offset);
#endif
        range->start = offset;
        for (size_t j = 0; j < nTypefaces; j++) {
            if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
                const FontInstance* instance = &mInstances[j];
                mInstanceVec.push_back(instance);
                offset++;
                uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage);
#ifdef VERBOSE_DEBUG
                ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
#endif
                lastChar[j] = nextChar;
            }
        }
        range->end = offset;
    }
}

FontCollection::~FontCollection() {
    for (size_t i = 0; i < mInstances.size(); i++) {
        delete mInstances[i].mCoverage;
        mInstances[i].mFamily->UnrefLocked();
    }
}

// Implement heuristic for choosing best-match font. Here are the rules:
// 1. If first font in the collection has the character, it wins.
// 2. If a font matches both language and script, it gets a score of 4.
// 3. If a font matches just language, it gets a score of 2.
// 4. Matching the "compact" or "elegant" variant adds one to the score.
// 5. Highest score wins, with ties resolved to the first font.
const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch,
            FontLanguage lang, int variant) const {
    if (ch >= mMaxChar) {
        return NULL;
    }
    const Range& range = mRanges[ch >> kLogCharsPerPage];
#ifdef VERBOSE_DEBUG
    ALOGD("querying range %d:%d\n", range.start, range.end);
#endif
    const FontInstance* bestInstance = NULL;
    int bestScore = -1;
    for (size_t i = range.start; i < range.end; i++) {
        const FontInstance* instance = mInstanceVec[i];
        if (instance->mCoverage->get(ch)) {
            FontFamily* family = instance->mFamily;
            // First font family in collection always matches
            if (mInstances[0].mFamily == family) {
                return instance;
            }
            int score = lang.match(family->lang()) * 2;
            if (variant != 0 && variant == family->variant()) {
                score++;
            }
            if (score > bestScore) {
                bestScore = score;
                bestInstance = instance;
            }
        }
    }
    return bestInstance;
}

void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
        vector<Run>* result) const {
    FontLanguage lang = style.getLanguage();
    int variant = style.getVariant();
    const FontInstance* lastInstance = NULL;
    Run* run = NULL;
    int nShorts;
    for (size_t i = 0; i < string_size; i += nShorts) {
        nShorts = 1;
        uint32_t ch = string[i];
        // sigh, decode UTF-16 by hand here
        if ((ch & 0xfc00) == 0xd800) {
            if ((i + 1) < string_size) {
                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
                nShorts = 2;
            }
        }
        // Continue using existing font as long as it has coverage.
        if (lastInstance == NULL || !lastInstance->mCoverage->get(ch)) {
            const FontInstance* instance = getInstanceForChar(ch, lang, variant);
            if (i == 0 || instance != lastInstance) {
                Run dummy;
                result->push_back(dummy);
                run = &result->back();
                if (instance == NULL) {
                    run->fakedFont.font = NULL;
                } else {
                    run->fakedFont = instance->mFamily->getClosestMatch(style);
                }
                lastInstance = instance;
                run->start = i;
            }
        }
        run->end = i + nShorts;
    }
}

MinikinFont* FontCollection::baseFont(FontStyle style) {
    return baseFontFaked(style).font;
}

FakedFont FontCollection::baseFontFaked(FontStyle style) {
    if (mInstances.empty()) {
        return FakedFont();
    }
    return mInstances[0].mFamily->getClosestMatch(style);
}

uint32_t FontCollection::getId() const {
    return mId;
}

}  // namespace android
<commit_msg>Fix missing text on nonexistent font file<commit_after>/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed 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.
 */

// #define VERBOSE_DEBUG

#define LOG_TAG "Minikin"
#include <cutils/log.h>

#include "MinikinInternal.h"
#include <minikin/CmapCoverage.h>
#include <minikin/FontCollection.h>

using std::vector;

namespace android {

template <typename T>
static inline T max(T a, T b) {
    return a>b ? a : b;
}

uint32_t FontCollection::sNextId = 0;

FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
    mMaxChar(0) {
    AutoMutex _l(gMinikinLock);
    mId = sNextId++;
    vector<uint32_t> lastChar;
    size_t nTypefaces = typefaces.size();
#ifdef VERBOSE_DEBUG
    ALOGD("nTypefaces = %d\n", nTypefaces);
#endif
    const FontStyle defaultStyle;
    for (size_t i = 0; i < nTypefaces; i++) {
        FontFamily* family = typefaces[i];
        MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
        if (typeface == NULL) {
            ALOGE("FontCollection: closest match was null");
            // TODO: we shouldn't hit this, as there should be more robust
            // checks upstream to prevent empty/invalid FontFamily objects
            continue;
        }
        family->RefLocked();
        FontInstance dummy;
        mInstances.push_back(dummy);  // emplace_back would be better
        FontInstance* instance = &mInstances.back();
        instance->mFamily = family;
        instance->mCoverage = new SparseBitSet;
#ifdef VERBOSE_DEBUG
        ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts());
#endif
        const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p');
        size_t cmapSize = 0;
        bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize);
        UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]);
        ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize);
        CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize);
#ifdef VERBOSE_DEBUG
        ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(),
                instance->mCoverage->nextSetBit(0));
#endif
        mMaxChar = max(mMaxChar, instance->mCoverage->length());
        lastChar.push_back(instance->mCoverage->nextSetBit(0));
    }
    nTypefaces = mInstances.size();
    size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
    size_t offset = 0;
    for (size_t i = 0; i < nPages; i++) {
        Range dummy;
        mRanges.push_back(dummy);
        Range* range = &mRanges.back();
#ifdef VERBOSE_DEBUG
        ALOGD("i=%d: range start = %d\n", i, offset);
#endif
        range->start = offset;
        for (size_t j = 0; j < nTypefaces; j++) {
            if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
                const FontInstance* instance = &mInstances[j];
                mInstanceVec.push_back(instance);
                offset++;
                uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage);
#ifdef VERBOSE_DEBUG
                ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
#endif
                lastChar[j] = nextChar;
            }
        }
        range->end = offset;
    }
}

FontCollection::~FontCollection() {
    for (size_t i = 0; i < mInstances.size(); i++) {
        delete mInstances[i].mCoverage;
        mInstances[i].mFamily->UnrefLocked();
    }
}

// Implement heuristic for choosing best-match font. Here are the rules:
// 1. If first font in the collection has the character, it wins.
// 2. If a font matches both language and script, it gets a score of 4.
// 3. If a font matches just language, it gets a score of 2.
// 4. Matching the "compact" or "elegant" variant adds one to the score.
// 5. Highest score wins, with ties resolved to the first font.
const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch,
            FontLanguage lang, int variant) const {
    if (ch >= mMaxChar) {
        return NULL;
    }
    const Range& range = mRanges[ch >> kLogCharsPerPage];
#ifdef VERBOSE_DEBUG
    ALOGD("querying range %d:%d\n", range.start, range.end);
#endif
    const FontInstance* bestInstance = NULL;
    int bestScore = -1;
    for (size_t i = range.start; i < range.end; i++) {
        const FontInstance* instance = mInstanceVec[i];
        if (instance->mCoverage->get(ch)) {
            FontFamily* family = instance->mFamily;
            // First font family in collection always matches
            if (mInstances[0].mFamily == family) {
                return instance;
            }
            int score = lang.match(family->lang()) * 2;
            if (variant != 0 && variant == family->variant()) {
                score++;
            }
            if (score > bestScore) {
                bestScore = score;
                bestInstance = instance;
            }
        }
    }
    return bestInstance;
}

void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
        vector<Run>* result) const {
    FontLanguage lang = style.getLanguage();
    int variant = style.getVariant();
    const FontInstance* lastInstance = NULL;
    Run* run = NULL;
    int nShorts;
    for (size_t i = 0; i < string_size; i += nShorts) {
        nShorts = 1;
        uint32_t ch = string[i];
        // sigh, decode UTF-16 by hand here
        if ((ch & 0xfc00) == 0xd800) {
            if ((i + 1) < string_size) {
                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
                nShorts = 2;
            }
        }
        // Continue using existing font as long as it has coverage.
        if (lastInstance == NULL || !lastInstance->mCoverage->get(ch)) {
            const FontInstance* instance = getInstanceForChar(ch, lang, variant);
            if (i == 0 || instance != lastInstance) {
                Run dummy;
                result->push_back(dummy);
                run = &result->back();
                if (instance == NULL) {
                    run->fakedFont.font = NULL;
                } else {
                    run->fakedFont = instance->mFamily->getClosestMatch(style);
                }
                lastInstance = instance;
                run->start = i;
            }
        }
        run->end = i + nShorts;
    }
}

MinikinFont* FontCollection::baseFont(FontStyle style) {
    return baseFontFaked(style).font;
}

FakedFont FontCollection::baseFontFaked(FontStyle style) {
    if (mInstances.empty()) {
        return FakedFont();
    }
    return mInstances[0].mFamily->getClosestMatch(style);
}

uint32_t FontCollection::getId() const {
    return mId;
}

}  // namespace android
<|endoftext|>


<commit_before>#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>

#include <pcl/compression/octree_pointcloud_compression.h>

#include <stdio.h>
#include <sstream>
#include <stdlib.h>

#ifdef WIN32
# define sleep(x) Sleep((x)*1000)
#endif

class SimpleOpenNIViewer
{
public:
  SimpleOpenNIViewer () :
    viewer (" Point Cloud Compression Example")
  {
  }

  void
  cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
  {
    if (!viewer.wasStopped ())
    {
      // stringstream to store compressed point cloud
      std::stringstream compressedData;
      // output pointcloud
      pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudOut (new pcl::PointCloud<pcl::PointXYZRGBA> ());

      // compress point cloud
      PointCloudEncoder->encodePointCloud (cloud, compressedData);

      // decompress point cloud
      PointCloudDecoder->decodePointCloud (compressedData, cloudOut);

      // show decompressed point cloud
      viewer.showCloud (cloudOut);
    }
  }

  void
  run ()
  {

    bool showStatistics = true;

    // for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h
    pcl::octree::compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR;

    // instantiate point cloud compression for encoding and decoding
    PointCloudEncoder = new pcl::octree::PointCloudCompression<pcl::PointXYZRGBA> (compressionProfile, showStatistics);
    PointCloudDecoder = new pcl::octree::PointCloudCompression<pcl::PointXYZRGBA> ();

    // create a new grabber for OpenNI devices
    pcl::Grabber* interface = new pcl::OpenNIGrabber ();

    // make callback function from member function
    boost::function<void
    (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

    // connect callback function for desired signal. In this case its a point cloud with color values
    boost::signals2::connection c = interface->registerCallback (f);

    // start receiving point clouds
    interface->start ();

    while (!viewer.wasStopped ())
    {
      sleep (1);
    }

    interface->stop ();

    // delete point cloud compression instances
    delete (PointCloudEncoder);
    delete (PointCloudDecoder);

  }

  pcl::visualization::CloudViewer viewer;

  pcl::octree::PointCloudCompression<pcl::PointXYZRGBA>* PointCloudEncoder;
  pcl::octree::PointCloudCompression<pcl::PointXYZRGBA>* PointCloudDecoder;

};

int
main (int argc, char **argv)
{
  SimpleOpenNIViewer v;
  v.run ();

  return (0);
}
<commit_msg>adjusting point_cloud_compression.cpp to recent code changes<commit_after>#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>

#include <pcl/compression/octree_pointcloud_compression.h>

#include <stdio.h>
#include <sstream>
#include <stdlib.h>

#ifdef WIN32
# define sleep(x) Sleep((x)*1000)
#endif

class SimpleOpenNIViewer
{
public:
  SimpleOpenNIViewer () :
    viewer (" Point Cloud Compression Example")
  {
  }

  void
  cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
  {
    if (!viewer.wasStopped ())
    {
      // stringstream to store compressed point cloud
      std::stringstream compressedData;
      // output pointcloud
      pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudOut (new pcl::PointCloud<pcl::PointXYZRGBA> ());

      // compress point cloud
      PointCloudEncoder->encodePointCloud (cloud, compressedData);

      // decompress point cloud
      PointCloudDecoder->decodePointCloud (compressedData, cloudOut);

      // show decompressed point cloud
      viewer.showCloud (cloudOut);
    }
  }

  void
  run ()
  {

    bool showStatistics = true;

    // for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h
    pcl::octree::compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR;

    // instantiate point cloud compression for encoding and decoding
    PointCloudEncoder = new pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA> (compressionProfile, showStatistics);
    PointCloudDecoder = new pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA> ();

    // create a new grabber for OpenNI devices
    pcl::Grabber* interface = new pcl::OpenNIGrabber ();

    // make callback function from member function
    boost::function<void
    (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

    // connect callback function for desired signal. In this case its a point cloud with color values
    boost::signals2::connection c = interface->registerCallback (f);

    // start receiving point clouds
    interface->start ();

    while (!viewer.wasStopped ())
    {
      sleep (1);
    }

    interface->stop ();

    // delete point cloud compression instances
    delete (PointCloudEncoder);
    delete (PointCloudDecoder);

  }

  pcl::visualization::CloudViewer viewer;

  pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA>* PointCloudEncoder;
  pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA>* PointCloudDecoder;

};

int
main (int argc, char **argv)
{
  SimpleOpenNIViewer v;
  v.run ();

  return (0);
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *             Copyright (C) 2000-2002 by the OpenSG Forum                   *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library 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         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <OpenSG/OSGConfig.h>
#include <OpenSG/OSGBaseInitFunctions.h>

#define SVN_REVISION "382"

/*! Append our version to the library versions string
*/
static bool versionAdder(void)
{
    OSG::addLibraryVersion("OSGBase:             " OSG_VERSION_STRING
                           "\tRev: "               SVN_REVISION );
    return true;
}

static OSG::StaticInitFuncWrapper versionAdderWrapper(versionAdder);
<commit_msg>fixed : include problems<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *             Copyright (C) 2000-2002 by the OpenSG Forum                   *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library 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         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <OSGConfig.h>
#include <OSGBaseInitFunctions.h>

#define SVN_REVISION "382"

/*! Append our version to the library versions string
*/
static bool versionAdder(void)
{
    OSG::addLibraryVersion("OSGBase:             " OSG_VERSION_STRING
                           "\tRev: "               SVN_REVISION );
    return true;
}

static OSG::StaticInitFuncWrapper versionAdderWrapper(versionAdder);
<|endoftext|>


<commit_before>#ifndef NGS_ARCHIVE_BASE
#define NGS_ARCHIVE_BASE

namespace ngstd
{

  class Archive
  {
  public:
    virtual bool Output () = 0;
    virtual bool Input () { return !Output(); }

    virtual Archive & operator & (double & d) = 0;
    virtual Archive & operator & (int & i) = 0;
    virtual Archive & operator & (long & i) = 0;
    virtual Archive & operator & (size_t & i) = 0;
    virtual Archive & operator & (short & i) = 0;
    virtual Archive & operator & (unsigned char & i) = 0;
    virtual Archive & operator & (bool & b) = 0;
    virtual Archive & operator & (string & str) = 0;
    virtual Archive & operator & (char *& str) = 0;

    template <typename T>
    Archive & operator << (const T & t)
    {
      T ht(t);
      (*this) & ht;
      return *this;
    }
  };

}

#endif
<commit_msg>archive array-functions<commit_after>#ifndef NGS_ARCHIVE_BASE
#define NGS_ARCHIVE_BASE

// copied from netgen

namespace ngstd
{

  class Archive
  {
  public:
    virtual bool Output () = 0;
    virtual bool Input () { return !Output(); }

    virtual Archive & operator & (double & d) = 0;
    virtual Archive & operator & (int & i) = 0;
    virtual Archive & operator & (long & i) = 0;
    virtual Archive & operator & (size_t & i) = 0;
    virtual Archive & operator & (short & i) = 0;
    virtual Archive & operator & (unsigned char & i) = 0;
    virtual Archive & operator & (bool & b) = 0;
    virtual Archive & operator & (string & str) = 0;
    virtual Archive & operator & (char *& str) = 0;

    template <typename T>
    Archive & Do (T * data, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & data[j]; }; return *this; };

    virtual Archive & Do (double * d, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & d[j]; }; return *this; };

    virtual Archive & Do (int * i, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; };

    virtual Archive & Do (long * i, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; };

    virtual Archive & Do (size_t * i, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; };

    virtual Archive & Do (short * i, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; };

    virtual Archive & Do (unsigned char * i, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; };

    virtual Archive & Do (bool * b, size_t n)
    { for (size_t j = 0; j < n; j++) { (*this) & b[j]; }; return *this; };

    // nvirtual Archive & Do (string * str, size_t n)
    // { for (size_t j = 0; j < n; j++) { (*this) & str[j]; }; return *this; };
    // virtual Archive & operator & (char *& str) = 0;

    template <typename T>
    Archive & operator << (const T & t)
    {
      T ht(t);
      (*this) & ht;
      return *this;
    }
  };

}

#endif
<|endoftext|>


<commit_before>#include <QCoreApplication>
#include "Network.IRC.Server.hpp"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Network::IRC::Server srv("irc.rizon.net", 9999, &a);
    srv.connect("testos", "Test-App", true);

    return a.exec();
}
<commit_msg>Rewrite of main()<commit_after>#include <QtCore/QCoreApplication>

#include "Network.IRC.Server.hpp"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Network::IRC::Server *srv = new Network::IRC::Server("irc.rizon.net", 9999);
    // Join channel when connected to server
    // Now with 100% more lambda voodoo
    QObject::connect(srv, &Network::IRC::Server::connected, [&](){ srv->join("mr-bigbang"); });
    QObject::connect(srv, &Network::IRC::Server::quitting, &a, &QCoreApplication::quit);

    srv->connect("testos", "Test-App", true);

    return a.exec();
}
<|endoftext|>