<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>

#include "sqlite3.h"

using namespace flusspferd;

// Put everything in an anon-namespace so typeid wont clash ever.
namespace {

void raise_sqlite_error(sqlite3* db);

///////////////////////////
// Classes
///////////////////////////

class sqlite3 : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    static char const *full_name() { return "SQLite3"; }
    typedef boost::mpl::bool_<true> constructible;
    static char const *constructor_name() { return "SQLite3"; }
    static void augment_constructor(object &ctor);
    static object create_prototype();
  };

  sqlite3(object const &obj, call_context &x);
  ~sqlite3();

protected:
  //void trace(tracer &);

private: // JS methods
  ::sqlite3 *db;

  void close();
  void cursor(call_context &x);
};

class sqlite3_cursor : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    typedef boost::mpl::bool_<false> constructible;
    static char const *full_name() { return "SQLite3.Cursor"; }
    static char const* constructor_name() { return "Cursor"; }
    static object create_prototype();
  };

  sqlite3_cursor(object const &obj, sqlite3_stmt *sth);
  ~sqlite3_cursor();

private:
  sqlite3_stmt *sth;
private: // JS methods
  void finish();
  void reset();
  object next();
  void bind(call_context &x);
};

///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
  return load_class<sqlite3>(container);
}

///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
  // Set static properties on the constructor
  ctor.define_property("version", SQLITE_VERSION_NUMBER,
      object::read_only_property | object::permanent_property);
  ctor.define_property("versionStr", string(SQLITE_VERSION),
      object::read_only_property | object::permanent_property);

  load_class<sqlite3_cursor>(ctor);
}

///////////////////////////
object sqlite3::class_info::create_prototype()
{
  object proto = create_object();

  create_native_method(proto, "cursor", 1);
  create_native_method(proto, "close", 0);
  return proto;
}

///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
  : native_object_base(obj),
    db(NULL)
{
  if (x.arg.size() == 0)
    throw exception ("SQLite3 requires more than 0 arguments");

  string dsn = x.arg[0];

  // TODO: pull arguments from 2nd/options argument
  if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
    if (db)
      raise_sqlite_error(db);
    else
      throw std::bad_alloc(); // out of memory. better way to signal this?
  }

  register_native_method("cursor", &sqlite3::cursor);
  register_native_method("close", &sqlite3::close);
}
///////////////////////////
sqlite3::~sqlite3()
{
  close();
}

///////////////////////////
void sqlite3::close()
{
  if (db) {
    sqlite3_close(db);
    db = NULL;
  }
}

///////////////////////////
void sqlite3::cursor(call_context &x) {
  local_root_scope scope;
  if (!db)
    throw exception("SQLite3.cursor called on closed dbh");

  if (x.arg.size() < 1)
    throw exception ("cursor requires more than 0 arguments");

  string sql = x.arg[0].to_string();
  size_t n_bytes = sql.length() * 2;
  sqlite3_stmt *sth;
  char16_t *tail; // uncompiled part of the sql (when multiple stmts)
  if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)
  {
    raise_sqlite_error(db);
  }
  object cursor = create_native_object<sqlite3_cursor>(object(), sth);

  // TODO: remove tail and set it seperately
  cursor.define_property("sql", sql);

  x.result = cursor;
}

///////////////////////////
object sqlite3_cursor::class_info::create_prototype() {
  object proto = create_object();

  create_native_method(proto, "finish", 0);
  create_native_method(proto, "reset", 0);
  create_native_method(proto, "next", 0);
  create_native_method(proto, "bind", 0);

  return proto;
}

///////////////////////////
// 'Private' constructor that is called from sqlite3::cursor
sqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)
  : native_object_base(obj),
    sth(_sth)
{
  register_native_method("finish", &sqlite3_cursor::finish);
  register_native_method("reset", &sqlite3_cursor::reset);
  register_native_method("next", &sqlite3_cursor::next);
  register_native_method("bind", &sqlite3_cursor::bind);
}

///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
  finish();
}

///////////////////////////
void sqlite3_cursor::finish() {
  if (sth) {
    sqlite3_finalize(sth);
    sth = NULL;
  }
}

///////////////////////////
void sqlite3_cursor::reset() {
}

///////////////////////////
object sqlite3_cursor::next() {
  return object();
}

///////////////////////////
void sqlite3_cursor::bind(call_context &) {
}

///////////////////////////
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
  std::string s = "SQLite3 Error: ";
  s += sqlite3_errmsg(db);
  throw exception(s);
}

}

<commit_msg>Plugins/sqlite3: Bind parameter support<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>

#include "sqlite3.h"

using namespace flusspferd;

// Put everything in an anon-namespace so typeid wont clash ever.
namespace {

void raise_sqlite_error(sqlite3* db);

///////////////////////////
// Classes
///////////////////////////

class sqlite3 : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    static char const *full_name() { return "SQLite3"; }
    typedef boost::mpl::bool_<true> constructible;
    static char const *constructor_name() { return "SQLite3"; }
    static void augment_constructor(object &ctor);
    static object create_prototype();
  };

  sqlite3(object const &obj, call_context &x);
  ~sqlite3();

protected:
  //void trace(tracer &);

private: // JS methods
  ::sqlite3 *db;

  void close();
  void cursor(call_context &x);
};

class sqlite3_cursor : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    typedef boost::mpl::bool_<false> constructible;
    static char const *full_name() { return "SQLite3.Cursor"; }
    static char const* constructor_name() { return "Cursor"; }
    static object create_prototype();
  };

  sqlite3_cursor(object const &obj, sqlite3_stmt *sth);
  ~sqlite3_cursor();

private:
  sqlite3_stmt *sth;

  // Methods that help wiht binding
  void bind_array(array &a, size_t num_binds);
  void bind_dict(object &o, size_t num_binds);
  void do_bind_param(int n, value v);

private: // JS methods
  void finish();
  void reset();
  object next();
  void bind(call_context &x);
};

///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
  return load_class<sqlite3>(container);
}

///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
  // Set static properties on the constructor
  ctor.define_property("version", SQLITE_VERSION_NUMBER,
      object::read_only_property | object::permanent_property);
  ctor.define_property("versionStr", string(SQLITE_VERSION),
      object::read_only_property | object::permanent_property);

  load_class<sqlite3_cursor>(ctor);
}

///////////////////////////
object sqlite3::class_info::create_prototype()
{
  object proto = create_object();

  create_native_method(proto, "cursor", 1);
  create_native_method(proto, "close", 0);
  return proto;
}

///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
  : native_object_base(obj),
    db(NULL)
{
  if (x.arg.size() == 0)
    throw exception ("SQLite3 requires more than 0 arguments");

  string dsn = x.arg[0];

  // TODO: pull arguments from 2nd/options argument
  if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
    if (db)
      raise_sqlite_error(db);
    else
      throw std::bad_alloc(); // out of memory. better way to signal this?
  }

  register_native_method("cursor", &sqlite3::cursor);
  register_native_method("close", &sqlite3::close);
}
///////////////////////////
sqlite3::~sqlite3()
{
  close();
}

///////////////////////////
void sqlite3::close()
{
  if (db) {
    sqlite3_close(db);
    db = NULL;
  }
}

///////////////////////////
void sqlite3::cursor(call_context &x) {
  local_root_scope scope;
  if (!db)
    throw exception("SQLite3.cursor called on closed dbh");

  if (x.arg.size() < 1)
    throw exception ("cursor requires more than 0 arguments");

  string sql = x.arg[0].to_string();
  size_t n_bytes = sql.length() * 2;
  sqlite3_stmt *sth;
  char16_t *tail; // uncompiled part of the sql (when multiple stmts)
  if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)
  {
    raise_sqlite_error(db);
  }
  object cursor = create_native_object<sqlite3_cursor>(object(), sth);

  // TODO: remove tail and set it seperately
  cursor.define_property("sql", sql);

  x.result = cursor;
}

///////////////////////////
object sqlite3_cursor::class_info::create_prototype() {
  object proto = create_object();

  create_native_method(proto, "finish", 0);
  create_native_method(proto, "reset", 0);
  create_native_method(proto, "next", 0);
  create_native_method(proto, "bind", 0);

  return proto;
}

///////////////////////////
// 'Private' constructor that is called from sqlite3::cursor
sqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)
  : native_object_base(obj),
    sth(_sth)
{
  register_native_method("finish", &sqlite3_cursor::finish);
  register_native_method("reset", &sqlite3_cursor::reset);
  register_native_method("next", &sqlite3_cursor::next);
  register_native_method("bind", &sqlite3_cursor::bind);
}

///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
  finish();
}

///////////////////////////
void sqlite3_cursor::finish() {
  if (sth) {
    sqlite3_finalize(sth);
    sth = NULL;
  }
}

///////////////////////////
void sqlite3_cursor::reset() {
}

///////////////////////////
object sqlite3_cursor::next() {
  return object();
}

///////////////////////////
// JS method
void sqlite3_cursor::bind(call_context &x) {
  local_root_scope scope;

  size_t num_binds = sqlite3_bind_parameter_count(sth);

  if (!num_binds)
    return;

  if (x.arg[0].is_object()) {
    object o = x.arg[0].get_object();

    if (o.is_array()) {
      array a = o;
      bind_array(a, num_binds);
    }
    else
      bind_dict(o, num_binds);
  } else if (num_binds == 1) {
    // Dont document that we accept a single param
    do_bind_param(1, x.arg[0]);

  } else {
    throw exception("SQLite3.Cursor.bind requires an array or an object as its only argument");
  }
}

///////////////////////////
// bind numbered params
void sqlite3_cursor::bind_array(array &a, size_t num_binds) {

  // Pull bind param 1 (the first) from array index 0 (also the first)
  for (size_t n = 1; n <= num_binds; n++) {
    value bind = a.get_element(n-1);

    if (!bind.is_void())
      do_bind_param(n, bind);

  }
}

///////////////////////////
// bind named or numbered params
void sqlite3_cursor::bind_dict(object &o, size_t num_binds) {

  for (size_t n = 1; n <= num_binds; n++) {
    const char* name = sqlite3_bind_parameter_name(sth, n);

    value bind;

    if (!name) {
      // Possibly a '?' unnnamed param
      // TODO: This will break when n is > 2^31.
      bind = o.get_property( value( int(n) ) );
    } else {
      // Named param
      bind = o.get_property(name);
    }

    if (!bind.is_void())
      do_bind_param(n, bind);

  }

}

#include <stdio.h>
///////////////////////////
// Bind the actual para
void sqlite3_cursor::do_bind_param(int n, value v) {
  int ok;
  printf("Binding %d to value %s\n", n, v.to_string().c_str());
  if (v.is_int()) {
      ok = sqlite3_bind_int(sth, n, v.get_int());
  } else if (v.is_double()) {
    ok = sqlite3_bind_double(sth, n, v.get_double());
  } else if (v.is_null()) {
    ok = sqlite3_bind_null(sth, n);
  } else {
    // Default, stringify the object
    string bind = v.to_string();
    ok = sqlite3_bind_text16(sth, n, bind.data(), bind.length()*2, SQLITE_TRANSIENT);
  }

  if (ok != SQLITE_OK)
    raise_sqlite_error( sqlite3_db_handle(sth) );
}

///////////////////////////
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
  std::string s = "SQLite3 Error: ";
  s += sqlite3_errmsg(db);
  throw exception(s);
}

}

<|endoftext|>


<commit_before>#pragma once

#include "types.hpp"
#include <CoreGraphics/CoreGraphics.h>
#include <vector>

namespace manipulator {
class modifier_flag_manager final {
public:
  modifier_flag_manager(void) {
    states_.resize(static_cast<size_t>(krbn::modifier_flag::prepared_modifier_flag_end_));

    states_[static_cast<size_t>(krbn::modifier_flag::caps_lock)] = std::make_unique<state>("caps lock", "⇪");
    states_[static_cast<size_t>(krbn::modifier_flag::left_control)] = std::make_unique<state>("control", "⌃");
    states_[static_cast<size_t>(krbn::modifier_flag::left_shift)] = std::make_unique<state>("shift", "⇧");
    states_[static_cast<size_t>(krbn::modifier_flag::left_option)] = std::make_unique<state>("option", "⌥");
    states_[static_cast<size_t>(krbn::modifier_flag::left_command)] = std::make_unique<state>("command", "⌘");
    states_[static_cast<size_t>(krbn::modifier_flag::right_control)] = std::make_unique<state>("control", "⌃");
    states_[static_cast<size_t>(krbn::modifier_flag::right_shift)] = std::make_unique<state>("shift", "⇧");
    states_[static_cast<size_t>(krbn::modifier_flag::right_option)] = std::make_unique<state>("option", "⌥");
    states_[static_cast<size_t>(krbn::modifier_flag::right_command)] = std::make_unique<state>("command", "⌘");
    states_[static_cast<size_t>(krbn::modifier_flag::fn)] = std::make_unique<state>("fn", "fn");
  }

  void reset(void) {
    for (const auto& s : states_) {
      if (s) {
        s->reset();
      }
    }
  }

  void unlock(void) {
    for (const auto& s : states_) {
      if (s) {
        s->unlock();
      }
    }
  }

  enum class operation {
    increase,
    decrease,
    lock,
    unlock,
    toggle_lock,
  };

  void manipulate(krbn::modifier_flag k, operation operation) {
    auto i = static_cast<size_t>(k);
    if (states_[i]) {
      switch (operation) {
      case operation::increase:
        states_[i]->increase();
        break;
      case operation::decrease:
        states_[i]->decrease();
        break;
      case operation::lock:
        states_[i]->lock();
        break;
      case operation::unlock:
        states_[i]->unlock();
        break;
      case operation::toggle_lock:
        states_[i]->toggle_lock();
        break;
      }
    }
  }

  bool pressed(krbn::modifier_flag m) const {
    if (m == krbn::modifier_flag::zero) {
      return true;
    }

    auto i = static_cast<size_t>(m);
    if (i < states_.size() && states_[i]) {
      return states_[i]->pressed();
    }
    return false;
  }

  bool pressed(const std::vector<krbn::modifier_flag>& modifier_flags) {
    // return true if all modifier flags are pressed.
    for (const auto& m : modifier_flags) {
      if (!pressed(m)) {
        return false;
      }
    }
    return true;
  }

  uint8_t get_hid_report_bits(void) const {
    uint8_t bits = 0;

    if (pressed(krbn::modifier_flag::left_control)) {
      bits |= (0x1 << 0);
    }
    if (pressed(krbn::modifier_flag::left_shift)) {
      bits |= (0x1 << 1);
    }
    if (pressed(krbn::modifier_flag::left_option)) {
      bits |= (0x1 << 2);
    }
    if (pressed(krbn::modifier_flag::left_command)) {
      bits |= (0x1 << 3);
    }
    if (pressed(krbn::modifier_flag::right_control)) {
      bits |= (0x1 << 4);
    }
    if (pressed(krbn::modifier_flag::right_shift)) {
      bits |= (0x1 << 5);
    }
    if (pressed(krbn::modifier_flag::right_option)) {
      bits |= (0x1 << 6);
    }
    if (pressed(krbn::modifier_flag::right_command)) {
      bits |= (0x1 << 7);
    }

    return bits;
  }

  IOOptionBits get_io_option_bits(void) const {
    IOOptionBits bits = 0;
    if (pressed(krbn::modifier_flag::caps_lock)) {
      bits |= NX_ALPHASHIFTMASK;
    }
    if (pressed(krbn::modifier_flag::left_control) ||
        pressed(krbn::modifier_flag::right_control)) {
      bits |= NX_CONTROLMASK;
    }
    if (pressed(krbn::modifier_flag::left_shift) ||
        pressed(krbn::modifier_flag::right_shift)) {
      bits |= NX_SHIFTMASK;
    }
    if (pressed(krbn::modifier_flag::left_option) ||
        pressed(krbn::modifier_flag::right_option)) {
      bits |= NX_ALTERNATEMASK;
    }
    if (pressed(krbn::modifier_flag::left_command) ||
        pressed(krbn::modifier_flag::right_command)) {
      bits |= NX_COMMANDMASK;
    }
    if (pressed(krbn::modifier_flag::fn)) {
      bits |= NX_SECONDARYFNMASK;
    }
    return bits;
  }

  CGEventFlags get_cg_event_flags(krbn::key_code key_code, CGEventFlags original_flags) const {
    original_flags = static_cast<CGEventFlags>(original_flags & ~(kCGEventFlagMaskAlphaShift | kCGEventFlagMaskControl | kCGEventFlagMaskShift | kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskNumericPad | kCGEventFlagMaskSecondaryFn));

    if (pressed(krbn::modifier_flag::caps_lock)) {
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskAlphaShift);
    }
    if (pressed(krbn::modifier_flag::left_control) ||
        pressed(krbn::modifier_flag::right_control)) {
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskControl);
    }
    if (pressed(krbn::modifier_flag::left_shift) ||
        pressed(krbn::modifier_flag::right_shift)) {
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskShift);
    }
    if (pressed(krbn::modifier_flag::left_option) ||
        pressed(krbn::modifier_flag::right_option)) {
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskAlternate);
    }
    if (pressed(krbn::modifier_flag::left_command) ||
        pressed(krbn::modifier_flag::right_command)) {
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskCommand);
    }
    if (pressed(krbn::modifier_flag::fn)) {
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskSecondaryFn);
    }

    // Add kCGEventFlagMaskNumericPad, kCGEventFlagMaskSecondaryFn by key_code.
    //
    // Note:
    //   Microsoft Remote Client will fail to treat shift-arrow keys unless these flags.

    switch (key_code) {
    case krbn::key_code::keypad_slash:
    case krbn::key_code::keypad_asterisk:
    case krbn::key_code::keypad_hyphen:
    case krbn::key_code::keypad_plus:
    case krbn::key_code::keypad_enter:
    case krbn::key_code::keypad_1:
    case krbn::key_code::keypad_2:
    case krbn::key_code::keypad_3:
    case krbn::key_code::keypad_4:
    case krbn::key_code::keypad_5:
    case krbn::key_code::keypad_6:
    case krbn::key_code::keypad_7:
    case krbn::key_code::keypad_8:
    case krbn::key_code::keypad_9:
    case krbn::key_code::keypad_0:
    case krbn::key_code::keypad_period:
    case krbn::key_code::keypad_equal_sign:
    case krbn::key_code::keypad_comma:
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskNumericPad);
      break;

    case krbn::key_code::right_arrow:
    case krbn::key_code::left_arrow:
    case krbn::key_code::down_arrow:
    case krbn::key_code::up_arrow:
      original_flags = static_cast<CGEventFlags>(original_flags | kCGEventFlagMaskNumericPad | kCGEventFlagMaskSecondaryFn);
      break;

    default:
      break;
    }

    return original_flags;
  }

private:
  class state final {
  public:
    state(const std::string& name, const std::string& symbol) : name_(name),
                                                                symbol_(symbol),
                                                                count_(0),
                                                                lock_count_(0) {}

    const std::string& get_name(void) const { return name_; }
    const std::string& get_symbol(void) const { return symbol_; }

    bool pressed(void) const { return (count_ + lock_count_) > 0; }

    void reset(void) {
      count_ = 0;
    }

    void increase(void) {
      ++count_;
    }

    void decrease(void) {
      --count_;
    }

    void lock(void) {
      lock_count_ = 1;
    }

    void unlock(void) {
      lock_count_ = 0;
    }

    void toggle_lock(void) {
      lock_count_ = lock_count_ == 0 ? 1 : 0;
    }

  private:
    std::string name_;
    std::string symbol_;
    int count_;
    int lock_count_;
  };

  std::vector<std::unique_ptr<state>> states_;
};
}
<commit_msg>remove unnecessary static_cast<commit_after>#pragma once

#include "types.hpp"
#include <CoreGraphics/CoreGraphics.h>
#include <vector>

namespace manipulator {
class modifier_flag_manager final {
public:
  modifier_flag_manager(void) {
    states_.resize(static_cast<size_t>(krbn::modifier_flag::prepared_modifier_flag_end_));

    states_[static_cast<size_t>(krbn::modifier_flag::caps_lock)] = std::make_unique<state>("caps lock", "⇪");
    states_[static_cast<size_t>(krbn::modifier_flag::left_control)] = std::make_unique<state>("control", "⌃");
    states_[static_cast<size_t>(krbn::modifier_flag::left_shift)] = std::make_unique<state>("shift", "⇧");
    states_[static_cast<size_t>(krbn::modifier_flag::left_option)] = std::make_unique<state>("option", "⌥");
    states_[static_cast<size_t>(krbn::modifier_flag::left_command)] = std::make_unique<state>("command", "⌘");
    states_[static_cast<size_t>(krbn::modifier_flag::right_control)] = std::make_unique<state>("control", "⌃");
    states_[static_cast<size_t>(krbn::modifier_flag::right_shift)] = std::make_unique<state>("shift", "⇧");
    states_[static_cast<size_t>(krbn::modifier_flag::right_option)] = std::make_unique<state>("option", "⌥");
    states_[static_cast<size_t>(krbn::modifier_flag::right_command)] = std::make_unique<state>("command", "⌘");
    states_[static_cast<size_t>(krbn::modifier_flag::fn)] = std::make_unique<state>("fn", "fn");
  }

  void reset(void) {
    for (const auto& s : states_) {
      if (s) {
        s->reset();
      }
    }
  }

  void unlock(void) {
    for (const auto& s : states_) {
      if (s) {
        s->unlock();
      }
    }
  }

  enum class operation {
    increase,
    decrease,
    lock,
    unlock,
    toggle_lock,
  };

  void manipulate(krbn::modifier_flag k, operation operation) {
    auto i = static_cast<size_t>(k);
    if (states_[i]) {
      switch (operation) {
      case operation::increase:
        states_[i]->increase();
        break;
      case operation::decrease:
        states_[i]->decrease();
        break;
      case operation::lock:
        states_[i]->lock();
        break;
      case operation::unlock:
        states_[i]->unlock();
        break;
      case operation::toggle_lock:
        states_[i]->toggle_lock();
        break;
      }
    }
  }

  bool pressed(krbn::modifier_flag m) const {
    if (m == krbn::modifier_flag::zero) {
      return true;
    }

    auto i = static_cast<size_t>(m);
    if (i < states_.size() && states_[i]) {
      return states_[i]->pressed();
    }
    return false;
  }

  bool pressed(const std::vector<krbn::modifier_flag>& modifier_flags) {
    // return true if all modifier flags are pressed.
    for (const auto& m : modifier_flags) {
      if (!pressed(m)) {
        return false;
      }
    }
    return true;
  }

  uint8_t get_hid_report_bits(void) const {
    uint8_t bits = 0;

    if (pressed(krbn::modifier_flag::left_control)) {
      bits |= (0x1 << 0);
    }
    if (pressed(krbn::modifier_flag::left_shift)) {
      bits |= (0x1 << 1);
    }
    if (pressed(krbn::modifier_flag::left_option)) {
      bits |= (0x1 << 2);
    }
    if (pressed(krbn::modifier_flag::left_command)) {
      bits |= (0x1 << 3);
    }
    if (pressed(krbn::modifier_flag::right_control)) {
      bits |= (0x1 << 4);
    }
    if (pressed(krbn::modifier_flag::right_shift)) {
      bits |= (0x1 << 5);
    }
    if (pressed(krbn::modifier_flag::right_option)) {
      bits |= (0x1 << 6);
    }
    if (pressed(krbn::modifier_flag::right_command)) {
      bits |= (0x1 << 7);
    }

    return bits;
  }

  IOOptionBits get_io_option_bits(void) const {
    IOOptionBits bits = 0;
    if (pressed(krbn::modifier_flag::caps_lock)) {
      bits |= NX_ALPHASHIFTMASK;
    }
    if (pressed(krbn::modifier_flag::left_control) ||
        pressed(krbn::modifier_flag::right_control)) {
      bits |= NX_CONTROLMASK;
    }
    if (pressed(krbn::modifier_flag::left_shift) ||
        pressed(krbn::modifier_flag::right_shift)) {
      bits |= NX_SHIFTMASK;
    }
    if (pressed(krbn::modifier_flag::left_option) ||
        pressed(krbn::modifier_flag::right_option)) {
      bits |= NX_ALTERNATEMASK;
    }
    if (pressed(krbn::modifier_flag::left_command) ||
        pressed(krbn::modifier_flag::right_command)) {
      bits |= NX_COMMANDMASK;
    }
    if (pressed(krbn::modifier_flag::fn)) {
      bits |= NX_SECONDARYFNMASK;
    }
    return bits;
  }

  CGEventFlags get_cg_event_flags(krbn::key_code key_code, CGEventFlags original_flags) const {
    original_flags = CGEventFlags(original_flags & ~(kCGEventFlagMaskAlphaShift | kCGEventFlagMaskControl | kCGEventFlagMaskShift | kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskNumericPad | kCGEventFlagMaskSecondaryFn));

    if (pressed(krbn::modifier_flag::caps_lock)) {
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskAlphaShift);
    }
    if (pressed(krbn::modifier_flag::left_control) ||
        pressed(krbn::modifier_flag::right_control)) {
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskControl);
    }
    if (pressed(krbn::modifier_flag::left_shift) ||
        pressed(krbn::modifier_flag::right_shift)) {
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskShift);
    }
    if (pressed(krbn::modifier_flag::left_option) ||
        pressed(krbn::modifier_flag::right_option)) {
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskAlternate);
    }
    if (pressed(krbn::modifier_flag::left_command) ||
        pressed(krbn::modifier_flag::right_command)) {
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskCommand);
    }
    if (pressed(krbn::modifier_flag::fn)) {
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskSecondaryFn);
    }

    // Add kCGEventFlagMaskNumericPad, kCGEventFlagMaskSecondaryFn by key_code.
    //
    // Note:
    //   Microsoft Remote Client will fail to treat shift-arrow keys unless these flags.

    switch (key_code) {
    case krbn::key_code::keypad_slash:
    case krbn::key_code::keypad_asterisk:
    case krbn::key_code::keypad_hyphen:
    case krbn::key_code::keypad_plus:
    case krbn::key_code::keypad_enter:
    case krbn::key_code::keypad_1:
    case krbn::key_code::keypad_2:
    case krbn::key_code::keypad_3:
    case krbn::key_code::keypad_4:
    case krbn::key_code::keypad_5:
    case krbn::key_code::keypad_6:
    case krbn::key_code::keypad_7:
    case krbn::key_code::keypad_8:
    case krbn::key_code::keypad_9:
    case krbn::key_code::keypad_0:
    case krbn::key_code::keypad_period:
    case krbn::key_code::keypad_equal_sign:
    case krbn::key_code::keypad_comma:
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskNumericPad);
      break;

    case krbn::key_code::right_arrow:
    case krbn::key_code::left_arrow:
    case krbn::key_code::down_arrow:
    case krbn::key_code::up_arrow:
      original_flags = CGEventFlags(original_flags | kCGEventFlagMaskNumericPad | kCGEventFlagMaskSecondaryFn);
      break;

    default:
      break;
    }

    return original_flags;
  }

private:
  class state final {
  public:
    state(const std::string& name, const std::string& symbol) : name_(name),
                                                                symbol_(symbol),
                                                                count_(0),
                                                                lock_count_(0) {}

    const std::string& get_name(void) const { return name_; }
    const std::string& get_symbol(void) const { return symbol_; }

    bool pressed(void) const { return (count_ + lock_count_) > 0; }

    void reset(void) {
      count_ = 0;
    }

    void increase(void) {
      ++count_;
    }

    void decrease(void) {
      --count_;
    }

    void lock(void) {
      lock_count_ = 1;
    }

    void unlock(void) {
      lock_count_ = 0;
    }

    void toggle_lock(void) {
      lock_count_ = lock_count_ == 0 ? 1 : 0;
    }

  private:
    std::string name_;
    std::string symbol_;
    int count_;
    int lock_count_;
  };

  std::vector<std::unique_ptr<state>> states_;
};
}
<|endoftext|>


<commit_before>/*
 * SessionPanmirrorCrossref.cpp
 *
 * Copyright (C) 2009-16 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 "SessionPanmirrorCrossref.hpp"

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

#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/http/Util.hpp>

#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncDownloadFile.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace crossref {

namespace {

const char * const kCrossrefApiHost = "https://api.crossref.org";
const char * const kCrossrefWorks = "works";

void crossrefRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
   if (json::isType<json::Object>(value))
   {
      json::Object responseJson = value.getObject();
      std::string status;
      json::Object message;
      Error error = json::readObject(responseJson, "status", status,
                                                   "message", message);
      if (error)
      {
         json::setErrorResponse(error, pResponse);
      }
      else if (status != "ok")
      {
         Error error = systemError(boost::system::errc::state_not_recoverable,
                                   "Unexpected status from crossref api: " + status,
                                   ERROR_LOCATION);
         json::setErrorResponse(error, pResponse);
      }
      else
      {
         pResponse->setResult(message);
      }
   }
   else
   {
      Error error = systemError(boost::system::errc::state_not_recoverable,
                                "Unexpected response from crossref api",
                                ERROR_LOCATION);
      json::setErrorResponse(error, pResponse);
   }
}

void crossrefRequest(const std::string& resource,
                     const http::Fields& params,
                     const json::JsonRpcFunctionContinuation& cont)
{
   // build query string
   std::string queryString;
   core::http::util::buildQueryString(params, &queryString);

   // build the url and make the request
   boost::format fmt("%s/%s?%s");
   const std::string url = boost::str(fmt % kCrossrefApiHost % resource % queryString);
   asyncJsonRpcRequest(url, crossrefRequestHandler, cont);
}

void crossrefWorks(const json::JsonRpcRequest& request,
                   const json::JsonRpcFunctionContinuation& cont)
{
   // extract query
   std::string query;
   Error error = json::readParams(request.params, &query);
   if (error)
   {
     json::JsonRpcResponse response;
     setErrorResponse(error, &response);
     cont(Success(), &response);
     return;
   }

   // build params
   core::http::Fields params;
   params.push_back(std::make_pair("query", query));

   // make the request
   crossrefRequest(kCrossrefWorks, params, cont);
}

void crossrefDoi(const json::JsonRpcRequest& request,
                 const json::JsonRpcFunctionContinuation& cont)
{
    std::string doi;
    Error error = json::readParams(request.params, &doi);
    if (error)
    {
      json::JsonRpcResponse response;
      setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
    }

    // Path to DOI metadata works/doi/{doi}
    boost::format fmt("%s/doi/%s");
    const std::string resourcePath = boost::str(fmt % kCrossrefWorks % doi);

    // No parameters
    core::http::Fields params;

    // make the request
    crossrefRequest(resourcePath, params, cont);
}

} // end anonymous namespace

Error initialize()
{
   ExecBlock initBlock;
   initBlock.addFunctions()
      (boost::bind(module_context::registerAsyncRpcMethod, "crossref_works", crossrefWorks))
      (boost::bind(module_context::registerAsyncRpcMethod, "crossref_doi", crossrefDoi))
   ;
   return initBlock.execute();
}

} // end namespace crossref
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>return csl-json for doi requests<commit_after>/*
 * SessionPanmirrorCrossref.cpp
 *
 * Copyright (C) 2009-16 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 "SessionPanmirrorCrossref.hpp"

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

#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/http/Util.hpp>

#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncDownloadFile.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace crossref {

namespace {

const char * const kCrossrefApiHost = "https://api.crossref.org";
const char * const kCrossrefWorks = "works";

void crossrefContentRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
   pResponse->setResult(value);
}

void crossrefApiRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
   if (json::isType<json::Object>(value))
   {
      json::Object responseJson = value.getObject();
      std::string status;
      json::Object message;
      Error error = json::readObject(responseJson, "status", status,
                                                   "message", message);
      if (error)
      {
         json::setErrorResponse(error, pResponse);
      }
      else if (status != "ok")
      {
         Error error = systemError(boost::system::errc::state_not_recoverable,
                                   "Unexpected status from crossref api: " + status,
                                   ERROR_LOCATION);
         json::setErrorResponse(error, pResponse);
      }
      else
      {
         pResponse->setResult(message);
      }
   }
   else
   {
      Error error = systemError(boost::system::errc::state_not_recoverable,
                                "Unexpected response from crossref api",
                                ERROR_LOCATION);
      json::setErrorResponse(error, pResponse);
   }
}

void crossrefRequest(const std::string& resource,
                     const http::Fields& params,
                     const session::JsonRpcResponseHandler& handler,
                     const json::JsonRpcFunctionContinuation& cont)
{
   // build query string
   std::string queryString;
   core::http::util::buildQueryString(params, &queryString);
   if (queryString.length() > 0)
      queryString = "?" + queryString;

   // build the url and make the request
   boost::format fmt("%s/%s%s");
   const std::string url = boost::str(fmt % kCrossrefApiHost % resource % queryString);

   asyncJsonRpcRequest(url, handler, cont);
}

void crossrefWorks(const json::JsonRpcRequest& request,
                   const json::JsonRpcFunctionContinuation& cont)
{
   // extract query
   std::string query;
   Error error = json::readParams(request.params, &query);
   if (error)
   {
     json::JsonRpcResponse response;
     setErrorResponse(error, &response);
     cont(Success(), &response);
     return;
   }

   // build params
   core::http::Fields params;
   params.push_back(std::make_pair("query", query));

   // make the request
   crossrefRequest(kCrossrefWorks, params, crossrefApiRequestHandler, cont);
}

void crossrefDoi(const json::JsonRpcRequest& request,
                 const json::JsonRpcFunctionContinuation& cont)
{
    std::string doi;
    Error error = json::readParams(request.params, &doi);
    if (error)
    {
      json::JsonRpcResponse response;
      setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
    }

    // Path to DOI metadata works/{doi}/transform/{format} (see: https://citation.crosscite.org/docs.html#sec-5)
    const char * const kCitationFormat = "application/vnd.citationstyles.csl+json";
    boost::format fmt("%s/%s/transform/%s");
    const std::string resourcePath = boost::str(fmt % kCrossrefWorks % doi % kCitationFormat);

    // No parameters
    core::http::Fields params;

    // make the request
    crossrefRequest(resourcePath, params, crossrefContentRequestHandler, cont);
}

} // end anonymous namespace

Error initialize()
{
   ExecBlock initBlock;
   initBlock.addFunctions()
      (boost::bind(module_context::registerAsyncRpcMethod, "crossref_works", crossrefWorks))
      (boost::bind(module_context::registerAsyncRpcMethod, "crossref_doi", crossrefDoi))
   ;
   return initBlock.execute();
}

} // end namespace crossref
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|>


<commit_before>/*
    g++ quick.cpp -o quick
Reference:
    http://www.sorting-algorithms.com/quick-sort
*/
#include <stdio.h>
#include "util.h"

// quick (with 2 partitions)
// Note: The common implementation uses a left and right index (this doesn't)
// ========================================================================
void sort( const int N, int *data )
{
    if( N <= 1 )
        return;
printf( "N=%d\n", N );

    // leave pivot; use as-is data[0]
    // swap( data[0], rand(1,N));

    // move all data that is less then the pivot to the left side
    // we end up with 2 partitions
    //   [1..k-1] all data is <  pivot data[k]
    //   [k..n  ] all data is >= pivot data[k]
    int k = 0;
printf( "pivot = [%d]:%d\n", k, data[k] );

    for( int i = 1; i < N; i++ )
    {
printf( "i:%d  k: %d\n", i, k );
        if( data[i] < data[0] )
        {
            swap( data, ++k, i ); // inefficent if data[1] > data[pivot] --> swap with itself!
dump( N, data );
        }
    }
printf( "sorted [%d]\n", k );
    swap( data, 0, k );
dump( N, data );

printf( "sort Left k=%d terms ...\n", k );
    sort( k    , data + 0   ); //   0..k-1

printf( "sort Right N-k-1 = %d-%d-1 = %d terms ...\n", N, k, N-k-1 );
    sort( N-k-1, data + k+1 ); // k+1..n   -->  n-k terms

printf( "\n" );
}

int main()
{
    /* */ int src[] = { 3, 4, 2, 1 };
//int src[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; // reverse
//int src[] = { 9, 7, 5, 3, 1, 2, 4, 6, 8 }; // alternating reverse and forward
    const int len   = sizeof( src ) / sizeof( int );

    dump( len, src );
    sort( len, src );
    dump( len, src );

    return 0;
}
<commit_msg>Fix spelling<commit_after>/*
    g++ quick.cpp -o quick
Reference:
    http://www.sorting-algorithms.com/quick-sort
*/
#include <stdio.h>
#include "util.h"

// quick (with 2 partitions)
// Note: The common implementation uses a left and right index (this doesn't)
// ========================================================================
void sort( const int N, int *data )
{
    if( N <= 1 )
        return;
printf( "N=%d\n", N );

    // leave pivot; use as-is data[0]
    // swap( data[0], rand(1,N));

    // move all data that is less then the pivot to the left side
    // we end up with 2 partitions
    //   [1..k-1] all data is <  pivot data[k]
    //   [k..n  ] all data is >= pivot data[k]
    int k = 0;
printf( "pivot = [%d]:%d\n", k, data[k] );

    for( int i = 1; i < N; i++ )
    {
printf( "i:%d  k: %d\n", i, k );
        if( data[i] < data[0] )
        {
            swap( data, ++k, i ); // inefficient if data[1] > data[pivot] --> swap with itself!
dump( N, data );
        }
    }
printf( "sorted [%d]\n", k );
    swap( data, 0, k );
dump( N, data );

printf( "sort Left k=%d terms ...\n", k );
    sort( k    , data + 0   ); //   0..k-1

printf( "sort Right N-k-1 = %d-%d-1 = %d terms ...\n", N, k, N-k-1 );
    sort( N-k-1, data + k+1 ); // k+1..n   -->  n-k terms

printf( "\n" );
}

int main()
{
    /* */ int src[] = { 3, 4, 2, 1 };
//int src[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; // reverse
//int src[] = { 9, 7, 5, 3, 1, 2, 4, 6, 8 }; // alternating reverse and forward
    const int len   = sizeof( src ) / sizeof( int );

    dump( len, src );
    sort( len, src );
    dump( len, src );

    return 0;
}
<|endoftext|>


<commit_before>#include "bgen_system.h"
#include "bgen_details.h"

#include <cinttypes>

#if defined (BGEN_OS_WINDOWS)

#elif defined (BGEN_OS_LINUX)

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <limits>
#include <cinttypes>

namespace bgen {
    namespace system {

        string get_executable_path () {
            char * path = realpath ("/prod/self/exe", nullptr);

            if (!path)
                return "";

            string result = path;
            free (path);
            return result;
        }

    }
}

#elif defined (BGEN_OS_DARWIN)

#include <mach-o/dyld.h>
#include <limits>
#include <stdlib>
#include <string>
#include <dlfcn.h>

namespace bgen {
    namespace system {

        string get_executable_path () {

            char * buffer = new char [PATH_MAX];

            // safelly clean up memory
            auto_guard ([&buffer]() {
                delete [] buffer;
            });

            string resolved;

            uint32_t size = PATH_MAX;

            if (_NSGetExecutablePath(buffer, &size) == -1) {
                delete [] buffer;
                buffer = new char [size];

                if (!_NSGetExecutablePath(buffer, &size))
                    return "";
            }

            char * real_path_buffer = realpath(buffer, nullptr);

            if (!real_path_buffer)
                return "";

            resolved = real_path_buffer;

            free (real_path_buffer);

            return resolved;
        }

    }
}

#endif

#if defined (BGEN_API_WIN32)

namespace bgen {
    namespace system {

        char get_path_separator () {
            return '\\';
        }

    }
}

#elif defined (BGEN_API_UNIX)

namespace bgen {
    namespace system {

        char get_path_separator () {
            return '/';
        }

    }
}

#endif

namespace bgen {
    namespace system {

        string get_executable_dir () {
            string path = get_executable_path();

            auto pos = path.find_last_of (get_path_separator());

            if (pos == string::npos)
                return path;

            return path.substr(0, pos + 1);
        }

        string merge_path ( const string & p1, const string & p2) {

            string::const_iterator
                p1_start = p1.begin (),
                p1_end = p1.end (),
                p2_start = p2.begin (),
                p2_end = p2.end ();

            char separator = get_path_separator();

            if (p1_start != p1_end && *(p1_end - 1) == separator)
                --p1_end;

            if (p2_start != p2_end && *(p2_start) == separator)
                ++p2_start;

            string res;

            res.reserve (p1.size () + p2.size () + 1);
            res.append (p1_start, p1_end);
            res.append (&separator, &separator + 1);
            res.append (p2_start, p2_end);

            return res;
        }

    }
}
<commit_msg>fix minor osx building issue<commit_after>#include "bgen_system.h"
#include "bgen_details.h"

#include <cinttypes>

#if defined (BGEN_OS_WINDOWS)

#elif defined (BGEN_OS_LINUX)

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <limits>
#include <cinttypes>

namespace bgen {
    namespace system {

        string get_executable_path () {
            char * path = realpath ("/prod/self/exe", nullptr);

            if (!path)
                return "";

            string result = path;
            free (path);
            return result;
        }

    }
}

#elif defined (BGEN_OS_DARWIN)

#include <mach-o/dyld.h>
#include <limits.h>
#include <stdlib.h>
#include <string>
#include <dlfcn.h>

namespace bgen {
    namespace system {

        string get_executable_path () {

            char * buffer = new char [PATH_MAX];

            // safelly clean up memory
            auto_guard ([&buffer]() {
                delete [] buffer;
            });

            string resolved;

            uint32_t size = PATH_MAX;

            if (_NSGetExecutablePath(buffer, &size) == -1) {
                delete [] buffer;
                buffer = new char [size];

                if (!_NSGetExecutablePath(buffer, &size))
                    return "";
            }

            char * real_path_buffer = realpath(buffer, nullptr);

            if (!real_path_buffer)
                return "";

            resolved = real_path_buffer;

            free (real_path_buffer);

            return resolved;
        }

    }
}

#endif

#if defined (BGEN_API_WIN32)

namespace bgen {
    namespace system {

        char get_path_separator () {
            return '\\';
        }

    }
}

#elif defined (BGEN_API_UNIX)

namespace bgen {
    namespace system {

        char get_path_separator () {
            return '/';
        }

    }
}

#endif

namespace bgen {
    namespace system {

        string get_executable_dir () {
            string path = get_executable_path();

            auto pos = path.find_last_of (get_path_separator());

            if (pos == string::npos)
                return path;

            return path.substr(0, pos + 1);
        }

        string merge_path ( const string & p1, const string & p2) {

            string::const_iterator
                p1_start = p1.begin (),
                p1_end = p1.end (),
                p2_start = p2.begin (),
                p2_end = p2.end ();

            char separator = get_path_separator();

            if (p1_start != p1_end && *(p1_end - 1) == separator)
                --p1_end;

            if (p2_start != p2_end && *(p2_start) == separator)
                ++p2_start;

            string res;

            res.reserve (p1.size () + p2.size () + 1);
            res.append (p1_start, p1_end);
            res.append (&separator, &separator + 1);
            res.append (p2_start, p2_end);

            return res;
        }

    }
}
<|endoftext|>


<commit_before><commit_msg>Create 1157 - Divisors I.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 * libjson-rpc-cpp
 *************************************************************************
 * @file    httpserver.cpp
 * @date    31.12.2012
 * @author  Peter Spiess-Knafl <dev@spiessknafl.at>
 * @license See attached LICENSE.txt
 ************************************************************************/

#include "httpserver.h"
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <jsonrpccpp/common/specificationparser.h>

using namespace jsonrpc;
using namespace std;

#define BUFFERSIZE 65536

struct mhd_coninfo {
        struct MHD_PostProcessor *postprocessor;
        MHD_Connection* connection;
        stringstream request;
        HttpServer* server;
        int code;
};

HttpServer::HttpServer(int port, const std::string &sslcert, const std::string &sslkey, int threads) :
    AbstractServerConnector(),
    port(port),
    threads(threads),
    running(false),
    path_sslcert(sslcert),
    path_sslkey(sslkey),
    daemon(NULL)
{
}

IClientConnectionHandler *HttpServer::GetHandler(const std::string &url)
{
    if (AbstractServerConnector::GetHandler() != NULL)
        return AbstractServerConnector::GetHandler();
    map<string, IClientConnectionHandler*>::iterator it = this->urlhandler.find(url);
    if (it != this->urlhandler.end())
        return it->second;
    return NULL;
}

bool HttpServer::StartListening()
{
    if(!this->running)
    {
        bool has_epoll = false;
        bool has_poll = false;
        unsigned int mhd_flags = MHD_USE_SELECT_INTERNALLY;

#ifdef MHD_FEATURE_EPOLL
        has_epoll = (MHD_is_feature_supported(MHD_FEATURE_EPOLL) == MHD_YES);
        if (has_epoll)
            mhd_flags = MHD_USE_EPOLL_INTERNALLY;
#endif

#ifdef MHD_FEATURE_POLL
        has_poll = (MHD_is_feature_supported(MHD_FEATURE_POLL) == MHD_YES);
        if (!has_epoll && has_poll)
            mhd_flags = MHD_USE_POLL_INTERNALLY;
#endif

        if (this->path_sslcert != "" && this->path_sslkey != "")
        {
            try {
                SpecificationParser::GetFileContent(this->path_sslcert, this->sslcert);
                SpecificationParser::GetFileContent(this->path_sslkey, this->sslkey);

                this->daemon = MHD_start_daemon(MHD_USE_SSL | mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, MHD_OPTION_HTTPS_MEM_KEY, this->sslkey.c_str(), MHD_OPTION_HTTPS_MEM_CERT, this->sslcert.c_str(), MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END);
            }
            catch (JsonRpcException& ex)
            {
                return false;
            }
        }
        else
        {
            this->daemon = MHD_start_daemon(mhd_flags, this->port, NULL, NULL, HttpServer::callback, this,   MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END);
        }
        if (this->daemon != NULL)
            this->running = true;

    }
    return this->running;
}

bool HttpServer::StopListening()
{
    if(this->running)
    {
        MHD_stop_daemon(this->daemon);
        this->running = false;
    }
    return true;
}

bool HttpServer::SendResponse(const string& response, void* addInfo)
{
    struct mhd_coninfo* client_connection = static_cast<struct mhd_coninfo*>(addInfo);
    struct MHD_Response *result = MHD_create_response_from_buffer(response.size(),(void *) response.c_str(), MHD_RESPMEM_MUST_COPY);

    MHD_add_response_header(result, "Content-Type", "application/json");
    MHD_add_response_header(result, "Access-Control-Allow-Origin", "*");

    int ret = MHD_queue_response(client_connection->connection, client_connection->code, result);
    MHD_destroy_response(result);
    return ret == MHD_YES;
}

bool HttpServer::SendOptionsResponse(void* addInfo)
{
    struct mhd_coninfo* client_connection = static_cast<struct mhd_coninfo*>(addInfo);
    struct MHD_Response *result = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_MUST_COPY);

    MHD_add_response_header(result, "Allow", "POST, OPTIONS");
    MHD_add_response_header(result, "Access-Control-Allow-Origin", "*");
    MHD_add_response_header(result, "Access-Control-Allow-Headers", "origin, content-type, accept");
    MHD_add_response_header(result, "DAV", "1");

    int ret = MHD_queue_response(client_connection->connection, client_connection->code, result);
    MHD_destroy_response(result);
    return ret == MHD_YES;
}

void HttpServer::SetUrlHandler(const string &url, IClientConnectionHandler *handler)
{
    this->urlhandler[url] = handler;
    this->SetHandler(NULL);
}

int HttpServer::callback(void *cls, MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls)
{
    (void)version;
    if (*con_cls == NULL)
    {
        struct mhd_coninfo* client_connection = new mhd_coninfo;
        client_connection->connection = connection;
        client_connection->server = static_cast<HttpServer*>(cls);
        *con_cls = client_connection;
        return MHD_YES;
    }
    struct mhd_coninfo* client_connection = static_cast<struct mhd_coninfo*>(*con_cls);

    if (string("POST") == method)
    {
        if (*upload_data_size != 0)
        {
            client_connection->request.write(upload_data, *upload_data_size);
            *upload_data_size = 0;
            return MHD_YES;
        }
        else
        {
            string response;
            IClientConnectionHandler* handler = client_connection->server->GetHandler(string(url));
            if (handler == NULL)
            {
                client_connection->code = MHD_HTTP_INTERNAL_SERVER_ERROR;
                client_connection->server->SendResponse("No client connection handler found", client_connection);
            }
            else
            {
                client_connection->code = MHD_HTTP_OK;
                handler->HandleRequest(client_connection->request.str(), response);
                client_connection->server->SendResponse(response, client_connection);
            }
        }
    }
	else if (string("OPTIONS") == method) {
        client_connection->code = MHD_HTTP_OK;
        client_connection->server->SendOptionsResponse(client_connection);
	}
    else
    {
        client_connection->code = MHD_HTTP_METHOD_NOT_ALLOWED;
        client_connection->server->SendResponse("Not allowed HTTP Method", client_connection);
    }
    delete client_connection;
    *con_cls = NULL;

    return MHD_YES;
}

<commit_msg>Detect MHD version<commit_after>/*************************************************************************
 * libjson-rpc-cpp
 *************************************************************************
 * @file    httpserver.cpp
 * @date    31.12.2012
 * @author  Peter Spiess-Knafl <dev@spiessknafl.at>
 * @license See attached LICENSE.txt
 ************************************************************************/

#include "httpserver.h"
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <jsonrpccpp/common/specificationparser.h>

using namespace jsonrpc;
using namespace std;

#define BUFFERSIZE 65536

struct mhd_coninfo {
        struct MHD_PostProcessor *postprocessor;
        MHD_Connection* connection;
        stringstream request;
        HttpServer* server;
        int code;
};

HttpServer::HttpServer(int port, const std::string &sslcert, const std::string &sslkey, int threads) :
    AbstractServerConnector(),
    port(port),
    threads(threads),
    running(false),
    path_sslcert(sslcert),
    path_sslkey(sslkey),
    daemon(NULL)
{
}

IClientConnectionHandler *HttpServer::GetHandler(const std::string &url)
{
    if (AbstractServerConnector::GetHandler() != NULL)
        return AbstractServerConnector::GetHandler();
    map<string, IClientConnectionHandler*>::iterator it = this->urlhandler.find(url);
    if (it != this->urlhandler.end())
        return it->second;
    return NULL;
}

bool HttpServer::StartListening()
{
    if(!this->running)
    {
        unsigned int mhd_flags = MHD_USE_SELECT_INTERNALLY;

#if (MHD_VERSION >= 0x00095100)
        if (MHD_is_feature_supported(MHD_FEATURE_EPOLL) == MHD_YES)
            mhd_flags = MHD_USE_EPOLL_INTERNALLY;
        else if (MHD_is_feature_supported(MHD_FEATURE_POLL) == MHD_YES)
            mhd_flags = MHD_USE_POLL_INTERNALLY;
#endif
        if (this->path_sslcert != "" && this->path_sslkey != "")
        {
            try {
                SpecificationParser::GetFileContent(this->path_sslcert, this->sslcert);
                SpecificationParser::GetFileContent(this->path_sslkey, this->sslkey);

                this->daemon = MHD_start_daemon(MHD_USE_SSL | mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, MHD_OPTION_HTTPS_MEM_KEY, this->sslkey.c_str(), MHD_OPTION_HTTPS_MEM_CERT, this->sslcert.c_str(), MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END);
            }
            catch (JsonRpcException& ex)
            {
                return false;
            }
        }
        else
        {
            this->daemon = MHD_start_daemon(mhd_flags, this->port, NULL, NULL, HttpServer::callback, this,   MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END);
        }
        if (this->daemon != NULL)
            this->running = true;

    }
    return this->running;
}

bool HttpServer::StopListening()
{
    if(this->running)
    {
        MHD_stop_daemon(this->daemon);
        this->running = false;
    }
    return true;
}

bool HttpServer::SendResponse(const string& response, void* addInfo)
{
    struct mhd_coninfo* client_connection = static_cast<struct mhd_coninfo*>(addInfo);
    struct MHD_Response *result = MHD_create_response_from_buffer(response.size(),(void *) response.c_str(), MHD_RESPMEM_MUST_COPY);

    MHD_add_response_header(result, "Content-Type", "application/json");
    MHD_add_response_header(result, "Access-Control-Allow-Origin", "*");

    int ret = MHD_queue_response(client_connection->connection, client_connection->code, result);
    MHD_destroy_response(result);
    return ret == MHD_YES;
}

bool HttpServer::SendOptionsResponse(void* addInfo)
{
    struct mhd_coninfo* client_connection = static_cast<struct mhd_coninfo*>(addInfo);
    struct MHD_Response *result = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_MUST_COPY);

    MHD_add_response_header(result, "Allow", "POST, OPTIONS");
    MHD_add_response_header(result, "Access-Control-Allow-Origin", "*");
    MHD_add_response_header(result, "Access-Control-Allow-Headers", "origin, content-type, accept");
    MHD_add_response_header(result, "DAV", "1");

    int ret = MHD_queue_response(client_connection->connection, client_connection->code, result);
    MHD_destroy_response(result);
    return ret == MHD_YES;
}

void HttpServer::SetUrlHandler(const string &url, IClientConnectionHandler *handler)
{
    this->urlhandler[url] = handler;
    this->SetHandler(NULL);
}

int HttpServer::callback(void *cls, MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls)
{
    (void)version;
    if (*con_cls == NULL)
    {
        struct mhd_coninfo* client_connection = new mhd_coninfo;
        client_connection->connection = connection;
        client_connection->server = static_cast<HttpServer*>(cls);
        *con_cls = client_connection;
        return MHD_YES;
    }
    struct mhd_coninfo* client_connection = static_cast<struct mhd_coninfo*>(*con_cls);

    if (string("POST") == method)
    {
        if (*upload_data_size != 0)
        {
            client_connection->request.write(upload_data, *upload_data_size);
            *upload_data_size = 0;
            return MHD_YES;
        }
        else
        {
            string response;
            IClientConnectionHandler* handler = client_connection->server->GetHandler(string(url));
            if (handler == NULL)
            {
                client_connection->code = MHD_HTTP_INTERNAL_SERVER_ERROR;
                client_connection->server->SendResponse("No client connection handler found", client_connection);
            }
            else
            {
                client_connection->code = MHD_HTTP_OK;
                handler->HandleRequest(client_connection->request.str(), response);
                client_connection->server->SendResponse(response, client_connection);
            }
        }
    }
	else if (string("OPTIONS") == method) {
        client_connection->code = MHD_HTTP_OK;
        client_connection->server->SendOptionsResponse(client_connection);
	}
    else
    {
        client_connection->code = MHD_HTTP_METHOD_NOT_ALLOWED;
        client_connection->server->SendResponse("Not allowed HTTP Method", client_connection);
    }
    delete client_connection;
    *con_cls = NULL;

    return MHD_YES;
}

<|endoftext|>


<commit_before>/*
 * Spatial Computation - Manifestation of Spatial computing.
 * Copyright © 2014 Pranav Kant
 *
 * This code is available to you under Apache License Version 2.0, January
 * 2014. You can grab a copy of license from the same repository from where you
 * fetched this code.
 */

#include "llvm/ADT/DenseMap.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/GraphWriter.h"

using namespace llvm;

class WaveScalar{
 public:
  void runBFS();
  void annotateWaves(const Function &F, SmallVectorImpl<std::pair<const BasicBlock*, const BasicBlock*> > *res);
  int isSameWave (Instruction* i, Instruction* e);
  int getWaveNo(std::string instruction);

 private:
  enum Color {WHITE, GREY, BLACK};
  typedef DenseMap<const BasicBlock *, Color> BBColorMap;
  typedef SmallVector<const BasicBlock *, 32> BBVector;
  typedef DenseMap<const BasicBlock *, unsigned> BBIDMap;
  //  typedef DenseMap<std::string, unsigned> InstrMap;
  //  InstrMap IMap;
  std::map<std::string, int> IMap;
  BBColorMap ColorMap;
  BBIDMap IDMap, BEMap;
  std::deque<const BasicBlock*> Q;
  unsigned waveNo;

  void init (const Function &F);
  void setIMap(BasicBlock* bb, unsigned waveNo);
  void setBackEdges (const Function &F, SmallVectorImpl<std::pair<const BasicBlock*, const BasicBlock*> > *res);
  void setLabel(BasicBlock **succ, unsigned k);
};

/*
  Helper Functions
*/
std::string escapeString (const std::string &Label);

std::string insertWA ();
<commit_msg>added ifndef protector in header file<commit_after>/*
 * Spatial Computation - Manifestation of Spatial computing.
 * Copyright © 2014 Pranav Kant
 *
 * This code is available to you under Apache License Version 2.0, January
 * 2014. You can grab a copy of license from the same repository from where you
 * fetched this code.
 */

#ifndef SPATIAL_WAVES_HPP
#define SPATIAL_WAVES_HPP

#include "llvm/ADT/DenseMap.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/GraphWriter.h"

using namespace llvm;

class WaveScalar{
 public:
  void runBFS();
  void annotateWaves(const Function &F, SmallVectorImpl<std::pair<const BasicBlock*, const BasicBlock*> > *res);
  int isSameWave (Instruction* i, Instruction* e);
  int getWaveNo(std::string instruction);

 private:
  enum Color {WHITE, GREY, BLACK};
  typedef DenseMap<const BasicBlock *, Color> BBColorMap;
  typedef SmallVector<const BasicBlock *, 32> BBVector;
  typedef DenseMap<const BasicBlock *, unsigned> BBIDMap;
  //  typedef DenseMap<std::string, unsigned> InstrMap;
  //  InstrMap IMap;
  std::map<std::string, int> IMap;
  BBColorMap ColorMap;
  BBIDMap IDMap, BEMap;
  std::deque<const BasicBlock*> Q;
  unsigned waveNo;

  void init (const Function &F);
  void setIMap(BasicBlock* bb, unsigned waveNo);
  void setBackEdges (const Function &F, SmallVectorImpl<std::pair<const BasicBlock*, const BasicBlock*> > *res);
  void setLabel(BasicBlock **succ, unsigned k);
};

/*
  Helper Functions
*/
std::string escapeString (const std::string &Label);

std::string insertWA ();

#endif
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include <test_precomp.hpp>

#ifdef HAVE_CUDA

using cv::gpu::GpuMat;

TEST(SoftCascade, readCascade)
{
    std::string xml = cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/icf-template.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

}

TEST(SoftCascade, detect)
{
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path()
        + "../cv/cascadeandhog/bahnhof/image_00000000_0.png");
    ASSERT_FALSE(coloredCpu.empty());
    GpuMat colored(coloredCpu), objectBoxes(1, 1000, CV_8UC1), rois;

    // ASSERT_NO_THROW(
    // {
        cascade.detectMultiScale(colored, rois, objectBoxes);
    // });
}

#endif<commit_msg>add test that stores detections on the specific scale<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include <test_precomp.hpp>

#ifdef HAVE_CUDA

using cv::gpu::GpuMat;

TEST(SoftCascade, readCascade)
{
    std::string xml = cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/icf-template.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

}

TEST(SoftCascade, detect)
{
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path()
        + "../cv/cascadeandhog/bahnhof/image_00000000_0.png");
    ASSERT_FALSE(coloredCpu.empty());
    GpuMat colored(coloredCpu), objectBoxes(1, 1000, CV_8UC1), rois;

    // ASSERT_NO_THROW(
    // {
        cascade.detectMultiScale(colored, rois, objectBoxes);
    // });
}

class SCSpecific : public ::testing::TestWithParam<std::tr1::tuple<std::string, int> > {
};

namespace {
std::string itoa(long i)
{
    static char s[65];
    sprintf(s, "%ld", i);
    return std::string(s);
}
}

TEST_P(SCSpecific, detect)
{
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    std::string path = GET_PARAM(0);
    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path() + path);

    ASSERT_FALSE(coloredCpu.empty());
    GpuMat colored(coloredCpu), objectBoxes(1, 1000, CV_8UC1), rois;

    int level = GET_PARAM(1);
    cascade.detectMultiScale(colored, rois, objectBoxes, 1, level);

    cv::Mat dt(objectBoxes);
    typedef cv::gpu::SoftCascade::Detection detection_t;

    detection_t* dts = (detection_t*)dt.data;
    cv::Mat result(coloredCpu);

    std::cout << "Total detections " << (dt.cols / sizeof(detection_t)) << std::endl;
    for(int i = 0; i  < (int)(dt.cols / sizeof(detection_t)); ++i)
    {
        detection_t d = dts[i];
        std::cout << "detection: [" << std::setw(4) << d.x << " " << std::setw(4) << d.y
                  << "] [" << std::setw(4) << d.w << " " << std::setw(4) << d.h << "] "
                  << std::setw(12)  << d.confidence << std::endl;

        cv::rectangle(result, cv::Rect(d.x, d.y, d.w, d.h), cv::Scalar(255, 0, 0, 255), 1);
    }

    std::cout << "Result stored in " << "/home/kellan/gpu_res_1_oct_" + itoa(level) << "_"
    + itoa((dt.cols / sizeof(detection_t))) + ".png" << std::endl;
    cv::imwrite("/home/kellan/gpu_res_1_oct_" + itoa(level) + "_" + itoa((dt.cols / sizeof(detection_t))) + ".png",
        result);
    cv::imshow("res", result);
    cv::waitKey(0);
}

INSTANTIATE_TEST_CASE_P(inLevel, SCSpecific,
    testing::Combine(
        testing::Values(std::string("../cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 47)
        ));

#endif<|endoftext|>


<commit_before>/*************************************************************************/
/*  noise_texture.cpp                                                    */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "noise_texture.h"

#include "core/core_string_names.h"

NoiseTexture::NoiseTexture() {
	update_queued = false;
	noise_thread = NULL;
	regen_queued = false;
	first_time = true;

	size = Vector2i(512, 512);
	seamless = false;
	as_normalmap = false;
	bump_strength = 8.0;
	flags = FLAGS_DEFAULT;

	noise = Ref<OpenSimplexNoise>();

	texture = VS::get_singleton()->texture_create();

	_queue_update();
}

NoiseTexture::~NoiseTexture() {
	VS::get_singleton()->free(texture);
}

void NoiseTexture::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_width", "width"), &NoiseTexture::set_width);
	ClassDB::bind_method(D_METHOD("set_height", "height"), &NoiseTexture::set_height);

	ClassDB::bind_method(D_METHOD("set_noise", "noise"), &NoiseTexture::set_noise);
	ClassDB::bind_method(D_METHOD("get_noise"), &NoiseTexture::get_noise);

	ClassDB::bind_method(D_METHOD("set_seamless", "seamless"), &NoiseTexture::set_seamless);
	ClassDB::bind_method(D_METHOD("get_seamless"), &NoiseTexture::get_seamless);

	ClassDB::bind_method(D_METHOD("set_as_normalmap", "as_normalmap"), &NoiseTexture::set_as_normalmap);
	ClassDB::bind_method(D_METHOD("is_normalmap"), &NoiseTexture::is_normalmap);

	ClassDB::bind_method(D_METHOD("set_bump_strength", "bump_strength"), &NoiseTexture::set_bump_strength);
	ClassDB::bind_method(D_METHOD("get_bump_strength"), &NoiseTexture::get_bump_strength);

	ClassDB::bind_method(D_METHOD("_update_texture"), &NoiseTexture::_update_texture);
	ClassDB::bind_method(D_METHOD("_generate_texture"), &NoiseTexture::_generate_texture);
	ClassDB::bind_method(D_METHOD("_thread_done", "image"), &NoiseTexture::_thread_done);

	ADD_PROPERTY(PropertyInfo(Variant::INT, "width", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_width", "get_width");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "height", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_height", "get_height");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "seamless"), "set_seamless", "get_seamless");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "as_normalmap"), "set_as_normalmap", "is_normalmap");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "bump_strength", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater"), "set_bump_strength", "get_bump_strength");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "OpenSimplexNoise"), "set_noise", "get_noise");
}

void NoiseTexture::_validate_property(PropertyInfo &property) const {

	if (property.name == "bump_strength") {
		if (!as_normalmap) {
			property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
		}
	}
}

void NoiseTexture::_set_texture_data(const Ref<Image> &p_image) {
	data = p_image;
	if (data.is_valid()) {
		VS::get_singleton()->texture_allocate(texture, size.x, size.y, 0, Image::FORMAT_RGBA8, VS::TEXTURE_TYPE_2D, flags);
		VS::get_singleton()->texture_set_data(texture, p_image);
	}
	emit_changed();
}

void NoiseTexture::_thread_done(const Ref<Image> &p_image) {

	_set_texture_data(p_image);
	Thread::wait_to_finish(noise_thread);
	memdelete(noise_thread);
	noise_thread = NULL;
	if (regen_queued) {
		noise_thread = Thread::create(_thread_function, this);
		regen_queued = false;
	}
}

void NoiseTexture::_thread_function(void *p_ud) {
	NoiseTexture *tex = (NoiseTexture *)p_ud;
	tex->call_deferred("_thread_done", tex->_generate_texture());
}

void NoiseTexture::_queue_update() {

	if (update_queued)
		return;

	update_queued = true;
	call_deferred("_update_texture");
}

Ref<Image> NoiseTexture::_generate_texture() {

	update_queued = false;

	if (noise.is_null()) return Ref<Image>();

	Ref<Image> image;

	if (seamless) {
		image = noise->get_seamless_image(size.x);
	} else {
		image = noise->get_image(size.x, size.y);
	}

	if (as_normalmap) {
		image->bumpmap_to_normalmap(bump_strength);
	}

	return image;
}

void NoiseTexture::_update_texture() {
	bool use_thread = true;
	if (first_time) {
		use_thread = false;
		first_time = false;
	}
#ifdef NO_THREADS
	use_thread = false;
#endif
	if (use_thread) {

		if (!noise_thread) {
			noise_thread = Thread::create(_thread_function, this);
			regen_queued = false;
		} else {
			regen_queued = true;
		}

	} else {
		Ref<Image> image = _generate_texture();
		_set_texture_data(image);
	}
}

void NoiseTexture::set_noise(Ref<OpenSimplexNoise> p_noise) {
	if (p_noise == noise)
		return;
	if (noise.is_valid()) {
		noise->disconnect(CoreStringNames::get_singleton()->changed, this, "_update_texture");
	}
	noise = p_noise;
	if (noise.is_valid()) {
		noise->connect(CoreStringNames::get_singleton()->changed, this, "_update_texture");
	}
	_queue_update();
}

Ref<OpenSimplexNoise> NoiseTexture::get_noise() {
	return noise;
}

void NoiseTexture::set_width(int p_width) {
	if (p_width == size.x) return;
	size.x = p_width;
	_queue_update();
}

void NoiseTexture::set_height(int p_height) {
	if (p_height == size.y) return;
	size.y = p_height;
	_queue_update();
}

void NoiseTexture::set_seamless(bool p_seamless) {
	if (p_seamless == seamless) return;
	seamless = p_seamless;
	_queue_update();
}

bool NoiseTexture::get_seamless() {
	return seamless;
}

void NoiseTexture::set_as_normalmap(bool p_as_normalmap) {
	if (p_as_normalmap == as_normalmap) return;
	as_normalmap = p_as_normalmap;
	_queue_update();
	_change_notify();
}

bool NoiseTexture::is_normalmap() {
	return as_normalmap;
}

void NoiseTexture::set_bump_strength(float p_bump_strength) {

	if (p_bump_strength == bump_strength) return;
	bump_strength = p_bump_strength;
	if (as_normalmap)
		_queue_update();
}

float NoiseTexture::get_bump_strength() {

	return bump_strength;
}

int NoiseTexture::get_width() const {

	return size.x;
}

int NoiseTexture::get_height() const {

	return size.y;
}

void NoiseTexture::set_flags(uint32_t p_flags) {
	flags = p_flags;
	VS::get_singleton()->texture_set_flags(texture, flags);
}

uint32_t NoiseTexture::get_flags() const {
	return flags;
}

Ref<Image> NoiseTexture::get_data() const {

	return data;
}
<commit_msg>Make NoiseTexture threading more robust<commit_after>/*************************************************************************/
/*  noise_texture.cpp                                                    */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "noise_texture.h"

#include "core/core_string_names.h"

NoiseTexture::NoiseTexture() {
	update_queued = false;
	noise_thread = NULL;
	regen_queued = false;
	first_time = true;

	size = Vector2i(512, 512);
	seamless = false;
	as_normalmap = false;
	bump_strength = 8.0;
	flags = FLAGS_DEFAULT;

	noise = Ref<OpenSimplexNoise>();

	texture = VS::get_singleton()->texture_create();

	_queue_update();
}

NoiseTexture::~NoiseTexture() {
	VS::get_singleton()->free(texture);
	if (noise_thread) {
		Thread::wait_to_finish(noise_thread);
		memdelete(noise_thread);
	}
}

void NoiseTexture::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_width", "width"), &NoiseTexture::set_width);
	ClassDB::bind_method(D_METHOD("set_height", "height"), &NoiseTexture::set_height);

	ClassDB::bind_method(D_METHOD("set_noise", "noise"), &NoiseTexture::set_noise);
	ClassDB::bind_method(D_METHOD("get_noise"), &NoiseTexture::get_noise);

	ClassDB::bind_method(D_METHOD("set_seamless", "seamless"), &NoiseTexture::set_seamless);
	ClassDB::bind_method(D_METHOD("get_seamless"), &NoiseTexture::get_seamless);

	ClassDB::bind_method(D_METHOD("set_as_normalmap", "as_normalmap"), &NoiseTexture::set_as_normalmap);
	ClassDB::bind_method(D_METHOD("is_normalmap"), &NoiseTexture::is_normalmap);

	ClassDB::bind_method(D_METHOD("set_bump_strength", "bump_strength"), &NoiseTexture::set_bump_strength);
	ClassDB::bind_method(D_METHOD("get_bump_strength"), &NoiseTexture::get_bump_strength);

	ClassDB::bind_method(D_METHOD("_update_texture"), &NoiseTexture::_update_texture);
	ClassDB::bind_method(D_METHOD("_queue_update"), &NoiseTexture::_queue_update);
	ClassDB::bind_method(D_METHOD("_generate_texture"), &NoiseTexture::_generate_texture);
	ClassDB::bind_method(D_METHOD("_thread_done", "image"), &NoiseTexture::_thread_done);

	ADD_PROPERTY(PropertyInfo(Variant::INT, "width", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_width", "get_width");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "height", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_height", "get_height");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "seamless"), "set_seamless", "get_seamless");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "as_normalmap"), "set_as_normalmap", "is_normalmap");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "bump_strength", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater"), "set_bump_strength", "get_bump_strength");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "OpenSimplexNoise"), "set_noise", "get_noise");
}

void NoiseTexture::_validate_property(PropertyInfo &property) const {

	if (property.name == "bump_strength") {
		if (!as_normalmap) {
			property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
		}
	}
}

void NoiseTexture::_set_texture_data(const Ref<Image> &p_image) {
	data = p_image;
	if (data.is_valid()) {
		VS::get_singleton()->texture_allocate(texture, size.x, size.y, 0, Image::FORMAT_RGBA8, VS::TEXTURE_TYPE_2D, flags);
		VS::get_singleton()->texture_set_data(texture, p_image);
	}
	emit_changed();
}

void NoiseTexture::_thread_done(const Ref<Image> &p_image) {

	_set_texture_data(p_image);
	Thread::wait_to_finish(noise_thread);
	memdelete(noise_thread);
	noise_thread = NULL;
	if (regen_queued) {
		noise_thread = Thread::create(_thread_function, this);
		regen_queued = false;
	}
}

void NoiseTexture::_thread_function(void *p_ud) {
	NoiseTexture *tex = (NoiseTexture *)p_ud;
	tex->call_deferred("_thread_done", tex->_generate_texture());
}

void NoiseTexture::_queue_update() {

	if (update_queued)
		return;

	update_queued = true;
	call_deferred("_update_texture");
}

Ref<Image> NoiseTexture::_generate_texture() {

	if (noise.is_null()) return Ref<Image>();

	Ref<Image> image;

	if (seamless) {
		image = noise->get_seamless_image(size.x);
	} else {
		image = noise->get_image(size.x, size.y);
	}

	if (as_normalmap) {
		image->bumpmap_to_normalmap(bump_strength);
	}

	return image;
}

void NoiseTexture::_update_texture() {
	bool use_thread = true;
	if (first_time) {
		use_thread = false;
		first_time = false;
	}
#ifdef NO_THREADS
	use_thread = false;
#endif
	if (use_thread) {

		if (!noise_thread) {
			noise_thread = Thread::create(_thread_function, this);
			regen_queued = false;
		} else {
			regen_queued = true;
		}

	} else {
		Ref<Image> image = _generate_texture();
		_set_texture_data(image);
	}
	update_queued = false;
}

void NoiseTexture::set_noise(Ref<OpenSimplexNoise> p_noise) {
	if (p_noise == noise)
		return;
	if (noise.is_valid()) {
		noise->disconnect(CoreStringNames::get_singleton()->changed, this, "_queue_update");
	}
	noise = p_noise;
	if (noise.is_valid()) {
		noise->connect(CoreStringNames::get_singleton()->changed, this, "_queue_update");
	}
	_queue_update();
}

Ref<OpenSimplexNoise> NoiseTexture::get_noise() {
	return noise;
}

void NoiseTexture::set_width(int p_width) {
	if (p_width == size.x) return;
	size.x = p_width;
	_queue_update();
}

void NoiseTexture::set_height(int p_height) {
	if (p_height == size.y) return;
	size.y = p_height;
	_queue_update();
}

void NoiseTexture::set_seamless(bool p_seamless) {
	if (p_seamless == seamless) return;
	seamless = p_seamless;
	_queue_update();
}

bool NoiseTexture::get_seamless() {
	return seamless;
}

void NoiseTexture::set_as_normalmap(bool p_as_normalmap) {
	if (p_as_normalmap == as_normalmap) return;
	as_normalmap = p_as_normalmap;
	_queue_update();
	_change_notify();
}

bool NoiseTexture::is_normalmap() {
	return as_normalmap;
}

void NoiseTexture::set_bump_strength(float p_bump_strength) {

	if (p_bump_strength == bump_strength) return;
	bump_strength = p_bump_strength;
	if (as_normalmap)
		_queue_update();
}

float NoiseTexture::get_bump_strength() {

	return bump_strength;
}

int NoiseTexture::get_width() const {

	return size.x;
}

int NoiseTexture::get_height() const {

	return size.y;
}

void NoiseTexture::set_flags(uint32_t p_flags) {
	flags = p_flags;
	VS::get_singleton()->texture_set_flags(texture, flags);
}

uint32_t NoiseTexture::get_flags() const {
	return flags;
}

Ref<Image> NoiseTexture::get_data() const {

	return data;
}
<|endoftext|>