<commit_before>#include <cassert>
#include <algorithm>
#include "jsobject.h"
#include "property.h"
#include "jsfunction.h"
#include "jsval.h"
#include "jsenv.h"
#include "context.h"
#include "class.h"

namespace iv {
namespace lv5 {

JSObject::JSObject()
  : prototype_(NULL),
    class_name_(),
    extensible_(true),
    table_() {
}

JSObject::JSObject(JSObject* proto,
                   Symbol class_name,
                   bool extensible)
  : prototype_(proto),
    class_name_(class_name),
    extensible_(extensible),
    table_() {
}

#define TRY(context, sym, arg, error)\
  do {\
    const JSVal method = Get(context, sym, error);\
    if (*error) {\
      return JSUndefined;\
    }\
    if (method.IsCallable()) {\
      const JSVal val = method.object()->AsCallable()->Call(arg, error);\
      if (*error) {\
        return JSUndefined;\
      }\
      if (val.IsPrimitive() || val.IsNull() || val.IsUndefined()) {\
        return val;\
      }\
    }\
  } while (0)
JSVal JSObject::DefaultValue(Context* ctx,
                             Hint::Object hint, Error* res) {
  const Arguments args(ctx, this);
  if (hint == Hint::STRING) {
    // hint is STRING
    TRY(ctx, ctx->toString_symbol(), args, res);
    TRY(ctx, ctx->valueOf_symbol(), args, res);
  } else {
    // section 8.12.8
    // hint is NUMBER or NONE
    TRY(ctx, ctx->valueOf_symbol(), args, res);
    TRY(ctx, ctx->toString_symbol(), args, res);
  }
  res->Report(Error::Type, "invalid default value");
  return JSUndefined;
}
#undef TRY

JSVal JSObject::Get(Context* ctx,
                    Symbol name, Error* res) {
  const PropertyDescriptor desc = GetProperty(ctx, name);
  if (desc.IsEmpty()) {
    return JSUndefined;
  }
  if (desc.IsDataDescriptor()) {
    return desc.AsDataDescriptor()->value();
  } else {
    assert(desc.IsAccessorDescriptor());
    JSObject* const getter = desc.AsAccessorDescriptor()->get();
    if (getter) {
      return getter->AsCallable()->Call(Arguments(ctx, this), res);
    } else {
      return JSUndefined;
    }
  }
}

JSVal JSObject::GetWithIndex(Context* ctx,
                             uint32_t index, Error* res) {
  return Get(ctx, ctx->InternIndex(index), res);
}

// not recursion
PropertyDescriptor JSObject::GetProperty(Context* ctx, Symbol name) const {
  const JSObject* obj = this;
  do {
    const PropertyDescriptor prop = obj->GetOwnProperty(ctx, name);
    if (!prop.IsEmpty()) {
      return prop;
    }
    obj = obj->prototype();
  } while (obj);
  return JSUndefined;
}

PropertyDescriptor JSObject::GetPropertyWithIndex(Context* ctx,
                                                  uint32_t index) const {
  return GetProperty(ctx, ctx->InternIndex(index));
}

PropertyDescriptor JSObject::GetOwnProperty(Context* ctx, Symbol name) const {
  const Properties::const_iterator it = table_.find(name);
  if (it == table_.end()) {
    return JSUndefined;
  } else {
    return it->second;
  }
}

PropertyDescriptor JSObject::GetOwnPropertyWithIndex(Context* ctx,
                                                     uint32_t index) const {
  return GetOwnProperty(ctx, ctx->InternIndex(index));
}

bool JSObject::CanPut(Context* ctx, Symbol name) const {
  const PropertyDescriptor desc = GetOwnProperty(ctx, name);
  if (!desc.IsEmpty()) {
    if (desc.IsAccessorDescriptor()) {
      return desc.AsAccessorDescriptor()->set();
    } else {
      assert(desc.IsDataDescriptor());
      return desc.AsDataDescriptor()->IsWritable();
    }
  }
  if (!prototype_) {
    return extensible_;
  }
  const PropertyDescriptor inherited = prototype_->GetProperty(ctx, name);
  if (inherited.IsEmpty()) {
    return extensible_;
  } else {
    if (inherited.IsAccessorDescriptor()) {
      return inherited.AsAccessorDescriptor()->set();
    } else {
      assert(inherited.IsDataDescriptor());
      return inherited.AsDataDescriptor()->IsWritable();
    }
  }
}

bool JSObject::CanPutWithIndex(Context* ctx, uint32_t index) const {
  return CanPut(ctx, ctx->InternIndex(index));
}

#define REJECT(str)\
  do {\
    if (th) {\
      res->Report(Error::Type, str);\
    }\
    return false;\
  } while (0)

bool JSObject::DefineOwnProperty(Context* ctx,
                                 Symbol name,
                                 const PropertyDescriptor& desc,
                                 bool th,
                                 Error* res) {
  // section 8.12.9 [[DefineOwnProperty]]
  const PropertyDescriptor current = GetOwnProperty(ctx, name);
  if (current.IsEmpty()) {
    if (!extensible_) {
      REJECT("object not extensible");
    } else {
      if (!desc.IsAccessorDescriptor()) {
        assert(desc.IsDataDescriptor() || desc.IsGenericDescriptor());
        table_[name] = PropertyDescriptor::SetDefault(desc);
      } else {
        assert(desc.IsAccessorDescriptor());
        table_[name] = PropertyDescriptor::SetDefault(desc);
      }
      return true;
    }
  }

  // step 5
  if (PropertyDescriptor::IsAbsent(desc)) {
    return true;
  }
  // step 6
  if (PropertyDescriptor::Equals(desc, current)) {
    return true;
  }

  // step 7
  if (!current.IsConfigurable()) {
    if (desc.IsConfigurable()) {
      REJECT(
          "changing [[Configurable]] of unconfigurable property not allowed");
    }
    if (!desc.IsEnumerableAbsent() &&
        current.IsEnumerable() != desc.IsEnumerable()) {
      REJECT("changing [[Enumerable]] of unconfigurable property not allowed");
    }
  }

  // step 9
  if (desc.IsGenericDescriptor()) {
    // no further validation
  } else if (current.type() != desc.type()) {
    if (!current.IsConfigurable()) {
      REJECT("changing descriptor type of unconfigurable property not allowed");
    }
    if (current.IsDataDescriptor()) {
      assert(desc.IsAccessorDescriptor());
    } else {
      assert(desc.IsDataDescriptor());
    }
  } else {
    // step 10
    if (current.IsDataDescriptor()) {
      assert(desc.IsDataDescriptor());
      if (!current.IsConfigurable()) {
        if (!current.AsDataDescriptor()->IsWritable()) {
          const DataDescriptor* const data = desc.AsDataDescriptor();
          if (data->IsWritable()) {
            REJECT(
                "changing [[Writable]] of unconfigurable property not allowed");
          }
          if (SameValue(current.AsDataDescriptor()->value(),
                        data->value())) {
            REJECT("changing [[Value]] of readonly property not allowed");
          }
        }
      }
    } else {
      // step 11
      assert(desc.IsAccessorDescriptor());
      if (!current.IsConfigurableAbsent() && !current.IsConfigurable()) {
        const AccessorDescriptor* const lhs = current.AsAccessorDescriptor();
        const AccessorDescriptor* const rhs = desc.AsAccessorDescriptor();
        if ((lhs->set() && (lhs->set() != rhs->set())) ||
            (lhs->get() && (lhs->get() != rhs->get()))) {
          REJECT("changing [[Set]] or [[Get]] "
                 "of unconfigurable property not allowed");
        }
      }
    }
  }
  table_[name] = PropertyDescriptor::Merge(desc, current);
  return true;
}

bool JSObject::DefineOwnPropertyWithIndex(Context* ctx,
                                          uint32_t index,
                                          const PropertyDescriptor& desc,
                                          bool th,
                                          Error* res) {
  return DefineOwnProperty(ctx,
                           ctx->InternIndex(index),
                           desc, th, res);
}

#undef REJECT

void JSObject::Put(Context* ctx,
                   Symbol name,
                   const JSVal& val, bool th, Error* res) {
  if (!CanPut(ctx, name)) {
    if (th) {
      res->Report(Error::Type, "put failed");
    }
    return;
  }
  const PropertyDescriptor own_desc = GetOwnProperty(ctx, name);
  if (!own_desc.IsEmpty() && own_desc.IsDataDescriptor()) {
    DefineOwnProperty(ctx,
                      name,
                      DataDescriptor(
                          val,
                          PropertyDescriptor::UNDEF_ENUMERABLE |
                          PropertyDescriptor::UNDEF_CONFIGURABLE |
                          PropertyDescriptor::UNDEF_WRITABLE), th, res);
    return;
  }
  const PropertyDescriptor desc = GetProperty(ctx, name);
  if (!desc.IsEmpty() && desc.IsAccessorDescriptor()) {
    const AccessorDescriptor* const accs = desc.AsAccessorDescriptor();
    assert(accs->set());
    Arguments args(ctx, 1);
    args.set_this_binding(this);
    args[0] = val;
    accs->set()->AsCallable()->Call(args, res);
  } else {
    DefineOwnProperty(ctx, name,
                      DataDescriptor(val,
                                     PropertyDescriptor::WRITABLE |
                                     PropertyDescriptor::ENUMERABLE |
                                     PropertyDescriptor::CONFIGURABLE),
                      th, res);
  }
}

void JSObject::PutWithIndex(Context* ctx,
                            uint32_t index,
                            const JSVal& val, bool th, Error* res) {
  Put(ctx, ctx->InternIndex(index), val, th, res);
}

bool JSObject::HasProperty(Context* ctx, Symbol name) const {
  return !GetProperty(ctx, name).IsEmpty();
}

bool JSObject::HasPropertyWithIndex(Context* ctx, uint32_t index) const {
  return HasProperty(ctx, ctx->InternIndex(index));
}

bool JSObject::Delete(Context* ctx, Symbol name, bool th, Error* res) {
  const PropertyDescriptor desc = GetOwnProperty(ctx, name);
  if (desc.IsEmpty()) {
    return true;
  }
  if (desc.IsConfigurable()) {
    table_.erase(name);
    return true;
  } else {
    if (th) {
      res->Report(Error::Type, "delete failed");
    }
    return false;
  }
}

bool JSObject::DeleteWithIndex(Context* ctx, uint32_t index,
                               bool th, Error* res) {
  return Delete(ctx, ctx->InternIndex(index), th, res);
}

void JSObject::GetPropertyNames(Context* ctx,
                                std::vector<Symbol>* vec,
                                EnumerationMode mode) const {
  using std::find;
  GetOwnPropertyNames(ctx, vec, mode);
  const JSObject* obj = prototype_;
  while (obj) {
    obj->GetOwnPropertyNames(ctx, vec, mode);
    obj = obj->prototype();
  }
}

void JSObject::GetOwnPropertyNames(Context* ctx,
                                   std::vector<Symbol>* vec,
                                   EnumerationMode mode) const {
  using std::find;
  if (vec->empty()) {
    for (JSObject::Properties::const_iterator it = table_.begin(),
         last = table_.end(); it != last; ++it) {
      if (it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) {
        vec->push_back(it->first);
      }
    }
  } else {
    for (JSObject::Properties::const_iterator it = table_.begin(),
         last = table_.end(); it != last; ++it) {
      if ((it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) &&
          (find(vec->begin(), vec->end(), it->first) == vec->end())) {
        vec->push_back(it->first);
      }
    }
  }
}

JSObject* JSObject::New(Context* ctx) {
  JSObject* const obj = NewPlain(ctx);
  const Symbol name = ctx->Intern("Object");
  const Class& cls = ctx->Cls(name);
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

JSObject* JSObject::NewPlain(Context* ctx) {
  return new JSObject();
}

JSStringObject::JSStringObject(Context* ctx, JSString* value)
  : value_(value) {
  DefineOwnProperty(ctx, ctx->length_symbol(),
                    DataDescriptor(value->size(),
                                   PropertyDescriptor::NONE),
                                   false, ctx->error());
}

JSStringObject* JSStringObject::New(Context* ctx, JSString* str) {
  JSStringObject* const obj = new JSStringObject(ctx, str);
  const Symbol name = ctx->Intern("String");
  const Class& cls = ctx->Cls(name);
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

JSStringObject* JSStringObject::NewPlain(Context* ctx) {
  return new JSStringObject(ctx, JSString::NewEmptyString(ctx));
}

JSNumberObject* JSNumberObject::New(Context* ctx, const double& value) {
  JSNumberObject* const obj = new JSNumberObject(value);
  const Class& cls = ctx->Cls("Number");
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

JSNumberObject* JSNumberObject::NewPlain(Context* ctx, const double& value) {
  return new JSNumberObject(value);
}

JSBooleanObject* JSBooleanObject::NewPlain(Context* ctx, bool value) {
  return new JSBooleanObject(value);
}

JSBooleanObject* JSBooleanObject::New(Context* ctx, bool value) {
  JSBooleanObject* const obj = new JSBooleanObject(value);
  const Class& cls = ctx->Cls(ctx->Intern("Boolean"));
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

} }  // namespace iv::lv5
<commit_msg>fix 2<commit_after>#include <cassert>
#include <algorithm>
#include "jsobject.h"
#include "property.h"
#include "jsfunction.h"
#include "jsval.h"
#include "jsenv.h"
#include "context.h"
#include "class.h"

namespace iv {
namespace lv5 {

JSObject::JSObject()
  : prototype_(NULL),
    class_name_(),
    extensible_(true),
    table_() {
}

JSObject::JSObject(JSObject* proto,
                   Symbol class_name,
                   bool extensible)
  : prototype_(proto),
    class_name_(class_name),
    extensible_(extensible),
    table_() {
}

#define TRY(context, sym, arg, error)\
  do {\
    const JSVal method = Get(context, sym, error);\
    if (*error) {\
      return JSUndefined;\
    }\
    if (method.IsCallable()) {\
      const JSVal val = method.object()->AsCallable()->Call(arg, error);\
      if (*error) {\
        return JSUndefined;\
      }\
      if (val.IsPrimitive() || val.IsNull() || val.IsUndefined()) {\
        return val;\
      }\
    }\
  } while (0)
JSVal JSObject::DefaultValue(Context* ctx,
                             Hint::Object hint, Error* res) {
  const Arguments args(ctx, this);
  if (hint == Hint::STRING) {
    // hint is STRING
    TRY(ctx, ctx->toString_symbol(), args, res);
    TRY(ctx, ctx->valueOf_symbol(), args, res);
  } else {
    // section 8.12.8
    // hint is NUMBER or NONE
    TRY(ctx, ctx->valueOf_symbol(), args, res);
    TRY(ctx, ctx->toString_symbol(), args, res);
  }
  res->Report(Error::Type, "invalid default value");
  return JSUndefined;
}
#undef TRY

JSVal JSObject::Get(Context* ctx,
                    Symbol name, Error* res) {
  const PropertyDescriptor desc = GetProperty(ctx, name);
  if (desc.IsEmpty()) {
    return JSUndefined;
  }
  if (desc.IsDataDescriptor()) {
    return desc.AsDataDescriptor()->value();
  } else {
    assert(desc.IsAccessorDescriptor());
    JSObject* const getter = desc.AsAccessorDescriptor()->get();
    if (getter) {
      return getter->AsCallable()->Call(Arguments(ctx, this), res);
    } else {
      return JSUndefined;
    }
  }
}

JSVal JSObject::GetWithIndex(Context* ctx,
                             uint32_t index, Error* res) {
  return Get(ctx, ctx->InternIndex(index), res);
}

// not recursion
PropertyDescriptor JSObject::GetProperty(Context* ctx, Symbol name) const {
  const JSObject* obj = this;
  do {
    const PropertyDescriptor prop = obj->GetOwnProperty(ctx, name);
    if (!prop.IsEmpty()) {
      return prop;
    }
    obj = obj->prototype();
  } while (obj);
  return JSUndefined;
}

PropertyDescriptor JSObject::GetPropertyWithIndex(Context* ctx,
                                                  uint32_t index) const {
  return GetProperty(ctx, ctx->InternIndex(index));
}

PropertyDescriptor JSObject::GetOwnProperty(Context* ctx, Symbol name) const {
  const Properties::const_iterator it = table_.find(name);
  if (it == table_.end()) {
    return JSUndefined;
  } else {
    return it->second;
  }
}

PropertyDescriptor JSObject::GetOwnPropertyWithIndex(Context* ctx,
                                                     uint32_t index) const {
  return GetOwnProperty(ctx, ctx->InternIndex(index));
}

bool JSObject::CanPut(Context* ctx, Symbol name) const {
  const PropertyDescriptor desc = GetOwnProperty(ctx, name);
  if (!desc.IsEmpty()) {
    if (desc.IsAccessorDescriptor()) {
      return desc.AsAccessorDescriptor()->set();
    } else {
      assert(desc.IsDataDescriptor());
      return desc.AsDataDescriptor()->IsWritable();
    }
  }
  if (!prototype_) {
    return extensible_;
  }
  const PropertyDescriptor inherited = prototype_->GetProperty(ctx, name);
  if (inherited.IsEmpty()) {
    return extensible_;
  } else {
    if (inherited.IsAccessorDescriptor()) {
      return inherited.AsAccessorDescriptor()->set();
    } else {
      assert(inherited.IsDataDescriptor());
      return inherited.AsDataDescriptor()->IsWritable();
    }
  }
}

bool JSObject::CanPutWithIndex(Context* ctx, uint32_t index) const {
  return CanPut(ctx, ctx->InternIndex(index));
}

#define REJECT(str)\
  do {\
    if (th) {\
      res->Report(Error::Type, str);\
    }\
    return false;\
  } while (0)

bool JSObject::DefineOwnProperty(Context* ctx,
                                 Symbol name,
                                 const PropertyDescriptor& desc,
                                 bool th,
                                 Error* res) {
  // section 8.12.9 [[DefineOwnProperty]]
  const PropertyDescriptor current = GetOwnProperty(ctx, name);
  if (current.IsEmpty()) {
    if (!extensible_) {
      REJECT("object not extensible");
    } else {
      if (!desc.IsAccessorDescriptor()) {
        assert(desc.IsDataDescriptor() || desc.IsGenericDescriptor());
        table_[name] = PropertyDescriptor::SetDefault(desc);
      } else {
        assert(desc.IsAccessorDescriptor());
        table_[name] = PropertyDescriptor::SetDefault(desc);
      }
      return true;
    }
  }

  // step 5
  if (PropertyDescriptor::IsAbsent(desc)) {
    return true;
  }
  // step 6
  if (PropertyDescriptor::Equals(desc, current)) {
    return true;
  }

  // step 7
  if (!current.IsConfigurable()) {
    if (desc.IsConfigurable()) {
      REJECT(
          "changing [[Configurable]] of unconfigurable property not allowed");
    }
    if (!desc.IsEnumerableAbsent() &&
        current.IsEnumerable() != desc.IsEnumerable()) {
      REJECT("changing [[Enumerable]] of unconfigurable property not allowed");
    }
  }

  // step 9
  if (desc.IsGenericDescriptor()) {
    // no further validation
  } else if (current.type() != desc.type()) {
    if (!current.IsConfigurable()) {
      REJECT("changing descriptor type of unconfigurable property not allowed");
    }
    if (current.IsDataDescriptor()) {
      assert(desc.IsAccessorDescriptor());
    } else {
      assert(desc.IsDataDescriptor());
    }
  } else {
    // step 10
    if (current.IsDataDescriptor()) {
      assert(desc.IsDataDescriptor());
      if (!current.IsConfigurable()) {
        if (!current.AsDataDescriptor()->IsWritable()) {
          const DataDescriptor* const data = desc.AsDataDescriptor();
          if (data->IsWritable()) {
            REJECT(
                "changing [[Writable]] of unconfigurable property not allowed");
          }
          if (SameValue(current.AsDataDescriptor()->value(),
                        data->value())) {
            REJECT("changing [[Value]] of readonly property not allowed");
          }
        }
      }
    } else {
      // step 11
      assert(desc.IsAccessorDescriptor());
      if (!current.IsConfigurableAbsent() && !current.IsConfigurable()) {
        const AccessorDescriptor* const lhs = current.AsAccessorDescriptor();
        const AccessorDescriptor* const rhs = desc.AsAccessorDescriptor();
        if ((rhs->set() && (lhs->set() != rhs->set())) ||
            (rhs->get() && (lhs->get() != rhs->get()))) {
          REJECT("changing [[Set]] or [[Get]] "
                 "of unconfigurable property not allowed");
        }
      }
    }
  }
  table_[name] = PropertyDescriptor::Merge(desc, current);
  return true;
}

bool JSObject::DefineOwnPropertyWithIndex(Context* ctx,
                                          uint32_t index,
                                          const PropertyDescriptor& desc,
                                          bool th,
                                          Error* res) {
  return DefineOwnProperty(ctx,
                           ctx->InternIndex(index),
                           desc, th, res);
}

#undef REJECT

void JSObject::Put(Context* ctx,
                   Symbol name,
                   const JSVal& val, bool th, Error* res) {
  if (!CanPut(ctx, name)) {
    if (th) {
      res->Report(Error::Type, "put failed");
    }
    return;
  }
  const PropertyDescriptor own_desc = GetOwnProperty(ctx, name);
  if (!own_desc.IsEmpty() && own_desc.IsDataDescriptor()) {
    DefineOwnProperty(ctx,
                      name,
                      DataDescriptor(
                          val,
                          PropertyDescriptor::UNDEF_ENUMERABLE |
                          PropertyDescriptor::UNDEF_CONFIGURABLE |
                          PropertyDescriptor::UNDEF_WRITABLE), th, res);
    return;
  }
  const PropertyDescriptor desc = GetProperty(ctx, name);
  if (!desc.IsEmpty() && desc.IsAccessorDescriptor()) {
    const AccessorDescriptor* const accs = desc.AsAccessorDescriptor();
    assert(accs->set());
    Arguments args(ctx, 1);
    args.set_this_binding(this);
    args[0] = val;
    accs->set()->AsCallable()->Call(args, res);
  } else {
    DefineOwnProperty(ctx, name,
                      DataDescriptor(val,
                                     PropertyDescriptor::WRITABLE |
                                     PropertyDescriptor::ENUMERABLE |
                                     PropertyDescriptor::CONFIGURABLE),
                      th, res);
  }
}

void JSObject::PutWithIndex(Context* ctx,
                            uint32_t index,
                            const JSVal& val, bool th, Error* res) {
  Put(ctx, ctx->InternIndex(index), val, th, res);
}

bool JSObject::HasProperty(Context* ctx, Symbol name) const {
  return !GetProperty(ctx, name).IsEmpty();
}

bool JSObject::HasPropertyWithIndex(Context* ctx, uint32_t index) const {
  return HasProperty(ctx, ctx->InternIndex(index));
}

bool JSObject::Delete(Context* ctx, Symbol name, bool th, Error* res) {
  const PropertyDescriptor desc = GetOwnProperty(ctx, name);
  if (desc.IsEmpty()) {
    return true;
  }
  if (desc.IsConfigurable()) {
    table_.erase(name);
    return true;
  } else {
    if (th) {
      res->Report(Error::Type, "delete failed");
    }
    return false;
  }
}

bool JSObject::DeleteWithIndex(Context* ctx, uint32_t index,
                               bool th, Error* res) {
  return Delete(ctx, ctx->InternIndex(index), th, res);
}

void JSObject::GetPropertyNames(Context* ctx,
                                std::vector<Symbol>* vec,
                                EnumerationMode mode) const {
  using std::find;
  GetOwnPropertyNames(ctx, vec, mode);
  const JSObject* obj = prototype_;
  while (obj) {
    obj->GetOwnPropertyNames(ctx, vec, mode);
    obj = obj->prototype();
  }
}

void JSObject::GetOwnPropertyNames(Context* ctx,
                                   std::vector<Symbol>* vec,
                                   EnumerationMode mode) const {
  using std::find;
  if (vec->empty()) {
    for (JSObject::Properties::const_iterator it = table_.begin(),
         last = table_.end(); it != last; ++it) {
      if (it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) {
        vec->push_back(it->first);
      }
    }
  } else {
    for (JSObject::Properties::const_iterator it = table_.begin(),
         last = table_.end(); it != last; ++it) {
      if ((it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) &&
          (find(vec->begin(), vec->end(), it->first) == vec->end())) {
        vec->push_back(it->first);
      }
    }
  }
}

JSObject* JSObject::New(Context* ctx) {
  JSObject* const obj = NewPlain(ctx);
  const Symbol name = ctx->Intern("Object");
  const Class& cls = ctx->Cls(name);
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

JSObject* JSObject::NewPlain(Context* ctx) {
  return new JSObject();
}

JSStringObject::JSStringObject(Context* ctx, JSString* value)
  : value_(value) {
  DefineOwnProperty(ctx, ctx->length_symbol(),
                    DataDescriptor(value->size(),
                                   PropertyDescriptor::NONE),
                                   false, ctx->error());
}

JSStringObject* JSStringObject::New(Context* ctx, JSString* str) {
  JSStringObject* const obj = new JSStringObject(ctx, str);
  const Symbol name = ctx->Intern("String");
  const Class& cls = ctx->Cls(name);
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

JSStringObject* JSStringObject::NewPlain(Context* ctx) {
  return new JSStringObject(ctx, JSString::NewEmptyString(ctx));
}

JSNumberObject* JSNumberObject::New(Context* ctx, const double& value) {
  JSNumberObject* const obj = new JSNumberObject(value);
  const Class& cls = ctx->Cls("Number");
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

JSNumberObject* JSNumberObject::NewPlain(Context* ctx, const double& value) {
  return new JSNumberObject(value);
}

JSBooleanObject* JSBooleanObject::NewPlain(Context* ctx, bool value) {
  return new JSBooleanObject(value);
}

JSBooleanObject* JSBooleanObject::New(Context* ctx, bool value) {
  JSBooleanObject* const obj = new JSBooleanObject(value);
  const Class& cls = ctx->Cls(ctx->Intern("Boolean"));
  obj->set_class_name(cls.name);
  obj->set_prototype(cls.prototype);
  return obj;
}

} }  // namespace iv::lv5
<|endoftext|>


<commit_before>/*
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>

extern "C" {
    #include "libjsonnet.h"
}

std::string next_arg(unsigned &i, const std::vector<std::string> &args)
{
    i++;
    if (i >= args.size()) {
        std::cerr << "Expected another commandline argument." << std::endl;
        exit(EXIT_FAILURE);
    }
    return args[i];
}

/** Collect commandline args into a vector of strings, and expand -foo to -f -o -o. */
std::vector<std::string> simplify_args (int argc, const char **argv)
{
    std::vector<std::string> r;
    for (int i=1 ; i<argc ; ++i) {
        std::string arg = argv[i];
        if (arg == "--") {
            // Add this arg and all remaining ones without simplification.
            r.push_back(arg);
            while ((++i) < argc)
                r.push_back(argv[i]);
            break;
        }
        // Check if it is of the form -abc and convert to -a -b -c
        if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-') {
            for (unsigned j=1 ; j<arg.length() ; ++j) {
                r.push_back("-" + arg.substr(j,1));
            }
        } else {
            r.push_back(arg);
        }
    }
    return r;
}

void usage(std::ostream &o)
{
    o << "Usage:\n";
    o << "jsonnet {<option>} [<filename>]\n";
    o << "where <filename> defaults to - (stdin)\n";
    o << "and <option> can be:\n";
    o << "    -h / --help            This message\n";
    o << "    -e / --exec            Treat filename as code (requires explicit filename)\n";
    o << "    -E --env               Add an environment variable\n\n";
    o << "    -s / --max-stack <n>   Number of allowed stack frames\n";
    o << "    -t / --max-trace <n>   Max length of stack trace before cropping\n";
    o << "    --gc-min-objects       Do not run garbage collector until this many\n";
    o << "    --gc-growth-trigger    Run garbage collector after this amount of object growth\n";
    o << "    --debug-ast            Unparse the parsed AST without executing it\n\n";
    o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
    o << "The -- option suppresses option processing.  Note that since jsonnet programs can\n";
    o << "begin with -, it is advised to use -- with -e if the program is unknown.";
    o << std::endl;
}

long strtol_check(const std::string &str)
{
    const char *arg = str.c_str();
    char *ep;
    long r = std::strtol(arg, &ep, 10);
    if (*ep != '\0' || *arg == '\0') {
        std::cerr << "ERROR: Invalid integer \"" << arg << "\"\n" << std::endl;
        usage(std::cerr);
        exit(EXIT_FAILURE);
    }
    return r;
}

int main(int argc, const char **argv)
{
    JsonnetVM *vm = jsonnet_make();
    std::string filename = "-";
    bool filename_is_code = false;

    auto args = simplify_args(argc, argv);
    std::vector<std::string> remaining_args;

    for (unsigned i=0 ; i<args.size() ; ++i) {
        const std::string &arg = args[i];
        if (arg == "-h" || arg == "--help") {
            usage(std::cout);
            exit(EXIT_SUCCESS);
        } else if (arg == "-s" || arg == "--max-stack") {
            long l = strtol_check(next_arg(i, args));
            if (l < 1) {
                std::cerr << "ERROR: Invalid --max-stack value: " << l << "\n" << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_max_stack(vm, l);
        } else if (arg == "-E" || arg == "--env") {
            const std::string &var = next_arg(i, args);
            const char *val = ::getenv(var.c_str());
            if (val == nullptr) {
                std::cerr << "ERROR: Environment variable " << var << " was undefined." << std::endl;
                exit(EXIT_FAILURE);
            }
            jsonnet_env(vm, var.c_str(), val);
        } else if (arg == "--gc-min-objects") {
            long l = strtol_check(next_arg(i, args));
            if (l < 0) {
                std::cerr << "ERROR: Invalid --gc-min-objects value: " << l << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_gc_min_objects(vm, l);
        } else if (arg == "-t" || arg == "--max-trace") {
            long l = strtol_check(next_arg(i, args));
            if (l < 0) {
                std::cerr << "ERROR: Invalid --max-trace value: " << l << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_max_trace(vm, l);
        } else if (arg == "--gc-growth-trigger") {
            const char *arg = next_arg(i,args).c_str();
            char *ep;
            double v = std::strtod(arg, &ep);
            if (*ep != '\0' || *arg == '\0') {
                std::cerr << "ERROR: Invalid number \"" << arg << "\"" << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            if (v < 0) {
                std::cerr << "ERROR: Invalid --gc-growth-trigger \"" << arg << "\"\n" << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_gc_growth_trigger(vm, v);
        } else if (arg == "-e" || arg == "--exec") {
            filename_is_code = true;
        } else if (arg == "--debug-ast") {
            jsonnet_debug_ast(vm, true);
        } else if (arg == "--") {
            // All subsequent args are not options.
            while ((++i) < args.size())
                remaining_args.push_back(args[i]);
            break;
        } else {
            remaining_args.push_back(args[i]);
        }
    }

    if (remaining_args.size() > 0)
        filename = remaining_args[0];

    if (remaining_args.size() > 1) {
        std::cerr << "ERROR: Filename already specified as \"" << filename << "\"\n"
                  << std::endl;
        usage(std::cerr);
        exit(EXIT_FAILURE);
    }

    if (filename_is_code && remaining_args.size() == 0) {
        std::cerr << "ERROR: Must give filename when using -e, --exec\n" << std::endl;
        usage(std::cerr);
        exit(EXIT_FAILURE);
    }

    std::string input;
    if (filename_is_code) {
        input = filename;
        filename = "<cmdline>";
    } else {
        if (filename == "-") {
            filename = "<stdin>";
            input.assign(std::istreambuf_iterator<char>(std::cin),
                         std::istreambuf_iterator<char>());
        } else {
            std::ifstream f;
            f.open(filename.c_str());
            if (!f.good()) {
                std::string msg = "Opening input file: " + filename;
                perror(msg.c_str());
                return EXIT_FAILURE;
            }
            input.assign(std::istreambuf_iterator<char>(f),
                         std::istreambuf_iterator<char>());
            if (!f.good()) {
                std::string msg = "Reading input file: " + filename;
                perror(msg.c_str());
                return EXIT_FAILURE;
            }
        }
    }

    int error;
    const char *output =
        jsonnet_evaluate_snippet(vm, filename.c_str(), input.c_str(), &error);

    if (error) {
        std::cerr << output;
        std::cerr.flush();
        jsonnet_cleanup_string(vm, output);
        jsonnet_destroy(vm);
        return EXIT_FAILURE;
    }

    std::cout << output;
    std::cout.flush();
    jsonnet_cleanup_string(vm, output);
    jsonnet_destroy(vm);
    return EXIT_SUCCESS;
}

<commit_msg>Fix --help output<commit_after>/*
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>

extern "C" {
    #include "libjsonnet.h"
}

std::string next_arg(unsigned &i, const std::vector<std::string> &args)
{
    i++;
    if (i >= args.size()) {
        std::cerr << "Expected another commandline argument." << std::endl;
        exit(EXIT_FAILURE);
    }
    return args[i];
}

/** Collect commandline args into a vector of strings, and expand -foo to -f -o -o. */
std::vector<std::string> simplify_args (int argc, const char **argv)
{
    std::vector<std::string> r;
    for (int i=1 ; i<argc ; ++i) {
        std::string arg = argv[i];
        if (arg == "--") {
            // Add this arg and all remaining ones without simplification.
            r.push_back(arg);
            while ((++i) < argc)
                r.push_back(argv[i]);
            break;
        }
        // Check if it is of the form -abc and convert to -a -b -c
        if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-') {
            for (unsigned j=1 ; j<arg.length() ; ++j) {
                r.push_back("-" + arg.substr(j,1));
            }
        } else {
            r.push_back(arg);
        }
    }
    return r;
}

void usage(std::ostream &o)
{
    o << "Usage:\n";
    o << "jsonnet {<option>} [<filename>]\n";
    o << "where <filename> defaults to - (stdin)\n";
    o << "and <option> can be:\n";
    o << "  -h / --help             This message\n";
    o << "  -e / --exec             Treat filename as code (requires explicit filename)\n";
    o << "  -E / --env              Add an environment variable\n\n";
    o << "  -s / --max-stack <n>    Number of allowed stack frames\n";
    o << "  -t / --max-trace <n>    Max length of stack trace before cropping\n";
    o << "  --gc-min-objects <n>    Do not run garbage collector until this many\n";
    o << "  --gc-growth-trigger <n> Run garbage collector after this amount of object growth\n";
    o << "  --debug-ast             Unparse the parsed AST without executing it\n\n";
    o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
    o << "The -- option suppresses option processing.  Note that since jsonnet programs can\n";
    o << "begin with -, it is advised to use -- with -e if the program is unknown.";
    o << std::endl;
}

long strtol_check(const std::string &str)
{
    const char *arg = str.c_str();
    char *ep;
    long r = std::strtol(arg, &ep, 10);
    if (*ep != '\0' || *arg == '\0') {
        std::cerr << "ERROR: Invalid integer \"" << arg << "\"\n" << std::endl;
        usage(std::cerr);
        exit(EXIT_FAILURE);
    }
    return r;
}

int main(int argc, const char **argv)
{
    JsonnetVM *vm = jsonnet_make();
    std::string filename = "-";
    bool filename_is_code = false;

    auto args = simplify_args(argc, argv);
    std::vector<std::string> remaining_args;

    for (unsigned i=0 ; i<args.size() ; ++i) {
        const std::string &arg = args[i];
        if (arg == "-h" || arg == "--help") {
            usage(std::cout);
            exit(EXIT_SUCCESS);
        } else if (arg == "-s" || arg == "--max-stack") {
            long l = strtol_check(next_arg(i, args));
            if (l < 1) {
                std::cerr << "ERROR: Invalid --max-stack value: " << l << "\n" << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_max_stack(vm, l);
        } else if (arg == "-E" || arg == "--env") {
            const std::string &var = next_arg(i, args);
            const char *val = ::getenv(var.c_str());
            if (val == nullptr) {
                std::cerr << "ERROR: Environment variable " << var << " was undefined." << std::endl;
                exit(EXIT_FAILURE);
            }
            jsonnet_env(vm, var.c_str(), val);
        } else if (arg == "--gc-min-objects") {
            long l = strtol_check(next_arg(i, args));
            if (l < 0) {
                std::cerr << "ERROR: Invalid --gc-min-objects value: " << l << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_gc_min_objects(vm, l);
        } else if (arg == "-t" || arg == "--max-trace") {
            long l = strtol_check(next_arg(i, args));
            if (l < 0) {
                std::cerr << "ERROR: Invalid --max-trace value: " << l << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_max_trace(vm, l);
        } else if (arg == "--gc-growth-trigger") {
            const char *arg = next_arg(i,args).c_str();
            char *ep;
            double v = std::strtod(arg, &ep);
            if (*ep != '\0' || *arg == '\0') {
                std::cerr << "ERROR: Invalid number \"" << arg << "\"" << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            if (v < 0) {
                std::cerr << "ERROR: Invalid --gc-growth-trigger \"" << arg << "\"\n" << std::endl;
                usage(std::cerr);
                exit(EXIT_FAILURE);
            }
            jsonnet_gc_growth_trigger(vm, v);
        } else if (arg == "-e" || arg == "--exec") {
            filename_is_code = true;
        } else if (arg == "--debug-ast") {
            jsonnet_debug_ast(vm, true);
        } else if (arg == "--") {
            // All subsequent args are not options.
            while ((++i) < args.size())
                remaining_args.push_back(args[i]);
            break;
        } else {
            remaining_args.push_back(args[i]);
        }
    }

    if (remaining_args.size() > 0)
        filename = remaining_args[0];

    if (remaining_args.size() > 1) {
        std::cerr << "ERROR: Filename already specified as \"" << filename << "\"\n"
                  << std::endl;
        usage(std::cerr);
        exit(EXIT_FAILURE);
    }

    if (filename_is_code && remaining_args.size() == 0) {
        std::cerr << "ERROR: Must give filename when using -e, --exec\n" << std::endl;
        usage(std::cerr);
        exit(EXIT_FAILURE);
    }

    std::string input;
    if (filename_is_code) {
        input = filename;
        filename = "<cmdline>";
    } else {
        if (filename == "-") {
            filename = "<stdin>";
            input.assign(std::istreambuf_iterator<char>(std::cin),
                         std::istreambuf_iterator<char>());
        } else {
            std::ifstream f;
            f.open(filename.c_str());
            if (!f.good()) {
                std::string msg = "Opening input file: " + filename;
                perror(msg.c_str());
                return EXIT_FAILURE;
            }
            input.assign(std::istreambuf_iterator<char>(f),
                         std::istreambuf_iterator<char>());
            if (!f.good()) {
                std::string msg = "Reading input file: " + filename;
                perror(msg.c_str());
                return EXIT_FAILURE;
            }
        }
    }

    int error;
    const char *output =
        jsonnet_evaluate_snippet(vm, filename.c_str(), input.c_str(), &error);

    if (error) {
        std::cerr << output;
        std::cerr.flush();
        jsonnet_cleanup_string(vm, output);
        jsonnet_destroy(vm);
        return EXIT_FAILURE;
    }

    std::cout << output;
    std::cout.flush();
    jsonnet_cleanup_string(vm, output);
    jsonnet_destroy(vm);
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <math.h>
#include <stdio.h>

using namespace cv;
using namespace std;

int main()
{

	//char dir[100]={"/home/sedrica/Desktop/images.jpg"};

	Mat img;
	img=imread("images.jpg", CV_LOAD_IMAGE_COLOR); // reading the rgb image in Mat data struct

	Mat img_bw;
	cvtColor(img, img_bw,COLOR_RGB2GRAY);  // conversion to greayscale
/*

note: we may have to either pre process the image or not work with the custom bgr to greyscale or both
	  as they might not be able to detect edge very well
*/

	Mat grad_x, grad_y;    // derivative along x and y direction respectively
    Mat square_grad_x, square_grad_y;   // absoute value of derivative

    /// Gradient  along X direction
	Sobel( img_bw, grad_x,CV_16S, 1, 0, 3, 1,0, BORDER_DEFAULT );
	/// Gradient  along y direction
	Sobel( img_bw, grad_y,CV_16S, 0, 1, 3, 1, 0, BORDER_DEFAULT );

	square_grad_y=grad_y.mul(grad_y);
	square_grad_x=grad_x.mul(grad_x);

	Mat img_edge;

    addWeighted( square_grad_x,1, square_grad_y, 0.5, 0,img_edge);    // more weight is provided in the horizontal direction for more importance to lane detection

    Mat img_edge_dilated;
    Point anchor=Point(-1,-1);
    Size str_elem_dim_11;
    str_elem_dim_11=Size(11,11);

    Mat rect_str_elem=getStructuringElement(MORPH_RECT,str_elem_dim_11,anchor);

    dilate(img_edge,img_edge_dilated,rect_str_elem);
/*
    Mat img_eroded;
    Mat circ_str_elem=getStructuringElement(MORPH_ELLIPSE,str_elem_dim_11,anchor);
    erode( img_edge_dilated,img_eroded,circ_str_elem);
*/
    Mat img_flood_fill;
    Point origin=Point(0,0);  // is this have to be origin or (-1,-1) ?

    floodFill(img_flood_fill,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

    Mat img_openloops_removed;

    morphologyEx(img_flood_fill,img_openloops_removed,MORPH_OPEN,rect_str_elem);  // <------ confirm it

    Mat img_small_closedloops_removed;
	morphologyEx(img_openloops_removed,img_small_closedloops_removed,MORPH_OPENCLOSED,rect_str_elem);  // comfirm it

	Mat img_erode_post_fill1;img_erode_post_erode;

	erode(img_small_closedloops_removed,img_erode_post_fill1,circ_str_elem);
	erode(img_erode_post_fill1,img_erode_post_erode,circ_str_elem);

	Mat img_final_filled;
	floodFill(img_final_filled,origin,Scalar(255),);   /// got an issue with arguments SCALAR

////////////////////////////////////////////////////////////////////////////

	int connected_components_count;

	Mat img_label;
	connected_components_count=onnectedComponents(img_final_filled,img_label,8,int ltype=cv_32s);

	Mat label;
	label = // add matlab labelmatrix function equivalent of opencv

	Mat final_color_segmented;
	applyColorMap(label,final_color_segmented, COLORMAP_JET);

	return 0;
}
<commit_msg>flood fill 2<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <math.h>
#include <stdio.h>

using namespace cv;
using namespace std;

int main()
{

	//char dir[100]={"/home/sedrica/Desktop/images.jpg"};

	Mat img;
	img=imread("images.jpg", CV_LOAD_IMAGE_COLOR); // reading the rgb image in Mat data struct

	Mat img_bw;
	cvtColor(img, img_bw,COLOR_RGB2GRAY);  // conversion to greayscale
/*

note: we may have to either pre process the image or not work with the custom bgr to greyscale or both
	  as they might not be able to detect edge very well
*/

	Mat grad_x, grad_y;    // derivative along x and y direction respectively
    Mat square_grad_x, square_grad_y;   // absoute value of derivative

    /// Gradient  along X direction
	Sobel( img_bw, grad_x,CV_16S, 1, 0, 3, 1,0, BORDER_DEFAULT );
	/// Gradient  along y direction
	Sobel( img_bw, grad_y,CV_16S, 0, 1, 3, 1, 0, BORDER_DEFAULT );

	square_grad_y=grad_y.mul(grad_y);
	square_grad_x=grad_x.mul(grad_x);

	Mat img_edge;

    addWeighted( square_grad_x,1, square_grad_y, 0.5, 0,img_edge);    // more weight is provided in the horizontal direction for more importance to lane detection

    Mat img_edge_dilated;
    Point anchor=Point(-1,-1);
    Size str_elem_dim_11;
    str_elem_dim_11=Size(11,11);

    Mat rect_str_elem=getStructuringElement(MORPH_RECT,str_elem_dim_11,anchor);

    dilate(img_edge,img_edge_dilated,rect_str_elem);
/*
    Mat img_eroded;
    Mat circ_str_elem=getStructuringElement(MORPH_ELLIPSE,str_elem_dim_11,anchor);
    erode( img_edge_dilated,img_eroded,circ_str_elem);
*/
    Mat img_flood_fill;
    Point origin=Point(0,0);  // is this have to be origin or (-1,-1) ?

    floodFill(img_flood_fill,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

    Mat img_openloops_removed;

    morphologyEx(img_flood_fill,img_openloops_removed,MORPH_OPEN,rect_str_elem);  // <------ confirm it

    Mat img_small_closedloops_removed;
	morphologyEx(img_openloops_removed,img_small_closedloops_removed,MORPH_OPENCLOSED,rect_str_elem);  // comfirm it

	Mat img_erode_post_fill1;img_erode_post_erode;

	erode(img_small_closedloops_removed,img_erode_post_fill1,circ_str_elem);
	erode(img_erode_post_fill1,img_erode_post_erode,circ_str_elem);

	Mat img_final_filled;
	floodFill(img_final_filled,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

////////////////////////////////////////////////////////////////////////////

	int connected_components_count;

	Mat img_label;
	connected_components_count=onnectedComponents(img_final_filled,img_label,8,int ltype=cv_32s);

	Mat label;
	label = // add matlab labelmatrix function equivalent of opencv

	Mat final_color_segmented;
	applyColorMap(label,final_color_segmented, COLORMAP_JET);

	return 0;
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkRawImageReadWrite.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

#include "itkImage.h"

// Include generic Input Source
#include "itkImageFileReader.h"

// Incluide generic Output Sink
#include "itkImageFileWriter.h"

// Include file-format specific readers/writers
#include "itkRawImageIO.h"

int main(int argc, char **argv)
{

  // Taking parameters from the command line

  if( argc < 6 )
    {
    std::cerr << std::endl;
    std::cerr << "Usage:  RawImageReadWrite  inputImageFile.raw   sizeX   sizeY   sizeZ   outputImageFile.raw" << std::endl;
    std::cerr << std::endl;
    return -1;
    }

  const char * inputFileName  = argv[1];
  const char * outputFileName = argv[5];

  const unsigned int nx = atoi( argv[2] );
  const unsigned int ny = atoi( argv[3] );
  const unsigned int nz = atoi( argv[4] );

  typedef  unsigned char    PixelType;
  const    unsigned int     Dimension = 3;

  typedef  itk::Image< PixelType, Dimension >     ImageType;

  // Read a Raw File
  typedef  itk::ImageFileReader< ImageType >      FileSourceType;
  typedef  itk::RawImageIO<PixelType,Dimension>   RawReaderType;

  FileSourceType::Pointer fileSource = FileSourceType::New();
  fileSource->SetFileName( inputFileName );

  RawReaderType::Pointer  rawReader  = RawReaderType::New();
  rawReader->SetDimensions( 0, nx );
  rawReader->SetDimensions( 1, ny );
  rawReader->SetDimensions( 2, nz );

  fileSource->SetImageIO( rawReader );

  try
    {
    fileSource->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during Raw file reading " << std::endl;
    std::cerr << e << std::endl;
    return -1;
    }

  std::cout << "File succesfully read ! " << std::endl;

  // Print information about the image
  ImageType::Pointer  image = fileSource->GetOutput();
  image->Print( std::cout );

  // Write a Raw File
  typedef  itk::ImageFileWriter< ImageType >      FileSinkType;
  typedef  itk::RawImageIO<PixelType,Dimension>   RawWriterType;

  FileSinkType::Pointer   fileSink   = FileSinkType::New();
  RawWriterType::Pointer  rawWriter  = RawWriterType::New();

  fileSink->SetImageIO( rawWriter );
  fileSink->SetFileName( outputFileName );
  fileSink->SetInput( image );

  try
    {
    fileSink->Write();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during Raw file writing " << std::endl;
    std::cerr << e << std::endl;
    return -1;
    }

  std::cout << "File succesfully writen ! " << std::endl;

  return 0;

}

<commit_msg>FIX: FileDimensionality( 3 ) was missing. Print's removed.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkRawImageReadWrite.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

#include "itkImage.h"

// Include generic Input Source
#include "itkImageFileReader.h"

// Incluide generic Output Sink
#include "itkImageFileWriter.h"

// Include file-format specific readers/writers
#include "itkRawImageIO.h"

int main(int argc, char **argv)
{

  // Taking parameters from the command line

  if( argc < 6 )
    {
    std::cerr << std::endl;
    std::cerr << "Usage:  RawImageReadWrite  inputImageFile.raw   sizeX   sizeY   sizeZ   outputImageFile.raw" << std::endl;
    std::cerr << std::endl;
    return -1;
    }

  const char * inputFileName  = argv[1];
  const char * outputFileName = argv[5];

  const unsigned int nx = atoi( argv[2] );
  const unsigned int ny = atoi( argv[3] );
  const unsigned int nz = atoi( argv[4] );

  typedef  unsigned char    PixelType;
  const    unsigned int     Dimension = 3;

  typedef  itk::Image< PixelType, Dimension >     ImageType;

  // Read a Raw File
  typedef  itk::ImageFileReader< ImageType >      FileSourceType;
  typedef  itk::RawImageIO<PixelType,Dimension>   RawReaderType;

  FileSourceType::Pointer fileSource = FileSourceType::New();
  fileSource->SetFileName( inputFileName );

  RawReaderType::Pointer  rawReader  = RawReaderType::New();
  rawReader->SetFileDimensionality( 3 );
  rawReader->SetDimensions( 0, nx );
  rawReader->SetDimensions( 1, ny );
  rawReader->SetDimensions( 2, nz );

  fileSource->SetImageIO( rawReader );

  try
    {
    fileSource->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during Raw file reading " << std::endl;
    std::cerr << e << std::endl;
    return -1;
    }

  std::cout << "File succesfully read ! " << std::endl;

  // Write a Raw File
  typedef  itk::ImageFileWriter< ImageType >      FileSinkType;
  typedef  itk::RawImageIO<PixelType,Dimension>   RawWriterType;

  FileSinkType::Pointer   fileSink   = FileSinkType::New();
  RawWriterType::Pointer  rawWriter  = RawWriterType::New();

  fileSink->SetImageIO( rawWriter );
  fileSink->SetFileName( outputFileName );
  fileSink->SetInput( fileSource->GetOutput() );

  try
    {
    fileSink->Write();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during Raw file writing " << std::endl;
    std::cerr << e << std::endl;
    return -1;
    }

  std::cout << "File succesfully writen ! " << std::endl;

  return 0;

}

<|endoftext|>


<commit_before>// Copyright (2015) Gustav

#include "ride/builtinthemes.h"

#include <string>

typedef google::protobuf::RepeatedPtrField<ride::Theme> ThemeList;

ride::Theme* GetOrCreateTheme(ThemeList* themes, const std::string& name) {
  for (ride::Theme& t : *themes) {
    if (t.name() == name) return &t;
  }

  ride::Theme* temp = themes->Add();
  temp->set_name(name);
  temp->set_can_remove(false);
  return temp;
}

ride::Color Color(google::protobuf::int32 r, google::protobuf::int32 g,
                  google::protobuf::int32 b) {
  ride::Color c;

  c.set_r(r);
  c.set_g(g);
  c.set_b(b);

  return c;
}

ride::Color Color(google::protobuf::int32 c) { return Color(c, c, c); }

ride::Style Style(ride::Color* front, ride::Color* back = NULL,
                  bool bold = false) {
  ride::Style style;

  if (front) {
    style.set_use_foreground(true);
    style.set_allocated_foreground(front);
  }

  if (back) {
    style.set_use_background(true);
    style.set_allocated_background(back);
  }

  if (bold) {
    style.set_use_bold(true);
    style.set_bold(true);
  }

  return style;
}

template <typename T>
T* New(const T& t) {
  return new T(t);
}

ride::Indicator Indicator(const ride::Color& c) {
  ride::Indicator ind;
  ind.set_allocated_foreground(New(c));
  return ind;
}

//////////////////////////////////////////////////////////////////////////

class BasicThemeBuilder {
 public:
  BasicThemeBuilder& set_selection_foreground(const ride::Color& c) {
    selection_foreground_ = c;
    return *this;
  }
  BasicThemeBuilder& set_selection_background(const ride::Color& c) {
    selection_background_ = c;
    return *this;
  }
  BasicThemeBuilder& set_front(const ride::Color& c) {
    front_ = c;
    return *this;
  }
  BasicThemeBuilder& set_bkg(const ride::Color& c) {
    bkg_ = c;
    return *this;
  }
  BasicThemeBuilder& set_fold_hi(const ride::Color& c) {
    fold_hi_ = c;
    return *this;
  }
  BasicThemeBuilder& set_fold_lo(const ride::Color& c) {
    fold_lo_ = c;
    return *this;
  }
  BasicThemeBuilder& set_selected_line(const ride::Color& c) {
    selected_line_ = c;
    return *this;
  }
  BasicThemeBuilder& set_comment(const ride::Color& c) {
    comment_ = c;
    return *this;
  }
  BasicThemeBuilder& set_keyword(const ride::Color& c) {
    keyword_ = c;
    return *this;
  }
  BasicThemeBuilder& set_error(const ride::Color& c) {
    error_ = c;
    return *this;
  }
  BasicThemeBuilder& set_error_front(const ride::Color& c) {
    error_front_ = c;
    return *this;
  }
  BasicThemeBuilder& set_warning(const ride::Color& c) {
    warning_ = c;
    return *this;
  }
  BasicThemeBuilder& set_warning_front(const ride::Color& c) {
    warning_front_ = c;
    return *this;
  }
  BasicThemeBuilder& set_search_hi(const ride::Color& c) {
    search_hi_ = c;
    return *this;
  }
  BasicThemeBuilder& set_select_hi(const ride::Color& c) {
    select_hi_ = c;
    return *this;
  }

  const ride::Color& selection_foreground() { return selection_foreground_; }
  const ride::Color& selection_background() { return selection_background_; }
  const ride::Color& front() { return front_; }
  const ride::Color& bkg() { return bkg_; }
  const ride::Color& fold_hi() { return fold_hi_; }
  const ride::Color& fold_lo() { return fold_lo_; }
  const ride::Color& selected_line() { return selected_line_; }
  const ride::Color& comment() { return comment_; }
  const ride::Color& keyword() { return keyword_; }
  const ride::Color& error() { return error_; }
  const ride::Color& error_front() { return error_front_; }
  const ride::Color& warning() { return warning_; }
  const ride::Color& warning_front() { return warning_front_; }
  const ride::Color& search_hi() { return search_hi_; }
  const ride::Color& select_hi() { return select_hi_; }

  void Setup(ride::FontsAndColors* colors) {
    colors->set_use_selection_background(true);
    colors->set_use_selection_foreground(true);
    colors->set_allocated_selection_foreground(New(selection_foreground_));
    colors->set_allocated_selection_background(New(selection_background_));

    colors->set_allocated_default_style(New(Style(New(front_), New(bkg_))));
    colors->set_allocated_line_number_style(New(Style(NULL, New(bkg_))));
    colors->set_allocated_fold_margin_hi(New(fold_hi_));
    colors->set_allocated_fold_margin_low(New(fold_lo_));

    colors->set_allocated_selected_line(New(selected_line_));  // yellow

    colors->set_allocated_style_comment(New(Style(New(comment_))));
    colors->set_allocated_style_commentline(New(Style(New(comment_))));
    colors->set_allocated_style_commentdoc(New(Style(New(comment_))));
    colors->set_allocated_style_commentlinedoc(New(Style(New(comment_))));
    colors->set_allocated_style_keyword(New(Style(New(keyword_), NULL, true)));

    colors->set_allocated_folderend_foreground(New(front_));
    colors->set_allocated_folderopenmid_foreground(New(front_));
    colors->set_allocated_foldermidtail_foreground(New(front_));
    colors->set_allocated_foldertail_foreground(New(front_));
    colors->set_allocated_foldersub_foreground(New(front_));
    colors->set_allocated_folder_foreground(New(front_));
    colors->set_allocated_folderopen_foreground(New(front_));

    colors->set_allocated_folderend_background(New(bkg_));
    colors->set_allocated_folderopenmid_background(New(bkg_));
    colors->set_allocated_foldermidtail_background(New(bkg_));
    colors->set_allocated_foldertail_background(New(bkg_));
    colors->set_allocated_foldersub_background(New(bkg_));
    colors->set_allocated_folder_background(New(bkg_));
    colors->set_allocated_folderopen_background(New(bkg_));

    colors->set_allocated_props_key(New(Style(New(keyword_))));
    colors->set_allocated_props_section(New(Style(NULL, NULL, true)));

    colors->set_allocated_indicator_error(New(Indicator(error_)));
    colors->set_allocated_indicator_warning(New(Indicator(warning_)));
    colors->set_allocated_indicator_search_highlight(
        New(Indicator(search_hi_)));
    colors->set_allocated_indicator_select_highlight(
        New(Indicator(select_hi_)));

    colors->set_allocated_annotation_error_style(
        New(Style(New(error_front_), New(error_))));
    colors->set_allocated_annotation_warning_style(
        New(Style(New(warning_front_), New(warning_))));
  }

 private:
  ride::Color selection_foreground_;
  ride::Color selection_background_;
  ride::Color front_;
  ride::Color bkg_;
  ride::Color fold_hi_;
  ride::Color fold_lo_;
  ride::Color selected_line_;
  ride::Color comment_;
  ride::Color keyword_;
  ride::Color error_;
  ride::Color error_front_;
  ride::Color warning_;
  ride::Color warning_front_;
  ride::Color search_hi_;
  ride::Color select_hi_;
};

//////////////////////////////////////////////////////////////////////////

void SetupDefaultTheme(ride::FontsAndColors* colors) {
  BasicThemeBuilder()
      .set_selection_foreground(Color(255))
      .set_selection_background(Color(0))
      .set_front(Color(0))
      .set_bkg(Color(224))
      .set_fold_hi(Color(192))
      .set_fold_lo(Color(224))
      .set_selected_line(Color(255, 255, 0))  // yellow
      .set_comment(Color(128, 64, 0))
      .set_keyword(Color(0, 0, 255))
      .set_error(Color(255, 60, 60))
      .set_error_front(Color(0))
      .set_warning(Color(0, 255, 0))
      .set_warning_front(Color(0))
      .set_search_hi(Color(200))
      .set_select_hi(Color(180))
      .Setup(colors);
}

//////////////////////////////////////////////////////////////////////////

// solarized colors from http://ethanschoonover.com/solarized
const ride::Color solarized_base03 = Color(0, 43, 54);
const ride::Color solarized_base02 = Color(7, 54, 66);
const ride::Color solarized_base01 = Color(88, 110, 117);
const ride::Color solarized_base00 = Color(101, 123, 131);
const ride::Color solarized_base0 = Color(131, 148, 150);
const ride::Color solarized_base1 = Color(147, 161, 161);
const ride::Color solarized_base2 = Color(238, 232, 213);
const ride::Color solarized_base3 = Color(253, 246, 227);
const ride::Color solarized_yellow = Color(181, 137, 0);
const ride::Color solarized_orange = Color(203, 75, 22);
const ride::Color solarized_red = Color(220, 50, 47);
const ride::Color solarized_magenta = Color(211, 54, 130);
const ride::Color solarized_violet = Color(108, 113, 196);
const ride::Color solarized_blue = Color(38, 139, 210);
const ride::Color solarized_cyan = Color(42, 161, 152);
const ride::Color solarized_green = Color(133, 153, 0);

void SetupSolarizedDarkTheme(ride::FontsAndColors* colors) {
  BasicThemeBuilder()
      .set_selection_foreground(solarized_base1)
      .set_selection_background(solarized_base00)
      .set_front(solarized_base0)
      .set_bkg(solarized_base03)
      .set_fold_hi(solarized_base02)
      .set_fold_lo(solarized_base02)
      .set_selected_line(solarized_base02)
      .set_comment(solarized_base01)
      .set_keyword(solarized_base1)
      .set_error(solarized_red)
      .set_error_front(solarized_base03)
      .set_warning(solarized_base00)
      .set_warning_front(solarized_base03)
      .set_search_hi(solarized_base01)
      .set_select_hi(solarized_base02)
      .Setup(colors);
}

//////////////////////////////////////////////////////////////////////////

void AddBuiltInThemes(::ride::Settings* settings) {
  ThemeList* themes = settings->mutable_themes();

  ride::Theme* default_theme = GetOrCreateTheme(themes, "Ride (default)");
  SetupDefaultTheme(default_theme->mutable_data());

  ride::Theme* solarized_dark_theme =
      GetOrCreateTheme(themes, "Solarized (dark)");
  SetupSolarizedDarkTheme(solarized_dark_theme->mutable_data());

  if (false == settings->has_fonts_and_colors()) {
    // if the current settings is missing the fonts and colors
    // apply the default theme
    settings->set_allocated_fonts_and_colors(
        new ride::FontsAndColors(default_theme->data()));
  }
}
<commit_msg>edge color fix for solarized #64<commit_after>// Copyright (2015) Gustav

#include "ride/builtinthemes.h"

#include <string>

typedef google::protobuf::RepeatedPtrField<ride::Theme> ThemeList;

ride::Theme* GetOrCreateTheme(ThemeList* themes, const std::string& name) {
  for (ride::Theme& t : *themes) {
    if (t.name() == name) return &t;
  }

  ride::Theme* temp = themes->Add();
  temp->set_name(name);
  temp->set_can_remove(false);
  return temp;
}

ride::Color Color(google::protobuf::int32 r, google::protobuf::int32 g,
                  google::protobuf::int32 b) {
  ride::Color c;

  c.set_r(r);
  c.set_g(g);
  c.set_b(b);

  return c;
}

ride::Color Color(google::protobuf::int32 c) { return Color(c, c, c); }

ride::Style Style(ride::Color* front, ride::Color* back = NULL,
                  bool bold = false) {
  ride::Style style;

  if (front) {
    style.set_use_foreground(true);
    style.set_allocated_foreground(front);
  }

  if (back) {
    style.set_use_background(true);
    style.set_allocated_background(back);
  }

  if (bold) {
    style.set_use_bold(true);
    style.set_bold(true);
  }

  return style;
}

template <typename T>
T* New(const T& t) {
  return new T(t);
}

ride::Indicator Indicator(const ride::Color& c) {
  ride::Indicator ind;
  ind.set_allocated_foreground(New(c));
  return ind;
}

//////////////////////////////////////////////////////////////////////////

class BasicThemeBuilder {
 public:
  BasicThemeBuilder& set_selection_foreground(const ride::Color& c) {
    selection_foreground_ = c;
    return *this;
  }
  BasicThemeBuilder& set_selection_background(const ride::Color& c) {
    selection_background_ = c;
    return *this;
  }
  BasicThemeBuilder& set_front(const ride::Color& c) {
    front_ = c;
    return *this;
  }
  BasicThemeBuilder& set_bkg(const ride::Color& c) {
    bkg_ = c;
    return *this;
  }
  BasicThemeBuilder& set_fold_hi(const ride::Color& c) {
    fold_hi_ = c;
    return *this;
  }
  BasicThemeBuilder& set_fold_lo(const ride::Color& c) {
    fold_lo_ = c;
    return *this;
  }
  BasicThemeBuilder& set_selected_line(const ride::Color& c) {
    selected_line_ = c;
    return *this;
  }
  BasicThemeBuilder& set_comment(const ride::Color& c) {
    comment_ = c;
    return *this;
  }
  BasicThemeBuilder& set_keyword(const ride::Color& c) {
    keyword_ = c;
    return *this;
  }
  BasicThemeBuilder& set_error(const ride::Color& c) {
    error_ = c;
    return *this;
  }
  BasicThemeBuilder& set_error_front(const ride::Color& c) {
    error_front_ = c;
    return *this;
  }
  BasicThemeBuilder& set_warning(const ride::Color& c) {
    warning_ = c;
    return *this;
  }
  BasicThemeBuilder& set_warning_front(const ride::Color& c) {
    warning_front_ = c;
    return *this;
  }
  BasicThemeBuilder& set_search_hi(const ride::Color& c) {
    search_hi_ = c;
    return *this;
  }
  BasicThemeBuilder& set_select_hi(const ride::Color& c) {
    select_hi_ = c;
    return *this;
  }
  BasicThemeBuilder& set_edge_color(const ride::Color& c) {
    edge_color_ = c;
    return *this;
  }

  const ride::Color& selection_foreground() { return selection_foreground_; }
  const ride::Color& selection_background() { return selection_background_; }
  const ride::Color& front() { return front_; }
  const ride::Color& bkg() { return bkg_; }
  const ride::Color& fold_hi() { return fold_hi_; }
  const ride::Color& fold_lo() { return fold_lo_; }
  const ride::Color& selected_line() { return selected_line_; }
  const ride::Color& comment() { return comment_; }
  const ride::Color& keyword() { return keyword_; }
  const ride::Color& error() { return error_; }
  const ride::Color& error_front() { return error_front_; }
  const ride::Color& warning() { return warning_; }
  const ride::Color& warning_front() { return warning_front_; }
  const ride::Color& search_hi() { return search_hi_; }
  const ride::Color& select_hi() { return select_hi_; }
  const ride::Color& edge_color() { return edge_color_; }

  void Setup(ride::FontsAndColors* colors) {
    colors->set_use_selection_background(true);
    colors->set_use_selection_foreground(true);
    colors->set_allocated_selection_foreground(New(selection_foreground_));
    colors->set_allocated_selection_background(New(selection_background_));

    colors->set_allocated_default_style(New(Style(New(front_), New(bkg_))));
    colors->set_allocated_line_number_style(New(Style(NULL, New(bkg_))));
    colors->set_allocated_fold_margin_hi(New(fold_hi_));
    colors->set_allocated_fold_margin_low(New(fold_lo_));

    colors->set_allocated_selected_line(New(selected_line_));  // yellow

    colors->set_allocated_style_comment(New(Style(New(comment_))));
    colors->set_allocated_style_commentline(New(Style(New(comment_))));
    colors->set_allocated_style_commentdoc(New(Style(New(comment_))));
    colors->set_allocated_style_commentlinedoc(New(Style(New(comment_))));
    colors->set_allocated_style_keyword(New(Style(New(keyword_), NULL, true)));

    colors->set_allocated_folderend_foreground(New(front_));
    colors->set_allocated_folderopenmid_foreground(New(front_));
    colors->set_allocated_foldermidtail_foreground(New(front_));
    colors->set_allocated_foldertail_foreground(New(front_));
    colors->set_allocated_foldersub_foreground(New(front_));
    colors->set_allocated_folder_foreground(New(front_));
    colors->set_allocated_folderopen_foreground(New(front_));

    colors->set_allocated_folderend_background(New(bkg_));
    colors->set_allocated_folderopenmid_background(New(bkg_));
    colors->set_allocated_foldermidtail_background(New(bkg_));
    colors->set_allocated_foldertail_background(New(bkg_));
    colors->set_allocated_foldersub_background(New(bkg_));
    colors->set_allocated_folder_background(New(bkg_));
    colors->set_allocated_folderopen_background(New(bkg_));

    colors->set_allocated_props_key(New(Style(New(keyword_))));
    colors->set_allocated_props_section(New(Style(NULL, NULL, true)));

    colors->set_allocated_indicator_error(New(Indicator(error_)));
    colors->set_allocated_indicator_warning(New(Indicator(warning_)));
    colors->set_allocated_indicator_search_highlight(
        New(Indicator(search_hi_)));
    colors->set_allocated_indicator_select_highlight(
        New(Indicator(select_hi_)));

    colors->set_allocated_annotation_error_style(
        New(Style(New(error_front_), New(error_))));
    colors->set_allocated_annotation_warning_style(
        New(Style(New(warning_front_), New(warning_))));

    colors->set_allocated_edgecolor(New(edge_color_));
  }

 private:
  ride::Color selection_foreground_;
  ride::Color selection_background_;
  ride::Color front_;
  ride::Color bkg_;
  ride::Color fold_hi_;
  ride::Color fold_lo_;
  ride::Color selected_line_;
  ride::Color comment_;
  ride::Color keyword_;
  ride::Color error_;
  ride::Color error_front_;
  ride::Color warning_;
  ride::Color warning_front_;
  ride::Color search_hi_;
  ride::Color select_hi_;
  ride::Color edge_color_;
};

//////////////////////////////////////////////////////////////////////////

void SetupDefaultTheme(ride::FontsAndColors* colors) {
  BasicThemeBuilder()
      .set_selection_foreground(Color(255))
      .set_selection_background(Color(0))
      .set_front(Color(0))
      .set_bkg(Color(224))
      .set_fold_hi(Color(192))
      .set_fold_lo(Color(224))
      .set_selected_line(Color(255, 255, 0))  // yellow
      .set_comment(Color(128, 64, 0))
      .set_keyword(Color(0, 0, 255))
      .set_error(Color(255, 60, 60))
      .set_error_front(Color(0))
      .set_warning(Color(0, 255, 0))
      .set_warning_front(Color(0))
      .set_search_hi(Color(200))
      .set_select_hi(Color(180))
      .set_edge_color(Color(0))
      .Setup(colors);
}

//////////////////////////////////////////////////////////////////////////

// solarized colors from http://ethanschoonover.com/solarized
const ride::Color solarized_base03 = Color(0, 43, 54);
const ride::Color solarized_base02 = Color(7, 54, 66);
const ride::Color solarized_base01 = Color(88, 110, 117);
const ride::Color solarized_base00 = Color(101, 123, 131);
const ride::Color solarized_base0 = Color(131, 148, 150);
const ride::Color solarized_base1 = Color(147, 161, 161);
const ride::Color solarized_base2 = Color(238, 232, 213);
const ride::Color solarized_base3 = Color(253, 246, 227);
const ride::Color solarized_yellow = Color(181, 137, 0);
const ride::Color solarized_orange = Color(203, 75, 22);
const ride::Color solarized_red = Color(220, 50, 47);
const ride::Color solarized_magenta = Color(211, 54, 130);
const ride::Color solarized_violet = Color(108, 113, 196);
const ride::Color solarized_blue = Color(38, 139, 210);
const ride::Color solarized_cyan = Color(42, 161, 152);
const ride::Color solarized_green = Color(133, 153, 0);

void SetupSolarizedDarkTheme(ride::FontsAndColors* colors) {
  BasicThemeBuilder()
      .set_selection_foreground(solarized_base1)
      .set_selection_background(solarized_base00)
      .set_front(solarized_base0)
      .set_bkg(solarized_base03)
      .set_fold_hi(solarized_base02)
      .set_fold_lo(solarized_base02)
      .set_selected_line(solarized_base02)
      .set_comment(solarized_base01)
      .set_keyword(solarized_base1)
      .set_error(solarized_red)
      .set_error_front(solarized_base03)
      .set_warning(solarized_base00)
      .set_warning_front(solarized_base03)
      .set_search_hi(solarized_base01)
      .set_select_hi(solarized_base02)
      .set_edge_color(solarized_base01)
      .Setup(colors);
}

//////////////////////////////////////////////////////////////////////////

void AddBuiltInThemes(::ride::Settings* settings) {
  ThemeList* themes = settings->mutable_themes();

  ride::Theme* default_theme = GetOrCreateTheme(themes, "Ride (default)");
  SetupDefaultTheme(default_theme->mutable_data());

  ride::Theme* solarized_dark_theme =
      GetOrCreateTheme(themes, "Solarized (dark)");
  SetupSolarizedDarkTheme(solarized_dark_theme->mutable_data());

  if (false == settings->has_fonts_and_colors()) {
    // if the current settings is missing the fonts and colors
    // apply the default theme
    settings->set_allocated_fonts_and_colors(
        new ride::FontsAndColors(default_theme->data()));
  }
}
<|endoftext|>


<commit_before>#include "catch.hpp"

// mapnik
#include <mapnik/vertex_cache.hpp>

// stl
#include <iostream>
#include <vector>
#include <tuple>

struct fake_path
{
    using coord_type = std::tuple<double, double, unsigned>;
    using cont_type = std::vector<coord_type>;
    cont_type vertices_;
    cont_type::iterator itr_;

    fake_path(std::initializer_list<double> l)
        : fake_path(l.begin(), l.size()) {
    }

    fake_path(std::vector<double> const &v)
        : fake_path(v.begin(), v.size()) {
    }

    template <typename Itr>
    fake_path(Itr itr, size_t sz) {
        size_t num_coords = sz >> 1;
        vertices_.reserve(num_coords);

        for (size_t i = 0; i < num_coords; ++i) {
            double x = *itr++;
            double y = *itr++;
            unsigned cmd = (i == 0) ? agg::path_cmd_move_to : agg::path_cmd_line_to;
            vertices_.push_back(std::make_tuple(x, y, cmd));
        }
        itr_ = vertices_.begin();
    }

    unsigned vertex(double *x, double *y) {
        if (itr_ == vertices_.end()) {
            return agg::path_cmd_stop;
        }
        *x = std::get<0>(*itr_);
        *y = std::get<1>(*itr_);
        unsigned cmd = std::get<2>(*itr_);
        ++itr_;
        return cmd;
    }

    void rewind(unsigned) {
        itr_ = vertices_.begin();
    }
};

double dist(mapnik::pixel_position const &a,
            mapnik::pixel_position const &b)
{
    mapnik::pixel_position d = a - b;
    return std::sqrt(d.x*d.x + d.y*d.y);
}

void test_simple_segment(double const &offset)
{
    const double dx = 0.01;
    fake_path path = {0, 0, 1, 0}, off_path = {0, offset, 1, offset};
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double pos = vc.linear_position();
        double off_pos = off_vc.position_closest_to(vc.current_position());
        REQUIRE(std::abs(pos - off_pos) < 1.0e-6);
    }
}

void test_straight_line(double const &offset) {
    const double dx = 0.01;
    fake_path path = {0, 0, 0.1, 0, 0.9, 0, 1, 0},
        off_path = {0, offset, 0.4, offset, 0.6, offset, 1, offset};
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double pos = vc.linear_position();
        double off_pos = off_vc.position_closest_to(vc.current_position());
        REQUIRE(std::abs(pos - off_pos) < 1.0e-6);
    }
}

void test_offset_curve(double const &offset) {
    const double dx = 0.01;
    const double r = (1.0 + offset);

    std::vector<double> pos, off_pos;
    const size_t max_i = 1000;
    for (size_t i = 0; i <= max_i; ++i) {
        double x = M_PI * double(i) / max_i;
        pos.push_back(-std::cos(x)); pos.push_back(std::sin(x));
        off_pos.push_back(-r * std::cos(x)); off_pos.push_back(r * std::sin(x));
    }

    fake_path path(pos), off_path(off_pos);
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double mpos = vc.linear_position();
        double moff_pos = off_vc.position_closest_to(vc.current_position());
        {
            mapnik::vertex_cache::scoped_state s(off_vc);
            off_vc.move(moff_pos);
            auto eps = (1.001 * offset);
            auto actual = dist(vc.current_position(), off_vc.current_position());
            REQUIRE(actual < eps);
        }
        REQUIRE(std::abs((mpos / vc.length()) - (moff_pos / off_vc.length())) < 1.0e-3);
    }
}

void test_s_shaped_curve(double const &offset) {
    const double dx = 0.01;
    const double r = (1.0 + offset);
    const double r2 = (1.0 - offset);

    std::vector<double> pos, off_pos;
    const size_t max_i = 1000;
    for (size_t i = 0; i <= max_i; ++i) {
        double x = M_PI * double(i) / max_i;
        pos.push_back(-std::cos(x) - 1); pos.push_back(std::sin(x));
        off_pos.push_back(-r * std::cos(x) - 1); off_pos.push_back(r * std::sin(x));
    }
    for (size_t i = 0; i <= max_i; ++i) {
        double x = M_PI * double(i) / max_i;
        pos.push_back(-std::cos(x) + 1); pos.push_back(-std::sin(x));
        off_pos.push_back(-r2 * std::cos(x) + 1); off_pos.push_back(-r2 * std::sin(x));
    }

    fake_path path(pos), off_path(off_pos);
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double moff_pos = off_vc.position_closest_to(vc.current_position());
        {
            mapnik::vertex_cache::scoped_state s(off_vc);
            off_vc.move(moff_pos);
            REQUIRE(dist(vc.current_position(), off_vc.current_position()) < (1.002 * offset));
        }
    }
}

TEST_CASE("offsets") {

SECTION("line") {
    try {

        std::vector<double> offsets = { 0.01, 0.02, 0.1, 0.2 };
        for (double offset : offsets) {
            // test simple straight line segment - should be easy to
            // find the correspondance here.
            test_simple_segment(offset);

            // test straight line consisting of more than one segment.
            test_straight_line(offset);

            // test an offset outer curve
            test_offset_curve(offset);

            // test an offset along an S-shaped curve, which is harder
            // because the positions along the offset are no longer
            // linearly related to the positions along the original
            // curve.
            test_s_shaped_curve(offset);
        }
    }
    catch (std::exception const& ex)
    {
        std::cerr << ex.what() << "\n";
        REQUIRE(false);
    }
}
}
<commit_msg>Windows tests: fix missing "M_PI"<commit_after>#include "catch.hpp"

// mapnik
#include <mapnik/vertex_cache.hpp>
#include <mapnik/global.hpp>

// stl
#include <iostream>
#include <vector>
#include <tuple>

struct fake_path
{
    using coord_type = std::tuple<double, double, unsigned>;
    using cont_type = std::vector<coord_type>;
    cont_type vertices_;
    cont_type::iterator itr_;

    fake_path(std::initializer_list<double> l)
        : fake_path(l.begin(), l.size()) {
    }

    fake_path(std::vector<double> const &v)
        : fake_path(v.begin(), v.size()) {
    }

    template <typename Itr>
    fake_path(Itr itr, size_t sz) {
        size_t num_coords = sz >> 1;
        vertices_.reserve(num_coords);

        for (size_t i = 0; i < num_coords; ++i) {
            double x = *itr++;
            double y = *itr++;
            unsigned cmd = (i == 0) ? agg::path_cmd_move_to : agg::path_cmd_line_to;
            vertices_.push_back(std::make_tuple(x, y, cmd));
        }
        itr_ = vertices_.begin();
    }

    unsigned vertex(double *x, double *y) {
        if (itr_ == vertices_.end()) {
            return agg::path_cmd_stop;
        }
        *x = std::get<0>(*itr_);
        *y = std::get<1>(*itr_);
        unsigned cmd = std::get<2>(*itr_);
        ++itr_;
        return cmd;
    }

    void rewind(unsigned) {
        itr_ = vertices_.begin();
    }
};

double dist(mapnik::pixel_position const &a,
            mapnik::pixel_position const &b)
{
    mapnik::pixel_position d = a - b;
    return std::sqrt(d.x*d.x + d.y*d.y);
}

void test_simple_segment(double const &offset)
{
    const double dx = 0.01;
    fake_path path = {0, 0, 1, 0}, off_path = {0, offset, 1, offset};
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double pos = vc.linear_position();
        double off_pos = off_vc.position_closest_to(vc.current_position());
        REQUIRE(std::abs(pos - off_pos) < 1.0e-6);
    }
}

void test_straight_line(double const &offset) {
    const double dx = 0.01;
    fake_path path = {0, 0, 0.1, 0, 0.9, 0, 1, 0},
        off_path = {0, offset, 0.4, offset, 0.6, offset, 1, offset};
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double pos = vc.linear_position();
        double off_pos = off_vc.position_closest_to(vc.current_position());
        REQUIRE(std::abs(pos - off_pos) < 1.0e-6);
    }
}

void test_offset_curve(double const &offset) {
    const double dx = 0.01;
    const double r = (1.0 + offset);

    std::vector<double> pos, off_pos;
    const size_t max_i = 1000;
    for (size_t i = 0; i <= max_i; ++i) {
        double x = M_PI * double(i) / max_i;
        pos.push_back(-std::cos(x)); pos.push_back(std::sin(x));
        off_pos.push_back(-r * std::cos(x)); off_pos.push_back(r * std::sin(x));
    }

    fake_path path(pos), off_path(off_pos);
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double mpos = vc.linear_position();
        double moff_pos = off_vc.position_closest_to(vc.current_position());
        {
            mapnik::vertex_cache::scoped_state s(off_vc);
            off_vc.move(moff_pos);
            auto eps = (1.001 * offset);
            auto actual = dist(vc.current_position(), off_vc.current_position());
            REQUIRE(actual < eps);
        }
        REQUIRE(std::abs((mpos / vc.length()) - (moff_pos / off_vc.length())) < 1.0e-3);
    }
}

void test_s_shaped_curve(double const &offset) {
    const double dx = 0.01;
    const double r = (1.0 + offset);
    const double r2 = (1.0 - offset);

    std::vector<double> pos, off_pos;
    const size_t max_i = 1000;
    for (size_t i = 0; i <= max_i; ++i) {
        double x = M_PI * double(i) / max_i;
        pos.push_back(-std::cos(x) - 1); pos.push_back(std::sin(x));
        off_pos.push_back(-r * std::cos(x) - 1); off_pos.push_back(r * std::sin(x));
    }
    for (size_t i = 0; i <= max_i; ++i) {
        double x = M_PI * double(i) / max_i;
        pos.push_back(-std::cos(x) + 1); pos.push_back(-std::sin(x));
        off_pos.push_back(-r2 * std::cos(x) + 1); off_pos.push_back(-r2 * std::sin(x));
    }

    fake_path path(pos), off_path(off_pos);
    mapnik::vertex_cache vc(path), off_vc(off_path);

    vc.reset(); vc.next_subpath();
    off_vc.reset(); off_vc.next_subpath();

    while (vc.move(dx)) {
        double moff_pos = off_vc.position_closest_to(vc.current_position());
        {
            mapnik::vertex_cache::scoped_state s(off_vc);
            off_vc.move(moff_pos);
            REQUIRE(dist(vc.current_position(), off_vc.current_position()) < (1.002 * offset));
        }
    }
}

TEST_CASE("offsets") {

SECTION("line") {
    try {

        std::vector<double> offsets = { 0.01, 0.02, 0.1, 0.2 };
        for (double offset : offsets) {
            // test simple straight line segment - should be easy to
            // find the correspondance here.
            test_simple_segment(offset);

            // test straight line consisting of more than one segment.
            test_straight_line(offset);

            // test an offset outer curve
            test_offset_curve(offset);

            // test an offset along an S-shaped curve, which is harder
            // because the positions along the offset are no longer
            // linearly related to the positions along the original
            // curve.
            test_s_shaped_curve(offset);
        }
    }
    catch (std::exception const& ex)
    {
        std::cerr << ex.what() << "\n";
        REQUIRE(false);
    }
}
}
<|endoftext|>