<commit_before>// Copyright (c) 2011 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 "webkit/plugins/ppapi/ppb_url_request_info_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "googleurl/src/url_util.h"
#include "net/http/http_util.h"
#include "ppapi/c/pp_var.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_file_ref_api.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebHTTPBody.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_file_ref_impl.h"
#include "webkit/plugins/ppapi/ppb_file_system_impl.h"
#include "webkit/plugins/ppapi/resource_helper.h"
#include "webkit/plugins/ppapi/string.h"

using ppapi::StringVar;
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_FileRef_API;
using ppapi::thunk::PPB_URLRequestInfo_API;
using WebKit::WebData;
using WebKit::WebHTTPBody;
using WebKit::WebString;
using WebKit::WebFrame;
using WebKit::WebURL;
using WebKit::WebURLRequest;

namespace webkit {
namespace ppapi {

namespace {

const int32_t kDefaultPrefetchBufferUpperThreshold = 100 * 1000 * 1000;
const int32_t kDefaultPrefetchBufferLowerThreshold = 50 * 1000 * 1000;

bool IsValidToken(const std::string& token) {
  size_t length = token.size();
  if (length == 0)
    return false;

  for (size_t i = 0; i < length; i++) {
    char c = token[i];
    if (c >= 127 || c <= 32)
      return false;
    if (c == '(' || c == ')' || c == '<' || c == '>' || c == '@' ||
        c == ',' || c == ';' || c == ':' || c == '\\' || c == '\"' ||
        c == '/' || c == '[' || c == ']' || c == '?' || c == '=' ||
        c == '{' || c == '}')
      return false;
  }
  return true;
}

// These methods are not allowed by the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-open-method
const char* const kForbiddenHttpMethods[] = {
  "connect",
  "trace",
  "track",
};

// These are the "known" methods in the Webkit XHR implementation. Also see
// the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-open-method
const char* const kKnownHttpMethods[] = {
  "get",
  "post",
  "put",
  "head",
  "copy",
  "delete",
  "index",
  "lock",
  "m-post",
  "mkcol",
  "move",
  "options",
  "propfind",
  "proppatch",
  "unlock",
};

std::string ValidateMethod(const std::string& method) {
  for (size_t i = 0; i < arraysize(kForbiddenHttpMethods); ++i) {
    if (LowerCaseEqualsASCII(method, kForbiddenHttpMethods[i]))
      return std::string();
  }
  for (size_t i = 0; i < arraysize(kKnownHttpMethods); ++i) {
    if (LowerCaseEqualsASCII(method, kKnownHttpMethods[i])) {
      // Convert the method name to upper case to match Webkit and Firefox's
      // XHR implementation.
      return StringToUpperASCII(std::string(kKnownHttpMethods[i]));
    }
  }
  // Pass through unknown methods that are not forbidden.
  return method;
}

// A header string containing any of the following fields will cause
// an error. The list comes from the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method
const char* const kForbiddenHeaderFields[] = {
  "accept-charset",
  "accept-encoding",
  "connection",
  "content-length",
  "cookie",
  "cookie2",
  "content-transfer-encoding",
  "date",
  "expect",
  "host",
  "keep-alive",
  "origin",
  "referer",
  "te",
  "trailer",
  "transfer-encoding",
  "upgrade",
  "user-agent",
  "via",
};

bool IsValidHeaderField(const std::string& name) {
  for (size_t i = 0; i < arraysize(kForbiddenHeaderFields); ++i) {
    if (LowerCaseEqualsASCII(name, kForbiddenHeaderFields[i]))
      return false;
  }
  if (StartsWithASCII(name, "proxy-", false))
    return false;
  if (StartsWithASCII(name, "sec-", false))
    return false;

  return true;
}

bool AreValidHeaders(const std::string& headers) {
  net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n");
  while (it.GetNext()) {
    if (!IsValidHeaderField(it.name()))
      return false;
  }
  return true;
}

}  // namespace

struct PPB_URLRequestInfo_Impl::BodyItem {
  explicit BodyItem(const std::string& data)
      : data(data),
        start_offset(0),
        number_of_bytes(-1),
        expected_last_modified_time(0.0) {
  }

  BodyItem(PPB_FileRef_Impl* file_ref,
           int64_t start_offset,
           int64_t number_of_bytes,
           PP_Time expected_last_modified_time)
      : file_ref(file_ref),
        start_offset(start_offset),
        number_of_bytes(number_of_bytes),
        expected_last_modified_time(expected_last_modified_time) {
  }

  std::string data;
  scoped_refptr<PPB_FileRef_Impl> file_ref;
  int64_t start_offset;
  int64_t number_of_bytes;
  PP_Time expected_last_modified_time;
};

PPB_URLRequestInfo_Impl::PPB_URLRequestInfo_Impl(PP_Instance instance)
    : Resource(instance),
      stream_to_file_(false),
      follow_redirects_(true),
      record_download_progress_(false),
      record_upload_progress_(false),
      has_custom_referrer_url_(false),
      allow_cross_origin_requests_(false),
      allow_credentials_(false),
      has_custom_content_transfer_encoding_(false),
      prefetch_buffer_upper_threshold_(kDefaultPrefetchBufferUpperThreshold),
      prefetch_buffer_lower_threshold_(kDefaultPrefetchBufferLowerThreshold) {
}

PPB_URLRequestInfo_Impl::~PPB_URLRequestInfo_Impl() {
}

PPB_URLRequestInfo_API* PPB_URLRequestInfo_Impl::AsPPB_URLRequestInfo_API() {
  return this;
}

PP_Bool PPB_URLRequestInfo_Impl::SetProperty(PP_URLRequestProperty property,
                                             PP_Var var) {
  PP_Bool result = PP_FALSE;
  switch (var.type) {
    case PP_VARTYPE_UNDEFINED:
      result = PP_FromBool(SetUndefinedProperty(property));
      break;
    case PP_VARTYPE_BOOL:
      result = PP_FromBool(
          SetBooleanProperty(property, PP_ToBool(var.value.as_bool)));
      break;
    case PP_VARTYPE_INT32:
      result = PP_FromBool(
          SetIntegerProperty(property, var.value.as_int));
      break;
    case PP_VARTYPE_STRING: {
      StringVar* string = StringVar::FromPPVar(var);
      if (string)
        result = PP_FromBool(SetStringProperty(property, string->value()));
      break;
    }
    default:
      break;
  }
  return result;
}

PP_Bool PPB_URLRequestInfo_Impl::AppendDataToBody(const void* data,
                                                  uint32_t len) {
  if (len > 0)
    body_.push_back(BodyItem(std::string(static_cast<const char*>(data), len)));
  return PP_TRUE;
}

PP_Bool PPB_URLRequestInfo_Impl::AppendFileToBody(
    PP_Resource file_ref,
    int64_t start_offset,
    int64_t number_of_bytes,
    PP_Time expected_last_modified_time) {
  // Ignore a call to append nothing.
  if (number_of_bytes == 0)
    return PP_TRUE;

  // Check for bad values.  (-1 means read until end of file.)
  if (start_offset < 0 || number_of_bytes < -1)
    return PP_FALSE;

  EnterResourceNoLock<PPB_FileRef_API> enter(file_ref, true);
  if (enter.failed())
    return PP_FALSE;

  body_.push_back(BodyItem(static_cast<PPB_FileRef_Impl*>(enter.object()),
                           start_offset,
                           number_of_bytes,
                           expected_last_modified_time));
  return PP_TRUE;
}

WebURLRequest PPB_URLRequestInfo_Impl::ToWebURLRequest(WebFrame* frame) const {
  WebURLRequest web_request;
  web_request.initialize();
  web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_)));
  web_request.setDownloadToFile(stream_to_file_);
  web_request.setReportUploadProgress(record_upload_progress());

  if (!method_.empty())
    web_request.setHTTPMethod(WebString::fromUTF8(method_));

  web_request.setFirstPartyForCookies(
      frame->document().firstPartyForCookies());

  if (!headers_.empty()) {
    net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), "\n");
    while (it.GetNext()) {
      web_request.addHTTPHeaderField(
          WebString::fromUTF8(it.name()),
          WebString::fromUTF8(it.values()));
    }
  }

  if (!body_.empty()) {
    WebHTTPBody http_body;
    http_body.initialize();
    for (size_t i = 0; i < body_.size(); ++i) {
      if (body_[i].file_ref) {
        FilePath platform_path;
        switch (body_[i].file_ref->file_system()->type()) {
          case PP_FILESYSTEMTYPE_LOCALTEMPORARY:
          case PP_FILESYSTEMTYPE_LOCALPERSISTENT: {
            // TODO(kinuko): remove this sync IPC when we add more generic
            // AppendURLRange solution that works for both Blob/FileSystem URL.
            PluginDelegate* plugin_delegate =
                ResourceHelper::GetPluginDelegate(this);
            if (plugin_delegate) {
              plugin_delegate->SyncGetFileSystemPlatformPath(
                    body_[i].file_ref->GetFileSystemURL(), &platform_path);
            }
            break;
          }
          case PP_FILESYSTEMTYPE_EXTERNAL:
            platform_path = body_[i].file_ref->GetSystemPath();
            break;
          default:
            NOTREACHED();
        }
        http_body.appendFileRange(
            webkit_glue::FilePathToWebString(platform_path),
            body_[i].start_offset,
            body_[i].number_of_bytes,
            body_[i].expected_last_modified_time);
      } else {
        DCHECK(!body_[i].data.empty());
        http_body.appendData(WebData(body_[i].data));
      }
    }
    web_request.setHTTPBody(http_body);
  }

  if (has_custom_referrer_url_) {
    if (!custom_referrer_url_.empty())
      frame->setReferrerForRequest(web_request, GURL(custom_referrer_url_));
  } else if (!allow_cross_origin_requests_) {
    // Use default, except for cross-origin requests, since 'referer' is not
    // whitelisted and will cause the request to fail.
    frame->setReferrerForRequest(web_request, WebURL());
  }

  if (has_custom_content_transfer_encoding_) {
    if (!custom_content_transfer_encoding_.empty()) {
      web_request.addHTTPHeaderField(
          WebString::fromUTF8("Content-Transfer-Encoding"),
          WebString::fromUTF8(custom_content_transfer_encoding_));
    }
  }

  return web_request;
}

bool PPB_URLRequestInfo_Impl::RequiresUniversalAccess() const {
  return
      has_custom_referrer_url_ ||
      has_custom_content_transfer_encoding_ ||
      url_util::FindAndCompareScheme(url_, "javascript", NULL);
}

bool PPB_URLRequestInfo_Impl::SetUndefinedProperty(
    PP_URLRequestProperty property) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL:
      has_custom_referrer_url_ = false;
      custom_referrer_url_ = std::string();
      return true;
    case PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING:
      has_custom_content_transfer_encoding_ = false;
      custom_content_transfer_encoding_ = std::string();
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetBooleanProperty(PP_URLRequestProperty property,
                                                 bool value) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_STREAMTOFILE:
      stream_to_file_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS:
      follow_redirects_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS:
      record_download_progress_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS:
      record_upload_progress_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_ALLOWCROSSORIGINREQUESTS:
      allow_cross_origin_requests_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_ALLOWCREDENTIALS:
      allow_credentials_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetIntegerProperty(PP_URLRequestProperty property,
                                                 int32_t value) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD:
      prefetch_buffer_upper_threshold_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD:
      prefetch_buffer_lower_threshold_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetStringProperty(PP_URLRequestProperty property,
                                                const std::string& value) {
  // TODO(darin): Validate input.  Perhaps at a different layer?
  switch (property) {
    case PP_URLREQUESTPROPERTY_URL:
      url_ = value;  // NOTE: This may be a relative URL.
      return true;
    case PP_URLREQUESTPROPERTY_METHOD:
      if (!IsValidToken(value))
        return false;
      method_ = ValidateMethod(value);
      return !method_.empty();
    case PP_URLREQUESTPROPERTY_HEADERS:
      if (!AreValidHeaders(value))
        return false;
      headers_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL:
      has_custom_referrer_url_ = true;
      custom_referrer_url_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING:
      has_custom_content_transfer_encoding_ = true;
      custom_content_transfer_encoding_ = value;
      return true;
    default:
      return false;
  }
}

}  // namespace ppapi
}  // namespace webkit
<commit_msg>Fix crash in PPB_URLRequestInfo::ToWebURLRequest<commit_after>// Copyright (c) 2011 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 "webkit/plugins/ppapi/ppb_url_request_info_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "googleurl/src/url_util.h"
#include "net/http/http_util.h"
#include "ppapi/c/pp_var.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_file_ref_api.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebHTTPBody.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_file_ref_impl.h"
#include "webkit/plugins/ppapi/ppb_file_system_impl.h"
#include "webkit/plugins/ppapi/resource_helper.h"
#include "webkit/plugins/ppapi/string.h"

using ppapi::StringVar;
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_FileRef_API;
using ppapi::thunk::PPB_URLRequestInfo_API;
using WebKit::WebData;
using WebKit::WebHTTPBody;
using WebKit::WebString;
using WebKit::WebFrame;
using WebKit::WebURL;
using WebKit::WebURLRequest;

namespace webkit {
namespace ppapi {

namespace {

const int32_t kDefaultPrefetchBufferUpperThreshold = 100 * 1000 * 1000;
const int32_t kDefaultPrefetchBufferLowerThreshold = 50 * 1000 * 1000;

bool IsValidToken(const std::string& token) {
  size_t length = token.size();
  if (length == 0)
    return false;

  for (size_t i = 0; i < length; i++) {
    char c = token[i];
    if (c >= 127 || c <= 32)
      return false;
    if (c == '(' || c == ')' || c == '<' || c == '>' || c == '@' ||
        c == ',' || c == ';' || c == ':' || c == '\\' || c == '\"' ||
        c == '/' || c == '[' || c == ']' || c == '?' || c == '=' ||
        c == '{' || c == '}')
      return false;
  }
  return true;
}

// These methods are not allowed by the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-open-method
const char* const kForbiddenHttpMethods[] = {
  "connect",
  "trace",
  "track",
};

// These are the "known" methods in the Webkit XHR implementation. Also see
// the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-open-method
const char* const kKnownHttpMethods[] = {
  "get",
  "post",
  "put",
  "head",
  "copy",
  "delete",
  "index",
  "lock",
  "m-post",
  "mkcol",
  "move",
  "options",
  "propfind",
  "proppatch",
  "unlock",
};

std::string ValidateMethod(const std::string& method) {
  for (size_t i = 0; i < arraysize(kForbiddenHttpMethods); ++i) {
    if (LowerCaseEqualsASCII(method, kForbiddenHttpMethods[i]))
      return std::string();
  }
  for (size_t i = 0; i < arraysize(kKnownHttpMethods); ++i) {
    if (LowerCaseEqualsASCII(method, kKnownHttpMethods[i])) {
      // Convert the method name to upper case to match Webkit and Firefox's
      // XHR implementation.
      return StringToUpperASCII(std::string(kKnownHttpMethods[i]));
    }
  }
  // Pass through unknown methods that are not forbidden.
  return method;
}

// A header string containing any of the following fields will cause
// an error. The list comes from the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method
const char* const kForbiddenHeaderFields[] = {
  "accept-charset",
  "accept-encoding",
  "connection",
  "content-length",
  "cookie",
  "cookie2",
  "content-transfer-encoding",
  "date",
  "expect",
  "host",
  "keep-alive",
  "origin",
  "referer",
  "te",
  "trailer",
  "transfer-encoding",
  "upgrade",
  "user-agent",
  "via",
};

bool IsValidHeaderField(const std::string& name) {
  for (size_t i = 0; i < arraysize(kForbiddenHeaderFields); ++i) {
    if (LowerCaseEqualsASCII(name, kForbiddenHeaderFields[i]))
      return false;
  }
  if (StartsWithASCII(name, "proxy-", false))
    return false;
  if (StartsWithASCII(name, "sec-", false))
    return false;

  return true;
}

bool AreValidHeaders(const std::string& headers) {
  net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n");
  while (it.GetNext()) {
    if (!IsValidHeaderField(it.name()))
      return false;
  }
  return true;
}

}  // namespace

struct PPB_URLRequestInfo_Impl::BodyItem {
  explicit BodyItem(const std::string& data)
      : data(data),
        start_offset(0),
        number_of_bytes(-1),
        expected_last_modified_time(0.0) {
  }

  BodyItem(PPB_FileRef_Impl* file_ref,
           int64_t start_offset,
           int64_t number_of_bytes,
           PP_Time expected_last_modified_time)
      : file_ref(file_ref),
        start_offset(start_offset),
        number_of_bytes(number_of_bytes),
        expected_last_modified_time(expected_last_modified_time) {
  }

  std::string data;
  scoped_refptr<PPB_FileRef_Impl> file_ref;
  int64_t start_offset;
  int64_t number_of_bytes;
  PP_Time expected_last_modified_time;
};

PPB_URLRequestInfo_Impl::PPB_URLRequestInfo_Impl(PP_Instance instance)
    : Resource(instance),
      stream_to_file_(false),
      follow_redirects_(true),
      record_download_progress_(false),
      record_upload_progress_(false),
      has_custom_referrer_url_(false),
      allow_cross_origin_requests_(false),
      allow_credentials_(false),
      has_custom_content_transfer_encoding_(false),
      prefetch_buffer_upper_threshold_(kDefaultPrefetchBufferUpperThreshold),
      prefetch_buffer_lower_threshold_(kDefaultPrefetchBufferLowerThreshold) {
}

PPB_URLRequestInfo_Impl::~PPB_URLRequestInfo_Impl() {
}

PPB_URLRequestInfo_API* PPB_URLRequestInfo_Impl::AsPPB_URLRequestInfo_API() {
  return this;
}

PP_Bool PPB_URLRequestInfo_Impl::SetProperty(PP_URLRequestProperty property,
                                             PP_Var var) {
  PP_Bool result = PP_FALSE;
  switch (var.type) {
    case PP_VARTYPE_UNDEFINED:
      result = PP_FromBool(SetUndefinedProperty(property));
      break;
    case PP_VARTYPE_BOOL:
      result = PP_FromBool(
          SetBooleanProperty(property, PP_ToBool(var.value.as_bool)));
      break;
    case PP_VARTYPE_INT32:
      result = PP_FromBool(
          SetIntegerProperty(property, var.value.as_int));
      break;
    case PP_VARTYPE_STRING: {
      StringVar* string = StringVar::FromPPVar(var);
      if (string)
        result = PP_FromBool(SetStringProperty(property, string->value()));
      break;
    }
    default:
      break;
  }
  return result;
}

PP_Bool PPB_URLRequestInfo_Impl::AppendDataToBody(const void* data,
                                                  uint32_t len) {
  if (len > 0)
    body_.push_back(BodyItem(std::string(static_cast<const char*>(data), len)));
  return PP_TRUE;
}

PP_Bool PPB_URLRequestInfo_Impl::AppendFileToBody(
    PP_Resource file_ref,
    int64_t start_offset,
    int64_t number_of_bytes,
    PP_Time expected_last_modified_time) {
  // Ignore a call to append nothing.
  if (number_of_bytes == 0)
    return PP_TRUE;

  // Check for bad values.  (-1 means read until end of file.)
  if (start_offset < 0 || number_of_bytes < -1)
    return PP_FALSE;

  EnterResourceNoLock<PPB_FileRef_API> enter(file_ref, true);
  if (enter.failed())
    return PP_FALSE;

  body_.push_back(BodyItem(static_cast<PPB_FileRef_Impl*>(enter.object()),
                           start_offset,
                           number_of_bytes,
                           expected_last_modified_time));
  return PP_TRUE;
}

WebURLRequest PPB_URLRequestInfo_Impl::ToWebURLRequest(WebFrame* frame) const {
  WebURLRequest web_request;
  web_request.initialize();
  web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_)));
  web_request.setDownloadToFile(stream_to_file_);
  web_request.setReportUploadProgress(record_upload_progress());

  if (!method_.empty())
    web_request.setHTTPMethod(WebString::fromUTF8(method_));

  web_request.setFirstPartyForCookies(
      frame->document().firstPartyForCookies());

  if (!headers_.empty()) {
    net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), "\n");
    while (it.GetNext()) {
      web_request.addHTTPHeaderField(
          WebString::fromUTF8(it.name()),
          WebString::fromUTF8(it.values()));
    }
  }

  if (!body_.empty()) {
    WebHTTPBody http_body;
    http_body.initialize();
    for (size_t i = 0; i < body_.size(); ++i) {
      if (body_[i].file_ref) {
        FilePath platform_path;
        switch (body_[i].file_ref->GetFileSystemType()) {
          case PP_FILESYSTEMTYPE_LOCALTEMPORARY:
          case PP_FILESYSTEMTYPE_LOCALPERSISTENT: {
            // TODO(kinuko): remove this sync IPC when we add more generic
            // AppendURLRange solution that works for both Blob/FileSystem URL.
            PluginDelegate* plugin_delegate =
                ResourceHelper::GetPluginDelegate(this);
            if (plugin_delegate) {
              plugin_delegate->SyncGetFileSystemPlatformPath(
                    body_[i].file_ref->GetFileSystemURL(), &platform_path);
            }
            break;
          }
          case PP_FILESYSTEMTYPE_EXTERNAL:
            platform_path = body_[i].file_ref->GetSystemPath();
            break;
          default:
            NOTREACHED();
        }
        http_body.appendFileRange(
            webkit_glue::FilePathToWebString(platform_path),
            body_[i].start_offset,
            body_[i].number_of_bytes,
            body_[i].expected_last_modified_time);
      } else {
        DCHECK(!body_[i].data.empty());
        http_body.appendData(WebData(body_[i].data));
      }
    }
    web_request.setHTTPBody(http_body);
  }

  if (has_custom_referrer_url_) {
    if (!custom_referrer_url_.empty())
      frame->setReferrerForRequest(web_request, GURL(custom_referrer_url_));
  } else if (!allow_cross_origin_requests_) {
    // Use default, except for cross-origin requests, since 'referer' is not
    // whitelisted and will cause the request to fail.
    frame->setReferrerForRequest(web_request, WebURL());
  }

  if (has_custom_content_transfer_encoding_) {
    if (!custom_content_transfer_encoding_.empty()) {
      web_request.addHTTPHeaderField(
          WebString::fromUTF8("Content-Transfer-Encoding"),
          WebString::fromUTF8(custom_content_transfer_encoding_));
    }
  }

  return web_request;
}

bool PPB_URLRequestInfo_Impl::RequiresUniversalAccess() const {
  return
      has_custom_referrer_url_ ||
      has_custom_content_transfer_encoding_ ||
      url_util::FindAndCompareScheme(url_, "javascript", NULL);
}

bool PPB_URLRequestInfo_Impl::SetUndefinedProperty(
    PP_URLRequestProperty property) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL:
      has_custom_referrer_url_ = false;
      custom_referrer_url_ = std::string();
      return true;
    case PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING:
      has_custom_content_transfer_encoding_ = false;
      custom_content_transfer_encoding_ = std::string();
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetBooleanProperty(PP_URLRequestProperty property,
                                                 bool value) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_STREAMTOFILE:
      stream_to_file_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS:
      follow_redirects_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS:
      record_download_progress_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS:
      record_upload_progress_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_ALLOWCROSSORIGINREQUESTS:
      allow_cross_origin_requests_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_ALLOWCREDENTIALS:
      allow_credentials_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetIntegerProperty(PP_URLRequestProperty property,
                                                 int32_t value) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD:
      prefetch_buffer_upper_threshold_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD:
      prefetch_buffer_lower_threshold_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetStringProperty(PP_URLRequestProperty property,
                                                const std::string& value) {
  // TODO(darin): Validate input.  Perhaps at a different layer?
  switch (property) {
    case PP_URLREQUESTPROPERTY_URL:
      url_ = value;  // NOTE: This may be a relative URL.
      return true;
    case PP_URLREQUESTPROPERTY_METHOD:
      if (!IsValidToken(value))
        return false;
      method_ = ValidateMethod(value);
      return !method_.empty();
    case PP_URLREQUESTPROPERTY_HEADERS:
      if (!AreValidHeaders(value))
        return false;
      headers_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL:
      has_custom_referrer_url_ = true;
      custom_referrer_url_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING:
      has_custom_content_transfer_encoding_ = true;
      custom_content_transfer_encoding_ = value;
      return true;
    default:
      return false;
  }
}

}  // namespace ppapi
}  // namespace webkit
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "webkit/tools/test_shell/mock_webclipboard_impl.h"

#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "net/base/escape.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCommon.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebImage.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "webkit/glue/webclipboard_impl.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/support/webkit_support_gfx.h"

#if WEBKIT_USING_CG
#include <ApplicationServices/ApplicationServices.h>
#include <CoreFoundation/CoreFoundation.h>
#endif

using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebVector;

MockWebClipboardImpl::MockWebClipboardImpl() {
}

MockWebClipboardImpl::~MockWebClipboardImpl() {
}

bool MockWebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) {
  switch (format) {
    case FormatPlainText:
      return !m_plainText.isEmpty();

    case FormatHTML:
      return !m_htmlText.isEmpty();

    case FormatSmartPaste:
      return m_writeSmartPaste;

    default:
      NOTREACHED();
      return false;
  }

  switch (buffer) {
    case BufferStandard:
      break;
    case BufferSelection:
#if defined(OS_POSIX) && !defined(OS_MACOSX)
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }

  return true;
}

WebKit::WebString MockWebClipboardImpl::readPlainText(
    WebKit::WebClipboard::Buffer buffer) {
  return m_plainText;
}

// TODO(wtc): set output argument *url.
WebKit::WebString MockWebClipboardImpl::readHTML(
    WebKit::WebClipboard::Buffer buffer, WebKit::WebURL* url) {
  return m_htmlText;
}

WebKit::WebData MockWebClipboardImpl::readImage(
    WebKit::WebClipboard::Buffer buffer) {
  std::string data;
  std::vector<unsigned char> encoded_image;
  // TODO(dcheng): Verify that we can assume the image is ARGB8888. Note that
  // for endianess reasons, it will be BGRA8888 on Windows.
#if WEBKIT_USING_SKIA
  const SkBitmap& bitmap = m_image.getSkBitmap();
  SkAutoLockPixels lock(bitmap);
  webkit_support::EncodeBGRAPNG(static_cast<unsigned char*>(bitmap.getPixels()),
                                bitmap.width(),
                                bitmap.height(),
                                bitmap.rowBytes(),
                                false,
                                &encoded_image);
#elif WEBKIT_USING_CG
  CGImageRef image = m_image.getCGImageRef();
  CFDataRef image_data_ref =
      CGDataProviderCopyData(CGImageGetDataProvider(image));
  webkit_support::EncodeRGBAPNG(CFDataGetBytePtr(image_data_ref),
                                CGImageGetWidth(image),
                                CGImageGetHeight(image),
                                CGImageGetBytesPerRow(image),
                                &encoded_image);
  CFRelease(image_data_ref);
#endif
  data.assign(reinterpret_cast<char*>(vector_as_array(&encoded_image)),
              encoded_image.size());
  return data;
}

void MockWebClipboardImpl::writeHTML(
    const WebKit::WebString& htmlText, const WebKit::WebURL& url,
    const WebKit::WebString& plainText, bool writeSmartPaste) {
  m_htmlText = htmlText;
  m_plainText = plainText;
  m_image.reset();
  m_writeSmartPaste = writeSmartPaste;
}

void MockWebClipboardImpl::writePlainText(const WebKit::WebString& plain_text) {
  m_htmlText = WebKit::WebString();
  m_plainText = plain_text;
  m_image.reset();
  m_writeSmartPaste = false;
}

void MockWebClipboardImpl::writeURL(
    const WebKit::WebURL& url, const WebKit::WebString& title) {
  m_htmlText = WebString::fromUTF8(
      webkit_glue::WebClipboardImpl::URLToMarkup(url, title));
  m_plainText = url.spec().utf16();
  m_image.reset();
  m_writeSmartPaste = false;
}

void MockWebClipboardImpl::writeImage(const WebKit::WebImage& image,
    const WebKit::WebURL& url, const WebKit::WebString& title) {
  if (!image.isNull()) {
    m_htmlText = WebString::fromUTF8(
        webkit_glue::WebClipboardImpl::URLToImageMarkup(url, title));
    m_plainText = m_htmlText;
    m_image = image;
    m_writeSmartPaste = false;
  }
}

WebVector<WebString> MockWebClipboardImpl::readAvailableTypes(
    Buffer buffer, bool* containsFilenames) {
  *containsFilenames = false;
  std::vector<WebString> results;
  if (!m_plainText.isEmpty()) {
    results.push_back(WebString("text/plain"));
  }
  if (!m_htmlText.isEmpty()) {
    results.push_back(WebString("text/html"));
  }
  if (!m_image.isNull()) {
    results.push_back(WebString("image/png"));
  }
  return results;
}
<commit_msg>Fix endianness issue in MockWebClipboardImpl PNG encoding.<commit_after>// Copyright (c) 2011 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 "webkit/tools/test_shell/mock_webclipboard_impl.h"

#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "net/base/escape.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCommon.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebImage.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "webkit/glue/webclipboard_impl.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/support/webkit_support_gfx.h"

#if WEBKIT_USING_CG
#include <ApplicationServices/ApplicationServices.h>
#include <CoreFoundation/CoreFoundation.h>
#endif

using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebVector;

MockWebClipboardImpl::MockWebClipboardImpl() {
}

MockWebClipboardImpl::~MockWebClipboardImpl() {
}

bool MockWebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) {
  switch (format) {
    case FormatPlainText:
      return !m_plainText.isEmpty();

    case FormatHTML:
      return !m_htmlText.isEmpty();

    case FormatSmartPaste:
      return m_writeSmartPaste;

    default:
      NOTREACHED();
      return false;
  }

  switch (buffer) {
    case BufferStandard:
      break;
    case BufferSelection:
#if defined(OS_POSIX) && !defined(OS_MACOSX)
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }

  return true;
}

WebKit::WebString MockWebClipboardImpl::readPlainText(
    WebKit::WebClipboard::Buffer buffer) {
  return m_plainText;
}

// TODO(wtc): set output argument *url.
WebKit::WebString MockWebClipboardImpl::readHTML(
    WebKit::WebClipboard::Buffer buffer, WebKit::WebURL* url) {
  return m_htmlText;
}

WebKit::WebData MockWebClipboardImpl::readImage(
    WebKit::WebClipboard::Buffer buffer) {
  std::string data;
  std::vector<unsigned char> encoded_image;
  // TODO(dcheng): Verify that we can assume the image is ARGB8888. Note that
  // for endianess reasons, it will be BGRA8888 on Windows.
#if WEBKIT_USING_SKIA
  const SkBitmap& bitmap = m_image.getSkBitmap();
  SkAutoLockPixels lock(bitmap);
  webkit_support::EncodeBGRAPNG(static_cast<unsigned char*>(bitmap.getPixels()),
                                bitmap.width(),
                                bitmap.height(),
                                bitmap.rowBytes(),
                                false,
                                &encoded_image);
#elif WEBKIT_USING_CG
  CGImageRef image = m_image.getCGImageRef();
  CFDataRef image_data_ref =
      CGDataProviderCopyData(CGImageGetDataProvider(image));
  webkit_support::EncodeBGRAPNG(CFDataGetBytePtr(image_data_ref),
                                CGImageGetWidth(image),
                                CGImageGetHeight(image),
                                CGImageGetBytesPerRow(image),
                                false,
                                &encoded_image);
  CFRelease(image_data_ref);
#endif
  data.assign(reinterpret_cast<char*>(vector_as_array(&encoded_image)),
              encoded_image.size());
  return data;
}

void MockWebClipboardImpl::writeHTML(
    const WebKit::WebString& htmlText, const WebKit::WebURL& url,
    const WebKit::WebString& plainText, bool writeSmartPaste) {
  m_htmlText = htmlText;
  m_plainText = plainText;
  m_image.reset();
  m_writeSmartPaste = writeSmartPaste;
}

void MockWebClipboardImpl::writePlainText(const WebKit::WebString& plain_text) {
  m_htmlText = WebKit::WebString();
  m_plainText = plain_text;
  m_image.reset();
  m_writeSmartPaste = false;
}

void MockWebClipboardImpl::writeURL(
    const WebKit::WebURL& url, const WebKit::WebString& title) {
  m_htmlText = WebString::fromUTF8(
      webkit_glue::WebClipboardImpl::URLToMarkup(url, title));
  m_plainText = url.spec().utf16();
  m_image.reset();
  m_writeSmartPaste = false;
}

void MockWebClipboardImpl::writeImage(const WebKit::WebImage& image,
    const WebKit::WebURL& url, const WebKit::WebString& title) {
  if (!image.isNull()) {
    m_htmlText = WebString::fromUTF8(
        webkit_glue::WebClipboardImpl::URLToImageMarkup(url, title));
    m_plainText = m_htmlText;
    m_image = image;
    m_writeSmartPaste = false;
  }
}

WebVector<WebString> MockWebClipboardImpl::readAvailableTypes(
    Buffer buffer, bool* containsFilenames) {
  *containsFilenames = false;
  std::vector<WebString> results;
  if (!m_plainText.isEmpty()) {
    results.push_back(WebString("text/plain"));
  }
  if (!m_htmlText.isEmpty()) {
    results.push_back(WebString("text/html"));
  }
  if (!m_image.isNull()) {
    results.push_back(WebString("image/png"));
  }
  return results;
}
<|endoftext|>


<commit_before><commit_msg>Printing out cross section (convolute) graph after is has been normalized<commit_after><|endoftext|>


<commit_before>
#pragma once

#include "testing_utilities/componentwise.hpp"

#include <string>

#include "gmock/gmock.h"

namespace principia {
namespace testing_utilities {
namespace internal_componentwise {

using ::testing::SafeMatcherCast;

template<typename T1Matcher, typename T2Matcher>
ComponentwiseMatcher2<T1Matcher, T2Matcher>
Componentwise(T1Matcher const& t1_matcher,
              T2Matcher const& t2_matcher) {
  return ComponentwiseMatcher2<T1Matcher, T2Matcher>(t1_matcher, t2_matcher);
}

template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3<XMatcher, YMatcher, ZMatcher>
Componentwise(XMatcher const& x_matcher,
              YMatcher const& y_matcher,
              ZMatcher const& z_matcher) {
  return ComponentwiseMatcher3<XMatcher, YMatcher, ZMatcher>(
             x_matcher, y_matcher, z_matcher);
}

template<typename T1Matcher, typename T2Matcher>
ComponentwiseMatcher2<T1Matcher, T2Matcher>::ComponentwiseMatcher2(
    T1Matcher const& t1_matcher,
    T2Matcher const& t2_matcher)
    : t1_matcher_(t1_matcher),
      t2_matcher_(t2_matcher) {}

template<typename T1Matcher, typename T2Matcher>
template<typename PairType>
ComponentwiseMatcher2<T1Matcher, T2Matcher>::operator Matcher<PairType>()
    const {
  return Matcher<PairType>(
      new ComponentwiseMatcher2Impl<PairType const&>(t1_matcher_, t2_matcher_));
}

template<typename T1Matcher, typename T2Matcher, typename T3Matcher>
ComponentwiseMatcher3<T1Matcher, T2Matcher, T3Matcher>::ComponentwiseMatcher3(
    T1Matcher const& t1_matcher,
    T2Matcher const& t2_matcher,
    T3Matcher const& t3_matcher)
    : t1_matcher_(t1_matcher),
      t2_matcher_(t2_matcher),
      t3_matcher_(t3_matcher) {}

template<typename T1Matcher, typename T2Matcher, typename T3Matcher>
template<typename TripleType>
ComponentwiseMatcher3<T1Matcher, T2Matcher, T3Matcher>::
operator Matcher<TripleType>() const {
  return Matcher<TripleType>(new ComponentwiseMatcher3Impl<TripleType const&>(
      t1_matcher_, t2_matcher_, t3_matcher_));
}

template<typename T1, typename T2>
template<typename T1Matcher, typename T2Matcher>
ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::
ComponentwiseMatcher2Impl(T1Matcher const& t1_matcher,
                          T2Matcher const& t2_matcher)
    : t1_matcher_(SafeMatcherCast<T1>(t1_matcher)),
      t2_matcher_(SafeMatcherCast<T2>(t2_matcher)) {}

template<typename T1, typename T2>
bool ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::MatchAndExplain(
    geometry::Pair<T1, T2> const& actual,
    MatchResultListener* listener) const {
  bool const t1_matches = t1_matcher_.MatchAndExplain(actual.t1_, listener);
  if (!t1_matches) {
    *listener << " in the first element; ";
  }
  bool const t2_matches = t2_matcher_.MatchAndExplain(actual.t2_, listener);
  if (!t2_matches) {
    *listener << " in the second element; ";
  }
  return t1_matches && t2_matches;
}

template<typename T1, typename T2>
void ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::DescribeTo(
    std::ostream* out) const {
  *out << "first element ";
  t1_matcher_.DescribeTo(out);
  *out << " and second element ";
  t2_matcher_.DescribeTo(out);
}

template<typename T1, typename T2>
void ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "first element ";
  t1_matcher_.DescribeNegationTo(out);
  *out << " or second element ";
  t2_matcher_.DescribeNegationTo(out);
}

template<typename Frame>
template<typename QMatcher, typename PMatcher>
ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
ComponentwiseMatcher2Impl(QMatcher const& q_matcher,
                          PMatcher const& p_matcher)
    : q_matcher_(SafeMatcherCast<Position<Frame>>(q_matcher)),
      p_matcher_(SafeMatcherCast<Velocity<Frame>>(p_matcher)) {}

template<typename Frame>
bool ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
MatchAndExplain(physics::DegreesOfFreedom<Frame> const& actual,
                MatchResultListener* listener) const {
  bool const q_matches =
      q_matcher_.MatchAndExplain(actual.position(), listener);
  if (!q_matches) {
    *listener << " in the position; ";
  }
  bool const p_matches =
      p_matcher_.MatchAndExplain(actual.velocity(), listener);
  if (!p_matches) {
    *listener << " in the velocity; ";
  }
  return q_matches && p_matches;
}

template<typename Frame>
void ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "position ";
  q_matcher_.DescribeTo(out);
  *out << " and velocity ";
  p_matcher_.DescribeTo(out);
}

template<typename Frame>
void ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "position ";
  q_matcher_.DescribeNegationTo(out);
  *out << " or velocity ";
  p_matcher_.DescribeNegationTo(out);
}

template<typename Frame>
template<typename QMatcher, typename PMatcher>
ComponentwiseMatcher2Impl<physics::RelativeDegreesOfFreedom<Frame> const&>::
ComponentwiseMatcher2Impl(QMatcher const& q_matcher,
                          PMatcher const& p_matcher)
    : q_matcher_(SafeMatcherCast<Displacement<Frame>>(q_matcher)),
      p_matcher_(SafeMatcherCast<Velocity<Frame>>(p_matcher)) {}

template<typename Frame>
bool
ComponentwiseMatcher2Impl<physics::RelativeDegreesOfFreedom<Frame> const&>::
MatchAndExplain(physics::RelativeDegreesOfFreedom<Frame> const& actual,
                MatchResultListener* listener) const {
  bool const q_matches =
      q_matcher_.MatchAndExplain(actual.displacement(), listener);
  if (!q_matches) {
    *listener << " in the displacement; ";
  }
  bool const p_matches =
      p_matcher_.MatchAndExplain(actual.velocity(), listener);
  if (!p_matches) {
    *listener << " in the velocity; ";
  }
  return q_matches && p_matches;
}

template<typename Frame>
void ComponentwiseMatcher2Impl<physics::RelativeDegreesOfFreedom<Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "displacement ";
  q_matcher_.DescribeTo(out);
  *out << " and velocity ";
  p_matcher_.DescribeTo(out);
}

template<typename Frame>
void ComponentwiseMatcher2Impl<physics::RelativeDegreesOfFreedom<Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "displacement ";
  q_matcher_.DescribeNegationTo(out);
  *out << " or velocity ";
  p_matcher_.DescribeNegationTo(out);
}

template<typename Scalar, typename Frame>
template<typename XMatcher, typename YMatcher>
ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
ComponentwiseMatcher2Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)) {}

template<typename Scalar, typename Frame>
bool ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
MatchAndExplain(geometry::RP2Point<Scalar, Frame> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches = x_matcher_.MatchAndExplain(actual.x(), listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches = y_matcher_.MatchAndExplain(actual.y(), listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  return x_matches && y_matches;
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
}

template<typename Scalar>
template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
ComponentwiseMatcher3Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher,
                          ZMatcher const& z_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)),
      z_matcher_(SafeMatcherCast<Scalar>(z_matcher)) {}

template<typename Scalar>
bool ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
MatchAndExplain(geometry::R3Element<Scalar> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches = x_matcher_.MatchAndExplain(actual.x, listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches = y_matcher_.MatchAndExplain(actual.y, listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  bool const z_matches = z_matcher_.MatchAndExplain(actual.z, listener);
  if (!z_matches) {
    *listener << " in the z coordinate; ";
  }
  return x_matches && y_matches && z_matches;
}

template<typename Scalar>
void ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
  *out << " and z ";
  z_matcher_.DescribeTo(out);
}

template<typename Scalar>
void ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
  *out << " or z ";
  z_matcher_.DescribeNegationTo(out);
}

template<typename Scalar, typename Frame>
template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
ComponentwiseMatcher3Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher,
                          ZMatcher const& z_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)),
      z_matcher_(SafeMatcherCast<Scalar>(z_matcher)) {}

template<typename Scalar, typename Frame>
bool ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
MatchAndExplain(geometry::Vector<Scalar, Frame> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches =
      x_matcher_.MatchAndExplain(actual.coordinates().x, listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches =
      y_matcher_.MatchAndExplain(actual.coordinates().y, listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  bool const z_matches =
      z_matcher_.MatchAndExplain(actual.coordinates().z, listener);
  if (!z_matches) {
    *listener << " in the z coordinate; ";
  }
  return x_matches && y_matches && z_matches;
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
  *out << " and z ";
  z_matcher_.DescribeTo(out);
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
  *out << " or z ";
  z_matcher_.DescribeNegationTo(out);
}

template<typename Scalar, typename Frame>
template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
ComponentwiseMatcher3Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher,
                          ZMatcher const& z_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)),
      z_matcher_(SafeMatcherCast<Scalar>(z_matcher)) {}

template<typename Scalar, typename Frame>
bool ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
MatchAndExplain(geometry::Bivector<Scalar, Frame> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches =
      x_matcher_.MatchAndExplain(actual.coordinates().x, listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches =
      y_matcher_.MatchAndExplain(actual.coordinates().y, listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  bool const z_matches =
      z_matcher_.MatchAndExplain(actual.coordinates().z, listener);
  if (!z_matches) {
    *listener << " in the z coordinate; ";
  }
  return x_matches && y_matches && z_matches;
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
  *out << " and z ";
  z_matcher_.DescribeTo(out);
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
  *out << " or z ";
  z_matcher_.DescribeNegationTo(out);
}

}  // namespace internal_componentwise
}  // namespace testing_utilities
}  // namespace principia
<commit_msg>Lint.<commit_after>
#pragma once

#include "testing_utilities/componentwise.hpp"

#include <string>

#include "gmock/gmock.h"

namespace principia {
namespace testing_utilities {
namespace internal_componentwise {

using ::testing::SafeMatcherCast;

template<typename T1Matcher, typename T2Matcher>
ComponentwiseMatcher2<T1Matcher, T2Matcher>
Componentwise(T1Matcher const& t1_matcher,
              T2Matcher const& t2_matcher) {
  return ComponentwiseMatcher2<T1Matcher, T2Matcher>(t1_matcher, t2_matcher);
}

template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3<XMatcher, YMatcher, ZMatcher>
Componentwise(XMatcher const& x_matcher,
              YMatcher const& y_matcher,
              ZMatcher const& z_matcher) {
  return ComponentwiseMatcher3<XMatcher, YMatcher, ZMatcher>(
             x_matcher, y_matcher, z_matcher);
}

template<typename T1Matcher, typename T2Matcher>
ComponentwiseMatcher2<T1Matcher, T2Matcher>::ComponentwiseMatcher2(
    T1Matcher const& t1_matcher,
    T2Matcher const& t2_matcher)
    : t1_matcher_(t1_matcher),
      t2_matcher_(t2_matcher) {}

template<typename T1Matcher, typename T2Matcher>
template<typename PairType>
ComponentwiseMatcher2<T1Matcher, T2Matcher>::operator Matcher<PairType>()
    const {
  return Matcher<PairType>(
      new ComponentwiseMatcher2Impl<PairType const&>(t1_matcher_, t2_matcher_));
}

template<typename T1Matcher, typename T2Matcher, typename T3Matcher>
ComponentwiseMatcher3<T1Matcher, T2Matcher, T3Matcher>::ComponentwiseMatcher3(
    T1Matcher const& t1_matcher,
    T2Matcher const& t2_matcher,
    T3Matcher const& t3_matcher)
    : t1_matcher_(t1_matcher),
      t2_matcher_(t2_matcher),
      t3_matcher_(t3_matcher) {}

template<typename T1Matcher, typename T2Matcher, typename T3Matcher>
template<typename TripleType>
ComponentwiseMatcher3<T1Matcher, T2Matcher, T3Matcher>::
operator Matcher<TripleType>() const {
  return Matcher<TripleType>(new ComponentwiseMatcher3Impl<TripleType const&>(
      t1_matcher_, t2_matcher_, t3_matcher_));
}

template<typename T1, typename T2>
template<typename T1Matcher, typename T2Matcher>
ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::
ComponentwiseMatcher2Impl(T1Matcher const& t1_matcher,
                          T2Matcher const& t2_matcher)
    : t1_matcher_(SafeMatcherCast<T1>(t1_matcher)),
      t2_matcher_(SafeMatcherCast<T2>(t2_matcher)) {}

template<typename T1, typename T2>
bool ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::MatchAndExplain(
    geometry::Pair<T1, T2> const& actual,
    MatchResultListener* listener) const {
  bool const t1_matches = t1_matcher_.MatchAndExplain(actual.t1_, listener);
  if (!t1_matches) {
    *listener << " in the first element; ";
  }
  bool const t2_matches = t2_matcher_.MatchAndExplain(actual.t2_, listener);
  if (!t2_matches) {
    *listener << " in the second element; ";
  }
  return t1_matches && t2_matches;
}

template<typename T1, typename T2>
void ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::DescribeTo(
    std::ostream* out) const {
  *out << "first element ";
  t1_matcher_.DescribeTo(out);
  *out << " and second element ";
  t2_matcher_.DescribeTo(out);
}

template<typename T1, typename T2>
void ComponentwiseMatcher2Impl<geometry::Pair<T1, T2> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "first element ";
  t1_matcher_.DescribeNegationTo(out);
  *out << " or second element ";
  t2_matcher_.DescribeNegationTo(out);
}

template<typename Frame>
template<typename QMatcher, typename PMatcher>
ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
ComponentwiseMatcher2Impl(QMatcher const& q_matcher,
                          PMatcher const& p_matcher)
    : q_matcher_(SafeMatcherCast<Position<Frame>>(q_matcher)),
      p_matcher_(SafeMatcherCast<Velocity<Frame>>(p_matcher)) {}

template<typename Frame>
bool ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
MatchAndExplain(physics::DegreesOfFreedom<Frame> const& actual,
                MatchResultListener* listener) const {
  bool const q_matches =
      q_matcher_.MatchAndExplain(actual.position(), listener);
  if (!q_matches) {
    *listener << " in the position; ";
  }
  bool const p_matches =
      p_matcher_.MatchAndExplain(actual.velocity(), listener);
  if (!p_matches) {
    *listener << " in the velocity; ";
  }
  return q_matches && p_matches;
}

template<typename Frame>
void ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "position ";
  q_matcher_.DescribeTo(out);
  *out << " and velocity ";
  p_matcher_.DescribeTo(out);
}

template<typename Frame>
void ComponentwiseMatcher2Impl<physics::DegreesOfFreedom<Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "position ";
  q_matcher_.DescribeNegationTo(out);
  *out << " or velocity ";
  p_matcher_.DescribeNegationTo(out);
}

template<typename Frame>
template<typename QMatcher, typename PMatcher>
ComponentwiseMatcher2Impl<physics::RelativeDegreesOfFreedom<Frame> const&>::
ComponentwiseMatcher2Impl(QMatcher const& q_matcher,
                          PMatcher const& p_matcher)
    : q_matcher_(SafeMatcherCast<Displacement<Frame>>(q_matcher)),
      p_matcher_(SafeMatcherCast<Velocity<Frame>>(p_matcher)) {}

template<typename Frame>
bool
ComponentwiseMatcher2Impl<physics::RelativeDegreesOfFreedom<Frame> const&>::
MatchAndExplain(physics::RelativeDegreesOfFreedom<Frame> const& actual,
                MatchResultListener* listener) const {
  bool const q_matches =
      q_matcher_.MatchAndExplain(actual.displacement(), listener);
  if (!q_matches) {
    *listener << " in the displacement; ";
  }
  bool const p_matches =
      p_matcher_.MatchAndExplain(actual.velocity(), listener);
  if (!p_matches) {
    *listener << " in the velocity; ";
  }
  return q_matches && p_matches;
}

template<typename Frame>
void ComponentwiseMatcher2Impl<
    physics::RelativeDegreesOfFreedom<Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "displacement ";
  q_matcher_.DescribeTo(out);
  *out << " and velocity ";
  p_matcher_.DescribeTo(out);
}

template<typename Frame>
void ComponentwiseMatcher2Impl<
    physics::RelativeDegreesOfFreedom<Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "displacement ";
  q_matcher_.DescribeNegationTo(out);
  *out << " or velocity ";
  p_matcher_.DescribeNegationTo(out);
}

template<typename Scalar, typename Frame>
template<typename XMatcher, typename YMatcher>
ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
ComponentwiseMatcher2Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)) {}

template<typename Scalar, typename Frame>
bool ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
MatchAndExplain(geometry::RP2Point<Scalar, Frame> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches = x_matcher_.MatchAndExplain(actual.x(), listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches = y_matcher_.MatchAndExplain(actual.y(), listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  return x_matches && y_matches;
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher2Impl<geometry::RP2Point<Scalar, Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
}

template<typename Scalar>
template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
ComponentwiseMatcher3Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher,
                          ZMatcher const& z_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)),
      z_matcher_(SafeMatcherCast<Scalar>(z_matcher)) {}

template<typename Scalar>
bool ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
MatchAndExplain(geometry::R3Element<Scalar> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches = x_matcher_.MatchAndExplain(actual.x, listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches = y_matcher_.MatchAndExplain(actual.y, listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  bool const z_matches = z_matcher_.MatchAndExplain(actual.z, listener);
  if (!z_matches) {
    *listener << " in the z coordinate; ";
  }
  return x_matches && y_matches && z_matches;
}

template<typename Scalar>
void ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
  *out << " and z ";
  z_matcher_.DescribeTo(out);
}

template<typename Scalar>
void ComponentwiseMatcher3Impl<geometry::R3Element<Scalar> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
  *out << " or z ";
  z_matcher_.DescribeNegationTo(out);
}

template<typename Scalar, typename Frame>
template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
ComponentwiseMatcher3Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher,
                          ZMatcher const& z_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)),
      z_matcher_(SafeMatcherCast<Scalar>(z_matcher)) {}

template<typename Scalar, typename Frame>
bool ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
MatchAndExplain(geometry::Vector<Scalar, Frame> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches =
      x_matcher_.MatchAndExplain(actual.coordinates().x, listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches =
      y_matcher_.MatchAndExplain(actual.coordinates().y, listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  bool const z_matches =
      z_matcher_.MatchAndExplain(actual.coordinates().z, listener);
  if (!z_matches) {
    *listener << " in the z coordinate; ";
  }
  return x_matches && y_matches && z_matches;
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
  *out << " and z ";
  z_matcher_.DescribeTo(out);
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Vector<Scalar, Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
  *out << " or z ";
  z_matcher_.DescribeNegationTo(out);
}

template<typename Scalar, typename Frame>
template<typename XMatcher, typename YMatcher, typename ZMatcher>
ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
ComponentwiseMatcher3Impl(XMatcher const& x_matcher,
                          YMatcher const& y_matcher,
                          ZMatcher const& z_matcher)
    : x_matcher_(SafeMatcherCast<Scalar>(x_matcher)),
      y_matcher_(SafeMatcherCast<Scalar>(y_matcher)),
      z_matcher_(SafeMatcherCast<Scalar>(z_matcher)) {}

template<typename Scalar, typename Frame>
bool ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
MatchAndExplain(geometry::Bivector<Scalar, Frame> const& actual,
                MatchResultListener* listener) const {
  bool const x_matches =
      x_matcher_.MatchAndExplain(actual.coordinates().x, listener);
  if (!x_matches) {
    *listener << " in the x coordinate; ";
  }
  bool const y_matches =
      y_matcher_.MatchAndExplain(actual.coordinates().y, listener);
  if (!y_matches) {
    *listener << " in the y coordinate; ";
  }
  bool const z_matches =
      z_matcher_.MatchAndExplain(actual.coordinates().z, listener);
  if (!z_matches) {
    *listener << " in the z coordinate; ";
  }
  return x_matches && y_matches && z_matches;
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
DescribeTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeTo(out);
  *out << " and y ";
  y_matcher_.DescribeTo(out);
  *out << " and z ";
  z_matcher_.DescribeTo(out);
}

template<typename Scalar, typename Frame>
void ComponentwiseMatcher3Impl<geometry::Bivector<Scalar, Frame> const&>::
DescribeNegationTo(std::ostream* out) const {
  *out << "x ";
  x_matcher_.DescribeNegationTo(out);
  *out << " or y ";
  y_matcher_.DescribeNegationTo(out);
  *out << " or z ";
  z_matcher_.DescribeNegationTo(out);
}

}  // namespace internal_componentwise
}  // namespace testing_utilities
}  // namespace principia
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include "GL/glut.h"   // - An interface and windows management library
#include "visuals.h"   // Header file for our OpenGL functions

myModel md;
static float tx = 0.0;
static float rotx = 0.0;
static bool animate = false;
static float red = 1.0;
static float green = 0.0;
static float blue = 0.0;

using namespace std;

Point::Point(float x, float y, float z) {
	this->x = x;
	this->y = y;
	this->z = z;
}
float Point::getX() {
	return this->x;
}

float Point::getY() {
	return this->y;
}

float Point::getZ() {
	return this->z;
}

void Point::print(void) {
	cout << this->x << " " << this->y << " " << this->z << endl;
}

Faces::Faces(float v1, float vn1, float v2, float vn2, float v3, float vn3) {
	this->v = new Point(v1, v2, v3);
	this->vn = new Point(vn1, vn2, vn3);
}

Point* Faces::getV() {
	return this->v;
}

Point* Faces::getVn() {
	return this->vn;
}

void Faces::print(void) {
	this->v->print();
	this->vn->print();
}

void keimeno(const char *str, float size) {
	glPushMatrix();
	glScalef(size,size,size);

	for (size_t i=0;i<strlen(str);i++) {
		glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
	}
	glPopMatrix();
}

void Render() {
	//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0)
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clean up the colour of the window and the depth buffer
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(0,0,-100);
	glTranslatef(tx,0.0,0.0);
	glRotatef(rotx,1,0,0);

	//(01)
	glColor3f(0.3, 0.2, 0.9);                            // Set drawing colour
	DisplayModel(md);

	//(02)
	//glColor3f(0.8, 0.1, 0.1);
	//glTranslatef(-20.0,0.0,0.0);
	//keimeno("Dokimastiko keimeno",0.05f);

	//(03)
	//glColor3f(red, green, blue);                            // Set drawing colour
	//glutSolidTeapot(20.0);

	glutSwapBuffers();	// All drawing commands applied to the hidden buffer, so now, bring forward the hidden buffer and hide the visible one
}

//-----------------------------------------------------------

void Resize(int w, int h) {
  // define the visible area of the window ( in pixels )
  if (h==0) h=1;
  glViewport(0,0,w,h);

  // Setup viewing volume
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  gluPerspective(60.0, (float)w/(float)h, 1.0, 500.0);
}

void Idle() {
	if (animate) {
		rotx += 0.4;
	}
	glutPostRedisplay();
}

void Keyboard(unsigned char key, int x, int y) {
	switch(key) {
		case 'q' :
			exit(0);
			break;
		case 'a' :
			tx-=0.5f;
			break;
		case 'd' :
			tx+=0.5f;
			break;
		default :
			break;
	}
	glutPostRedisplay();
}

void Mouse(int button, int state, int x, int y) {
	if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) {
		animate = !animate;
		glutPostRedisplay();
	}
}

void Setup() {
	char path[] = "../planet.obj";
	ReadFile(&md, path);

	//Parameter handling
	glShadeModel (GL_SMOOTH);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);  //renders a fragment if its z value is less or equal of the stored value
	glClearDepth(1);

	// polygon rendering mode
	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );

	//Set up light source
	GLfloat light_position[] = { 0.0, 30.0, 50.0, 0.0 };
	glLightfv( GL_LIGHT0, GL_POSITION, light_position);

	GLfloat ambientLight[] = { 0.3, 0.3, 0.3, 1.0 };
	GLfloat diffuseLight[] = { 0.8, 0.8, 0.8, 1.0 };
	// GLfloat specularLight[] = { 1.0, 1.0, 1.0, 1.0 };

	glLightfv( GL_LIGHT0, GL_AMBIENT, ambientLight );
	glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseLight );

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);

	//01
	glFrontFace(GL_CCW);

	// Black background
	glClearColor(0.0f,0.0f,0.0f,1.0f);
}

void MenuSelect(int choice) {
	switch (choice) {
		case RED:
			red = 1.0;
			green = 0.0;
			blue = 0.0;
			break;
		case GREEN:
			red = 0.0;
			green = 1.0;
			blue = 0.0;
			break;
		case BLUE:
			red = 0.0;
			green = 0.0;
			blue = 1.0;
			break;
		case WHITE:
			red = 1.0;
			green = 1.0;
			blue = 1.0;
			break;
		default:
			break;
	}
}

void ReadFile(myModel *md, char *path) {
	string line;
	float x, y, z;
	string::size_type sz, sz2;
	ifstream myfile(path);
	if (myfile) {
		while (getline(myfile, line))	{
			if (line.find("v ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->v.push_back(new Point(x, y, z));
			} else if (line.find("vn ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->vn.push_back(new Point(x, y, z));
			} else if (line.find("f ") == 0) {
				int v1, vn1, v2, vn2, v3, vn3;
				string::size_type sz, sz2, sz3, sz4, sz5;
 				string temp = line.substr(3);
				v1 = stoi(temp, &sz);
				vn1 = stoi(temp.substr(sz+2), &sz2);
				v2 = stoi(temp.substr(sz+2+sz2), &sz3);
				vn2 = stoi(temp.substr(sz+2+sz2+sz3+2), &sz4);
				v3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4), &sz5);
				vn3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4+sz5+2));
				md->f.push_back(new Faces(v1, vn1, v2, vn2, v3, vn3));
			}
		}
		myfile.close();
	}
	cout << "Done reading from " << path << endl;
}

void DisplayModel(myModel md) {
	glPushMatrix();
	glBegin(GL_TRIANGLES);

	for (size_t i = 0; i < md.f.size(); i++) {

glVertex3f(md.vn[md.f[i]->getVn()->getX()-1]->getX(), md.vn[md.f[i]->getVn()->getX()-1]->getY(), md.vn[md.f[i]->getVn()->getX()-1]->getZ());
glVertex3f(md.vn[md.f[i]->getVn()->getY()-1]->getX(), md.vn[md.f[i]->getVn()->getY()-1]->getY(), md.vn[md.f[i]->getVn()->getY()-1]->getZ());
glVertex3f(md.vn[md.f[i]->getVn()->getZ()-1]->getX(), md.vn[md.f[i]->getVn()->getZ()-1]->getY(), md.vn[md.f[i]->getVn()->getZ()-1]->getZ());

glVertex3f(md.v[md.f[i]->getV()->getX()-1]->getX(), md.v[md.f[i]->getV()->getX()-1]->getY(), md.v[md.f[i]->getV()->getX()-1]->getZ());
glVertex3f(md.v[md.f[i]->getV()->getY()-1]->getX(), md.v[md.f[i]->getV()->getY()-1]->getY(), md.v[md.f[i]->getV()->getY()-1]->getZ());
glVertex3f(md.v[md.f[i]->getV()->getZ()-1]->getX(), md.v[md.f[i]->getV()->getZ()-1]->getY(), md.v[md.f[i]->getV()->getZ()-1]->getZ());

	}

	glEnd();
	glPopMatrix();

}
<commit_msg>A better planet view<commit_after>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include "GL/glut.h"   // - An interface and windows management library
#include "visuals.h"   // Header file for our OpenGL functions

myModel md;
static float tx = 0.0;
static float rotx = 0.0;
static bool animate = false;
static float red = 1.0;
static float green = 0.0;
static float blue = 0.0;

using namespace std;

Point::Point(float x, float y, float z) {
	this->x = x;
	this->y = y;
	this->z = z;
}
float Point::getX() {
	return this->x;
}

float Point::getY() {
	return this->y;
}

float Point::getZ() {
	return this->z;
}

void Point::print(void) {
	cout << this->x << " " << this->y << " " << this->z << endl;
}

Faces::Faces(float v1, float vn1, float v2, float vn2, float v3, float vn3) {
	this->v = new Point(v1, v2, v3);
	this->vn = new Point(vn1, vn2, vn3);
}

Point* Faces::getV() {
	return this->v;
}

Point* Faces::getVn() {
	return this->vn;
}

void Faces::print(void) {
	this->v->print();
	this->vn->print();
}

void keimeno(const char *str, float size) {
	glPushMatrix();
	glScalef(size,size,size);

	for (size_t i=0;i<strlen(str);i++) {
		glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
	}
	glPopMatrix();
}

void Render() {
	//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0)
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clean up the colour of the window and the depth buffer
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(0, 0, -100);
	glTranslatef(tx, 0.0, 0.0);
	glRotatef(rotx, 1, 0, 0);

	//(01)
	glColor3f(0.8, 0.1, 0.1);
	DisplayModel(md);

	//(02)
	// glColor3f(0.3, 0.2, 0.9);                            // Set drawing colour
	//glTranslatef(-20.0,0.0,0.0);
	//keimeno("Dokimastiko keimeno",0.05f);

	//(03)
	//glColor3f(red, green, blue);                            // Set drawing colour
	//glutSolidTeapot(20.0);

	glutSwapBuffers();	// All drawing commands applied to the hidden buffer, so now, bring forward the hidden buffer and hide the visible one
}

//-----------------------------------------------------------

void Resize(int w, int h) {
	// define the visible area of the window ( in pixels )
	if (h == 0) {
		h = 1;
	}
	glViewport(0, 0, w, h);

	// Setup viewing volume
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluPerspective(2.0, (float)w/(float)h, 1.0, 500.0);
}

void Idle() {
	if (animate) {
		rotx += 0.4;
	}
	glutPostRedisplay();
}

void Keyboard(unsigned char key, int x, int y) {
	switch(key) {
		case 'q' :
			exit(0);
			break;
		case 'a' :
			tx -= 0.5f;
			break;
		case 'd' :
			tx += 0.5f;
			break;
		default :
			break;
	}
	glutPostRedisplay();
}

void Mouse(int button, int state, int x, int y) {
	if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) {
		animate = !animate;
		glutPostRedisplay();
	}
}

void Setup() {
	char path[] = "../planet.obj";
	ReadFile(&md, path);

	//Parameter handling
	glShadeModel (GL_SMOOTH);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);  //renders a fragment if its z value is less or equal of the stored value
	glClearDepth(1);

	// polygon rendering mode
	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );

	//Set up light source
	GLfloat light_position[] = { 0.0, 30.0, 50.0, 0.0 };
	glLightfv( GL_LIGHT0, GL_POSITION, light_position);

	GLfloat ambientLight[] = { 0.3, 0.3, 0.3, 1.0 };
	GLfloat diffuseLight[] = { 0.8, 0.8, 0.8, 1.0 };
	// GLfloat specularLight[] = { 1.0, 1.0, 1.0, 1.0 };

	glLightfv( GL_LIGHT0, GL_AMBIENT, ambientLight );
	glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseLight );

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);

	//01
	glFrontFace(GL_CCW);

	// Black background
	glClearColor(0.0f,0.0f,0.0f,1.0f);
}

void MenuSelect(int choice) {
	switch (choice) {
		case RED:
			red = 1.0;
			green = 0.0;
			blue = 0.0;
			break;
		case GREEN:
			red = 0.0;
			green = 1.0;
			blue = 0.0;
			break;
		case BLUE:
			red = 0.0;
			green = 0.0;
			blue = 1.0;
			break;
		case WHITE:
			red = 1.0;
			green = 1.0;
			blue = 1.0;
			break;
		default:
			break;
	}
}

void ReadFile(myModel *md, char *path) {
	string line;
	float x, y, z;
	string::size_type sz, sz2;
	ifstream myfile(path);
	if (myfile) {
		while (getline(myfile, line))	{
			if (line.find("v ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->v.push_back(new Point(x, y, z));
			} else if (line.find("vn ") == 0) {
				string temp = line.substr(3);
				x = stod(temp, &sz);
				y = stod(temp.substr(sz), &sz2);
				z = stod(temp.substr(sz+sz2));
				md->vn.push_back(new Point(x, y, z));
			} else if (line.find("f ") == 0) {
				int v1, vn1, v2, vn2, v3, vn3;
				string::size_type sz, sz2, sz3, sz4, sz5;
 				string temp = line.substr(3);
				v1 = stoi(temp, &sz);
				vn1 = stoi(temp.substr(sz+2), &sz2);
				v2 = stoi(temp.substr(sz+2+sz2), &sz3);
				vn2 = stoi(temp.substr(sz+2+sz2+sz3+2), &sz4);
				v3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4), &sz5);
				vn3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4+sz5+2));
				md->f.push_back(new Faces(v1, vn1, v2, vn2, v3, vn3));
			}
		}
		myfile.close();
	}
	cout << "Done reading from " << path << endl;
}

void DisplayModel(myModel md) {
	glPushMatrix();
	glBegin(GL_POINTS);

	for (size_t i = 0; i < md.f.size(); i++) {
		/* Vns */
		glVertex3f(md.vn[md.f[i]->getVn()->getX()-1]->getX(), md.vn[md.f[i]->getVn()->getX()-1]->getY(), md.vn[md.f[i]->getVn()->getX()-1]->getZ());
		glVertex3f(md.vn[md.f[i]->getVn()->getY()-1]->getX(), md.vn[md.f[i]->getVn()->getY()-1]->getY(), md.vn[md.f[i]->getVn()->getY()-1]->getZ());
		glVertex3f(md.vn[md.f[i]->getVn()->getZ()-1]->getX(), md.vn[md.f[i]->getVn()->getZ()-1]->getY(), md.vn[md.f[i]->getVn()->getZ()-1]->getZ());
		/* Vs */
		glVertex3f(md.v[md.f[i]->getV()->getX()-1]->getX(), md.v[md.f[i]->getV()->getX()-1]->getY(), md.v[md.f[i]->getV()->getX()-1]->getZ());
		glVertex3f(md.v[md.f[i]->getV()->getY()-1]->getX(), md.v[md.f[i]->getV()->getY()-1]->getY(), md.v[md.f[i]->getV()->getY()-1]->getZ());
		glVertex3f(md.v[md.f[i]->getV()->getZ()-1]->getX(), md.v[md.f[i]->getV()->getZ()-1]->getY(), md.v[md.f[i]->getV()->getZ()-1]->getZ());
	}

	glEnd();
	glPopMatrix();
}
<|endoftext|>


<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        env_var_tests.cpp
 * @brief       環境変数対応テスト
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2012-2017, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"
#include <errno.h>

#if defined(USE_GTEST_PREFIX) || defined(IUTEST_USE_GTEST)
#  define ENV_PREFIX    "GTEST_"
#else
#  define ENV_PREFIX    "IUTEST_"
#endif

int SetUpEnvironmentImpl(void)
{
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "SHUFFLE=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "RANDOM_SEED=200") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "ALSO_RUN_DISABLED_TESTS=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "BREAK_ON_FAILURE=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "THROW_ON_FAILURE=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "CATCH_EXCEPTIONS=0") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "PRINT_TIME=0") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "REPEAT=2") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "FILTER=Flag*") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "OUTPUT=test") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv("XML_OUTPUT_FILE=hoge") == -1 ) return -1; // OUTPUT envrionment takes precedence

    if( ::iutest::internal::posix::PutEnv("IUTEST_DEFAULT_PACKAGE_NAME=env_var") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv("IUTEST_FILE_LOCATION=vs") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv("IUTEST_WARNING_INTO_ERROR=1") == -1 ) return -1;

    return 0;
}

static int lasterror = 0;

int SetUpEnvironment(void)
{
    if( SetUpEnvironmentImpl() == 0 ) return 0;
    lasterror = errno;
    return -1;
}

class SetUpResult
{
public:
    explicit SetUpResult(int n) : setup_environment(n) {}
    int setup_environment;
};
static volatile SetUpResult g_result IUTEST_ATTRIBUTE_INIT_PRIORITY_(101) = SetUpResult(SetUpEnvironment());

IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN()

IUTEST(FlagTest, Check)
{
    IUTEST_ASSUME_EQ(0, g_result.setup_environment) << lasterror << ": " << strerror(lasterror);  // putenv に失敗した場合はテストしない
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(also_run_disabled_tests) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(break_on_failure) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(throw_on_failure) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(shuffle) );
    IUTEST_EXPECT_FALSE( ::iutest::IUTEST_FLAG(catch_exceptions) );
    IUTEST_EXPECT_FALSE( ::iutest::IUTEST_FLAG(print_time) );
#if !defined(IUTEST_USE_GTEST)
    IUTEST_EXPECT_STREQ( "env_var", ::iutest::IUTEST_FLAG(default_package_name).c_str() );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(file_location_style_msvc) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(warning_into_error) );
#endif

    IUTEST_EXPECT_EQ( 200u, ::iutest::IUTEST_FLAG(random_seed) );
    IUTEST_EXPECT_EQ(   2 , ::iutest::IUTEST_FLAG(repeat) );

    IUTEST_EXPECT_STREQ( "Flag*", ::iutest::IUTEST_FLAG(filter).c_str() );
    IUTEST_EXPECT_STREQ( "test", ::iutest::IUTEST_FLAG(output).c_str() );
}

IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END()

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    (void)argc;
    (void)argv;

#ifdef UNICODE
    wchar_t a[] = "";
    wchar_t* targv[] = { a };
#else
    char a[] = "";
    char* targv[] =  { a };
#endif
    int targc = 1;
    IUTEST_INIT(&targc, targv);
#if !defined(IUTEST_USE_GTEST)
    if( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;
#else
    if( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;
#endif
    return 0;
}

<commit_msg>fix test<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        env_var_tests.cpp
 * @brief       環境変数対応テスト
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2012-2017, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"
#include <errno.h>

#if defined(USE_GTEST_PREFIX) || defined(IUTEST_USE_GTEST)
#  define ENV_PREFIX    "GTEST_"
#else
#  define ENV_PREFIX    "IUTEST_"
#endif

int SetUpEnvironmentImpl(void)
{
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "SHUFFLE=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "RANDOM_SEED=200") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "ALSO_RUN_DISABLED_TESTS=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "BREAK_ON_FAILURE=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "THROW_ON_FAILURE=1") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "CATCH_EXCEPTIONS=0") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "PRINT_TIME=0") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "REPEAT=2") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "FILTER=Flag*") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv(ENV_PREFIX "OUTPUT=test") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv("XML_OUTPUT_FILE=hoge") == -1 ) return -1; // OUTPUT envrionment takes precedence

    if( ::iutest::internal::posix::PutEnv("IUTEST_DEFAULT_PACKAGE_NAME=env_var") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv("IUTEST_FILE_LOCATION=vs") == -1 ) return -1;
    if( ::iutest::internal::posix::PutEnv("IUTEST_WARNING_INTO_ERROR=1") == -1 ) return -1;

    return 0;
}

static int lasterror = 0;

int SetUpEnvironment(void)
{
    if( SetUpEnvironmentImpl() == 0 ) return 0;
    lasterror = errno;
    return -1;
}

class SetUpResult
{
public:
    explicit SetUpResult(int n) : setup_environment(n) {}
    int setup_environment;
};
static volatile SetUpResult g_result IUTEST_ATTRIBUTE_INIT_PRIORITY_(101) = SetUpResult(SetUpEnvironment());

IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN()

IUTEST(FlagTest, Check)
{
    IUTEST_ASSUME_EQ(0, g_result.setup_environment) << "\n" << lasterror << ": " << strerror(lasterror);  // putenv に失敗した場合はテストしない
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(also_run_disabled_tests) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(break_on_failure) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(throw_on_failure) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(shuffle) );
    IUTEST_EXPECT_FALSE( ::iutest::IUTEST_FLAG(catch_exceptions) );
    IUTEST_EXPECT_FALSE( ::iutest::IUTEST_FLAG(print_time) );
#if !defined(IUTEST_USE_GTEST)
    IUTEST_EXPECT_STREQ( "env_var", ::iutest::IUTEST_FLAG(default_package_name).c_str() );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(file_location_style_msvc) );
    IUTEST_EXPECT_TRUE( ::iutest::IUTEST_FLAG(warning_into_error) );
#endif

    IUTEST_EXPECT_EQ( 200u, ::iutest::IUTEST_FLAG(random_seed) );
    IUTEST_EXPECT_EQ(   2 , ::iutest::IUTEST_FLAG(repeat) );

    IUTEST_EXPECT_STREQ( "Flag*", ::iutest::IUTEST_FLAG(filter).c_str() );
    IUTEST_EXPECT_STREQ( "test", ::iutest::IUTEST_FLAG(output).c_str() );
}

IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END()

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    (void)argc;
    (void)argv;

#ifdef UNICODE
    wchar_t a[] = "";
    wchar_t* targv[] = { a };
#else
    char a[] = "";
    char* targv[] =  { a };
#endif
    int targc = 1;
    IUTEST_INIT(&targc, targv);
#if !defined(IUTEST_USE_GTEST)
    if( g_result.setup_environment == 0 && ::iutest::IUTEST_FLAG(warning_into_error) )
    {
        if( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;
    }
    else
#endif
    {
        if( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;
    }
    return 0;
}

<|endoftext|>


<commit_before><commit_msg>core: fixed erroneous Tag1 tag insertion<commit_after><|endoftext|>


<commit_before>/*
 * scenewindow.cpp
 *
 *  Created on: 2014-6-5
 *      Author: Wang Yang
 *        Mail: admin@wysaid.org
*/

#include "scenewindow.h"

SceneWindow* g_sceneWindow = NULL;

const char* const s_vshScene = SHADER_STRING
(
attribute vec3 vPosition;

void main()
{
	gl_Position = vec4(vPosition, 1.0);
}
);

const char* const s_fshSceneNormal = SHADER_STRING_PRECISION_M
(

void main()
{
	gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
);

const char* const s_fshSceneMesh = SHADER_STRING_PRECISION_M
(

void main()
{
	gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
);

SceneWindow::SceneWindow(QWidget* parent) : QGLWidget(parent), m_programDrawNormal(NULL), m_programDrawMesh(NULL), m_ground(NULL), m_bIsMouseDown(false), m_lastX(0), m_lastY(0), m_farAway(100.0f), m_headUp(0.0f)
{
	if(g_sceneWindow != NULL)
	{
		LOG_ERROR("Invalid Usage!\n");
	}
	g_sceneWindow = this;
	setAttribute(Qt::WA_PaintOnScreen);
	setAttribute(Qt::WA_NoSystemBackground);
	setAutoBufferSwap(false);

	m_v2Position = HTAlgorithm::Vec2f(0.0f, 0.0f);
	m_v2Direction = HTAlgorithm::Vec2f(0.0f, m_farAway);

	m_m4Projection.loadIdentity();
	updateModelView();
	grabKeyboard();
}

SceneWindow::~SceneWindow()
{
	delete m_programDrawNormal;
	delete m_programDrawMesh;
	delete m_ground;
}

void SceneWindow::paintGL()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	HTAlgorithm::Mat4 qmat = m_m4Projection * m_m4ModelView;

	m_ground->drawGround(qmat);
	m_ground->drawGroundWithMesh(qmat);

	swapBuffers();
}

void SceneWindow::initializeGL()
{
	makeCurrent();

#if !defined(QT_OPENGL_ES_2) && defined(Q_OS_WIN)
    g_glFunctions = context()->functions();
#endif

	m_programDrawNormal = new WYQOpenGLShaderProgram;

	if(!(m_programDrawNormal->addShaderFromSourceCode(QOpenGLShader::Vertex, s_vshScene) &&
		m_programDrawNormal->addShaderFromSourceCode(QOpenGLShader::Fragment, s_fshSceneNormal) &&
		m_programDrawNormal->link()))
	{
		LOG_ERROR("Program link failed!\n");
	}

	m_programDrawMesh = new WYQOpenGLShaderProgram;

	if(!(m_programDrawMesh->addShaderFromSourceCode(QOpenGLShader::Vertex, s_vshScene) &&
		m_programDrawMesh->addShaderFromSourceCode(QOpenGLShader::Fragment, s_fshSceneMesh) &&
		m_programDrawMesh->link()))
	{
		LOG_ERROR("Program link failed!\n");
	}

	glClearColor(0.2f, 0.2f, 0.1f, 1.0f);

	m_ground = new Ground;
	m_ground->initWithStage(g_stage1, g_stage1Width, g_stage1Height);
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), SLOT(updateGL()));
	timer->start(20);
}

void SceneWindow::resizeGL(int w, int h)
{
	glViewport(0, 0, w, h);
	initPerspective(w, h);
}

void SceneWindow::mousePressEvent(QMouseEvent *e)
{
	m_bIsMouseDown = true;
	m_lastX = e->x();
	m_lastY = e->y();
}

void SceneWindow::mouseDoubleClickEvent(QMouseEvent *e)
{

}

void SceneWindow::mouseMoveEvent(QMouseEvent *e)
{
	if(!m_bIsMouseDown)
		return;

	using namespace HTAlgorithm;

	//m_modelView.rotateZ((m_lastX - e->x()) / 180.0f);

	m_v2Direction = Mat2::makeRotation((e->x() - m_lastX) / 180.0f) * m_v2Direction;

	m_headUp += (e->y() - m_lastY);// * 100.0f;

	if(m_headUp < -m_farAway / 2.0f)
		m_headUp = -m_farAway / 2.0f;
	else if(m_headUp > m_farAway)
		m_headUp = m_farAway;

	m_lastX = e->x();
	m_lastY = e->y();

	updateModelView();
}

void SceneWindow::mouseReleaseEvent(QMouseEvent *e)
{

}

void SceneWindow::keyPressEvent(QKeyEvent *e)
{
	using namespace HTAlgorithm;

	float motion = 0.1f;

	switch (e->key())
	{
	case Qt::Key_Left: case Qt::Key_A:
		goLeft(motion);
		break;
	case Qt::Key_Right: case Qt::Key_D:
		goRight(motion);
		break;
	case Qt::Key_Up: case Qt::Key_W:
		goForward(motion);
		break;
	case Qt::Key_Down: case Qt::Key_S:
		goBack(motion);
		break;
	default:
		return;
	}

	updateModelView();
}

void SceneWindow::keyReleaseEvent(QKeyEvent *)
{

}

GLuint SceneWindow::genTextureWithBuffer(const void* bufferData, GLint w, GLint h, GLenum channelFmt, GLenum dataFmt)
{
	GLuint tex;
    glActiveTexture(GL_TEXTURE0);
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, channelFmt, dataFmt, bufferData);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	return tex;
}

void SceneWindow::initOrtho(int w, int h)
{
	m_m4Projection = HTAlgorithm::Mat4::makeOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, -1.0);
}

void SceneWindow::initPerspective(int w, int h)
{
	float aspectRatio = w / float(h);
	float z = HT_MIN(width(), height());
	m_m4Projection = HTAlgorithm::Mat4::makePerspective(M_PI / 3.0f, aspectRatio, .1f, 10000.0f);
}

void SceneWindow::updateModelView()
{
	using namespace HTAlgorithm;
	const Vec2f v2Dir = m_v2Position + m_v2Direction;
	const float len = v2Dir.length();
	const Vec2f v2DirBack = v2Dir * (- m_headUp / len);

	m_m4ModelView = HTAlgorithm::Mat4::makeLookAt(m_v2Position[0], m_v2Position[1], 0.1f, v2Dir[0], v2Dir[1], m_headUp, v2DirBack[0], v2DirBack[1], len);

}

void SceneWindow::goForward(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	m_v2Position += tmp.normalize() * dis;
}

void SceneWindow::goBack(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	m_v2Position -= tmp.normalize() * dis;
}

void SceneWindow::goLeft(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	tmp.normalize();
	m_v2Position += HTAlgorithm::Vec2f(-tmp[1], tmp[0]) * dis;
}

void SceneWindow::goRight(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	tmp.normalize();
	m_v2Position += HTAlgorithm::Vec2f(tmp[1], -tmp[0]) * dis;
}
<commit_msg>solve the "Invalid Drawable" error under mac<commit_after>/*
 * scenewindow.cpp
 *
 *  Created on: 2014-6-5
 *      Author: Wang Yang
 *        Mail: admin@wysaid.org
*/

#include "scenewindow.h"

SceneWindow* g_sceneWindow = NULL;

const char* const s_vshScene = SHADER_STRING
(
attribute vec3 vPosition;

void main()
{
	gl_Position = vec4(vPosition, 1.0);
}
);

const char* const s_fshSceneNormal = SHADER_STRING_PRECISION_M
(

void main()
{
	gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
);

const char* const s_fshSceneMesh = SHADER_STRING_PRECISION_M
(

void main()
{
	gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
);

SceneWindow::SceneWindow(QWidget* parent) : QGLWidget(parent), m_programDrawNormal(NULL), m_programDrawMesh(NULL), m_ground(NULL), m_bIsMouseDown(false), m_lastX(0), m_lastY(0), m_farAway(100.0f), m_headUp(0.0f)
{
	if(g_sceneWindow != NULL)
	{
		LOG_ERROR("Invalid Usage!\n");
	}
	g_sceneWindow = this;
	setAttribute(Qt::WA_PaintOnScreen);
	setAttribute(Qt::WA_NoSystemBackground);
	setAutoBufferSwap(false);

	m_v2Position = HTAlgorithm::Vec2f(0.0f, 0.0f);
	m_v2Direction = HTAlgorithm::Vec2f(0.0f, m_farAway);

	m_m4Projection.loadIdentity();
	updateModelView();
	grabKeyboard();
    makeCurrent();
}

SceneWindow::~SceneWindow()
{
    makeCurrent();
	delete m_programDrawNormal;
	delete m_programDrawMesh;
	delete m_ground;
}

void SceneWindow::paintGL()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	HTAlgorithm::Mat4 qmat = m_m4Projection * m_m4ModelView;

	m_ground->drawGround(qmat);
	m_ground->drawGroundWithMesh(qmat);

	swapBuffers();
}

void SceneWindow::initializeGL()
{
	makeCurrent();

#if !defined(QT_OPENGL_ES_2) && defined(Q_OS_WIN)
    g_glFunctions = context()->functions();
#endif

	m_programDrawNormal = new WYQOpenGLShaderProgram;

	if(!(m_programDrawNormal->addShaderFromSourceCode(QOpenGLShader::Vertex, s_vshScene) &&
		m_programDrawNormal->addShaderFromSourceCode(QOpenGLShader::Fragment, s_fshSceneNormal) &&
		m_programDrawNormal->link()))
	{
		LOG_ERROR("Program link failed!\n");
	}

	m_programDrawMesh = new WYQOpenGLShaderProgram;

	if(!(m_programDrawMesh->addShaderFromSourceCode(QOpenGLShader::Vertex, s_vshScene) &&
		m_programDrawMesh->addShaderFromSourceCode(QOpenGLShader::Fragment, s_fshSceneMesh) &&
		m_programDrawMesh->link()))
	{
		LOG_ERROR("Program link failed!\n");
	}

	glClearColor(0.2f, 0.2f, 0.1f, 1.0f);

	m_ground = new Ground;
	m_ground->initWithStage(g_stage1, g_stage1Width, g_stage1Height);
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), SLOT(updateGL()));
	timer->start(20);
}

void SceneWindow::resizeGL(int w, int h)
{
	glViewport(0, 0, w, h);
	initPerspective(w, h);
}

void SceneWindow::mousePressEvent(QMouseEvent *e)
{
	m_bIsMouseDown = true;
	m_lastX = e->x();
	m_lastY = e->y();
}

void SceneWindow::mouseDoubleClickEvent(QMouseEvent *e)
{

}

void SceneWindow::mouseMoveEvent(QMouseEvent *e)
{
	if(!m_bIsMouseDown)
		return;

	using namespace HTAlgorithm;

	//m_modelView.rotateZ((m_lastX - e->x()) / 180.0f);

	m_v2Direction = Mat2::makeRotation((e->x() - m_lastX) / 180.0f) * m_v2Direction;

	m_headUp += (e->y() - m_lastY);// * 100.0f;

	if(m_headUp < -m_farAway / 2.0f)
		m_headUp = -m_farAway / 2.0f;
	else if(m_headUp > m_farAway)
		m_headUp = m_farAway;

	m_lastX = e->x();
	m_lastY = e->y();

	updateModelView();
}

void SceneWindow::mouseReleaseEvent(QMouseEvent *e)
{

}

void SceneWindow::keyPressEvent(QKeyEvent *e)
{
	using namespace HTAlgorithm;

	float motion = 0.1f;

	switch (e->key())
	{
	case Qt::Key_Left: case Qt::Key_A:
		goLeft(motion);
		break;
	case Qt::Key_Right: case Qt::Key_D:
		goRight(motion);
		break;
	case Qt::Key_Up: case Qt::Key_W:
		goForward(motion);
		break;
	case Qt::Key_Down: case Qt::Key_S:
		goBack(motion);
		break;
	default:
		return;
	}

	updateModelView();
}

void SceneWindow::keyReleaseEvent(QKeyEvent *)
{

}

GLuint SceneWindow::genTextureWithBuffer(const void* bufferData, GLint w, GLint h, GLenum channelFmt, GLenum dataFmt)
{
	GLuint tex;
    glActiveTexture(GL_TEXTURE0);
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, channelFmt, dataFmt, bufferData);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	return tex;
}

void SceneWindow::initOrtho(int w, int h)
{
	m_m4Projection = HTAlgorithm::Mat4::makeOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, -1.0);
}

void SceneWindow::initPerspective(int w, int h)
{
	float aspectRatio = w / float(h);
	float z = HT_MIN(width(), height());
	m_m4Projection = HTAlgorithm::Mat4::makePerspective(M_PI / 3.0f, aspectRatio, .1f, 10000.0f);
}

void SceneWindow::updateModelView()
{
	using namespace HTAlgorithm;
	const Vec2f v2Dir = m_v2Position + m_v2Direction;
	const float len = v2Dir.length();
	const Vec2f v2DirBack = v2Dir * (- m_headUp / len);

	m_m4ModelView = HTAlgorithm::Mat4::makeLookAt(m_v2Position[0], m_v2Position[1], 0.1f, v2Dir[0], v2Dir[1], m_headUp, v2DirBack[0], v2DirBack[1], len);

}

void SceneWindow::goForward(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	m_v2Position += tmp.normalize() * dis;
}

void SceneWindow::goBack(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	m_v2Position -= tmp.normalize() * dis;
}

void SceneWindow::goLeft(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	tmp.normalize();
	m_v2Position += HTAlgorithm::Vec2f(-tmp[1], tmp[0]) * dis;
}

void SceneWindow::goRight(float dis)
{
	HTAlgorithm::Vec2f tmp(m_v2Direction);
	tmp.normalize();
	m_v2Position += HTAlgorithm::Vec2f(tmp[1], -tmp[0]) * dis;
}
<|endoftext|>


<commit_before><commit_msg>Removed an extra pair of braces which didnt make sense.<commit_after><|endoftext|>


<commit_before><commit_msg>Version number output<commit_after><|endoftext|>