<commit_before>/*
**
** Author(s):
**  - Pierre ROULLON <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2012, 2013 Aldebaran Robotics
** See COPYING for the license
*/

#include <qi/anyobject.hpp>
#include <qi/jsoncodec.hpp>

#include <jnitools.hpp>
#include <object.hpp>
#include <callbridge.hpp>
#include <jobjectconverter.hpp>

qiLogCategory("qimessaging.jni");

extern MethodInfoHandler gInfoHandler;

static void adaptFuture(qi::Future<void> f, qi::Promise<qi::AnyValue> p)
{
  if (f.hasError())
    p.setError(f.error());
  else
    p.setValue(qi::AnyValue(qi::typeOf<void>()));
}

jlong   Java_com_aldebaran_qi_AnyObject_property(JNIEnv* env, jobject jobj, jlong pObj, jstring name)
{
  qi::AnyObject&     obj = *(reinterpret_cast<qi::AnyObject*>(pObj));
  std::string        propName = qi::jni::toString(name);

  qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();

  qi::jni::JNIAttach attach(env);

  try
  {
    *ret = obj.property<qi::AnyValue>(propName);
  } catch (qi::FutureUserException& e)
  {
    delete ret;
    throwJavaError(env, e.what());
    return 0;
  }

  return (jlong) ret;
}

jlong  Java_com_aldebaran_qi_AnyObject_setProperty(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name, jobject property)
{
  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObj));
  std::string       propName = qi::jni::toString(name);

  qi::jni::JNIAttach attach(env);

  qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();

  qi::Future<void> f = obj.setProperty(propName, qi::AnyValue::from<jobject>(property)).async();
  qi::Promise<qi::AnyValue> promise;
  *ret = promise.future();
  f.connect(adaptFuture, _1, promise);
  return (jlong) ret;
}

jlong     Java_com_aldebaran_qi_AnyObject_asyncCall(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject, jstring jmethod, jobjectArray args)
{
  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));
  std::string       method;
  qi::Future<qi::AnyValue>* fut = 0;

  qi::jni::JNIAttach attach(env);

  if (!obj)
  {
    qiLogError() << "Given object not valid.";
    throwJavaError(env, "Given object is not valid.");
    return 0;
  }

  // Get method name and parameters C style.
  method = qi::jni::toString(jmethod);
  try {
    fut = call_from_java(env, obj, method, args);
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
    return 0;
  }

  return (jlong) fut;
}

jstring   Java_com_aldebaran_qi_AnyObject_printMetaObject(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject)
{
  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));
  std::stringstream ss;

  qi::details::printMetaObject(ss, obj.metaObject());
  return qi::jni::toJstring(ss.str());
}

void      Java_com_aldebaran_qi_AnyObject_destroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)
{
  qi::AnyObject*    obj = reinterpret_cast<qi::AnyObject*>(pObject);

  delete obj;
}

jlong     Java_com_aldebaran_qi_AnyObject_disconnect(JNIEnv *env, jobject jobj, jlong pObject, jlong subscriberId)
{
  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));
  try {
    obj.disconnect(subscriberId);
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
  }
  return 0;
}

jlong     Java_com_aldebaran_qi_AnyObject_connect(JNIEnv *env, jobject jobj, jlong pObject, jstring method, jobject instance, jstring service, jstring eventName)
{
  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));
  std::string                signature = qi::jni::toString(method);
  std::string                event = qi::jni::toString(eventName);
  qi_method_info*            data;
  std::vector<std::string>  sigInfo;

  // Keep a pointer on JavaVM singleton if not already set.
  JVM(env);

  // Create a new global reference on object instance.
  // jobject structure are local reference and are destroyed when returning to JVM
  instance = env->NewGlobalRef(instance);

  // Remove return value
  sigInfo = qi::signatureSplit(signature);
  signature = sigInfo[1];
  signature.append("::");
  signature.append(sigInfo[2]);

  // Create a struct holding a jobject instance, jmethodId id and other needed thing for callback
  // Pass it to void * data to register_method
  data = new qi_method_info(instance, signature, jobj);
  gInfoHandler.push(data);

  try {
    qi::SignalLink link =obj.connect(event,
                        qi::SignalSubscriber(
                          qi::AnyFunction::fromDynamicFunction(
                            boost::bind(&event_callback_to_java, (void*) data, _1))).setCallType(qi::MetaCallType_Direct));
    return link;
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
    return 0;
  }
}

void      Java_com_aldebaran_qi_AnyObject_post(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jstring eventName, jobjectArray jargs)
{
  qi::AnyObject obj = *(reinterpret_cast<qi::AnyObject *>(pObject));
  std::string   event = qi::jni::toString(eventName);
  qi::GenericFunctionParameters params;
  std::string signature;
  jsize size;
  jsize i = 0;

  qi::jni::JNIAttach attach(env);

  size = env->GetArrayLength(jargs);
  i = 0;
  while (i < size)
  {
    jobject current = env->NewGlobalRef(env->GetObjectArrayElement(jargs, i));
    qi::AnyReference val = qi::AnyReference(AnyValue_from_JObject(current).first);
    params.push_back(val);
    i++;
  }

  // Signature construction
  signature = event + "::(";
  for (unsigned i=0; i< params.size(); ++i)
    signature += params[i].signature(true).toString();
  signature += ")";

  try {
    obj.metaPost(event, params);
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
  }

  // Destroy arguments
  i = 0;
  for(qi::GenericFunctionParameters::iterator it = params.begin(); it != params.end(); ++it)
    (*it).destroy();
  return;
}

jobject Java_com_aldebaran_qi_AnyObject_decodeJSON(JNIEnv* env, jclass, jstring what)
{
  std::string str = qi::jni::toString(what);
  qi::AnyValue val = qi::decodeJSON(str);
  return JObject_from_AnyValue(val.asReference());
}

jstring Java_com_aldebaran_qi_AnyObject_encodeJSON(JNIEnv* env, jclass, jobject what)
{
  std::string res = qi::encodeJSON(what);
  return qi::jni::toJstring(res);
}
<commit_msg>AnyObject.post: fix memory leak on arguments #21714<commit_after>/*
**
** Author(s):
**  - Pierre ROULLON <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2012, 2013 Aldebaran Robotics
** See COPYING for the license
*/

#include <qi/anyobject.hpp>
#include <qi/jsoncodec.hpp>

#include <jnitools.hpp>
#include <object.hpp>
#include <callbridge.hpp>
#include <jobjectconverter.hpp>

qiLogCategory("qimessaging.jni");

extern MethodInfoHandler gInfoHandler;

static void adaptFuture(qi::Future<void> f, qi::Promise<qi::AnyValue> p)
{
  if (f.hasError())
    p.setError(f.error());
  else
    p.setValue(qi::AnyValue(qi::typeOf<void>()));
}

jlong   Java_com_aldebaran_qi_AnyObject_property(JNIEnv* env, jobject jobj, jlong pObj, jstring name)
{
  qi::AnyObject&     obj = *(reinterpret_cast<qi::AnyObject*>(pObj));
  std::string        propName = qi::jni::toString(name);

  qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();

  qi::jni::JNIAttach attach(env);

  try
  {
    *ret = obj.property<qi::AnyValue>(propName);
  } catch (qi::FutureUserException& e)
  {
    delete ret;
    throwJavaError(env, e.what());
    return 0;
  }

  return (jlong) ret;
}

jlong  Java_com_aldebaran_qi_AnyObject_setProperty(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name, jobject property)
{
  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObj));
  std::string       propName = qi::jni::toString(name);

  qi::jni::JNIAttach attach(env);

  qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();

  qi::Future<void> f = obj.setProperty(propName, qi::AnyValue::from<jobject>(property)).async();
  qi::Promise<qi::AnyValue> promise;
  *ret = promise.future();
  f.connect(adaptFuture, _1, promise);
  return (jlong) ret;
}

jlong     Java_com_aldebaran_qi_AnyObject_asyncCall(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject, jstring jmethod, jobjectArray args)
{
  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));
  std::string       method;
  qi::Future<qi::AnyValue>* fut = 0;

  qi::jni::JNIAttach attach(env);

  if (!obj)
  {
    qiLogError() << "Given object not valid.";
    throwJavaError(env, "Given object is not valid.");
    return 0;
  }

  // Get method name and parameters C style.
  method = qi::jni::toString(jmethod);
  try {
    fut = call_from_java(env, obj, method, args);
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
    return 0;
  }

  return (jlong) fut;
}

jstring   Java_com_aldebaran_qi_AnyObject_printMetaObject(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject)
{
  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));
  std::stringstream ss;

  qi::details::printMetaObject(ss, obj.metaObject());
  return qi::jni::toJstring(ss.str());
}

void      Java_com_aldebaran_qi_AnyObject_destroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)
{
  qi::AnyObject*    obj = reinterpret_cast<qi::AnyObject*>(pObject);

  delete obj;
}

jlong     Java_com_aldebaran_qi_AnyObject_disconnect(JNIEnv *env, jobject jobj, jlong pObject, jlong subscriberId)
{
  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));
  try {
    obj.disconnect(subscriberId);
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
  }
  return 0;
}

jlong     Java_com_aldebaran_qi_AnyObject_connect(JNIEnv *env, jobject jobj, jlong pObject, jstring method, jobject instance, jstring service, jstring eventName)
{
  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));
  std::string                signature = qi::jni::toString(method);
  std::string                event = qi::jni::toString(eventName);
  qi_method_info*            data;
  std::vector<std::string>  sigInfo;

  // Keep a pointer on JavaVM singleton if not already set.
  JVM(env);

  // Create a new global reference on object instance.
  // jobject structure are local reference and are destroyed when returning to JVM
  instance = env->NewGlobalRef(instance);

  // Remove return value
  sigInfo = qi::signatureSplit(signature);
  signature = sigInfo[1];
  signature.append("::");
  signature.append(sigInfo[2]);

  // Create a struct holding a jobject instance, jmethodId id and other needed thing for callback
  // Pass it to void * data to register_method
  data = new qi_method_info(instance, signature, jobj);
  gInfoHandler.push(data);

  try {
    qi::SignalLink link =obj.connect(event,
                        qi::SignalSubscriber(
                          qi::AnyFunction::fromDynamicFunction(
                            boost::bind(&event_callback_to_java, (void*) data, _1))).setCallType(qi::MetaCallType_Direct));
    return link;
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
    return 0;
  }
}

void      Java_com_aldebaran_qi_AnyObject_post(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jstring eventName, jobjectArray jargs)
{
  qi::AnyObject obj = *(reinterpret_cast<qi::AnyObject *>(pObject));
  std::string   event = qi::jni::toString(eventName);
  qi::GenericFunctionParameters params;
  std::string signature;
  jsize size;
  jsize i = 0;

  qi::jni::JNIAttach attach(env);

  size = env->GetArrayLength(jargs);
  i = 0;
  while (i < size)
  {
    jobject current = env->GetObjectArrayElement(jargs, i);
    qi::AnyReference val = qi::AnyReference(AnyValue_from_JObject(current).first);
    params.push_back(val);
    i++;
  }

  // Signature construction
  signature = event + "::(";
  for (unsigned i=0; i< params.size(); ++i)
    signature += params[i].signature(true).toString();
  signature += ")";

  try {
    obj.metaPost(event, params);
  } catch (std::exception& e)
  {
    throwJavaError(env, e.what());
  }

  // Destroy arguments
  i = 0;
  for(qi::GenericFunctionParameters::iterator it = params.begin(); it != params.end(); ++it)
    (*it).destroy();
  return;
}

jobject Java_com_aldebaran_qi_AnyObject_decodeJSON(JNIEnv* env, jclass, jstring what)
{
  std::string str = qi::jni::toString(what);
  qi::AnyValue val = qi::decodeJSON(str);
  return JObject_from_AnyValue(val.asReference());
}

jstring Java_com_aldebaran_qi_AnyObject_encodeJSON(JNIEnv* env, jclass, jobject what)
{
  std::string res = qi::encodeJSON(what);
  return qi::jni::toJstring(res);
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "CachedCSSStyleSheet.h"
#include "CachedResource.h"
#include "CachedScript.h"
#include "CachedXSLStyleSheet.h"
#include "DocLoader.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "FrameLoader.h"
#include "PlatformString.h"
#include "ResourceError.h"
#include "ResourceRequest.h"
#include "ResourceResponse.h"
#include "ScriptString.h"
#include "TextEncoding.h"
#include <wtf/CurrentTime.h>
#undef LOG

#include "base/basictypes.h"
#include "base/values.h"
#include "googleurl/src/gurl.h"
#include "webkit/glue/devtools/net_agent_impl.h"
#include "webkit/glue/glue_util.h"

using namespace WebCore;

NetAgentImpl::NetAgentImpl(NetAgentDelegate* delegate)
    : delegate_(delegate),
      document_(NULL),
      main_loader_(NULL),
      last_cached_identifier_(-2),
      attached_(false)  {
}

NetAgentImpl::~NetAgentImpl() {
  SetDocument(NULL);
  DidCommitMainResourceLoad();
  deleteAllValues(pending_resources_);
  pending_resources_.clear();
}

void NetAgentImpl::SetDocument(Document* doc) {
  document_ = doc;
}

void NetAgentImpl::Attach() {
  for (FinishedResources::iterator it = finished_resources_.begin();
       it != finished_resources_.end(); ++it) {
    DictionaryValue value;
    Serialize(*it->second, &value);
    delegate_->DidFinishLoading(it->first, value);
  }
  attached_ = true;
}

void NetAgentImpl::Detach() {
  attached_ = false;
}

void NetAgentImpl::DidCommitMainResourceLoad() {
  for (FinishedResources::iterator it = finished_resources_.begin();
       it != finished_resources_.end(); ++it) {
    delete it->second;
  }
  finished_resources_.clear();
  main_loader_ = NULL;
}

void NetAgentImpl::AssignIdentifierToRequest(
    DocumentLoader* loader,
    int identifier,
    const ResourceRequest& request) {
}

void NetAgentImpl::WillSendRequest(
    DocumentLoader* loader,
    int identifier,
    const ResourceRequest& request) {
  if (pending_resources_.contains(identifier)) {
    // We are going through redirect, nuke old resource.
    delete pending_resources_.get(identifier);
  }

  Resource* resource = new Resource();
  pending_resources_.set(identifier, resource);
  KURL url = request.url();
  resource->start_time = WTF::currentTime();
  resource->url = request.url();
  resource->request_headers = request.httpHeaderFields();

  if (attached_) {
    DictionaryValue value;
    Serialize(*resource, &value);
    delegate_->WillSendRequest(identifier, value);
  }
}

void NetAgentImpl::DidReceiveResponse(
    DocumentLoader* loader,
    int identifier,
    const ResourceResponse &response) {
  if (!pending_resources_.contains(identifier)) {
    return;
  }

  KURL url = response.url();
  Resource* resource = pending_resources_.get(identifier);
  resource->response_received_time = WTF::currentTime();
  resource->expected_content_length =
      static_cast<int>(response.expectedContentLength());
  resource->http_status_code = response.httpStatusCode();
  resource->mime_type = response.mimeType();
  resource->suggested_filename = response.suggestedFilename();
  resource->response_headers = response.httpHeaderFields();

  if (attached_) {
    DictionaryValue value;
    Serialize(*resource, &value);
    delegate_->DidReceiveResponse(identifier, value);
  }
}

void NetAgentImpl::DidReceiveContentLength(
    DocumentLoader* loader,
    int identifier,
    int length) {
}

void NetAgentImpl::DidFinishLoading(
    DocumentLoader* loader,
    int identifier) {
  if (!pending_resources_.contains(identifier)) {
    return;
  }

  // This is the first command being dispatched after
  // DidCommitMainResourceLoad, we know that the first resource to be reported
  // as loaded is main resource.
  if (!main_loader_.get()) {
    main_loader_ = loader;
  }

  Resource* resource = pending_resources_.get(identifier);
  resource->end_time = WTF::currentTime();

  pending_resources_.remove(identifier);
  finished_resources_.append(std::make_pair(identifier, resource));

  // Start removing resources from the cache once there are too many of them.
  if (finished_resources_.size() > 200) {
    for (int i = 0; i < 50; ++i) {
      xml_http_sources_.remove(finished_resources_[i].first);
      delete finished_resources_[i].second;
    }
    finished_resources_.remove(0, 50);
  }

  if (attached_) {
    DictionaryValue value;
    Serialize(*resource, &value);
    delegate_->DidFinishLoading(identifier, value);
  }
}

void NetAgentImpl::DidFailLoading(
    DocumentLoader* loader,
    int identifier,
    const ResourceError& error) {
  if (!pending_resources_.contains(identifier)) {
    return;
  }
  Resource* resource = pending_resources_.get(identifier);
  resource->error_code = error.errorCode();
  resource->error_description = error.localizedDescription();
  DidFinishLoading(loader, identifier);
}

void NetAgentImpl::DidLoadResourceFromMemoryCache(
    DocumentLoader* loader,
    const ResourceRequest& request,
    const ResourceResponse& response,
    int length) {
  int identifier = last_cached_identifier_--;
}

void NetAgentImpl::DidLoadResourceByXMLHttpRequest(
    int identifier,
    const WebCore::ScriptString& source) {
  xml_http_sources_.set(identifier, source);
}

void NetAgentImpl::GetResourceContent(
    int call_id,
    int identifier,
    const String& url) {
  if (!document_) {
    return;
  }

  String source;

  WebCore::ScriptString script = xml_http_sources_.get(identifier);
  if (!script.isNull()) {
    source = String(script);
  } else if (main_loader_.get() && main_loader_->requestURL() == url) {
    RefPtr<SharedBuffer> buffer = main_loader_->mainResourceData();
    String text_encoding_name = document_->inputEncoding();
    if (buffer) {
      WebCore::TextEncoding encoding(text_encoding_name);
      if (!encoding.isValid())
        encoding = WindowsLatin1Encoding();
      source = encoding.decode(buffer->data(), buffer->size());
    }
  } else {
    CachedResource* cached_resource = document_->
        docLoader()->cachedResource(url);
    if (!cached_resource) {
      delegate_->GetResourceContentResult(call_id, "");
      return;
    }
    if (cached_resource->isPurgeable()) {
      // If the resource is purgeable then make it unpurgeable to get its data.
      // This might fail, in which case we return an empty string.
      if (!cached_resource->makePurgeable(false)) {
        delegate_->GetResourceContentResult(call_id, "");
        return;
      }
    }

    // Try to get the decoded source.  Only applies to some CachedResource
    // types.
    switch (cached_resource->type()) {
      case CachedResource::CSSStyleSheet: {
        CachedCSSStyleSheet *sheet =
            reinterpret_cast<CachedCSSStyleSheet*>(cached_resource);
        source = sheet->sheetText();
        break;
      }
      case CachedResource::Script: {
        CachedScript *script =
            reinterpret_cast<CachedScript*>(cached_resource);
        source = script->script();
        break;
      }
#if ENABLE(XSLT)
      case CachedResource::XSLStyleSheet: {
        CachedXSLStyleSheet *sheet =
            reinterpret_cast<CachedXSLStyleSheet*>(cached_resource);
        source = sheet->sheet();
        break;
      }
#endif
      default:
        break;
    }
  }
  delegate_->GetResourceContentResult(call_id,
      webkit_glue::StringToStdString(source));
}

// static
Value* NetAgentImpl::BuildValueForHeaders(const HTTPHeaderMap& headers) {
  OwnPtr<DictionaryValue> value(new DictionaryValue());
  HTTPHeaderMap::const_iterator end = headers.end();
  for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it) {
    value->SetString(webkit_glue::StringToStdWString(it->first),
        webkit_glue::StringToStdString(it->second));
  }
  return value.release();
}

// static
void NetAgentImpl::Serialize(const Resource& resource,
                             DictionaryValue* value) {
  value->SetReal(L"startTime", resource.start_time);
  value->SetReal(L"responseReceivedTime", resource.response_received_time);
  value->SetReal(L"endTime", resource.end_time);

  value->SetString(L"url",
                   webkit_glue::StringToStdString(resource.url.string()));
  value->SetString(L"domain",
                   webkit_glue::StringToStdString(resource.url.host()));
  value->SetString(L"path",
                   webkit_glue::StringToStdString(resource.url.path()));
  value->SetString(
      L"lastPathComponent",
      webkit_glue::StringToStdString(resource.url.lastPathComponent()));

  value->SetString(L"mimeType",
      webkit_glue::StringToStdWString(resource.mime_type));
  value->SetString(L"suggestedFilename",
      webkit_glue::StringToStdWString(resource.suggested_filename));

  value->SetInteger(L"expectedContentLength",
                    resource.expected_content_length);
  value->SetInteger(L"responseStatusCode", resource.http_status_code);

  value->Set(L"requestHeaders",
             BuildValueForHeaders(resource.request_headers));
  value->Set(L"responseHeaders",
             BuildValueForHeaders(resource.response_headers));

  if (resource.error_code) {
    value->SetInteger(L"errorCode", resource.error_code);
    value->SetString(L"localizedDescription",
        webkit_glue::StringToStdString(resource.error_description));
  }
}
<commit_msg>DevTools: do not cache xmlhttp when client is not attached; reduce agent cache size. Review URL: http://codereview.chromium.org/115508<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "CachedCSSStyleSheet.h"
#include "CachedResource.h"
#include "CachedScript.h"
#include "CachedXSLStyleSheet.h"
#include "DocLoader.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "FrameLoader.h"
#include "PlatformString.h"
#include "ResourceError.h"
#include "ResourceRequest.h"
#include "ResourceResponse.h"
#include "ScriptString.h"
#include "TextEncoding.h"
#include <wtf/CurrentTime.h>
#undef LOG

#include "base/basictypes.h"
#include "base/values.h"
#include "googleurl/src/gurl.h"
#include "webkit/glue/devtools/net_agent_impl.h"
#include "webkit/glue/glue_util.h"

using namespace WebCore;

NetAgentImpl::NetAgentImpl(NetAgentDelegate* delegate)
    : delegate_(delegate),
      document_(NULL),
      main_loader_(NULL),
      last_cached_identifier_(-2),
      attached_(false)  {
}

NetAgentImpl::~NetAgentImpl() {
  SetDocument(NULL);
  DidCommitMainResourceLoad();
  deleteAllValues(pending_resources_);
  pending_resources_.clear();
}

void NetAgentImpl::SetDocument(Document* doc) {
  document_ = doc;
}

void NetAgentImpl::Attach() {
  for (FinishedResources::iterator it = finished_resources_.begin();
       it != finished_resources_.end(); ++it) {
    DictionaryValue value;
    Serialize(*it->second, &value);
    delegate_->DidFinishLoading(it->first, value);
  }
  attached_ = true;
}

void NetAgentImpl::Detach() {
  attached_ = false;
  xml_http_sources_.clear();
  ExpireFinishedResourcesCache();
}

void NetAgentImpl::DidCommitMainResourceLoad() {
  for (FinishedResources::iterator it = finished_resources_.begin();
       it != finished_resources_.end(); ++it) {
    delete it->second;
  }
  finished_resources_.clear();
  main_loader_ = NULL;
}

void NetAgentImpl::AssignIdentifierToRequest(
    DocumentLoader* loader,
    int identifier,
    const ResourceRequest& request) {
}

void NetAgentImpl::WillSendRequest(
    DocumentLoader* loader,
    int identifier,
    const ResourceRequest& request) {
  if (pending_resources_.contains(identifier)) {
    // We are going through redirect, nuke old resource.
    delete pending_resources_.get(identifier);
  }

  Resource* resource = new Resource();
  pending_resources_.set(identifier, resource);
  KURL url = request.url();
  resource->start_time = WTF::currentTime();
  resource->url = request.url();
  resource->request_headers = request.httpHeaderFields();

  if (attached_) {
    DictionaryValue value;
    Serialize(*resource, &value);
    delegate_->WillSendRequest(identifier, value);
  }
}

void NetAgentImpl::DidReceiveResponse(
    DocumentLoader* loader,
    int identifier,
    const ResourceResponse &response) {
  if (!pending_resources_.contains(identifier)) {
    return;
  }

  KURL url = response.url();
  Resource* resource = pending_resources_.get(identifier);
  resource->response_received_time = WTF::currentTime();
  resource->expected_content_length =
      static_cast<int>(response.expectedContentLength());
  resource->http_status_code = response.httpStatusCode();
  resource->mime_type = response.mimeType();
  resource->suggested_filename = response.suggestedFilename();
  resource->response_headers = response.httpHeaderFields();

  if (attached_) {
    DictionaryValue value;
    Serialize(*resource, &value);
    delegate_->DidReceiveResponse(identifier, value);
  }
}

void NetAgentImpl::DidReceiveContentLength(
    DocumentLoader* loader,
    int identifier,
    int length) {
}

void NetAgentImpl::DidFinishLoading(
    DocumentLoader* loader,
    int identifier) {
  if (!pending_resources_.contains(identifier)) {
    return;
  }

  // This is the first command being dispatched after
  // DidCommitMainResourceLoad, we know that the first resource to be reported
  // as loaded is main resource.
  if (!main_loader_.get()) {
    main_loader_ = loader;
  }

  Resource* resource = pending_resources_.get(identifier);
  resource->end_time = WTF::currentTime();

  pending_resources_.remove(identifier);
  finished_resources_.append(std::make_pair(identifier, resource));

  if (attached_) {
    DictionaryValue value;
    Serialize(*resource, &value);
    delegate_->DidFinishLoading(identifier, value);
  } else {
    ExpireFinishedResourcesCache();
  }
}

void NetAgentImpl::DidFailLoading(
    DocumentLoader* loader,
    int identifier,
    const ResourceError& error) {
  if (!pending_resources_.contains(identifier)) {
    return;
  }
  Resource* resource = pending_resources_.get(identifier);
  resource->error_code = error.errorCode();
  resource->error_description = error.localizedDescription();
  DidFinishLoading(loader, identifier);
}

void NetAgentImpl::DidLoadResourceFromMemoryCache(
    DocumentLoader* loader,
    const ResourceRequest& request,
    const ResourceResponse& response,
    int length) {
  int identifier = last_cached_identifier_--;
}

void NetAgentImpl::DidLoadResourceByXMLHttpRequest(
    int identifier,
    const WebCore::ScriptString& source) {
  if (attached_) {
    // Only store XmlHttpRequests data when client is attached.
    xml_http_sources_.set(identifier, source);
  }
}

void NetAgentImpl::GetResourceContent(
    int call_id,
    int identifier,
    const String& url) {
  if (!document_) {
    return;
  }

  String source;

  WebCore::ScriptString script = xml_http_sources_.get(identifier);
  if (!script.isNull()) {
    source = String(script);
  } else if (main_loader_.get() && main_loader_->requestURL() == url) {
    RefPtr<SharedBuffer> buffer = main_loader_->mainResourceData();
    String text_encoding_name = document_->inputEncoding();
    if (buffer) {
      WebCore::TextEncoding encoding(text_encoding_name);
      if (!encoding.isValid())
        encoding = WindowsLatin1Encoding();
      source = encoding.decode(buffer->data(), buffer->size());
    }
  } else {
    CachedResource* cached_resource = document_->
        docLoader()->cachedResource(url);
    if (!cached_resource) {
      delegate_->GetResourceContentResult(call_id, "");
      return;
    }
    if (cached_resource->isPurgeable()) {
      // If the resource is purgeable then make it unpurgeable to get its data.
      // This might fail, in which case we return an empty string.
      if (!cached_resource->makePurgeable(false)) {
        delegate_->GetResourceContentResult(call_id, "");
        return;
      }
    }

    // Try to get the decoded source.  Only applies to some CachedResource
    // types.
    switch (cached_resource->type()) {
      case CachedResource::CSSStyleSheet: {
        CachedCSSStyleSheet *sheet =
            reinterpret_cast<CachedCSSStyleSheet*>(cached_resource);
        source = sheet->sheetText();
        break;
      }
      case CachedResource::Script: {
        CachedScript *script =
            reinterpret_cast<CachedScript*>(cached_resource);
        source = script->script();
        break;
      }
#if ENABLE(XSLT)
      case CachedResource::XSLStyleSheet: {
        CachedXSLStyleSheet *sheet =
            reinterpret_cast<CachedXSLStyleSheet*>(cached_resource);
        source = sheet->sheet();
        break;
      }
#endif
      default:
        break;
    }
  }
  delegate_->GetResourceContentResult(call_id,
      webkit_glue::StringToStdString(source));
}

// static
Value* NetAgentImpl::BuildValueForHeaders(const HTTPHeaderMap& headers) {
  OwnPtr<DictionaryValue> value(new DictionaryValue());
  HTTPHeaderMap::const_iterator end = headers.end();
  for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it) {
    value->SetString(webkit_glue::StringToStdWString(it->first),
        webkit_glue::StringToStdString(it->second));
  }
  return value.release();
}

// static
void NetAgentImpl::Serialize(const Resource& resource,
                             DictionaryValue* value) {
  value->SetReal(L"startTime", resource.start_time);
  value->SetReal(L"responseReceivedTime", resource.response_received_time);
  value->SetReal(L"endTime", resource.end_time);

  value->SetString(L"url",
                   webkit_glue::StringToStdString(resource.url.string()));
  value->SetString(L"domain",
                   webkit_glue::StringToStdString(resource.url.host()));
  value->SetString(L"path",
                   webkit_glue::StringToStdString(resource.url.path()));
  value->SetString(
      L"lastPathComponent",
      webkit_glue::StringToStdString(resource.url.lastPathComponent()));

  value->SetString(L"mimeType",
      webkit_glue::StringToStdWString(resource.mime_type));
  value->SetString(L"suggestedFilename",
      webkit_glue::StringToStdWString(resource.suggested_filename));

  value->SetInteger(L"expectedContentLength",
                    resource.expected_content_length);
  value->SetInteger(L"responseStatusCode", resource.http_status_code);

  value->Set(L"requestHeaders",
             BuildValueForHeaders(resource.request_headers));
  value->Set(L"responseHeaders",
             BuildValueForHeaders(resource.response_headers));

  if (resource.error_code) {
    value->SetInteger(L"errorCode", resource.error_code);
    value->SetString(L"localizedDescription",
        webkit_glue::StringToStdString(resource.error_description));
  }
}

void NetAgentImpl::ExpireFinishedResourcesCache() {
  if (finished_resources_.size() > 100) {
    for (int i = 0; i < 20; ++i) {
      delete finished_resources_[i].second;
    }
    finished_resources_.remove(0, 20);
  }
}
<|endoftext|>


<commit_before>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh is distributed in the hope that it will be useful,              *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

/** \file ModBaseT.hh
    Base class for all decimation modules.
 */

//=============================================================================
//
//  CLASS ModBaseT
//
//=============================================================================

#ifndef OPENMESH_DECIMATER_MODBASET_HH
#define OPENMESH_DECIMATER_MODBASET_HH

//== INCLUDES =================================================================

#include <OpenMesh/Core/Utils/Noncopyable.hh>
#include <OpenMesh/Tools/Decimater/CollapseInfoT.hh>
#include <string>

//== NAMESPACE ================================================================

namespace OpenMesh  {
namespace Decimater {

//== FORWARD DECLARATIONS =====================================================

template <typename Mesh> class BaseDecimaterT;

//== CLASS DEFINITION =========================================================

/** Handle for mesh decimation modules
    \internal
 */

template <typename Module>
class ModHandleT : private Utils::Noncopyable
{
public:

  typedef ModHandleT<Module> Self;
  typedef Module module_type;

public:

  /// Default constructor
  ModHandleT() : mod_(NULL) {}

  /// Destructor
  ~ModHandleT() { /* don't delete mod_, since handle is not owner! */ }

  /// Check handle status
  /// \return \c true, if handle is valid, else \c false.
  bool is_valid() const { return mod_ != NULL; }

private:

#if defined(OM_CC_MSVC)
  friend class BaseDecimaterT;
#else
  template <typename Mesh> friend class BaseDecimaterT;
#endif

  void     clear()           { mod_ = NULL; }
  void     init(Module* _m)  { mod_ = _m;   }
  Module*  module()          { return mod_; }

private:

  Module* mod_;

};

//== CLASS DEFINITION =========================================================

/// Macro that sets up the name() function
/// \internal
#define DECIMATER_MODNAME(_mod_name) \
 virtual const std::string& name() const { \
  static std::string _s_modname_(#_mod_name); return _s_modname_; \
}

/** Convenience macro, to be used in derived modules
 *  The macro defines the types
 *  - \c Handle, type of the module's handle.
 *  - \c Base,   type of ModBaseT<>.
 *  - \c Mesh,   type of the associated mesh passed by the decimater type.
 *  - \c CollapseInfo,  to your convenience
 *  and uses DECIMATER_MODNAME() to define the name of the module.
 *
 *  \param Classname  The name of the derived class.
 *  \param DecimaterT Pass here the decimater type, which is the
 *                    template parameter passed to ModBaseT.
 *  \param Name       Give the module a name.
 */
#define DECIMATING_MODULE(Classname, MeshT, Name)	\
  typedef Classname < MeshT >    Self;		\
  typedef OpenMesh::Decimater::ModHandleT< Self >     Handle; \
  typedef OpenMesh::Decimater::ModBaseT< MeshT > Base;   \
  typedef typename Base::Mesh         Mesh;		\
  typedef typename Base::CollapseInfo CollapseInfo;	\
  DECIMATER_MODNAME( Name )

//== CLASS DEFINITION =========================================================

/** Base class for all decimation modules.

    Each module has to implement this interface.
    To build your own module you have to
    -# derive from this class.
    -# create the basic settings with DECIMATING_MODULE().
    -# override collapse_priority(), if necessary.
    -# override initialize(), if necessary.
    -# override postprocess_collapse(), if necessary.

    A module has two major working modes:
    -# binary mode
    -# non-binary mode

    In the binary mode collapse_priority() checks a constraint and
    returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.

    In the non-binary mode the module computes a float error value in
    the range [0, inf) and returns it. In the case a constraint has
    been set, e.g. the error must be lower than a upper bound, and the
    constraint is violated, collapse_priority() must return
    ILLEGAL_COLLAPSE.

    \see collapse_priority()

    \todo "Tutorial on building a custom decimation module."

*/

template <typename MeshT>
class ModBaseT
{
public:
  typedef MeshT Mesh;
  typedef CollapseInfoT<MeshT>                 CollapseInfo;

  enum {
    ILLEGAL_COLLAPSE = -1, ///< indicates an illegal collapse
    LEGAL_COLLAPSE   = 0   ///< indicates a legal collapse
  };

protected:

  /// Default constructor
  /// \see \ref decimater_docu
  ModBaseT(MeshT& _mesh, bool _is_binary)
    : mesh_(_mesh), is_binary_(_is_binary) {}

public:

  /// Virtual desctructor
  virtual ~ModBaseT() { }

  /// Set module's name (using DECIMATER_MODNAME macro)
  DECIMATER_MODNAME(ModBase);

  /// Returns true if criteria returns a binary value.
  bool is_binary(void) const { return is_binary_; }

  /// Set whether module is binary or not.
  void set_binary(bool _b)   { is_binary_ = _b; }

public: // common interface

   /// Initialize module-internal stuff
   virtual void initialize() { }

   /** Return collapse priority.
    *
    *  In the binary mode collapse_priority() checks a constraint and
    *  returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.
    *
    *  In the non-binary mode the module computes a float error value in
    *  the range [0, inf) and returns it. In the case a constraint has
    *  been set, e.g. the error must be lower than a upper bound, and the
    *  constraint is violated, collapse_priority() must return
    *  ILLEGAL_COLLAPSE.
    *
    *  \return Collapse priority in the range [0,inf),
    *          \c LEGAL_COLLAPSE or \c ILLEGAL_COLLAPSE.
    */
   virtual float collapse_priority(const CollapseInfoT<MeshT>& /* _ci */)
   { return LEGAL_COLLAPSE; }

   /** Before _from_vh has been collapsed into _to_vh, this method
       will be called.
    */
   virtual void preprocess_collapse(const CollapseInfoT<MeshT>& /* _ci */)
   {}

   /** After _from_vh has been collapsed into _to_vh, this method
       will be called.
    */
   virtual void postprocess_collapse(const CollapseInfoT<MeshT>& /* _ci */)
   {}

protected:

  /// Access the mesh associated with the decimater.
  MeshT& mesh() { return mesh_; }

private:

  // hide copy constructor & assignemnt
  ModBaseT(const ModBaseT& _cpy);
  ModBaseT& operator=(const ModBaseT& );

  MeshT& mesh_;

  bool is_binary_;
};

//=============================================================================
} // namespace Decimater
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_DECIMATER_MODBASE_HH defined
//=============================================================================

<commit_msg>- fix doc warning<commit_after>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh is distributed in the hope that it will be useful,              *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

/** \file ModBaseT.hh
    Base class for all decimation modules.
 */

//=============================================================================
//
//  CLASS ModBaseT
//
//=============================================================================

#ifndef OPENMESH_DECIMATER_MODBASET_HH
#define OPENMESH_DECIMATER_MODBASET_HH

//== INCLUDES =================================================================

#include <OpenMesh/Core/Utils/Noncopyable.hh>
#include <OpenMesh/Tools/Decimater/CollapseInfoT.hh>
#include <string>

//== NAMESPACE ================================================================

namespace OpenMesh  {
namespace Decimater {

//== FORWARD DECLARATIONS =====================================================

template <typename Mesh> class BaseDecimaterT;

//== CLASS DEFINITION =========================================================

/** Handle for mesh decimation modules
    \internal
 */

template <typename Module>
class ModHandleT : private Utils::Noncopyable
{
public:

  typedef ModHandleT<Module> Self;
  typedef Module module_type;

public:

  /// Default constructor
  ModHandleT() : mod_(NULL) {}

  /// Destructor
  ~ModHandleT() { /* don't delete mod_, since handle is not owner! */ }

  /// Check handle status
  /// \return \c true, if handle is valid, else \c false.
  bool is_valid() const { return mod_ != NULL; }

private:

#if defined(OM_CC_MSVC)
  friend class BaseDecimaterT;
#else
  template <typename Mesh> friend class BaseDecimaterT;
#endif

  void     clear()           { mod_ = NULL; }
  void     init(Module* _m)  { mod_ = _m;   }
  Module*  module()          { return mod_; }

private:

  Module* mod_;

};

//== CLASS DEFINITION =========================================================

/// Macro that sets up the name() function
/// \internal
#define DECIMATER_MODNAME(_mod_name) \
 virtual const std::string& name() const { \
  static std::string _s_modname_(#_mod_name); return _s_modname_; \
}

/** Convenience macro, to be used in derived modules
 *  The macro defines the types
 *  - \c Handle, type of the module's handle.
 *  - \c Base,   type of ModBaseT<>.
 *  - \c Mesh,   type of the associated mesh passed by the decimater type.
 *  - \c CollapseInfo,  to your convenience
 *  and uses DECIMATER_MODNAME() to define the name of the module.
 *
 *  \param Classname  The name of the derived class.
 *  \param MeshT      Pass here the mesh type, which is the
 *                    template parameter passed to ModBaseT.
 *  \param Name       Give the module a name.
 */
#define DECIMATING_MODULE(Classname, MeshT, Name)	\
  typedef Classname < MeshT >    Self;		\
  typedef OpenMesh::Decimater::ModHandleT< Self >     Handle; \
  typedef OpenMesh::Decimater::ModBaseT< MeshT > Base;   \
  typedef typename Base::Mesh         Mesh;		\
  typedef typename Base::CollapseInfo CollapseInfo;	\
  DECIMATER_MODNAME( Name )

//== CLASS DEFINITION =========================================================

/** Base class for all decimation modules.

    Each module has to implement this interface.
    To build your own module you have to
    -# derive from this class.
    -# create the basic settings with DECIMATING_MODULE().
    -# override collapse_priority(), if necessary.
    -# override initialize(), if necessary.
    -# override postprocess_collapse(), if necessary.

    A module has two major working modes:
    -# binary mode
    -# non-binary mode

    In the binary mode collapse_priority() checks a constraint and
    returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.

    In the non-binary mode the module computes a float error value in
    the range [0, inf) and returns it. In the case a constraint has
    been set, e.g. the error must be lower than a upper bound, and the
    constraint is violated, collapse_priority() must return
    ILLEGAL_COLLAPSE.

    \see collapse_priority()

    \todo "Tutorial on building a custom decimation module."

*/

template <typename MeshT>
class ModBaseT
{
public:
  typedef MeshT Mesh;
  typedef CollapseInfoT<MeshT>                 CollapseInfo;

  enum {
    ILLEGAL_COLLAPSE = -1, ///< indicates an illegal collapse
    LEGAL_COLLAPSE   = 0   ///< indicates a legal collapse
  };

protected:

  /// Default constructor
  /// \see \ref decimater_docu
  ModBaseT(MeshT& _mesh, bool _is_binary)
    : mesh_(_mesh), is_binary_(_is_binary) {}

public:

  /// Virtual desctructor
  virtual ~ModBaseT() { }

  /// Set module's name (using DECIMATER_MODNAME macro)
  DECIMATER_MODNAME(ModBase);

  /// Returns true if criteria returns a binary value.
  bool is_binary(void) const { return is_binary_; }

  /// Set whether module is binary or not.
  void set_binary(bool _b)   { is_binary_ = _b; }

public: // common interface

   /// Initialize module-internal stuff
   virtual void initialize() { }

   /** Return collapse priority.
    *
    *  In the binary mode collapse_priority() checks a constraint and
    *  returns LEGAL_COLLAPSE or ILLEGAL_COLLAPSE.
    *
    *  In the non-binary mode the module computes a float error value in
    *  the range [0, inf) and returns it. In the case a constraint has
    *  been set, e.g. the error must be lower than a upper bound, and the
    *  constraint is violated, collapse_priority() must return
    *  ILLEGAL_COLLAPSE.
    *
    *  \return Collapse priority in the range [0,inf),
    *          \c LEGAL_COLLAPSE or \c ILLEGAL_COLLAPSE.
    */
   virtual float collapse_priority(const CollapseInfoT<MeshT>& /* _ci */)
   { return LEGAL_COLLAPSE; }

   /** Before _from_vh has been collapsed into _to_vh, this method
       will be called.
    */
   virtual void preprocess_collapse(const CollapseInfoT<MeshT>& /* _ci */)
   {}

   /** After _from_vh has been collapsed into _to_vh, this method
       will be called.
    */
   virtual void postprocess_collapse(const CollapseInfoT<MeshT>& /* _ci */)
   {}

protected:

  /// Access the mesh associated with the decimater.
  MeshT& mesh() { return mesh_; }

private:

  // hide copy constructor & assignemnt
  ModBaseT(const ModBaseT& _cpy);
  ModBaseT& operator=(const ModBaseT& );

  MeshT& mesh_;

  bool is_binary_;
};

//=============================================================================
} // namespace Decimater
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_DECIMATER_MODBASE_HH defined
//=============================================================================

<|endoftext|>


<commit_before>#include <GL/glew.h>
#include "EditorWindow.hpp"

#include "Util/EditorSettings.hpp"
#include <Engine/Util/Log.hpp>

#include "GUI/ImageButton.hpp"
#include "GUI/ImageTextButton.hpp"
#include <Engine/Resources.hpp>
#include <File.png.hpp>
#include <Options.png.hpp>
#include <Play.png.hpp>
#include <NewHymn.png.hpp>
#include <OpenHymn.png.hpp>
#include <ABeeZee.ttf.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>

EditorWindow::EditorWindow() : Container(nullptr) {
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Enable debug context and set message callback.
    if (EditorSettings::GetInstance().GetBool("Debug Context"))
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

    window = glfwCreateWindow(640, 480, "Hymn to Beauty", nullptr, nullptr);
    if (!window) {
        glfwTerminate();
        /// @todo Print error to log.
    }

    glfwMakeContextCurrent(window);

    gameWindow = nullptr;
    childWindow = nullptr;
    input = new InputHandler(window);
}

EditorWindow::~EditorWindow() {
    delete fileButton;
    delete optionsButton;
    delete playButton;
    delete menuBar;

    delete newHymnButton;
    delete openHymnButton;
    delete fileMenu;

    Resources().FreeTexture2D(fileTexture);
    Resources().FreeTexture2D(optionsTexture);
    Resources().FreeTexture2D(playTexture);

    Resources().FreeTexture2D(newHymnTexture);
    Resources().FreeTexture2D(openHymnTexture);

    delete input;

    Resources().FreeFont(font);

    glfwDestroyWindow(window);
}

void EditorWindow::Init() {
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    font = Resources().CreateFontEmbedded(ABEEZEE_TTF, ABEEZEE_TTF_LENGTH, 24.f);

    // Menu bar.
    menuBar = new GUI::HorizontalLayout(this);
    menuBar->SetSize(glm::vec2(static_cast<float>(width), 64.f));
    AddWidget(menuBar);

    fileTexture = Resources().CreateTexture2D(FILE_PNG, FILE_PNG_LENGTH);
    fileButton = new GUI::ImageButton(menuBar, fileTexture);
    fileButton->SetClickedCallback(std::bind(&OpenFileMenu, this));
    menuBar->AddWidget(fileButton);

    optionsTexture = Resources().CreateTexture2D(OPTIONS_PNG, OPTIONS_PNG_LENGTH);
    optionsButton = new GUI::ImageButton(menuBar, optionsTexture);
    optionsButton->SetClickedCallback(std::bind(&OpenProjectOptions, this));
    menuBar->AddWidget(optionsButton);

    playTexture = Resources().CreateTexture2D(PLAY_PNG, PLAY_PNG_LENGTH);
    playButton = new GUI::ImageButton(menuBar, playTexture);
    playButton->SetClickedCallback(std::bind(&Play, this));
    menuBar->AddWidget(playButton);

    // File menu.
    fileMenu = new GUI::VerticalLayout(this);
    fileMenu->SetSize(glm::vec2(256.f, 2.f * 64.f));
    fileMenu->SetPosition(glm::vec2(0.f, 64.f));
    fileMenu->SetVisible(false);
    AddWidget(fileMenu);

    newHymnTexture = Resources().CreateTexture2D(NEWHYMN_PNG, NEWHYMN_PNG_LENGTH);
    newHymnButton = new GUI::ImageTextButton(fileMenu, newHymnTexture, font, "New Hymn");
    newHymnButton->SetSize(glm::vec2(256.f, 64.f));
    newHymnButton->SetClickedCallback(std::bind(&NewHymn, this));
    fileMenu->AddWidget(newHymnButton);

    openHymnTexture = Resources().CreateTexture2D(OPENHYMN_PNG, OPENHYMN_PNG_LENGTH);
    openHymnButton = new GUI::ImageTextButton(fileMenu, openHymnTexture, font, "Open Hymn");
    openHymnButton->SetSize(glm::vec2(256.f, 64.f));
    openHymnButton->SetClickedCallback(std::bind(&OpenHymn, this));
    fileMenu->AddWidget(openHymnButton);

    glEnable(GL_DEPTH_TEST);
}

bool EditorWindow::ShouldClose() const {
    return (glfwWindowShouldClose(window) != 0);
}

void EditorWindow::Update() {
    // Handle running game.
    if (gameWindow != nullptr) {
        gameWindow->Update();
        if (gameWindow->ShouldClose()) {
            delete gameWindow;
            gameWindow = nullptr;
        }
    } else if (childWindow != nullptr) {
        input->Update();
        input->SetActive();
        childWindow->Update();
    } else if (glfwGetKey(window, GLFW_KEY_F5) == GLFW_PRESS) {
        Play();
    } else {
        input->Update();
        input->SetActive();
        UpdateWidgets();
    }
}

void EditorWindow::Render() {
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    Render(glm::vec2(static_cast<float>(width), static_cast<float>(height)));
}

void EditorWindow::Render(const glm::vec2& screenSize) {
    if (gameWindow != nullptr) {
        gameWindow->Render();
    } else {
        glfwMakeContextCurrent(window);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        RenderWidgets(screenSize);

        if (childWindow != nullptr)
            childWindow->Render(screenSize);

        glfwSwapBuffers(window);
    }
}

glm::vec2 EditorWindow::Size() const {
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    return glm::vec2(static_cast<float>(width), static_cast<float>(height));
}

void EditorWindow::SetSize(const glm::vec2& size) {
    /// @todo Resize window.
}

void EditorWindow::OpenFileMenu() {
    fileMenu->SetVisible(!fileMenu->Visible());
}

void EditorWindow::OpenProjectOptions() {
    ///@todo Project options
    Log() << "Click test!\n";
}

void EditorWindow::Play() {
    gameWindow = new GameWindow();
}

void EditorWindow::NewHymn() {
    childWindow = new GUI::SelectHymnWindow(this);
    childWindow->SetPosition(glm::vec2(0.f, 0.f));
    childWindow->SetSize(Size());
    childWindow->SetClosedCallback(std::bind(&NewHymnClosed, this, std::placeholders::_1));
}

void EditorWindow::NewHymnClosed(const std::string& hymn) {
    // Create new hymn
    if (!hymn.empty()) {
        Hymn().Clear();
        Hymn().SetPath(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));
    }

    delete childWindow;
    childWindow = nullptr;
}

void EditorWindow::OpenHymn() {
    childWindow = new GUI::SelectHymnWindow(this);
    childWindow->SetPosition(glm::vec2(0.f, 0.f));
    childWindow->SetSize(Size());
    childWindow->SetClosedCallback(std::bind(&OpenHymnClosed, this, std::placeholders::_1));
}

void EditorWindow::OpenHymnClosed(const std::string& hymn) {
    // Open hymn.
    if (!hymn.empty())
        Hymn().Load(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));

    delete childWindow;
    childWindow = nullptr;
}
<commit_msg>Hide file menu after selecting a hymn.<commit_after>#include <GL/glew.h>
#include "EditorWindow.hpp"

#include "Util/EditorSettings.hpp"
#include <Engine/Util/Log.hpp>

#include "GUI/ImageButton.hpp"
#include "GUI/ImageTextButton.hpp"
#include <Engine/Resources.hpp>
#include <File.png.hpp>
#include <Options.png.hpp>
#include <Play.png.hpp>
#include <NewHymn.png.hpp>
#include <OpenHymn.png.hpp>
#include <ABeeZee.ttf.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>

EditorWindow::EditorWindow() : Container(nullptr) {
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Enable debug context and set message callback.
    if (EditorSettings::GetInstance().GetBool("Debug Context"))
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

    window = glfwCreateWindow(640, 480, "Hymn to Beauty", nullptr, nullptr);
    if (!window) {
        glfwTerminate();
        /// @todo Print error to log.
    }

    glfwMakeContextCurrent(window);

    gameWindow = nullptr;
    childWindow = nullptr;
    input = new InputHandler(window);
}

EditorWindow::~EditorWindow() {
    delete fileButton;
    delete optionsButton;
    delete playButton;
    delete menuBar;

    delete newHymnButton;
    delete openHymnButton;
    delete fileMenu;

    Resources().FreeTexture2D(fileTexture);
    Resources().FreeTexture2D(optionsTexture);
    Resources().FreeTexture2D(playTexture);

    Resources().FreeTexture2D(newHymnTexture);
    Resources().FreeTexture2D(openHymnTexture);

    delete input;

    Resources().FreeFont(font);

    glfwDestroyWindow(window);
}

void EditorWindow::Init() {
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    font = Resources().CreateFontEmbedded(ABEEZEE_TTF, ABEEZEE_TTF_LENGTH, 24.f);

    // Menu bar.
    menuBar = new GUI::HorizontalLayout(this);
    menuBar->SetSize(glm::vec2(static_cast<float>(width), 64.f));
    AddWidget(menuBar);

    fileTexture = Resources().CreateTexture2D(FILE_PNG, FILE_PNG_LENGTH);
    fileButton = new GUI::ImageButton(menuBar, fileTexture);
    fileButton->SetClickedCallback(std::bind(&OpenFileMenu, this));
    menuBar->AddWidget(fileButton);

    optionsTexture = Resources().CreateTexture2D(OPTIONS_PNG, OPTIONS_PNG_LENGTH);
    optionsButton = new GUI::ImageButton(menuBar, optionsTexture);
    optionsButton->SetClickedCallback(std::bind(&OpenProjectOptions, this));
    menuBar->AddWidget(optionsButton);

    playTexture = Resources().CreateTexture2D(PLAY_PNG, PLAY_PNG_LENGTH);
    playButton = new GUI::ImageButton(menuBar, playTexture);
    playButton->SetClickedCallback(std::bind(&Play, this));
    menuBar->AddWidget(playButton);

    // File menu.
    fileMenu = new GUI::VerticalLayout(this);
    fileMenu->SetSize(glm::vec2(256.f, 2.f * 64.f));
    fileMenu->SetPosition(glm::vec2(0.f, 64.f));
    fileMenu->SetVisible(false);
    AddWidget(fileMenu);

    newHymnTexture = Resources().CreateTexture2D(NEWHYMN_PNG, NEWHYMN_PNG_LENGTH);
    newHymnButton = new GUI::ImageTextButton(fileMenu, newHymnTexture, font, "New Hymn");
    newHymnButton->SetSize(glm::vec2(256.f, 64.f));
    newHymnButton->SetClickedCallback(std::bind(&NewHymn, this));
    fileMenu->AddWidget(newHymnButton);

    openHymnTexture = Resources().CreateTexture2D(OPENHYMN_PNG, OPENHYMN_PNG_LENGTH);
    openHymnButton = new GUI::ImageTextButton(fileMenu, openHymnTexture, font, "Open Hymn");
    openHymnButton->SetSize(glm::vec2(256.f, 64.f));
    openHymnButton->SetClickedCallback(std::bind(&OpenHymn, this));
    fileMenu->AddWidget(openHymnButton);

    glEnable(GL_DEPTH_TEST);
}

bool EditorWindow::ShouldClose() const {
    return (glfwWindowShouldClose(window) != 0);
}

void EditorWindow::Update() {
    // Handle running game.
    if (gameWindow != nullptr) {
        gameWindow->Update();
        if (gameWindow->ShouldClose()) {
            delete gameWindow;
            gameWindow = nullptr;
        }
    } else if (childWindow != nullptr) {
        input->Update();
        input->SetActive();
        childWindow->Update();
    } else if (glfwGetKey(window, GLFW_KEY_F5) == GLFW_PRESS) {
        Play();
    } else {
        input->Update();
        input->SetActive();
        UpdateWidgets();
    }
}

void EditorWindow::Render() {
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    Render(glm::vec2(static_cast<float>(width), static_cast<float>(height)));
}

void EditorWindow::Render(const glm::vec2& screenSize) {
    if (gameWindow != nullptr) {
        gameWindow->Render();
    } else {
        glfwMakeContextCurrent(window);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        RenderWidgets(screenSize);

        if (childWindow != nullptr)
            childWindow->Render(screenSize);

        glfwSwapBuffers(window);
    }
}

glm::vec2 EditorWindow::Size() const {
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    return glm::vec2(static_cast<float>(width), static_cast<float>(height));
}

void EditorWindow::SetSize(const glm::vec2& size) {
    /// @todo Resize window.
}

void EditorWindow::OpenFileMenu() {
    fileMenu->SetVisible(!fileMenu->Visible());
}

void EditorWindow::OpenProjectOptions() {
    ///@todo Project options
    Log() << "Click test!\n";
}

void EditorWindow::Play() {
    gameWindow = new GameWindow();
}

void EditorWindow::NewHymn() {
    childWindow = new GUI::SelectHymnWindow(this);
    childWindow->SetPosition(glm::vec2(0.f, 0.f));
    childWindow->SetSize(Size());
    childWindow->SetClosedCallback(std::bind(&NewHymnClosed, this, std::placeholders::_1));
}

void EditorWindow::NewHymnClosed(const std::string& hymn) {
    // Create new hymn
    if (!hymn.empty()) {
        Hymn().Clear();
        Hymn().SetPath(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));
    }

    delete childWindow;
    childWindow = nullptr;

    fileMenu->SetVisible(false);
}

void EditorWindow::OpenHymn() {
    childWindow = new GUI::SelectHymnWindow(this);
    childWindow->SetPosition(glm::vec2(0.f, 0.f));
    childWindow->SetSize(Size());
    childWindow->SetClosedCallback(std::bind(&OpenHymnClosed, this, std::placeholders::_1));
}

void EditorWindow::OpenHymnClosed(const std::string& hymn) {
    // Open hymn.
    if (!hymn.empty())
        Hymn().Load(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));

    delete childWindow;
    childWindow = nullptr;

    fileMenu->SetVisible(false);
}
<|endoftext|>


<commit_before>#include "ovassvepCSSVEPFlickeringObject.h"
#include <iostream>

using namespace OpenViBESSVEP;

CSSVEPFlickeringObject::CSSVEPFlickeringObject(Ogre::SceneNode* poObjectNode, OpenViBE::uint32 ui32LitFrames, OpenViBE::uint32 ui32DarkFrames) :
	m_poObjectNode( poObjectNode ),
	m_ui32LitFrames( ui32LitFrames ),
	m_ui32DarkFrames( ui32DarkFrames ),
	m_bVisible( true )
{
	std::cout << "lit " << ui32LitFrames << " dark " << ui32DarkFrames << "\n";
}

void CSSVEPFlickeringObject::setVisible( bool bVisibility )
{
	if ( (!m_bVisible && bVisibility) || (m_bVisible && !bVisibility) )
	{
		m_poObjectNode->flipVisibility();
	}
	m_bVisible = bVisibility;
}

void CSSVEPFlickeringObject::processFrame(OpenViBE::uint32 ui32CurrentFrame)
{
	if (ui32CurrentFrame % ( m_ui32LitFrames + m_ui32DarkFrames ) < m_ui32LitFrames)
	{
		this->setVisible( true );
	}
	else
	{
		this->setVisible( false );
	}
}
<commit_msg>openvibe-applications/ssvep: - removed a debug message<commit_after>#include "ovassvepCSSVEPFlickeringObject.h"
#include <iostream>

using namespace OpenViBESSVEP;

CSSVEPFlickeringObject::CSSVEPFlickeringObject(Ogre::SceneNode* poObjectNode, OpenViBE::uint32 ui32LitFrames, OpenViBE::uint32 ui32DarkFrames) :
	m_poObjectNode( poObjectNode ),
	m_ui32LitFrames( ui32LitFrames ),
	m_ui32DarkFrames( ui32DarkFrames ),
	m_bVisible( true )
{
}

void CSSVEPFlickeringObject::setVisible( bool bVisibility )
{
	if ( (!m_bVisible && bVisibility) || (m_bVisible && !bVisibility) )
	{
		m_poObjectNode->flipVisibility();
	}
	m_bVisible = bVisibility;
}

void CSSVEPFlickeringObject::processFrame(OpenViBE::uint32 ui32CurrentFrame)
{
	if (ui32CurrentFrame % ( m_ui32LitFrames + m_ui32DarkFrames ) < m_ui32LitFrames)
	{
		this->setVisible( true );
	}
	else
	{
		this->setVisible( false );
	}
}
<|endoftext|>


<commit_before>#include <algorithm>

#include <glog/logging.h>

#include "simple_allocator.hpp"

using std::max;
using std::sort;

using namespace mesos;
using namespace mesos::internal;
using namespace mesos::internal::master;

void SimpleAllocator::frameworkAdded(Framework* framework)
{
  LOG(INFO) << "Added " << framework;
  makeNewOffers();
}

void SimpleAllocator::frameworkRemoved(Framework* framework)
{
  LOG(INFO) << "Removed " << framework;
  foreachpair (Slave* s, unordered_set<Framework*>& refs, refusers)
    refs.erase(framework);
  // TODO: Re-offer just the slaves that the framework had tasks on?
  //       Alternatively, comment this out and wait for a timer tick
  makeNewOffers();
}

void SimpleAllocator::slaveAdded(Slave* slave)
{
  LOG(INFO) << "Added " << slave;
  refusers[slave] = unordered_set<Framework*>();
  totalResources += slave->resources;
  makeNewOffers(slave);
}

void SimpleAllocator::slaveRemoved(Slave* slave)
{
  LOG(INFO) << "Removed " << slave;
  totalResources -= slave->resources;
  refusers.erase(slave);
}

void SimpleAllocator::taskRemoved(Task* task, TaskRemovalReason reason)
{
  LOG(INFO) << "Removed " << task;
  // Remove all refusers from this slave since it has more resources free
  Slave* slave = master->lookupSlave(task->slaveId);
  CHECK(slave != 0);
  refusers[slave].clear();
  // Re-offer the resources, unless this task was removed due to a lost
  // slave or a lost framework (in which case we'll get another callback)
  if (reason == TRR_TASK_ENDED || reason == TRR_EXECUTOR_LOST)
    makeNewOffers(slave);
}

void SimpleAllocator::offerReturned(SlotOffer* offer,
                                    OfferReturnReason reason,
                                    const vector<SlaveResources>& resLeft)
{
  LOG(INFO) << "Offer returned: " << offer << ", reason = " << reason;
  // If this offer returned due to the framework replying, add it to refusers
  if (reason == ORR_FRAMEWORK_REPLIED) {
    Framework* framework = master->lookupFramework(offer->frameworkId);
    CHECK(framework != 0);
    foreach (const SlaveResources& r, resLeft) {
      VLOG(1) << "Framework reply leaves " << r.resources
              << " free on " << r.slave;
      if (r.resources.cpus > 0 || r.resources.mem > 0) {
        VLOG(1) << "Inserting " << framework << " as refuser for " << r.slave;
        refusers[r.slave].insert(framework);
      }
    }
  }
  // Make new offers, unless the offer returned due to a lost framework or slave
  // (in those cases, frameworkRemoved and slaveRemoved will be called later)
  if (reason != ORR_SLAVE_LOST && reason != ORR_FRAMEWORK_LOST) {
    vector<Slave*> slaves;
    foreach (const SlaveResources& r, resLeft)
      slaves.push_back(r.slave);
    makeNewOffers(slaves);
  }
}

void SimpleAllocator::offersRevived(Framework* framework)
{
  LOG(INFO) << "Filters removed for " << framework;
  makeNewOffers();
}

void SimpleAllocator::timerTick()
{
  // TODO: Is this necessary?
  makeNewOffers();
}

namespace {

struct DominantShareComparator
{
  Resources total;

  DominantShareComparator(Resources _total) : total(_total)
  {
    if (total.cpus == 0) // Prevent division by zero if there are no slaves
      total.cpus = 1;
    if (total.mem == 0)
      total.mem = 1;
  }

  bool operator() (Framework* f1, Framework* f2)
  {
    double share1 = max(f1->resources.cpus / (double) total.cpus,
                        f1->resources.mem  / (double) total.mem);
    double share2 = max(f2->resources.cpus / (double) total.cpus,
                        f2->resources.mem  / (double) total.mem);
    if (share1 == share2)
      return f1->id < f2->id; // Make the sort deterministic for unit testing
    else
      return share1 < share2;
  }
};

}

vector<Framework*> SimpleAllocator::getAllocationOrdering()
{
  vector<Framework*> frameworks = master->getActiveFrameworks();
  DominantShareComparator comp(totalResources);
  sort(frameworks.begin(), frameworks.end(), comp);
  return frameworks;
}

void SimpleAllocator::makeNewOffers()
{
  // TODO: Create a method in master so that we don't return the whole list of slaves
  vector<Slave*> slaves = master->getActiveSlaves();
  makeNewOffers(slaves);
}

void SimpleAllocator::makeNewOffers(Slave* slave)
{
  vector<Slave*> slaves;
  slaves.push_back(slave);
  makeNewOffers(slaves);
}

void SimpleAllocator::makeNewOffers(const vector<Slave*>& slaves)
{
  // Get an ordering of frameworks to send offers to
  vector<Framework*> ordering = getAllocationOrdering();
  if (ordering.size() == 0) {
    VLOG(1) << "makeNewOffers returning because no frameworks are connected";
    return;
  }

  // Find all the free resources that can be allocated
  unordered_map<Slave* , Resources> freeResources;
  foreach (Slave* slave, slaves) {
    if (slave->active) {
      Resources res = slave->resourcesFree();
      if (res.cpus >= MIN_CPUS && res.mem >= MIN_MEM) {
        VLOG(1) << "Found free resources: " << res << " on " << slave;
        freeResources[slave] = res;
      }
    }
  }
  if (freeResources.size() == 0) {
    VLOG(1) << "makeNewOffers returning because there are no free resources";
    return;
  }

  // Clear refusers on any slave that has been refused by everyone
  foreachpair (Slave* slave, _, freeResources) {
    unordered_set<Framework*>& refs = refusers[slave];
    if (refs.size() == ordering.size()) {
      VLOG(1) << "Clearing refusers for " << slave
              << " because everyone refused it";
      refs.clear();
    }
  }

  foreach (Framework* framework, ordering) {
    // See which resources this framework can take (given filters & refusals)
    vector<SlaveResources> offerable;
    foreachpair (Slave* slave, Resources resources, freeResources) {
      if (refusers[slave].find(framework) == refusers[slave].end() &&
          !framework->filters(slave, resources)) {
        VLOG(1) << "Offering " << resources << " on " << slave
                << " to framework " << framework->id;
        offerable.push_back(SlaveResources(slave, resources));
      }
    }
    if (offerable.size() > 0) {
      foreach (SlaveResources& r, offerable) {
        freeResources.erase(r.slave);
      }
      master->makeOffer(framework, offerable);
    }
  }
}
<commit_msg>Fixed a bug with offerReturned in simple_allocator: When offerReturned is called due to a framework failover, the framework's new PID will not be set yet, so we shouldn't reoffer resources right away. This was probably not a problem before the issue 108 patch because the old Framework object was marked as inactive so the allocator reoffered to other frameworks. However, it seems weird to mark the framework as inactive when we're going to mark it as active again later in the failover case, and it's easier to just wait for the next timer tick to reoffer those resources.<commit_after>#include <algorithm>

#include <glog/logging.h>

#include "simple_allocator.hpp"

using std::max;
using std::sort;

using namespace mesos;
using namespace mesos::internal;
using namespace mesos::internal::master;

void SimpleAllocator::frameworkAdded(Framework* framework)
{
  LOG(INFO) << "Added " << framework;
  makeNewOffers();
}

void SimpleAllocator::frameworkRemoved(Framework* framework)
{
  LOG(INFO) << "Removed " << framework;
  foreachpair (Slave* s, unordered_set<Framework*>& refs, refusers)
    refs.erase(framework);
  // TODO: Re-offer just the slaves that the framework had tasks on?
  //       Alternatively, comment this out and wait for a timer tick
  makeNewOffers();
}

void SimpleAllocator::slaveAdded(Slave* slave)
{
  LOG(INFO) << "Added " << slave;
  refusers[slave] = unordered_set<Framework*>();
  totalResources += slave->resources;
  makeNewOffers(slave);
}

void SimpleAllocator::slaveRemoved(Slave* slave)
{
  LOG(INFO) << "Removed " << slave;
  totalResources -= slave->resources;
  refusers.erase(slave);
}

void SimpleAllocator::taskRemoved(Task* task, TaskRemovalReason reason)
{
  LOG(INFO) << "Removed " << task;
  // Remove all refusers from this slave since it has more resources free
  Slave* slave = master->lookupSlave(task->slaveId);
  CHECK(slave != 0);
  refusers[slave].clear();
  // Re-offer the resources, unless this task was removed due to a lost
  // slave or a lost framework (in which case we'll get another callback)
  if (reason == TRR_TASK_ENDED || reason == TRR_EXECUTOR_LOST)
    makeNewOffers(slave);
}

void SimpleAllocator::offerReturned(SlotOffer* offer,
                                    OfferReturnReason reason,
                                    const vector<SlaveResources>& resLeft)
{
  LOG(INFO) << "Offer returned: " << offer << ", reason = " << reason;
  // If this offer returned due to the framework replying, add it to refusers
  if (reason == ORR_FRAMEWORK_REPLIED) {
    Framework* framework = master->lookupFramework(offer->frameworkId);
    CHECK(framework != 0);
    foreach (const SlaveResources& r, resLeft) {
      VLOG(1) << "Framework reply leaves " << r.resources
              << " free on " << r.slave;
      if (r.resources.cpus > 0 || r.resources.mem > 0) {
        VLOG(1) << "Inserting " << framework << " as refuser for " << r.slave;
        refusers[r.slave].insert(framework);
      }
    }
  }
  // Make new offers unless the offer returned due to a lost framework or slave
  // (in those cases, frameworkRemoved and slaveRemoved will be called later),
  // or returned due to a framework failover (in which case the framework's
  // new PID won't be set yet so we just wait for the next timer tick).
  if (reason != ORR_SLAVE_LOST && reason != ORR_FRAMEWORK_LOST &&
      reason != ORR_FRAMEWORK_FAILOVER) {
    vector<Slave*> slaves;
    foreach (const SlaveResources& r, resLeft)
      slaves.push_back(r.slave);
    makeNewOffers(slaves);
  }
}

void SimpleAllocator::offersRevived(Framework* framework)
{
  LOG(INFO) << "Filters removed for " << framework;
  makeNewOffers();
}

void SimpleAllocator::timerTick()
{
  // TODO: Is this necessary?
  makeNewOffers();
}

namespace {

struct DominantShareComparator
{
  Resources total;

  DominantShareComparator(Resources _total) : total(_total)
  {
    if (total.cpus == 0) // Prevent division by zero if there are no slaves
      total.cpus = 1;
    if (total.mem == 0)
      total.mem = 1;
  }

  bool operator() (Framework* f1, Framework* f2)
  {
    double share1 = max(f1->resources.cpus / (double) total.cpus,
                        f1->resources.mem  / (double) total.mem);
    double share2 = max(f2->resources.cpus / (double) total.cpus,
                        f2->resources.mem  / (double) total.mem);
    if (share1 == share2)
      return f1->id < f2->id; // Make the sort deterministic for unit testing
    else
      return share1 < share2;
  }
};

}

vector<Framework*> SimpleAllocator::getAllocationOrdering()
{
  vector<Framework*> frameworks = master->getActiveFrameworks();
  DominantShareComparator comp(totalResources);
  sort(frameworks.begin(), frameworks.end(), comp);
  return frameworks;
}

void SimpleAllocator::makeNewOffers()
{
  // TODO: Create a method in master so that we don't return the whole list of slaves
  vector<Slave*> slaves = master->getActiveSlaves();
  makeNewOffers(slaves);
}

void SimpleAllocator::makeNewOffers(Slave* slave)
{
  vector<Slave*> slaves;
  slaves.push_back(slave);
  makeNewOffers(slaves);
}

void SimpleAllocator::makeNewOffers(const vector<Slave*>& slaves)
{
  // Get an ordering of frameworks to send offers to
  vector<Framework*> ordering = getAllocationOrdering();
  if (ordering.size() == 0) {
    VLOG(1) << "makeNewOffers returning because no frameworks are connected";
    return;
  }

  // Find all the free resources that can be allocated
  unordered_map<Slave* , Resources> freeResources;
  foreach (Slave* slave, slaves) {
    if (slave->active) {
      Resources res = slave->resourcesFree();
      if (res.cpus >= MIN_CPUS && res.mem >= MIN_MEM) {
        VLOG(1) << "Found free resources: " << res << " on " << slave;
        freeResources[slave] = res;
      }
    }
  }
  if (freeResources.size() == 0) {
    VLOG(1) << "makeNewOffers returning because there are no free resources";
    return;
  }

  // Clear refusers on any slave that has been refused by everyone
  foreachpair (Slave* slave, _, freeResources) {
    unordered_set<Framework*>& refs = refusers[slave];
    if (refs.size() == ordering.size()) {
      VLOG(1) << "Clearing refusers for " << slave
              << " because everyone refused it";
      refs.clear();
    }
  }

  foreach (Framework* framework, ordering) {
    // See which resources this framework can take (given filters & refusals)
    vector<SlaveResources> offerable;
    foreachpair (Slave* slave, Resources resources, freeResources) {
      if (refusers[slave].find(framework) == refusers[slave].end() &&
          !framework->filters(slave, resources)) {
        VLOG(1) << "Offering " << resources << " on " << slave
                << " to framework " << framework->id;
        offerable.push_back(SlaveResources(slave, resources));
      }
    }
    if (offerable.size() > 0) {
      foreach (SlaveResources& r, offerable) {
        freeResources.erase(r.slave);
      }
      master->makeOffer(framework, offerable);
    }
  }
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <opencv/cv.h>
#include <opencv/cxcore.h>
#include <opencv/highgui.h>
#include <opencv/cvaux.h>
#include <libusb-1.0/libusb.h>
#include <libuvc/libuvc.h>
#include <libuvc/libuvc_config.h>
#include "libuvc/include/libuvc/libuvc_internal.h"

void smd_cmd(uvc_device_handle_t *devh);

void cb(uvc_frame_t *frame, void *ptr)
{
  uvc_frame_t *bgr=NULL;
  uvc_error_t ret=(uvc_error_t)0;
  IplImage* cvImg=NULL;
  IplImage *leftim = cvCreateImage(cvSize(640,480),8,3);
  IplImage *rightim = cvCreateImage(cvSize(640,480),8,3);
  IplImage *tmp = NULL;
  IplImage* depth = cvCreateImage(cvGetSize(leftim),8,1);
  IplImage* l = cvCreateImage(cvGetSize(leftim),8,1);
  IplImage* r = cvCreateImage(cvGetSize(leftim),8,1);
  IplImage* dest = cvCreateImage(cvGetSize(leftim),8,3);

  printf("callback! length = %u, ptr = %d\n", (unsigned int)frame->data_bytes, (int)ptr);
  bgr = uvc_allocate_frame(frame->width * frame->height * 3);
  if(!bgr){
    printf("unable to allocate bgr frame!\n");
    return;
  }
  ret = uvc_any2bgr(frame, bgr);
  if(ret){
    uvc_perror(ret, "uvc_any2bgr");
    return;
  }

  cvImg = cvCreateImageHeader(
			      cvSize(bgr->width, bgr->height),
			      IPL_DEPTH_8U,
			      3);

  cvSetData(cvImg, bgr->data, bgr->width * 3);

  tmp=cvCloneImage(cvImg);
  cvSetImageROI(tmp,cvRect(0,0,320,480));
  cvResize(tmp,leftim,CV_INTER_LINEAR);
  cvSetImageROI(tmp,cvRect(320,0,320,480));
  cvResize(tmp,rightim,CV_INTER_LINEAR);
  cvReleaseImage(&tmp);

  cvNamedWindow("Left", CV_WINDOW_AUTOSIZE);
  cvShowImage("Left", leftim);
  cvWaitKey(10);

  cvNamedWindow("Right", CV_WINDOW_AUTOSIZE);
  cvShowImage("Right", rightim);
  cvWaitKey(10);

  cvCvtColor(leftim,l,CV_BGR2GRAY);
  cvCvtColor(rightim,r,CV_BGR2GRAY);
  cvFindStereoCorrespondence( l, r, CV_DISPARITY_BIRCHFIELD, depth, 100,
15, 3, 6, 8, 15 );
  cvCvtColor(depth,dest,CV_GRAY2BGR);
  cvScale(dest,dest,255/100);
  cvNamedWindow("Depth", CV_WINDOW_AUTOSIZE);
  cvShowImage("Depth", dest);
  cvWaitKey(10);

  cvReleaseImage(&depth);
  cvReleaseImage(&l);
  cvReleaseImage(&r);
  cvReleaseImage(&dest);

  cvReleaseImageHeader(&cvImg);
  cvReleaseImageHeader(&leftim);
  cvReleaseImageHeader(&rightim);

  uvc_free_frame(bgr);
}

int main()
{
  uvc_context_t *ctx=NULL;
  uvc_device_t *dev=NULL;
  uvc_device_handle_t *devh=NULL;
  uvc_stream_ctrl_t ctrl;
  uvc_error_t res=(uvc_error_t)0;
  uvc_error_t resAEMODE=(uvc_error_t)0;
  uvc_error_t resEXP=(uvc_error_t)0;

  unsigned int i,j;

  res = uvc_init(&ctx, NULL);

  if (res < 0) {
    uvc_perror(res, "uvc_init");
    return res;
  }
  puts("UVC initialized");

  res = uvc_find_device(
			ctx, &dev,
			0, 0, NULL);
  if (res < 0) {
    uvc_perror(res, "uvc_find_device"); /* no devices found */
  } else {
    puts("Device found");

    res = uvc_open(dev, &devh);
    if (res < 0) {
      uvc_perror(res, "uvc_open"); /* unable to open device */
    } else {
      puts("Device opened");
      uvc_print_diag(devh, stderr);

      /* Try to negotiate a 640x480 30 fps YUYV stream profile */
      res = uvc_get_stream_ctrl_format_size(
					    devh, &ctrl, /* result stored in ctrl */
					    UVC_FRAME_FORMAT_YUYV, /* YUV 422, aka YUV 4:2:2. try _COMPRESSED */
					    640, 480, 30 /* width, height, fps */
					    );
      /* Print out the result */
      uvc_print_stream_ctrl(&ctrl, stderr);

      if(res < 0){
	uvc_perror(res, "get_mode");
      }else{
	res = uvc_start_streaming(devh, &ctrl, cb, (void *)12345, 0);
	smd_cmd(devh);
	if(res < 0){
	  uvc_perror(res, "start_streaming");
	}else{
	  puts("Streaming for 10 seconds...");
	  resAEMODE = uvc_set_ae_mode(devh, 1);
	  uvc_perror(resAEMODE, "set_ae_mode");

	  while(1){
	    scanf("%d",&i);
	  }
	  uvc_stop_streaming(devh);
	  puts("Done streaming.");

	}

	uvc_close(devh);
	puts("Device closed");
      }
      uvc_unref_device(dev);
    }
  }
  uvc_exit(ctx);
  puts("UVC exited");

  return 0;
}

void smd_cmd(uvc_device_handle_t *devh)
{
  char buf[2];
  int res=0;

  libusb_device_handle *dev_handle=NULL;

  buf[0] = 0x76;
  buf[1] = 0xc3;
  dev_handle = devh->usb_devh;
  res = libusb_claim_interface(dev_handle, 0);
  if(res != LIBUSB_SUCCESS) printf("claim 0 is failed!\n");
  res = libusb_control_transfer(devh->usb_devh,
				0x21,
				0x01,
				0x0800,
				0x0600,
				(unsigned char *)buf,
				sizeof(buf),
				0);
  printf("res = %d\n",res);
  if(res == sizeof(buf))printf("Control transfer Success!\n");
  else printf("Control transfer Failed!\n");

  buf[0] = 0x04;
  buf[1] = 0x00;
  res = libusb_control_transfer(devh->usb_devh,
				0x21,
				0x01,
				0xa00,
				0x600,
				(unsigned char *)buf,
				sizeof(buf),
				0);
  if(res == sizeof(buf))printf("Control transfer Success!\n");
  else printf("Control transfer Failed!\n");
}

<commit_msg>remove stereo correspondanse temporery<commit_after>#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <opencv/cv.h>
#include <opencv/cxcore.h>
#include <opencv/highgui.h>
#include <opencv/cvaux.h>
#include <libusb-1.0/libusb.h>
#include <libuvc/libuvc.h>
#include <libuvc/libuvc_config.h>
#include "libuvc/include/libuvc/libuvc_internal.h"

void smd_cmd(uvc_device_handle_t *devh);

void cb(uvc_frame_t *frame, void *ptr)
{
  uvc_frame_t *bgr=NULL;
  uvc_error_t ret=(uvc_error_t)0;
  IplImage* cvImg=NULL;
  IplImage *leftim = cvCreateImage(cvSize(320,480),8,3);
  IplImage *rightim = cvCreateImage(cvSize(320,480),8,3);
  IplImage *tmp = NULL;
  IplImage* depth = cvCreateImage(cvGetSize(leftim),8,1);
  IplImage* l = cvCreateImage(cvGetSize(leftim),8,1);
  IplImage* r = cvCreateImage(cvGetSize(leftim),8,1);
  IplImage* dest = cvCreateImage(cvGetSize(leftim),8,3);

  printf("callback! length = %u, ptr = %d\n", (unsigned int)frame->data_bytes, (int)ptr);
  bgr = uvc_allocate_frame(frame->width * frame->height * 3);
  if(!bgr){
    printf("unable to allocate bgr frame!\n");
    return;
  }
  ret = uvc_any2bgr(frame, bgr);
  if(ret){
    uvc_perror(ret, "uvc_any2bgr");
    return;
  }

  cvImg = cvCreateImageHeader(
			      cvSize(bgr->width, bgr->height),
			      IPL_DEPTH_8U,
			      3);

  cvSetData(cvImg, bgr->data, bgr->width * 3);

  tmp=cvCloneImage(cvImg);
  cvSetImageROI(tmp,cvRect(0,0,320,480));
  cvResize(tmp,leftim,CV_INTER_LINEAR);
  cvSetImageROI(tmp,cvRect(320,0,320,480));
  cvResize(tmp,rightim,CV_INTER_LINEAR);
  cvReleaseImage(&tmp);

  cvNamedWindow("Left", CV_WINDOW_AUTOSIZE);
  cvShowImage("Left", leftim);
  cvWaitKey(10);

  cvNamedWindow("Right", CV_WINDOW_AUTOSIZE);
  cvShowImage("Right", rightim);

  cvCvtColor(leftim,l,CV_BGR2GRAY);
  cvCvtColor(rightim,r,CV_BGR2GRAY);
// cvFindStereoCorrespondence( l, r, CV_DISPARITY_BIRCHFIELD, depth, 127,
//15, 3, 6, 8, 15 );
//  cvCvtColor(depth,dest,CV_GRAY2BGR);
//  cvScale(dest,dest,255/100);
//  cvNamedWindow("Depth", CV_WINDOW_AUTOSIZE);
//  cvShowImage("Depth", dest);
  cvNamedWindow("Original", CV_WINDOW_AUTOSIZE);
  cvShowImage("Original", cvImg);

//  cvWaitKey(10);

  cvReleaseImage(&depth);
  cvReleaseImage(&l);
  cvReleaseImage(&r);
  cvReleaseImage(&dest);

  cvReleaseImageHeader(&cvImg);
  cvReleaseImageHeader(&leftim);
  cvReleaseImageHeader(&rightim);

  uvc_free_frame(bgr);
}

int main()
{
  uvc_context_t *ctx=NULL;
  uvc_device_t *dev=NULL;
  uvc_device_handle_t *devh=NULL;
  uvc_stream_ctrl_t ctrl;
  uvc_error_t res=(uvc_error_t)0;
  uvc_error_t resAEMODE=(uvc_error_t)0;
  uvc_error_t resEXP=(uvc_error_t)0;

  unsigned int i,j;

  res = uvc_init(&ctx, NULL);

  if (res < 0) {
    uvc_perror(res, "uvc_init");
    return res;
  }
  puts("UVC initialized");

  res = uvc_find_device(
			ctx, &dev,
			0, 0, NULL);
  if (res < 0) {
    uvc_perror(res, "uvc_find_device"); /* no devices found */
  } else {
    puts("Device found");

    res = uvc_open(dev, &devh);
    if (res < 0) {
      uvc_perror(res, "uvc_open"); /* unable to open device */
    } else {
      puts("Device opened");
      uvc_print_diag(devh, stderr);

      /* Try to negotiate a 640x480 30 fps YUYV stream profile */
      res = uvc_get_stream_ctrl_format_size(
					    devh, &ctrl, /* result stored in ctrl */
					    UVC_FRAME_FORMAT_YUYV, /* YUV 422, aka YUV 4:2:2. try _COMPRESSED */
					    640, 480, 30 /* width, height, fps */
					    );
      /* Print out the result */
      uvc_print_stream_ctrl(&ctrl, stderr);

      if(res < 0){
	uvc_perror(res, "get_mode");
      }else{
	res = uvc_start_streaming(devh, &ctrl, cb, (void *)12345, 0);
	smd_cmd(devh);
	if(res < 0){
	  uvc_perror(res, "start_streaming");
	}else{
	  puts("Streaming for 10 seconds...");
	  resAEMODE = uvc_set_ae_mode(devh, 1);
	  uvc_perror(resAEMODE, "set_ae_mode");

	  while(1){
	    scanf("%d",i);
//	    usleep(500000);
	  }
	  uvc_stop_streaming(devh);
	  puts("Done streaming.");

	}

	uvc_close(devh);
	puts("Device closed");
      }
      uvc_unref_device(dev);
    }
  }
  uvc_exit(ctx);
  puts("UVC exited");

  return 0;
}

void smd_cmd(uvc_device_handle_t *devh)
{
  char buf[2];
  int res=0;

  libusb_device_handle *dev_handle=NULL;

  buf[0] = 0x76;
  buf[1] = 0xc3;
  dev_handle = devh->usb_devh;
  res = libusb_claim_interface(dev_handle, 0);
  if(res != LIBUSB_SUCCESS) printf("claim 0 is failed!\n");
  res = libusb_control_transfer(devh->usb_devh,
				0x21,
				0x01,
				0x0800,
				0x0600,
				(unsigned char *)buf,
				sizeof(buf),
				0);
  printf("res = %d\n",res);
  if(res == sizeof(buf))printf("Control transfer Success!\n");
  else printf("Control transfer Failed!\n");

  buf[0] = 0x04;
  buf[1] = 0x00;
  res = libusb_control_transfer(devh->usb_devh,
				0x21,
				0x01,
				0xa00,
				0x600,
				(unsigned char *)buf,
				sizeof(buf),
				0);
  if(res == sizeof(buf))printf("Control transfer Success!\n");
  else printf("Control transfer Failed!\n");
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// lib.hpp
//
// Copyright (c) 2016-2017 Jeff Hutchinson
//
// 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.
//-----------------------------------------------------------------------------

#ifndef _JBL_LIB_HPP_
#define _JBL_LIB_HPP_

// Exception: These are compile time and do not link with the code.
// Thus I will allow it.
#include <type_traits>

#include <string.h>
#include "compiler.hpp"
#include "types.hpp"

template<typename T>
FORCE_INLINE T&& move_cast(T &ref)
{
	return static_cast<T&&>(ref);
}

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

template<typename T>
FORCE_INLINE T min(T a, T b)
{
	return (a < b) ? a : b;
}

// Equals override.
template<typename T> FORCE_INLINE bool equals(const T &lhs, const T &rhs);

template<typename T>
FORCE_INLINE bool equals(const T &lhs, const T &rhs)
{
	return lhs == rhs;
}

template<>
FORCE_INLINE bool equals(const char* const &lhs, const char *const &rhs)
{
	return strcmp(lhs, rhs) == 0;
}

#endif // _JBL_LIB_H_
<commit_msg>remove type traits header. MacOS using libstdc++ doesn't have it as its C++98<commit_after>//------------------------------------------------------------------------------
// lib.hpp
//
// Copyright (c) 2016-2017 Jeff Hutchinson
//
// 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.
//-----------------------------------------------------------------------------

#ifndef _JBL_LIB_HPP_
#define _JBL_LIB_HPP_

#include <string.h>
#include "compiler.hpp"
#include "types.hpp"

template<typename T>
FORCE_INLINE T&& move_cast(T &ref)
{
	return static_cast<T&&>(ref);
}

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

template<typename T>
FORCE_INLINE T min(T a, T b)
{
	return (a < b) ? a : b;
}

// Equals override.
template<typename T> FORCE_INLINE bool equals(const T &lhs, const T &rhs);

template<typename T>
FORCE_INLINE bool equals(const T &lhs, const T &rhs)
{
	return lhs == rhs;
}

template<>
FORCE_INLINE bool equals(const char* const &lhs, const char *const &rhs)
{
	return strcmp(lhs, rhs) == 0;
}

#endif // _JBL_LIB_H_
<|endoftext|>


<commit_before>/*   www.nalug.net
 *   www.linuxdaynapoli.org
 *   www.gbr1technologies.altervista.org
 *
 *	 Open Data Day Napoli 2015
 *
 *   Giovanni di Dio Bruno ;)
 *
 *
 */

#include "mbed.h"
#include "EthernetInterface.h"
#include "TMP102.h"
#include <string>
#include <cstring>
#include "TextLCD.h"

TextLCD lcd(p15, p16, p21, p22, p23, p24); // rs, e, d4-d7

float LAT= 40.86;
float LONG=14.17;
float ALT=100;

TMP102 temperature(p9,p10, 0x90);
DigitalOut l1(LED1);
DigitalOut l2(LED2);
DigitalOut l3(LED3);
DigitalOut l4(LED4);

float temp=0;
char command[1024];
char s[1024];
char wk[5];

string id = "***************";  //username:password  with base64

TCPSocketConnection sock;

void send_temp(void const *args) {
    while (true) {
        l3=1;
        sock.connect("openweathermap.org",80);
        printf("socket connesso\r\n");
        int len=0;
        len=sprintf(s,"temp=%f&lat=%2f&long=%f&alt=%f",temp,LAT,LONG,ALT);
        printf("%s",s);
        sprintf(wk,"%d",len);
        string http_cmd = "POST /data/post HTTP/1.1\r\nAuthorization: Basic "+id+"\r\nHost: openweathermap.org\r\nAccept: */*\r\nContent-Length: "+string(wk)+"\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"+string(s);
        int n = sprintf(command,http_cmd.c_str());
        printf("%s",command);
        printf("\r\n%d\r\n",n);
        sock.send_all(command, n);
        sock.receive(command,1024);
        l3=0;
        printf("\r\n\r\n%s\r\n\r\n",command);
        wait(19.9);
        sock.close();
        Thread::wait(20000);

    }
}

void update_screen(void const *args) {
    while (true) {
        l2=1;
        temp=temperature.read();
        printf("temp: %f\r\n",temp);
        wait(0.1);
        l2=0;
        lcd.cls();
        lcd.printf("%3.3f C\nNalug Weather",temp);
        Thread::wait(5000);
    }
}

int main() {
    l1=0;
    l2=0;
    l3=0;
    l4=0;
    l1=1;
    lcd.printf("Open Data Day 15Nalug Weather");
    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    printf("IP Address is %s\r\n", eth.getIPAddress());
    l1=0;
    l4=1;

    Thread thread(send_temp);
    Thread thread2(update_screen);

    while(1){
    }
    eth.disconnect();
}
<commit_msg>comments added in main.cpp<commit_after>/*   www.nalug.net
 *   www.linuxdaynapoli.org
 *   www.gbr1technologies.altervista.org
 *
 *	 Open Data Day Napoli 2015
 *
 *   Giovanni di Dio Bruno ;)
 *
 *
 */

#include "mbed.h"
#include "EthernetInterface.h"
#include "TMP102.h"
#include <string>
#include <cstring>
#include "TextLCD.h"

//lcd pinout
TextLCD lcd(p15, p16, p21, p22, p23, p24); // rs, e, d4-d7

//your latitude, longitude and altitude
float LAT= 40.86;
float LONG=14.17;
float ALT=100;

//cheap but powerfull temperature sensor
TMP102 temperature(p9,p10, 0x90);

DigitalOut l1(LED1); //ip OK
DigitalOut l2(LED2); //temp read
DigitalOut l3(LED3); //openweathermap connction
DigitalOut l4(LED4); //working

float temp=0;        //temperature
char command[1024];  //string for http post
char s[1024];
char wk[5];

string id = "***************";  //username:password  with base64

TCPSocketConnection sock;

//thread to send temperature to openweathermap.org  -> every 20s
void send_temp(void const *args) {
    while (true) {
        l3=1;  //active led 3
        sock.connect("openweathermap.org",80);    //open socket connection
        printf("socket connesso\r\n");
        int len=0;
        len=sprintf(s,"temp=%f&lat=%2f&long=%f&alt=%f",temp,LAT,LONG,ALT);   //create data to send to server and his length
        printf("%s",s);
        sprintf(wk,"%d",len);    //convert int to char[]
        //complete command to do http post to openweathermap.org server
        string http_cmd = "POST /data/post HTTP/1.1\r\nAuthorization: Basic "+id+"\r\nHost: openweathermap.org\r\nAccept: */*\r\nContent-Length: "+string(wk)+"\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"+string(s);
        int n = sprintf(command,http_cmd.c_str());  //string to char[] and its length
        printf("%s",command);
        printf("\r\n%d\r\n",n);
        //send
        sock.send_all(command, n);
        //receive response from openweeathermap server
        sock.receive(command,1024);
        l3=0;
        printf("\r\n\r\n%s\r\n\r\n",command);
        //close socket
        sock.close();
        //thread every 20s
        Thread::wait(20000);

    }
}

//thread for updating screen
void update_screen(void const *args) {
    while (true) {
        l2=1;      //update temperature
        temp=temperature.read();
        printf("temp: %f\r\n",temp);
        wait(0.1);
        l2=0;
        //lcd print
        lcd.cls();
        lcd.printf("%3.3f C\nNalug Weather",temp);
        //thread every 5s
        Thread::wait(5000);
    }
}

int main() {
    //init leds
    l1=0;
    l2=0;
    l3=0;
    l4=0;

    //getting ip and ethernet connection
    l1=1;
    lcd.printf("Open Data Day 15Nalug Weather");
    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    printf("IP Address is %s\r\n", eth.getIPAddress());
    l1=0;
    l4=1;

    //starting threads
    Thread thread(send_temp);
    Thread thread2(update_screen);

    while(1){
    }

    //close ethernet
    eth.disconnect();
}
<|endoftext|>