<commit_before>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <algorithm>
#include <random>

#include <boost/property_tree/json_parser.hpp>

#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/packs.h>
#include <osquery/sql.h>

#include "osquery/core/conversions.h"

namespace pt = boost::property_tree;

namespace osquery {

FLAG(int32,
     pack_refresh_interval,
     3600,
     "Cache expiration for a packs discovery queries");

FLAG(string, pack_delimiter, "_", "Delimiter for pack and query names");

FLAG(int32, schedule_splay_percent, 10, "Percent to splay config times");

FLAG(int32,
     schedule_default_interval,
     3600,
     "Query interval to use if none is provided");

size_t splayValue(size_t original, size_t splayPercent) {
  if (splayPercent <= 0 || splayPercent > 100) {
    return original;
  }

  float percent_to_modify_by = (float)splayPercent / 100;
  size_t possible_difference = original * percent_to_modify_by;
  size_t max_value = original + possible_difference;
  size_t min_value = std::max((size_t)1, original - possible_difference);

  if (max_value == min_value) {
    return max_value;
  }

  std::default_random_engine generator;
  generator.seed(
      std::chrono::high_resolution_clock::now().time_since_epoch().count());
  std::uniform_int_distribution<size_t> distribution(min_value, max_value);
  return distribution(generator);
}

size_t restoreSplayedValue(const std::string& name, size_t interval) {
  // Attempt to restore a previously-calculated splay.
  std::string content;
  getDatabaseValue(kPersistentSettings, "interval." + name, content);
  if (!content.empty()) {
    // This query name existed before, check the last requested interval.
    auto details = osquery::split(content, ":");
    if (details.size() == 2) {
      long last_interval, last_splay;
      if (safeStrtol(details[0], 10, last_interval) &&
          safeStrtol(details[1], 10, last_splay)) {
        if (last_interval == static_cast<long>(interval) && last_splay > 0) {
          // This is a matching interval, use the previous splay.
          return static_cast<size_t>(last_splay);
        }
      }
    }
  }

  // If the splayed interval was not restored from the database.
  auto splay = splayValue(interval, FLAGS_schedule_splay_percent);
  content = std::to_string(interval) + ":" + std::to_string(splay);
  setDatabaseValue(kPersistentSettings, "interval." + name, content);
  return splay;
}

void Pack::initialize(const std::string& name,
                      const std::string& source,
                      const pt::ptree& tree) {
  name_ = name;
  source_ = source;
  discovery_queries_.clear();
  if (tree.count("discovery") > 0) {
    for (const auto& item : tree.get_child("discovery")) {
      discovery_queries_.push_back(item.second.get_value<std::string>());
    }
  }

  discovery_cache_ = std::make_pair<int, bool>(0, false);
  stats_ = {0, 0, 0};

  platform_.clear();
  if (tree.count("platform") > 0) {
    platform_ = tree.get<std::string>("platform", "");
  }

  version_.clear();
  if (tree.count("version") > 0) {
    version_ = tree.get<std::string>("version", "");
  }

  schedule_.clear();
  if (tree.count("queries") == 0) {
    // This pack contained no queries.
    return;
  }

  // If the splay percent is less than 1 reset to a sane estimate.
  if (FLAGS_schedule_splay_percent <= 1) {
    FLAGS_schedule_splay_percent = 10;
  }

  // Iterate the queries (or schedule) and check platform/version/sanity.
  for (const auto& q : tree.get_child("queries")) {
    if (q.second.count("platform")) {
      if (!checkPlatform(q.second.get<std::string>("platform", ""))) {
        continue;
      }
    }

    if (q.second.count("version")) {
      if (!checkVersion(q.second.get<std::string>("version", ""))) {
        continue;
      }
    }

    ScheduledQuery query;
    query.query = q.second.get<std::string>("query", "");
    query.interval = q.second.get("interval", FLAGS_schedule_default_interval);
    if (query.interval <= 0 || query.query.empty()) {
      // Invalid pack query.
      continue;
    }

    query.splayed_interval = restoreSplayedValue(q.first, query.interval);
    query.options["snapshot"] = q.second.get<bool>("snapshot", false);
    query.options["removed"] = q.second.get<bool>("removed", true);
    schedule_[q.first] = query;
  }
}

const std::map<std::string, ScheduledQuery>& Pack::getSchedule() const {
  return schedule_;
}

const std::vector<std::string>& Pack::getDiscoveryQueries() const {
  return discovery_queries_;
}

const PackStats& Pack::getStats() const { return stats_; }

const std::string& Pack::getPlatform() const { return platform_; }

const std::string& Pack::getVersion() const { return version_; }

bool Pack::shouldPackExecute() {
  return checkVersion() && checkPlatform() && checkDiscovery();
}

const std::string& Pack::getName() const { return name_; }

const std::string& Pack::getSource() const { return source_; }

void Pack::setName(const std::string& name) { name_ = name; }

bool Pack::checkPlatform() const { return checkPlatform(platform_); }

bool Pack::checkPlatform(const std::string& platform) const {
  if (platform == "") {
    return true;
  }

#ifdef __linux__
  if (platform.find("linux") != std::string::npos) {
    return true;
  }
#endif

  if (platform.find("any") != std::string::npos ||
      platform.find("all") != std::string::npos) {
    return true;
  }
  return (platform.find(kSDKPlatform) != std::string::npos);
}

bool Pack::checkVersion() const { return checkVersion(version_); }

bool Pack::checkVersion(const std::string& version) const {
  if (version == "") {
    return true;
  }

  auto required_version = split(version, ".");
  auto build_version = split(kSDKVersion, ".");

  size_t index = 0;
  for (const auto& chunk : build_version) {
    if (required_version.size() <= index) {
      return true;
    }
    try {
      if (std::stoi(chunk) < std::stoi(required_version[index])) {
        return false;
      } else if (std::stoi(chunk) > std::stoi(required_version[index])) {
        return true;
      }
    } catch (const std::invalid_argument& e) {
      if (chunk.compare(required_version[index]) < 0) {
        return false;
      }
    }
    index++;
  }
  return true;
}

bool Pack::checkDiscovery() {
  stats_.total++;
  int current = (int)getUnixTime();
  if ((current - discovery_cache_.first) < FLAGS_pack_refresh_interval) {
    stats_.hits++;
    return discovery_cache_.second;
  }

  stats_.misses++;
  discovery_cache_.first = current;
  discovery_cache_.second = true;
  for (const auto& q : discovery_queries_) {
    auto sql = SQL(q);
    if (!sql.ok()) {
      LOG(WARNING) << "Discovery query failed (" << q
                   << "): " << sql.getMessageString();
      discovery_cache_.second = false;
      break;
    }
    if (sql.rows().size() == 0) {
      discovery_cache_.second = false;
      break;
    }
  }
  return discovery_cache_.second;
}
}
<commit_msg>Fix clang-analyzer warning -- Use uint32_t instead of size_t for uniform_int_distribution<commit_after>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <algorithm>
#include <random>

#include <boost/property_tree/json_parser.hpp>

#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/packs.h>
#include <osquery/sql.h>

#include "osquery/core/conversions.h"

namespace pt = boost::property_tree;

namespace osquery {

FLAG(int32,
     pack_refresh_interval,
     3600,
     "Cache expiration for a packs discovery queries");

FLAG(string, pack_delimiter, "_", "Delimiter for pack and query names");

FLAG(int32, schedule_splay_percent, 10, "Percent to splay config times");

FLAG(int32,
     schedule_default_interval,
     3600,
     "Query interval to use if none is provided");

size_t splayValue(size_t original, size_t splayPercent) {
  if (splayPercent <= 0 || splayPercent > 100) {
    return original;
  }

  float percent_to_modify_by = (float)splayPercent / 100;
  size_t possible_difference = original * percent_to_modify_by;
  size_t max_value = original + possible_difference;
  size_t min_value = std::max((size_t)1, original - possible_difference);

  if (max_value == min_value) {
    return max_value;
  }

  std::default_random_engine generator;
  generator.seed(
      std::chrono::high_resolution_clock::now().time_since_epoch().count());
  std::uniform_int_distribution<uint32_t> distribution(min_value, max_value);
  return distribution(generator);
}

size_t restoreSplayedValue(const std::string& name, size_t interval) {
  // Attempt to restore a previously-calculated splay.
  std::string content;
  getDatabaseValue(kPersistentSettings, "interval." + name, content);
  if (!content.empty()) {
    // This query name existed before, check the last requested interval.
    auto details = osquery::split(content, ":");
    if (details.size() == 2) {
      long last_interval, last_splay;
      if (safeStrtol(details[0], 10, last_interval) &&
          safeStrtol(details[1], 10, last_splay)) {
        if (last_interval == static_cast<long>(interval) && last_splay > 0) {
          // This is a matching interval, use the previous splay.
          return static_cast<size_t>(last_splay);
        }
      }
    }
  }

  // If the splayed interval was not restored from the database.
  auto splay = splayValue(interval, FLAGS_schedule_splay_percent);
  content = std::to_string(interval) + ":" + std::to_string(splay);
  setDatabaseValue(kPersistentSettings, "interval." + name, content);
  return splay;
}

void Pack::initialize(const std::string& name,
                      const std::string& source,
                      const pt::ptree& tree) {
  name_ = name;
  source_ = source;
  discovery_queries_.clear();
  if (tree.count("discovery") > 0) {
    for (const auto& item : tree.get_child("discovery")) {
      discovery_queries_.push_back(item.second.get_value<std::string>());
    }
  }

  discovery_cache_ = std::make_pair<int, bool>(0, false);
  stats_ = {0, 0, 0};

  platform_.clear();
  if (tree.count("platform") > 0) {
    platform_ = tree.get<std::string>("platform", "");
  }

  version_.clear();
  if (tree.count("version") > 0) {
    version_ = tree.get<std::string>("version", "");
  }

  schedule_.clear();
  if (tree.count("queries") == 0) {
    // This pack contained no queries.
    return;
  }

  // If the splay percent is less than 1 reset to a sane estimate.
  if (FLAGS_schedule_splay_percent <= 1) {
    FLAGS_schedule_splay_percent = 10;
  }

  // Iterate the queries (or schedule) and check platform/version/sanity.
  for (const auto& q : tree.get_child("queries")) {
    if (q.second.count("platform")) {
      if (!checkPlatform(q.second.get<std::string>("platform", ""))) {
        continue;
      }
    }

    if (q.second.count("version")) {
      if (!checkVersion(q.second.get<std::string>("version", ""))) {
        continue;
      }
    }

    ScheduledQuery query;
    query.query = q.second.get<std::string>("query", "");
    query.interval = q.second.get("interval", FLAGS_schedule_default_interval);
    if (query.interval <= 0 || query.query.empty()) {
      // Invalid pack query.
      continue;
    }

    query.splayed_interval = restoreSplayedValue(q.first, query.interval);
    query.options["snapshot"] = q.second.get<bool>("snapshot", false);
    query.options["removed"] = q.second.get<bool>("removed", true);
    schedule_[q.first] = query;
  }
}

const std::map<std::string, ScheduledQuery>& Pack::getSchedule() const {
  return schedule_;
}

const std::vector<std::string>& Pack::getDiscoveryQueries() const {
  return discovery_queries_;
}

const PackStats& Pack::getStats() const { return stats_; }

const std::string& Pack::getPlatform() const { return platform_; }

const std::string& Pack::getVersion() const { return version_; }

bool Pack::shouldPackExecute() {
  return checkVersion() && checkPlatform() && checkDiscovery();
}

const std::string& Pack::getName() const { return name_; }

const std::string& Pack::getSource() const { return source_; }

void Pack::setName(const std::string& name) { name_ = name; }

bool Pack::checkPlatform() const { return checkPlatform(platform_); }

bool Pack::checkPlatform(const std::string& platform) const {
  if (platform == "") {
    return true;
  }

#ifdef __linux__
  if (platform.find("linux") != std::string::npos) {
    return true;
  }
#endif

  if (platform.find("any") != std::string::npos ||
      platform.find("all") != std::string::npos) {
    return true;
  }
  return (platform.find(kSDKPlatform) != std::string::npos);
}

bool Pack::checkVersion() const { return checkVersion(version_); }

bool Pack::checkVersion(const std::string& version) const {
  if (version == "") {
    return true;
  }

  auto required_version = split(version, ".");
  auto build_version = split(kSDKVersion, ".");

  size_t index = 0;
  for (const auto& chunk : build_version) {
    if (required_version.size() <= index) {
      return true;
    }
    try {
      if (std::stoi(chunk) < std::stoi(required_version[index])) {
        return false;
      } else if (std::stoi(chunk) > std::stoi(required_version[index])) {
        return true;
      }
    } catch (const std::invalid_argument& e) {
      if (chunk.compare(required_version[index]) < 0) {
        return false;
      }
    }
    index++;
  }
  return true;
}

bool Pack::checkDiscovery() {
  stats_.total++;
  int current = (int)getUnixTime();
  if ((current - discovery_cache_.first) < FLAGS_pack_refresh_interval) {
    stats_.hits++;
    return discovery_cache_.second;
  }

  stats_.misses++;
  discovery_cache_.first = current;
  discovery_cache_.second = true;
  for (const auto& q : discovery_queries_) {
    auto sql = SQL(q);
    if (!sql.ok()) {
      LOG(WARNING) << "Discovery query failed (" << q
                   << "): " << sql.getMessageString();
      discovery_cache_.second = false;
      break;
    }
    if (sql.rows().size() == 0) {
      discovery_cache_.second = false;
      break;
    }
  }
  return discovery_cache_.second;
}
}
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "oslmaterial.h"

// appleseed.renderer headers.
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/oslbsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/edf/osledf.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/shadergroup/shadergroup.h"

// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"

using namespace foundation;

namespace renderer
{

namespace
{
    //
    // OSL Material.
    //

    const char* Model = "osl_material";

    class OSLMaterial
      : public Material
    {
      public:
        OSLMaterial(
            const char*                 name,
            const ParamArray&           params)
          : Material(name, params)
        {
            m_inputs.declare("osl_surface", InputFormatEntity, "");
            m_inputs.declare("alpha_map", InputFormatScalar, "");

            m_osl_bsdf = OSLBSDFFactory().create();
            m_osl_edf = OSLEDFFactory().create();
        }

        virtual void release() APPLESEED_OVERRIDE
        {
            delete this;
        }

        virtual const char* get_model() const APPLESEED_OVERRIDE
        {
            return Model;
        }

        virtual bool on_frame_begin(
            const Project&              project,
            const Assembly&             assembly,
            foundation::IAbortSwitch*   abort_switch = 0) APPLESEED_OVERRIDE
        {
            if (!Material::on_frame_begin(project, assembly, abort_switch))
                return false;

            m_shader_group = get_uncached_osl_surface();

            if (m_shader_group)
            {
                m_bsdf = m_osl_bsdf.get();
                m_osl_bsdf->on_frame_begin(project, assembly, abort_switch);

                if (m_shader_group->has_emission())
                {
                    m_edf = m_osl_edf.get();
                    m_osl_edf->on_frame_begin(project, assembly, abort_switch);
                }
            }

            return true;
        }

        virtual void on_frame_end(
            const Project&              project,
            const Assembly&             assembly) APPLESEED_OVERRIDE
        {
            Material::on_frame_end(project, assembly);

            m_osl_bsdf->on_frame_end(project, assembly);

            if (m_shader_group->has_emission())
                m_osl_edf->on_frame_end(project, assembly);

            m_shader_group = 0;
        }

        virtual bool has_osl_surface() const APPLESEED_OVERRIDE
        {
            return get_non_empty(m_params, "osl_surface") != 0;
        }

        virtual bool has_emission() const APPLESEED_OVERRIDE
        {
            if (const ShaderGroup* s = get_uncached_osl_surface())
                return s->has_emission();

            return false;
        }

        virtual const EDF* get_uncached_edf() const APPLESEED_OVERRIDE
        {
            if (has_emission())
                return m_osl_edf.get();

            return 0;
        }

      private:
        auto_release_ptr<BSDF>  m_osl_bsdf;
        auto_release_ptr<EDF>   m_osl_edf;

        virtual const ShaderGroup* get_uncached_osl_surface() const APPLESEED_OVERRIDE
        {
            const ShaderGroup* sg =
                static_cast<const ShaderGroup*>(m_inputs.get_entity("osl_surface"));

            // Skip invalid shader groups.
            if (!sg->valid())
                return 0;

            return sg;
        }
    };
}

//
// OSLMaterialFactory class implementation.
//

const char* OSLMaterialFactory::get_model() const
{
    return "osl_material";
}

Dictionary OSLMaterialFactory::get_model_metadata() const
{
    return
        Dictionary()
            .insert("name", Model)
            .insert("label", "OSL Material");
}

DictionaryArray OSLMaterialFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    add_common_input_metadata(metadata);

    metadata.push_back(
        Dictionary()
            .insert("name", "osl_surface")
            .insert("label", "OSL Surface")
            .insert("type", "entity")
            .insert("entity_types",
                Dictionary()
                    .insert("shader_group", "Shader Groups"))
            .insert("use", "optional"));

    metadata.push_back(
        Dictionary()
            .insert("name", "alpha_map")
            .insert("label", "Alpha Map")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "optional"));

    return metadata;
}

auto_release_ptr<Material> OSLMaterialFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return
        auto_release_ptr<Material>(
            new OSLMaterial(name, params));
}

}   // namespace renderer
<commit_msg>Fixed crash with OSL materials without shaders.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "oslmaterial.h"

// appleseed.renderer headers.
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/bsdf/oslbsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/edf/osledf.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/shadergroup/shadergroup.h"

// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"

using namespace foundation;

namespace renderer
{

namespace
{
    //
    // OSL Material.
    //

    const char* Model = "osl_material";

    class OSLMaterial
      : public Material
    {
      public:
        OSLMaterial(
            const char*                 name,
            const ParamArray&           params)
          : Material(name, params)
        {
            m_inputs.declare("osl_surface", InputFormatEntity, "");
            m_inputs.declare("alpha_map", InputFormatScalar, "");

            m_osl_bsdf = OSLBSDFFactory().create();
            m_osl_edf = OSLEDFFactory().create();
        }

        virtual void release() APPLESEED_OVERRIDE
        {
            delete this;
        }

        virtual const char* get_model() const APPLESEED_OVERRIDE
        {
            return Model;
        }

        virtual bool on_frame_begin(
            const Project&              project,
            const Assembly&             assembly,
            foundation::IAbortSwitch*   abort_switch = 0) APPLESEED_OVERRIDE
        {
            if (!Material::on_frame_begin(project, assembly, abort_switch))
                return false;

            m_shader_group = get_uncached_osl_surface();

            if (m_shader_group)
            {
                m_bsdf = m_osl_bsdf.get();
                m_osl_bsdf->on_frame_begin(project, assembly, abort_switch);

                if (m_shader_group->has_emission())
                {
                    m_edf = m_osl_edf.get();
                    m_osl_edf->on_frame_begin(project, assembly, abort_switch);
                }
            }

            return true;
        }

        virtual void on_frame_end(
            const Project&              project,
            const Assembly&             assembly) APPLESEED_OVERRIDE
        {
            Material::on_frame_end(project, assembly);

            m_osl_bsdf->on_frame_end(project, assembly);

            if (m_shader_group && m_shader_group->has_emission())
                m_osl_edf->on_frame_end(project, assembly);

            m_shader_group = 0;
        }

        virtual bool has_osl_surface() const APPLESEED_OVERRIDE
        {
            return get_non_empty(m_params, "osl_surface") != 0;
        }

        virtual bool has_emission() const APPLESEED_OVERRIDE
        {
            if (const ShaderGroup* s = get_uncached_osl_surface())
                return s->has_emission();

            return false;
        }

        virtual const EDF* get_uncached_edf() const APPLESEED_OVERRIDE
        {
            if (has_emission())
                return m_osl_edf.get();

            return 0;
        }

      private:
        auto_release_ptr<BSDF>  m_osl_bsdf;
        auto_release_ptr<EDF>   m_osl_edf;

        virtual const ShaderGroup* get_uncached_osl_surface() const APPLESEED_OVERRIDE
        {
            const ShaderGroup* sg =
                static_cast<const ShaderGroup*>(m_inputs.get_entity("osl_surface"));

            // Skip invalid shader groups.
            if (sg && sg->valid())
                return sg;

            return 0;
        }
    };
}

//
// OSLMaterialFactory class implementation.
//

const char* OSLMaterialFactory::get_model() const
{
    return "osl_material";
}

Dictionary OSLMaterialFactory::get_model_metadata() const
{
    return
        Dictionary()
            .insert("name", Model)
            .insert("label", "OSL Material");
}

DictionaryArray OSLMaterialFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    add_common_input_metadata(metadata);

    metadata.push_back(
        Dictionary()
            .insert("name", "osl_surface")
            .insert("label", "OSL Surface")
            .insert("type", "entity")
            .insert("entity_types",
                Dictionary()
                    .insert("shader_group", "Shader Groups"))
            .insert("use", "optional"));

    metadata.push_back(
        Dictionary()
            .insert("name", "alpha_map")
            .insert("label", "Alpha Map")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "optional"));

    return metadata;
}

auto_release_ptr<Material> OSLMaterialFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return
        auto_release_ptr<Material>(
            new OSLMaterial(name, params));
}

}   // namespace renderer
<|endoftext|>


<commit_before>/* Brainfuck interpreter using interpreter and composite patterns :) */

#include <exception>
#include <iostream>
#include <list>
#include <deque>
#include <map>
#include <string>
#include <algorithm>
#include <memory>

using namespace std;

struct Data
{
    deque<int> array;
    int ptr;
};

class AbstractExpression
{
    public:
        AbstractExpression() {}
        virtual void interpret(Data &) = 0;
        virtual void add(shared_ptr<AbstractExpression>) {}
        virtual bool isComposite() {return false;}
	virtual void parse(const string &) {}
        virtual ~AbstractExpression() {}
};

class IncrementByte: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.array[data.ptr]++;
        }
};

class DecrementByte: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.array[data.ptr]--;
        }
};

class IncrementPtr: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.ptr++;
            if(data.array.size()==data.ptr) data.array.push_back(0);
        }
};

class DecrementPtr: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.ptr--;
            if(data.ptr<0) throw out_of_range("Negative value of pointer");
        }
};

class Output: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            cout<<char(data.array[data.ptr]);
        }
};

class Input: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            char input;
            cin>>input;
            data.array[data.ptr] = static_cast<char>(input);
        }
};

typedef shared_ptr<AbstractExpression> AbstractExpressionPtr;

class CompositeExpression: public AbstractExpression
{
    protected:
        map<char, AbstractExpressionPtr> expMap;
	deque<char> chars;
        list<AbstractExpressionPtr> expTree;
    public:
        CompositeExpression(): expTree() {
	    chars.push_back('+'); expMap[chars.back()] = AbstractExpressionPtr(new IncrementByte);
            chars.push_back('-'); expMap[chars.back()] = AbstractExpressionPtr(new DecrementByte);
            chars.push_back('>'); expMap[chars.back()] = AbstractExpressionPtr(new IncrementPtr);
            chars.push_back('<'); expMap[chars.back()] = AbstractExpressionPtr(new DecrementPtr);
            chars.push_back('.'); expMap[chars.back()] = AbstractExpressionPtr(new Output);
            chars.push_back(','); expMap[chars.back()] = AbstractExpressionPtr(new Input);
        }

        virtual ~CompositeExpression() {}

        virtual bool isComposite() {return true;}

        virtual void add(AbstractExpressionPtr exp) {expTree.push_back(exp);}

        virtual void parse(const string & code) {
            int skip(0);
            for(int i=0; i<code.size(); i++) {
                if(skip) {
                    if(code[i] == '[') skip++;
                    if(code[i] == ']') skip--;
                    continue;
                }
                if(find(chars.begin(), chars.end(), code[i]) != chars.end()) {
                    this->add(expMap[code[i]]);
                }
                else if (code[i] == '[') {
                    AbstractExpressionPtr expr(new CompositeExpression());
                    expr->parse(code.substr(i+1));
                    this->add(expr);
                    skip = 1;
                }
                else if(code[i]==']') break;
            }
        }

        virtual void interpret(Data &data)
        {
            for(list<AbstractExpressionPtr>::iterator it=expTree.begin(); it!=expTree.end(); it++) {
                if((*it)->isComposite()) {
                    while(data.array[data.ptr])
                        (*it)->interpret(data);
                }
                else {
                    (*it)->interpret(data);
                }
            }
        }
};

int main()
{
    Data data; data.array.assign(1,0); data.ptr = 0;
    string code("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
    //string code(",[.[-],]");
    CompositeExpression parser;
    parser.parse(code);
    parser.interpret(data);
}
<commit_msg>Replace deque by list for chars + remove tab + simplify AbstractExpression<commit_after>/* Brainfuck interpreter using interpreter and composite patterns :) */

#include <exception>
#include <iostream>
#include <list>
#include <deque>
#include <map>
#include <string>
#include <algorithm>
#include <memory>

using namespace std;

struct Data
{
    deque<int> array;
    int ptr;
};

class AbstractExpression
{
    public:
        AbstractExpression() {}
        virtual ~AbstractExpression() {}
        virtual void add(shared_ptr<AbstractExpression>) {}
        virtual bool isComposite() {return false;}
        virtual void interpret(Data &) = 0;
        virtual void parse(const string &) {}
};

class IncrementByte: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.array[data.ptr]++;
        }
};

class DecrementByte: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.array[data.ptr]--;
        }
};

class IncrementPtr: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.ptr++;
            if(data.array.size()==data.ptr) data.array.push_back(0);
        }
};

class DecrementPtr: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            data.ptr--;
            if(data.ptr<0) throw out_of_range("Negative value of pointer");
        }
};

class Output: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            cout<<char(data.array[data.ptr]);
        }
};

class Input: public AbstractExpression
{
    public:
        virtual void interpret(Data &data) {
            char input;
            cin>>input;
            data.array[data.ptr] = static_cast<char>(input);
        }
};

typedef shared_ptr<AbstractExpression> AbstractExpressionPtr;

class CompositeExpression: public AbstractExpression
{
    protected:
        map<char, AbstractExpressionPtr> expMap;
        list<char> chars;
        list<AbstractExpressionPtr> expTree;
    public:
        CompositeExpression(): expTree() {
            chars.push_back('+'); expMap[chars.back()] = AbstractExpressionPtr(new IncrementByte);
            chars.push_back('-'); expMap[chars.back()] = AbstractExpressionPtr(new DecrementByte);
            chars.push_back('>'); expMap[chars.back()] = AbstractExpressionPtr(new IncrementPtr);
            chars.push_back('<'); expMap[chars.back()] = AbstractExpressionPtr(new DecrementPtr);
            chars.push_back('.'); expMap[chars.back()] = AbstractExpressionPtr(new Output);
            chars.push_back(','); expMap[chars.back()] = AbstractExpressionPtr(new Input);
        }

        virtual ~CompositeExpression() {}

        virtual bool isComposite() {return true;}

        virtual void add(AbstractExpressionPtr exp) {expTree.push_back(exp);}

        virtual void parse(const string & code) {
            int skip(0);
            for(int i=0; i<code.size(); i++) {
                if(skip) {
                    if(code[i] == '[') skip++;
                    if(code[i] == ']') skip--;
                    continue;
                }
                if(find(chars.begin(), chars.end(), code[i]) != chars.end()) {
                    this->add(expMap[code[i]]);
                }
                else if (code[i] == '[') {
                    AbstractExpressionPtr expr(new CompositeExpression());
                    expr->parse(code.substr(i+1));
                    this->add(expr);
                    skip = 1;
                }
                else if(code[i]==']') break;
            }
        }

        virtual void interpret(Data &data)
        {
            for(list<AbstractExpressionPtr>::iterator it=expTree.begin(); it!=expTree.end(); it++) {
                if((*it)->isComposite()) {
                    while(data.array[data.ptr])
                        (*it)->interpret(data);
                }
                else {
                    (*it)->interpret(data);
                }
            }
        }
};

int main()
{
    Data data; data.array.assign(1,0); data.ptr = 0;
    string code("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
    //string code(",[.[-],]");
    CompositeExpression parser;
    parser.parse(code);
    parser.interpret(data);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__

#include "base/bitunion.hh"

namespace ArmISA
{
    enum ConditionCode {
        COND_EQ  =   0,
        COND_NE, //  1
        COND_CS, //  2
        COND_CC, //  3
        COND_MI, //  4
        COND_PL, //  5
        COND_VS, //  6
        COND_VC, //  7
        COND_HI, //  8
        COND_LS, //  9
        COND_GE, // 10
        COND_LT, // 11
        COND_GT, // 12
        COND_LE, // 13
        COND_AL, // 14
        COND_UC  // 15
    };

    enum MiscRegIndex {
        MISCREG_CPSR = 0,
        MISCREG_SPSR,
        MISCREG_SPSR_FIQ,
        MISCREG_SPSR_IRQ,
        MISCREG_SPSR_SVC,
        MISCREG_SPSR_MON,
        MISCREG_SPSR_UND,
        MISCREG_SPSR_ABT,
        MISCREG_FPSR,
        MISCREG_FPSID,
        MISCREG_FPSCR,
        MISCREG_FPEXC,

        // CP15 registers
        MISCREG_CP15_START,
        MISCREG_SCTLR = MISCREG_CP15_START,
        MISCREG_DCCISW,
        MISCREG_CP15_UNIMP_START,
        MISCREG_CTR = MISCREG_CP15_UNIMP_START,
        MISCREG_TCMTR,
        MISCREG_MPUIR,
        MISCREG_MPIDR,
        MISCREG_MIDR,
        MISCREG_ID_PFR0,
        MISCREG_ID_PFR1,
        MISCREG_ID_DFR0,
        MISCREG_ID_AFR0,
        MISCREG_ID_MMFR0,
        MISCREG_ID_MMFR1,
        MISCREG_ID_MMFR2,
        MISCREG_ID_MMFR3,
        MISCREG_ID_ISAR0,
        MISCREG_ID_ISAR1,
        MISCREG_ID_ISAR2,
        MISCREG_ID_ISAR3,
        MISCREG_ID_ISAR4,
        MISCREG_ID_ISAR5,
        MISCREG_CCSIDR,
        MISCREG_CLIDR,
        MISCREG_AIDR,
        MISCREG_CSSELR,
        MISCREG_ACTLR,
        MISCREG_CPACR,
        MISCREG_DFSR,
        MISCREG_IFSR,
        MISCREG_ADFSR,
        MISCREG_AIFSR,
        MISCREG_DFAR,
        MISCREG_IFAR,
        MISCREG_DRBAR,
        MISCREG_IRBAR,
        MISCREG_DRSR,
        MISCREG_IRSR,
        MISCREG_DRACR,
        MISCREG_IRACR,
        MISCREG_RGNR,
        MISCREG_ICIALLUIS,
        MISCREG_BPIALLIS,
        MISCREG_ICIALLU,
        MISCREG_ICIMVAU,
        MISCREG_CP15ISB,
        MISCREG_BPIALL,
        MISCREG_BPIMVA,
        MISCREG_DCIMVAC,
        MISCREG_DCISW,
        MISCREG_DCCMVAC,
        MISCREG_MCCSW,
        MISCREG_CP15DSB,
        MISCREG_CP15DMB,
        MISCREG_DCCMVAU,
        MISCREG_DCCIMVAC,
        MISCREG_CONTEXTIDR,
        MISCREG_TPIDRURW,
        MISCREG_TPIDRURO,
        MISCREG_TPIDRPRW,

        MISCREG_CP15_END,

        // Dummy indices
        MISCREG_NOP = MISCREG_CP15_END,
        MISCREG_RAZ,

        NUM_MISCREGS
    };

    MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
                               unsigned crm, unsigned opc2);

    const char * const miscRegName[NUM_MISCREGS] = {
        "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
        "spsr_mon", "spsr_und", "spsr_abt",
        "fpsr", "fpsid", "fpscr", "fpexc",
        "sctlr", "dccisw", "ctr", "tcmtr", "mpuir", "mpidr", "midr",
        "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
        "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
        "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
        "ccsidr", "clidr", "aidr", "csselr", "actlr", "cpacr",
        "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
        "drbar", "irbar", "drsr", "irsr", "dracr", "iracr",
        "rgnr", "icialluis", "bpiallis", "iciallu", "icimvau",
        "cp15isb", "bpiall", "bpimva", "dcimvac", "dcisw", "dccmvac", "mccsw",
        "cp15dsb", "cp15dmb", "dccmvau", "dccimvac",
        "contextidr", "tpidrurw", "tpidruro", "tpidrprw",
        "nop", "raz"
    };

    BitUnion32(CPSR)
        Bitfield<31> n;
        Bitfield<30> z;
        Bitfield<29> c;
        Bitfield<28> v;
        Bitfield<27> q;
        Bitfield<26,25> it1;
        Bitfield<24> j;
        Bitfield<19, 16> ge;
        Bitfield<15,10> it2;
        Bitfield<9> e;
        Bitfield<8> a;
        Bitfield<7> i;
        Bitfield<6> f;
        Bitfield<5> t;
        Bitfield<4, 0> mode;
    EndBitUnion(CPSR)

    // This mask selects bits of the CPSR that actually go in the CondCodes
    // integer register to allow renaming.
    static const uint32_t CondCodesMask = 0xF80F0000;

    // These otherwise unused bits of the PC are used to select a mode
    // like the J and T bits of the CPSR.
    static const Addr PcJBitShift = 33;
    static const Addr PcTBitShift = 34;
    static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
                                   (ULL(1) << PcTBitShift);

    BitUnion32(SCTLR)
        Bitfield<30> te;  // Thumb Exception Enable
        Bitfield<29> afe; // Access flag enable
        Bitfield<28> tre; // TEX Remap bit
        Bitfield<27> nmfi;// Non-maskable fast interrupts enable
        Bitfield<25> ee;  // Exception Endianness bit
        Bitfield<24> ve;  // Interrupt vectors enable
        Bitfield<23> rao1;// Read as one
        Bitfield<22> u;   // Alignment (now unused)
        Bitfield<21> fi;  // Fast interrupts configuration enable
        Bitfield<18> rao2;// Read as one
        Bitfield<17> ha;  // Hardware access flag enable
        Bitfield<16> rao3;// Read as one
        Bitfield<14> rr;  // Round robin cache replacement
        Bitfield<13> v;   // Base address for exception vectors
        Bitfield<12> i;   // instruction cache enable
        Bitfield<11> z;   // branch prediction enable bit
        Bitfield<10> sw;  // Enable swp/swpb
        Bitfield<6,3> rao4;// Read as one
        Bitfield<7>  b;   // Endianness support (unused)
        Bitfield<2>  c;   // Cache enable bit
        Bitfield<1>  a;   // Alignment fault checking
        Bitfield<0>  m;   // MMU enable bit
    EndBitUnion(SCTLR)
};

#endif // __ARCH_ARM_MISCREGS_HH__
<commit_msg>ARM: Allow accesses to the contextidr register.<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__

#include "base/bitunion.hh"

namespace ArmISA
{
    enum ConditionCode {
        COND_EQ  =   0,
        COND_NE, //  1
        COND_CS, //  2
        COND_CC, //  3
        COND_MI, //  4
        COND_PL, //  5
        COND_VS, //  6
        COND_VC, //  7
        COND_HI, //  8
        COND_LS, //  9
        COND_GE, // 10
        COND_LT, // 11
        COND_GT, // 12
        COND_LE, // 13
        COND_AL, // 14
        COND_UC  // 15
    };

    enum MiscRegIndex {
        MISCREG_CPSR = 0,
        MISCREG_SPSR,
        MISCREG_SPSR_FIQ,
        MISCREG_SPSR_IRQ,
        MISCREG_SPSR_SVC,
        MISCREG_SPSR_MON,
        MISCREG_SPSR_UND,
        MISCREG_SPSR_ABT,
        MISCREG_FPSR,
        MISCREG_FPSID,
        MISCREG_FPSCR,
        MISCREG_FPEXC,

        // CP15 registers
        MISCREG_CP15_START,
        MISCREG_SCTLR = MISCREG_CP15_START,
        MISCREG_DCCISW,
        MISCREG_CONTEXTIDR,
        MISCREG_CP15_UNIMP_START,
        MISCREG_CTR = MISCREG_CP15_UNIMP_START,
        MISCREG_TCMTR,
        MISCREG_MPUIR,
        MISCREG_MPIDR,
        MISCREG_MIDR,
        MISCREG_ID_PFR0,
        MISCREG_ID_PFR1,
        MISCREG_ID_DFR0,
        MISCREG_ID_AFR0,
        MISCREG_ID_MMFR0,
        MISCREG_ID_MMFR1,
        MISCREG_ID_MMFR2,
        MISCREG_ID_MMFR3,
        MISCREG_ID_ISAR0,
        MISCREG_ID_ISAR1,
        MISCREG_ID_ISAR2,
        MISCREG_ID_ISAR3,
        MISCREG_ID_ISAR4,
        MISCREG_ID_ISAR5,
        MISCREG_CCSIDR,
        MISCREG_CLIDR,
        MISCREG_AIDR,
        MISCREG_CSSELR,
        MISCREG_ACTLR,
        MISCREG_CPACR,
        MISCREG_DFSR,
        MISCREG_IFSR,
        MISCREG_ADFSR,
        MISCREG_AIFSR,
        MISCREG_DFAR,
        MISCREG_IFAR,
        MISCREG_DRBAR,
        MISCREG_IRBAR,
        MISCREG_DRSR,
        MISCREG_IRSR,
        MISCREG_DRACR,
        MISCREG_IRACR,
        MISCREG_RGNR,
        MISCREG_ICIALLUIS,
        MISCREG_BPIALLIS,
        MISCREG_ICIALLU,
        MISCREG_ICIMVAU,
        MISCREG_CP15ISB,
        MISCREG_BPIALL,
        MISCREG_BPIMVA,
        MISCREG_DCIMVAC,
        MISCREG_DCISW,
        MISCREG_DCCMVAC,
        MISCREG_MCCSW,
        MISCREG_CP15DSB,
        MISCREG_CP15DMB,
        MISCREG_DCCMVAU,
        MISCREG_DCCIMVAC,
        MISCREG_TPIDRURW,
        MISCREG_TPIDRURO,
        MISCREG_TPIDRPRW,

        MISCREG_CP15_END,

        // Dummy indices
        MISCREG_NOP = MISCREG_CP15_END,
        MISCREG_RAZ,

        NUM_MISCREGS
    };

    MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
                               unsigned crm, unsigned opc2);

    const char * const miscRegName[NUM_MISCREGS] = {
        "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
        "spsr_mon", "spsr_und", "spsr_abt",
        "fpsr", "fpsid", "fpscr", "fpexc",
        "sctlr", "dccisw", "contextidr", "ctr", "tcmtr", "mpuir", "mpidr", "midr",
        "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
        "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
        "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
        "ccsidr", "clidr", "aidr", "csselr", "actlr", "cpacr",
        "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
        "drbar", "irbar", "drsr", "irsr", "dracr", "iracr",
        "rgnr", "icialluis", "bpiallis", "iciallu", "icimvau",
        "cp15isb", "bpiall", "bpimva", "dcimvac", "dcisw", "dccmvac", "mccsw",
        "cp15dsb", "cp15dmb", "dccmvau", "dccimvac",
        "tpidrurw", "tpidruro", "tpidrprw",
        "nop", "raz"
    };

    BitUnion32(CPSR)
        Bitfield<31> n;
        Bitfield<30> z;
        Bitfield<29> c;
        Bitfield<28> v;
        Bitfield<27> q;
        Bitfield<26,25> it1;
        Bitfield<24> j;
        Bitfield<19, 16> ge;
        Bitfield<15,10> it2;
        Bitfield<9> e;
        Bitfield<8> a;
        Bitfield<7> i;
        Bitfield<6> f;
        Bitfield<5> t;
        Bitfield<4, 0> mode;
    EndBitUnion(CPSR)

    // This mask selects bits of the CPSR that actually go in the CondCodes
    // integer register to allow renaming.
    static const uint32_t CondCodesMask = 0xF80F0000;

    // These otherwise unused bits of the PC are used to select a mode
    // like the J and T bits of the CPSR.
    static const Addr PcJBitShift = 33;
    static const Addr PcTBitShift = 34;
    static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
                                   (ULL(1) << PcTBitShift);

    BitUnion32(SCTLR)
        Bitfield<30> te;  // Thumb Exception Enable
        Bitfield<29> afe; // Access flag enable
        Bitfield<28> tre; // TEX Remap bit
        Bitfield<27> nmfi;// Non-maskable fast interrupts enable
        Bitfield<25> ee;  // Exception Endianness bit
        Bitfield<24> ve;  // Interrupt vectors enable
        Bitfield<23> rao1;// Read as one
        Bitfield<22> u;   // Alignment (now unused)
        Bitfield<21> fi;  // Fast interrupts configuration enable
        Bitfield<18> rao2;// Read as one
        Bitfield<17> ha;  // Hardware access flag enable
        Bitfield<16> rao3;// Read as one
        Bitfield<14> rr;  // Round robin cache replacement
        Bitfield<13> v;   // Base address for exception vectors
        Bitfield<12> i;   // instruction cache enable
        Bitfield<11> z;   // branch prediction enable bit
        Bitfield<10> sw;  // Enable swp/swpb
        Bitfield<6,3> rao4;// Read as one
        Bitfield<7>  b;   // Endianness support (unused)
        Bitfield<2>  c;   // Cache enable bit
        Bitfield<1>  a;   // Alignment fault checking
        Bitfield<0>  m;   // MMU enable bit
    EndBitUnion(SCTLR)
};

#endif // __ARCH_ARM_MISCREGS_HH__
<|endoftext|>


<commit_before>#include <stdafx.h>
#include "ViewerWindow.h"

const wchar_t* CViewerWindow::ClassName = L"CViewerWindow";
const wchar_t* CViewerWindow::ViewerApplicationName = L"Powerspace Viewer";
const UINT TICK_LENGTH = 10;

CViewerWindow::CViewerWindow( CStage& _stage, CViewport& _viewport, CCanvas& _canvas) :
	windowHeight( 600 ), windowWidth( 800 ), viewport(_viewport), canvas(_canvas),
    handle(nullptr), stage(_stage), scriptEngine(stage)
{
}

CViewerWindow::~CViewerWindow()
{
}

//
//  FUNCTION: RegisterClass()
//
//  PURPOSE: Registers the viewer window class.
//
bool CViewerWindow::RegisterClass()
{
	HBRUSH backgroundBrush = reinterpret_cast<HBRUSH> (::GetStockObject( WHITE_BRUSH ));
	HMODULE instance = GetModuleHandleW( nullptr );

	WNDCLASSEX windowClassInformation;
	windowClassInformation.cbSize = sizeof( WNDCLASSEX );
	windowClassInformation.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
	windowClassInformation.lpfnWndProc = WindowProc;
	windowClassInformation.cbClsExtra = 0;
	windowClassInformation.cbWndExtra = 2 * sizeof( LONG_PTR );
	windowClassInformation.hInstance = instance;
	windowClassInformation.hIcon = LoadIcon( instance, MAKEINTRESOURCE( IDI_SMALL ) );
	windowClassInformation.hCursor = LoadCursor( nullptr, IDC_ARROW );
	windowClassInformation.hbrBackground = backgroundBrush;
	windowClassInformation.lpszMenuName = 0;
	windowClassInformation.lpszClassName = ClassName;
	windowClassInformation.hIconSm = LoadIcon( instance, MAKEINTRESOURCE( IDI_SMALL ) );

	return (::RegisterClassEx( &windowClassInformation ) != 0);
}

//
//  FUNCTION: Create()
//
//  PURPOSE: Creates the viewer window
//
bool CViewerWindow::Create()
{
	HINSTANCE hInstance = GetModuleHandle( nullptr );

	handle = CreateWindowEx( 0, ClassName, ViewerApplicationName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
		windowHeight, windowWidth, nullptr, nullptr, hInstance, this );

	return (handle != 0);
}

//
//  FUNCTION: WindowProc()
//
//  PURPOSE: Main window proc
//
LRESULT CViewerWindow::WindowProc( HWND handle, UINT msg, WPARAM wParam, LPARAM lParam )
{
	if( msg == WM_NCCREATE ) {
		SetWindowLongPtr( handle, 0, reinterpret_cast<LONG_PTR>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams) );

		return DefWindowProc( handle, msg, wParam, lParam );
	}

	CViewerWindow* wndPtr = reinterpret_cast<CViewerWindow*>(GetWindowLongPtr( handle, 0 ));

	switch( msg ) {
	case WM_CREATE:
		wndPtr->onCreate();
		return 0;

    case WM_CLOSE:
		wndPtr->onClose();
        return 0;

	case WM_SIZE:
		wndPtr->onSize();
		return 0;

	case WM_PAINT:
		wndPtr->onPaint();
		return 0;

	case WM_MOUSEMOVE:
		wndPtr->onMouseMove( wParam, lParam );
		return 0;

	case WM_LBUTTONDOWN:
		wndPtr->onMouseClick( msg, wParam, lParam );
		return 0;

	default:
		return ::DefWindowProc( handle, msg, wParam, lParam );
	}
}

void CViewerWindow::onClose()
{
	if( ::MessageBox( handle, L"Really quit?", ViewerApplicationName, MB_OKCANCEL ) == IDOK ) {
		::DestroyWindow( handle );
	}
}

POINT CViewerWindow::getMouseCoords( LPARAM lParam )
{
	POINT mouseCoords;

	mouseCoords.x = LOWORD( lParam );
	mouseCoords.y = HIWORD( lParam );

	return mouseCoords;
}

bool CViewerWindow::pointInBox( TBox box, POINT point )
{
	if( point.x <= box.right &&
		point.x >= box.left &&
		point.y <= box.bottom &&
		point.y >= box.top )
		return true;
	else
		return false;
}

void CViewerWindow::onCreate()
{
	::SetTimer( handle, 1, TICK_LENGTH, nullptr );
}

//
//  FUNCTION: onTimer()
//
//  PURPOSE: HERE WE HANDLE THE ONTICK EVENTS
//
void CViewerWindow::onTimer()
{
//	tickHandler();
}

//
//  FUNCTION: onPaint()
//
//  PURPOSE: repainter
//
void CViewerWindow::onPaint()
{
	PAINTSTRUCT paintStruct;

	HDC hdc = ::BeginPaint( handle, &paintStruct );

	RECT rect;
	::GetClientRect( handle, &rect );

	int winWidth = rect.right - rect.left;
	int winHeight = rect.bottom + rect.left;

	HDC Memhdc = ::CreateCompatibleDC( hdc );

	HBITMAP Membitmap = ::CreateCompatibleBitmap( hdc, winWidth, winHeight );

	::SelectObject( Memhdc, Membitmap );

	::FillRect( Memhdc, &paintStruct.rcPaint, (HBRUSH)COLOR_WINDOW );

    stage.ClipAndDrawObjects( Memhdc );

	BOOL result = ::BitBlt( hdc, 0, 0, winWidth, winHeight, Memhdc, 0, 0, SRCCOPY );
	if( !result ) {
		::MessageBox( handle, L"BitBlt : onPaint() : CViewerWindow", L"Error", MB_ICONERROR );
		PostQuitMessage( NULL );
	}
	::DeleteObject( Membitmap );
	::DeleteDC( Memhdc );

	::EndPaint( handle, &paintStruct );
}

//
//  FUNCTION: onSize()
//
//  PURPOSE: resize handler
//
void CViewerWindow::onSize()
{
	RECT area;
	::GetClientRect( handle, &area );

	HDC tmp = ::GetDC( handle );
	bitmapContext = ::CreateCompatibleDC( tmp );

	bitmapWidth = area.right - area.left + 1;
	bitmapHeight = area.bottom - area.top + 1;

	bitmap = ::CreateCompatibleBitmap( tmp, bitmapWidth, bitmapHeight );
	::SelectObject( bitmapContext, bitmap );

	if( ::SetGraphicsMode( bitmapContext, GM_ADVANCED ) == 0 ) {
		::MessageBox( handle, L"Error", L"Error", MB_ICONERROR | MB_OK );
	}

	::ReleaseDC( handle, tmp );
}

void CViewerWindow::onMouseMove( const WPARAM wParam, const LPARAM lParam )
{
	// TODO: handle mouse moving
	// E.g. mouse is on the object => change the color

	UNREFERENCED_PARAMETER( wParam );
	UNREFERENCED_PARAMETER( lParam );
}

//
//  FUNCTION: onMouseClick()
//
//  PURPOSE: HERE WE HANDLE THE ONCLICK EVENTS
//
void CViewerWindow::onMouseClick( UINT msg, const WPARAM wParam, const LPARAM lParam )
{
    UNREFERENCED_PARAMETER( wParam );
    UNREFERENCED_PARAMETER( msg );

	POINT mouseCoords = getMouseCoords( lParam );

	activeId = -1;

	// handle mouse clicks on objects
    // todo: detect which object was clicked, now all the objects are activated
	for( auto pair : stage.GetObjects() ) {
		TBox curBox = pair.second->GetContainingBox();

		if( pointInBox( curBox, mouseCoords ) ) {
			activeId = pair.second->GetId();
		}
	}

	if( activeId == -1 )
		return;

	//stage.GetObjectById( activeId )->SetColor(RGB(255, 255, 255));

    auto scripts = stage.GetObjectById(activeId)->GetScripts( EventType::EventClick );
    if( !scripts.empty() ) {
        scriptEngine.RunScripts(activeId, scripts);
    }

    RECT rect;
    GetClientRect( handle, &rect );
    InvalidateRect( handle, &rect, false );
}

void CViewerWindow::Show() const
{
	::ShowWindow( handle, SW_MAXIMIZE );
}

HWND CViewerWindow::GetHandle() const
{
	return handle;
}<commit_msg>EventTick support added<commit_after>#include <stdafx.h>
#include "ViewerWindow.h"

const wchar_t* CViewerWindow::ClassName = L"CViewerWindow";
const wchar_t* CViewerWindow::ViewerApplicationName = L"Powerspace Viewer";
const UINT TICK_LENGTH = 10;

CViewerWindow::CViewerWindow( CStage& _stage, CViewport& _viewport, CCanvas& _canvas) :
	windowHeight( 600 ), windowWidth( 800 ), viewport(_viewport), canvas(_canvas),
    handle(nullptr), stage(_stage), scriptEngine(stage)
{
}

CViewerWindow::~CViewerWindow()
{
}

//
//  FUNCTION: RegisterClass()
//
//  PURPOSE: Registers the viewer window class.
//
bool CViewerWindow::RegisterClass()
{
	HBRUSH backgroundBrush = reinterpret_cast<HBRUSH> (::GetStockObject( WHITE_BRUSH ));
	HMODULE instance = GetModuleHandleW( nullptr );

	WNDCLASSEX windowClassInformation;
	windowClassInformation.cbSize = sizeof( WNDCLASSEX );
	windowClassInformation.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
	windowClassInformation.lpfnWndProc = WindowProc;
	windowClassInformation.cbClsExtra = 0;
	windowClassInformation.cbWndExtra = 2 * sizeof( LONG_PTR );
	windowClassInformation.hInstance = instance;
	windowClassInformation.hIcon = LoadIcon( instance, MAKEINTRESOURCE( IDI_SMALL ) );
	windowClassInformation.hCursor = LoadCursor( nullptr, IDC_ARROW );
	windowClassInformation.hbrBackground = backgroundBrush;
	windowClassInformation.lpszMenuName = 0;
	windowClassInformation.lpszClassName = ClassName;
	windowClassInformation.hIconSm = LoadIcon( instance, MAKEINTRESOURCE( IDI_SMALL ) );

	return (::RegisterClassEx( &windowClassInformation ) != 0);
}

//
//  FUNCTION: Create()
//
//  PURPOSE: Creates the viewer window
//
bool CViewerWindow::Create()
{
	HINSTANCE hInstance = GetModuleHandle( nullptr );

	handle = CreateWindowEx( 0, ClassName, ViewerApplicationName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
		windowHeight, windowWidth, nullptr, nullptr, hInstance, this );

	return (handle != 0);
}

//
//  FUNCTION: WindowProc()
//
//  PURPOSE: Main window proc
//
LRESULT CViewerWindow::WindowProc( HWND handle, UINT msg, WPARAM wParam, LPARAM lParam )
{
	if( msg == WM_NCCREATE ) {
		SetWindowLongPtr( handle, 0, reinterpret_cast<LONG_PTR>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams) );

		return DefWindowProc( handle, msg, wParam, lParam );
	}

	CViewerWindow* wndPtr = reinterpret_cast<CViewerWindow*>(GetWindowLongPtr( handle, 0 ));

	switch( msg ) {
	case WM_CREATE:
		wndPtr->onCreate();
		return 0;

    case WM_CLOSE:
		wndPtr->onClose();
        return 0;

	case WM_SIZE:
		wndPtr->onSize();
		return 0;

	case WM_PAINT:
		wndPtr->onPaint();
		return 0;

	case WM_MOUSEMOVE:
		wndPtr->onMouseMove( wParam, lParam );
		return 0;

	case WM_LBUTTONDOWN:
		wndPtr->onMouseClick( msg, wParam, lParam );
		return 0;

	default:
		return ::DefWindowProc( handle, msg, wParam, lParam );
	}
}

void CViewerWindow::onClose()
{
	if( ::MessageBox( handle, L"Really quit?", ViewerApplicationName, MB_OKCANCEL ) == IDOK ) {
		::DestroyWindow( handle );
	}
}

POINT CViewerWindow::getMouseCoords( LPARAM lParam )
{
	POINT mouseCoords;

	mouseCoords.x = LOWORD( lParam );
	mouseCoords.y = HIWORD( lParam );

	return mouseCoords;
}

bool CViewerWindow::pointInBox( TBox box, POINT point )
{
	if( point.x <= box.right &&
		point.x >= box.left &&
		point.y <= box.bottom &&
		point.y >= box.top )
		return true;
	else
		return false;
}

void CViewerWindow::onCreate()
{
	::SetTimer( handle, 1, TICK_LENGTH, nullptr );
}

//
//  FUNCTION: onTimer()
//
//  PURPOSE: HERE WE HANDLE THE ONTICK EVENTS
//
void CViewerWindow::onTimer()
{
	// handle mouse clicks on objects
	// todo: detect which object was clicked, now all the objects are activated
	for( auto pair : stage.GetObjects() ) {
		auto scripts = pair.second->GetScripts( EventType::EventTick );
		if( !scripts.empty() ) {
			scriptEngine.RunScripts( activeId, scripts );
		}
	}

	RECT rect;
	GetClientRect( handle, &rect );
	InvalidateRect( handle, &rect, false );
}

//
//  FUNCTION: onPaint()
//
//  PURPOSE: repainter
//
void CViewerWindow::onPaint()
{
	PAINTSTRUCT paintStruct;

	HDC hdc = ::BeginPaint( handle, &paintStruct );

	RECT rect;
	::GetClientRect( handle, &rect );

	int winWidth = rect.right - rect.left;
	int winHeight = rect.bottom + rect.left;

	HDC Memhdc = ::CreateCompatibleDC( hdc );

	HBITMAP Membitmap = ::CreateCompatibleBitmap( hdc, winWidth, winHeight );

	::SelectObject( Memhdc, Membitmap );

	::FillRect( Memhdc, &paintStruct.rcPaint, (HBRUSH)COLOR_WINDOW );

    stage.ClipAndDrawObjects( Memhdc );

	BOOL result = ::BitBlt( hdc, 0, 0, winWidth, winHeight, Memhdc, 0, 0, SRCCOPY );
	if( !result ) {
		::MessageBox( handle, L"BitBlt : onPaint() : CViewerWindow", L"Error", MB_ICONERROR );
		PostQuitMessage( NULL );
	}
	::DeleteObject( Membitmap );
	::DeleteDC( Memhdc );

	::EndPaint( handle, &paintStruct );
}

//
//  FUNCTION: onSize()
//
//  PURPOSE: resize handler
//
void CViewerWindow::onSize()
{
	RECT area;
	::GetClientRect( handle, &area );

	HDC tmp = ::GetDC( handle );
	bitmapContext = ::CreateCompatibleDC( tmp );

	bitmapWidth = area.right - area.left + 1;
	bitmapHeight = area.bottom - area.top + 1;

	bitmap = ::CreateCompatibleBitmap( tmp, bitmapWidth, bitmapHeight );
	::SelectObject( bitmapContext, bitmap );

	if( ::SetGraphicsMode( bitmapContext, GM_ADVANCED ) == 0 ) {
		::MessageBox( handle, L"Error", L"Error", MB_ICONERROR | MB_OK );
	}

	::ReleaseDC( handle, tmp );
}

void CViewerWindow::onMouseMove( const WPARAM wParam, const LPARAM lParam )
{
	// TODO: handle mouse moving
	// E.g. mouse is on the object => change the color

	UNREFERENCED_PARAMETER( wParam );
	UNREFERENCED_PARAMETER( lParam );
}

//
//  FUNCTION: onMouseClick()
//
//  PURPOSE: HERE WE HANDLE THE ONCLICK EVENTS
//
void CViewerWindow::onMouseClick( UINT msg, const WPARAM wParam, const LPARAM lParam )
{
    UNREFERENCED_PARAMETER( wParam );
    UNREFERENCED_PARAMETER( msg );

	POINT mouseCoords = getMouseCoords( lParam );

	activeId = -1;

	// handle mouse clicks on objects
    // todo: detect which object was clicked, now all the objects are activated
	for( auto pair : stage.GetObjects() ) {
		TBox curBox = pair.second->GetContainingBox();

		if( pointInBox( curBox, mouseCoords ) ) {
			activeId = pair.second->GetId();
		}
	}

	if( activeId == -1 )
		return;

	//stage.GetObjectById( activeId )->SetColor(RGB(255, 255, 255));

    auto scripts = stage.GetObjectById(activeId)->GetScripts( EventType::EventClick );
    if( !scripts.empty() ) {
        scriptEngine.RunScripts(activeId, scripts);
    }

    RECT rect;
    GetClientRect( handle, &rect );
    InvalidateRect( handle, &rect, false );
}

void CViewerWindow::Show() const
{
	::ShowWindow( handle, SW_MAXIMIZE );
}

HWND CViewerWindow::GetHandle() const
{
	return handle;
}<|endoftext|>


<commit_before>/*
    This file is part of libkcal.
    Copyright (c) 1998 Preston Brown
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    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; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <typeinfo>
#include <stdlib.h>

#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>

#include <kdebug.h>
#include <klocale.h>
#include <kurl.h>

#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "event.h"
#include "todo.h"
#include "journal.h"
#include "filestorage.h"

#include <kresources/configwidget.h>

#include "resourcelocalconfig.h"

#include "resourcelocal.h"

using namespace KCal;

extern "C"
{
  void *init_kcal_local()
  {
    return new KRES::PluginFactory<ResourceLocal,ResourceLocalConfig>();
  }
}

ResourceLocal::ResourceLocal( const KConfig* config )
  : ResourceCalendar( config )
{
  if ( config ) {
    QString url = config->readEntry( "CalendarURL" );
    mURL = KURL( url );

    QString format = config->readEntry( "Format" );
    if ( format == "ical" )
      mFormat = new ICalFormat();
    else if ( format == "vcal" )
      mFormat = new VCalFormat();
    else {
      mFormat = new ICalFormat();
    }
  } else {
    mURL = KURL();
    mFormat = new ICalFormat();
  }
  init();
}

ResourceLocal::ResourceLocal( const QString& fileName )
  : ResourceCalendar( 0 )
{
  mURL = KURL( fileName );
  mFormat = new ICalFormat();
  init();
}

void ResourceLocal::writeConfig( KConfig* config )
{
  kdDebug() << "ResourceLocal::writeConfig()" << endl;

  ResourceCalendar::writeConfig( config );
  config->writeEntry( "CalendarURL", mURL.prettyURL() );
  QString typeID = typeid( *mFormat ).name();

  if ( typeid( *mFormat ) == typeid( ICalFormat ) )
    config->writeEntry( "Format", "ical" );
  else if ( typeid( *mFormat ) == typeid( VCalFormat ) ) // if ( typeID == "ICalFormat" )
    config->writeEntry( "Format", "vcal" );
  else
    kdDebug() << "ERROR: Unknown format type" << endl;
}

void ResourceLocal::init()
{
  setType( "file" );

  mOpen = false;

  connect( &mDirWatch, SIGNAL( dirty( const QString & ) ),
           SLOT( reload() ) );
  connect( &mDirWatch, SIGNAL( created( const QString & ) ),
           SLOT( reload() ) );
  connect( &mDirWatch, SIGNAL( deleted( const QString & ) ),
           SLOT( reload() ) );

  mDirWatch.addFile( mURL.path() );
  mDirWatch.startScan();
}

ResourceLocal::~ResourceLocal()
{
  close();
}

bool ResourceLocal::doOpen()
{
  kdDebug(5800) << "Opening resource " << resourceName() << " with URL " << mURL.prettyURL() << endl;

  mOpen = true;

  return true;
}

bool ResourceLocal::load()
{
  if ( !mOpen ) return true;

  return mCalendar.load( mURL.path() );
}

bool ResourceLocal::save()
{
  if ( !mOpen ) return true;

  return mCalendar.save( mURL.path() );
}

void ResourceLocal::reload()
{
  if ( !mOpen ) return;

  mCalendar.close();
  mCalendar.load( mURL.path() );

  emit resourceChanged( this );
}

void ResourceLocal::doClose()
{
  if ( !mOpen ) return;

  mCalendar.close();
  mOpen = false;
}

bool ResourceLocal::addEvent(Event *event)
{
  return mCalendar.addEvent( event );
}

// probably not really efficient, but...it works for now.
void ResourceLocal::deleteEvent(Event *event)
{
  kdDebug(5800) << "ResourceLocal::deleteEvent" << endl;

  mCalendar.deleteEvent( event );
}

Event *ResourceLocal::event( const QString &uid )
{
  return mCalendar.event( uid );
}

QPtrList<Event> ResourceLocal::rawEventsForDate(const QDate &qd, bool sorted)
{
  return mCalendar.rawEventsForDate( qd, sorted );
}

QPtrList<Event> ResourceLocal::rawEvents( const QDate &start, const QDate &end,
                                          bool inclusive )
{
  return mCalendar.rawEvents( start, end, inclusive );
}

QPtrList<Event> ResourceLocal::rawEventsForDate(const QDateTime &qdt)
{
  return mCalendar.rawEventsForDate( qdt.date() );
}

QPtrList<Event> ResourceLocal::rawEvents()
{
  return mCalendar.rawEvents();
}

bool ResourceLocal::addTodo(Todo *todo)
{
  return mCalendar.addTodo( todo );
}

void ResourceLocal::deleteTodo(Todo *todo)
{
  mCalendar.deleteTodo( todo );
}

QPtrList<Todo> ResourceLocal::rawTodos()
{
  return mCalendar.rawTodos();
}

Todo *ResourceLocal::todo( const QString &uid )
{
  return mCalendar.todo( uid );
}

QPtrList<Todo> ResourceLocal::todos( const QDate &date )
{
  return mCalendar.todos( date );
}

bool ResourceLocal::addJournal(Journal *journal)
{
  kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;

  return mCalendar.addJournal( journal );
}

Journal *ResourceLocal::journal(const QDate &date)
{
//  kdDebug(5800) << "ResourceLocal::journal() " << date.toString() << endl;

  return mCalendar.journal( date );
}

Journal *ResourceLocal::journal(const QString &uid)
{
  return mCalendar.journal( uid );
}

QPtrList<Journal> ResourceLocal::journals()
{
  return mCalendar.journals();
}

Alarm::List ResourceLocal::alarmsTo( const QDateTime &to )
{
  return mCalendar.alarmsTo( to );
}

Alarm::List ResourceLocal::alarms( const QDateTime &from, const QDateTime &to )
{
//  kdDebug(5800) << "ResourceLocal::alarms(" << from.toString() << " - " << to.toString() << ")\n";

  return mCalendar.alarms( from, to );
}

void ResourceLocal::update(IncidenceBase *)
{
}

void ResourceLocal::dump() const
{
  ResourceCalendar::dump();
  kdDebug(5800) << "  Url: " << mURL.url() << endl;
}

#include "resourcelocal.moc"
<commit_msg>Fix name of init function.<commit_after>/*
    This file is part of libkcal.
    Copyright (c) 1998 Preston Brown
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    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; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <typeinfo>
#include <stdlib.h>

#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>

#include <kdebug.h>
#include <klocale.h>
#include <kurl.h>

#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "event.h"
#include "todo.h"
#include "journal.h"
#include "filestorage.h"

#include <kresources/configwidget.h>

#include "resourcelocalconfig.h"

#include "resourcelocal.h"

using namespace KCal;

extern "C"
{
  void *init_libkcal()
  {
    return new KRES::PluginFactory<ResourceLocal,ResourceLocalConfig>();
  }
}

ResourceLocal::ResourceLocal( const KConfig* config )
  : ResourceCalendar( config )
{
  if ( config ) {
    QString url = config->readEntry( "CalendarURL" );
    mURL = KURL( url );

    QString format = config->readEntry( "Format" );
    if ( format == "ical" )
      mFormat = new ICalFormat();
    else if ( format == "vcal" )
      mFormat = new VCalFormat();
    else {
      mFormat = new ICalFormat();
    }
  } else {
    mURL = KURL();
    mFormat = new ICalFormat();
  }
  init();
}

ResourceLocal::ResourceLocal( const QString& fileName )
  : ResourceCalendar( 0 )
{
  mURL = KURL( fileName );
  mFormat = new ICalFormat();
  init();
}

void ResourceLocal::writeConfig( KConfig* config )
{
  kdDebug() << "ResourceLocal::writeConfig()" << endl;

  ResourceCalendar::writeConfig( config );
  config->writeEntry( "CalendarURL", mURL.prettyURL() );
  QString typeID = typeid( *mFormat ).name();

  if ( typeid( *mFormat ) == typeid( ICalFormat ) )
    config->writeEntry( "Format", "ical" );
  else if ( typeid( *mFormat ) == typeid( VCalFormat ) ) // if ( typeID == "ICalFormat" )
    config->writeEntry( "Format", "vcal" );
  else
    kdDebug() << "ERROR: Unknown format type" << endl;
}

void ResourceLocal::init()
{
  setType( "file" );

  mOpen = false;

  connect( &mDirWatch, SIGNAL( dirty( const QString & ) ),
           SLOT( reload() ) );
  connect( &mDirWatch, SIGNAL( created( const QString & ) ),
           SLOT( reload() ) );
  connect( &mDirWatch, SIGNAL( deleted( const QString & ) ),
           SLOT( reload() ) );

  mDirWatch.addFile( mURL.path() );
  mDirWatch.startScan();
}

ResourceLocal::~ResourceLocal()
{
  close();
}

bool ResourceLocal::doOpen()
{
  kdDebug(5800) << "Opening resource " << resourceName() << " with URL " << mURL.prettyURL() << endl;

  mOpen = true;

  return true;
}

bool ResourceLocal::load()
{
  if ( !mOpen ) return true;

  return mCalendar.load( mURL.path() );
}

bool ResourceLocal::save()
{
  if ( !mOpen ) return true;

  return mCalendar.save( mURL.path() );
}

void ResourceLocal::reload()
{
  if ( !mOpen ) return;

  mCalendar.close();
  mCalendar.load( mURL.path() );

  emit resourceChanged( this );
}

void ResourceLocal::doClose()
{
  if ( !mOpen ) return;

  mCalendar.close();
  mOpen = false;
}

bool ResourceLocal::addEvent(Event *event)
{
  return mCalendar.addEvent( event );
}

// probably not really efficient, but...it works for now.
void ResourceLocal::deleteEvent(Event *event)
{
  kdDebug(5800) << "ResourceLocal::deleteEvent" << endl;

  mCalendar.deleteEvent( event );
}

Event *ResourceLocal::event( const QString &uid )
{
  return mCalendar.event( uid );
}

QPtrList<Event> ResourceLocal::rawEventsForDate(const QDate &qd, bool sorted)
{
  return mCalendar.rawEventsForDate( qd, sorted );
}

QPtrList<Event> ResourceLocal::rawEvents( const QDate &start, const QDate &end,
                                          bool inclusive )
{
  return mCalendar.rawEvents( start, end, inclusive );
}

QPtrList<Event> ResourceLocal::rawEventsForDate(const QDateTime &qdt)
{
  return mCalendar.rawEventsForDate( qdt.date() );
}

QPtrList<Event> ResourceLocal::rawEvents()
{
  return mCalendar.rawEvents();
}

bool ResourceLocal::addTodo(Todo *todo)
{
  return mCalendar.addTodo( todo );
}

void ResourceLocal::deleteTodo(Todo *todo)
{
  mCalendar.deleteTodo( todo );
}

QPtrList<Todo> ResourceLocal::rawTodos()
{
  return mCalendar.rawTodos();
}

Todo *ResourceLocal::todo( const QString &uid )
{
  return mCalendar.todo( uid );
}

QPtrList<Todo> ResourceLocal::todos( const QDate &date )
{
  return mCalendar.todos( date );
}

bool ResourceLocal::addJournal(Journal *journal)
{
  kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;

  return mCalendar.addJournal( journal );
}

Journal *ResourceLocal::journal(const QDate &date)
{
//  kdDebug(5800) << "ResourceLocal::journal() " << date.toString() << endl;

  return mCalendar.journal( date );
}

Journal *ResourceLocal::journal(const QString &uid)
{
  return mCalendar.journal( uid );
}

QPtrList<Journal> ResourceLocal::journals()
{
  return mCalendar.journals();
}

Alarm::List ResourceLocal::alarmsTo( const QDateTime &to )
{
  return mCalendar.alarmsTo( to );
}

Alarm::List ResourceLocal::alarms( const QDateTime &from, const QDateTime &to )
{
//  kdDebug(5800) << "ResourceLocal::alarms(" << from.toString() << " - " << to.toString() << ")\n";

  return mCalendar.alarms( from, to );
}

void ResourceLocal::update(IncidenceBase *)
{
}

void ResourceLocal::dump() const
{
  ResourceCalendar::dump();
  kdDebug(5800) << "  Url: " << mURL.url() << endl;
}

#include "resourcelocal.moc"
<|endoftext|>


<commit_before>/* Copyright (C) 2000 MySQL AB

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
  This is a replacement of new/delete operators to be used when compiling
  with gcc 3.0.x to avoid including libstdc++
*/

#ifdef USE_MYSYS_NEW

#include "mysys_priv.h"

void *operator new (size_t sz)
{
  return (void *) malloc (sz ? sz : 1);
}

void *operator new[] (size_t sz)
{
  return (void *) malloc (sz ? sz : 1);
}

void operator delete (void *ptr)
{
  if (ptr)
    free(ptr);
}

void operator delete[] (void *ptr) throw ()
{
  if (ptr)
    free(ptr);
}

#endif /* USE_MYSYS_NEW */

<commit_msg>reverted fixed in 4.0 properly<commit_after>/* Copyright (C) 2000 MySQL AB

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
  This is a replacement of new/delete operators to be used when compiling
  with gcc 3.0.x to avoid including libstdc++
*/

#include "mysys_priv.h"

#ifdef USE_MYSYS_NEW

void *operator new (size_t sz)
{
  return (void *) malloc (sz ? sz : 1);
}

void *operator new[] (size_t sz)
{
  return (void *) malloc (sz ? sz : 1);
}

void operator delete (void *ptr)
{
  if (ptr)
    free(ptr);
}

void operator delete[] (void *ptr) throw ()
{
  if (ptr)
    free(ptr);
}

#endif /* USE_MYSYS_NEW */

<|endoftext|>


<commit_before>// clang++ -mcpu=cortex-a57 -O2 repro.cc

#include <vector>
#include <time.h>
#include <sched.h>

static inline double millis_since_boot() {
  struct timespec t;
  clock_gettime(CLOCK_BOOTTIME, &t);
  return t.tv_sec * 1000.0 + t.tv_nsec * 1e-6;
}

int set_realtime_priority(int level) {
  long tid = getpid();

  // should match python using chrt
  struct sched_param sa;
  memset(&sa, 0, sizeof(sa));
  sa.sched_priority = level;
  return sched_setscheduler(tid, SCHED_FIFO, &sa);
}

#define MODEL_WIDTH 320
#define MODEL_HEIGHT 640
#define input_lambda(x) (x - 128.f) * 0.0078125f

template <class T>
static inline T *get_buffer(std::vector<T> &buf, const size_t size) {
  if (buf.size() < size) {
    buf.resize(size);
  }
  return buf.data();
}

void inner(uint8_t *resized_buf, float *net_input_buf) {
  int resized_width = MODEL_WIDTH;
  int resized_height = MODEL_HEIGHT;

  // one shot conversion, O(n) anyway
  // yuvframe2tensor, normalize
  for (int r = 0; r < MODEL_HEIGHT/2; r++) {
    for (int c = 0; c < MODEL_WIDTH/2; c++) {
      // Y_ul
      net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]);
      // Y_ur
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]);
      // Y_dl
      net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]);
      // Y_dr
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]);
      // U
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]);
      // V
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]);
    }
  }
}

float trial() {
  std::vector<uint8_t> vec_resized_buf;
  std::vector<float> vec_net_input_buf;

  int resized_width = MODEL_WIDTH;
  int resized_height = MODEL_HEIGHT;
  uint8_t *resized_buf = get_buffer(vec_resized_buf, resized_width*resized_height*3/2);

  int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v
  float *net_input_buf = get_buffer(vec_net_input_buf, yuv_buf_len);

  float avg = 0.0;
  for (int i = 0; i < 20; i++) {
    __builtin___clear_cache((char*)resized_buf, (char*)resized_buf + (resized_width*resized_height*3/2));
    __builtin___clear_cache((char*)net_input_buf, (char*)net_input_buf + yuv_buf_len);

    double s4 = millis_since_boot();
    inner(resized_buf, net_input_buf);
    double s5 = millis_since_boot();
    avg += s5-s4;
  }

  avg /= 20;
  if (avg > 5) {
    printf("HIT %f\n", avg);
    printf("BAD\n");

    for (int i = 0; i < 200; i++) {
      __builtin___clear_cache((char*)resized_buf, (char*)resized_buf + (resized_width*resized_height*3/2));
      __builtin___clear_cache((char*)net_input_buf, (char*)net_input_buf + yuv_buf_len);

      double s4 = millis_since_boot();
      inner(resized_buf, net_input_buf);
      double s5 = millis_since_boot();
      printf("%.2f   ", s5-s4);
    }
    printf("\n");

    exit(0);
  }
  return avg;
}

int main() {
  // the realtime priority seems to be what breaks it
  set_realtime_priority(51);

  while (1) {
    float ret = trial();
    printf("got %f\n", ret);
  }
}

<commit_msg>simpler repro, no vector required<commit_after>// clang++ -mcpu=cortex-a57 -O2 repro.cc

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sched.h>

static inline double millis_since_boot() {
  struct timespec t;
  clock_gettime(CLOCK_BOOTTIME, &t);
  return t.tv_sec * 1000.0 + t.tv_nsec * 1e-6;
}

int set_realtime_priority(int level) {
  long tid = getpid();

  // should match python using chrt
  struct sched_param sa;
  memset(&sa, 0, sizeof(sa));
  sa.sched_priority = level;
  return sched_setscheduler(tid, SCHED_FIFO, &sa);
}

#define MODEL_WIDTH 320
#define MODEL_HEIGHT 640
#define input_lambda(x) (x - 128.f) * 0.0078125f

void inner(uint8_t *resized_buf, float *net_input_buf) {
  int resized_width = MODEL_WIDTH;
  int resized_height = MODEL_HEIGHT;

  // one shot conversion, O(n) anyway
  // yuvframe2tensor, normalize
  for (int r = 0; r < MODEL_HEIGHT/2; r++) {
    for (int c = 0; c < MODEL_WIDTH/2; c++) {
      // Y_ul
      net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]);
      // Y_ur
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]);
      // Y_dl
      net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]);
      // Y_dr
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]);
      // U
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]);
      // V
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]);
    }
  }
}

float trial() {
  int resized_width = MODEL_WIDTH;
  int resized_height = MODEL_HEIGHT;

  int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v

  uint8_t *resized_buf = (uint8_t*)malloc(resized_width*resized_height*3/2);
  float *net_input_buf = (float*)malloc(yuv_buf_len*sizeof(float));

  printf("allocate -- %p 0x%x -- %p 0x%lx\n", resized_buf, resized_width*resized_height*3/2, net_input_buf, yuv_buf_len*sizeof(float));

  float avg = 0.0;
  for (int i = 0; i < 20; i++) {
    __builtin___clear_cache((char*)resized_buf, (char*)resized_buf + (resized_width*resized_height*3/2));
    __builtin___clear_cache((char*)net_input_buf, (char*)net_input_buf + yuv_buf_len);

    double s4 = millis_since_boot();
    inner(resized_buf, net_input_buf);
    double s5 = millis_since_boot();
    avg += s5-s4;
  }

  avg /= 20;
  if (avg > 5) {
    printf("HIT %f\n", avg);
    printf("BAD\n");

    for (int i = 0; i < 200; i++) {
      __builtin___clear_cache((char*)resized_buf, (char*)resized_buf + (resized_width*resized_height*3/2));
      __builtin___clear_cache((char*)net_input_buf, (char*)net_input_buf + yuv_buf_len);

      double s4 = millis_since_boot();
      inner(resized_buf, net_input_buf);
      double s5 = millis_since_boot();
      printf("%.2f   ", s5-s4);
    }
    printf("\n");

    exit(0);
  }

  // don't free
  //free(resized_buf);
  //free(net_input_buf);

  return avg;
}

int main() {
  // the realtime priority seems to be what breaks it
  // nope, breaks without it too
  //set_realtime_priority(51);

  while (1) {
    float ret = trial();
    printf("got %f\n", ret);
  }
}

<|endoftext|>