<commit_before>/*
 * ZoteroCollectionsLocal.cpp
 *
 * Copyright (C) 2009-20 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "ZoteroCollectionsLocal.hpp"

#include <boost/bind.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>

#include <core/FileSerializer.hpp>
#include <core/Database.hpp>

#include <core/system/Process.hpp>

#include <r/RExec.hpp>

#include <session/prefs/UserState.hpp>
#include <session/SessionModuleContext.hpp>

#include "session-config.h"

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace zotero {
namespace collections {

namespace {

SEXP createCacheSpecSEXP( ZoteroCollectionSpec cacheSpec, r::sexp::Protect* pProtect)
{
   std::vector<std::string> names;
   names.push_back(kName);
   names.push_back(kVersion);
   SEXP cacheSpecSEXP = r::sexp::createList(names, pProtect);
   r::sexp::setNamedListElement(cacheSpecSEXP, kName, cacheSpec.name);
   r::sexp::setNamedListElement(cacheSpecSEXP, kVersion, cacheSpec.version);
   return cacheSpecSEXP;
}

void execQuery(boost::shared_ptr<database::IConnection> pConnection,
               const std::string& sql,
               boost::function<void(const database::Row&)> rowHandler)
{
   database::Rowset rows;
   database::Query query = pConnection->query(sql);
   Error error = pConnection->execute(query, rows);
   if (error)
   {
      LOG_ERROR(error);
      return;
   }

   for (database::RowsetIterator it = rows.begin(); it != rows.end(); ++it)
   {
      const database::Row& row = *it;
      rowHandler(row);
   }
}

ZoteroCollectionSpecs getCollections(boost::shared_ptr<database::IConnection> pConnection)
{
   ZoteroCollectionSpecs specs;
   execQuery(pConnection, "select collectionName, version from collections", [&specs](const database::Row& row) {
      ZoteroCollectionSpec spec;
      spec.name = row.get<std::string>("collectionName");
      spec.version = row.get<int>("version");
      specs.push_back(spec);
   });
   return specs;
}

int getLibraryVersion(boost::shared_ptr<database::IConnection> pConnection)
{
   int version = 0;
   execQuery(pConnection, "SELECT MAX(version) AS version from items", [&version](const database::Row& row) {
      std::string versionStr = row.get<std::string>("version");
      version = safe_convert::stringTo<int>(versionStr, 0);
   });
   return version;
}

void testZoteroSQLite(std::string dataDir)
{
   // connect to sqlite
   std::string db = dataDir + "/zotero.sqlite";
   database::SqliteConnectionOptions options = { db };
   boost::shared_ptr<database::IConnection> pConnection;
   Error error = database::connect(options, &pConnection);
   if (error)
   {
      LOG_ERROR(error);
      return;
   }

   std::cerr << "library: " << getLibraryVersion(pConnection) << std::endl;

   ZoteroCollectionSpecs specs = getCollections(pConnection);
   for (auto spec : specs)
      std::cerr << spec.name << ": " << spec.version << std::endl;

}

void getLocalLibrary(std::string key,
                     ZoteroCollectionSpec cacheSpec,
                     ZoteroCollectionsHandler handler)
{
   testZoteroSQLite(key);

   r::sexp::Protect protect;
   std::string libraryJsonStr;
   Error error = r::exec::RFunction(".rs.zoteroGetLibrary", key,
                                    createCacheSpecSEXP(cacheSpec, &protect)).call(&libraryJsonStr);
   if (error)
   {
      handler(error, std::vector<ZoteroCollection>());
   }
   else
   {
      json::Object libraryJson;
      error = libraryJson.parse(libraryJsonStr);
      if (error)
      {
         handler(error, std::vector<ZoteroCollection>());
      }
      else
      {
         ZoteroCollection collection;
         collection.name = libraryJson[kName].getString();
         collection.version = libraryJson[kVersion].getInt();
         collection.items = libraryJson[kItems].getArray();
         handler(Success(), std::vector<ZoteroCollection>{ collection });
      }
   }
}

void getLocalCollections(std::string key,
                         std::vector<std::string> collections,
                         ZoteroCollectionSpecs cacheSpecs,
                         ZoteroCollectionsHandler handler)
{
    json::Array cacheSpecsJson;
    std::transform(cacheSpecs.begin(), cacheSpecs.end(), std::back_inserter(cacheSpecsJson), [](ZoteroCollectionSpec spec) {
       json::Object specJson;
       specJson[kName] = spec.name;
       specJson[kVersion] = spec.version;
       return specJson;
    });

    r::sexp::Protect protect;
    std::string collectionJsonStr;
    Error error = r::exec::RFunction(".rs.zoteroGetCollections", key, collections, cacheSpecsJson)
                                     .call(&collectionJsonStr);
    if (error)
    {
       handler(error, std::vector<ZoteroCollection>());
    }
    else
    {
       json::Array collectionsJson;
       error = collectionsJson.parse(collectionJsonStr);
       if (error)
       {
          handler(error, std::vector<ZoteroCollection>());
       }
       else
       {
           ZoteroCollections collections;
           std::transform(collectionsJson.begin(), collectionsJson.end(), std::back_inserter(collections), [](json::Value json) {
              ZoteroCollection collection;
              json::Object collectionJson = json.getObject();
              collection.name = collectionJson[kName].getString();
              collection.version = collectionJson[kVersion].getInt();
              collection.items = collectionJson[kItems].getArray();
              return collection;
           });
           handler(Success(), collections);
       }
    }
}

FilePath userHomeDir()
{
   std::string homeEnv;
#ifdef _WIN32
   homeEnv = "USERPROFILE";
#else
   homeEnv = "HOME";
#endif
   return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv)));
}

// https://www.zotero.org/support/kb/profile_directory
FilePath zoteroProfilesDir()
{
   FilePath homeDir = userHomeDir();
   std::string profilesDir;
#if defined(_WIN32)
   profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles";
#elif defined(__APPLE__)
   profilesDir = "Library/Application Support/Zotero/Profiles";
#else
   profilesDir = ".zotero/zotero";
#endif
   return homeDir.completeChildPath(profilesDir);
}

// https://www.zotero.org/support/zotero_data
FilePath defaultZoteroDataDir()
{
   FilePath homeDir = userHomeDir();
   return homeDir.completeChildPath("Zotero");
}

FilePath detectZoteroDataDir()
{
   // we'll fall back to the default if we can't find another dir in the profile
   FilePath dataDir = defaultZoteroDataDir();

   // find the zotero profiles dir
   FilePath profilesDir = zoteroProfilesDir();
   if (profilesDir.exists())
   {
      // there will be one path in the directory
      std::vector<FilePath> children;
      Error error = profilesDir.getChildren(children);
      if (error)
         LOG_ERROR(error);
      if (children.size() > 0)
      {
         // there will be a single directory inside the profiles dir
         FilePath profileDir = children[0];
         FilePath prefsFile = profileDir.completeChildPath("prefs.js");
         if (prefsFile.exists())
         {
            // read the prefs.js file
            std::string prefs;
            error = core::readStringFromFile(prefsFile, &prefs);
            if (error)
               LOG_ERROR(error);

            // look for the zotero.dataDir pref
            boost::smatch match;
            boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);");
            if (boost::regex_search(prefs, match, regex))
            {
               // set dataDiroly if the path exists
               FilePath profileDataDir(match[1]);
               if (profileDataDir.exists())
                  dataDir = profileDataDir;
            }
         }
      }
   }

   // return the data dir
   return dataDir;
}

} // end anonymous namespace

bool localZoteroAvailable()
{
   // availability based on server vs. desktop
#ifdef RSTUDIO_SERVER
   bool local = false;
#else
   bool local = true;
#endif

   // however, also make it available in debug mode for local dev/test
#ifndef NDEBUG
   local = true;
#endif

   return local;
}

// Detect the Zotero data directory and return it if it exists
FilePath detectedZoteroDataDirectory()
{
   if (localZoteroAvailable())
   {
      FilePath dataDir = detectZoteroDataDir();
      if (dataDir.exists())
         return dataDir;
      else
         return FilePath();
   }
   else
   {
      return FilePath();
   }
}

// Returns the zoteroDataDirectory (if any). This will return a valid FilePath
// if the user has specified a zotero data dir in the preferences; OR if
// a zotero data dir was detected on the system. In the former case the
// path may not exist (and this should be logged as an error)
FilePath zoteroDataDirectory()
{
   std::string dataDir = prefs::userState().zoteroDataDir();
   if (!dataDir.empty())
      return module_context::resolveAliasedPath(dataDir);
   else
      return detectedZoteroDataDirectory();
}

ZoteroCollectionSource localCollections()
{
   ZoteroCollectionSource source;
   source.getLibrary = getLocalLibrary;
   source.getCollections = getLocalCollections;
   return source;
}

} // end namespace collections
} // end namespace zotero
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>defuned against unexpected data types in getLibraryVersion<commit_after>/*
 * ZoteroCollectionsLocal.cpp
 *
 * Copyright (C) 2009-20 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "ZoteroCollectionsLocal.hpp"

#include <boost/bind.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>

#include <core/FileSerializer.hpp>
#include <core/Database.hpp>

#include <core/system/Process.hpp>

#include <r/RExec.hpp>

#include <session/prefs/UserState.hpp>
#include <session/SessionModuleContext.hpp>

#include "session-config.h"

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace zotero {
namespace collections {

namespace {

SEXP createCacheSpecSEXP( ZoteroCollectionSpec cacheSpec, r::sexp::Protect* pProtect)
{
   std::vector<std::string> names;
   names.push_back(kName);
   names.push_back(kVersion);
   SEXP cacheSpecSEXP = r::sexp::createList(names, pProtect);
   r::sexp::setNamedListElement(cacheSpecSEXP, kName, cacheSpec.name);
   r::sexp::setNamedListElement(cacheSpecSEXP, kVersion, cacheSpec.version);
   return cacheSpecSEXP;
}

void execQuery(boost::shared_ptr<database::IConnection> pConnection,
               const std::string& sql,
               boost::function<void(const database::Row&)> rowHandler)
{
   database::Rowset rows;
   database::Query query = pConnection->query(sql);
   Error error = pConnection->execute(query, rows);
   if (error)
   {
      LOG_ERROR(error);
      return;
   }

   for (database::RowsetIterator it = rows.begin(); it != rows.end(); ++it)
   {
      const database::Row& row = *it;
      rowHandler(row);
   }
}

ZoteroCollectionSpecs getCollections(boost::shared_ptr<database::IConnection> pConnection)
{
   ZoteroCollectionSpecs specs;
   execQuery(pConnection, "select collectionName, version from collections", [&specs](const database::Row& row) {
      ZoteroCollectionSpec spec;
      spec.name = row.get<std::string>("collectionName");
      spec.version = row.get<int>("version");
      specs.push_back(spec);
   });
   return specs;
}

int getLibraryVersion(boost::shared_ptr<database::IConnection> pConnection)
{
   int version = 0;
   execQuery(pConnection, "SELECT MAX(version) AS version from items", [&version](const database::Row& row) {
      // bizzarly, this value comes back as a dt_string!?!?! we crashed when attempting
      // to do a get<int>. rather than just switch to std::string, let's actually check
      // the type to make sure we don't crash at some point in the future if this no
      // longer returns dt_string
      std::ostringstream ostr;
      auto& props = row.get_properties(0);
      switch(props.get_data_type())
      {
      case soci::dt_string:
         ostr << row.get<std::string>(0);
         break;
      case soci::dt_double:
         ostr << row.get<double>(0);
         break;
      case soci::dt_integer:
         ostr << row.get<int>(0);
         break;
      case soci::dt_long_long:
         ostr << row.get<long long>(0);
         break;
      case soci::dt_unsigned_long_long:
         ostr << row.get<unsigned long long>(0);
         break;
      default:
         ostr << "0";
      }
      version = safe_convert::stringTo<int>(ostr.str(), 0);
   });
   return version;
}

void testZoteroSQLite(std::string dataDir)
{
   // connect to sqlite
   std::string db = dataDir + "/zotero.sqlite";
   database::SqliteConnectionOptions options = { db };
   boost::shared_ptr<database::IConnection> pConnection;
   Error error = database::connect(options, &pConnection);
   if (error)
   {
      LOG_ERROR(error);
      return;
   }

   std::cerr << "library: " << getLibraryVersion(pConnection) << std::endl;

   ZoteroCollectionSpecs specs = getCollections(pConnection);
   for (auto spec : specs)
      std::cerr << spec.name << ": " << spec.version << std::endl;

}

void getLocalLibrary(std::string key,
                     ZoteroCollectionSpec cacheSpec,
                     ZoteroCollectionsHandler handler)
{
   testZoteroSQLite(key);

   r::sexp::Protect protect;
   std::string libraryJsonStr;
   Error error = r::exec::RFunction(".rs.zoteroGetLibrary", key,
                                    createCacheSpecSEXP(cacheSpec, &protect)).call(&libraryJsonStr);
   if (error)
   {
      handler(error, std::vector<ZoteroCollection>());
   }
   else
   {
      json::Object libraryJson;
      error = libraryJson.parse(libraryJsonStr);
      if (error)
      {
         handler(error, std::vector<ZoteroCollection>());
      }
      else
      {
         ZoteroCollection collection;
         collection.name = libraryJson[kName].getString();
         collection.version = libraryJson[kVersion].getInt();
         collection.items = libraryJson[kItems].getArray();
         handler(Success(), std::vector<ZoteroCollection>{ collection });
      }
   }
}

void getLocalCollections(std::string key,
                         std::vector<std::string> collections,
                         ZoteroCollectionSpecs cacheSpecs,
                         ZoteroCollectionsHandler handler)
{
    json::Array cacheSpecsJson;
    std::transform(cacheSpecs.begin(), cacheSpecs.end(), std::back_inserter(cacheSpecsJson), [](ZoteroCollectionSpec spec) {
       json::Object specJson;
       specJson[kName] = spec.name;
       specJson[kVersion] = spec.version;
       return specJson;
    });

    r::sexp::Protect protect;
    std::string collectionJsonStr;
    Error error = r::exec::RFunction(".rs.zoteroGetCollections", key, collections, cacheSpecsJson)
                                     .call(&collectionJsonStr);
    if (error)
    {
       handler(error, std::vector<ZoteroCollection>());
    }
    else
    {
       json::Array collectionsJson;
       error = collectionsJson.parse(collectionJsonStr);
       if (error)
       {
          handler(error, std::vector<ZoteroCollection>());
       }
       else
       {
           ZoteroCollections collections;
           std::transform(collectionsJson.begin(), collectionsJson.end(), std::back_inserter(collections), [](json::Value json) {
              ZoteroCollection collection;
              json::Object collectionJson = json.getObject();
              collection.name = collectionJson[kName].getString();
              collection.version = collectionJson[kVersion].getInt();
              collection.items = collectionJson[kItems].getArray();
              return collection;
           });
           handler(Success(), collections);
       }
    }
}

FilePath userHomeDir()
{
   std::string homeEnv;
#ifdef _WIN32
   homeEnv = "USERPROFILE";
#else
   homeEnv = "HOME";
#endif
   return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv)));
}

// https://www.zotero.org/support/kb/profile_directory
FilePath zoteroProfilesDir()
{
   FilePath homeDir = userHomeDir();
   std::string profilesDir;
#if defined(_WIN32)
   profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles";
#elif defined(__APPLE__)
   profilesDir = "Library/Application Support/Zotero/Profiles";
#else
   profilesDir = ".zotero/zotero";
#endif
   return homeDir.completeChildPath(profilesDir);
}

// https://www.zotero.org/support/zotero_data
FilePath defaultZoteroDataDir()
{
   FilePath homeDir = userHomeDir();
   return homeDir.completeChildPath("Zotero");
}

FilePath detectZoteroDataDir()
{
   // we'll fall back to the default if we can't find another dir in the profile
   FilePath dataDir = defaultZoteroDataDir();

   // find the zotero profiles dir
   FilePath profilesDir = zoteroProfilesDir();
   if (profilesDir.exists())
   {
      // there will be one path in the directory
      std::vector<FilePath> children;
      Error error = profilesDir.getChildren(children);
      if (error)
         LOG_ERROR(error);
      if (children.size() > 0)
      {
         // there will be a single directory inside the profiles dir
         FilePath profileDir = children[0];
         FilePath prefsFile = profileDir.completeChildPath("prefs.js");
         if (prefsFile.exists())
         {
            // read the prefs.js file
            std::string prefs;
            error = core::readStringFromFile(prefsFile, &prefs);
            if (error)
               LOG_ERROR(error);

            // look for the zotero.dataDir pref
            boost::smatch match;
            boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);");
            if (boost::regex_search(prefs, match, regex))
            {
               // set dataDiroly if the path exists
               FilePath profileDataDir(match[1]);
               if (profileDataDir.exists())
                  dataDir = profileDataDir;
            }
         }
      }
   }

   // return the data dir
   return dataDir;
}

} // end anonymous namespace

bool localZoteroAvailable()
{
   // availability based on server vs. desktop
#ifdef RSTUDIO_SERVER
   bool local = false;
#else
   bool local = true;
#endif

   // however, also make it available in debug mode for local dev/test
#ifndef NDEBUG
   local = true;
#endif

   return local;
}

// Detect the Zotero data directory and return it if it exists
FilePath detectedZoteroDataDirectory()
{
   if (localZoteroAvailable())
   {
      FilePath dataDir = detectZoteroDataDir();
      if (dataDir.exists())
         return dataDir;
      else
         return FilePath();
   }
   else
   {
      return FilePath();
   }
}

// Returns the zoteroDataDirectory (if any). This will return a valid FilePath
// if the user has specified a zotero data dir in the preferences; OR if
// a zotero data dir was detected on the system. In the former case the
// path may not exist (and this should be logged as an error)
FilePath zoteroDataDirectory()
{
   std::string dataDir = prefs::userState().zoteroDataDir();
   if (!dataDir.empty())
      return module_context::resolveAliasedPath(dataDir);
   else
      return detectedZoteroDataDirectory();
}

ZoteroCollectionSource localCollections()
{
   ZoteroCollectionSource source;
   source.getLibrary = getLocalLibrary;
   source.getCollections = getLocalCollections;
   return source;
}

} // end namespace collections
} // end namespace zotero
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|>


<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 "otbMirrorBoundaryCondition.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkMacro.h"

int otbMirrorBoundaryConditionTest(int argc, char * argv[])
{
  typedef otb::VectorImage<double,2> ImageType;
  typedef otb::ImageFileReader<ImageType> ReaderType;

  typedef itk::ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType;
  typedef NeighborhoodIteratorType::RadiusType   RadiusType;
  typedef otb::MirrorBoundaryCondition<ImageType> ConditionType;
  typedef NeighborhoodIteratorType::OffsetType OffsetType;
  typedef ImageType::PixelType PixelType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(argv[1]);
  reader->Update();

  RadiusType rad;
  rad.Fill(atoi(argv[2]));

  ConditionType nbc;

  NeighborhoodIteratorType it(rad,reader->GetOutput(),reader->GetOutput()->GetLargestPossibleRegion());
  it.OverrideBoundaryCondition( &nbc );
  it.GoToBegin();

  OffsetType off1,off2;

  itk::OStringStream oss;
  PixelType in,out;

  for(unsigned int i = 0;i<rad[0];++i)
    {
      for(unsigned int j = 0;j<rad[1];++j)
	{
	  off1[0] = -static_cast<int>(i);
	  off1[1] = -static_cast<int>(j);
	  off2[0] = i;
	  off2[1] = j;

	  out=it.GetPixel(off1);
	  in = it.GetPixel(off2);

	  for(unsigned int band = 0;band<reader->GetOutput()->GetNumberOfComponentsPerPixel();++band)
	    {
	      oss.str("");
	      oss<<"Band "<<band<<" : OutOfBound offset: "<<off1<<" <-> value: "<<out[band]<<" != inside image offset: "<<off2<<" <-> value: "<<in[band];
	      otbControlConditionTestMacro(out[band]!=in[band],oss.str().c_str());

	    }
	}
    }

  return EXIT_SUCCESS;
}
<commit_msg>Conditions mirroir au bord<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 "otbMirrorBoundaryCondition.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkMacro.h"

int otbMirrorBoundaryConditionTest(int argc, char * argv[])
{
  typedef otb::VectorImage<double,2> ImageType;
  typedef otb::ImageFileReader<ImageType> ReaderType;

  typedef itk::ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType;
  typedef NeighborhoodIteratorType::RadiusType   RadiusType;
  typedef otb::MirrorBoundaryCondition<ImageType> ConditionType;
  typedef NeighborhoodIteratorType::OffsetType OffsetType;
  typedef ImageType::PixelType PixelType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(argv[1]);
  reader->Update();

  RadiusType rad;
  rad.Fill(atoi(argv[2]));

  ConditionType nbc;

  NeighborhoodIteratorType it(rad,reader->GetOutput(),reader->GetOutput()->GetLargestPossibleRegion());
  it.OverrideBoundaryCondition( &nbc );
  it.GoToBegin();

  OffsetType off1,off2;

  itk::OStringStream oss;
  PixelType in,out;
  for(unsigned int i = 0;i<rad[0];++i)
    {
      for(unsigned int j = 0;j<rad[1];++j)
	{
	  off1[0] = -static_cast<int>(i);
	  off1[1] = -static_cast<int>(j);
	  off2[0] = i;
	  off2[1] = j;

	  out=it.GetPixel(off1);
	  in = it.GetPixel(off2);

	  for(unsigned int band = 0;band<reader->GetOutput()->GetNumberOfComponentsPerPixel();++band)
	    {
	      oss.str("");
	      oss<<"Band "<<band<<" : OutOfBound offset: "<<off1<<" <-> value: "<<out[band]<<" != inside image offset: "<<off2<<" <-> value: "<<in[band];
	      otbControlConditionTestMacro(out[band]!=in[band],oss.str().c_str());

	    }
	}
    }

  ImageType::IndexType center;
  center[0]=reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0]/2;
  center[1]=reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1]/2;

  it.SetLocation(center);

  bool resp = true;

  for(unsigned int i = 0;i<rad[0];++i)
    {
      for(unsigned int j = 0;j<rad[1];++j)
	{
	  off1[0] = -static_cast<int>(i);
	  off1[1] = -static_cast<int>(j);
	  off2[0] = i;
	  off2[1] = j;

	  out=it.GetPixel(off1);
	  in = it.GetPixel(off2);

	  for(unsigned int band = 0;band<reader->GetOutput()->GetNumberOfComponentsPerPixel();++band)
	    {
	      resp = resp && (out[band]==in[band]);
	    }
	}
    }

  otbControlConditionTestMacro(resp,"All symmetrical value of the iterator are equal in the center of the image. their might be a problem.");

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "core/loadedfont.h"

#include "approx_equal.h"
#include "stringeq.h"

#include "catch.hpp"

using namespace euphoria::tests;
using namespace euphoria::core;

TEST_CASE("fonts-", "[fonts]")
{
    auto font = LoadedFont{};

    SECTION("private use")
    {
        const auto acp = font.NewPrivateUse("a");
        const auto it = font.private_use_aliases.find("a");
        const auto found = it != font.private_use_aliases.end();
        REQUIRE(found);
        CHECK(it->second == acp);
    }

    SECTION("combine private use")
    {
        constexpr int a_advance = 10;
        constexpr int b_advance = 20;

        auto a = LoadedGlyph{};
        a.valid = true;
        a.advance = a_advance;

        auto b = LoadedGlyph{};
        b.valid = true;
        b.advance = b_advance;

        auto load = [](const std::string& name, const LoadedGlyph& g) -> LoadedFont
        {
            auto f = LoadedFont{};
            const auto cp = f.NewPrivateUse(name);
            f.codepoint_to_glyph[cp] = g;
            return f;
        };
        font.CombineWith(load("a", a));
        font.CombineWith(load("b", b));

        {
            const auto codepoint_iterator = font.private_use_aliases.find("a");
            const auto found_codepoint =
                codepoint_iterator != font.private_use_aliases.end();
            REQUIRE(found_codepoint);
            const auto glyph_iterator = font.codepoint_to_glyph.find
            (
                codepoint_iterator->second
            );
            const auto found_glyph =
                glyph_iterator != font.codepoint_to_glyph.end();
            REQUIRE(found_glyph);
            CHECK(glyph_iterator->second.advance == a_advance);
        }

        {
            const auto codepoint_iterator = font.private_use_aliases.find("b");
            const auto found_codepoint =
                codepoint_iterator != font.private_use_aliases.end();
            REQUIRE(found_codepoint);
            const auto glyph_iterator = font.codepoint_to_glyph.find
            (
                codepoint_iterator->second
            );
            const auto found_glyph =
                glyph_iterator != font.codepoint_to_glyph.end();
            REQUIRE(found_glyph);
            CHECK(glyph_iterator->second.advance == b_advance);
        }
    }
}

<commit_msg>removed too much space<commit_after>#include "core/loadedfont.h"

#include "approx_equal.h"
#include "stringeq.h"

#include "catch.hpp"

using namespace euphoria::tests;
using namespace euphoria::core;

TEST_CASE("fonts-", "[fonts]")
{
    auto font = LoadedFont{};

    SECTION("private use")
    {
        const auto acp = font.NewPrivateUse("a");
        const auto it = font.private_use_aliases.find("a");
        const auto found = it != font.private_use_aliases.end();
        REQUIRE(found);
        CHECK(it->second == acp);
    }

    SECTION("combine private use")
    {
        constexpr int a_advance = 10;
        constexpr int b_advance = 20;

        auto a = LoadedGlyph{};
        a.valid = true;
        a.advance = a_advance;

        auto b = LoadedGlyph{};
        b.valid = true;
        b.advance = b_advance;

        auto load = [](const std::string& name, const LoadedGlyph& g) -> LoadedFont
        {
            auto f = LoadedFont{};
            const auto cp = f.NewPrivateUse(name);
            f.codepoint_to_glyph[cp] = g;
            return f;
        };
        font.CombineWith(load("a", a));
        font.CombineWith(load("b", b));

        {
            const auto codepoint_iterator = font.private_use_aliases.find("a");
            const auto found_codepoint =
                codepoint_iterator != font.private_use_aliases.end();
            REQUIRE(found_codepoint);
            const auto glyph_iterator = font.codepoint_to_glyph.find
            (
                codepoint_iterator->second
            );
            const auto found_glyph =
                glyph_iterator != font.codepoint_to_glyph.end();
            REQUIRE(found_glyph);
            CHECK(glyph_iterator->second.advance == a_advance);
        }

        {
            const auto codepoint_iterator = font.private_use_aliases.find("b");
            const auto found_codepoint =
                codepoint_iterator != font.private_use_aliases.end();
            REQUIRE(found_codepoint);
            const auto glyph_iterator = font.codepoint_to_glyph.find
            (
                codepoint_iterator->second
            );
            const auto found_glyph =
                glyph_iterator != font.codepoint_to_glyph.end();
            REQUIRE(found_glyph);
            CHECK(glyph_iterator->second.advance == b_advance);
        }
    }
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_frequency_buckets.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

// constant defining number of NEST PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t NEST_PLL_FREQ_BUCKETS = 5;

// Nest PLL frequency in MHZ
// index is bucket number
const uint32_t NEST_PLL_FREQ_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    1600,
    1866,
    2000,
    2133,
    2400
};

// I2C bus divisor
// index is bucket number
// The values in this list will be factor of 1:64 to the NEST_PLL_FREQ_LIST
const uint32_t NEST_PLL_FREQ_I2CDIV_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    25,
    29,
    31,
    33,
    37
};

// constant defining number of MEM PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t MEM_PLL_FREQ_BUCKETS = 5;

// MEM PLL frequency in MHz
// index is bucket number
const uint32_t MEM_PLL_FREQ_LIST[MEM_PLL_FREQ_BUCKETS] =
{
    1866,
    2133,
    2400,
    2666,
    2666
};

// constant definining number of OBUS PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t OBUS_PLL_FREQ_BUCKETS = 3;

// OBUS PLL frequency in MHz
// index is bucket number
const uint32_t OBUS_PLL_FREQ_LIST_P9N_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1250,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_20[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_21[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_22[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1563
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1601,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_12[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};
<commit_msg>Add p9n 2.3 to p9_frequency_buckets.H<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_frequency_buckets.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

// constant defining number of NEST PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t NEST_PLL_FREQ_BUCKETS = 5;

// Nest PLL frequency in MHZ
// index is bucket number
const uint32_t NEST_PLL_FREQ_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    1600,
    1866,
    2000,
    2133,
    2400
};

// I2C bus divisor
// index is bucket number
// The values in this list will be factor of 1:64 to the NEST_PLL_FREQ_LIST
const uint32_t NEST_PLL_FREQ_I2CDIV_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    25,
    29,
    31,
    33,
    37
};

// constant defining number of MEM PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t MEM_PLL_FREQ_BUCKETS = 5;

// MEM PLL frequency in MHz
// index is bucket number
const uint32_t MEM_PLL_FREQ_LIST[MEM_PLL_FREQ_BUCKETS] =
{
    1866,
    2133,
    2400,
    2666,
    2666
};

// constant definining number of OBUS PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t OBUS_PLL_FREQ_BUCKETS = 3;

// OBUS PLL frequency in MHz
// index is bucket number
const uint32_t OBUS_PLL_FREQ_LIST_P9N_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1250,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_20[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_21[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_22[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1563
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_23[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1563
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1601,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_12[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_volt.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>Add L1 procedures for p9a and makefiles<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_volt.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9a_mss_volt.H
/// @brief Calculate and save off rail voltages
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Andre A. Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#ifndef P9A_MSS_VOLT_H_
#define P9A_MSS_VOLT_H_

#include <fapi2.H>
#include <vector>

typedef fapi2::ReturnCode (*p9a_mss_volt_FP_t) (const std::vector <fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>>&);

extern "C"
{

    ///
    /// @brief Calculate and save off rail voltages
    /// @param[in] i_targets vector of ports (e.g., MEM_PORT)
    /// @return FAPI2_RC_SUCCESS iff ok
    ///
    fapi2::ReturnCode p9a_mss_volt( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT> >& i_targets );
}

#endif
<|endoftext|>


<commit_before>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Implementation for URI class.
 *
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

/* This must be included before anything else */
#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include <cctype>
#include <cstdlib>
#include <sstream>

#include <boost/algorithm/string/split.hpp>

#include "opflex/modb/URI.h"

namespace opflex {
namespace modb {

using std::string;
using std::vector;
using std::stringstream;
using boost::algorithm::is_iequal;
using boost::algorithm::split_iterator;
using boost::algorithm::make_split_iterator;
using boost::algorithm::first_finder;
using boost::iterator_range;
using boost::copy_range;

const URI URI::ROOT("/");

URI::URI(const OF_SHARED_PTR<const std::string>& uri_)
    : uri(uri_) {
    hashv = 0;
    boost::hash_combine(hashv, *uri);
}

URI::URI(const std::string& uri_) {
    uri = OF_MAKE_SHARED<const std::string>(uri_);

    hashv = 0;
    boost::hash_combine(hashv, uri_);
}

URI::URI(const URI& uri_)
    : uri(uri_.uri) {
    hashv = uri_.hashv;
}

URI::~URI() {
}

std::ostream & operator<<(std::ostream &os, const URI& uri) {
    os << uri.toString();
    return os;
}

const std::string& URI::toString() const {
    return *uri;
}

typedef split_iterator<string::const_iterator> string_split_iter;

enum UState {
    BEGIN,
    P1,
    P2
};

void URI::getElements(/* out */ vector<string>& elements) const {
    char p[3];
    p[2] = '\0';

    for(string_split_iter it =
        make_split_iterator(*uri, first_finder("/", is_iequal()));
        it != string_split_iter();
        ++it) {
        UState state = BEGIN;
        bool found = false;
        stringstream estream;

        for (string::const_iterator segment = it->begin();
             segment != it->end(); ++segment) {
            char c = *segment;
            switch (state) {
            case BEGIN:
                if (c == '%') {
                    state = P1;
                } else {
                    estream << c;
                    found = true;
                }
                break;
            case P1:
                p[0] = c;
                state = P2;
                break;
            case P2:
                p[1] = c;
                state = BEGIN;
                if (isxdigit(p[0]) && isxdigit(p[1])) {
                    estream << (char)strtol(p, NULL, 16);
                    found = true;
                }
                break;
            }
        }
        if (found)
            elements.push_back(estream.str());
    }
}

URI& URI::operator=(const URI& rhs) {
    uri = rhs.uri;
    hashv = rhs.hashv;
    return *this;
}

bool operator==(const URI& lhs, const URI& rhs) {
    return *lhs.uri == *rhs.uri;
}
bool operator!=(const URI& lhs, const URI& rhs) {
    return !operator==(lhs,rhs);
}

bool operator<(const URI& lhs, const URI& rhs) {
    return *lhs.uri < *rhs.uri;
}

size_t hash_value(URI const& uri) {
    return uri.hashv;
}

} /* namespace modb */
} /* namespace opflex */

#if __cplusplus > 199711L

namespace std {
std::size_t
hash<opflex::modb::URI>::operator()(const opflex::modb::URI& u) const {
    return opflex::modb::hash_value(u);
}

#endif

} /* namespace std */
<commit_msg>Fix C++11 ifdef in URI.cpp that was breaking non-C++11 compilation<commit_after>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Implementation for URI class.
 *
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

/* This must be included before anything else */
#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include <cctype>
#include <cstdlib>
#include <sstream>

#include <boost/algorithm/string/split.hpp>

#include "opflex/modb/URI.h"

namespace opflex {
namespace modb {

using std::string;
using std::vector;
using std::stringstream;
using boost::algorithm::is_iequal;
using boost::algorithm::split_iterator;
using boost::algorithm::make_split_iterator;
using boost::algorithm::first_finder;
using boost::iterator_range;
using boost::copy_range;

const URI URI::ROOT("/");

URI::URI(const OF_SHARED_PTR<const std::string>& uri_)
    : uri(uri_) {
    hashv = 0;
    boost::hash_combine(hashv, *uri);
}

URI::URI(const std::string& uri_) {
    uri = OF_MAKE_SHARED<const std::string>(uri_);

    hashv = 0;
    boost::hash_combine(hashv, uri_);
}

URI::URI(const URI& uri_)
    : uri(uri_.uri) {
    hashv = uri_.hashv;
}

URI::~URI() {
}

std::ostream & operator<<(std::ostream &os, const URI& uri) {
    os << uri.toString();
    return os;
}

const std::string& URI::toString() const {
    return *uri;
}

typedef split_iterator<string::const_iterator> string_split_iter;

enum UState {
    BEGIN,
    P1,
    P2
};

void URI::getElements(/* out */ vector<string>& elements) const {
    char p[3];
    p[2] = '\0';

    for(string_split_iter it =
        make_split_iterator(*uri, first_finder("/", is_iequal()));
        it != string_split_iter();
        ++it) {
        UState state = BEGIN;
        bool found = false;
        stringstream estream;

        for (string::const_iterator segment = it->begin();
             segment != it->end(); ++segment) {
            char c = *segment;
            switch (state) {
            case BEGIN:
                if (c == '%') {
                    state = P1;
                } else {
                    estream << c;
                    found = true;
                }
                break;
            case P1:
                p[0] = c;
                state = P2;
                break;
            case P2:
                p[1] = c;
                state = BEGIN;
                if (isxdigit(p[0]) && isxdigit(p[1])) {
                    estream << (char)strtol(p, NULL, 16);
                    found = true;
                }
                break;
            }
        }
        if (found)
            elements.push_back(estream.str());
    }
}

URI& URI::operator=(const URI& rhs) {
    uri = rhs.uri;
    hashv = rhs.hashv;
    return *this;
}

bool operator==(const URI& lhs, const URI& rhs) {
    return *lhs.uri == *rhs.uri;
}
bool operator!=(const URI& lhs, const URI& rhs) {
    return !operator==(lhs,rhs);
}

bool operator<(const URI& lhs, const URI& rhs) {
    return *lhs.uri < *rhs.uri;
}

size_t hash_value(URI const& uri) {
    return uri.hashv;
}

} /* namespace modb */
} /* namespace opflex */

#if __cplusplus > 199711L

namespace std {

std::size_t
hash<opflex::modb::URI>::operator()(const opflex::modb::URI& u) const {
    return opflex::modb::hash_value(u);
}

} /* namespace std */

#endif /* __cplusplus > 199711L */
<|endoftext|>


<commit_before>/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */
#include "../ui_module.h"
#include <Poco/Environment.h>
#include <Poco/URI.h>
using Poco::URI;
using std::string;
namespace ti
{

	void NormalizeURLCallback(const char* url, char* buffer, int bufferLength)
	{
		strncpy(buffer, url, bufferLength);
		buffer[bufferLength - 1] = '\0';

		string urlString = url;
		string normalized = URLUtils::NormalizeURL(urlString);
		if (normalized != urlString)
		{
			strncpy(buffer, normalized.c_str(), bufferLength);
			buffer[bufferLength - 1] = '\0';
		}
		printf("normalize: %s\n", buffer);
	}

	void URLToFileURLCallback(const char* url, char* buffer, int bufferLength)
	{
		strncpy(buffer, url, bufferLength);
		buffer[bufferLength - 1] = '\0';

		try
		{
			string newURL = url;
			string path = URLUtils::URLToPath(newURL);
			if (path != newURL)
				newURL = URLUtils::PathToFileURL(path);

			strncpy(buffer, newURL.c_str(), bufferLength);
			buffer[bufferLength - 1] = '\0';
		}
		catch (ValueException& e)
		{
			SharedString ss = e.DisplayString();
			Logger* log = Logger::Get("UI.URL");
			log->Error("Could not convert %s to a path: %s", url, ss->c_str());
		}
		catch (...)
		{
			Logger* log = Logger::Get("UI.URL");
			log->Error("Could not convert %s to a path", url);
		}
		printf("file url: %s\n", buffer);
	}
}
<commit_msg>Remove debug printf statements.<commit_after>/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */
#include "../ui_module.h"
#include <Poco/Environment.h>
#include <Poco/URI.h>
using Poco::URI;
using std::string;
namespace ti
{

	void NormalizeURLCallback(const char* url, char* buffer, int bufferLength)
	{
		strncpy(buffer, url, bufferLength);
		buffer[bufferLength - 1] = '\0';

		string urlString = url;
		string normalized = URLUtils::NormalizeURL(urlString);
		if (normalized != urlString)
		{
			strncpy(buffer, normalized.c_str(), bufferLength);
			buffer[bufferLength - 1] = '\0';
		}
	}

	void URLToFileURLCallback(const char* url, char* buffer, int bufferLength)
	{
		strncpy(buffer, url, bufferLength);
		buffer[bufferLength - 1] = '\0';

		try
		{
			string newURL = url;
			string path = URLUtils::URLToPath(newURL);
			if (path != newURL)
				newURL = URLUtils::PathToFileURL(path);

			strncpy(buffer, newURL.c_str(), bufferLength);
			buffer[bufferLength - 1] = '\0';
		}
		catch (ValueException& e)
		{
			SharedString ss = e.DisplayString();
			Logger* log = Logger::Get("UI.URL");
			log->Error("Could not convert %s to a path: %s", url, ss->c_str());
		}
		catch (...)
		{
			Logger* log = Logger::Get("UI.URL");
			log->Error("Could not convert %s to a path", url);
		}
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 odan
 * License: MIT License
 */
#ifndef INCLUDED_CALC_5GEN_SEED_HPP
#define INCLUDED_CALC_5GEN_SEED_HPP
#include <cstdint>

namespace RNGLib {
class Calc5GenSeed {
private:
#ifdef _MSC_VER
    static const uint32_t K0 = 0x5a827999;
    static const uint32_t K1 = 0x6ed9eba1;
    static const uint32_t K2 = 0x8f1bbcdc;
    static const uint32_t K3 = 0xca62c1d6;

    static const uint32_t H0 = 0x67452301;
    static const uint32_t H1 = 0xefcdab89;
    static const uint32_t H2 = 0x98badcfe;
    static const uint32_t H3 = 0x10325476;
    static const uint32_t H4 = 0xc3d2e1f0;
    uint32_t W[80];
#else
    static constexpr uint32_t K0 = 0x5a827999;
    static constexpr uint32_t K1 = 0x6ed9eba1;
    static constexpr uint32_t K2 = 0x8f1bbcdc;
    static constexpr uint32_t K3 = 0xca62c1d6;

    static constexpr uint32_t H0 = 0x67452301;
    static constexpr uint32_t H1 = 0xefcdab89;
    static constexpr uint32_t H2 = 0x98badcfe;
    static constexpr uint32_t H3 = 0x10325476;
    static constexpr uint32_t H4 = 0xc3d2e1f0;
    uint32_t W[80];
#endif

    uint32_t to_uint32_little_endian(uint32_t val) const {
        return ((val&0xff)<<24) | (((val>>8)&0xff)<<16) |
            (((val>>16)&0xff)<<8) | ((val>>24)&0xff);
    }

    uint32_t to_bcd(uint32_t val) const {
        return ((val/10)<<4) | (val%10);
    }
    uint32_t sha1_circular_shift(uint32_t bits, uint32_t word) const {
        return ((word << bits) | (word >> (32-bits)));
    }
public:
    template<class T>
    uint64_t operator() (const T& paramers) {
        uint64_t seed = 0;
        uint32_t A, B, C, D, E;
        uint32_t temp;
        uint32_t i,t;
        W[0] = to_uint32_little_endian(paramers.get_nazo1());
        W[1] = to_uint32_little_endian(paramers.get_nazo2());
        W[2] = to_uint32_little_endian(paramers.get_nazo3());
        W[3] = to_uint32_little_endian(paramers.get_nazo4());
        W[4] = to_uint32_little_endian(paramers.get_nazo5());
        W[5] = to_uint32_little_endian(
                    (paramers.get_vcount()<<16) | paramers.get_timer0()
                );
        W[6] = (paramers.get_mac_add5() << 8) | paramers.get_mac_add6();
        W[7] = to_uint32_little_endian(
                    paramers.get_gxstat() ^ paramers.get_frame() ^
                    ((paramers.get_mac_add4()<<24) |
                    (paramers.get_mac_add3()<<16) |
                    (paramers.get_mac_add2()<<8 ) |
                    (paramers.get_mac_add1()))
                );
        W[8] = (to_bcd(paramers.get_year())  << 24) |
               (to_bcd(paramers.get_month()) << 16) |
               (to_bcd(paramers.get_day()) << 8) |
                paramers.get_week();
        W[9] = ((to_bcd(paramers.get_hour()) |
               ((12<=paramers.get_hour())<<6)) << 24) |
               (to_bcd(paramers.get_minute()) << 16) |
               (to_bcd(paramers.get_sec()) << 8);
        W[10] = 0x00000000;
        W[11] = 0x00000000;
        W[12] = to_uint32_little_endian(paramers.get_key());
        W[13] = 0x80000000;
        W[14] = 0x00000000;
        W[15] = 0x000001A0;
        for (t = 16; t < 80; t++) {
            W[t] = sha1_circular_shift(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
        }

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for (t = 0; t < 20; t++) {
            temp =  sha1_circular_shift(5, A) +((B & C) | ((~B) & D)) + E + W[t] + K0;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for (t = 20; t < 40; t++) {
            temp = sha1_circular_shift(5, A) + (B ^ C ^ D) + E + W[t] + K1;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for (t = 40; t < 60; t++) {
            temp = sha1_circular_shift(5, A) +
                ((B & C) | (B & D) | (C & D)) + E + W[t] + K2;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for (t = 60; t < 80; t++) {
            temp = sha1_circular_shift(5, A) + (B ^ C ^ D) + E + W[t] + K3;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for(i = 0; i < 32; i+=8) {
            seed |= (((H1+B) >> i) & 0xff) << (24 - i);
        }
        seed <<= 32;
        for(i = 0; i < 32; i+=8) {
            seed |= (((H0+A) >> i) & 0xff) << (24 - i);
        }

        return seed;
    }

};
} // end RNGLib

#endif
<commit_msg>Calc5GenSeedの初期シード生成部分を変更<commit_after>/*
 * Copyright (c) 2014 odan
 * License: MIT License
 */
#ifndef INCLUDED_CALC_5GEN_SEED_HPP
#define INCLUDED_CALC_5GEN_SEED_HPP
#include <cstdint>

namespace RNGLib {
class Calc5GenSeed {
private:
#ifdef _MSC_VER
    static const uint32_t K0 = 0x5a827999;
    static const uint32_t K1 = 0x6ed9eba1;
    static const uint32_t K2 = 0x8f1bbcdc;
    static const uint32_t K3 = 0xca62c1d6;

    static const uint32_t H0 = 0x67452301;
    static const uint32_t H1 = 0xefcdab89;
    static const uint32_t H2 = 0x98badcfe;
    static const uint32_t H3 = 0x10325476;
    static const uint32_t H4 = 0xc3d2e1f0;
    uint32_t W[80];
#else
    static constexpr uint32_t K0 = 0x5a827999;
    static constexpr uint32_t K1 = 0x6ed9eba1;
    static constexpr uint32_t K2 = 0x8f1bbcdc;
    static constexpr uint32_t K3 = 0xca62c1d6;

    static constexpr uint32_t H0 = 0x67452301;
    static constexpr uint32_t H1 = 0xefcdab89;
    static constexpr uint32_t H2 = 0x98badcfe;
    static constexpr uint32_t H3 = 0x10325476;
    static constexpr uint32_t H4 = 0xc3d2e1f0;
    uint32_t W[80];
#endif

    uint32_t to_uint32_little_endian(uint32_t val) const {
        return ((val&0xff)<<24) | (((val>>8)&0xff)<<16) |
            (((val>>16)&0xff)<<8) | ((val>>24)&0xff);
    }

    uint32_t to_bcd(uint32_t val) const {
        return ((val/10)<<4) | (val%10);
    }
    uint32_t sha1_circular_shift(uint32_t bits, uint32_t word) const {
        return ((word << bits) | (word >> (32-bits)));
    }
public:
    template<class T>
    uint64_t operator() (const T& paramers) {
        uint64_t seed = 0;
        uint32_t A, B, C, D, E;
        uint32_t temp;
        uint32_t i,t;
        W[0] = to_uint32_little_endian(paramers.get_nazo1());
        W[1] = to_uint32_little_endian(paramers.get_nazo2());
        W[2] = to_uint32_little_endian(paramers.get_nazo3());
        W[3] = to_uint32_little_endian(paramers.get_nazo4());
        W[4] = to_uint32_little_endian(paramers.get_nazo5());
        W[5] = to_uint32_little_endian(
                    (paramers.get_vcount()<<16) | paramers.get_timer0()
                );
        W[6] = (paramers.get_mac_add5() << 8) | paramers.get_mac_add6();
        W[7] = to_uint32_little_endian(
                    paramers.get_gxstat() ^ paramers.get_frame() ^
                    ((paramers.get_mac_add4()<<24) |
                    (paramers.get_mac_add3()<<16) |
                    (paramers.get_mac_add2()<<8 ) |
                    (paramers.get_mac_add1()))
                );
        W[8] = (to_bcd(paramers.get_year())  << 24) |
               (to_bcd(paramers.get_month()) << 16) |
               (to_bcd(paramers.get_day()) << 8) |
                paramers.get_week();
        W[9] = ((to_bcd(paramers.get_hour()) |
               ((12<=paramers.get_hour())<<6)) << 24) |
               (to_bcd(paramers.get_minute()) << 16) |
               (to_bcd(paramers.get_sec()) << 8);
        W[10] = 0x00000000;
        W[11] = 0x00000000;
        W[12] = to_uint32_little_endian(paramers.get_key());
        W[13] = 0x80000000;
        W[14] = 0x00000000;
        W[15] = 0x000001A0;
        for (t = 16; t < 80; t++) {
            W[t] = sha1_circular_shift(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
        }

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for (t = 0; t < 20; t++) {
            temp =  sha1_circular_shift(5, A) +((B & C) | ((~B) & D)) + E + W[t] + K0;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for (t = 20; t < 40; t++) {
            temp = sha1_circular_shift(5, A) + (B ^ C ^ D) + E + W[t] + K1;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for (t = 40; t < 60; t++) {
            temp = sha1_circular_shift(5, A) +
                ((B & C) | (B & D) | (C & D)) + E + W[t] + K2;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        for (t = 60; t < 80; t++) {
            temp = sha1_circular_shift(5, A) + (B ^ C ^ D) + E + W[t] + K3;
            E = D;
            D = C;
            C = sha1_circular_shift(30, B);
            B = A;
            A = temp;
        }

        seed = to_uint32_little_endian(H1+B);
        seed <<= 32;
        seed |= to_uint32_little_endian(H0+A);

        return seed;
    }

};
} // end RNGLib

#endif
<|endoftext|>


<commit_before>/*
    Crystal Space Windowing System: button class
    Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>

    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; either
    version 2 of the License, or (at your option) any later version.

    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.
*/

#include <string.h>

#define SYSDEF_CASE
#include "cssysdef.h"
#include "csws/cscomp.h"
#include "csws/csapp.h"
#include "csws/csbutton.h"
#include "csws/csstatic.h"
#include "csws/csskin.h"

#define SKIN ((csButtonSkin *)skinslice)

csButton::csButton (csComponent *iParent, int iCommandCode,
  int iButtonStyle, csButtonFrameStyle iFrameStyle) : csComponent (iParent),
  ImageNormal (NULL), ImagePressed (NULL),
  FrameNormal (NULL), FramePressed (NULL), FrameHighlighted (NULL),
  delImages (false), delFrameImages(false),
  CommandCode (iCommandCode), underline_pos (-1),
  ButtonStyle (iButtonStyle), FrameStyle (iFrameStyle),
  ButtonAlpha(0), Pressed (false), Highlighted (false), DrawTextOnHighlightOnly (false)
{
  SetPalette (CSPAL_BUTTON);
  if (ButtonStyle & CSBS_SELECTABLE)
    SetState (CSS_SELECTABLE, true);
  if (FrameStyle == csbfsOblique || FrameStyle == csbfsTextured || FrameStyle == csbfsBitmap)
    SetState (CSS_TRANSPARENT, true);
  id = iCommandCode;
  ApplySkin (GetSkin ());
}

csButton::~csButton ()
{
  FreeBitmaps ();
  FreeFrameBitmaps();
}

void csButton::SetBitmap (csPixmap *iNormal, csPixmap *iPressed,
  bool iDelete)
{
  FreeBitmaps ();
  ImageNormal = iNormal;
  if (iPressed)
    ImagePressed = iPressed;
  else
    ImagePressed = iNormal;
  delImages = iDelete;
  Invalidate ();
}

void csButton::GetBitmap (csPixmap **iNormal, csPixmap **iPressed)
{
  if (iNormal)
    *iNormal = ImageNormal;
  if (iPressed)
    *iPressed = ImagePressed;
}

void csButton::GetFrameBitmaps(csPixmap **iNormal, csPixmap **iPressed, csPixmap **iHighlighted)
{
  if (iNormal)
  	*iNormal = FrameNormal;

  if (iPressed)
  	*iPressed = FramePressed;

  if (iHighlighted)
  	*iHighlighted = FrameHighlighted;
}

void csButton::SetFrameBitmaps(csPixmap *iNormal, csPixmap *iPressed, csPixmap *iHighlighted, bool iDelete)
{
	FreeFrameBitmaps();

	FrameNormal = iNormal;
	if (iPressed)
		FramePressed = iPressed;
	else
		FramePressed = iNormal;

	if (iHighlighted)
		FrameHighlighted = iHighlighted;
	else
		FrameHighlighted = iNormal;

	delFrameImages = iDelete;

	Invalidate();
}

void csButton::SetButtonTexture(csPixmap *iNormal, csPixmap *iPressed, bool iDelete)
{
	FreeFrameBitmaps();

	FrameNormal = iNormal;
	if (iPressed)
		FramePressed = iPressed;
	else
		FramePressed = iNormal;

	FrameHighlighted = NULL;

	delFrameImages = iDelete;

	Invalidate();
}

void csButton::SetAlpha(uint8 iAlpha)
{
	ButtonAlpha=iAlpha;
}

void csButton::SetTextureOrigin(int iOrgX, int iOrgY)
{
 TexOrgX = iOrgX;
 TexOrgY = iOrgY;
}

void
csButton::GetTextureOrigin(int *iOrgX, int *iOrgY)
{
 if (iOrgX)
 	*iOrgX = TexOrgX;

 if (iOrgY)
 	*iOrgY = TexOrgY;
}

void csButton::FreeBitmaps ()
{
  if (delImages)
  {
    if (ImageNormal)
      delete ImageNormal;
    if (ImagePressed && ImagePressed != ImageNormal)
      delete ImagePressed;
  } /* endif */
  delImages = false;
  ImageNormal = NULL;
  ImagePressed = NULL;
}

void csButton::FreeFrameBitmaps ()
{
  if (delFrameImages)
  {
  	if (FramePressed && FramePressed != FrameNormal)
      delete FramePressed;

   	if (FrameHighlighted && FrameHighlighted != FrameNormal)
      delete FrameHighlighted;

    if (FrameNormal)
      delete FrameNormal;
  } /* endif */

  delFrameImages = false;
  FrameNormal = NULL;
  FramePressed = NULL;
  FrameHighlighted = NULL;
}

bool csButton::HandleEvent (iEvent &Event)
{
  switch (Event.Type)
  {
    case csevCommand:
      switch (Event.Command.Code)
      {
        case cscmdAreYouDefault:
          if (GetState (CSS_FOCUSED) || (ButtonStyle & CSBS_DEFAULT))
            Event.Command.Info = this;
          return true;
        case cscmdButtonDeselect:
          if ((ButtonStyle & CSBS_MULTICHOOSE)
           && Pressed)
            SetPressed (false);
          return true;
        case cscmdActivate:
          Event.Command.Info = this;
          Press ();
          return true;
        case cscmdStaticHotKeyEvent:
        {
          iEvent *ev = (iEvent *)Event.Command.Info;
          ev->Key.Code = CSKEY_SPACE;
          return csButton::HandleEvent (*ev);
        }
        case cscmdStaticMouseEvent:
        {
          iEvent *ev = (iEvent *)Event.Command.Info;
          if (app->MouseOwner)
          {
            int dX = 0, dY = 0;
            app->MouseOwner->LocalToGlobal (dX, dY);
            GlobalToLocal (dX, dY);
            // release mouse ownership so that csButton::HandleEvent can capture it
            app->CaptureMouse (NULL);
            if ((ev->Type == csevMouseMove)
             && app->MouseOwner->bound.ContainsRel (ev->Mouse.x, ev->Mouse.y))
              ev->Mouse.x = ev->Mouse.y = 0;
            else
            {
              ev->Mouse.x -= dX;
              ev->Mouse.y -= dY;
            } /* endif */
          } /* endif */
          return csButton::HandleEvent (*ev);
        }
      } /* endswitch */
      break;
    case csevMouseDown:
      switch (Event.Mouse.Button)
      {
        case 1:
          if (GetState (CSS_DISABLED)
           || app->MouseOwner)
            return true;
          app->CaptureMouse (this);
          SetPressed (true);
          if ((ButtonStyle & CSBS_NOMOUSEFOCUS) == 0)
            csComponent::HandleEvent (Event);
          return true;
        case 2:
          if (parent && !GetState (CSS_DISABLED))
            parent->SendCommand (cscmdButtonRightClick, (void *)this);
          return true;
      }
      break;
    case csevMouseUp:
      if (Event.Mouse.Button == 1)
      {
        if (app->MouseOwner == this)
        {
          app->CaptureMouse (NULL);
          if (Pressed)
          {
            if (!(ButtonStyle & CSBS_MULTICHOOSE))
              SetPressed (false);
            Press ();
          }
        }
        return true;
      }
      break;

    case csevMouseMove:
      if ((app->MouseOwner == this)
       && !(ButtonStyle & CSBS_MULTICHOOSE))
      {
        bool inside = bound.ContainsRel (Event.Mouse.x, Event.Mouse.y);
        if (inside != Pressed)
          SetPressed (inside);
        return true;
      } /* endif */
      return true;
      break;

    case csevMouseEnter:
      Highlighted=true;
      if (GetState(CSS_TRANSPARENT))  	   parent->Invalidate(true);
      Invalidate();
    return true;
    break;

    case csevMouseExit:
      Highlighted=false;
      if (GetState(CSS_TRANSPARENT)) 	   parent->Invalidate(true);
      Invalidate();
    return true;
    break;

    case csevKeyDown:
      return HandleKeyPress (Event);
    case csevKeyUp:
      if (app->KeyboardOwner)
        if (((underline_pos >= 0)
          && (UPPERCASE (Event.Key.Char) == UPPERCASE (text [underline_pos])))
         || ((Event.Key.Code == CSKEY_SPACE)
          && (GetState (CSS_FOCUSED))))
        {
          if (!(ButtonStyle & CSBS_MULTICHOOSE))
            SetPressed (false);
          Invalidate ();
          app->CaptureKeyboard (NULL);
          Press ();
          return true;
        }
      return false;
  } /* endswitch */
  return csComponent::HandleEvent (Event);
}

bool csButton::PostHandleEvent (iEvent &Event)
{
  if (parent->GetState (CSS_FOCUSED)
   && GetState (CSS_VISIBLE)
   && (Event.Type == csevKeyDown))
    return HandleKeyPress (Event);
  return csComponent::PostHandleEvent (Event);
}

bool csButton::HandleKeyPress (iEvent &Event)
{
  // Check hot key
  if (!GetState (CSS_DISABLED))
    if (((underline_pos >= 0)
      && (app->KeyboardOwner == NULL)
      && CheckHotKey (Event, text [underline_pos]))
     || ((GetState (CSS_FOCUSED))
      && (Event.Key.Code == CSKEY_SPACE)
      && (Event.Key.Modifiers & CSMASK_FIRST)
      && (!(Event.Key.Modifiers & (CSMASK_ALLSHIFTS - CSMASK_ALT)))))
    {
      if (!app->KeyboardOwner)
        app->CaptureKeyboard (this);
      SetPressed (true);
      if ((ButtonStyle & CSBS_NOKEYBOARDFOCUS) == 0)
        Select ();
      return true;
    }
  return false;
}

void csButton::DeselectNeighbours ()
{
  csComponent *c = this;
  while (((c = c->next) != this)
     && !c->GetState (CSS_GROUP))
    c->SendCommand (cscmdButtonDeselect, this);
  if ((c != this) && (!GetState (CSS_GROUP)))
  {
    c = this;
    while ((c = c->prev) != this)
    {
      c->SendCommand (cscmdButtonDeselect, this);
      if (c->GetState (CSS_GROUP))
        break;
    } /* endwhile */
  } /* endif */
}

void csButton::SetPressed (bool state)
{
  if ((ButtonStyle & CSBS_MULTICHOOSE)
   && state)
    DeselectNeighbours ();

  Pressed = state;
  if (parent)
  {
    parent->SendCommand (Pressed ? cscmdButtonDown : cscmdButtonUp,
      (void *)this);

    if (GetState(CSS_TRANSPARENT)) parent->Invalidate(true);

  }

  Invalidate ();
}

void csButton::Press ()
{
  if (ButtonStyle & CSBS_DISMISS)
    app->Dismiss (CommandCode);
  if (parent && CommandCode)
    parent->SendCommand (CommandCode, (void *)this);
}

void csButton::SetState (int mask, bool enable)
{
  int oldstate = state;
  csComponent::SetState (mask, enable);
  if (((oldstate ^ state) & CSS_FOCUSED)
   || ((oldstate ^ state) & CSS_DISABLED))
  {
    if (((state & CSS_FOCUSED) == 0)
     && (app->KeyboardOwner == this))
    {
      SetPressed (false);
      if (app->KeyboardOwner == this)
        app->CaptureKeyboard (NULL);
    } /* endif */
    if ((state & CSS_DISABLED)
     && (app->MouseOwner))
    {
      if (app->MouseOwner == this)
        app->CaptureMouse (NULL);
      if (Pressed)
        if (!(ButtonStyle & CSBS_MULTICHOOSE))
          SetPressed (false);
    } /* endif */
    Invalidate ();
  }
}

void csButton::SuggestSize (int &w, int &h)
{
  SKIN->SuggestSize (*this, w, h);
}
<commit_msg>Fixed that pesky warning that the constructor initializers would be reordered by changing the initializing order of members in csButton.<commit_after>/*
    Crystal Space Windowing System: button class
    Copyright (C) 1998,1999 by Andrew Zabolotny <bit@eltech.ru>

    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; either
    version 2 of the License, or (at your option) any later version.

    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.
*/

#include <string.h>

#define SYSDEF_CASE
#include "cssysdef.h"
#include "csws/cscomp.h"
#include "csws/csapp.h"
#include "csws/csbutton.h"
#include "csws/csstatic.h"
#include "csws/csskin.h"

#define SKIN ((csButtonSkin *)skinslice)

csButton::csButton (csComponent *iParent, int iCommandCode,
  int iButtonStyle, csButtonFrameStyle iFrameStyle) : csComponent (iParent),
  ImageNormal (NULL), ImagePressed (NULL),
  FrameNormal (NULL), FramePressed (NULL), FrameHighlighted (NULL),
  delImages (false), delFrameImages(false),
  CommandCode (iCommandCode), underline_pos (-1),
  ButtonStyle (iButtonStyle), FrameStyle (iFrameStyle),
  ButtonAlpha(0), DrawTextOnHighlightOnly (false),
  Pressed (false), Highlighted (false)
{
  SetPalette (CSPAL_BUTTON);
  if (ButtonStyle & CSBS_SELECTABLE)
    SetState (CSS_SELECTABLE, true);
  if (FrameStyle == csbfsOblique || FrameStyle == csbfsTextured || FrameStyle == csbfsBitmap)
    SetState (CSS_TRANSPARENT, true);
  id = iCommandCode;
  ApplySkin (GetSkin ());
}

csButton::~csButton ()
{
  FreeBitmaps ();
  FreeFrameBitmaps();
}

void csButton::SetBitmap (csPixmap *iNormal, csPixmap *iPressed,
  bool iDelete)
{
  FreeBitmaps ();
  ImageNormal = iNormal;
  if (iPressed)
    ImagePressed = iPressed;
  else
    ImagePressed = iNormal;
  delImages = iDelete;
  Invalidate ();
}

void csButton::GetBitmap (csPixmap **iNormal, csPixmap **iPressed)
{
  if (iNormal)
    *iNormal = ImageNormal;
  if (iPressed)
    *iPressed = ImagePressed;
}

void csButton::GetFrameBitmaps(csPixmap **iNormal, csPixmap **iPressed, csPixmap **iHighlighted)
{
  if (iNormal)
  	*iNormal = FrameNormal;

  if (iPressed)
  	*iPressed = FramePressed;

  if (iHighlighted)
  	*iHighlighted = FrameHighlighted;
}

void csButton::SetFrameBitmaps(csPixmap *iNormal, csPixmap *iPressed, csPixmap *iHighlighted, bool iDelete)
{
	FreeFrameBitmaps();

	FrameNormal = iNormal;
	if (iPressed)
		FramePressed = iPressed;
	else
		FramePressed = iNormal;

	if (iHighlighted)
		FrameHighlighted = iHighlighted;
	else
		FrameHighlighted = iNormal;

	delFrameImages = iDelete;

	Invalidate();
}

void csButton::SetButtonTexture(csPixmap *iNormal, csPixmap *iPressed, bool iDelete)
{
	FreeFrameBitmaps();

	FrameNormal = iNormal;
	if (iPressed)
		FramePressed = iPressed;
	else
		FramePressed = iNormal;

	FrameHighlighted = NULL;

	delFrameImages = iDelete;

	Invalidate();
}

void csButton::SetAlpha(uint8 iAlpha)
{
	ButtonAlpha=iAlpha;
}

void csButton::SetTextureOrigin(int iOrgX, int iOrgY)
{
 TexOrgX = iOrgX;
 TexOrgY = iOrgY;
}

void
csButton::GetTextureOrigin(int *iOrgX, int *iOrgY)
{
 if (iOrgX)
 	*iOrgX = TexOrgX;

 if (iOrgY)
 	*iOrgY = TexOrgY;
}

void csButton::FreeBitmaps ()
{
  if (delImages)
  {
    if (ImageNormal)
      delete ImageNormal;
    if (ImagePressed && ImagePressed != ImageNormal)
      delete ImagePressed;
  } /* endif */
  delImages = false;
  ImageNormal = NULL;
  ImagePressed = NULL;
}

void csButton::FreeFrameBitmaps ()
{
  if (delFrameImages)
  {
  	if (FramePressed && FramePressed != FrameNormal)
      delete FramePressed;

   	if (FrameHighlighted && FrameHighlighted != FrameNormal)
      delete FrameHighlighted;

    if (FrameNormal)
      delete FrameNormal;
  } /* endif */

  delFrameImages = false;
  FrameNormal = NULL;
  FramePressed = NULL;
  FrameHighlighted = NULL;
}

bool csButton::HandleEvent (iEvent &Event)
{
  switch (Event.Type)
  {
    case csevCommand:
      switch (Event.Command.Code)
      {
        case cscmdAreYouDefault:
          if (GetState (CSS_FOCUSED) || (ButtonStyle & CSBS_DEFAULT))
            Event.Command.Info = this;
          return true;
        case cscmdButtonDeselect:
          if ((ButtonStyle & CSBS_MULTICHOOSE)
           && Pressed)
            SetPressed (false);
          return true;
        case cscmdActivate:
          Event.Command.Info = this;
          Press ();
          return true;
        case cscmdStaticHotKeyEvent:
        {
          iEvent *ev = (iEvent *)Event.Command.Info;
          ev->Key.Code = CSKEY_SPACE;
          return csButton::HandleEvent (*ev);
        }
        case cscmdStaticMouseEvent:
        {
          iEvent *ev = (iEvent *)Event.Command.Info;
          if (app->MouseOwner)
          {
            int dX = 0, dY = 0;
            app->MouseOwner->LocalToGlobal (dX, dY);
            GlobalToLocal (dX, dY);
            // release mouse ownership so that csButton::HandleEvent can capture it
            app->CaptureMouse (NULL);
            if ((ev->Type == csevMouseMove)
             && app->MouseOwner->bound.ContainsRel (ev->Mouse.x, ev->Mouse.y))
              ev->Mouse.x = ev->Mouse.y = 0;
            else
            {
              ev->Mouse.x -= dX;
              ev->Mouse.y -= dY;
            } /* endif */
          } /* endif */
          return csButton::HandleEvent (*ev);
        }
      } /* endswitch */
      break;
    case csevMouseDown:
      switch (Event.Mouse.Button)
      {
        case 1:
          if (GetState (CSS_DISABLED)
           || app->MouseOwner)
            return true;
          app->CaptureMouse (this);
          SetPressed (true);
          if ((ButtonStyle & CSBS_NOMOUSEFOCUS) == 0)
            csComponent::HandleEvent (Event);
          return true;
        case 2:
          if (parent && !GetState (CSS_DISABLED))
            parent->SendCommand (cscmdButtonRightClick, (void *)this);
          return true;
      }
      break;
    case csevMouseUp:
      if (Event.Mouse.Button == 1)
      {
        if (app->MouseOwner == this)
        {
          app->CaptureMouse (NULL);
          if (Pressed)
          {
            if (!(ButtonStyle & CSBS_MULTICHOOSE))
              SetPressed (false);
            Press ();
          }
        }
        return true;
      }
      break;

    case csevMouseMove:
      if ((app->MouseOwner == this)
       && !(ButtonStyle & CSBS_MULTICHOOSE))
      {
        bool inside = bound.ContainsRel (Event.Mouse.x, Event.Mouse.y);
        if (inside != Pressed)
          SetPressed (inside);
        return true;
      } /* endif */
      return true;
      break;

    case csevMouseEnter:
      Highlighted=true;
      if (GetState(CSS_TRANSPARENT))  	   parent->Invalidate(true);
      Invalidate();
    return true;
    break;

    case csevMouseExit:
      Highlighted=false;
      if (GetState(CSS_TRANSPARENT)) 	   parent->Invalidate(true);
      Invalidate();
    return true;
    break;

    case csevKeyDown:
      return HandleKeyPress (Event);
    case csevKeyUp:
      if (app->KeyboardOwner)
        if (((underline_pos >= 0)
          && (UPPERCASE (Event.Key.Char) == UPPERCASE (text [underline_pos])))
         || ((Event.Key.Code == CSKEY_SPACE)
          && (GetState (CSS_FOCUSED))))
        {
          if (!(ButtonStyle & CSBS_MULTICHOOSE))
            SetPressed (false);
          Invalidate ();
          app->CaptureKeyboard (NULL);
          Press ();
          return true;
        }
      return false;
  } /* endswitch */
  return csComponent::HandleEvent (Event);
}

bool csButton::PostHandleEvent (iEvent &Event)
{
  if (parent->GetState (CSS_FOCUSED)
   && GetState (CSS_VISIBLE)
   && (Event.Type == csevKeyDown))
    return HandleKeyPress (Event);
  return csComponent::PostHandleEvent (Event);
}

bool csButton::HandleKeyPress (iEvent &Event)
{
  // Check hot key
  if (!GetState (CSS_DISABLED))
    if (((underline_pos >= 0)
      && (app->KeyboardOwner == NULL)
      && CheckHotKey (Event, text [underline_pos]))
     || ((GetState (CSS_FOCUSED))
      && (Event.Key.Code == CSKEY_SPACE)
      && (Event.Key.Modifiers & CSMASK_FIRST)
      && (!(Event.Key.Modifiers & (CSMASK_ALLSHIFTS - CSMASK_ALT)))))
    {
      if (!app->KeyboardOwner)
        app->CaptureKeyboard (this);
      SetPressed (true);
      if ((ButtonStyle & CSBS_NOKEYBOARDFOCUS) == 0)
        Select ();
      return true;
    }
  return false;
}

void csButton::DeselectNeighbours ()
{
  csComponent *c = this;
  while (((c = c->next) != this)
     && !c->GetState (CSS_GROUP))
    c->SendCommand (cscmdButtonDeselect, this);
  if ((c != this) && (!GetState (CSS_GROUP)))
  {
    c = this;
    while ((c = c->prev) != this)
    {
      c->SendCommand (cscmdButtonDeselect, this);
      if (c->GetState (CSS_GROUP))
        break;
    } /* endwhile */
  } /* endif */
}

void csButton::SetPressed (bool state)
{
  if ((ButtonStyle & CSBS_MULTICHOOSE)
   && state)
    DeselectNeighbours ();

  Pressed = state;
  if (parent)
  {
    parent->SendCommand (Pressed ? cscmdButtonDown : cscmdButtonUp,
      (void *)this);

    if (GetState(CSS_TRANSPARENT)) parent->Invalidate(true);

  }

  Invalidate ();
}

void csButton::Press ()
{
  if (ButtonStyle & CSBS_DISMISS)
    app->Dismiss (CommandCode);
  if (parent && CommandCode)
    parent->SendCommand (CommandCode, (void *)this);
}

void csButton::SetState (int mask, bool enable)
{
  int oldstate = state;
  csComponent::SetState (mask, enable);
  if (((oldstate ^ state) & CSS_FOCUSED)
   || ((oldstate ^ state) & CSS_DISABLED))
  {
    if (((state & CSS_FOCUSED) == 0)
     && (app->KeyboardOwner == this))
    {
      SetPressed (false);
      if (app->KeyboardOwner == this)
        app->CaptureKeyboard (NULL);
    } /* endif */
    if ((state & CSS_DISABLED)
     && (app->MouseOwner))
    {
      if (app->MouseOwner == this)
        app->CaptureMouse (NULL);
      if (Pressed)
        if (!(ButtonStyle & CSBS_MULTICHOOSE))
          SetPressed (false);
    } /* endif */
    Invalidate ();
  }
}

void csButton::SuggestSize (int &w, int &h)
{
  SKIN->SuggestSize (*this, w, h);
}
<|endoftext|>