{"text":"\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \"atom\/browser\/api\/atom_api_session.h\"\n#include \"atom\/browser\/api\/atom_api_url_request.h\"\n#include \"atom\/browser\/net\/atom_url_request.h\"\n#include \"atom\/common\/native_mate_converters\/callback.h\"\n#include \"atom\/common\/native_mate_converters\/net_converter.h\"\n#include \"atom\/common\/native_mate_converters\/string16_converter.h\"\n#include \"atom\/common\/node_includes.h\"\n#include \"native_mate\/dictionary.h\"\n\n\n\nnamespace mate {\n\ntemplate<>\nstruct Converter> {\n static v8::Local ToV8(\n v8::Isolate* isolate,\n scoped_refptr val) {\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n if (val) {\n size_t iter = 0;\n std::string name;\n std::string value;\n while (val->EnumerateHeaderLines(&iter, &name, &value)) {\n dict.Set(name, value);\n }\n }\n return dict.GetHandle();\n }\n};\n\ntemplate<>\nstruct Converter> {\n static v8::Local ToV8(\n v8::Isolate* isolate,\n scoped_refptr buffer) {\n return node::Buffer::Copy(isolate,\n buffer->data(),\n buffer->size()).ToLocalChecked();\n }\n\n static bool FromV8(\n v8::Isolate* isolate,\n v8::Local val,\n scoped_refptr* out) {\n auto size = node::Buffer::Length(val);\n\n if (size == 0) {\n \/\/ Support conversion from empty buffer. A use case is\n \/\/ a GET request without body.\n \/\/ Since zero-sized IOBuffer(s) are not supported, we set the\n \/\/ out pointer to null.\n *out = nullptr;\n return true;\n }\n auto data = node::Buffer::Data(val);\n if (!data) {\n \/\/ This is an error as size is positive but data is null.\n return false;\n }\n\n auto io_buffer = new net::IOBufferWithSize(size);\n if (!io_buffer) {\n \/\/ Assuming allocation failed.\n return false;\n }\n\n \/\/ We do a deep copy. We could have used Buffer's internal memory\n \/\/ but that is much more complicated to be properly handled.\n memcpy(io_buffer->data(), data, size);\n *out = io_buffer;\n return true;\n }\n};\n\n} \/\/ namespace mate\n\nnamespace atom {\nnamespace api {\n\n\ntemplate \nURLRequest::StateBase::StateBase(Flags initialState)\n : state_(initialState) {\n}\n\ntemplate \nvoid URLRequest::StateBase::SetFlag(Flags flag) {\n state_ = static_cast(static_cast(state_) &\n static_cast(flag));\n}\n\ntemplate \nbool URLRequest::StateBase::operator==(Flags flag) const {\n return state_ == flag;\n}\n\ntemplate \nbool URLRequest::StateBase::IsFlagSet(Flags flag) const {\n return static_cast(state_) & static_cast(flag);\n}\n\nURLRequest::RequestState::RequestState()\n : StateBase(RequestStateFlags::kNotStarted) {\n}\n\nbool URLRequest::RequestState::NotStarted() const {\n return *this == RequestStateFlags::kNotStarted;\n}\n\nbool URLRequest::RequestState::Started() const {\n return IsFlagSet(RequestStateFlags::kStarted);\n}\n\nbool URLRequest::RequestState::Finished() const {\n return IsFlagSet(RequestStateFlags::kFinished);\n}\n\nbool URLRequest::RequestState::Canceled() const {\n return IsFlagSet(RequestStateFlags::kCanceled);\n}\n\nbool URLRequest::RequestState::Failed() const {\n return IsFlagSet(RequestStateFlags::kFailed);\n}\n\nbool URLRequest::RequestState::Closed() const {\n return IsFlagSet(RequestStateFlags::kClosed);\n}\n\nURLRequest::ResponseState::ResponseState()\n : StateBase(ResponseStateFlags::kNotStarted) {\n}\n\nbool URLRequest::ResponseState::NotStarted() const {\n return *this == ResponseStateFlags::kNotStarted;\n}\n\nbool URLRequest::ResponseState::Started() const {\n return IsFlagSet(ResponseStateFlags::kStarted);\n}\n\nbool URLRequest::ResponseState::Ended() const {\n return IsFlagSet(ResponseStateFlags::kEnded);\n}\n\n\nbool URLRequest::ResponseState::Failed() const {\n return IsFlagSet(ResponseStateFlags::kFailed);\n}\n\nURLRequest::URLRequest(v8::Isolate* isolate, v8::Local wrapper)\n : weak_ptr_factory_(this) {\n InitWith(isolate, wrapper);\n}\n\nURLRequest::~URLRequest() {\n}\n\n\/\/ static\nmate::WrappableBase* URLRequest::New(mate::Arguments* args) {\n v8::Local options;\n args->GetNext(&options);\n mate::Dictionary dict(args->isolate(), options);\n std::string method;\n dict.Get(\"method\", &method);\n std::string url;\n dict.Get(\"url\", &url);\n std::string session_name;\n dict.Get(\"session\", &session_name);\n\n auto session = Session::FromPartition(args->isolate(), session_name);\n\n auto browser_context = session->browser_context();\n auto api_url_request = new URLRequest(args->isolate(), args->GetThis());\n auto weak_ptr = api_url_request->weak_ptr_factory_.GetWeakPtr();\n auto atom_url_request = AtomURLRequest::Create(\n browser_context,\n method,\n url,\n weak_ptr);\n\n api_url_request->atom_request_ = atom_url_request;\n\n return api_url_request;\n}\n\n\/\/ static\nvoid URLRequest::BuildPrototype(v8::Isolate* isolate,\n v8::Local prototype) {\n prototype->SetClassName(mate::StringToV8(isolate, \"URLRequest\"));\n mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())\n \/\/ Request API\n .MakeDestroyable()\n .SetMethod(\"write\", &URLRequest::Write)\n .SetMethod(\"cancel\", &URLRequest::Cancel)\n .SetMethod(\"setExtraHeader\", &URLRequest::SetExtraHeader)\n .SetMethod(\"removeExtraHeader\", &URLRequest::RemoveExtraHeader)\n .SetMethod(\"setChunkedUpload\", &URLRequest::SetChunkedUpload)\n .SetProperty(\"notStarted\", &URLRequest::NotStarted)\n .SetProperty(\"finished\", &URLRequest::Finished)\n \/\/ Response APi\n .SetProperty(\"statusCode\", &URLRequest::StatusCode)\n .SetProperty(\"statusMessage\", &URLRequest::StatusMessage)\n .SetProperty(\"rawResponseHeaders\", &URLRequest::RawResponseHeaders)\n .SetProperty(\"httpVersionMajor\", &URLRequest::ResponseHttpVersionMajor)\n .SetProperty(\"httpVersionMinor\", &URLRequest::ResponseHttpVersionMinor);\n}\n\nbool URLRequest::NotStarted() const {\n return request_state_.NotStarted();\n}\n\nbool URLRequest::Finished() const {\n return request_state_.Finished();\n}\n\nbool URLRequest::Canceled() const {\n return request_state_.Canceled();\n}\n\nbool URLRequest::Write(\n scoped_refptr buffer,\n bool is_last) {\n if (request_state_.Canceled() ||\n request_state_.Failed() ||\n request_state_.Finished() ||\n request_state_.Closed()) {\n return false;\n }\n\n if (request_state_.NotStarted()) {\n request_state_.SetFlag(RequestStateFlags::kStarted);\n \/\/ Pin on first write.\n pin();\n }\n\n if (is_last) {\n request_state_.SetFlag(RequestStateFlags::kFinished);\n EmitRequestEvent(true, \"finish\");\n }\n\n DCHECK(atom_request_);\n if (atom_request_) {\n return atom_request_->Write(buffer, is_last);\n }\n return false;\n}\n\n\nvoid URLRequest::Cancel() {\n if (request_state_.Canceled() ||\n request_state_.Closed()) {\n \/\/ Cancel only once.\n return;\n }\n\n \/\/ Mark as canceled.\n request_state_.SetFlag(RequestStateFlags::kCanceled);\n\n DCHECK(atom_request_);\n if (atom_request_ && request_state_.Started()) {\n \/\/ Really cancel if it was started.\n atom_request_->Cancel();\n }\n EmitRequestEvent(true, \"abort\");\n\n if (response_state_.Started() && !response_state_.Ended()) {\n EmitResponseEvent(true, \"aborted\");\n }\n Close();\n}\n\nbool URLRequest::SetExtraHeader(const std::string& name,\n const std::string& value) {\n \/\/ State must be equal to not started.\n if (!request_state_.NotStarted()) {\n \/\/ Cannot change headers after send.\n return false;\n }\n\n if (!net::HttpUtil::IsValidHeaderName(name)) {\n return false;\n }\n\n if (!net::HttpUtil::IsValidHeaderValue(value)) {\n return false;\n }\n\n atom_request_->SetExtraHeader(name, value);\n return true;\n}\n\nvoid URLRequest::RemoveExtraHeader(const std::string& name) {\n \/\/ State must be equal to not started.\n if (!request_state_.NotStarted()) {\n \/\/ Cannot change headers after send.\n return;\n }\n atom_request_->RemoveExtraHeader(name);\n}\n\nvoid URLRequest::SetChunkedUpload(bool is_chunked_upload) {\n \/\/ State must be equal to not started.\n if (!request_state_.NotStarted()) {\n \/\/ Cannot change headers after send.\n return;\n }\n atom_request_->SetChunkedUpload(is_chunked_upload);\n}\n\nvoid URLRequest::OnAuthenticationRequired(\n scoped_refptr auth_info) {\n EmitRequestEvent(\n false,\n \"login\",\n auth_info.get(),\n base::Bind(&AtomURLRequest::PassLoginInformation, atom_request_));\n}\n\nvoid URLRequest::OnResponseStarted(\n scoped_refptr response_headers) {\n if (request_state_.Canceled() ||\n request_state_.Failed() ||\n request_state_.Closed()) {\n \/\/ Don't emit any event after request cancel.\n return;\n }\n response_headers_ = response_headers;\n response_state_.SetFlag(ResponseStateFlags::kStarted);\n Emit(\"response\");\n}\n\nvoid URLRequest::OnResponseData(\n scoped_refptr buffer) {\n if (request_state_.Canceled() ||\n request_state_.Closed() ||\n request_state_.Failed() ||\n response_state_.Failed()) {\n \/\/ In case we received an unexpected event from Chromium net,\n \/\/ don't emit any data event after request cancel\/error\/close.\n return;\n }\n if (!buffer || !buffer->data() || !buffer->size()) {\n return;\n }\n EmitResponseEvent(false, \"data\", buffer);\n}\n\nvoid URLRequest::OnResponseCompleted() {\n if (request_state_.Canceled() ||\n request_state_.Closed() ||\n request_state_.Failed() ||\n response_state_.Failed()) {\n \/\/ In case we received an unexpected event from Chromium net,\n \/\/ don't emit any data event after request cancel\/error\/close.\n return;\n }\n response_state_.SetFlag(ResponseStateFlags::kEnded);\n EmitResponseEvent(false, \"end\");\n Close();\n}\n\nvoid URLRequest::OnRequestError(const std::string& error) {\n request_state_.SetFlag(RequestStateFlags::kFailed);\n auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));\n EmitRequestEvent(false, \"error\", error_object);\n Close();\n}\n\nvoid URLRequest::OnResponseError(const std::string& error) {\n response_state_.SetFlag(ResponseStateFlags::kFailed);\n auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));\n EmitResponseEvent(false, \"error\", error_object);\n Close();\n}\n\n\nint URLRequest::StatusCode() const {\n if (response_headers_) {\n return response_headers_->response_code();\n }\n return -1;\n}\n\nstd::string URLRequest::StatusMessage() const {\n std::string result;\n if (response_headers_) {\n result = response_headers_->GetStatusText();\n }\n return result;\n}\n\nscoped_refptr\nURLRequest::RawResponseHeaders() const {\n return response_headers_;\n}\n\nuint32_t URLRequest::ResponseHttpVersionMajor() const {\n if (response_headers_) {\n return response_headers_->GetHttpVersion().major_value();\n }\n return 0;\n}\n\nuint32_t URLRequest::ResponseHttpVersionMinor() const {\n if (response_headers_) {\n return response_headers_->GetHttpVersion().minor_value();\n }\n return 0;\n}\n\nvoid URLRequest::Close() {\n if (!request_state_.Closed()) {\n request_state_.SetFlag(RequestStateFlags::kClosed);\n if (response_state_.Started()) {\n \/\/ Emit a close event if we really have a response object.\n EmitResponseEvent(true, \"close\");\n }\n EmitRequestEvent(true, \"close\");\n }\n unpin();\n atom_request_ = nullptr;\n}\n\nvoid URLRequest::pin() {\n if (wrapper_.IsEmpty()) {\n wrapper_.Reset(isolate(), GetWrapper());\n }\n}\n\nvoid URLRequest::unpin() {\n wrapper_.Reset();\n}\n\n} \/\/ namespace api\n\n} \/\/ namespace atom\nAdding systematic checks on the atom_request_ pointer as it may be reset to null.\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \"atom\/browser\/api\/atom_api_session.h\"\n#include \"atom\/browser\/api\/atom_api_url_request.h\"\n#include \"atom\/browser\/net\/atom_url_request.h\"\n#include \"atom\/common\/native_mate_converters\/callback.h\"\n#include \"atom\/common\/native_mate_converters\/net_converter.h\"\n#include \"atom\/common\/native_mate_converters\/string16_converter.h\"\n#include \"atom\/common\/node_includes.h\"\n#include \"native_mate\/dictionary.h\"\n\n\n\nnamespace mate {\n\ntemplate<>\nstruct Converter> {\n static v8::Local ToV8(\n v8::Isolate* isolate,\n scoped_refptr val) {\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n if (val) {\n size_t iter = 0;\n std::string name;\n std::string value;\n while (val->EnumerateHeaderLines(&iter, &name, &value)) {\n dict.Set(name, value);\n }\n }\n return dict.GetHandle();\n }\n};\n\ntemplate<>\nstruct Converter> {\n static v8::Local ToV8(\n v8::Isolate* isolate,\n scoped_refptr buffer) {\n return node::Buffer::Copy(isolate,\n buffer->data(),\n buffer->size()).ToLocalChecked();\n }\n\n static bool FromV8(\n v8::Isolate* isolate,\n v8::Local val,\n scoped_refptr* out) {\n auto size = node::Buffer::Length(val);\n\n if (size == 0) {\n \/\/ Support conversion from empty buffer. A use case is\n \/\/ a GET request without body.\n \/\/ Since zero-sized IOBuffer(s) are not supported, we set the\n \/\/ out pointer to null.\n *out = nullptr;\n return true;\n }\n auto data = node::Buffer::Data(val);\n if (!data) {\n \/\/ This is an error as size is positive but data is null.\n return false;\n }\n\n auto io_buffer = new net::IOBufferWithSize(size);\n if (!io_buffer) {\n \/\/ Assuming allocation failed.\n return false;\n }\n\n \/\/ We do a deep copy. We could have used Buffer's internal memory\n \/\/ but that is much more complicated to be properly handled.\n memcpy(io_buffer->data(), data, size);\n *out = io_buffer;\n return true;\n }\n};\n\n} \/\/ namespace mate\n\nnamespace atom {\nnamespace api {\n\n\ntemplate \nURLRequest::StateBase::StateBase(Flags initialState)\n : state_(initialState) {\n}\n\ntemplate \nvoid URLRequest::StateBase::SetFlag(Flags flag) {\n state_ = static_cast(static_cast(state_) &\n static_cast(flag));\n}\n\ntemplate \nbool URLRequest::StateBase::operator==(Flags flag) const {\n return state_ == flag;\n}\n\ntemplate \nbool URLRequest::StateBase::IsFlagSet(Flags flag) const {\n return static_cast(state_) & static_cast(flag);\n}\n\nURLRequest::RequestState::RequestState()\n : StateBase(RequestStateFlags::kNotStarted) {\n}\n\nbool URLRequest::RequestState::NotStarted() const {\n return *this == RequestStateFlags::kNotStarted;\n}\n\nbool URLRequest::RequestState::Started() const {\n return IsFlagSet(RequestStateFlags::kStarted);\n}\n\nbool URLRequest::RequestState::Finished() const {\n return IsFlagSet(RequestStateFlags::kFinished);\n}\n\nbool URLRequest::RequestState::Canceled() const {\n return IsFlagSet(RequestStateFlags::kCanceled);\n}\n\nbool URLRequest::RequestState::Failed() const {\n return IsFlagSet(RequestStateFlags::kFailed);\n}\n\nbool URLRequest::RequestState::Closed() const {\n return IsFlagSet(RequestStateFlags::kClosed);\n}\n\nURLRequest::ResponseState::ResponseState()\n : StateBase(ResponseStateFlags::kNotStarted) {\n}\n\nbool URLRequest::ResponseState::NotStarted() const {\n return *this == ResponseStateFlags::kNotStarted;\n}\n\nbool URLRequest::ResponseState::Started() const {\n return IsFlagSet(ResponseStateFlags::kStarted);\n}\n\nbool URLRequest::ResponseState::Ended() const {\n return IsFlagSet(ResponseStateFlags::kEnded);\n}\n\n\nbool URLRequest::ResponseState::Failed() const {\n return IsFlagSet(ResponseStateFlags::kFailed);\n}\n\nURLRequest::URLRequest(v8::Isolate* isolate, v8::Local wrapper)\n : weak_ptr_factory_(this) {\n InitWith(isolate, wrapper);\n}\n\nURLRequest::~URLRequest() {\n}\n\n\/\/ static\nmate::WrappableBase* URLRequest::New(mate::Arguments* args) {\n v8::Local options;\n args->GetNext(&options);\n mate::Dictionary dict(args->isolate(), options);\n std::string method;\n dict.Get(\"method\", &method);\n std::string url;\n dict.Get(\"url\", &url);\n std::string session_name;\n dict.Get(\"session\", &session_name);\n\n auto session = Session::FromPartition(args->isolate(), session_name);\n\n auto browser_context = session->browser_context();\n auto api_url_request = new URLRequest(args->isolate(), args->GetThis());\n auto weak_ptr = api_url_request->weak_ptr_factory_.GetWeakPtr();\n auto atom_url_request = AtomURLRequest::Create(\n browser_context,\n method,\n url,\n weak_ptr);\n\n api_url_request->atom_request_ = atom_url_request;\n\n return api_url_request;\n}\n\n\/\/ static\nvoid URLRequest::BuildPrototype(v8::Isolate* isolate,\n v8::Local prototype) {\n prototype->SetClassName(mate::StringToV8(isolate, \"URLRequest\"));\n mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())\n \/\/ Request API\n .MakeDestroyable()\n .SetMethod(\"write\", &URLRequest::Write)\n .SetMethod(\"cancel\", &URLRequest::Cancel)\n .SetMethod(\"setExtraHeader\", &URLRequest::SetExtraHeader)\n .SetMethod(\"removeExtraHeader\", &URLRequest::RemoveExtraHeader)\n .SetMethod(\"setChunkedUpload\", &URLRequest::SetChunkedUpload)\n .SetProperty(\"notStarted\", &URLRequest::NotStarted)\n .SetProperty(\"finished\", &URLRequest::Finished)\n \/\/ Response APi\n .SetProperty(\"statusCode\", &URLRequest::StatusCode)\n .SetProperty(\"statusMessage\", &URLRequest::StatusMessage)\n .SetProperty(\"rawResponseHeaders\", &URLRequest::RawResponseHeaders)\n .SetProperty(\"httpVersionMajor\", &URLRequest::ResponseHttpVersionMajor)\n .SetProperty(\"httpVersionMinor\", &URLRequest::ResponseHttpVersionMinor);\n}\n\nbool URLRequest::NotStarted() const {\n return request_state_.NotStarted();\n}\n\nbool URLRequest::Finished() const {\n return request_state_.Finished();\n}\n\nbool URLRequest::Canceled() const {\n return request_state_.Canceled();\n}\n\nbool URLRequest::Write(\n scoped_refptr buffer,\n bool is_last) {\n if (request_state_.Canceled() ||\n request_state_.Failed() ||\n request_state_.Finished() ||\n request_state_.Closed()) {\n return false;\n }\n\n if (request_state_.NotStarted()) {\n request_state_.SetFlag(RequestStateFlags::kStarted);\n \/\/ Pin on first write.\n pin();\n }\n\n if (is_last) {\n request_state_.SetFlag(RequestStateFlags::kFinished);\n EmitRequestEvent(true, \"finish\");\n }\n\n DCHECK(atom_request_);\n if (atom_request_) {\n return atom_request_->Write(buffer, is_last);\n }\n return false;\n}\n\n\nvoid URLRequest::Cancel() {\n if (request_state_.Canceled() ||\n request_state_.Closed()) {\n \/\/ Cancel only once.\n return;\n }\n\n \/\/ Mark as canceled.\n request_state_.SetFlag(RequestStateFlags::kCanceled);\n\n DCHECK(atom_request_);\n if (atom_request_ && request_state_.Started()) {\n \/\/ Really cancel if it was started.\n atom_request_->Cancel();\n }\n EmitRequestEvent(true, \"abort\");\n\n if (response_state_.Started() && !response_state_.Ended()) {\n EmitResponseEvent(true, \"aborted\");\n }\n Close();\n}\n\nbool URLRequest::SetExtraHeader(const std::string& name,\n const std::string& value) {\n \/\/ Request state must be in the initial non started state.\n if (!request_state_.NotStarted()) {\n \/\/ Cannot change headers after send.\n return false;\n }\n\n if (!net::HttpUtil::IsValidHeaderName(name)) {\n return false;\n }\n\n if (!net::HttpUtil::IsValidHeaderValue(value)) {\n return false;\n }\n\n DCHECK(atom_request_);\n if (atom_request_) {\n atom_request_->SetExtraHeader(name, value);\n }\n return true;\n}\n\nvoid URLRequest::RemoveExtraHeader(const std::string& name) {\n \/\/ State must be equal to not started.\n if (!request_state_.NotStarted()) {\n \/\/ Cannot change headers after send.\n return;\n }\n DCHECK(atom_request_);\n if (atom_request_) {\n atom_request_->RemoveExtraHeader(name);\n }\n}\n\nvoid URLRequest::SetChunkedUpload(bool is_chunked_upload) {\n \/\/ State must be equal to not started.\n if (!request_state_.NotStarted()) {\n \/\/ Cannot change headers after send.\n return;\n }\n DCHECK(atom_request_);\n if (atom_request_) {\n atom_request_->SetChunkedUpload(is_chunked_upload);\n }\n}\n\nvoid URLRequest::OnAuthenticationRequired(\n scoped_refptr auth_info) {\n if (request_state_.Canceled() ||\n request_state_.Closed()) {\n return;\n }\n\n DCHECK(atom_request_);\n if (!atom_request_) {\n return;\n }\n \n EmitRequestEvent(\n false,\n \"login\",\n auth_info.get(),\n base::Bind(&AtomURLRequest::PassLoginInformation, atom_request_));\n}\n\nvoid URLRequest::OnResponseStarted(\n scoped_refptr response_headers) {\n if (request_state_.Canceled() ||\n request_state_.Failed() ||\n request_state_.Closed()) {\n \/\/ Don't emit any event after request cancel.\n return;\n }\n response_headers_ = response_headers;\n response_state_.SetFlag(ResponseStateFlags::kStarted);\n Emit(\"response\");\n}\n\nvoid URLRequest::OnResponseData(\n scoped_refptr buffer) {\n if (request_state_.Canceled() ||\n request_state_.Closed() ||\n request_state_.Failed() ||\n response_state_.Failed()) {\n \/\/ In case we received an unexpected event from Chromium net,\n \/\/ don't emit any data event after request cancel\/error\/close.\n return;\n }\n if (!buffer || !buffer->data() || !buffer->size()) {\n return;\n }\n EmitResponseEvent(false, \"data\", buffer);\n}\n\nvoid URLRequest::OnResponseCompleted() {\n if (request_state_.Canceled() ||\n request_state_.Closed() ||\n request_state_.Failed() ||\n response_state_.Failed()) {\n \/\/ In case we received an unexpected event from Chromium net,\n \/\/ don't emit any data event after request cancel\/error\/close.\n return;\n }\n response_state_.SetFlag(ResponseStateFlags::kEnded);\n EmitResponseEvent(false, \"end\");\n Close();\n}\n\nvoid URLRequest::OnRequestError(const std::string& error) {\n auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));\n request_state_.SetFlag(RequestStateFlags::kFailed);\n EmitRequestEvent(false, \"error\", error_object);\n Close();\n}\n\nvoid URLRequest::OnResponseError(const std::string& error) {\n auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));\n response_state_.SetFlag(ResponseStateFlags::kFailed);\n EmitResponseEvent(false, \"error\", error_object);\n Close();\n}\n\n\nint URLRequest::StatusCode() const {\n if (response_headers_) {\n return response_headers_->response_code();\n }\n return -1;\n}\n\nstd::string URLRequest::StatusMessage() const {\n std::string result;\n if (response_headers_) {\n result = response_headers_->GetStatusText();\n }\n return result;\n}\n\nscoped_refptr\nURLRequest::RawResponseHeaders() const {\n return response_headers_;\n}\n\nuint32_t URLRequest::ResponseHttpVersionMajor() const {\n if (response_headers_) {\n return response_headers_->GetHttpVersion().major_value();\n }\n return 0;\n}\n\nuint32_t URLRequest::ResponseHttpVersionMinor() const {\n if (response_headers_) {\n return response_headers_->GetHttpVersion().minor_value();\n }\n return 0;\n}\n\nvoid URLRequest::Close() {\n if (!request_state_.Closed()) {\n request_state_.SetFlag(RequestStateFlags::kClosed);\n if (response_state_.Started()) {\n \/\/ Emit a close event if we really have a response object.\n EmitResponseEvent(true, \"close\");\n }\n EmitRequestEvent(true, \"close\");\n }\n unpin();\n atom_request_ = nullptr;\n}\n\nvoid URLRequest::pin() {\n if (wrapper_.IsEmpty()) {\n wrapper_.Reset(isolate(), GetWrapper());\n }\n}\n\nvoid URLRequest::unpin() {\n wrapper_.Reset();\n}\n\n} \/\/ namespace api\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: parsenv2.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:46:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \n#include \n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\n\nnamespace csi\n{\nnamespace uidl\n{\n\n\nUnoIDL_PE::~UnoIDL_PE()\n{\n}\n\nvoid\nUnoIDL_PE::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::n22::Repository & io_rRepository,\n TokenProcessing_Result & o_rResult )\n{\n aMyNode.EstablishContacts(io_pParentPE, io_rRepository.Gate_Idl(), o_rResult);\n}\n\nvoid\nUnoIDL_PE::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::idl::Gate & io_rGate,\n TokenProcessing_Result & o_rResult )\n{\n aMyNode.EstablishContacts(io_pParentPE, io_rGate, o_rResult);\n}\n\nvoid\nUnoIDL_PE::Enter( E_EnvStackAction i_eWayOfEntering )\n{\n switch (i_eWayOfEntering)\n {\n case push_sure:\n InitData();\n break;\n case push_try:\n csv_assert(false);\n break;\n case pop_success:\n ReceiveData();\n break;\n case pop_failure:\n throw X_AutodocParser(X_AutodocParser::x_Any);\n break;\n default:\n csv_assert(false);\n } \/\/ end switch\n}\n\nvoid\nUnoIDL_PE::Leave( E_EnvStackAction i_eWayOfLeaving )\n{\n switch (i_eWayOfLeaving)\n {\n case push_sure:\n break;\n case push_try:\n csv_assert(false);\n break;\n case pop_success:\n TransferData();\n break;\n case pop_failure:\n throw X_AutodocParser(X_AutodocParser::x_Any);\n break;\n default:\n csv_assert(false);\n } \/\/ end switch\n}\n\nvoid\nUnoIDL_PE::SetDocu( DYN ary::info::CodeInformation * let_dpDocu )\n{\n pDocu = let_dpDocu;\n}\n\nvoid\nUnoIDL_PE::SetPublished()\n{\n if (NOT pDocu)\n {\n pDocu = new ary::info::CodeInformation;\n }\n pDocu->SetPublished();\n}\n\nvoid\nUnoIDL_PE::SetOptional()\n{\n if (NOT pDocu)\n {\n pDocu = new ary::info::CodeInformation;\n }\n pDocu->SetOptional();\n}\n\nvoid\nUnoIDL_PE::PassDocuAt( ary::idl::CodeEntity & io_rCe )\n{\n if (pDocu)\n {\n io_rCe.Set_Docu(pDocu.Release());\n }\n else if \/\/ KORR_FUTURE\n \/\/ Re-enable doc-warning for Enum Values, as soon as there is a\n \/\/ @option -no-doc-for-enumvalues.\n ( io_rCe.ClassId() != ary::idl::Module::class_id\n AND io_rCe.ClassId() != ary::idl::EnumValue::class_id )\n {\n TheMessages().Out_MissingDoc(\n io_rCe.LocalName(),\n ParseInfo().CurFile(),\n ParseInfo().CurLine() );\n }\n}\n\nvoid\nUnoIDL_PE::InitData()\n{\n \/\/ Needs not anything to do.\n}\n\nvoid\nUnoIDL_PE::ReceiveData()\n{\n \/\/ Needs not anything to do.\n}\n\nconst ary::idl::Module &\nUnoIDL_PE::CurNamespace() const\n{\n if ( Parent() != 0 )\n return Parent()->CurNamespace();\n else\n {\n csv_assert(false);\n return *(const ary::idl::Module*)0;\n }\n}\n\nconst ParserInfo &\nUnoIDL_PE::ParseInfo() const\n{\n if ( Parent() != 0 )\n return Parent()->ParseInfo();\n else\n {\n csv_assert(false);\n return *(const ParserInfo*)0;\n }\n}\n\n} \/\/ namespace uidl\n} \/\/ namespace csi\n\nINTEGRATION: CWS warnings01 (1.9.4); FILE MERGED 2005\/10\/19 09:29:04 np 1.9.4.2: #i53898# 2005\/10\/18 08:36:16 np 1.9.4.1: #i53898#\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: parsenv2.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 12:06:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \n#include \n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\n\nnamespace csi\n{\nnamespace uidl\n{\n\n\nUnoIDL_PE::~UnoIDL_PE()\n{\n}\n\nvoid\nUnoIDL_PE::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::n22::Repository & io_rRepository,\n TokenProcessing_Result & o_rResult )\n{\n pRepository = &io_rRepository;\n aMyNode.EstablishContacts(io_pParentPE, io_rRepository.Gate_Idl(), o_rResult);\n}\n\n\/\/void\n\/\/UnoIDL_PE::EstablishContacts( UnoIDL_PE * io_pParentPE,\n\/\/ ary::idl::Gate & io_rGate,\n\/\/ TokenProcessing_Result & o_rResult )\n\/\/{\n\/\/ aMyNode.EstablishContacts(io_pParentPE, io_rGate, o_rResult);\n\/\/}\n\nvoid\nUnoIDL_PE::Enter( E_EnvStackAction i_eWayOfEntering )\n{\n switch (i_eWayOfEntering)\n {\n case push_sure:\n InitData();\n break;\n case push_try:\n csv_assert(false);\n break;\n case pop_success:\n ReceiveData();\n break;\n case pop_failure:\n throw X_AutodocParser(X_AutodocParser::x_Any);\n \/\/ no break because of throw\n default:\n csv_assert(false);\n } \/\/ end switch\n}\n\nvoid\nUnoIDL_PE::Leave( E_EnvStackAction i_eWayOfLeaving )\n{\n switch (i_eWayOfLeaving)\n {\n case push_sure:\n break;\n case push_try:\n csv_assert(false);\n break;\n case pop_success:\n TransferData();\n break;\n case pop_failure:\n throw X_AutodocParser(X_AutodocParser::x_Any);\n \/\/ no break because of throw\n default:\n csv_assert(false);\n } \/\/ end switch\n}\n\nvoid\nUnoIDL_PE::SetDocu( DYN ary::info::CodeInformation * let_dpDocu )\n{\n pDocu = let_dpDocu;\n}\n\nvoid\nUnoIDL_PE::SetPublished()\n{\n if (NOT pDocu)\n {\n pDocu = new ary::info::CodeInformation;\n }\n pDocu->SetPublished();\n}\n\nvoid\nUnoIDL_PE::SetOptional()\n{\n if (NOT pDocu)\n {\n pDocu = new ary::info::CodeInformation;\n }\n pDocu->SetOptional();\n}\n\nvoid\nUnoIDL_PE::PassDocuAt( ary::idl::CodeEntity & io_rCe )\n{\n if (pDocu)\n {\n io_rCe.Set_Docu(pDocu.Release());\n }\n else if \/\/ KORR_FUTURE\n \/\/ Re-enable doc-warning for Enum Values, as soon as there is a\n \/\/ @option -no-doc-for-enumvalues.\n ( io_rCe.ClassId() != ary::idl::Module::class_id\n AND io_rCe.ClassId() != ary::idl::EnumValue::class_id )\n {\n TheMessages().Out_MissingDoc(\n io_rCe.LocalName(),\n ParseInfo().CurFile(),\n ParseInfo().CurLine() );\n }\n}\n\nvoid\nUnoIDL_PE::InitData()\n{\n \/\/ Needs not anything to do.\n}\n\nvoid\nUnoIDL_PE::ReceiveData()\n{\n \/\/ Needs not anything to do.\n}\n\nconst ary::idl::Module &\nUnoIDL_PE::CurNamespace() const\n{\n if ( Parent() != 0 )\n return Parent()->CurNamespace();\n else\n {\n csv_assert(false);\n return *(const ary::idl::Module*)0;\n }\n}\n\nconst ParserInfo &\nUnoIDL_PE::ParseInfo() const\n{\n if ( Parent() != 0 )\n return Parent()->ParseInfo();\n else\n {\n csv_assert(false);\n return *(const ParserInfo*)0;\n }\n}\n\nUnoIDL_PE::UnoIDL_PE()\n : aMyNode(),\n pDocu(),\n pRepository(0)\n{\n}\n\n\n} \/\/ namespace uidl\n} \/\/ namespace csi\n<|endoftext|>"} {"text":"#include \n\\\n#include \"animatedtilesplugin.h\"\n#include \"animatedtilesitem.h\"\n\n\nAnimatedTilesPlugin::AnimatedTilesPlugin()\n{\n this->mName = \"AnimatedTiles\";\n \/\/This should not be an advertized plugin until it is implemented\n \/\/this->mRole = \"animatedTiles\";\n}\n\n\nQ_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)\n\nvoid AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)\n{\n qmlRegisterType(\"AnimatedTiles\", 1, 0, \"AnimatedTiles\");\n}\nAdjust minor animated tiles transgression#include \n\\\n#include \"animatedtilesplugin.h\"\n#include \"animatedtilesitem.h\"\n\n\nAnimatedTilesPlugin::AnimatedTilesPlugin()\n{\n setName(\"AnimatedTiles\");\n \/\/This should not be an advertized plugin until it is implemented\n \/\/setRole(\"animatedTiles\");\n}\n\n\nQ_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)\n\nvoid AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)\n{\n qmlRegisterType(\"AnimatedTiles\", 1, 0, \"AnimatedTiles\");\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"localplaingdbadapter.h\"\n\n#include \"gdbengine.h\"\n#include \"procinterrupt.h\"\n#include \"debuggercore.h\"\n#include \"debuggerstringutils.h\"\n\n#include \n\n#include \n#include \n#include \n\nnamespace Debugger {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PlainGdbAdapter\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)\n : AbstractPlainGdbAdapter(engine, parent)\n{\n \/\/ Output\n connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),\n engine, SLOT(readDebugeeOutput(QByteArray)));\n}\n\nAbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const\n{\n \/\/ LD_PRELOAD fails for System-Qt on Mac.\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n return DumperLoadedByGdb;\n#else\n return DumperLoadedByGdbPreload;\n#endif\n}\n\nvoid LocalPlainGdbAdapter::startAdapter()\n{\n QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());\n showMessage(_(\"TRYING TO START ADAPTER\"));\n\n#ifdef Q_OS_WIN\n if (!prepareWinCommand())\n return;\n#endif\n\n QStringList gdbArgs;\n\n if (!m_outputCollector.listen()) {\n m_engine->handleAdapterStartFailed(tr(\"Cannot set up communication with child process: %1\")\n .arg(m_outputCollector.errorString()), QString());\n return;\n }\n gdbArgs.append(_(\"--tty=\") + m_outputCollector.serverName());\n\n if (!startParameters().workingDirectory.isEmpty())\n m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);\n if (startParameters().environment.size())\n m_gdbProc.setEnvironment(startParameters().environment.toStringList());\n\n if (!m_engine->startGdb(gdbArgs)) {\n m_outputCollector.shutdown();\n return;\n }\n\n checkForReleaseBuild();\n m_engine->handleAdapterStarted();\n}\n\nvoid LocalPlainGdbAdapter::setupInferior()\n{\n AbstractPlainGdbAdapter::setupInferior();\n}\n\nvoid LocalPlainGdbAdapter::runEngine()\n{\n AbstractPlainGdbAdapter::runEngine();\n}\n\nvoid LocalPlainGdbAdapter::shutdownInferior()\n{\n m_engine->defaultInferiorShutdown(\"kill\");\n}\n\nvoid LocalPlainGdbAdapter::shutdownAdapter()\n{\n showMessage(_(\"PLAIN ADAPTER SHUTDOWN %1\").arg(state()));\n m_outputCollector.shutdown();\n m_engine->notifyAdapterShutdownOk();\n}\n\nvoid LocalPlainGdbAdapter::checkForReleaseBuild()\n{\n \/\/ Quick check for a \"release\" build\n QProcess proc;\n QStringList args;\n args.append(_(\"-h\"));\n args.append(_(\"-j\"));\n args.append(_(\".debug_info\"));\n args.append(startParameters().executable);\n proc.start(_(\"objdump\"), args);\n proc.closeWriteChannel();\n if (!proc.waitForStarted()) {\n showMessage(_(\"OBJDUMP PROCESS COULD NOT BE STARTED. \"\n \"RELEASE BUILD CHECK WILL FAIL\"));\n return;\n }\n proc.waitForFinished();\n QByteArray ba = proc.readAllStandardOutput();\n \/\/ This should yield something like\n \/\/ \"debuggertest: file format elf32-i386\\n\\n\"\n \/\/ \"Sections:\\nIdx Name Size VMA LMA File off Algn\\n\"\n \/\/ \"30 .debug_info 00087d36 00000000 00000000 0006bbd5 2**0\\n\"\n \/\/ \" CONTENTS, READONLY, DEBUGGING\"\n if (ba.contains(\"Sections:\") && !ba.contains(\".debug_info\")) {\n showMessageBox(QMessageBox::Information, \"Warning\",\n tr(\"This does not seem to be a \\\"Debug\\\" build.\\n\"\n \"Setting breakpoints by file name and line number may fail.\"));\n }\n}\n\nvoid LocalPlainGdbAdapter::interruptInferior()\n{\n const qint64 attachedPID = m_engine->inferiorPid();\n if (attachedPID <= 0) {\n showMessage(_(\"TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED\"));\n return;\n }\n\n if (!interruptProcess(attachedPID)) {\n showMessage(_(\"CANNOT INTERRUPT %1\").arg(attachedPID));\n m_engine->notifyInferiorStopFailed();\n }\n}\n\nQByteArray LocalPlainGdbAdapter::execFilePath() const\n{\n return QFileInfo(startParameters().executable)\n .absoluteFilePath().toLocal8Bit();\n}\n\nbool LocalPlainGdbAdapter::infoTargetNecessary() const\n{\n#ifdef Q_OS_LINUX\n return true;\n#else\n return false;\n#endif\n}\n\nQByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const\n{\n return s.toLocal8Bit();\n}\n\nQString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const\n{\n return QString::fromLocal8Bit(b);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\ndebugger: be a bit more verbose in the log on process interruption\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"localplaingdbadapter.h\"\n\n#include \"gdbengine.h\"\n#include \"procinterrupt.h\"\n#include \"debuggercore.h\"\n#include \"debuggerstringutils.h\"\n\n#include \n\n#include \n#include \n#include \n\nnamespace Debugger {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PlainGdbAdapter\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)\n : AbstractPlainGdbAdapter(engine, parent)\n{\n \/\/ Output\n connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),\n engine, SLOT(readDebugeeOutput(QByteArray)));\n}\n\nAbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const\n{\n \/\/ LD_PRELOAD fails for System-Qt on Mac.\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n return DumperLoadedByGdb;\n#else\n return DumperLoadedByGdbPreload;\n#endif\n}\n\nvoid LocalPlainGdbAdapter::startAdapter()\n{\n QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());\n showMessage(_(\"TRYING TO START ADAPTER\"));\n\n#ifdef Q_OS_WIN\n if (!prepareWinCommand())\n return;\n#endif\n\n QStringList gdbArgs;\n\n if (!m_outputCollector.listen()) {\n m_engine->handleAdapterStartFailed(tr(\"Cannot set up communication with child process: %1\")\n .arg(m_outputCollector.errorString()), QString());\n return;\n }\n gdbArgs.append(_(\"--tty=\") + m_outputCollector.serverName());\n\n if (!startParameters().workingDirectory.isEmpty())\n m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);\n if (startParameters().environment.size())\n m_gdbProc.setEnvironment(startParameters().environment.toStringList());\n\n if (!m_engine->startGdb(gdbArgs)) {\n m_outputCollector.shutdown();\n return;\n }\n\n checkForReleaseBuild();\n m_engine->handleAdapterStarted();\n}\n\nvoid LocalPlainGdbAdapter::setupInferior()\n{\n AbstractPlainGdbAdapter::setupInferior();\n}\n\nvoid LocalPlainGdbAdapter::runEngine()\n{\n AbstractPlainGdbAdapter::runEngine();\n}\n\nvoid LocalPlainGdbAdapter::shutdownInferior()\n{\n m_engine->defaultInferiorShutdown(\"kill\");\n}\n\nvoid LocalPlainGdbAdapter::shutdownAdapter()\n{\n showMessage(_(\"PLAIN ADAPTER SHUTDOWN %1\").arg(state()));\n m_outputCollector.shutdown();\n m_engine->notifyAdapterShutdownOk();\n}\n\nvoid LocalPlainGdbAdapter::checkForReleaseBuild()\n{\n \/\/ Quick check for a \"release\" build\n QProcess proc;\n QStringList args;\n args.append(_(\"-h\"));\n args.append(_(\"-j\"));\n args.append(_(\".debug_info\"));\n args.append(startParameters().executable);\n proc.start(_(\"objdump\"), args);\n proc.closeWriteChannel();\n if (!proc.waitForStarted()) {\n showMessage(_(\"OBJDUMP PROCESS COULD NOT BE STARTED. \"\n \"RELEASE BUILD CHECK WILL FAIL\"));\n return;\n }\n proc.waitForFinished();\n QByteArray ba = proc.readAllStandardOutput();\n \/\/ This should yield something like\n \/\/ \"debuggertest: file format elf32-i386\\n\\n\"\n \/\/ \"Sections:\\nIdx Name Size VMA LMA File off Algn\\n\"\n \/\/ \"30 .debug_info 00087d36 00000000 00000000 0006bbd5 2**0\\n\"\n \/\/ \" CONTENTS, READONLY, DEBUGGING\"\n if (ba.contains(\"Sections:\") && !ba.contains(\".debug_info\")) {\n showMessageBox(QMessageBox::Information, \"Warning\",\n tr(\"This does not seem to be a \\\"Debug\\\" build.\\n\"\n \"Setting breakpoints by file name and line number may fail.\"));\n }\n}\n\nvoid LocalPlainGdbAdapter::interruptInferior()\n{\n const qint64 attachedPID = m_engine->inferiorPid();\n if (attachedPID <= 0) {\n showMessage(_(\"TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED\"));\n return;\n }\n\n if (interruptProcess(attachedPID)) {\n showMessage(_(\"INTERRUPTED %1\").arg(attachedPID));\n } else {\n showMessage(_(\"CANNOT INTERRUPT %1\").arg(attachedPID));\n m_engine->notifyInferiorStopFailed();\n }\n}\n\nQByteArray LocalPlainGdbAdapter::execFilePath() const\n{\n return QFileInfo(startParameters().executable)\n .absoluteFilePath().toLocal8Bit();\n}\n\nbool LocalPlainGdbAdapter::infoTargetNecessary() const\n{\n#ifdef Q_OS_LINUX\n return true;\n#else\n return false;\n#endif\n}\n\nQByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const\n{\n return s.toLocal8Bit();\n}\n\nQString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const\n{\n return QString::fromLocal8Bit(b);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"projecttreewidget.h\"\n\n#include \"projectexplorer.h\"\n#include \"projectnodes.h\"\n#include \"project.h\"\n#include \"session.h\"\n#include \"projectexplorerconstants.h\"\n#include \"projectmodels.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ProjectExplorer;\nusing namespace ProjectExplorer::Internal;\n\nnamespace {\n bool debug = false;\n}\n\nclass ProjectTreeView : public Utils::NavigationTreeView\n{\npublic:\n ProjectTreeView()\n {\n setEditTriggers(QAbstractItemView::EditKeyPressed);\n setContextMenuPolicy(Qt::CustomContextMenu);\n\/\/ setExpandsOnDoubleClick(false);\n m_context = new Core::IContext(this);\n m_context->setContext(Core::Context(Constants::C_PROJECT_TREE));\n m_context->setWidget(this);\n Core::ICore::addContextObject(m_context);\n }\n ~ProjectTreeView()\n {\n Core::ICore::removeContextObject(m_context);\n delete m_context;\n }\n\nprivate:\n Core::IContext *m_context;\n};\n\n\/*!\n \/class ProjectTreeWidget\n\n Shows the projects in form of a tree.\n *\/\nProjectTreeWidget::ProjectTreeWidget(QWidget *parent)\n : QWidget(parent),\n m_explorer(ProjectExplorerPlugin::instance()),\n m_view(0),\n m_model(0),\n m_filterProjectsAction(0),\n m_autoSync(false),\n m_autoExpand(true)\n{\n m_model = new FlatModel(m_explorer->session()->sessionNode(), this);\n Project *pro = m_explorer->session()->startupProject();\n if (pro)\n m_model->setStartupProject(pro->rootProjectNode());\n NodesWatcher *watcher = new NodesWatcher(this);\n m_explorer->session()->sessionNode()->registerWatcher(watcher);\n\n connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode*,QList)),\n this, SLOT(foldersAboutToBeRemoved(FolderNode*,QList)));\n connect(watcher, SIGNAL(filesAboutToBeRemoved(FolderNode*,QList)),\n this, SLOT(filesAboutToBeRemoved(FolderNode*,QList)));\n\n m_view = new ProjectTreeView;\n m_view->setModel(m_model);\n setFocusProxy(m_view);\n initView();\n\n QVBoxLayout *layout = new QVBoxLayout();\n layout->addWidget(m_view);\n layout->setContentsMargins(0, 0, 0, 0);\n setLayout(layout);\n\n m_filterProjectsAction = new QAction(tr(\"Simplify Tree\"), this);\n m_filterProjectsAction->setCheckable(true);\n m_filterProjectsAction->setChecked(false); \/\/ default is the traditional complex tree\n connect(m_filterProjectsAction, SIGNAL(toggled(bool)), this, SLOT(setProjectFilter(bool)));\n\n m_filterGeneratedFilesAction = new QAction(tr(\"Hide Generated Files\"), this);\n m_filterGeneratedFilesAction->setCheckable(true);\n m_filterGeneratedFilesAction->setChecked(true);\n connect(m_filterGeneratedFilesAction, SIGNAL(toggled(bool)), this, SLOT(setGeneratedFilesFilter(bool)));\n\n \/\/ connections\n connect(m_model, SIGNAL(modelReset()),\n this, SLOT(initView()));\n connect(m_view, SIGNAL(activated(QModelIndex)),\n this, SLOT(openItem(QModelIndex)));\n connect(m_view->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n this, SLOT(handleCurrentItemChange(QModelIndex)));\n connect(m_view, SIGNAL(customContextMenuRequested(QPoint)),\n this, SLOT(showContextMenu(QPoint)));\n connect(m_explorer->session(), SIGNAL(singleProjectAdded(ProjectExplorer::Project*)),\n this, SLOT(handleProjectAdded(ProjectExplorer::Project*)));\n connect(m_explorer->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),\n this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));\n\n connect(m_explorer->session(), SIGNAL(aboutToLoadSession(QString)),\n this, SLOT(disableAutoExpand()));\n connect(m_explorer->session(), SIGNAL(sessionLoaded(QString)),\n this, SLOT(loadExpandData()));\n connect(m_explorer->session(), SIGNAL(aboutToSaveSession()),\n this, SLOT(saveExpandData()));\n\n m_toggleSync = new QToolButton;\n m_toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));\n m_toggleSync->setCheckable(true);\n m_toggleSync->setChecked(autoSynchronization());\n m_toggleSync->setToolTip(tr(\"Synchronize with Editor\"));\n connect(m_toggleSync, SIGNAL(clicked(bool)), this, SLOT(toggleAutoSynchronization()));\n\n setAutoSynchronization(true);\n}\n\nvoid ProjectTreeWidget::disableAutoExpand()\n{\n m_autoExpand = false;\n}\n\nvoid ProjectTreeWidget::loadExpandData()\n{\n m_autoExpand = true;\n QStringList data = m_explorer->session()->value(QLatin1String(\"ProjectTree.ExpandData\")).toStringList();\n recursiveLoadExpandData(m_view->rootIndex(), data.toSet());\n}\n\nvoid ProjectTreeWidget::recursiveLoadExpandData(const QModelIndex &index, const QSet &data)\n{\n if (data.contains(m_model->nodeForIndex(index)->path())) {\n m_view->expand(index);\n int count = m_model->rowCount(index);\n for (int i = 0; i < count; ++i)\n recursiveLoadExpandData(index.child(i, 0), data);\n }\n}\n\nvoid ProjectTreeWidget::saveExpandData()\n{\n QStringList data;\n recursiveSaveExpandData(m_view->rootIndex(), &data);\n \/\/ TODO if there are multiple ProjectTreeWidgets, the last one saves the data\n m_explorer->session()->setValue(QLatin1String(\"ProjectTree.ExpandData\"), data);\n}\n\nvoid ProjectTreeWidget::recursiveSaveExpandData(const QModelIndex &index, QStringList *data)\n{\n Q_ASSERT(data);\n if (m_view->isExpanded(index)) {\n data->append(m_model->nodeForIndex(index)->path());\n int count = m_model->rowCount(index);\n for (int i = 0; i < count; ++i)\n recursiveSaveExpandData(index.child(i, 0), data);\n }\n}\n\nvoid ProjectTreeWidget::foldersAboutToBeRemoved(FolderNode *, const QList &list)\n{\n Node *n = m_explorer->currentNode();\n while (n) {\n if (FolderNode *fn = qobject_cast(n)) {\n if (list.contains(fn)) {\n ProjectNode *pn = n->projectNode();\n \/\/ Make sure the node we are switching too isn't going to be removed also\n while (list.contains(pn))\n pn = pn->parentFolderNode()->projectNode();\n m_explorer->setCurrentNode(pn);\n break;\n }\n }\n n = n->parentFolderNode();\n }\n}\n\nvoid ProjectTreeWidget::filesAboutToBeRemoved(FolderNode *, const QList &list)\n{\n if (FileNode *fileNode = qobject_cast(m_explorer->currentNode())) {\n if (list.contains(fileNode))\n m_explorer->setCurrentNode(fileNode->projectNode());\n }\n}\n\nQToolButton *ProjectTreeWidget::toggleSync()\n{\n return m_toggleSync;\n}\n\nvoid ProjectTreeWidget::toggleAutoSynchronization()\n{\n setAutoSynchronization(!m_autoSync);\n}\n\nbool ProjectTreeWidget::autoSynchronization() const\n{\n return m_autoSync;\n}\n\nvoid ProjectTreeWidget::setAutoSynchronization(bool sync, bool syncNow)\n{\n m_toggleSync->setChecked(sync);\n if (sync == m_autoSync)\n return;\n\n m_autoSync = sync;\n\n if (debug)\n qDebug() << (m_autoSync ? \"Enabling auto synchronization\" : \"Disabling auto synchronization\");\n if (m_autoSync) {\n connect(m_explorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),\n this, SLOT(setCurrentItem(ProjectExplorer::Node*,ProjectExplorer::Project*)));\n if (syncNow)\n setCurrentItem(m_explorer->currentNode(), ProjectExplorerPlugin::currentProject());\n } else {\n disconnect(m_explorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),\n this, SLOT(setCurrentItem(ProjectExplorer::Node*,ProjectExplorer::Project*)));\n }\n}\n\nvoid ProjectTreeWidget::collapseAll()\n{\n m_view->collapseAll();\n}\n\nvoid ProjectTreeWidget::editCurrentItem()\n{\n if (m_view->selectionModel()->currentIndex().isValid())\n m_view->edit(m_view->selectionModel()->currentIndex());\n}\n\nvoid ProjectTreeWidget::setCurrentItem(Node *node, Project *project)\n{\n if (debug)\n qDebug() << \"ProjectTreeWidget::setCurrentItem(\" << (project ? project->displayName() : QLatin1String(\"0\"))\n << \", \" << (node ? node->path() : QLatin1String(\"0\")) << \")\";\n\n if (!project)\n return;\n\n const QModelIndex mainIndex = m_model->indexForNode(node);\n\n if (mainIndex.isValid() && mainIndex != m_view->selectionModel()->currentIndex()) {\n m_view->setCurrentIndex(mainIndex);\n m_view->scrollTo(mainIndex);\n } else {\n if (debug)\n qDebug() << \"clear selection\";\n m_view->clearSelection();\n }\n\n}\n\nvoid ProjectTreeWidget::handleCurrentItemChange(const QModelIndex ¤t)\n{\n Node *node = m_model->nodeForIndex(current);\n \/\/ node might be 0. that's okay\n bool autoSync = autoSynchronization();\n setAutoSynchronization(false);\n m_explorer->setCurrentNode(node);\n setAutoSynchronization(autoSync, false);\n}\n\nvoid ProjectTreeWidget::showContextMenu(const QPoint &pos)\n{\n QModelIndex index = m_view->indexAt(pos);\n Node *node = m_model->nodeForIndex(index);\n m_explorer->showContextMenu(this, m_view->mapToGlobal(pos), node);\n}\n\nvoid ProjectTreeWidget::handleProjectAdded(ProjectExplorer::Project *project)\n{\n Node *node = project->rootProjectNode();\n QModelIndex idx = m_model->indexForNode(node);\n if (m_autoExpand) \/\/ disabled while session restoring\n m_view->setExpanded(idx, true);\n m_view->setCurrentIndex(idx);\n}\n\nvoid ProjectTreeWidget::startupProjectChanged(ProjectExplorer::Project *project)\n{\n if (project) {\n ProjectNode *node = project->rootProjectNode();\n m_model->setStartupProject(node);\n } else {\n m_model->setStartupProject(0);\n }\n}\n\nvoid ProjectTreeWidget::initView()\n{\n QModelIndex sessionIndex = m_model->index(0, 0);\n\n \/\/ hide root folder\n m_view->setRootIndex(sessionIndex);\n\n while (m_model->canFetchMore(sessionIndex))\n m_model->fetchMore(sessionIndex);\n\n \/\/ expand top level projects\n for (int i = 0; i < m_model->rowCount(sessionIndex); ++i)\n m_view->expand(m_model->index(i, 0, sessionIndex));\n\n setCurrentItem(m_explorer->currentNode(), ProjectExplorerPlugin::currentProject());\n}\n\nvoid ProjectTreeWidget::openItem(const QModelIndex &mainIndex)\n{\n Node *node = m_model->nodeForIndex(mainIndex);\n if (node->nodeType() == FileNodeType)\n Core::EditorManager::openEditor(node->path(), Core::Id(), Core::EditorManager::ModeSwitch);\n}\n\nvoid ProjectTreeWidget::setProjectFilter(bool filter)\n{\n m_model->setProjectFilterEnabled(filter);\n m_filterProjectsAction->setChecked(filter);\n}\n\nvoid ProjectTreeWidget::setGeneratedFilesFilter(bool filter)\n{\n m_model->setGeneratedFilesFilterEnabled(filter);\n m_filterGeneratedFilesAction->setChecked(filter);\n}\n\nbool ProjectTreeWidget::generatedFilesFilter()\n{\n return m_model->generatedFilesFilterEnabled();\n}\n\nbool ProjectTreeWidget::projectFilter()\n{\n return m_model->projectFilterEnabled();\n}\n\n\nProjectTreeWidgetFactory::ProjectTreeWidgetFactory()\n{\n}\n\nProjectTreeWidgetFactory::~ProjectTreeWidgetFactory()\n{\n}\n\nQString ProjectTreeWidgetFactory::displayName() const\n{\n return tr(\"Projects\");\n}\n\nint ProjectTreeWidgetFactory::priority() const\n{\n return 100;\n}\n\nCore::Id ProjectTreeWidgetFactory::id() const\n{\n return Core::Id(\"Projects\");\n}\n\nQKeySequence ProjectTreeWidgetFactory::activationSequence() const\n{\n return QKeySequence(Core::UseMacShortcuts ? tr(\"Meta+X\") : tr(\"Alt+X\"));\n}\n\nCore::NavigationView ProjectTreeWidgetFactory::createWidget()\n{\n Core::NavigationView n;\n ProjectTreeWidget *ptw = new ProjectTreeWidget;\n n.widget = ptw;\n\n QToolButton *filter = new QToolButton;\n filter->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));\n filter->setToolTip(tr(\"Filter Tree\"));\n filter->setPopupMode(QToolButton::InstantPopup);\n filter->setProperty(\"noArrow\", true);\n QMenu *filterMenu = new QMenu(filter);\n filterMenu->addAction(ptw->m_filterProjectsAction);\n filterMenu->addAction(ptw->m_filterGeneratedFilesAction);\n filter->setMenu(filterMenu);\n\n n.dockToolBarWidgets << filter << ptw->toggleSync();\n return n;\n}\n\nvoid ProjectTreeWidgetFactory::saveSettings(int position, QWidget *widget)\n{\n ProjectTreeWidget *ptw = qobject_cast(widget);\n Q_ASSERT(ptw);\n QSettings *settings = Core::ICore::settings();\n const QString baseKey = QLatin1String(\"ProjectTreeWidget.\") + QString::number(position);\n settings->setValue(baseKey + QLatin1String(\".ProjectFilter\"), ptw->projectFilter());\n settings->setValue(baseKey + QLatin1String(\".GeneratedFilter\"), ptw->generatedFilesFilter());\n settings->setValue(baseKey + QLatin1String(\".SyncWithEditor\"), ptw->autoSynchronization());\n}\n\nvoid ProjectTreeWidgetFactory::restoreSettings(int position, QWidget *widget)\n{\n ProjectTreeWidget *ptw = qobject_cast(widget);\n Q_ASSERT(ptw);\n QSettings *settings = Core::ICore::settings();\n const QString baseKey = QLatin1String(\"ProjectTreeWidget.\") + QString::number(position);\n ptw->setProjectFilter(settings->value(baseKey + QLatin1String(\".ProjectFilter\"), false).toBool());\n ptw->setGeneratedFilesFilter(settings->value(baseKey + QLatin1String(\".GeneratedFilter\"), true).toBool());\n ptw->setAutoSynchronization(settings->value(baseKey + QLatin1String(\".SyncWithEditor\"), true).toBool());\n}\nProjectTreeWidget: Use Core namespace\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"projecttreewidget.h\"\n\n#include \"projectexplorer.h\"\n#include \"projectnodes.h\"\n#include \"project.h\"\n#include \"session.h\"\n#include \"projectexplorerconstants.h\"\n#include \"projectmodels.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Core;\nusing namespace ProjectExplorer;\nusing namespace ProjectExplorer::Internal;\n\nnamespace {\n bool debug = false;\n}\n\nclass ProjectTreeView : public Utils::NavigationTreeView\n{\npublic:\n ProjectTreeView()\n {\n setEditTriggers(QAbstractItemView::EditKeyPressed);\n setContextMenuPolicy(Qt::CustomContextMenu);\n m_context = new IContext(this);\n m_context->setContext(Context(ProjectExplorer::Constants::C_PROJECT_TREE));\n m_context->setWidget(this);\n ICore::addContextObject(m_context);\n }\n ~ProjectTreeView()\n {\n ICore::removeContextObject(m_context);\n delete m_context;\n }\n\nprivate:\n IContext *m_context;\n};\n\n\/*!\n \/class ProjectTreeWidget\n\n Shows the projects in form of a tree.\n *\/\nProjectTreeWidget::ProjectTreeWidget(QWidget *parent)\n : QWidget(parent),\n m_explorer(ProjectExplorerPlugin::instance()),\n m_view(0),\n m_model(0),\n m_filterProjectsAction(0),\n m_autoSync(false),\n m_autoExpand(true)\n{\n m_model = new FlatModel(m_explorer->session()->sessionNode(), this);\n Project *pro = m_explorer->session()->startupProject();\n if (pro)\n m_model->setStartupProject(pro->rootProjectNode());\n NodesWatcher *watcher = new NodesWatcher(this);\n m_explorer->session()->sessionNode()->registerWatcher(watcher);\n\n connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode*,QList)),\n this, SLOT(foldersAboutToBeRemoved(FolderNode*,QList)));\n connect(watcher, SIGNAL(filesAboutToBeRemoved(FolderNode*,QList)),\n this, SLOT(filesAboutToBeRemoved(FolderNode*,QList)));\n\n m_view = new ProjectTreeView;\n m_view->setModel(m_model);\n setFocusProxy(m_view);\n initView();\n\n QVBoxLayout *layout = new QVBoxLayout();\n layout->addWidget(m_view);\n layout->setContentsMargins(0, 0, 0, 0);\n setLayout(layout);\n\n m_filterProjectsAction = new QAction(tr(\"Simplify Tree\"), this);\n m_filterProjectsAction->setCheckable(true);\n m_filterProjectsAction->setChecked(false); \/\/ default is the traditional complex tree\n connect(m_filterProjectsAction, SIGNAL(toggled(bool)), this, SLOT(setProjectFilter(bool)));\n\n m_filterGeneratedFilesAction = new QAction(tr(\"Hide Generated Files\"), this);\n m_filterGeneratedFilesAction->setCheckable(true);\n m_filterGeneratedFilesAction->setChecked(true);\n connect(m_filterGeneratedFilesAction, SIGNAL(toggled(bool)), this, SLOT(setGeneratedFilesFilter(bool)));\n\n \/\/ connections\n connect(m_model, SIGNAL(modelReset()),\n this, SLOT(initView()));\n connect(m_view, SIGNAL(activated(QModelIndex)),\n this, SLOT(openItem(QModelIndex)));\n connect(m_view->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n this, SLOT(handleCurrentItemChange(QModelIndex)));\n connect(m_view, SIGNAL(customContextMenuRequested(QPoint)),\n this, SLOT(showContextMenu(QPoint)));\n connect(m_explorer->session(), SIGNAL(singleProjectAdded(ProjectExplorer::Project*)),\n this, SLOT(handleProjectAdded(ProjectExplorer::Project*)));\n connect(m_explorer->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),\n this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));\n\n connect(m_explorer->session(), SIGNAL(aboutToLoadSession(QString)),\n this, SLOT(disableAutoExpand()));\n connect(m_explorer->session(), SIGNAL(sessionLoaded(QString)),\n this, SLOT(loadExpandData()));\n connect(m_explorer->session(), SIGNAL(aboutToSaveSession()),\n this, SLOT(saveExpandData()));\n\n m_toggleSync = new QToolButton;\n m_toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));\n m_toggleSync->setCheckable(true);\n m_toggleSync->setChecked(autoSynchronization());\n m_toggleSync->setToolTip(tr(\"Synchronize with Editor\"));\n connect(m_toggleSync, SIGNAL(clicked(bool)), this, SLOT(toggleAutoSynchronization()));\n\n setAutoSynchronization(true);\n}\n\nvoid ProjectTreeWidget::disableAutoExpand()\n{\n m_autoExpand = false;\n}\n\nvoid ProjectTreeWidget::loadExpandData()\n{\n m_autoExpand = true;\n QStringList data = m_explorer->session()->value(QLatin1String(\"ProjectTree.ExpandData\")).toStringList();\n recursiveLoadExpandData(m_view->rootIndex(), data.toSet());\n}\n\nvoid ProjectTreeWidget::recursiveLoadExpandData(const QModelIndex &index, const QSet &data)\n{\n if (data.contains(m_model->nodeForIndex(index)->path())) {\n m_view->expand(index);\n int count = m_model->rowCount(index);\n for (int i = 0; i < count; ++i)\n recursiveLoadExpandData(index.child(i, 0), data);\n }\n}\n\nvoid ProjectTreeWidget::saveExpandData()\n{\n QStringList data;\n recursiveSaveExpandData(m_view->rootIndex(), &data);\n \/\/ TODO if there are multiple ProjectTreeWidgets, the last one saves the data\n m_explorer->session()->setValue(QLatin1String(\"ProjectTree.ExpandData\"), data);\n}\n\nvoid ProjectTreeWidget::recursiveSaveExpandData(const QModelIndex &index, QStringList *data)\n{\n Q_ASSERT(data);\n if (m_view->isExpanded(index)) {\n data->append(m_model->nodeForIndex(index)->path());\n int count = m_model->rowCount(index);\n for (int i = 0; i < count; ++i)\n recursiveSaveExpandData(index.child(i, 0), data);\n }\n}\n\nvoid ProjectTreeWidget::foldersAboutToBeRemoved(FolderNode *, const QList &list)\n{\n Node *n = m_explorer->currentNode();\n while (n) {\n if (FolderNode *fn = qobject_cast(n)) {\n if (list.contains(fn)) {\n ProjectNode *pn = n->projectNode();\n \/\/ Make sure the node we are switching too isn't going to be removed also\n while (list.contains(pn))\n pn = pn->parentFolderNode()->projectNode();\n m_explorer->setCurrentNode(pn);\n break;\n }\n }\n n = n->parentFolderNode();\n }\n}\n\nvoid ProjectTreeWidget::filesAboutToBeRemoved(FolderNode *, const QList &list)\n{\n if (FileNode *fileNode = qobject_cast(m_explorer->currentNode())) {\n if (list.contains(fileNode))\n m_explorer->setCurrentNode(fileNode->projectNode());\n }\n}\n\nQToolButton *ProjectTreeWidget::toggleSync()\n{\n return m_toggleSync;\n}\n\nvoid ProjectTreeWidget::toggleAutoSynchronization()\n{\n setAutoSynchronization(!m_autoSync);\n}\n\nbool ProjectTreeWidget::autoSynchronization() const\n{\n return m_autoSync;\n}\n\nvoid ProjectTreeWidget::setAutoSynchronization(bool sync, bool syncNow)\n{\n m_toggleSync->setChecked(sync);\n if (sync == m_autoSync)\n return;\n\n m_autoSync = sync;\n\n if (debug)\n qDebug() << (m_autoSync ? \"Enabling auto synchronization\" : \"Disabling auto synchronization\");\n if (m_autoSync) {\n connect(m_explorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),\n this, SLOT(setCurrentItem(ProjectExplorer::Node*,ProjectExplorer::Project*)));\n if (syncNow)\n setCurrentItem(m_explorer->currentNode(), ProjectExplorerPlugin::currentProject());\n } else {\n disconnect(m_explorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),\n this, SLOT(setCurrentItem(ProjectExplorer::Node*,ProjectExplorer::Project*)));\n }\n}\n\nvoid ProjectTreeWidget::collapseAll()\n{\n m_view->collapseAll();\n}\n\nvoid ProjectTreeWidget::editCurrentItem()\n{\n if (m_view->selectionModel()->currentIndex().isValid())\n m_view->edit(m_view->selectionModel()->currentIndex());\n}\n\nvoid ProjectTreeWidget::setCurrentItem(Node *node, Project *project)\n{\n if (debug)\n qDebug() << \"ProjectTreeWidget::setCurrentItem(\" << (project ? project->displayName() : QLatin1String(\"0\"))\n << \", \" << (node ? node->path() : QLatin1String(\"0\")) << \")\";\n\n if (!project)\n return;\n\n const QModelIndex mainIndex = m_model->indexForNode(node);\n\n if (mainIndex.isValid() && mainIndex != m_view->selectionModel()->currentIndex()) {\n m_view->setCurrentIndex(mainIndex);\n m_view->scrollTo(mainIndex);\n } else {\n if (debug)\n qDebug() << \"clear selection\";\n m_view->clearSelection();\n }\n\n}\n\nvoid ProjectTreeWidget::handleCurrentItemChange(const QModelIndex ¤t)\n{\n Node *node = m_model->nodeForIndex(current);\n \/\/ node might be 0. that's okay\n bool autoSync = autoSynchronization();\n setAutoSynchronization(false);\n m_explorer->setCurrentNode(node);\n setAutoSynchronization(autoSync, false);\n}\n\nvoid ProjectTreeWidget::showContextMenu(const QPoint &pos)\n{\n QModelIndex index = m_view->indexAt(pos);\n Node *node = m_model->nodeForIndex(index);\n m_explorer->showContextMenu(this, m_view->mapToGlobal(pos), node);\n}\n\nvoid ProjectTreeWidget::handleProjectAdded(ProjectExplorer::Project *project)\n{\n Node *node = project->rootProjectNode();\n QModelIndex idx = m_model->indexForNode(node);\n if (m_autoExpand) \/\/ disabled while session restoring\n m_view->setExpanded(idx, true);\n m_view->setCurrentIndex(idx);\n}\n\nvoid ProjectTreeWidget::startupProjectChanged(ProjectExplorer::Project *project)\n{\n if (project) {\n ProjectNode *node = project->rootProjectNode();\n m_model->setStartupProject(node);\n } else {\n m_model->setStartupProject(0);\n }\n}\n\nvoid ProjectTreeWidget::initView()\n{\n QModelIndex sessionIndex = m_model->index(0, 0);\n\n \/\/ hide root folder\n m_view->setRootIndex(sessionIndex);\n\n while (m_model->canFetchMore(sessionIndex))\n m_model->fetchMore(sessionIndex);\n\n \/\/ expand top level projects\n for (int i = 0; i < m_model->rowCount(sessionIndex); ++i)\n m_view->expand(m_model->index(i, 0, sessionIndex));\n\n setCurrentItem(m_explorer->currentNode(), ProjectExplorerPlugin::currentProject());\n}\n\nvoid ProjectTreeWidget::openItem(const QModelIndex &mainIndex)\n{\n Node *node = m_model->nodeForIndex(mainIndex);\n if (node->nodeType() == FileNodeType)\n EditorManager::openEditor(node->path(), Id(), EditorManager::ModeSwitch);\n}\n\nvoid ProjectTreeWidget::setProjectFilter(bool filter)\n{\n m_model->setProjectFilterEnabled(filter);\n m_filterProjectsAction->setChecked(filter);\n}\n\nvoid ProjectTreeWidget::setGeneratedFilesFilter(bool filter)\n{\n m_model->setGeneratedFilesFilterEnabled(filter);\n m_filterGeneratedFilesAction->setChecked(filter);\n}\n\nbool ProjectTreeWidget::generatedFilesFilter()\n{\n return m_model->generatedFilesFilterEnabled();\n}\n\nbool ProjectTreeWidget::projectFilter()\n{\n return m_model->projectFilterEnabled();\n}\n\n\nProjectTreeWidgetFactory::ProjectTreeWidgetFactory()\n{\n}\n\nProjectTreeWidgetFactory::~ProjectTreeWidgetFactory()\n{\n}\n\nQString ProjectTreeWidgetFactory::displayName() const\n{\n return tr(\"Projects\");\n}\n\nint ProjectTreeWidgetFactory::priority() const\n{\n return 100;\n}\n\nId ProjectTreeWidgetFactory::id() const\n{\n return Id(\"Projects\");\n}\n\nQKeySequence ProjectTreeWidgetFactory::activationSequence() const\n{\n return QKeySequence(UseMacShortcuts ? tr(\"Meta+X\") : tr(\"Alt+X\"));\n}\n\nNavigationView ProjectTreeWidgetFactory::createWidget()\n{\n NavigationView n;\n ProjectTreeWidget *ptw = new ProjectTreeWidget;\n n.widget = ptw;\n\n QToolButton *filter = new QToolButton;\n filter->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));\n filter->setToolTip(tr(\"Filter Tree\"));\n filter->setPopupMode(QToolButton::InstantPopup);\n filter->setProperty(\"noArrow\", true);\n QMenu *filterMenu = new QMenu(filter);\n filterMenu->addAction(ptw->m_filterProjectsAction);\n filterMenu->addAction(ptw->m_filterGeneratedFilesAction);\n filter->setMenu(filterMenu);\n\n n.dockToolBarWidgets << filter << ptw->toggleSync();\n return n;\n}\n\nvoid ProjectTreeWidgetFactory::saveSettings(int position, QWidget *widget)\n{\n ProjectTreeWidget *ptw = qobject_cast(widget);\n Q_ASSERT(ptw);\n QSettings *settings = ICore::settings();\n const QString baseKey = QLatin1String(\"ProjectTreeWidget.\") + QString::number(position);\n settings->setValue(baseKey + QLatin1String(\".ProjectFilter\"), ptw->projectFilter());\n settings->setValue(baseKey + QLatin1String(\".GeneratedFilter\"), ptw->generatedFilesFilter());\n settings->setValue(baseKey + QLatin1String(\".SyncWithEditor\"), ptw->autoSynchronization());\n}\n\nvoid ProjectTreeWidgetFactory::restoreSettings(int position, QWidget *widget)\n{\n ProjectTreeWidget *ptw = qobject_cast(widget);\n Q_ASSERT(ptw);\n QSettings *settings = ICore::settings();\n const QString baseKey = QLatin1String(\"ProjectTreeWidget.\") + QString::number(position);\n ptw->setProjectFilter(settings->value(baseKey + QLatin1String(\".ProjectFilter\"), false).toBool());\n ptw->setGeneratedFilesFilter(settings->value(baseKey + QLatin1String(\".GeneratedFilter\"), true).toBool());\n ptw->setAutoSynchronization(settings->value(baseKey + QLatin1String(\".SyncWithEditor\"), true).toBool());\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014-2021 AscEmu Team \n * Copyright (c) 2008-2015 Sun++ Team \n * Copyright (C) 2008-2012 ArcEmu Team \n * Copyright (C) 2008 WEmu Team\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"Setup.h\"\n#include \"Server\/Script\/CreatureAIScript.h\"\n\nclass TheDormantShade : public QuestScript\n{\npublic:\n void OnQuestComplete(Player* mTarget, QuestLogEntry* \/*qLogEntry*\/) override\n {\n Creature* creat = mTarget->GetMapMgr()->GetInterface()->SpawnCreature(1946, 2467.314f, 14.8471f, 23.5950f, 0, true, false, 0, 0);\n creat->Despawn(60000, 0);\n creat->sendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, \"You have disturbed my rest. Now face my wrath!\");\n }\n};\n\nclass CalvinMontague : public CreatureAIScript\n{\npublic:\n static CreatureAIScript* Create(Creature* c) { return new CalvinMontague(c); }\n explicit CalvinMontague(Creature* pCreature) : CreatureAIScript(pCreature) {}\n\n void OnLoad() override\n {\n getCreature()->SetFaction(68);\n getCreature()->setStandState(STANDSTATE_STAND);\n }\n\n void OnDamageTaken(Unit* mAttacker, uint32_t \/*fAmount*\/) override\n {\n if (getCreature()->getHealthPct() < 10)\n {\n if (mAttacker->isPlayer())\n {\n getCreature()->addUnitFlags(UNIT_FLAG_NOT_SELECTABLE);\n if (auto* questLog = static_cast(mAttacker)->getQuestLogByQuestId(590))\n {\n questLog->sendQuestComplete();\n setScriptPhase(2);\n }\n }\n }\n }\n\n void OnScriptPhaseChange(uint32_t phase) override\n {\n if (phase == 2)\n {\n getCreature()->sendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, \"Okay, okay! Enough fighting.\");\n getCreature()->RemoveNegativeAuras();\n getCreature()->SetFaction(68);\n getCreature()->setStandState(STANDSTATE_SIT);\n getCreature()->castSpell(getCreature(), sSpellMgr.getSpellInfo(433), true);\n sEventMgr.AddEvent(static_cast(getCreature()), &Unit::setStandState, (uint8_t)STANDSTATE_STAND, EVENT_CREATURE_UPDATE, 18000, 0, 1);\n getCreature()->getThreatManager().clearAllThreat();\n getCreature()->getThreatManager().removeMeFromThreatLists();\n getCreature()->GetAIInterface()->handleEvent(EVENT_LEAVECOMBAT, getCreature(), 0);\n _setMeleeDisabled(true);\n getCreature()->GetAIInterface()->setAllowedToEnterCombat(false);\n getCreature()->removeUnitFlags(UNIT_FLAG_NOT_SELECTABLE);\n }\n }\n};\n\nclass ARoguesDeal : public QuestScript\n{\npublic:\n void OnQuestStart(Player* mTarget, QuestLogEntry* \/*qLogEntry*\/) override\n {\n float SSX = mTarget->GetPositionX();\n float SSY = mTarget->GetPositionY();\n float SSZ = mTarget->GetPositionZ();\n\n Creature* Dashel = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 6784);\n\n if (Dashel == nullptr)\n return;\n\n Dashel->SetFaction(28);\n Dashel->GetAIInterface()->setMeleeDisabled(false);\n Dashel->GetAIInterface()->setAllowedToEnterCombat(true);\n }\n};\n\nclass Zealot : public CreatureAIScript\n{\npublic:\n static CreatureAIScript* Create(Creature* c) { return new Zealot(c); }\n explicit Zealot(Creature* pCreature) : CreatureAIScript(pCreature) {}\n\n void OnReachWP(uint32_t type, uint32_t iWaypointId) override\n {\n if (type != WAYPOINT_MOTION_TYPE)\n return;\n\n if (!getCreature()->HasAura(3287))\n return;\n if (iWaypointId == 2)\n {\n getCreature()->sendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, \"My mind. . .me flesh. . .I'm. . .rotting. . . .!\");\n }\n\n if (iWaypointId == 7)\n {\n getCreature()->castSpell(getCreature(), sSpellMgr.getSpellInfo(5), true);\n }\n }\n};\n\nvoid SetupTirisfalGlades(ScriptMgr* mgr)\n{\n mgr->register_quest_script(410, new TheDormantShade());\n mgr->register_creature_script(6784, &CalvinMontague::Create);\n mgr->register_quest_script(590, new ARoguesDeal());\n mgr->register_creature_script(1931, &Zealot::Create);\n}\nUndeadStartQuest\/*\n * Copyright (c) 2014-2021 AscEmu Team \n * Copyright (c) 2008-2015 Sun++ Team \n * Copyright (C) 2008-2012 ArcEmu Team \n * Copyright (C) 2008 WEmu Team\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"Setup.h\"\n#include \"Server\/Script\/CreatureAIScript.h\"\n\nclass TheDormantShade : public QuestScript\n{\npublic:\n void OnQuestComplete(Player* mTarget, QuestLogEntry* \/*qLogEntry*\/) override\n {\n Creature* creat = mTarget->GetMapMgr()->GetInterface()->SpawnCreature(1946, 2467.314f, 14.8471f, 23.5950f, 0, true, false, 0, 0);\n creat->Despawn(60000, 0);\n creat->sendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, \"You have disturbed my rest. Now face my wrath!\");\n }\n};\n\nclass CalvinMontague : public CreatureAIScript\n{\npublic:\n static CreatureAIScript* Create(Creature* c) { return new CalvinMontague(c); }\n explicit CalvinMontague(Creature* pCreature) : CreatureAIScript(pCreature) {}\n\n void OnLoad() override\n {\n getCreature()->SetFaction(68);\n getCreature()->setStandState(STANDSTATE_STAND);\n }\n\n void OnDamageTaken(Unit* mAttacker, uint32_t \/*fAmount*\/) override\n {\n if (getCreature()->getHealthPct() < 10)\n {\n if (mAttacker->isPlayer())\n {\n getCreature()->addUnitFlags(UNIT_FLAG_NOT_SELECTABLE);\n if (auto* questLog = static_cast(mAttacker)->getQuestLogByQuestId(590))\n {\n questLog->sendQuestComplete();\n setScriptPhase(2);\n }\n }\n }\n }\n\n void OnScriptPhaseChange(uint32_t phase) override\n {\n if (phase == 2)\n {\n getCreature()->sendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, \"Okay, okay! Enough fighting.\");\n getCreature()->RemoveNegativeAuras();\n getCreature()->SetFaction(68);\n getCreature()->setStandState(STANDSTATE_SIT);\n getCreature()->castSpell(getCreature(), sSpellMgr.getSpellInfo(433), true);\n sEventMgr.AddEvent(static_cast(getCreature()), &Unit::setStandState, (uint8_t)STANDSTATE_STAND, EVENT_CREATURE_UPDATE, 18000, 0, 1);\n getCreature()->getThreatManager().clearAllThreat();\n getCreature()->getThreatManager().removeMeFromThreatLists();\n getCreature()->GetAIInterface()->handleEvent(EVENT_LEAVECOMBAT, getCreature(), 0);\n _setMeleeDisabled(true);\n getCreature()->GetAIInterface()->setAllowedToEnterCombat(false);\n getCreature()->removeUnitFlags(UNIT_FLAG_NOT_SELECTABLE);\n }\n }\n};\n\nclass ARoguesDeal : public QuestScript\n{\npublic:\n void OnQuestStart(Player* mTarget, QuestLogEntry* \/*qLogEntry*\/) override\n {\n float SSX = mTarget->GetPositionX();\n float SSY = mTarget->GetPositionY();\n float SSZ = mTarget->GetPositionZ();\n\n Creature* Dashel = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 6784);\n\n if (Dashel == nullptr)\n return;\n\n Dashel->SetFaction(28);\n Dashel->GetAIInterface()->setMeleeDisabled(false);\n Dashel->GetAIInterface()->setAllowedToEnterCombat(true);\n }\n};\n\nclass Zealot : public CreatureAIScript\n{\npublic:\n static CreatureAIScript* Create(Creature* c) { return new Zealot(c); }\n explicit Zealot(Creature* pCreature) : CreatureAIScript(pCreature) {}\n\n void OnReachWP(uint32_t type, uint32_t iWaypointId) override\n {\n if (type != WAYPOINT_MOTION_TYPE)\n return;\n\n if (!getCreature()->HasAura(3287))\n return;\n if (iWaypointId == 2)\n {\n getCreature()->sendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, \"My mind. . .me flesh. . .I'm. . .rotting. . . .!\");\n }\n\n if (iWaypointId == 7)\n {\n getCreature()->castSpell(getCreature(), sSpellMgr.getSpellInfo(5), true);\n }\n }\n};\n\nclass FreshOutOfTheGrave : public QuestScript\n{\npublic:\n void OnQuestStart(Player* mTarget, QuestLogEntry* \/*qLogEntry*\/) override\n {\n uint32_t rigorMortisSpell = 73523;\n uint32_t ressurrectSpell = 73524;\n\n \/\/ Ressurect our Player\n mTarget->castSpell(mTarget, sSpellMgr.getSpellInfo(ressurrectSpell), true);\n\n \/\/ Remove death Aura\n if (mTarget->HasAura(rigorMortisSpell))\n {\n mTarget->removeAllAurasById(rigorMortisSpell);\n mTarget->removeSpell(rigorMortisSpell, false, false, 0);\n }\n }\n};\n\nvoid SetupTirisfalGlades(ScriptMgr* mgr)\n{\n mgr->register_quest_script(410, new TheDormantShade());\n mgr->register_creature_script(6784, &CalvinMontague::Create);\n mgr->register_quest_script(590, new ARoguesDeal());\n mgr->register_creature_script(1931, &Zealot::Create);\n mgr->register_quest_script(24959, new FreshOutOfTheGrave());\n}\n<|endoftext|>"} {"text":"#include \"precompiled.h\"\r\n\r\nusing namespace mix;\r\n\r\nnamespace {\r\n\r\nclass STA_TAOCP_Book_Test : public ::testing::Test\r\n{\r\nprivate:\r\n\tvoid SetUp() override\r\n\t{\r\n\t\tdest_address = 2000;\r\n\t\tdest_cell.set_sign(Sign::Negative);\r\n\t\tdest_cell.set_byte(1, 1);\r\n\t\tdest_cell.set_byte(2, 2);\r\n\t\tdest_cell.set_byte(3, 3);\r\n\t\tdest_cell.set_byte(4, 4);\r\n\t\tdest_cell.set_byte(5, 5);\r\n\r\n\t\tmix.set_memory(dest_address, dest_cell);\r\n\r\n\t\tRegister ra;\r\n\t\tra.set_sign(Sign::Positive);\r\n\t\tra.set_byte(1, 6);\r\n\t\tra.set_byte(2, 7);\r\n\t\tra.set_byte(3, 8);\r\n\t\tra.set_byte(4, 9);\r\n\t\tra.set_byte(5, 10);\r\n\r\n\t\tmix.set_ra(ra);\r\n\t}\r\n\r\nprotected:\r\n\tconst Word& dest_word()\r\n\t{\r\n#if defined(__clang__)\r\n# pragma clang diagnostic push\r\n\t\/\/ implicit conversion loses integer precision\r\n# pragma clang diagnostic ignored \"-Wshorten-64-to-32\"\r\n#endif\r\n\t\treturn mix.memory(static_cast(dest_address));\r\n#if defined(__clang__)\r\n# pragma clang diagnostic pop\r\n#endif\r\n\t}\r\n\r\nprotected:\r\n\tComputer mix;\r\n\tWord dest_cell;\r\n\tint dest_address;\r\n};\r\n} \/\/ namespace\r\n\r\n\/\/ STA 2000\r\nTEST_F(STA_TAOCP_Book_Test, Default_STA_Stores_All_Word)\r\n{\r\n\tmix.execute(MakeSTA(dest_address));\r\n\tASSERT_EQ(mix.ra(), dest_word());\r\n}\r\n\r\n\/\/ STA 2000(1:5)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_All_BytesField_Gets_All_Except_Sign)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{1, 5}));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 6);\r\n\tASSERT_EQ(dest_word().byte(2), 7);\r\n\tASSERT_EQ(dest_word().byte(3), 8);\r\n\tASSERT_EQ(dest_word().byte(4), 9);\r\n\tASSERT_EQ(dest_word().byte(5), 10);\r\n}\r\n\r\n\/\/ STA 2000(5:5)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_RightMost_Field_Sets_Byte_Without_Shift)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{5, 5}));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 1);\r\n\tASSERT_EQ(dest_word().byte(2), 2);\r\n\tASSERT_EQ(dest_word().byte(3), 3);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 10);\r\n}\r\n\r\n\/\/ STA 2000(2:2)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_One_ByteField_Length_Gets_Value_From_5_RA_Byte)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{2, 2}));\r\n\tASSERT_EQ(mix.ra().byte(5), dest_word().byte(2));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 1);\r\n\tASSERT_EQ(dest_word().byte(2), 10);\r\n\tASSERT_EQ(dest_word().byte(3), 3);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 5);\r\n}\r\n\r\n\/\/ STA 2000(2:3)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_Two_ByteField_Length_Gets_Value_From_Last_Two_RA_Bytes)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{2, 3}));\r\n\tASSERT_EQ(mix.ra().byte(5), dest_word().byte(3));\r\n\tASSERT_EQ(mix.ra().byte(4), dest_word().byte(2));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 1);\r\n\tASSERT_EQ(dest_word().byte(2), 9);\r\n\tASSERT_EQ(dest_word().byte(3), 10);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 5);\r\n}\r\n\r\n\/\/ STA 2000(0:1)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_One_Sign_ByteField_Gets_Value_From_5_RA_Byte_And_Its_Sign)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{0, 1}));\r\n\tASSERT_EQ(mix.ra().byte(5), dest_word().byte(1));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Positive);\r\n\tASSERT_EQ(dest_word().byte(1), 10);\r\n\tASSERT_EQ(dest_word().byte(2), 2);\r\n\tASSERT_EQ(dest_word().byte(3), 3);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 5);\r\n}\r\nRemove useless static_cast in test#include \"precompiled.h\"\r\n\r\nusing namespace mix;\r\n\r\nnamespace {\r\n\r\nclass STA_TAOCP_Book_Test : public ::testing::Test\r\n{\r\nprivate:\r\n\tvoid SetUp() override\r\n\t{\r\n\t\tdest_address = 2000;\r\n\t\tdest_cell.set_sign(Sign::Negative);\r\n\t\tdest_cell.set_byte(1, 1);\r\n\t\tdest_cell.set_byte(2, 2);\r\n\t\tdest_cell.set_byte(3, 3);\r\n\t\tdest_cell.set_byte(4, 4);\r\n\t\tdest_cell.set_byte(5, 5);\r\n\r\n\t\tmix.set_memory(dest_address, dest_cell);\r\n\r\n\t\tRegister ra;\r\n\t\tra.set_sign(Sign::Positive);\r\n\t\tra.set_byte(1, 6);\r\n\t\tra.set_byte(2, 7);\r\n\t\tra.set_byte(3, 8);\r\n\t\tra.set_byte(4, 9);\r\n\t\tra.set_byte(5, 10);\r\n\r\n\t\tmix.set_ra(ra);\r\n\t}\r\n\r\nprotected:\r\n\tconst Word& dest_word()\r\n\t{\r\n\t\treturn mix.memory(dest_address);\r\n\t}\r\n\r\nprotected:\r\n\tComputer mix;\r\n\tWord dest_cell;\r\n\tint dest_address;\r\n};\r\n} \/\/ namespace\r\n\r\n\/\/ STA 2000\r\nTEST_F(STA_TAOCP_Book_Test, Default_STA_Stores_All_Word)\r\n{\r\n\tmix.execute(MakeSTA(dest_address));\r\n\tASSERT_EQ(mix.ra(), dest_word());\r\n}\r\n\r\n\/\/ STA 2000(1:5)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_All_BytesField_Gets_All_Except_Sign)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{1, 5}));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 6);\r\n\tASSERT_EQ(dest_word().byte(2), 7);\r\n\tASSERT_EQ(dest_word().byte(3), 8);\r\n\tASSERT_EQ(dest_word().byte(4), 9);\r\n\tASSERT_EQ(dest_word().byte(5), 10);\r\n}\r\n\r\n\/\/ STA 2000(5:5)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_RightMost_Field_Sets_Byte_Without_Shift)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{5, 5}));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 1);\r\n\tASSERT_EQ(dest_word().byte(2), 2);\r\n\tASSERT_EQ(dest_word().byte(3), 3);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 10);\r\n}\r\n\r\n\/\/ STA 2000(2:2)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_One_ByteField_Length_Gets_Value_From_5_RA_Byte)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{2, 2}));\r\n\tASSERT_EQ(mix.ra().byte(5), dest_word().byte(2));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 1);\r\n\tASSERT_EQ(dest_word().byte(2), 10);\r\n\tASSERT_EQ(dest_word().byte(3), 3);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 5);\r\n}\r\n\r\n\/\/ STA 2000(2:3)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_Two_ByteField_Length_Gets_Value_From_Last_Two_RA_Bytes)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{2, 3}));\r\n\tASSERT_EQ(mix.ra().byte(5), dest_word().byte(3));\r\n\tASSERT_EQ(mix.ra().byte(4), dest_word().byte(2));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Negative);\r\n\tASSERT_EQ(dest_word().byte(1), 1);\r\n\tASSERT_EQ(dest_word().byte(2), 9);\r\n\tASSERT_EQ(dest_word().byte(3), 10);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 5);\r\n}\r\n\r\n\/\/ STA 2000(0:1)\r\nTEST_F(STA_TAOCP_Book_Test, STA_With_One_Sign_ByteField_Gets_Value_From_5_RA_Byte_And_Its_Sign)\r\n{\r\n\tmix.execute(MakeSTA(dest_address, WordField{0, 1}));\r\n\tASSERT_EQ(mix.ra().byte(5), dest_word().byte(1));\r\n\r\n\tASSERT_EQ(dest_word().sign(), Sign::Positive);\r\n\tASSERT_EQ(dest_word().byte(1), 10);\r\n\tASSERT_EQ(dest_word().byte(2), 2);\r\n\tASSERT_EQ(dest_word().byte(3), 3);\r\n\tASSERT_EQ(dest_word().byte(4), 4);\r\n\tASSERT_EQ(dest_word().byte(5), 5);\r\n}\r\n<|endoftext|>"} {"text":"\n#include \"geometry.hpp\"\n#include \"quadric.hpp\"\n#include \"line.hpp\"\n#include \"accurate_intersections.hpp\"\n#include \"quadric_classify.hpp\"\n#include \"timer.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nstruct GlobalVars {\n bool run = true;\n} globals;\n\nvoid sigInt(int signum) { globals.run = false; }\n\ntemplate \nstd::list> parseQuadrics(\n const char *fname) {\n std::ifstream file(fname);\n if(!file.is_open()) {\n return std::list>();\n }\n using Qf = Geometry::Quadric;\n int qtypeCount[QuadricClassify::QUADT_ERRORINVALID];\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++)\n qtypeCount[i] = 0;\n std::list quads;\n int imQuads = 0;\n int numQuads = 0;\n while(!file.eof()) {\n Qf q;\n file >> q;\n QuadricClassify::QuadType type =\n QuadricClassify::classifyQuadric(q);\n if(!QuadricClassify::isImaginary(type) &&\n type != QuadricClassify::QUADT_ERROR &&\n type != QuadricClassify::QUADT_DEGENERATE &&\n type != QuadricClassify::QUADT_ERRORINVALID) {\n quads.push_back(q);\n qtypeCount[type]++;\n } else {\n std::cout << \"Quadric \" << numQuads\n << \" is invalid, returned type \"\n << QuadricClassify::QuadTypeNames[type]\n << \"\\n\";\n imQuads++;\n }\n numQuads++;\n }\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++) {\n std::cout << qtypeCount[i] << \" \"\n << QuadricClassify::QuadTypeNames[i] << \"\\n\";\n }\n return quads;\n}\n\nbool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) {\n \/* Use a heuristic on truth to determine whether adjacent\n * intersections occur at the same place.\n * This will basically be a threshold on the largest\n * different bit in the mantissa.\n *\/\n \/* A relative heuristic does not work when one (or both!)\n * is 0 *\/\n if(int1 == 0.0 || int2 == 0.0) {\n constexpr const double eps = 0.000001;\n return (mpfr::fabs(int1 - int2) < eps);\n }\n mpfr::mpreal largest =\n mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2));\n mp_exp_t largestExp = largest.get_exp();\n mpfr::mpreal diff = mpfr::fabs(int1 - int2);\n int p1 = int1.getPrecision(), p2 = int2.getPrecision();\n int minPrec = std::min(p1, p2);\n mp_exp_t maxExp = largestExp - minPrec * 1 \/ 48,\n diffExp = diff.get_exp();\n return maxExp >= diffExp;\n}\n\ntemplate \nbool validateResults(ListFP &inter, ListMP &truth) {\n auto j = truth->begin();\n for(auto i = inter->begin();\n i != inter->end() || j != truth->end();) {\n \/* First determine the length of the region of equal\n * intersections.\n * Then verify there's an equal number of\n * intersections in the approximately equal range and\n * that they correspond to the correct intersections.\n * If not, then print the intersection\n *\/\n if(j != truth->end()) {\n \/* Create the region boundaries [sameBeg, sameEnd).\n * These are intersections which are probably the same\n *\/\n auto sameBeg = j;\n auto sameEnd = j;\n int regLen = 0;\n while(sameEnd != truth->end() &&\n isSameInt(j->intPos, sameEnd->intPos)) {\n sameEnd++;\n regLen++;\n }\n \/* Increment i until it's not found in the region *\/\n int numInRegion = 0;\n bool isInRegion = true;\n while(i != inter->end() && isInRegion &&\n numInRegion < regLen) {\n j = sameBeg;\n while(j != sameEnd && i->q != j->q) j++;\n \/* sameEnd is not in the region, so if j reaches it,\n * i isn't in the region *\/\n if(j == sameEnd) {\n isInRegion = false;\n } else {\n i++;\n numInRegion++;\n }\n }\n \/* i isn't in the region.\n * Verify all elements in the region were used *\/\n if(regLen != numInRegion) {\n return false;\n }\n j = sameEnd;\n } else {\n int numRemaining = 0;\n while(i != inter->end()) {\n i++;\n numRemaining++;\n }\n return false;\n }\n }\n return true;\n}\n\ntemplate \nint countIP(List inter) {\n int numIP = 0;\n for(auto i : *inter) numIP += i.incPrecCount();\n return numIP;\n}\n\ntemplate \nusing randLineGen =\n Geometry::Line (*)(std::mt19937_64 &rng);\n\ntemplate \nstd::shared_ptr>> __attribute__((noinline))\nrunTest(std::list> &quads,\n Geometry::Line &line,\n Timer::Timer &timer) {\n const double eps = 0.75 \/ (2 * quads.size());\n timer.startTimer();\n auto inter =\n Geometry::sortIntersections(line, quads, fptype(eps));\n timer.stopTimer();\n return inter;\n}\n\ntemplate \nvoid intersectionTest(\n std::list> &quads,\n std::ostream &results, const int numTests,\n randLineGen rlgf) {\n \/* First build a scene of quadrics.\n * Then generate random lines on a disk centered at the\n * intersection of the cylinders.\n * Then sort the intersections\n * Finally validate them with a higher precision sort\n *\/\n using Vf = Geometry::Vector;\n using Pf = Geometry::Point;\n using Lf = Geometry::Line;\n using Qm = Geometry::Quadric;\n using Lm = Geometry::Line;\n constexpr const int machPrec =\n GenericFP::fpconvert::precision;\n constexpr const int precMult = 24;\n constexpr const int truthPrec = precMult * machPrec;\n mpfr::mpreal::set_default_prec(truthPrec);\n std::list truthQuads;\n \/* Generate the quadrics *\/\n for(auto q : quads) {\n Qm quadMP(q);\n truthQuads.push_back(quadMP);\n }\n std::random_device rd;\n std::mt19937_64 engine(rd());\n Timer::Timer fp_time, mp_time;\n struct TimeArr {\n int fpns;\n int mpns;\n bool correct;\n int resNumIP;\n int mpNumIP;\n } *times = new struct TimeArr[numTests];\n \/* Run the tests *\/\n int t;\n for(t = 0; t < numTests && globals.run; t++) {\n Lf line = rlgf(engine);\n Lm truthLine(line);\n constexpr const fptype eps =\n std::numeric_limits::infinity();\n \/* Then sort the intersections *\/\n auto inter = runTest(quads, line, fp_time);\n auto truth = runTest(truthQuads, truthLine, mp_time);\n times[t].fpns = fp_time.instant_ns();\n times[t].mpns = mp_time.instant_ns();\n times[t].correct = validateResults(inter, truth);\n times[t].resNumIP = countIP(inter);\n times[t].mpNumIP = countIP(truth);\n }\n \/* Output all of the results *\/\n results << \"Test #, Resultants, FP Time (ns), \"\n \"Increased Precs, MP Time (ns), Correct\\n\";\n int resTotIP = 0;\n int MPTotIP = 0;\n int totIncorrect = 0;\n for(int i = 0; i < t; i++) {\n results << i + 1 << \", \" << times[i].resNumIP << \", \"\n << times[i].fpns << \", \" << times[i].mpNumIP\n << \", \" << times[i].mpns << \", \"\n << times[i].correct << \"\\n\";\n resTotIP += times[i].resNumIP;\n MPTotIP += times[i].mpNumIP;\n totIncorrect += 1 - times[i].correct;\n }\n results << \"\\n\"\n << \"Total resultant computations: \" << resTotIP\n << \"\\n\"\n << \"Total FP Time (s): \" << fp_time.elapsed_s()\n << \".\" << std::setw(9) << std::setfill('0')\n << fp_time.elapsed_ns() << \"\\n\"\n << \"Total increased precision computations: \"\n << MPTotIP << \"\\n\"\n << \"Total MP Time (s): \" << mp_time.elapsed_s()\n << \".\" << std::setw(9) << std::setfill('0')\n << mp_time.elapsed_ns() << \"\\n\";\n results << \"Total potentially incorrect: \" << totIncorrect\n << \"\\n\";\n delete[] times;\n}\n\nvoid lockCPU() {\n const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);\n const int cpuSets =\n numCPUs \/ CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0);\n cpu_set_t *cpus = new cpu_set_t[cpuSets];\n const size_t cpuSize = sizeof(cpu_set_t[cpuSets]);\n sched_getaffinity(0, cpuSize, cpus);\n for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus);\n CPU_SET(0, cpus);\n sched_setaffinity(0, cpuSize, cpus);\n delete[] cpus;\n}\n\ntemplate \nGeometry::Line defRandLine(\n std::mt19937_64 &rng) {\n constexpr const fptype minPos = 0, maxPos = 2;\n std::uniform_real_distribution genPos(minPos,\n maxPos);\n std::uniform_real_distribution genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector lineDir;\n Geometry::Vector lineInt;\n for(int i = 0; i < dim; i++) {\n fptype tmp = genPos(rng);\n lineInt.set(i, tmp);\n tmp = genDir(rng);\n lineDir.set(i, tmp);\n }\n return Geometry::Line(\n Geometry::Point(lineInt), lineInt);\n}\n\ntemplate \nGeometry::Line cylRandLine(\n std::mt19937_64 &rng) {\n constexpr const fptype minPos = 0.375, maxPos = 0.625;\n std::uniform_real_distribution genPos(minPos,\n maxPos);\n std::uniform_real_distribution genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector lineDir;\n Geometry::Vector lineInt;\n lineInt.set(1, genPos(rng));\n for(int i = 0; i < dim; i++) {\n lineInt.set(i, lineInt.get(1));\n lineDir.set(i, genDir(rng));\n }\n lineInt.set(0, genPos(rng));\n return Geometry::Line(\n Geometry::Point(lineInt), lineInt);\n}\n\nint main(int argc, char **argv) {\n using fptype = float;\n constexpr const int dim = 3;\n lockCPU();\n std::list> quads;\n const char *outFName = \"results\";\n int numTests = 1e4;\n randLineGen rlg = cylRandLine;\n if(argc > 1) {\n quads = parseQuadrics(argv[1]);\n rlg = defRandLine;\n if(argc > 2) {\n outFName = argv[2];\n if(argc > 3) numTests = atoi(argv[3]);\n }\n } else {\n quads = parseQuadrics(\"cylinders.csg\");\n }\n std::ofstream results(outFName);\n signal(SIGINT, sigInt);\n intersectionTest(quads, results, numTests, defRandLine);\n return 0;\n}\nUpdated for gcc-6 by explicitly including random. Use a typename to specify the RNG algorithm\n#include \"geometry.hpp\"\n#include \"quadric.hpp\"\n#include \"line.hpp\"\n#include \"accurate_intersections.hpp\"\n#include \"quadric_classify.hpp\"\n#include \"timer.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nstruct GlobalVars {\n bool run = true;\n} globals;\n\nvoid sigInt(int signum) { globals.run = false; }\n\ntemplate \nstd::list> parseQuadrics(\n const char *fname) {\n std::ifstream file(fname);\n if(!file.is_open()) {\n return std::list>();\n }\n using Qf = Geometry::Quadric;\n int qtypeCount[QuadricClassify::QUADT_ERRORINVALID];\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++)\n qtypeCount[i] = 0;\n std::list quads;\n int imQuads = 0;\n int numQuads = 0;\n while(!file.eof()) {\n Qf q;\n file >> q;\n QuadricClassify::QuadType type =\n QuadricClassify::classifyQuadric(q);\n if(!QuadricClassify::isImaginary(type) &&\n type != QuadricClassify::QUADT_ERROR &&\n type != QuadricClassify::QUADT_DEGENERATE &&\n type != QuadricClassify::QUADT_ERRORINVALID) {\n quads.push_back(q);\n qtypeCount[type]++;\n } else {\n std::cout << \"Quadric \" << numQuads\n << \" is invalid, returned type \"\n << QuadricClassify::QuadTypeNames[type]\n << \"\\n\";\n imQuads++;\n }\n numQuads++;\n }\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++) {\n std::cout << qtypeCount[i] << \" \"\n << QuadricClassify::QuadTypeNames[i] << \"\\n\";\n }\n return quads;\n}\n\nbool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) {\n \/* Use a heuristic on truth to determine whether adjacent\n * intersections occur at the same place.\n * This will basically be a threshold on the largest\n * different bit in the mantissa.\n *\/\n \/* A relative heuristic does not work when one (or both!)\n * is 0 *\/\n if(int1 == 0.0 || int2 == 0.0) {\n constexpr const double eps = 0.000001;\n return (mpfr::fabs(int1 - int2) < eps);\n }\n mpfr::mpreal largest =\n mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2));\n mp_exp_t largestExp = largest.get_exp();\n mpfr::mpreal diff = mpfr::fabs(int1 - int2);\n int p1 = int1.getPrecision(), p2 = int2.getPrecision();\n int minPrec = std::min(p1, p2);\n mp_exp_t maxExp = largestExp - minPrec * 1 \/ 48,\n diffExp = diff.get_exp();\n return maxExp >= diffExp;\n}\n\ntemplate \nbool validateResults(ListFP &inter, ListMP &truth) {\n auto j = truth->begin();\n for(auto i = inter->begin();\n i != inter->end() || j != truth->end();) {\n \/* First determine the length of the region of equal\n * intersections.\n * Then verify there's an equal number of\n * intersections in the approximately equal range and\n * that they correspond to the correct intersections.\n * If not, then print the intersection\n *\/\n if(j != truth->end()) {\n \/* Create the region boundaries [sameBeg, sameEnd).\n * These are intersections which are probably the same\n *\/\n auto sameBeg = j;\n auto sameEnd = j;\n int regLen = 0;\n while(sameEnd != truth->end() &&\n isSameInt(j->intPos, sameEnd->intPos)) {\n sameEnd++;\n regLen++;\n }\n \/* Increment i until it's not found in the region *\/\n int numInRegion = 0;\n bool isInRegion = true;\n while(i != inter->end() && isInRegion &&\n numInRegion < regLen) {\n j = sameBeg;\n while(j != sameEnd && i->q != j->q) j++;\n \/* sameEnd is not in the region, so if j reaches it,\n * i isn't in the region *\/\n if(j == sameEnd) {\n isInRegion = false;\n } else {\n i++;\n numInRegion++;\n }\n }\n \/* i isn't in the region.\n * Verify all elements in the region were used *\/\n if(regLen != numInRegion) {\n return false;\n }\n j = sameEnd;\n } else {\n int numRemaining = 0;\n while(i != inter->end()) {\n i++;\n numRemaining++;\n }\n return false;\n }\n }\n return true;\n}\n\ntemplate \nint countIP(List inter) {\n int numIP = 0;\n for(auto i : *inter) numIP += i.incPrecCount();\n return numIP;\n}\n\nusing rngAlg = std::mt19937_64;\n\ntemplate \nusing randLineGen =\n Geometry::Line (*)(rngAlg &rng);\n\ntemplate \nstd::shared_ptr>> __attribute__((noinline))\nrunTest(std::list> &quads,\n Geometry::Line &line,\n Timer::Timer &timer) {\n const double eps = 0.75 \/ (2 * quads.size());\n timer.startTimer();\n auto inter =\n Geometry::sortIntersections(line, quads, fptype(eps));\n timer.stopTimer();\n return inter;\n}\n\ntemplate \nvoid intersectionTest(\n std::list> &quads,\n std::ostream &results, const int numTests,\n randLineGen rlgf) {\n \/* First build a scene of quadrics.\n * Then generate random lines on a disk centered at the\n * intersection of the cylinders.\n * Then sort the intersections\n * Finally validate them with a higher precision sort\n *\/\n using Vf = Geometry::Vector;\n using Pf = Geometry::Point;\n using Lf = Geometry::Line;\n using Qm = Geometry::Quadric;\n using Lm = Geometry::Line;\n constexpr const int machPrec =\n GenericFP::fpconvert::precision;\n constexpr const int precMult = 24;\n constexpr const int truthPrec = precMult * machPrec;\n mpfr::mpreal::set_default_prec(truthPrec);\n std::list truthQuads;\n \/* Generate the quadrics *\/\n for(auto q : quads) {\n Qm quadMP(q);\n truthQuads.push_back(quadMP);\n }\n std::random_device rd;\n rngAlg engine(rd());\n Timer::Timer fp_time, mp_time;\n struct TimeArr {\n int fpns;\n int mpns;\n bool correct;\n int resNumIP;\n int mpNumIP;\n } *times = new struct TimeArr[numTests];\n \/* Run the tests *\/\n int t;\n for(t = 0; t < numTests && globals.run; t++) {\n Lf line = rlgf(engine);\n Lm truthLine(line);\n constexpr const fptype eps =\n std::numeric_limits::infinity();\n \/* Then sort the intersections *\/\n auto inter = runTest(quads, line, fp_time);\n auto truth = runTest(truthQuads, truthLine, mp_time);\n times[t].fpns = fp_time.instant_ns();\n times[t].mpns = mp_time.instant_ns();\n times[t].correct = validateResults(inter, truth);\n times[t].resNumIP = countIP(inter);\n times[t].mpNumIP = countIP(truth);\n }\n \/* Output all of the results *\/\n results << \"Test #, Resultants, FP Time (ns), \"\n \"Increased Precs, MP Time (ns), Correct\\n\";\n int resTotIP = 0;\n int MPTotIP = 0;\n int totIncorrect = 0;\n for(int i = 0; i < t; i++) {\n results << i + 1 << \", \" << times[i].resNumIP << \", \"\n << times[i].fpns << \", \" << times[i].mpNumIP\n << \", \" << times[i].mpns << \", \"\n << times[i].correct << \"\\n\";\n resTotIP += times[i].resNumIP;\n MPTotIP += times[i].mpNumIP;\n totIncorrect += 1 - times[i].correct;\n }\n results << \"\\n\"\n << \"Total resultant computations: \" << resTotIP\n << \"\\n\"\n << \"Total FP Time (s): \" << fp_time.elapsed_s()\n << \".\" << std::setw(9) << std::setfill('0')\n << fp_time.elapsed_ns() << \"\\n\"\n << \"Total increased precision computations: \"\n << MPTotIP << \"\\n\"\n << \"Total MP Time (s): \" << mp_time.elapsed_s()\n << \".\" << std::setw(9) << std::setfill('0')\n << mp_time.elapsed_ns() << \"\\n\";\n results << \"Total potentially incorrect: \" << totIncorrect\n << \"\\n\";\n delete[] times;\n}\n\nvoid lockCPU() {\n const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);\n const int cpuSets =\n numCPUs \/ CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0);\n cpu_set_t *cpus = new cpu_set_t[cpuSets];\n const size_t cpuSize = sizeof(cpu_set_t[cpuSets]);\n sched_getaffinity(0, cpuSize, cpus);\n for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus);\n CPU_SET(0, cpus);\n sched_setaffinity(0, cpuSize, cpus);\n delete[] cpus;\n}\n\ntemplate \nGeometry::Line defRandLine(\n rngAlg &rng) {\n constexpr const fptype minPos = 0, maxPos = 2;\n std::uniform_real_distribution genPos(minPos,\n maxPos);\n std::uniform_real_distribution genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector lineDir;\n Geometry::Vector lineInt;\n for(int i = 0; i < dim; i++) {\n fptype tmp = genPos(rng);\n lineInt.set(i, tmp);\n tmp = genDir(rng);\n lineDir.set(i, tmp);\n }\n return Geometry::Line(\n Geometry::Point(lineInt), lineInt);\n}\n\ntemplate \nGeometry::Line cylRandLine(\n rngAlg &rng) {\n constexpr const fptype minPos = 0.375, maxPos = 0.625;\n std::uniform_real_distribution genPos(minPos,\n maxPos);\n std::uniform_real_distribution genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector lineDir;\n Geometry::Vector lineInt;\n lineInt.set(1, genPos(rng));\n for(int i = 0; i < dim; i++) {\n lineInt.set(i, lineInt.get(1));\n lineDir.set(i, genDir(rng));\n }\n lineInt.set(0, genPos(rng));\n return Geometry::Line(\n Geometry::Point(lineInt), lineInt);\n}\n\nint main(int argc, char **argv) {\n using fptype = float;\n constexpr const int dim = 3;\n lockCPU();\n std::list> quads;\n const char *outFName = \"results\";\n int numTests = 1e4;\n randLineGen rlg = cylRandLine;\n if(argc > 1) {\n quads = parseQuadrics(argv[1]);\n rlg = defRandLine;\n if(argc > 2) {\n outFName = argv[2];\n if(argc > 3) numTests = atoi(argv[3]);\n }\n } else {\n quads = parseQuadrics(\"cylinders.csg\");\n }\n std::ofstream results(outFName);\n signal(SIGINT, sigInt);\n intersectionTest(quads, results, numTests, defRandLine);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include \"hadesmem\/pelib\/import_thunk_list.hpp\"\r\n\r\n#include \r\n\r\n#include \"hadesmem\/detail\/warning_disable_prefix.hpp\"\r\n#include \r\n#include \r\n#include \"hadesmem\/detail\/warning_disable_suffix.hpp\"\r\n\r\n#include \r\n\r\n#include \"hadesmem\/read.hpp\"\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/config.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/pelib\/pe_file.hpp\"\r\n#include \"hadesmem\/pelib\/import_thunk.hpp\"\r\n\r\nnamespace hadesmem\r\n{\r\n\r\nstruct ImportThunkIterator::Impl\r\n{\r\n explicit Impl(Process const& process, PeFile const& pe_file) \r\n HADESMEM_NOEXCEPT\r\n : process_(&process), \r\n pe_file_(&pe_file), \r\n import_thunk_()\r\n { }\r\n\r\n Process const* process_;\r\n PeFile const* pe_file_;\r\n boost::optional import_thunk_;\r\n};\r\n\r\nImportThunkIterator::ImportThunkIterator() HADESMEM_NOEXCEPT\r\n : impl_()\r\n{ }\r\n\r\nImportThunkIterator::ImportThunkIterator(Process const& process, \r\n PeFile const& pe_file, DWORD first_thunk)\r\n : impl_(new Impl(process, pe_file))\r\n{\r\n try\r\n {\r\n auto const thunk_ptr = reinterpret_cast(RvaToVa(\r\n process, pe_file, first_thunk));\r\n impl_->import_thunk_ = ImportThunk(process, pe_file, thunk_ptr);\r\n }\r\n catch (std::exception const& \/*e*\/)\r\n {\r\n \/\/ TODO: Check whether this is the right thing to do. We should only \r\n \/\/ flag as the 'end' once we've actually reached the end of the list. If \r\n \/\/ the iteration fails we should throw an exception.\r\n impl_.reset();\r\n }\r\n}\r\n\r\nImportThunkIterator::ImportThunkIterator(ImportThunkIterator const& other) \r\n HADESMEM_NOEXCEPT\r\n : impl_(other.impl_)\r\n{ }\r\n\r\nImportThunkIterator& ImportThunkIterator::operator=(\r\n ImportThunkIterator const& other) HADESMEM_NOEXCEPT\r\n{\r\n impl_ = other.impl_;\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkIterator::ImportThunkIterator(ImportThunkIterator&& other) \r\n HADESMEM_NOEXCEPT\r\n : impl_(std::move(other.impl_))\r\n{ }\r\n\r\nImportThunkIterator& ImportThunkIterator::operator=(\r\n ImportThunkIterator&& other) HADESMEM_NOEXCEPT\r\n{\r\n impl_ = std::move(other.impl_);\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkIterator::~ImportThunkIterator()\r\n{ }\r\n\r\nImportThunkIterator::reference ImportThunkIterator::operator*() const \r\n HADESMEM_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return *impl_->import_thunk_;\r\n}\r\n\r\nImportThunkIterator::pointer ImportThunkIterator::operator->() const \r\n HADESMEM_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return &*impl_->import_thunk_;\r\n}\r\n\r\nImportThunkIterator& ImportThunkIterator::operator++()\r\n{\r\n try\r\n {\r\n BOOST_ASSERT(impl_.get());\r\n\r\n auto const cur_base = reinterpret_cast(\r\n impl_->import_thunk_->GetBase());\r\n impl_->import_thunk_ = ImportThunk(*impl_->process_, *impl_->pe_file_, \r\n cur_base + 1);\r\n\r\n if (!impl_->import_thunk_->GetAddressOfData())\r\n {\r\n impl_.reset();\r\n return *this;\r\n }\r\n }\r\n catch (std::exception const& \/*e*\/)\r\n {\r\n \/\/ TODO: Check whether this is the right thing to do. We should only \r\n \/\/ flag as the 'end' once we've actually reached the end of the list. If \r\n \/\/ the iteration fails we should throw an exception.\r\n impl_.reset();\r\n }\r\n \r\n return *this;\r\n}\r\n\r\nImportThunkIterator ImportThunkIterator::operator++(int)\r\n{\r\n ImportThunkIterator iter(*this);\r\n ++*this;\r\n return iter;\r\n}\r\n\r\nbool ImportThunkIterator::operator==(ImportThunkIterator const& other) const \r\n HADESMEM_NOEXCEPT\r\n{\r\n return impl_ == other.impl_;\r\n}\r\n\r\nbool ImportThunkIterator::operator!=(ImportThunkIterator const& other) const \r\n HADESMEM_NOEXCEPT\r\n{\r\n return !(*this == other);\r\n}\r\n\r\nstruct ImportThunkList::Impl\r\n{\r\n Impl(Process const& process, PeFile const& pe_file, DWORD first_thunk)\r\n : process_(&process), \r\n pe_file_(&pe_file), \r\n first_thunk_(first_thunk)\r\n { }\r\n\r\n Process const* process_;\r\n PeFile const* pe_file_;\r\n DWORD first_thunk_;\r\n};\r\n\r\nImportThunkList::ImportThunkList(Process const& process, PeFile const& pe_file, \r\n DWORD first_thunk)\r\n : impl_(new Impl(process, pe_file, first_thunk))\r\n{ }\r\n\r\nImportThunkList::ImportThunkList(ImportThunkList const& other)\r\n : impl_(new Impl(*other.impl_))\r\n{ }\r\n\r\nImportThunkList& ImportThunkList::operator=(ImportThunkList const& other)\r\n{\r\n impl_ = std::unique_ptr(new Impl(*other.impl_));\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkList::ImportThunkList(ImportThunkList&& other) HADESMEM_NOEXCEPT\r\n : impl_(std::move(other.impl_))\r\n{ }\r\n\r\nImportThunkList& ImportThunkList::operator=(ImportThunkList&& other) \r\n HADESMEM_NOEXCEPT\r\n{\r\n impl_ = std::move(other.impl_);\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkList::~ImportThunkList()\r\n{ }\r\n\r\nImportThunkList::iterator ImportThunkList::begin()\r\n{\r\n return ImportThunkList::iterator(*impl_->process_, *impl_->pe_file_, \r\n impl_->first_thunk_);\r\n}\r\n\r\nImportThunkList::const_iterator ImportThunkList::begin() const\r\n{\r\n return ImportThunkList::iterator(*impl_->process_, *impl_->pe_file_, \r\n impl_->first_thunk_);\r\n}\r\n\r\nImportThunkList::iterator ImportThunkList::end() HADESMEM_NOEXCEPT\r\n{\r\n return ImportThunkList::iterator();\r\n}\r\n\r\nImportThunkList::const_iterator ImportThunkList::end() const HADESMEM_NOEXCEPT\r\n{\r\n return ImportThunkList::iterator();\r\n}\r\n\r\n}\r\n* Fix enumeration of a valid but empty import thunk list.\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include \"hadesmem\/pelib\/import_thunk_list.hpp\"\r\n\r\n#include \r\n\r\n#include \"hadesmem\/detail\/warning_disable_prefix.hpp\"\r\n#include \r\n#include \r\n#include \"hadesmem\/detail\/warning_disable_suffix.hpp\"\r\n\r\n#include \r\n\r\n#include \"hadesmem\/read.hpp\"\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/config.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/pelib\/pe_file.hpp\"\r\n#include \"hadesmem\/pelib\/import_thunk.hpp\"\r\n\r\nnamespace hadesmem\r\n{\r\n\r\nstruct ImportThunkIterator::Impl\r\n{\r\n explicit Impl(Process const& process, PeFile const& pe_file) \r\n HADESMEM_NOEXCEPT\r\n : process_(&process), \r\n pe_file_(&pe_file), \r\n import_thunk_()\r\n { }\r\n\r\n Process const* process_;\r\n PeFile const* pe_file_;\r\n boost::optional import_thunk_;\r\n};\r\n\r\nImportThunkIterator::ImportThunkIterator() HADESMEM_NOEXCEPT\r\n : impl_()\r\n{ }\r\n\r\nImportThunkIterator::ImportThunkIterator(Process const& process, \r\n PeFile const& pe_file, DWORD first_thunk)\r\n : impl_(new Impl(process, pe_file))\r\n{\r\n try\r\n {\r\n auto const thunk_ptr = reinterpret_cast(RvaToVa(\r\n process, pe_file, first_thunk));\r\n impl_->import_thunk_ = ImportThunk(process, pe_file, thunk_ptr);\r\n if (!impl_->import_thunk_->GetAddressOfData())\r\n {\r\n impl_.reset();\r\n }\r\n }\r\n catch (std::exception const& \/*e*\/)\r\n {\r\n \/\/ TODO: Check whether this is the right thing to do. We should only \r\n \/\/ flag as the 'end' once we've actually reached the end of the list. If \r\n \/\/ the iteration fails we should throw an exception.\r\n impl_.reset();\r\n }\r\n}\r\n\r\nImportThunkIterator::ImportThunkIterator(ImportThunkIterator const& other) \r\n HADESMEM_NOEXCEPT\r\n : impl_(other.impl_)\r\n{ }\r\n\r\nImportThunkIterator& ImportThunkIterator::operator=(\r\n ImportThunkIterator const& other) HADESMEM_NOEXCEPT\r\n{\r\n impl_ = other.impl_;\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkIterator::ImportThunkIterator(ImportThunkIterator&& other) \r\n HADESMEM_NOEXCEPT\r\n : impl_(std::move(other.impl_))\r\n{ }\r\n\r\nImportThunkIterator& ImportThunkIterator::operator=(\r\n ImportThunkIterator&& other) HADESMEM_NOEXCEPT\r\n{\r\n impl_ = std::move(other.impl_);\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkIterator::~ImportThunkIterator()\r\n{ }\r\n\r\nImportThunkIterator::reference ImportThunkIterator::operator*() const \r\n HADESMEM_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return *impl_->import_thunk_;\r\n}\r\n\r\nImportThunkIterator::pointer ImportThunkIterator::operator->() const \r\n HADESMEM_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return &*impl_->import_thunk_;\r\n}\r\n\r\nImportThunkIterator& ImportThunkIterator::operator++()\r\n{\r\n try\r\n {\r\n BOOST_ASSERT(impl_.get());\r\n\r\n auto const cur_base = reinterpret_cast(\r\n impl_->import_thunk_->GetBase());\r\n impl_->import_thunk_ = ImportThunk(*impl_->process_, *impl_->pe_file_, \r\n cur_base + 1);\r\n\r\n if (!impl_->import_thunk_->GetAddressOfData())\r\n {\r\n impl_.reset();\r\n return *this;\r\n }\r\n }\r\n catch (std::exception const& \/*e*\/)\r\n {\r\n \/\/ TODO: Check whether this is the right thing to do. We should only \r\n \/\/ flag as the 'end' once we've actually reached the end of the list. If \r\n \/\/ the iteration fails we should throw an exception.\r\n impl_.reset();\r\n }\r\n \r\n return *this;\r\n}\r\n\r\nImportThunkIterator ImportThunkIterator::operator++(int)\r\n{\r\n ImportThunkIterator iter(*this);\r\n ++*this;\r\n return iter;\r\n}\r\n\r\nbool ImportThunkIterator::operator==(ImportThunkIterator const& other) const \r\n HADESMEM_NOEXCEPT\r\n{\r\n return impl_ == other.impl_;\r\n}\r\n\r\nbool ImportThunkIterator::operator!=(ImportThunkIterator const& other) const \r\n HADESMEM_NOEXCEPT\r\n{\r\n return !(*this == other);\r\n}\r\n\r\nstruct ImportThunkList::Impl\r\n{\r\n Impl(Process const& process, PeFile const& pe_file, DWORD first_thunk)\r\n : process_(&process), \r\n pe_file_(&pe_file), \r\n first_thunk_(first_thunk)\r\n { }\r\n\r\n Process const* process_;\r\n PeFile const* pe_file_;\r\n DWORD first_thunk_;\r\n};\r\n\r\nImportThunkList::ImportThunkList(Process const& process, PeFile const& pe_file, \r\n DWORD first_thunk)\r\n : impl_(new Impl(process, pe_file, first_thunk))\r\n{ }\r\n\r\nImportThunkList::ImportThunkList(ImportThunkList const& other)\r\n : impl_(new Impl(*other.impl_))\r\n{ }\r\n\r\nImportThunkList& ImportThunkList::operator=(ImportThunkList const& other)\r\n{\r\n impl_ = std::unique_ptr(new Impl(*other.impl_));\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkList::ImportThunkList(ImportThunkList&& other) HADESMEM_NOEXCEPT\r\n : impl_(std::move(other.impl_))\r\n{ }\r\n\r\nImportThunkList& ImportThunkList::operator=(ImportThunkList&& other) \r\n HADESMEM_NOEXCEPT\r\n{\r\n impl_ = std::move(other.impl_);\r\n\r\n return *this;\r\n}\r\n\r\nImportThunkList::~ImportThunkList()\r\n{ }\r\n\r\nImportThunkList::iterator ImportThunkList::begin()\r\n{\r\n return ImportThunkList::iterator(*impl_->process_, *impl_->pe_file_, \r\n impl_->first_thunk_);\r\n}\r\n\r\nImportThunkList::const_iterator ImportThunkList::begin() const\r\n{\r\n return ImportThunkList::iterator(*impl_->process_, *impl_->pe_file_, \r\n impl_->first_thunk_);\r\n}\r\n\r\nImportThunkList::iterator ImportThunkList::end() HADESMEM_NOEXCEPT\r\n{\r\n return ImportThunkList::iterator();\r\n}\r\n\r\nImportThunkList::const_iterator ImportThunkList::end() const HADESMEM_NOEXCEPT\r\n{\r\n return ImportThunkList::iterator();\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qgraphicsvideoitem.h\"\n\n#ifdef Q_OS_SYMBIAN\n#define QGRAPHICSVIDEOITEM_ROTATION_SUPPORT\n#endif\n\n#include \n#include \n#include \n\n\nQT_BEGIN_NAMESPACE\n\n#define DEBUG_GFX_VIDEO_ITEM\n\nclass QGraphicsVideoItemPrivate : public QObject\n{\npublic:\n QGraphicsVideoItemPrivate()\n : q_ptr(0)\n , mediaObject(0)\n , service(0)\n , windowControl(0)\n , savedViewportUpdateMode(QGraphicsView::FullViewportUpdate)\n , aspectRatioMode(Qt::KeepAspectRatio)\n , rect(0.0, 0.0, 320, 240)\n , videoWidget(0)\n {\n }\n\n QGraphicsVideoItem *q_ptr;\n\n QMediaObject *mediaObject;\n QMediaService *service;\n QVideoWindowControl *windowControl;\n QPointer currentView;\n QList > eventFilterTargets;\n QGraphicsView::ViewportUpdateMode savedViewportUpdateMode;\n\n Qt::AspectRatioMode aspectRatioMode;\n QRectF rect;\n QRectF boundingRect;\n QRectF displayRect;\n QSizeF nativeSize;\n\n QWidget *videoWidget;\n\n bool eventFilter(QObject *object, QEvent *event);\n void updateEventFilters();\n\n void setWidget(QWidget *widget);\n void clearService();\n void updateRects();\n void updateLastFrame();\n\n void _q_present();\n void _q_updateNativeSize();\n void _q_serviceDestroyed();\n void _q_mediaObjectDestroyed();\n};\n\nvoid QGraphicsVideoItemPrivate::_q_present()\n{\n\n}\n\nbool QGraphicsVideoItemPrivate::eventFilter(QObject *object, QEvent *event)\n{\n if (windowControl && object == videoWidget && QEvent::WinIdChange == event->type()) {\n windowControl->setWinId(videoWidget->effectiveWinId());\n } else {\n bool updateEventFiltersRequired = false;\n bool refreshDisplayRequired = false;\n foreach (QPointer target, eventFilterTargets) {\n if (object == target.data()) {\n switch (event->type()) {\n case QEvent::ParentChange:\n updateEventFiltersRequired = true;\n refreshDisplayRequired = true;\n break;\n case QEvent::Move:\n case QEvent::Resize:\n refreshDisplayRequired = true;\n break;\n default: ;\n }\n }\n }\n if (updateEventFiltersRequired)\n updateEventFilters();\n#ifdef Q_OS_SYMBIAN\n if (refreshDisplayRequired && windowControl)\n QMetaObject::invokeMethod(windowControl, \"refreshDisplay\");\n#endif\n }\n return false;\n}\n\nvoid QGraphicsVideoItemPrivate::setWidget(QWidget *widget)\n{\n if (videoWidget != widget) {\n videoWidget = widget;\n if (widget) {\n windowControl->setWinId(widget->winId());\n widget->installEventFilter(this);\n }\n }\n}\n\nvoid QGraphicsVideoItemPrivate::clearService()\n{\n if (windowControl) {\n QObject::disconnect(windowControl, SIGNAL(nativeSizeChanged()), q_ptr, SLOT(_q_updateNativeSize()));\n service->releaseControl(windowControl);\n windowControl = 0;\n }\n\n if (service) {\n QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed()));\n service = 0;\n }\n}\n\nvoid QGraphicsVideoItemPrivate::updateRects()\n{\n q_ptr->prepareGeometryChange();\n QSizeF videoSize;\n if (nativeSize.isEmpty()) {\n videoSize = rect.size();\n } else if (aspectRatioMode == Qt::IgnoreAspectRatio) {\n videoSize = rect.size();\n } else {\n \/\/ KeepAspectRatio or KeepAspectRatioByExpanding\n videoSize = nativeSize;\n videoSize.scale(rect.size(), aspectRatioMode);\n }\n displayRect = QRectF(QPointF(0, 0), videoSize);\n displayRect.moveCenter(rect.center());\n boundingRect = displayRect.intersected(rect);\n}\n\nvoid QGraphicsVideoItemPrivate::updateLastFrame()\n{\n}\n\nvoid QGraphicsVideoItemPrivate::updateEventFilters()\n{\n \/\/ In order to determine when the absolute screen position of the item\n \/\/ changes, we need to receive move events sent to m_currentView\n \/\/ or any of its ancestors.\n foreach (QPointer target, eventFilterTargets)\n if (target)\n target->removeEventFilter(this);\n eventFilterTargets.clear();\n QObject *target = currentView;\n while (target) {\n target->installEventFilter(this);\n eventFilterTargets.append(target);\n target = target->parent();\n }\n}\n\nvoid QGraphicsVideoItemPrivate::_q_updateNativeSize()\n{\n const QSize size = windowControl->nativeSize();\n if (nativeSize != size) {\n nativeSize = size;\n\n updateRects();\n emit q_ptr->nativeSizeChanged(nativeSize);\n }\n}\n\nvoid QGraphicsVideoItemPrivate::_q_serviceDestroyed()\n{\n windowControl = 0;\n service = 0;\n}\n\nvoid QGraphicsVideoItemPrivate::_q_mediaObjectDestroyed()\n{\n mediaObject = 0;\n\n clearService();\n}\n\nQGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent)\n : QGraphicsObject(parent)\n , d_ptr(new QGraphicsVideoItemPrivate)\n{\n d_ptr->q_ptr = this;\n\n setCacheMode(NoCache);\n setFlag(QGraphicsItem::ItemIgnoresParentOpacity);\n setFlag(QGraphicsItem::ItemSendsGeometryChanges);\n setFlag(QGraphicsItem::ItemSendsScenePositionChanges);\n}\n\nQGraphicsVideoItem::~QGraphicsVideoItem()\n{\n if (d_ptr->windowControl) {\n d_ptr->service->releaseControl(d_ptr->windowControl);\n }\n\n if (d_ptr->currentView)\n d_ptr->currentView->setViewportUpdateMode(d_ptr->savedViewportUpdateMode);\n\n delete d_ptr;\n}\n\nQMediaObject *QGraphicsVideoItem::mediaObject() const\n{\n return d_func()->mediaObject;\n}\n\nbool QGraphicsVideoItem::setMediaObject(QMediaObject *object)\n{\n Q_D(QGraphicsVideoItem);\n\n if (object == d->mediaObject)\n return true;\n\n d->clearService();\n\n d->mediaObject = object;\n\n if (d->mediaObject) {\n d->service = d->mediaObject->service();\n\n if (d->service) {\n d->windowControl = qobject_cast(\n d->service->requestControl(QVideoWindowControl_iid));\n\n if (d->windowControl != 0) {\n connect(d->service, SIGNAL(destroyed()), SLOT(_q_serviceDestroyed()));\n connect(d->windowControl, SIGNAL(nativeSizeChanged()), SLOT(_q_updateNativeSize()));\n d->windowControl->setAspectRatioMode(Qt::IgnoreAspectRatio);\n \/\/d->windowControl->setProperty(\"colorKey\", QVariant(QColor(16,7,2)));\n d->windowControl->setProperty(\"autopaintColorKey\", QVariant(false));\n\n d->updateRects();\n return true;\n } else {\n qWarning() << \"Service doesn't support QVideoWindowControl, overlay item failed\";\n }\n }\n }\n\n d->mediaObject = 0;\n return false;\n}\n\nQt::AspectRatioMode QGraphicsVideoItem::aspectRatioMode() const\n{\n return d_func()->aspectRatioMode;\n}\n\nvoid QGraphicsVideoItem::setAspectRatioMode(Qt::AspectRatioMode mode)\n{\n Q_D(QGraphicsVideoItem);\n\n d->aspectRatioMode = mode;\n d->updateRects();\n}\n\nQPointF QGraphicsVideoItem::offset() const\n{\n return d_func()->rect.topLeft();\n}\n\nvoid QGraphicsVideoItem::setOffset(const QPointF &offset)\n{\n Q_D(QGraphicsVideoItem);\n\n d->rect.moveTo(offset);\n d->updateRects();\n}\n\nQSizeF QGraphicsVideoItem::size() const\n{\n return d_func()->rect.size();\n}\n\nvoid QGraphicsVideoItem::setSize(const QSizeF &size)\n{\n Q_D(QGraphicsVideoItem);\n\n d->rect.setSize(size.isValid() ? size : QSizeF(0, 0));\n d->updateRects();\n}\n\nQSizeF QGraphicsVideoItem::nativeSize() const\n{\n return d_func()->nativeSize;\n}\n\nQRectF QGraphicsVideoItem::boundingRect() const\n{\n return d_func()->boundingRect;\n}\n\nvoid QGraphicsVideoItem::paint(\n QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n#ifdef DEBUG_GFX_VIDEO_ITEM\n qDebug() << \"QGraphicsVideoItem::paint\";\n#endif\n\n Q_UNUSED(option);\n Q_D(QGraphicsVideoItem);\n\n QGraphicsView *view = 0;\n if (scene() && !scene()->views().isEmpty())\n view = scene()->views().first();\n\n \/\/it's necessary to switch vieport update mode to FullViewportUpdate\n \/\/otherwise the video item area can be just scrolled without notifying overlay\n \/\/about geometry changes\n if (view != d->currentView) {\n if (d->currentView) {\n d->currentView->setViewportUpdateMode(d->savedViewportUpdateMode);\n }\n\n d->currentView = view;\n if (view) {\n d->savedViewportUpdateMode = view->viewportUpdateMode();\n view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);\n }\n d->updateEventFilters();\n }\n\n QColor colorKey = Qt::black;\n\n if (d->windowControl != 0 && widget != 0) {\n d->setWidget(widget);\n\n QTransform transform = painter->combinedTransform();\n QRect overlayRect = transform.mapRect(d->displayRect).toRect();\n QRect currentSurfaceRect = d->windowControl->displayRect();\n\n if (currentSurfaceRect != overlayRect) { \n#ifdef DEBUG_GFX_VIDEO_ITEM\n qDebug() << \"set video display rect:\" << overlayRect;\n#endif\n d->windowControl->setDisplayRect(overlayRect);\n }\n\n colorKey = d->windowControl->property(\"colorKey\").value();\n#ifdef QGRAPHICSVIDEOITEM_ROTATION_SUPPORT\n const qreal angle = transform.map(QLineF(0, 0, 1, 0)).angle();\n d->windowControl->setProperty(\"rotation\", QVariant::fromValue(angle));\n#endif\n }\n\n if (colorKey.alpha() != 255)\n painter->setCompositionMode(QPainter::CompositionMode_Source);\n painter->fillRect(d->boundingRect, colorKey);\n}\n\nQVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value)\n{\n Q_D(QGraphicsVideoItem);\n\n switch (change) {\n case ItemScenePositionHasChanged:\n update(boundingRect());\n break;\n case ItemVisibleChange:\n \/\/move overlay out of the screen if video item becomes invisible\n if (d->windowControl != 0 && !value.toBool())\n d->windowControl->setDisplayRect(QRect(-1,-1,1,1));\n break;\n default:\n break;\n }\n\n return QGraphicsItem::itemChange(change, value);\n}\n\nvoid QGraphicsVideoItem::timerEvent(QTimerEvent *event)\n{\n QGraphicsObject::timerEvent(event);\n}\n\n#include \"moc_qgraphicsvideoitem.cpp\"\nQT_END_NAMESPACE\nQtMultimedia: micro-optimisation\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qgraphicsvideoitem.h\"\n\n#ifdef Q_OS_SYMBIAN\n#define QGRAPHICSVIDEOITEM_ROTATION_SUPPORT\n#endif\n\n#include \n#include \n#include \n\n\nQT_BEGIN_NAMESPACE\n\n#define DEBUG_GFX_VIDEO_ITEM\n\nclass QGraphicsVideoItemPrivate : public QObject\n{\npublic:\n QGraphicsVideoItemPrivate()\n : q_ptr(0)\n , mediaObject(0)\n , service(0)\n , windowControl(0)\n , savedViewportUpdateMode(QGraphicsView::FullViewportUpdate)\n , aspectRatioMode(Qt::KeepAspectRatio)\n , rect(0.0, 0.0, 320, 240)\n , videoWidget(0)\n {\n }\n\n QGraphicsVideoItem *q_ptr;\n\n QMediaObject *mediaObject;\n QMediaService *service;\n QVideoWindowControl *windowControl;\n QPointer currentView;\n QList > eventFilterTargets;\n QGraphicsView::ViewportUpdateMode savedViewportUpdateMode;\n\n Qt::AspectRatioMode aspectRatioMode;\n QRectF rect;\n QRectF boundingRect;\n QRectF displayRect;\n QSizeF nativeSize;\n\n QWidget *videoWidget;\n\n bool eventFilter(QObject *object, QEvent *event);\n void updateEventFilters();\n\n void setWidget(QWidget *widget);\n void clearService();\n void updateRects();\n void updateLastFrame();\n\n void _q_present();\n void _q_updateNativeSize();\n void _q_serviceDestroyed();\n void _q_mediaObjectDestroyed();\n};\n\nvoid QGraphicsVideoItemPrivate::_q_present()\n{\n\n}\n\nbool QGraphicsVideoItemPrivate::eventFilter(QObject *object, QEvent *event)\n{\n if (windowControl && object == videoWidget && QEvent::WinIdChange == event->type()) {\n windowControl->setWinId(videoWidget->effectiveWinId());\n } else {\n bool updateEventFiltersRequired = false;\n bool refreshDisplayRequired = false;\n foreach (const QPointer &target, eventFilterTargets) {\n if (object == target.data()) {\n switch (event->type()) {\n case QEvent::ParentChange:\n updateEventFiltersRequired = true;\n refreshDisplayRequired = true;\n break;\n case QEvent::Move:\n case QEvent::Resize:\n refreshDisplayRequired = true;\n break;\n default: ;\n }\n }\n }\n if (updateEventFiltersRequired)\n updateEventFilters();\n#ifdef Q_OS_SYMBIAN\n if (refreshDisplayRequired && windowControl)\n QMetaObject::invokeMethod(windowControl, \"refreshDisplay\");\n#endif\n }\n return false;\n}\n\nvoid QGraphicsVideoItemPrivate::setWidget(QWidget *widget)\n{\n if (videoWidget != widget) {\n videoWidget = widget;\n if (widget) {\n windowControl->setWinId(widget->winId());\n widget->installEventFilter(this);\n }\n }\n}\n\nvoid QGraphicsVideoItemPrivate::clearService()\n{\n if (windowControl) {\n QObject::disconnect(windowControl, SIGNAL(nativeSizeChanged()), q_ptr, SLOT(_q_updateNativeSize()));\n service->releaseControl(windowControl);\n windowControl = 0;\n }\n\n if (service) {\n QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed()));\n service = 0;\n }\n}\n\nvoid QGraphicsVideoItemPrivate::updateRects()\n{\n q_ptr->prepareGeometryChange();\n QSizeF videoSize;\n if (nativeSize.isEmpty()) {\n videoSize = rect.size();\n } else if (aspectRatioMode == Qt::IgnoreAspectRatio) {\n videoSize = rect.size();\n } else {\n \/\/ KeepAspectRatio or KeepAspectRatioByExpanding\n videoSize = nativeSize;\n videoSize.scale(rect.size(), aspectRatioMode);\n }\n displayRect = QRectF(QPointF(0, 0), videoSize);\n displayRect.moveCenter(rect.center());\n boundingRect = displayRect.intersected(rect);\n}\n\nvoid QGraphicsVideoItemPrivate::updateLastFrame()\n{\n}\n\nvoid QGraphicsVideoItemPrivate::updateEventFilters()\n{\n \/\/ In order to determine when the absolute screen position of the item\n \/\/ changes, we need to receive move events sent to m_currentView\n \/\/ or any of its ancestors.\n foreach (QPointer target, eventFilterTargets)\n if (target)\n target->removeEventFilter(this);\n eventFilterTargets.clear();\n QObject *target = currentView;\n while (target) {\n target->installEventFilter(this);\n eventFilterTargets.append(target);\n target = target->parent();\n }\n}\n\nvoid QGraphicsVideoItemPrivate::_q_updateNativeSize()\n{\n const QSize size = windowControl->nativeSize();\n if (nativeSize != size) {\n nativeSize = size;\n\n updateRects();\n emit q_ptr->nativeSizeChanged(nativeSize);\n }\n}\n\nvoid QGraphicsVideoItemPrivate::_q_serviceDestroyed()\n{\n windowControl = 0;\n service = 0;\n}\n\nvoid QGraphicsVideoItemPrivate::_q_mediaObjectDestroyed()\n{\n mediaObject = 0;\n\n clearService();\n}\n\nQGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent)\n : QGraphicsObject(parent)\n , d_ptr(new QGraphicsVideoItemPrivate)\n{\n d_ptr->q_ptr = this;\n\n setCacheMode(NoCache);\n setFlag(QGraphicsItem::ItemIgnoresParentOpacity);\n setFlag(QGraphicsItem::ItemSendsGeometryChanges);\n setFlag(QGraphicsItem::ItemSendsScenePositionChanges);\n}\n\nQGraphicsVideoItem::~QGraphicsVideoItem()\n{\n if (d_ptr->windowControl) {\n d_ptr->service->releaseControl(d_ptr->windowControl);\n }\n\n if (d_ptr->currentView)\n d_ptr->currentView->setViewportUpdateMode(d_ptr->savedViewportUpdateMode);\n\n delete d_ptr;\n}\n\nQMediaObject *QGraphicsVideoItem::mediaObject() const\n{\n return d_func()->mediaObject;\n}\n\nbool QGraphicsVideoItem::setMediaObject(QMediaObject *object)\n{\n Q_D(QGraphicsVideoItem);\n\n if (object == d->mediaObject)\n return true;\n\n d->clearService();\n\n d->mediaObject = object;\n\n if (d->mediaObject) {\n d->service = d->mediaObject->service();\n\n if (d->service) {\n d->windowControl = qobject_cast(\n d->service->requestControl(QVideoWindowControl_iid));\n\n if (d->windowControl != 0) {\n connect(d->service, SIGNAL(destroyed()), SLOT(_q_serviceDestroyed()));\n connect(d->windowControl, SIGNAL(nativeSizeChanged()), SLOT(_q_updateNativeSize()));\n d->windowControl->setAspectRatioMode(Qt::IgnoreAspectRatio);\n \/\/d->windowControl->setProperty(\"colorKey\", QVariant(QColor(16,7,2)));\n d->windowControl->setProperty(\"autopaintColorKey\", QVariant(false));\n\n d->updateRects();\n return true;\n } else {\n qWarning() << \"Service doesn't support QVideoWindowControl, overlay item failed\";\n }\n }\n }\n\n d->mediaObject = 0;\n return false;\n}\n\nQt::AspectRatioMode QGraphicsVideoItem::aspectRatioMode() const\n{\n return d_func()->aspectRatioMode;\n}\n\nvoid QGraphicsVideoItem::setAspectRatioMode(Qt::AspectRatioMode mode)\n{\n Q_D(QGraphicsVideoItem);\n\n d->aspectRatioMode = mode;\n d->updateRects();\n}\n\nQPointF QGraphicsVideoItem::offset() const\n{\n return d_func()->rect.topLeft();\n}\n\nvoid QGraphicsVideoItem::setOffset(const QPointF &offset)\n{\n Q_D(QGraphicsVideoItem);\n\n d->rect.moveTo(offset);\n d->updateRects();\n}\n\nQSizeF QGraphicsVideoItem::size() const\n{\n return d_func()->rect.size();\n}\n\nvoid QGraphicsVideoItem::setSize(const QSizeF &size)\n{\n Q_D(QGraphicsVideoItem);\n\n d->rect.setSize(size.isValid() ? size : QSizeF(0, 0));\n d->updateRects();\n}\n\nQSizeF QGraphicsVideoItem::nativeSize() const\n{\n return d_func()->nativeSize;\n}\n\nQRectF QGraphicsVideoItem::boundingRect() const\n{\n return d_func()->boundingRect;\n}\n\nvoid QGraphicsVideoItem::paint(\n QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n#ifdef DEBUG_GFX_VIDEO_ITEM\n qDebug() << \"QGraphicsVideoItem::paint\";\n#endif\n\n Q_UNUSED(option);\n Q_D(QGraphicsVideoItem);\n\n QGraphicsView *view = 0;\n if (scene() && !scene()->views().isEmpty())\n view = scene()->views().first();\n\n \/\/it's necessary to switch vieport update mode to FullViewportUpdate\n \/\/otherwise the video item area can be just scrolled without notifying overlay\n \/\/about geometry changes\n if (view != d->currentView) {\n if (d->currentView) {\n d->currentView->setViewportUpdateMode(d->savedViewportUpdateMode);\n }\n\n d->currentView = view;\n if (view) {\n d->savedViewportUpdateMode = view->viewportUpdateMode();\n view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);\n }\n d->updateEventFilters();\n }\n\n QColor colorKey = Qt::black;\n\n if (d->windowControl != 0 && widget != 0) {\n d->setWidget(widget);\n\n QTransform transform = painter->combinedTransform();\n QRect overlayRect = transform.mapRect(d->displayRect).toRect();\n QRect currentSurfaceRect = d->windowControl->displayRect();\n\n if (currentSurfaceRect != overlayRect) { \n#ifdef DEBUG_GFX_VIDEO_ITEM\n qDebug() << \"set video display rect:\" << overlayRect;\n#endif\n d->windowControl->setDisplayRect(overlayRect);\n }\n\n colorKey = d->windowControl->property(\"colorKey\").value();\n#ifdef QGRAPHICSVIDEOITEM_ROTATION_SUPPORT\n const qreal angle = transform.map(QLineF(0, 0, 1, 0)).angle();\n d->windowControl->setProperty(\"rotation\", QVariant::fromValue(angle));\n#endif\n }\n\n if (colorKey.alpha() != 255)\n painter->setCompositionMode(QPainter::CompositionMode_Source);\n painter->fillRect(d->boundingRect, colorKey);\n}\n\nQVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value)\n{\n Q_D(QGraphicsVideoItem);\n\n switch (change) {\n case ItemScenePositionHasChanged:\n update(boundingRect());\n break;\n case ItemVisibleChange:\n \/\/move overlay out of the screen if video item becomes invisible\n if (d->windowControl != 0 && !value.toBool())\n d->windowControl->setDisplayRect(QRect(-1,-1,1,1));\n break;\n default:\n break;\n }\n\n return QGraphicsItem::itemChange(change, value);\n}\n\nvoid QGraphicsVideoItem::timerEvent(QTimerEvent *event)\n{\n QGraphicsObject::timerEvent(event);\n}\n\n#include \"moc_qgraphicsvideoitem.cpp\"\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2011, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Ioan Sucan *\/\n\n#include \"ompl\/tools\/multiplan\/ParallelPlan.h\"\n#include \"ompl\/geometric\/PathHybridization.h\"\n\nompl::tools::ParallelPlan::ParallelPlan(const base::ProblemDefinitionPtr &pdef) :\n pdef_(pdef), phybrid_(new geometric::PathHybridization(pdef->getSpaceInformation()))\n{\n}\n\nompl::tools::ParallelPlan::~ParallelPlan()\n{\n}\n\nvoid ompl::tools::ParallelPlan::addPlanner(const base::PlannerPtr &planner)\n{\n if (planner && planner->getSpaceInformation().get() != pdef_->getSpaceInformation().get())\n throw Exception(\"Planner instance does not match space information\");\n if (planner->getProblemDefinition().get() != pdef_.get())\n planner->setProblemDefinition(pdef_);\n planners_.push_back(planner);\n}\n\nvoid ompl::tools::ParallelPlan::addPlannerAllocator(const base::PlannerAllocator &pa)\n{\n base::PlannerPtr planner = pa(pdef_->getSpaceInformation());\n planner->setProblemDefinition(pdef_);\n planners_.push_back(planner);\n}\n\nvoid ompl::tools::ParallelPlan::clearPlanners()\n{\n planners_.clear();\n}\n\nvoid ompl::tools::ParallelPlan::clearHybridizationPaths()\n{\n phybrid_->clear();\n}\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(double solveTime, bool hybridize)\n{\n return solve(solveTime, 1, planners_.size(), hybridize);\n}\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(double solveTime, std::size_t minSolCount, std::size_t maxSolCount, bool hybridize)\n{\n return solve(base::timedPlannerTerminationCondition(solveTime, std::min(solveTime \/ 100.0, 0.1)), minSolCount, maxSolCount, hybridize);\n}\n\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(const base::PlannerTerminationCondition &ptc, bool hybridize)\n{\n return solve(ptc, 1, planners_.size(), hybridize);\n}\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(const base::PlannerTerminationCondition &ptc, std::size_t minSolCount,\n std::size_t maxSolCount, bool hybridize)\n{\n if (!pdef_->getSpaceInformation()->isSetup())\n pdef_->getSpaceInformation()->setup();\n foundSolCount_ = 0;\n\n time::point start = time::now();\n std::vector threads(planners_.size());\n\n \/\/ Decide if we are combining solutions or just taking the first one\n if (hybridize)\n for (std::size_t i = 0 ; i < threads.size() ; ++i)\n threads[i] = new boost::thread(boost::bind(&ParallelPlan::solveMore, this, planners_[i].get(), minSolCount, maxSolCount, &ptc));\n else\n for (std::size_t i = 0 ; i < threads.size() ; ++i)\n threads[i] = new boost::thread(boost::bind(&ParallelPlan::solveOne, this, planners_[i].get(), minSolCount, &ptc));\n\n for (std::size_t i = 0 ; i < threads.size() ; ++i)\n {\n threads[i]->join();\n delete threads[i];\n }\n\n if (hybridize)\n {\n if (phybrid_->pathCount() > 1)\n if (const base::PathPtr &hsol = phybrid_->getHybridPath())\n {\n geometric::PathGeometric *pg = static_cast(hsol.get());\n double difference = 0.0;\n bool approximate = !pdef_->getGoal()->isSatisfied(pg->getStates().back(), &difference);\n pdef_->addSolutionPath(hsol, approximate, difference, phybrid_->getName()); \/\/ name this solution after the hybridization algorithm\n }\n }\n\n if (pdef_->hasSolution())\n OMPL_INFORM(\"ParallelPlan::solve(): Solution found by one or more threads in %f seconds\", time::seconds(time::now() - start));\n else\n OMPL_WARN(\"ParallelPlan::solve(): Unable to find solution by any of the threads in %f seconds\", time::seconds(time::now() - start));\n\n return base::PlannerStatus(pdef_->hasSolution(), pdef_->hasApproximateSolution());\n}\n\nvoid ompl::tools::ParallelPlan::solveOne(base::Planner *planner, std::size_t minSolCount, const base::PlannerTerminationCondition *ptc)\n{\n OMPL_DEBUG(\"ParallelPlam.solveOne starting planner %s\", planner->getName().c_str());\n\n time::point start = time::now();\n if (planner->solve(*ptc))\n {\n double duration = time::seconds(time::now() - start);\n foundSolCountLock_.lock();\n unsigned int nrSol = ++foundSolCount_;\n foundSolCountLock_.unlock();\n if (nrSol >= minSolCount)\n ptc->terminate();\n OMPL_DEBUG(\"ParallelPlan.solveOne: Solution found by %s in %lf seconds\", planner->getName().c_str(), duration);\n }\n}\n\nvoid ompl::tools::ParallelPlan::solveMore(base::Planner *planner, std::size_t minSolCount, std::size_t maxSolCount,\n const base::PlannerTerminationCondition *ptc)\n{\n OMPL_DEBUG(\"ParallelPlan.solveMore: starting planner %s\", planner->getName().c_str());\n\n time::point start = time::now();\n if (planner->solve(*ptc))\n {\n double duration = time::seconds(time::now() - start);\n foundSolCountLock_.lock();\n unsigned int nrSol = ++foundSolCount_;\n foundSolCountLock_.unlock();\n\n if (nrSol >= maxSolCount)\n ptc->terminate();\n\n OMPL_DEBUG(\"ParallelPlan.solveMore: Solution found by %s in %lf seconds\", planner->getName().c_str(), duration);\n\n const std::vector &paths = pdef_->getSolutions();\n\n boost::mutex::scoped_lock slock(phlock_);\n start = time::now();\n unsigned int attempts = 0;\n for (std::size_t i = 0 ; i < paths.size() ; ++i)\n attempts += phybrid_->recordPath(paths[i].path_, false);\n\n if (phybrid_->pathCount() >= minSolCount)\n phybrid_->computeHybridPath();\n\n duration = time::seconds(time::now() - start);\n OMPL_DEBUG(\"ParallelPlan.solveMore: Spent %f seconds hybridizing %u solution paths (attempted %u connections between paths)\", duration,\n (unsigned int)phybrid_->pathCount(), attempts);\n }\n}\nSpellcheck\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2011, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Ioan Sucan *\/\n\n#include \"ompl\/tools\/multiplan\/ParallelPlan.h\"\n#include \"ompl\/geometric\/PathHybridization.h\"\n\nompl::tools::ParallelPlan::ParallelPlan(const base::ProblemDefinitionPtr &pdef) :\n pdef_(pdef), phybrid_(new geometric::PathHybridization(pdef->getSpaceInformation()))\n{\n}\n\nompl::tools::ParallelPlan::~ParallelPlan()\n{\n}\n\nvoid ompl::tools::ParallelPlan::addPlanner(const base::PlannerPtr &planner)\n{\n if (planner && planner->getSpaceInformation().get() != pdef_->getSpaceInformation().get())\n throw Exception(\"Planner instance does not match space information\");\n if (planner->getProblemDefinition().get() != pdef_.get())\n planner->setProblemDefinition(pdef_);\n planners_.push_back(planner);\n}\n\nvoid ompl::tools::ParallelPlan::addPlannerAllocator(const base::PlannerAllocator &pa)\n{\n base::PlannerPtr planner = pa(pdef_->getSpaceInformation());\n planner->setProblemDefinition(pdef_);\n planners_.push_back(planner);\n}\n\nvoid ompl::tools::ParallelPlan::clearPlanners()\n{\n planners_.clear();\n}\n\nvoid ompl::tools::ParallelPlan::clearHybridizationPaths()\n{\n phybrid_->clear();\n}\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(double solveTime, bool hybridize)\n{\n return solve(solveTime, 1, planners_.size(), hybridize);\n}\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(double solveTime, std::size_t minSolCount, std::size_t maxSolCount, bool hybridize)\n{\n return solve(base::timedPlannerTerminationCondition(solveTime, std::min(solveTime \/ 100.0, 0.1)), minSolCount, maxSolCount, hybridize);\n}\n\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(const base::PlannerTerminationCondition &ptc, bool hybridize)\n{\n return solve(ptc, 1, planners_.size(), hybridize);\n}\n\nompl::base::PlannerStatus ompl::tools::ParallelPlan::solve(const base::PlannerTerminationCondition &ptc, std::size_t minSolCount,\n std::size_t maxSolCount, bool hybridize)\n{\n if (!pdef_->getSpaceInformation()->isSetup())\n pdef_->getSpaceInformation()->setup();\n foundSolCount_ = 0;\n\n time::point start = time::now();\n std::vector threads(planners_.size());\n\n \/\/ Decide if we are combining solutions or just taking the first one\n if (hybridize)\n for (std::size_t i = 0 ; i < threads.size() ; ++i)\n threads[i] = new boost::thread(boost::bind(&ParallelPlan::solveMore, this, planners_[i].get(), minSolCount, maxSolCount, &ptc));\n else\n for (std::size_t i = 0 ; i < threads.size() ; ++i)\n threads[i] = new boost::thread(boost::bind(&ParallelPlan::solveOne, this, planners_[i].get(), minSolCount, &ptc));\n\n for (std::size_t i = 0 ; i < threads.size() ; ++i)\n {\n threads[i]->join();\n delete threads[i];\n }\n\n if (hybridize)\n {\n if (phybrid_->pathCount() > 1)\n if (const base::PathPtr &hsol = phybrid_->getHybridPath())\n {\n geometric::PathGeometric *pg = static_cast(hsol.get());\n double difference = 0.0;\n bool approximate = !pdef_->getGoal()->isSatisfied(pg->getStates().back(), &difference);\n pdef_->addSolutionPath(hsol, approximate, difference, phybrid_->getName()); \/\/ name this solution after the hybridization algorithm\n }\n }\n\n if (pdef_->hasSolution())\n OMPL_INFORM(\"ParallelPlan::solve(): Solution found by one or more threads in %f seconds\", time::seconds(time::now() - start));\n else\n OMPL_WARN(\"ParallelPlan::solve(): Unable to find solution by any of the threads in %f seconds\", time::seconds(time::now() - start));\n\n return base::PlannerStatus(pdef_->hasSolution(), pdef_->hasApproximateSolution());\n}\n\nvoid ompl::tools::ParallelPlan::solveOne(base::Planner *planner, std::size_t minSolCount, const base::PlannerTerminationCondition *ptc)\n{\n OMPL_DEBUG(\"ParallelPlan.solveOne starting planner %s\", planner->getName().c_str());\n\n time::point start = time::now();\n if (planner->solve(*ptc))\n {\n double duration = time::seconds(time::now() - start);\n foundSolCountLock_.lock();\n unsigned int nrSol = ++foundSolCount_;\n foundSolCountLock_.unlock();\n if (nrSol >= minSolCount)\n ptc->terminate();\n OMPL_DEBUG(\"ParallelPlan.solveOne: Solution found by %s in %lf seconds\", planner->getName().c_str(), duration);\n }\n}\n\nvoid ompl::tools::ParallelPlan::solveMore(base::Planner *planner, std::size_t minSolCount, std::size_t maxSolCount,\n const base::PlannerTerminationCondition *ptc)\n{\n OMPL_DEBUG(\"ParallelPlan.solveMore: starting planner %s\", planner->getName().c_str());\n\n time::point start = time::now();\n if (planner->solve(*ptc))\n {\n double duration = time::seconds(time::now() - start);\n foundSolCountLock_.lock();\n unsigned int nrSol = ++foundSolCount_;\n foundSolCountLock_.unlock();\n\n if (nrSol >= maxSolCount)\n ptc->terminate();\n\n OMPL_DEBUG(\"ParallelPlan.solveMore: Solution found by %s in %lf seconds\", planner->getName().c_str(), duration);\n\n const std::vector &paths = pdef_->getSolutions();\n\n boost::mutex::scoped_lock slock(phlock_);\n start = time::now();\n unsigned int attempts = 0;\n for (std::size_t i = 0 ; i < paths.size() ; ++i)\n attempts += phybrid_->recordPath(paths[i].path_, false);\n\n if (phybrid_->pathCount() >= minSolCount)\n phybrid_->computeHybridPath();\n\n duration = time::seconds(time::now() - start);\n OMPL_DEBUG(\"ParallelPlan.solveMore: Spent %f seconds hybridizing %u solution paths (attempted %u connections between paths)\", duration,\n (unsigned int)phybrid_->pathCount(), attempts);\n }\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/inc_navier_stokes_stab_base.h\"\n\n\/\/ GRINS\n#include \"grins\/assembly_context.h\"\n\nnamespace GRINS\n{\n\n IncompressibleNavierStokesStabilizationBase::IncompressibleNavierStokesStabilizationBase( const std::string& physics_name, \n const GetPot& input )\n : IncompressibleNavierStokesBase(physics_name,input),\n _stab_helper( input )\n {\n this->read_input_options(input);\n\n return;\n }\n\n IncompressibleNavierStokesStabilizationBase::~IncompressibleNavierStokesStabilizationBase()\n {\n return;\n }\n\n void IncompressibleNavierStokesStabilizationBase::init_context( AssemblyContext& context )\n {\n \/\/ First call base class\n IncompressibleNavierStokesBase::init_context(context);\n \n \/\/ We need pressure derivatives\n context.get_element_fe(this->_flow_vars.p_var())->get_dphi();\n\n \/\/ We also need second derivatives, so initialize those.\n context.get_element_fe(this->_flow_vars.u_var())->get_d2phi();\n\n return;\n }\n\n void IncompressibleNavierStokesStabilizationBase::init_variables( libMesh::FEMSystem* system )\n {\n \/\/ First call base class\n IncompressibleNavierStokesBase::init_variables(system);\n\n _stab_helper.init(*system);\n\n return;\n }\n\n} \/\/ namespace GRINS\nThought I'd gotten rid of that read_input_options call.\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/inc_navier_stokes_stab_base.h\"\n\n\/\/ GRINS\n#include \"grins\/assembly_context.h\"\n\nnamespace GRINS\n{\n\n IncompressibleNavierStokesStabilizationBase::IncompressibleNavierStokesStabilizationBase( const std::string& physics_name, \n const GetPot& input )\n : IncompressibleNavierStokesBase(physics_name,input),\n _stab_helper( input )\n {\n return;\n }\n\n IncompressibleNavierStokesStabilizationBase::~IncompressibleNavierStokesStabilizationBase()\n {\n return;\n }\n\n void IncompressibleNavierStokesStabilizationBase::init_context( AssemblyContext& context )\n {\n \/\/ First call base class\n IncompressibleNavierStokesBase::init_context(context);\n \n \/\/ We need pressure derivatives\n context.get_element_fe(this->_flow_vars.p_var())->get_dphi();\n\n \/\/ We also need second derivatives, so initialize those.\n context.get_element_fe(this->_flow_vars.u_var())->get_d2phi();\n\n return;\n }\n\n void IncompressibleNavierStokesStabilizationBase::init_variables( libMesh::FEMSystem* system )\n {\n \/\/ First call base class\n IncompressibleNavierStokesBase::init_variables(system);\n\n _stab_helper.init(*system);\n\n return;\n }\n\n} \/\/ namespace GRINS\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n#include \"maemoremotecopyfacility.h\"\n\n#include \"maemoglobal.h\"\n\n#include \n#include \n#include \n\n#include \n\nusing namespace RemoteLinux;\nusing namespace Utils;\n\nnamespace Madde {\nnamespace Internal {\n\nMaemoRemoteCopyFacility::MaemoRemoteCopyFacility(QObject *parent) :\n QObject(parent), m_isCopying(false), m_copyRunner(0)\n{\n}\n\nMaemoRemoteCopyFacility::~MaemoRemoteCopyFacility() {}\n\nvoid MaemoRemoteCopyFacility::copyFiles(const SshConnection::Ptr &connection,\n const LinuxDeviceConfiguration::ConstPtr &devConf,\n const QList &deployables, const QString &mountPoint)\n{\n Q_ASSERT(connection->state() == SshConnection::Connected);\n Q_ASSERT(!m_isCopying);\n\n m_devConf = devConf;\n m_deployables = deployables;\n m_mountPoint = mountPoint;\n\n delete m_copyRunner;\n m_copyRunner = new SshRemoteProcessRunner(connection, this);\n connect(m_copyRunner, SIGNAL(connectionError(Utils::SshError)), SLOT(handleConnectionError()));\n connect(m_copyRunner, SIGNAL(processOutputAvailable(QByteArray)),\n SLOT(handleRemoteStdout(QByteArray)));\n connect(m_copyRunner, SIGNAL(processErrorOutputAvailable(QByteArray)),\n SLOT(handleRemoteStderr(QByteArray)));\n connect(m_copyRunner, SIGNAL(processClosed(int)), SLOT(handleCopyFinished(int)));\n\n m_isCopying = true;\n copyNextFile();\n}\n\nvoid MaemoRemoteCopyFacility::cancel()\n{\n Q_ASSERT(m_isCopying);\n\n \/\/ TODO: Make member as to not waste memory.\n SshRemoteProcessRunner * const killProcess\n = new SshRemoteProcessRunner(m_copyRunner->connection(), this);\n killProcess->run(\"pkill cp\");\n setFinished();\n}\n\nvoid MaemoRemoteCopyFacility::handleConnectionError()\n{\n const QString errMsg = m_copyRunner->connection()->errorString();\n setFinished();\n emit finished(tr(\"Connection failed: %1\").arg(errMsg));\n}\n\nvoid MaemoRemoteCopyFacility::handleRemoteStdout(const QByteArray &output)\n{\n emit stdoutData(QString::fromUtf8(output));\n}\n\nvoid MaemoRemoteCopyFacility::handleRemoteStderr(const QByteArray &output)\n{\n emit stderrData(QString::fromUtf8(output));\n}\n\nvoid MaemoRemoteCopyFacility::handleCopyFinished(int exitStatus)\n{\n if (!m_isCopying)\n return;\n\n if (exitStatus != SshRemoteProcess::ExitedNormally\n || m_copyRunner->process()->exitCode() != 0) {\n setFinished();\n emit finished(tr(\"Error: Copy command failed.\"));\n } else {\n emit fileCopied(m_deployables.takeFirst());\n copyNextFile();\n }\n}\n\nvoid MaemoRemoteCopyFacility::copyNextFile()\n{\n Q_ASSERT(m_isCopying);\n\n if (m_deployables.isEmpty()) {\n setFinished();\n emit finished();\n return;\n }\n\n const DeployableFile &d = m_deployables.first();\n QString sourceFilePath = m_mountPoint;\n#ifdef Q_OS_WIN\n const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath);\n sourceFilePath += QLatin1Char('\/') + localFilePath.at(0).toLower()\n + localFilePath.mid(2);\n#else\n sourceFilePath += d.localFilePath;\n#endif\n\n QString command = QString::fromLatin1(\"%1 mkdir -p %3 && %1 cp -a %2 %3\")\n .arg(MaemoGlobal::remoteSudo(m_devConf->osType(),\n m_copyRunner->connection()->connectionParameters().userName),\n sourceFilePath, d.remoteDir);\n emit progress(tr(\"Copying file '%1' to directory '%2' on the device...\")\n .arg(d.localFilePath, d.remoteDir));\n m_copyRunner->run(command.toUtf8());\n}\n\nvoid MaemoRemoteCopyFacility::setFinished()\n{\n disconnect(m_copyRunner, 0, this, 0);\n delete m_copyRunner;\n m_copyRunner = 0;\n m_deployables.clear();\n m_isCopying = false;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Madde\nFix warning\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n#include \"maemoremotecopyfacility.h\"\n\n#include \"maemoglobal.h\"\n\n#include \n#include \n#include \n\n#include \n\nusing namespace RemoteLinux;\nusing namespace Utils;\n\nnamespace Madde {\nnamespace Internal {\n\nMaemoRemoteCopyFacility::MaemoRemoteCopyFacility(QObject *parent) :\n QObject(parent), m_copyRunner(0), m_isCopying(false)\n{\n}\n\nMaemoRemoteCopyFacility::~MaemoRemoteCopyFacility() {}\n\nvoid MaemoRemoteCopyFacility::copyFiles(const SshConnection::Ptr &connection,\n const LinuxDeviceConfiguration::ConstPtr &devConf,\n const QList &deployables, const QString &mountPoint)\n{\n Q_ASSERT(connection->state() == SshConnection::Connected);\n Q_ASSERT(!m_isCopying);\n\n m_devConf = devConf;\n m_deployables = deployables;\n m_mountPoint = mountPoint;\n\n delete m_copyRunner;\n m_copyRunner = new SshRemoteProcessRunner(connection, this);\n connect(m_copyRunner, SIGNAL(connectionError(Utils::SshError)), SLOT(handleConnectionError()));\n connect(m_copyRunner, SIGNAL(processOutputAvailable(QByteArray)),\n SLOT(handleRemoteStdout(QByteArray)));\n connect(m_copyRunner, SIGNAL(processErrorOutputAvailable(QByteArray)),\n SLOT(handleRemoteStderr(QByteArray)));\n connect(m_copyRunner, SIGNAL(processClosed(int)), SLOT(handleCopyFinished(int)));\n\n m_isCopying = true;\n copyNextFile();\n}\n\nvoid MaemoRemoteCopyFacility::cancel()\n{\n Q_ASSERT(m_isCopying);\n\n \/\/ TODO: Make member as to not waste memory.\n SshRemoteProcessRunner * const killProcess\n = new SshRemoteProcessRunner(m_copyRunner->connection(), this);\n killProcess->run(\"pkill cp\");\n setFinished();\n}\n\nvoid MaemoRemoteCopyFacility::handleConnectionError()\n{\n const QString errMsg = m_copyRunner->connection()->errorString();\n setFinished();\n emit finished(tr(\"Connection failed: %1\").arg(errMsg));\n}\n\nvoid MaemoRemoteCopyFacility::handleRemoteStdout(const QByteArray &output)\n{\n emit stdoutData(QString::fromUtf8(output));\n}\n\nvoid MaemoRemoteCopyFacility::handleRemoteStderr(const QByteArray &output)\n{\n emit stderrData(QString::fromUtf8(output));\n}\n\nvoid MaemoRemoteCopyFacility::handleCopyFinished(int exitStatus)\n{\n if (!m_isCopying)\n return;\n\n if (exitStatus != SshRemoteProcess::ExitedNormally\n || m_copyRunner->process()->exitCode() != 0) {\n setFinished();\n emit finished(tr(\"Error: Copy command failed.\"));\n } else {\n emit fileCopied(m_deployables.takeFirst());\n copyNextFile();\n }\n}\n\nvoid MaemoRemoteCopyFacility::copyNextFile()\n{\n Q_ASSERT(m_isCopying);\n\n if (m_deployables.isEmpty()) {\n setFinished();\n emit finished();\n return;\n }\n\n const DeployableFile &d = m_deployables.first();\n QString sourceFilePath = m_mountPoint;\n#ifdef Q_OS_WIN\n const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath);\n sourceFilePath += QLatin1Char('\/') + localFilePath.at(0).toLower()\n + localFilePath.mid(2);\n#else\n sourceFilePath += d.localFilePath;\n#endif\n\n QString command = QString::fromLatin1(\"%1 mkdir -p %3 && %1 cp -a %2 %3\")\n .arg(MaemoGlobal::remoteSudo(m_devConf->osType(),\n m_copyRunner->connection()->connectionParameters().userName),\n sourceFilePath, d.remoteDir);\n emit progress(tr(\"Copying file '%1' to directory '%2' on the device...\")\n .arg(d.localFilePath, d.remoteDir));\n m_copyRunner->run(command.toUtf8());\n}\n\nvoid MaemoRemoteCopyFacility::setFinished()\n{\n disconnect(m_copyRunner, 0, this, 0);\n delete m_copyRunner;\n m_copyRunner = 0;\n m_deployables.clear();\n m_isCopying = false;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Madde\n<|endoftext|>"} {"text":"\/*\n * prepare_state.cpp\n *\n * Created on: Jul 20, 2015\n * Author: zmij\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace tip {\nnamespace db {\nnamespace pg {\nnamespace detail {\n\nnamespace {\n\/** Local logging facility *\/\nusing namespace tip::log;\n\nconst std::string LOG_CATEGORY = \"PGEQUERY\";\nlogger::event_severity DEFAULT_SEVERITY = logger::TRACE;\nlocal\nlocal_log(logger::event_severity s = DEFAULT_SEVERITY)\n{\n\treturn local(LOG_CATEGORY, s);\n}\n\n} \/\/ namespace\n\/\/ For more convenient changing severity, eg local_log(logger::WARNING)\nusing tip::log::logger;\n\n\nextended_query_state::extended_query_state(connection_base& conn,\n\t\tstd::string const& query,\n\t\tparam_types const& types,\n\t\tparams_buffer const& params,\n\t\tresult_callback const& cb,\n\t\tquery_error_callback const& err)\n\t: basic_state(conn), query_(query), param_types_(types), params_(params),\n\t result_(cb), error_(err), stage_(PARSE)\n{\n}\n\nbool\nextended_query_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tswitch (tag) {\n\t\tcase ready_for_query_tag : {\n\t\t\tif (stage_ == PARSE) {\n\t\t\t\tstage_ = BIND;\n\t\t\t\tenter();\n\t\t\t} else if (stage_ == BIND) {\n\t\t\t\tstage_ = FETCH;\n\t\t\t\tenter();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tcase command_complete_tag: {\n\t\t\tconn.pop_state(this);\n\t\t\tconn.state()->handle_message(m);\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn false;\n}\n\nvoid\nextended_query_state::do_enter()\n{\n\tstd::string query_hash = \"q_\" +\n\t\t\tstd::string(boost::md5( query_.c_str() ).digest().hex_str_value());\n\tif (conn.is_prepared(query_hash)) {\n\t\tstd::string portal_name = \"p_\" +\n\t\t\t\tstd::string(boost::md5( query_hash.c_str() ).digest().hex_str_value());\n\t\tif (stage_ == PARSE) {\n\t\t\tstage_ = BIND;\n\t\t}\n\t\tif (stage_ == BIND) {\n\t\t\tlocal_log() << \"Bind params\";\n\t\t\t\/\/ bind params\n\t\t\tconn.push_state(connection_state_ptr(\n\t\t\t\t\tnew bind_state(conn, query_hash, params_, error_) ));\n\t\t} else {\n\t\t\tlocal_log() << \"Execute statement\";\n\t\t\t\/\/ execute and fetch\n\t\t\tconn.push_state(connection_state_ptr(\n\t\t\t\t\tnew execute_state(conn, \"\", result_, error_) ));\n\t\t}\n\t} else {\n\t\t\/\/ parse\n\t\tconn.push_state( connection_state_ptr(\n\t\t\t\tnew parse_state( conn, query_hash, query_, param_types_, error_ ) ) );\n\t}\n}\n\nparse_state::parse_state(connection_base& conn,\n\t\tstd::string const& query_name,\n\t\tstd::string const& query,\n\t\textended_query_state::param_types const& types,\n\t\tquery_error_callback const& err)\n\t: basic_state(conn), query_name_(query_name), query_(query), param_types_(types), error_(err)\n{\n}\n\nvoid\nparse_state::do_enter()\n{\n\t{\n\t\tlocal_log() << \"Parse query \"\n\t\t\t\t<< (util::MAGENTA | util::BRIGHT)\n\t\t\t\t<< query_\n\t\t\t\t<< logger::severity_color();\n\t}\n\n\t{\n\t\tmessage parse(parse_tag);\n\t\tparse.write(query_name_);\n\t\tparse.write(query_);\n\t\tparse.write( (smallint)param_types_.size() );\n\t\tfor (oids::type::oid_type oid : param_types_) {\n\t\t\tparse.write( (integer)oid );\n\t\t}\n\t\tconn.send(parse);\n\t}\n\t{\n\t\tmessage describe(describe_tag);\n\t\tdescribe.write('S');\n\t\tdescribe.write(query_name_);\n\t\tconn.send(describe);\n\t}\n\t{\n\t\tmessage sync(sync_tag);\n\t\tconn.send(sync);\n\t}\n}\n\nbool\nparse_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tswitch (tag) {\n\t\tcase parse_complete_tag : {\n\t\t\t{\n\t\t\t\tlocal_log() << \"Parse complete\";\n\t\t\t}\n\t\t\tconn.set_prepared(query_name_);\n\t\t\tconn.pop_state(this);\n\t\t\treturn true;\n\t\t}\n\t\tcase ready_for_query_tag : {\n\t\t\t{\n\t\t\t\tlocal_log() << \"Ready for query in parse state\";\n\t\t\t}\n\t\t\tmessage m(sync_tag);\n\t\t\tconn.send(m);\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn false;\n}\n\nbind_state::bind_state(connection_base& conn,\n\t\tstd::string const& query_name,\n\t\tparams_buffer const& params,\n\t\tquery_error_callback const& err)\n\t: basic_state(conn), query_name_(query_name),\n\t params_(params)\n{\n}\n\nvoid\nbind_state::do_enter()\n{\n\t{\n\t\tmessage m(bind_tag);\n\t\tm.write(std::string(\"\"));\n\t\tm.write(query_name_);\n\t\tif (!params_.empty()) {\n\t\t\tlocal_log() << \"Params buffer size \" << params_.size();\n\t\t\tauto out = m.output();\n\t\t\tstd::copy( params_.begin(), params_.end(), out );\n\t\t} else {\n\t\t\tm.write((smallint)0); \/\/ parameter format codes\n\t\t\tm.write((smallint)0); \/\/ number of parameters\n\t\t}\n\t\tm.write((smallint)0); \/\/ result format codes\n\t\tconn.send(m);\n\t}\n\t{\n\t\tmessage m(sync_tag);\n\t\tconn.send(m);\n\t}\n}\n\nbool\nbind_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tswitch (tag) {\n\t\tcase bind_complete_tag: {\n\t\t\t{\n\t\t\t\tlocal_log() << \"Bind complete\";\n\t\t\t}\n\t\t\tconn.pop_state(this);\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn false;\n}\n\nexecute_state::execute_state(connection_base& conn,\n\t\tstd::string const& portal_name,\n\t\tresult_callback const& cb,\n\t\tquery_error_callback const& err)\n\t: fetch_state(conn, cb, err), portal_name_(portal_name),\n\t sync_sent_(false), prev_rows_(0)\n{\n}\n\nvoid\nexecute_state::do_enter()\n{\n\t{\n\t\tmessage m(describe_tag);\n\t\tm.write('P');\n\t\tm.write(portal_name_);\n\t\tconn.send(m);\n\t}\n\t{\n\t\tmessage m(sync_tag);\n\t\tconn.send(m);\n\t}\n}\n\nbool\nexecute_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tif (fetch_state::do_handle_message(m) && tag != command_complete_tag) {\n\t\treturn true;\n\t} else {\n\t\tswitch (tag) {\n\t\t\tcase ready_for_query_tag: {\n\t\t\t\tif (!complete_) {\n\t\t\t\t\t{\n\t\t\t\t\t\tlocal_log() << \"Ready for query in execute state\";\n\t\t\t\t\t}\n\t\t\t\t\t{\n\t\t\t\t\t\tsync_sent_ = false;\n\t\t\t\t\t\tmessage m(execute_tag);\n\t\t\t\t\t\tm.write(portal_name_);\n\t\t\t\t\t\tm.write((integer)0); \/\/ row limit\n\t\t\t\t\t\tconn.send(m);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcase command_complete_tag: {\n\t\t\t\t{\n\t\t\t\t\tlocal_log() << \"Command complete in execute state\";\n\t\t\t\t}\n\t\t\t\tconn.pop_state(this);\n\t\t\t\tconn.state()->handle_message(m);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid\nexecute_state::on_package_complete(size_t bytes)\n{\n\tfetch_state::on_package_complete(bytes);\n\t{\n\t\tlocal_log() << \"Package complete in execute state\";\n\t}\n\tif (!result_) {\n\t\tmessage m(sync_tag);\n\t\tconn.send(m);\n\t\tprev_rows_ = 0;\n\t\tlocal_log() << \"Send sync\";\n\t} else if (result_) {\n\t\tif (result_->size() == prev_rows_) {\n\t\t\tmessage m(sync_tag);\n\t\t\tconn.send(m);\n\t\t\tlocal_log() << \"Send sync\";\n\t\t}\n\t\tprev_rows_ = result_->size();\n\t}\n\/\/\tif (!complete_ && !sync_sent_) {\n\/\/\t\tmessage m(sync_tag);\n\/\/\t\tconn.send(m);\n\/\/\t\tsync_sent_ = true;\n\/\/\t}\n}\n\n} \/* namespace detail *\/\n} \/* namespace pg *\/\n} \/* namespace db *\/\n} \/* namespace tip *\/\nAdd parameter types to query \"name\" hash\/*\n * prepare_state.cpp\n *\n * Created on: Jul 20, 2015\n * Author: zmij\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace tip {\nnamespace db {\nnamespace pg {\nnamespace detail {\n\nnamespace {\n\/** Local logging facility *\/\nusing namespace tip::log;\n\nconst std::string LOG_CATEGORY = \"PGEQUERY\";\nlogger::event_severity DEFAULT_SEVERITY = logger::TRACE;\nlocal\nlocal_log(logger::event_severity s = DEFAULT_SEVERITY)\n{\n\treturn local(LOG_CATEGORY, s);\n}\n\n} \/\/ namespace\n\/\/ For more convenient changing severity, eg local_log(logger::WARNING)\nusing tip::log::logger;\n\n\nextended_query_state::extended_query_state(connection_base& conn,\n\t\tstd::string const& query,\n\t\tparam_types const& types,\n\t\tparams_buffer const& params,\n\t\tresult_callback const& cb,\n\t\tquery_error_callback const& err)\n\t: basic_state(conn), query_(query), param_types_(types), params_(params),\n\t result_(cb), error_(err), stage_(PARSE)\n{\n}\n\nbool\nextended_query_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tswitch (tag) {\n\t\tcase ready_for_query_tag : {\n\t\t\tif (stage_ == PARSE) {\n\t\t\t\tstage_ = BIND;\n\t\t\t\tenter();\n\t\t\t} else if (stage_ == BIND) {\n\t\t\t\tstage_ = FETCH;\n\t\t\t\tenter();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tcase command_complete_tag: {\n\t\t\tconn.pop_state(this);\n\t\t\tconn.state()->handle_message(m);\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn false;\n}\n\nvoid\nextended_query_state::do_enter()\n{\n\tstd::ostringstream os;\n\tos << query_ << \" {\";\n\tfor (auto oid : param_types_) {\n\t\tos << oid;\n\t}\n\tos << \"}\";\n\tstd::string query_hash = \"q_\" +\n\t\t\tstd::string(boost::md5( os.str().c_str() ).digest().hex_str_value());\n\tif (conn.is_prepared(query_hash)) {\n\t\tstd::string portal_name = \"p_\" +\n\t\t\t\tstd::string(boost::md5( query_hash.c_str() ).digest().hex_str_value());\n\t\tif (stage_ == PARSE) {\n\t\t\tstage_ = BIND;\n\t\t}\n\t\tif (stage_ == BIND) {\n\t\t\tlocal_log() << \"Bind params\";\n\t\t\t\/\/ bind params\n\t\t\tconn.push_state(connection_state_ptr(\n\t\t\t\t\tnew bind_state(conn, query_hash, params_, error_) ));\n\t\t} else {\n\t\t\tlocal_log() << \"Execute statement\";\n\t\t\t\/\/ execute and fetch\n\t\t\tconn.push_state(connection_state_ptr(\n\t\t\t\t\tnew execute_state(conn, \"\", result_, error_) ));\n\t\t}\n\t} else {\n\t\t\/\/ parse\n\t\tconn.push_state( connection_state_ptr(\n\t\t\t\tnew parse_state( conn, query_hash, query_, param_types_, error_ ) ) );\n\t}\n}\n\nparse_state::parse_state(connection_base& conn,\n\t\tstd::string const& query_name,\n\t\tstd::string const& query,\n\t\textended_query_state::param_types const& types,\n\t\tquery_error_callback const& err)\n\t: basic_state(conn), query_name_(query_name), query_(query), param_types_(types), error_(err)\n{\n}\n\nvoid\nparse_state::do_enter()\n{\n\t{\n\t\tlocal_log() << \"Parse query \"\n\t\t\t\t<< (util::MAGENTA | util::BRIGHT)\n\t\t\t\t<< query_\n\t\t\t\t<< logger::severity_color();\n\t}\n\n\t{\n\t\tmessage parse(parse_tag);\n\t\tparse.write(query_name_);\n\t\tparse.write(query_);\n\t\tparse.write( (smallint)param_types_.size() );\n\t\tfor (oids::type::oid_type oid : param_types_) {\n\t\t\tparse.write( (integer)oid );\n\t\t}\n\t\tconn.send(parse);\n\t}\n\t{\n\t\tmessage describe(describe_tag);\n\t\tdescribe.write('S');\n\t\tdescribe.write(query_name_);\n\t\tconn.send(describe);\n\t}\n\t{\n\t\tmessage sync(sync_tag);\n\t\tconn.send(sync);\n\t}\n}\n\nbool\nparse_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tswitch (tag) {\n\t\tcase parse_complete_tag : {\n\t\t\t{\n\t\t\t\tlocal_log() << \"Parse complete\";\n\t\t\t}\n\t\t\tconn.set_prepared(query_name_);\n\t\t\tconn.pop_state(this);\n\t\t\treturn true;\n\t\t}\n\t\tcase ready_for_query_tag : {\n\t\t\t{\n\t\t\t\tlocal_log() << \"Ready for query in parse state\";\n\t\t\t}\n\t\t\tmessage m(sync_tag);\n\t\t\tconn.send(m);\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn false;\n}\n\nbind_state::bind_state(connection_base& conn,\n\t\tstd::string const& query_name,\n\t\tparams_buffer const& params,\n\t\tquery_error_callback const& err)\n\t: basic_state(conn), query_name_(query_name),\n\t params_(params)\n{\n}\n\nvoid\nbind_state::do_enter()\n{\n\t{\n\t\tmessage m(bind_tag);\n\t\tm.write(std::string(\"\"));\n\t\tm.write(query_name_);\n\t\tif (!params_.empty()) {\n\t\t\tlocal_log() << \"Params buffer size \" << params_.size();\n\t\t\tauto out = m.output();\n\t\t\tstd::copy( params_.begin(), params_.end(), out );\n\t\t} else {\n\t\t\tm.write((smallint)0); \/\/ parameter format codes\n\t\t\tm.write((smallint)0); \/\/ number of parameters\n\t\t}\n\t\tm.write((smallint)0); \/\/ result format codes\n\t\tconn.send(m);\n\t}\n\t{\n\t\tmessage m(sync_tag);\n\t\tconn.send(m);\n\t}\n}\n\nbool\nbind_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tswitch (tag) {\n\t\tcase bind_complete_tag: {\n\t\t\t{\n\t\t\t\tlocal_log() << \"Bind complete\";\n\t\t\t}\n\t\t\tconn.pop_state(this);\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn false;\n}\n\nexecute_state::execute_state(connection_base& conn,\n\t\tstd::string const& portal_name,\n\t\tresult_callback const& cb,\n\t\tquery_error_callback const& err)\n\t: fetch_state(conn, cb, err), portal_name_(portal_name),\n\t sync_sent_(false), prev_rows_(0)\n{\n}\n\nvoid\nexecute_state::do_enter()\n{\n\t{\n\t\tmessage m(describe_tag);\n\t\tm.write('P');\n\t\tm.write(portal_name_);\n\t\tconn.send(m);\n\t}\n\t{\n\t\tmessage m(sync_tag);\n\t\tconn.send(m);\n\t}\n}\n\nbool\nexecute_state::do_handle_message(message_ptr m)\n{\n\tmessage_tag tag = m->tag();\n\tif (fetch_state::do_handle_message(m) && tag != command_complete_tag) {\n\t\treturn true;\n\t} else {\n\t\tswitch (tag) {\n\t\t\tcase ready_for_query_tag: {\n\t\t\t\tif (!complete_) {\n\t\t\t\t\t{\n\t\t\t\t\t\tlocal_log() << \"Ready for query in execute state\";\n\t\t\t\t\t}\n\t\t\t\t\t{\n\t\t\t\t\t\tsync_sent_ = false;\n\t\t\t\t\t\tmessage m(execute_tag);\n\t\t\t\t\t\tm.write(portal_name_);\n\t\t\t\t\t\tm.write((integer)0); \/\/ row limit\n\t\t\t\t\t\tconn.send(m);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcase command_complete_tag: {\n\t\t\t\t{\n\t\t\t\t\tlocal_log() << \"Command complete in execute state\";\n\t\t\t\t}\n\t\t\t\tconn.pop_state(this);\n\t\t\t\tconn.state()->handle_message(m);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid\nexecute_state::on_package_complete(size_t bytes)\n{\n\tfetch_state::on_package_complete(bytes);\n\t{\n\t\tlocal_log() << \"Package complete in execute state\";\n\t}\n\tif (!result_) {\n\t\tmessage m(sync_tag);\n\t\tconn.send(m);\n\t\tprev_rows_ = 0;\n\t\tlocal_log() << \"Send sync\";\n\t} else if (result_) {\n\t\tif (result_->size() == prev_rows_) {\n\t\t\tmessage m(sync_tag);\n\t\t\tconn.send(m);\n\t\t\tlocal_log() << \"Send sync\";\n\t\t}\n\t\tprev_rows_ = result_->size();\n\t}\n\/\/\tif (!complete_ && !sync_sent_) {\n\/\/\t\tmessage m(sync_tag);\n\/\/\t\tconn.send(m);\n\/\/\t\tsync_sent_ = true;\n\/\/\t}\n}\n\n} \/* namespace detail *\/\n} \/* namespace pg *\/\n} \/* namespace db *\/\n} \/* namespace tip *\/\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace svl;\n\nclass MockedStyleSheet : public SfxStyleSheetBase\n{\n public:\n MockedStyleSheet(const rtl::OUString& name, SfxStyleFamily fam = SFX_STYLE_FAMILY_CHAR)\n : SfxStyleSheetBase(name, NULL, fam, 0)\n {;}\n\n};\n\nstruct DummyPredicate : public StyleSheetPredicate {\n bool Check(const SfxStyleSheetBase& styleSheet) SAL_OVERRIDE {\n (void)styleSheet; \/\/ fix compiler warning\n return true;\n }\n};\n\nclass IndexedStyleSheetsTest : public CppUnit::TestFixture\n{\n void InstantiationWorks();\n void AddedStylesheetsCanBeFoundAndRetrievedByPosition();\n void AddingSameStylesheetTwiceHasNoEffect();\n void RemovedStyleSheetIsNotFound();\n void RemovingStyleSheetWhichIsNotAvailableHasNoEffect();\n void StyleSheetsCanBeRetrievedByTheirName();\n void KnowsThatItStoresAStyleSheet();\n void PositionCanBeQueriedByFamily();\n void OnlyOneStyleSheetIsReturnedWhenReturnFirstIsUsed();\n\n \/\/ Adds code needed to register the test suite\n CPPUNIT_TEST_SUITE(IndexedStyleSheetsTest);\n\n CPPUNIT_TEST(InstantiationWorks);\n CPPUNIT_TEST(AddedStylesheetsCanBeFoundAndRetrievedByPosition);\n CPPUNIT_TEST(AddingSameStylesheetTwiceHasNoEffect);\n CPPUNIT_TEST(RemovedStyleSheetIsNotFound);\n CPPUNIT_TEST(RemovingStyleSheetWhichIsNotAvailableHasNoEffect);\n CPPUNIT_TEST(StyleSheetsCanBeRetrievedByTheirName);\n CPPUNIT_TEST(KnowsThatItStoresAStyleSheet);\n CPPUNIT_TEST(PositionCanBeQueriedByFamily);\n CPPUNIT_TEST(OnlyOneStyleSheetIsReturnedWhenReturnFirstIsUsed);\n\n \/\/ End of test suite definition\n CPPUNIT_TEST_SUITE_END();\n\n};\n\nvoid IndexedStyleSheetsTest::InstantiationWorks()\n{\n IndexedStyleSheets iss;\n}\n\nvoid IndexedStyleSheetsTest::AddedStylesheetsCanBeFoundAndRetrievedByPosition()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name2));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n unsigned pos = iss.FindStyleSheetPosition(*sheet2);\n rtl::Reference retrieved = iss.GetStyleSheetByPosition(pos);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"retrieved sheet is that which has been inserted.\", sheet2.get(), retrieved.get());\n}\n\nvoid IndexedStyleSheetsTest::AddingSameStylesheetTwiceHasNoEffect()\n{\n rtl::Reference sheet1(new MockedStyleSheet(rtl::OUString(\"sheet1\")));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n iss.AddStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n}\n\nvoid IndexedStyleSheetsTest::RemovedStyleSheetIsNotFound()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name2));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.RemoveStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Removed style sheet is not found.\",\n false, iss.HasStyleSheet(sheet1));\n}\n\nvoid IndexedStyleSheetsTest::RemovingStyleSheetWhichIsNotAvailableHasNoEffect()\n{\n rtl::Reference sheet1(new MockedStyleSheet(rtl::OUString(\"sheet1\")));\n rtl::Reference sheet2(new MockedStyleSheet(rtl::OUString(\"sheet2\")));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n iss.RemoveStyleSheet(sheet2);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n}\n\nvoid IndexedStyleSheetsTest::StyleSheetsCanBeRetrievedByTheirName()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name2));\n rtl::Reference sheet3(new MockedStyleSheet(name1));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n\n std::vector r = iss.FindPositionsByName(name1);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Two style sheets are found by 'name1'\",\n 2u, static_cast(r.size()));\n CPPUNIT_ASSERT_EQUAL(0u, r.at(0));\n CPPUNIT_ASSERT_EQUAL(2u, r.at(1));\n\n r = iss.FindPositionsByName(name2);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"One style sheets is found by 'name2'\",\n 1u, static_cast(r.size()));\n CPPUNIT_ASSERT_EQUAL(1u, r.at(0));\n}\n\nvoid IndexedStyleSheetsTest::KnowsThatItStoresAStyleSheet()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name1));\n rtl::Reference sheet3(new MockedStyleSheet(name2));\n rtl::Reference sheet4(new MockedStyleSheet(name1));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n \/\/ do not add sheet 4\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Finds first stored style sheet even though two style sheets have the same name.\",\n true, iss.HasStyleSheet(sheet1));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Finds second stored style sheet even though two style sheets have the same name.\",\n true, iss.HasStyleSheet(sheet2));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Does not find style sheet which is not stored and has the same name as a stored.\",\n false, iss.HasStyleSheet(sheet4));\n}\n\nvoid IndexedStyleSheetsTest::PositionCanBeQueriedByFamily()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::OUString name3(\"name3\");\n rtl::Reference sheet1(new MockedStyleSheet(name1, SFX_STYLE_FAMILY_CHAR));\n rtl::Reference sheet2(new MockedStyleSheet(name2, SFX_STYLE_FAMILY_PARA));\n rtl::Reference sheet3(new MockedStyleSheet(name3, SFX_STYLE_FAMILY_CHAR));\n\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n\n const std::vector& v = iss.GetStyleSheetPositionsByFamily(SFX_STYLE_FAMILY_CHAR);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Separation by family works.\", static_cast(2), v.size());\n\n const std::vector& w = iss.GetStyleSheetPositionsByFamily(SFX_STYLE_FAMILY_ALL);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Wildcard works for family queries.\", static_cast(3), w.size());\n}\n\nvoid IndexedStyleSheetsTest::OnlyOneStyleSheetIsReturnedWhenReturnFirstIsUsed()\n{\n rtl::OUString name(\"name1\");\n rtl::Reference sheet1(new MockedStyleSheet(name, SFX_STYLE_FAMILY_CHAR));\n rtl::Reference sheet2(new MockedStyleSheet(name, SFX_STYLE_FAMILY_PARA));\n rtl::Reference sheet3(new MockedStyleSheet(name, SFX_STYLE_FAMILY_CHAR));\n\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n\n DummyPredicate predicate; \/\/ returns always true, i.e., all style sheets match the predicate.\n\n std::vector v = iss.FindPositionsByNameAndPredicate(name, predicate,\n IndexedStyleSheets::RETURN_FIRST);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Only one style sheet is returned.\", static_cast(1), v.size());\n\n std::vector w = iss.FindPositionsByNameAndPredicate(name, predicate,\n IndexedStyleSheets::RETURN_ALL);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"All style sheets are returned.\", static_cast(1), v.size());\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(IndexedStyleSheetsTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\nsvl: fix comparison in new unit test\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace svl;\n\nclass MockedStyleSheet : public SfxStyleSheetBase\n{\n public:\n MockedStyleSheet(const rtl::OUString& name, SfxStyleFamily fam = SFX_STYLE_FAMILY_CHAR)\n : SfxStyleSheetBase(name, NULL, fam, 0)\n {;}\n\n};\n\nstruct DummyPredicate : public StyleSheetPredicate {\n bool Check(const SfxStyleSheetBase& styleSheet) SAL_OVERRIDE {\n (void)styleSheet; \/\/ fix compiler warning\n return true;\n }\n};\n\nclass IndexedStyleSheetsTest : public CppUnit::TestFixture\n{\n void InstantiationWorks();\n void AddedStylesheetsCanBeFoundAndRetrievedByPosition();\n void AddingSameStylesheetTwiceHasNoEffect();\n void RemovedStyleSheetIsNotFound();\n void RemovingStyleSheetWhichIsNotAvailableHasNoEffect();\n void StyleSheetsCanBeRetrievedByTheirName();\n void KnowsThatItStoresAStyleSheet();\n void PositionCanBeQueriedByFamily();\n void OnlyOneStyleSheetIsReturnedWhenReturnFirstIsUsed();\n\n \/\/ Adds code needed to register the test suite\n CPPUNIT_TEST_SUITE(IndexedStyleSheetsTest);\n\n CPPUNIT_TEST(InstantiationWorks);\n CPPUNIT_TEST(AddedStylesheetsCanBeFoundAndRetrievedByPosition);\n CPPUNIT_TEST(AddingSameStylesheetTwiceHasNoEffect);\n CPPUNIT_TEST(RemovedStyleSheetIsNotFound);\n CPPUNIT_TEST(RemovingStyleSheetWhichIsNotAvailableHasNoEffect);\n CPPUNIT_TEST(StyleSheetsCanBeRetrievedByTheirName);\n CPPUNIT_TEST(KnowsThatItStoresAStyleSheet);\n CPPUNIT_TEST(PositionCanBeQueriedByFamily);\n CPPUNIT_TEST(OnlyOneStyleSheetIsReturnedWhenReturnFirstIsUsed);\n\n \/\/ End of test suite definition\n CPPUNIT_TEST_SUITE_END();\n\n};\n\nvoid IndexedStyleSheetsTest::InstantiationWorks()\n{\n IndexedStyleSheets iss;\n}\n\nvoid IndexedStyleSheetsTest::AddedStylesheetsCanBeFoundAndRetrievedByPosition()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name2));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n unsigned pos = iss.FindStyleSheetPosition(*sheet2);\n rtl::Reference retrieved = iss.GetStyleSheetByPosition(pos);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"retrieved sheet is that which has been inserted.\", sheet2.get(), retrieved.get());\n}\n\nvoid IndexedStyleSheetsTest::AddingSameStylesheetTwiceHasNoEffect()\n{\n rtl::Reference sheet1(new MockedStyleSheet(rtl::OUString(\"sheet1\")));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n iss.AddStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n}\n\nvoid IndexedStyleSheetsTest::RemovedStyleSheetIsNotFound()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name2));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.RemoveStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Removed style sheet is not found.\",\n false, iss.HasStyleSheet(sheet1));\n}\n\nvoid IndexedStyleSheetsTest::RemovingStyleSheetWhichIsNotAvailableHasNoEffect()\n{\n rtl::Reference sheet1(new MockedStyleSheet(rtl::OUString(\"sheet1\")));\n rtl::Reference sheet2(new MockedStyleSheet(rtl::OUString(\"sheet2\")));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n iss.RemoveStyleSheet(sheet2);\n CPPUNIT_ASSERT_EQUAL(1u, iss.GetNumberOfStyleSheets());\n}\n\nvoid IndexedStyleSheetsTest::StyleSheetsCanBeRetrievedByTheirName()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name2));\n rtl::Reference sheet3(new MockedStyleSheet(name1));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n\n std::vector r = iss.FindPositionsByName(name1);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Two style sheets are found by 'name1'\",\n 2u, static_cast(r.size()));\n CPPUNIT_ASSERT_EQUAL(0u, r.at(0));\n CPPUNIT_ASSERT_EQUAL(2u, r.at(1));\n\n r = iss.FindPositionsByName(name2);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"One style sheets is found by 'name2'\",\n 1u, static_cast(r.size()));\n CPPUNIT_ASSERT_EQUAL(1u, r.at(0));\n}\n\nvoid IndexedStyleSheetsTest::KnowsThatItStoresAStyleSheet()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::Reference sheet1(new MockedStyleSheet(name1));\n rtl::Reference sheet2(new MockedStyleSheet(name1));\n rtl::Reference sheet3(new MockedStyleSheet(name2));\n rtl::Reference sheet4(new MockedStyleSheet(name1));\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n \/\/ do not add sheet 4\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Finds first stored style sheet even though two style sheets have the same name.\",\n true, iss.HasStyleSheet(sheet1));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Finds second stored style sheet even though two style sheets have the same name.\",\n true, iss.HasStyleSheet(sheet2));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Does not find style sheet which is not stored and has the same name as a stored.\",\n false, iss.HasStyleSheet(sheet4));\n}\n\nvoid IndexedStyleSheetsTest::PositionCanBeQueriedByFamily()\n{\n rtl::OUString name1(\"name1\");\n rtl::OUString name2(\"name2\");\n rtl::OUString name3(\"name3\");\n rtl::Reference sheet1(new MockedStyleSheet(name1, SFX_STYLE_FAMILY_CHAR));\n rtl::Reference sheet2(new MockedStyleSheet(name2, SFX_STYLE_FAMILY_PARA));\n rtl::Reference sheet3(new MockedStyleSheet(name3, SFX_STYLE_FAMILY_CHAR));\n\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n\n const std::vector& v = iss.GetStyleSheetPositionsByFamily(SFX_STYLE_FAMILY_CHAR);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Separation by family works.\", static_cast(2), v.size());\n\n const std::vector& w = iss.GetStyleSheetPositionsByFamily(SFX_STYLE_FAMILY_ALL);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Wildcard works for family queries.\", static_cast(3), w.size());\n}\n\nvoid IndexedStyleSheetsTest::OnlyOneStyleSheetIsReturnedWhenReturnFirstIsUsed()\n{\n rtl::OUString name(\"name1\");\n rtl::Reference sheet1(new MockedStyleSheet(name, SFX_STYLE_FAMILY_CHAR));\n rtl::Reference sheet2(new MockedStyleSheet(name, SFX_STYLE_FAMILY_PARA));\n rtl::Reference sheet3(new MockedStyleSheet(name, SFX_STYLE_FAMILY_CHAR));\n\n IndexedStyleSheets iss;\n iss.AddStyleSheet(sheet1);\n iss.AddStyleSheet(sheet2);\n iss.AddStyleSheet(sheet3);\n\n DummyPredicate predicate; \/\/ returns always true, i.e., all style sheets match the predicate.\n\n std::vector v = iss.FindPositionsByNameAndPredicate(name, predicate,\n IndexedStyleSheets::RETURN_FIRST);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Only one style sheet is returned.\", static_cast(1), v.size());\n\n std::vector w = iss.FindPositionsByNameAndPredicate(name, predicate,\n IndexedStyleSheets::RETURN_ALL);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"All style sheets are returned.\", static_cast(3), w.size());\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(IndexedStyleSheetsTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: emptyproperties.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 16:30:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SDR_PROPERTIES_EMPTYPROPERTIES_HXX\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n\n#ifndef _SVDDEF_HXX\n#include \n#endif\n\n#ifndef _SVDOBJ_HXX\n#include \n#endif\n\n#ifndef _SVDPOOL_HXX\n#include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n \/\/ create a new itemset\n SfxItemSet& EmptyProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)\n {\n \/\/ Basic implementation; Basic object has NO attributes\n DBG_ASSERT(sal_False, \"EmptyProperties::CreateObjectSpecificItemSet() should never be called\");\n return *(new SfxItemSet(rPool));\n }\n\n EmptyProperties::EmptyProperties(SdrObject& rObj)\n : BaseProperties(rObj),\n mpEmptyItemSet(0L)\n {\n }\n\n EmptyProperties::EmptyProperties(const EmptyProperties& rProps, SdrObject& rObj)\n : BaseProperties(rProps, rObj),\n mpEmptyItemSet(0L)\n {\n \/\/ #115593#\n \/\/ do not gererate an assert, else derivations like PageProperties will generate an assert\n \/\/ using the Clone() operator path.\n }\n\n EmptyProperties::~EmptyProperties()\n {\n if(mpEmptyItemSet)\n {\n delete mpEmptyItemSet;\n mpEmptyItemSet = 0L;\n }\n }\n\n BaseProperties& EmptyProperties::Clone(SdrObject& rObj) const\n {\n return *(new EmptyProperties(*this, rObj));\n }\n\n const SfxItemSet& EmptyProperties::GetObjectItemSet() const\n {\n if(!mpEmptyItemSet)\n {\n ((EmptyProperties*)this)->mpEmptyItemSet = &(((EmptyProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool()));\n }\n\n DBG_ASSERT(mpEmptyItemSet, \"Could not create an SfxItemSet(!)\");\n DBG_ASSERT(sal_False, \"EmptyProperties::GetObjectItemSet() should never be called (!)\");\n\n return *mpEmptyItemSet;\n }\n\n void EmptyProperties::SetObjectItem(const SfxPoolItem& \/*rItem*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetObjectItem() should never be called (!)\");\n }\n\n void EmptyProperties::SetObjectItemDirect(const SfxPoolItem& \/*rItem*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetObjectItemDirect() should never be called (!)\");\n }\n\n void EmptyProperties::ClearObjectItem(const sal_uInt16 \/*nWhich*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ClearObjectItem() should never be called (!)\");\n }\n\n void EmptyProperties::ClearObjectItemDirect(const sal_uInt16 \/*nWhich*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ClearObjectItemDirect() should never be called (!)\");\n }\n\n void EmptyProperties::SetObjectItemSet(const SfxItemSet& \/*rSet*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetObjectItemSet() should never be called (!)\");\n }\n\n void EmptyProperties::ItemSetChanged(const SfxItemSet& \/*rSet*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ItemSetChanged() should never be called (!)\");\n }\n\n sal_Bool EmptyProperties::AllowItemChange(const sal_uInt16 \/*nWhich*\/, const SfxPoolItem* \/*pNewItem*\/) const\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::AllowItemChange() should never be called (!)\");\n return sal_True;\n }\n\n void EmptyProperties::ItemChange(const sal_uInt16 \/*nWhich*\/, const SfxPoolItem* \/*pNewItem*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ItemChange() should never be called (!)\");\n }\n\n void EmptyProperties::PostItemChange(const sal_uInt16 \/*nWhich*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::PostItemChange() should never be called (!)\");\n }\n\n void EmptyProperties::SetStyleSheet(SfxStyleSheet* \/*pNewStyleSheet*\/, sal_Bool \/*bDontRemoveHardAttr*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetStyleSheet() should never be called (!)\");\n }\n\n SfxStyleSheet* EmptyProperties::GetStyleSheet() const\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::GetStyleSheet() should never be called (!)\");\n return 0L;\n }\n\n\/\/BFS01 void EmptyProperties::PreProcessSave()\n\/\/BFS01 {\n\/\/BFS01 }\n\n\/\/BFS01 void EmptyProperties::PostProcessSave()\n\/\/BFS01 {\n\/\/BFS01 }\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\nINTEGRATION: CWS pchfix02 (1.6.114); FILE MERGED 2006\/09\/01 17:47:16 kaib 1.6.114.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: emptyproperties.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 05:42:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#ifndef _SDR_PROPERTIES_EMPTYPROPERTIES_HXX\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n\n#ifndef _SVDDEF_HXX\n#include \n#endif\n\n#ifndef _SVDOBJ_HXX\n#include \n#endif\n\n#ifndef _SVDPOOL_HXX\n#include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n \/\/ create a new itemset\n SfxItemSet& EmptyProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)\n {\n \/\/ Basic implementation; Basic object has NO attributes\n DBG_ASSERT(sal_False, \"EmptyProperties::CreateObjectSpecificItemSet() should never be called\");\n return *(new SfxItemSet(rPool));\n }\n\n EmptyProperties::EmptyProperties(SdrObject& rObj)\n : BaseProperties(rObj),\n mpEmptyItemSet(0L)\n {\n }\n\n EmptyProperties::EmptyProperties(const EmptyProperties& rProps, SdrObject& rObj)\n : BaseProperties(rProps, rObj),\n mpEmptyItemSet(0L)\n {\n \/\/ #115593#\n \/\/ do not gererate an assert, else derivations like PageProperties will generate an assert\n \/\/ using the Clone() operator path.\n }\n\n EmptyProperties::~EmptyProperties()\n {\n if(mpEmptyItemSet)\n {\n delete mpEmptyItemSet;\n mpEmptyItemSet = 0L;\n }\n }\n\n BaseProperties& EmptyProperties::Clone(SdrObject& rObj) const\n {\n return *(new EmptyProperties(*this, rObj));\n }\n\n const SfxItemSet& EmptyProperties::GetObjectItemSet() const\n {\n if(!mpEmptyItemSet)\n {\n ((EmptyProperties*)this)->mpEmptyItemSet = &(((EmptyProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool()));\n }\n\n DBG_ASSERT(mpEmptyItemSet, \"Could not create an SfxItemSet(!)\");\n DBG_ASSERT(sal_False, \"EmptyProperties::GetObjectItemSet() should never be called (!)\");\n\n return *mpEmptyItemSet;\n }\n\n void EmptyProperties::SetObjectItem(const SfxPoolItem& \/*rItem*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetObjectItem() should never be called (!)\");\n }\n\n void EmptyProperties::SetObjectItemDirect(const SfxPoolItem& \/*rItem*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetObjectItemDirect() should never be called (!)\");\n }\n\n void EmptyProperties::ClearObjectItem(const sal_uInt16 \/*nWhich*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ClearObjectItem() should never be called (!)\");\n }\n\n void EmptyProperties::ClearObjectItemDirect(const sal_uInt16 \/*nWhich*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ClearObjectItemDirect() should never be called (!)\");\n }\n\n void EmptyProperties::SetObjectItemSet(const SfxItemSet& \/*rSet*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetObjectItemSet() should never be called (!)\");\n }\n\n void EmptyProperties::ItemSetChanged(const SfxItemSet& \/*rSet*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ItemSetChanged() should never be called (!)\");\n }\n\n sal_Bool EmptyProperties::AllowItemChange(const sal_uInt16 \/*nWhich*\/, const SfxPoolItem* \/*pNewItem*\/) const\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::AllowItemChange() should never be called (!)\");\n return sal_True;\n }\n\n void EmptyProperties::ItemChange(const sal_uInt16 \/*nWhich*\/, const SfxPoolItem* \/*pNewItem*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::ItemChange() should never be called (!)\");\n }\n\n void EmptyProperties::PostItemChange(const sal_uInt16 \/*nWhich*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::PostItemChange() should never be called (!)\");\n }\n\n void EmptyProperties::SetStyleSheet(SfxStyleSheet* \/*pNewStyleSheet*\/, sal_Bool \/*bDontRemoveHardAttr*\/)\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::SetStyleSheet() should never be called (!)\");\n }\n\n SfxStyleSheet* EmptyProperties::GetStyleSheet() const\n {\n DBG_ASSERT(sal_False, \"EmptyProperties::GetStyleSheet() should never be called (!)\");\n return 0L;\n }\n\n\/\/BFS01 void EmptyProperties::PreProcessSave()\n\/\/BFS01 {\n\/\/BFS01 }\n\n\/\/BFS01 void EmptyProperties::PostProcessSave()\n\/\/BFS01 {\n\/\/BFS01 }\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2003 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/* @file\n * System Console Definition\n *\/\n\n#include \n#include \n#include \n\n#include \"base\/inifile.hh\"\n#include \"base\/str.hh\"\t\/\/ for to_number()\n#include \"base\/trace.hh\"\n#include \"cpu\/base_cpu.hh\"\n#include \"cpu\/exec_context.hh\"\n#include \"dev\/alpha_console.hh\"\n#include \"dev\/console.hh\"\n#include \"dev\/simple_disk.hh\"\n#include \"dev\/tlaser_clock.hh\"\n#include \"mem\/bus\/bus.hh\"\n#include \"mem\/bus\/pio_interface.hh\"\n#include \"mem\/bus\/pio_interface_impl.hh\"\n#include \"mem\/functional_mem\/memory_control.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nAlphaConsole::AlphaConsole(const string &name, SimConsole *cons, SimpleDisk *d,\n System *system, BaseCPU *cpu, TlaserClock *clock,\n int num_cpus, MemoryController *mmu, Addr a,\n HierParams *hier, Bus *bus)\n : PioDevice(name), disk(d), console(cons), addr(a)\n{\n mmu->add_child(this, Range(addr, addr + size));\n\n if (bus) {\n pioInterface = newPioInterface(name, hier, bus, this,\n &AlphaConsole::cacheAccess);\n pioInterface->setAddrRange(addr, addr + size);\n }\n\n consoleData = new uint8_t[size];\n memset(consoleData, 0, size);\n\n alphaAccess->last_offset = size - 1;\n alphaAccess->kernStart = system->getKernelStart();\n alphaAccess->kernEnd = system->getKernelEnd();\n alphaAccess->entryPoint = system->getKernelEntry();\n\n alphaAccess->version = ALPHA_ACCESS_VERSION;\n alphaAccess->numCPUs = num_cpus;\n alphaAccess->mem_size = system->physmem->size();\n alphaAccess->cpuClock = cpu->getFreq() \/ 1000000;\n alphaAccess->intrClockFrequency = clock->frequency();\n\n alphaAccess->diskUnit = 1;\n}\n\nFault\nAlphaConsole::read(MemReqPtr &req, uint8_t *data)\n{\n memset(data, 0, req->size);\n uint64_t val;\n\n Addr daddr = req->paddr - addr;\n\n switch (daddr) {\n case offsetof(AlphaAccess, inputChar):\n val = console->console_in();\n break;\n\n default:\n val = *(uint64_t *)(consoleData + daddr);\n break;\n }\n\n DPRINTF(AlphaConsole, \"read: offset=%#x val=%#x\\n\", daddr, val);\n\n switch (req->size) {\n case sizeof(uint32_t):\n *(uint32_t *)data = (uint32_t)val;\n break;\n\n case sizeof(uint64_t):\n *(uint64_t *)data = val;\n break;\n\n default:\n return Machine_Check_Fault;\n }\n\n\n return No_Fault;\n}\n\nFault\nAlphaConsole::write(MemReqPtr &req, const uint8_t *data)\n{\n uint64_t val;\n\n switch (req->size) {\n case sizeof(uint32_t):\n val = *(uint32_t *)data;\n break;\n\n case sizeof(uint64_t):\n val = *(uint64_t *)data;\n break;\n default:\n return Machine_Check_Fault;\n }\n\n Addr daddr = req->paddr - addr;\n ExecContext *other_xc;\n\n switch (daddr) {\n case offsetof(AlphaAccess, diskUnit):\n alphaAccess->diskUnit = val;\n break;\n\n case offsetof(AlphaAccess, diskCount):\n alphaAccess->diskCount = val;\n break;\n\n case offsetof(AlphaAccess, diskPAddr):\n alphaAccess->diskPAddr = val;\n break;\n\n case offsetof(AlphaAccess, diskBlock):\n alphaAccess->diskBlock = val;\n break;\n\n case offsetof(AlphaAccess, diskOperation):\n if (val == 0x13)\n disk->read(alphaAccess->diskPAddr, alphaAccess->diskBlock,\n alphaAccess->diskCount);\n else\n panic(\"Invalid disk operation!\");\n\n break;\n\n case offsetof(AlphaAccess, outputChar):\n console->out((char)(val & 0xff), false);\n break;\n\n case offsetof(AlphaAccess, bootStrapImpure):\n alphaAccess->bootStrapImpure = val;\n break;\n\n case offsetof(AlphaAccess, bootStrapCPU):\n warn(\"%d: Trying to launch another CPU!\", curTick);\n assert(val > 0 && \"Must not access primary cpu\");\n\n other_xc = req->xc->system->execContexts[val];\n other_xc->regs.intRegFile[16] = val;\n other_xc->regs.ipr[TheISA::IPR_PALtemp16] = val;\n other_xc->regs.intRegFile[0] = val;\n other_xc->regs.intRegFile[30] = alphaAccess->bootStrapImpure;\n other_xc->activate(); \/\/Start the cpu\n break;\n\n default:\n return Machine_Check_Fault;\n }\n\n return No_Fault;\n}\n\nTick\nAlphaConsole::cacheAccess(MemReqPtr &req)\n{\n return curTick + 1000;\n}\n\nvoid\nAlphaAccess::serialize(ostream &os)\n{\n SERIALIZE_SCALAR(last_offset);\n SERIALIZE_SCALAR(version);\n SERIALIZE_SCALAR(numCPUs);\n SERIALIZE_SCALAR(mem_size);\n SERIALIZE_SCALAR(cpuClock);\n SERIALIZE_SCALAR(intrClockFrequency);\n SERIALIZE_SCALAR(kernStart);\n SERIALIZE_SCALAR(kernEnd);\n SERIALIZE_SCALAR(entryPoint);\n SERIALIZE_SCALAR(diskUnit);\n SERIALIZE_SCALAR(diskCount);\n SERIALIZE_SCALAR(diskPAddr);\n SERIALIZE_SCALAR(diskBlock);\n SERIALIZE_SCALAR(diskOperation);\n SERIALIZE_SCALAR(outputChar);\n SERIALIZE_SCALAR(inputChar);\n SERIALIZE_SCALAR(bootStrapImpure);\n SERIALIZE_SCALAR(bootStrapCPU);\n}\n\nvoid\nAlphaAccess::unserialize(Checkpoint *cp, const std::string §ion)\n{\n UNSERIALIZE_SCALAR(last_offset);\n UNSERIALIZE_SCALAR(version);\n UNSERIALIZE_SCALAR(numCPUs);\n UNSERIALIZE_SCALAR(mem_size);\n UNSERIALIZE_SCALAR(cpuClock);\n UNSERIALIZE_SCALAR(intrClockFrequency);\n UNSERIALIZE_SCALAR(kernStart);\n UNSERIALIZE_SCALAR(kernEnd);\n UNSERIALIZE_SCALAR(entryPoint);\n UNSERIALIZE_SCALAR(diskUnit);\n UNSERIALIZE_SCALAR(diskCount);\n UNSERIALIZE_SCALAR(diskPAddr);\n UNSERIALIZE_SCALAR(diskBlock);\n UNSERIALIZE_SCALAR(diskOperation);\n UNSERIALIZE_SCALAR(outputChar);\n UNSERIALIZE_SCALAR(inputChar);\n UNSERIALIZE_SCALAR(bootStrapImpure);\n UNSERIALIZE_SCALAR(bootStrapCPU);\n}\n\nvoid\nAlphaConsole::serialize(ostream &os)\n{\n alphaAccess->serialize(os);\n}\n\nvoid\nAlphaConsole::unserialize(Checkpoint *cp, const std::string §ion)\n{\n alphaAccess->unserialize(cp, section);\n}\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(AlphaConsole)\n\n SimObjectParam sim_console;\n SimObjectParam disk;\n Param num_cpus;\n SimObjectParam mmu;\n Param addr;\n SimObjectParam system;\n SimObjectParam cpu;\n SimObjectParam clock;\n SimObjectParam io_bus;\n SimObjectParam hier;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(AlphaConsole)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(AlphaConsole)\n\n INIT_PARAM(sim_console, \"The Simulator Console\"),\n INIT_PARAM(disk, \"Simple Disk\"),\n INIT_PARAM_DFLT(num_cpus, \"Number of CPU's\", 1),\n INIT_PARAM(mmu, \"Memory Controller\"),\n INIT_PARAM(addr, \"Device Address\"),\n INIT_PARAM(system, \"system object\"),\n INIT_PARAM(cpu, \"Processor\"),\n INIT_PARAM(clock, \"Turbolaser Clock\"),\n INIT_PARAM_DFLT(io_bus, \"The IO Bus to attach to\", NULL),\n INIT_PARAM_DFLT(hier, \"Hierarchy global variables\", &defaultHierParams)\n\nEND_INIT_SIM_OBJECT_PARAMS(AlphaConsole)\n\nCREATE_SIM_OBJECT(AlphaConsole)\n{\n return new AlphaConsole(getInstanceName(), sim_console, disk,\n system, cpu, clock, num_cpus, mmu,\n addr, hier, io_bus);\n}\n\nREGISTER_SIM_OBJECT(\"AlphaConsole\", AlphaConsole)\nAdd support for multiple address ranges in memory interfaces.\/*\n * Copyright (c) 2003 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/* @file\n * System Console Definition\n *\/\n\n#include \n#include \n#include \n\n#include \"base\/inifile.hh\"\n#include \"base\/str.hh\"\t\/\/ for to_number()\n#include \"base\/trace.hh\"\n#include \"cpu\/base_cpu.hh\"\n#include \"cpu\/exec_context.hh\"\n#include \"dev\/alpha_console.hh\"\n#include \"dev\/console.hh\"\n#include \"dev\/simple_disk.hh\"\n#include \"dev\/tlaser_clock.hh\"\n#include \"mem\/bus\/bus.hh\"\n#include \"mem\/bus\/pio_interface.hh\"\n#include \"mem\/bus\/pio_interface_impl.hh\"\n#include \"mem\/functional_mem\/memory_control.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nAlphaConsole::AlphaConsole(const string &name, SimConsole *cons, SimpleDisk *d,\n System *system, BaseCPU *cpu, TlaserClock *clock,\n int num_cpus, MemoryController *mmu, Addr a,\n HierParams *hier, Bus *bus)\n : PioDevice(name), disk(d), console(cons), addr(a)\n{\n mmu->add_child(this, Range(addr, addr + size));\n\n if (bus) {\n pioInterface = newPioInterface(name, hier, bus, this,\n &AlphaConsole::cacheAccess);\n pioInterface->addAddrRange(addr, addr + size);\n }\n\n consoleData = new uint8_t[size];\n memset(consoleData, 0, size);\n\n alphaAccess->last_offset = size - 1;\n alphaAccess->kernStart = system->getKernelStart();\n alphaAccess->kernEnd = system->getKernelEnd();\n alphaAccess->entryPoint = system->getKernelEntry();\n\n alphaAccess->version = ALPHA_ACCESS_VERSION;\n alphaAccess->numCPUs = num_cpus;\n alphaAccess->mem_size = system->physmem->size();\n alphaAccess->cpuClock = cpu->getFreq() \/ 1000000;\n alphaAccess->intrClockFrequency = clock->frequency();\n\n alphaAccess->diskUnit = 1;\n}\n\nFault\nAlphaConsole::read(MemReqPtr &req, uint8_t *data)\n{\n memset(data, 0, req->size);\n uint64_t val;\n\n Addr daddr = req->paddr - addr;\n\n switch (daddr) {\n case offsetof(AlphaAccess, inputChar):\n val = console->console_in();\n break;\n\n default:\n val = *(uint64_t *)(consoleData + daddr);\n break;\n }\n\n DPRINTF(AlphaConsole, \"read: offset=%#x val=%#x\\n\", daddr, val);\n\n switch (req->size) {\n case sizeof(uint32_t):\n *(uint32_t *)data = (uint32_t)val;\n break;\n\n case sizeof(uint64_t):\n *(uint64_t *)data = val;\n break;\n\n default:\n return Machine_Check_Fault;\n }\n\n\n return No_Fault;\n}\n\nFault\nAlphaConsole::write(MemReqPtr &req, const uint8_t *data)\n{\n uint64_t val;\n\n switch (req->size) {\n case sizeof(uint32_t):\n val = *(uint32_t *)data;\n break;\n\n case sizeof(uint64_t):\n val = *(uint64_t *)data;\n break;\n default:\n return Machine_Check_Fault;\n }\n\n Addr daddr = req->paddr - addr;\n ExecContext *other_xc;\n\n switch (daddr) {\n case offsetof(AlphaAccess, diskUnit):\n alphaAccess->diskUnit = val;\n break;\n\n case offsetof(AlphaAccess, diskCount):\n alphaAccess->diskCount = val;\n break;\n\n case offsetof(AlphaAccess, diskPAddr):\n alphaAccess->diskPAddr = val;\n break;\n\n case offsetof(AlphaAccess, diskBlock):\n alphaAccess->diskBlock = val;\n break;\n\n case offsetof(AlphaAccess, diskOperation):\n if (val == 0x13)\n disk->read(alphaAccess->diskPAddr, alphaAccess->diskBlock,\n alphaAccess->diskCount);\n else\n panic(\"Invalid disk operation!\");\n\n break;\n\n case offsetof(AlphaAccess, outputChar):\n console->out((char)(val & 0xff), false);\n break;\n\n case offsetof(AlphaAccess, bootStrapImpure):\n alphaAccess->bootStrapImpure = val;\n break;\n\n case offsetof(AlphaAccess, bootStrapCPU):\n warn(\"%d: Trying to launch another CPU!\", curTick);\n assert(val > 0 && \"Must not access primary cpu\");\n\n other_xc = req->xc->system->execContexts[val];\n other_xc->regs.intRegFile[16] = val;\n other_xc->regs.ipr[TheISA::IPR_PALtemp16] = val;\n other_xc->regs.intRegFile[0] = val;\n other_xc->regs.intRegFile[30] = alphaAccess->bootStrapImpure;\n other_xc->activate(); \/\/Start the cpu\n break;\n\n default:\n return Machine_Check_Fault;\n }\n\n return No_Fault;\n}\n\nTick\nAlphaConsole::cacheAccess(MemReqPtr &req)\n{\n return curTick + 1000;\n}\n\nvoid\nAlphaAccess::serialize(ostream &os)\n{\n SERIALIZE_SCALAR(last_offset);\n SERIALIZE_SCALAR(version);\n SERIALIZE_SCALAR(numCPUs);\n SERIALIZE_SCALAR(mem_size);\n SERIALIZE_SCALAR(cpuClock);\n SERIALIZE_SCALAR(intrClockFrequency);\n SERIALIZE_SCALAR(kernStart);\n SERIALIZE_SCALAR(kernEnd);\n SERIALIZE_SCALAR(entryPoint);\n SERIALIZE_SCALAR(diskUnit);\n SERIALIZE_SCALAR(diskCount);\n SERIALIZE_SCALAR(diskPAddr);\n SERIALIZE_SCALAR(diskBlock);\n SERIALIZE_SCALAR(diskOperation);\n SERIALIZE_SCALAR(outputChar);\n SERIALIZE_SCALAR(inputChar);\n SERIALIZE_SCALAR(bootStrapImpure);\n SERIALIZE_SCALAR(bootStrapCPU);\n}\n\nvoid\nAlphaAccess::unserialize(Checkpoint *cp, const std::string §ion)\n{\n UNSERIALIZE_SCALAR(last_offset);\n UNSERIALIZE_SCALAR(version);\n UNSERIALIZE_SCALAR(numCPUs);\n UNSERIALIZE_SCALAR(mem_size);\n UNSERIALIZE_SCALAR(cpuClock);\n UNSERIALIZE_SCALAR(intrClockFrequency);\n UNSERIALIZE_SCALAR(kernStart);\n UNSERIALIZE_SCALAR(kernEnd);\n UNSERIALIZE_SCALAR(entryPoint);\n UNSERIALIZE_SCALAR(diskUnit);\n UNSERIALIZE_SCALAR(diskCount);\n UNSERIALIZE_SCALAR(diskPAddr);\n UNSERIALIZE_SCALAR(diskBlock);\n UNSERIALIZE_SCALAR(diskOperation);\n UNSERIALIZE_SCALAR(outputChar);\n UNSERIALIZE_SCALAR(inputChar);\n UNSERIALIZE_SCALAR(bootStrapImpure);\n UNSERIALIZE_SCALAR(bootStrapCPU);\n}\n\nvoid\nAlphaConsole::serialize(ostream &os)\n{\n alphaAccess->serialize(os);\n}\n\nvoid\nAlphaConsole::unserialize(Checkpoint *cp, const std::string §ion)\n{\n alphaAccess->unserialize(cp, section);\n}\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(AlphaConsole)\n\n SimObjectParam sim_console;\n SimObjectParam disk;\n Param num_cpus;\n SimObjectParam mmu;\n Param addr;\n SimObjectParam system;\n SimObjectParam cpu;\n SimObjectParam clock;\n SimObjectParam io_bus;\n SimObjectParam hier;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(AlphaConsole)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(AlphaConsole)\n\n INIT_PARAM(sim_console, \"The Simulator Console\"),\n INIT_PARAM(disk, \"Simple Disk\"),\n INIT_PARAM_DFLT(num_cpus, \"Number of CPU's\", 1),\n INIT_PARAM(mmu, \"Memory Controller\"),\n INIT_PARAM(addr, \"Device Address\"),\n INIT_PARAM(system, \"system object\"),\n INIT_PARAM(cpu, \"Processor\"),\n INIT_PARAM(clock, \"Turbolaser Clock\"),\n INIT_PARAM_DFLT(io_bus, \"The IO Bus to attach to\", NULL),\n INIT_PARAM_DFLT(hier, \"Hierarchy global variables\", &defaultHierParams)\n\nEND_INIT_SIM_OBJECT_PARAMS(AlphaConsole)\n\nCREATE_SIM_OBJECT(AlphaConsole)\n{\n return new AlphaConsole(getInstanceName(), sim_console, disk,\n system, cpu, clock, num_cpus, mmu,\n addr, hier, io_bus);\n}\n\nREGISTER_SIM_OBJECT(\"AlphaConsole\", AlphaConsole)\n<|endoftext|>"} {"text":"\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/tpu\/tpu_initializer_helper.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/synchronization\/mutex.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/tpu\/libtftpu.h\"\n#include \"tensorflow\/core\/tpu\/tpu_api_dlsym_set_fn.h\"\n#include \"tensorflow\/core\/tpu\/tpu_ops_c_api.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_executor_c_api.h\"\n\n#if !defined(PLATFORM_GOOGLE)\n#include \"tensorflow\/core\/platform\/cloud\/gcs_file_system.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/tpu\/tpu_api.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_platform.h\"\n#elif defined(LIBTPU_STATIC)\n#include \"tensorflow\/core\/tpu\/tpu_api.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_platform.h\"\n#endif \/\/ PLATFORM_GOOGLE\n\nnamespace tensorflow {\nnamespace tpu {\nnamespace {\n\nstatic std::string GetEnvVar(const char* name) {\n \/\/ Constructing a std::string directly from nullptr is undefined behavior.\n return absl::StrCat(getenv(name));\n}\n\nbool GetEnvBool(const char* name, bool defval) {\n const char* env = getenv(name);\n if (env == nullptr) {\n return defval;\n }\n if (std::strcmp(env, \"true\") == 0) {\n return true;\n }\n if (std::strcmp(env, \"false\") == 0) {\n return false;\n }\n int int_env;\n bool has_int = absl::SimpleAtoi(env, &int_env);\n return has_int && int_env != 0;\n}\n\n} \/\/ namespace\n\n\/\/ This function gets pid of a process and checks if that process is using tpu.\n\/\/ It is not able to check processes that are owned by another user.\nbool IsTpuUsed(int64_t pid) {\n std::string path = absl::StrCat(\"\/proc\/\", pid, \"\/fd\");\n DIR* raw_fd_dir = opendir(path.c_str());\n if (!raw_fd_dir) {\n return false;\n }\n std::unique_ptr fd_dir(raw_fd_dir, closedir);\n struct dirent* ent;\n std::string line;\n std::string tpu_dev_path = \"\/dev\/accel0\";\n line.resize(tpu_dev_path.size());\n while ((ent = readdir(raw_fd_dir))) {\n if (!isdigit(*ent->d_name)) continue;\n int64_t fd = strtol(ent->d_name, nullptr, 10);\n path = absl::StrCat(\"\/proc\/\", pid, \"\/fd\/\", fd);\n if (!readlink(path.c_str(), &line[0], line.size())) continue;\n if (line != tpu_dev_path) continue;\n return true;\n }\n return false;\n}\n\n\/\/ This function iterates through all the processes in \/proc and finds out if\n\/\/ any process it was able to check is using the TPU. It does not have\n\/\/ permission to processes owned by another user.\n\/\/ TODO (shahrokhi) use tensorflow\/core\/platform\/filesystem (GetChildren) for\n\/\/ this.\nStatusOr FindLibtpuProcess() {\n DIR* proc = opendir(\"\/proc\");\n\n if (proc == nullptr) {\n return errors::Unavailable(\"was not able to open \/proc\");\n }\n std::unique_ptr proc_dir(proc, closedir);\n struct dirent* ent;\n int64_t pid;\n while ((ent = readdir(proc))) {\n if (!isdigit(*ent->d_name)) continue;\n\n pid = strtol(ent->d_name, nullptr, 10);\n if (IsTpuUsed(pid)) {\n return pid;\n }\n }\n return errors::NotFound(\"did not find which pid uses the libtpu.so\");\n}\n\nStatus TryAcquireTpuLock() {\n static absl::Mutex* mu = new absl::Mutex();\n absl::MutexLock l(mu);\n\n std::string load_library_override = absl::StrCat(getenv(\"TPU_LOAD_LIBRARY\"));\n\n if (load_library_override == \"1\") {\n return Status::OK();\n } else if (load_library_override == \"0\") {\n return errors::FailedPrecondition(\"TPU_LOAD_LIBRARY=0, not loading libtpu\");\n }\n\n \/\/ If TPU_CHIPS_PER_PROCESS_BOUNDS doesn't include all chips, we assume\n \/\/ we're using different chips in different processes and thus multiple\n \/\/ libtpu loads are ok.\n \/\/ TODO(skyewm): we could make per-chip lock files and look at\n \/\/ TPU_VISIBLE_DEVICES if we wanted to make this really precise.\n std::string chips_per_process_bounds =\n GetEnvVar(\"TPU_CHIPS_PER_PROCESS_BOUNDS\");\n bool allow_multiple_libtpu_load =\n GetEnvBool(\"ALLOW_MULTIPLE_LIBTPU_LOAD\", false);\n \/\/ TODO(skyewm): remove this when TPU_CHIPS_PER_HOST_BOUNDS is fully\n \/\/ deprecated\n if (chips_per_process_bounds.empty()) {\n chips_per_process_bounds = GetEnvVar(\"TPU_CHIPS_PER_HOST_BOUNDS\");\n }\n if ((chips_per_process_bounds.empty() ||\n chips_per_process_bounds == \"2,2,1\") &&\n !allow_multiple_libtpu_load) {\n int fd = open(\"\/tmp\/libtpu_lockfile\", O_CREAT | O_RDWR, 0644);\n\n \/\/ This lock is held until the process exits intentionally. The underlying\n \/\/ TPU device will be held on until it quits.\n if (lockf(fd, F_TLOCK, 0) != 0) {\n auto pid = FindLibtpuProcess();\n if (pid.ok()) {\n return errors::Aborted(absl::StrCat(\n \"libtpu.so is already in use by process with pid \",\n pid.ValueOrDie(),\n \". Not attempting to load libtpu.so in this process.\"));\n } else {\n return errors::Aborted(\n \"libtpu.so already in use by another process probably owned by \"\n \"another user. Run \\\"$ sudo lsof -w \/dev\/accel0\\\" to figure out \"\n \"which process is using the TPU. Not attempting to load \"\n \"libtpu.so in this process.\");\n }\n } else {\n return Status::OK();\n }\n } else {\n VLOG(1) << \"TPU_CHIPS_PER_PROCESS_BOUNDS is not empty or \"\n \"ALLOW_MULTIPLE_LIBTPU_LOAD is set to True, \"\n \"therefore allowing multiple libtpu.so loads.\";\n return Status::OK();\n }\n}\n#if !defined(PLATFORM_GOOGLE)\n#include \"tensorflow\/core\/tpu\/tpu_library_init_fns.inc\"\n\nStatus InitializeTpuLibrary(void* library_handle) {\n Status s = InitializeTpuStructFns(library_handle);\n\n \/\/ Retrieve arguments from environment if applicable\n std::pair, std::vector> args =\n GetLibTpuInitArguments();\n\n \/\/ TPU platform registration must only be performed after the library is\n \/\/ loaded. We do not want to register a TPU platform in XLA without the\n \/\/ supporting library providing the necessary APIs.\n if (s.ok()) {\n void (*initialize_fn)(bool init_library, int num_args, const char** args);\n initialize_fn = reinterpret_cast(\n dlsym(library_handle, \"TfTpu_Initialize\"));\n (*initialize_fn)(\/*init_library=*\/true, args.second.size(),\n args.second.data());\n\n RegisterTpuPlatform();\n }\n\n return s;\n}\n\nnamespace {\nvoid* CreateGcsFilesystemFn() {\n return new tensorflow::RetryingGcsFileSystem();\n}\n\n\/\/ This is a temporary fix for including GCS file system on TPU builds.\n\/\/ Will be removed once b\/176954917 is fully resolved with the build fix.\nvoid InitializeCreateGcsFileSystemFnPtr() {\n int fd = shm_open(absl::StrCat(\"\/tmp_tf_gcs_fs_pointer_\", getpid()).data(),\n O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);\n if (fd == -1) {\n LOG(ERROR) << \"Unable to open shared memory for GCS file system creator.\";\n return;\n }\n\n if (ftruncate(fd, sizeof(tensorflow::FileSystem*)) == -1) {\n LOG(ERROR)\n << \"Unable to allocate shared memory for GCS file system creator.\";\n return;\n }\n\n void* (**fn)() = reinterpret_cast(mmap(\n NULL, sizeof(void* (*)()), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));\n if (fn == MAP_FAILED) {\n LOG(ERROR) << \"Cannot mmap shared memory for GCS file system creator.\";\n return;\n }\n\n *fn = &CreateGcsFilesystemFn;\n\n munmap(fn, sizeof(void* (*)()));\n close(fd);\n\n \/\/ Clean up shared memory on a clean exit.\n atexit([]() {\n shm_unlink(absl::StrCat(\"\/tmp_tf_gcs_fs_pointer_\", getpid()).data());\n });\n}\n} \/\/ namespace\nStatus FindAndLoadTpuLibrary() {\n const char* env_value = getenv(\"TPU_LIBRARY_PATH\");\n const char* libtpu_path =\n env_value && strlen(env_value) > 0 ? env_value : \"libtpu.so\";\n LOG(INFO) << \"Libtpu path is: \" << libtpu_path;\n void* library = dlopen(libtpu_path, RTLD_NOW);\n if (library) {\n \/\/ We can open the shared library which means we are in a TPU environment.\n \/\/ Try to acquire exclusive access.\n TF_RETURN_IF_ERROR(TryAcquireTpuLock());\n TF_RETURN_IF_ERROR(InitializeTpuLibrary(library));\n }\n\n InitializeCreateGcsFileSystemFnPtr();\n return Status::OK();\n}\n\n#elif defined(LIBTPU_STATIC)\n\n#include \"tensorflow\/core\/tpu\/tpu_library_init_fns.inc\"\n\nStatus InitializeTpuLibrary() {\n \/\/ Retrieve arguments from environment if applicable\n std::pair, std::vector> args =\n GetLibTpuInitArguments();\n\n TfTpu_Initialize(\/*init_library*\/ true, args.second.size(),\n args.second.data());\n\n RegisterTpuPlatform();\n return Status::OK();\n}\n\nStatus FindAndLoadTpuLibrary() {\n \/\/ We can open the shared library which means we are in a TPU environment.\n \/\/ Try to acquire exclusive access.\n TF_RETURN_IF_ERROR(TryAcquireTpuLock());\n TF_RETURN_IF_ERROR(InitializeTpuLibrary());\n return Status::OK();\n}\n\n#else \/\/ PLATFORM_GOOGLE\nStatus InitializeTpuLibrary(void* library_handle) {\n return errors::Unimplemented(\"You must statically link in a TPU library.\");\n}\n#endif \/\/ PLATFORM_GOOGLE\nstd::pair, std::vector>\nGetLibTpuInitArguments() {\n \/\/ We make copies of the arguments returned by getenv because the memory\n \/\/ returned may be altered or invalidated by further calls to getenv.\n std::vector args;\n std::vector arg_ptrs;\n\n \/\/ Retrieve arguments from environment if applicable.\n char* env = getenv(\"LIBTPU_INIT_ARGS\");\n if (env != nullptr) {\n \/\/ TODO(frankchn): Handles quotes properly if necessary.\n args = absl::StrSplit(env, ' ');\n }\n\n arg_ptrs.reserve(args.size());\n for (int i = 0; i < args.size(); ++i) {\n arg_ptrs.push_back(args[i].data());\n }\n\n return {std::move(args), std::move(arg_ptrs)};\n}\n\n} \/\/ namespace tpu\n} \/\/ namespace tensorflow\nFix JAX \/ TPU builds\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/tpu\/tpu_initializer_helper.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/synchronization\/mutex.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/tpu\/libtftpu.h\"\n#include \"tensorflow\/core\/tpu\/tpu_api_dlsym_set_fn.h\"\n#include \"tensorflow\/core\/tpu\/tpu_ops_c_api.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_executor_c_api.h\"\n\n#if !defined(PLATFORM_GOOGLE)\n#include \"tensorflow\/core\/platform\/cloud\/gcs_file_system.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/tpu\/tpu_api.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_platform.h\"\n#elif defined(LIBTPU_STATIC)\n#include \"tensorflow\/core\/tpu\/tpu_api.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_platform.h\"\n#endif \/\/ PLATFORM_GOOGLE\n\nnamespace tensorflow {\nnamespace tpu {\nnamespace {\n\nstatic std::string GetEnvVar(const char* name) {\n \/\/ Constructing a std::string directly from nullptr is undefined behavior.\n return absl::StrCat(getenv(name));\n}\n\nbool GetEnvBool(const char* name, bool defval) {\n const char* env = getenv(name);\n if (env == nullptr) {\n return defval;\n }\n if (std::strcmp(env, \"true\") == 0) {\n return true;\n }\n if (std::strcmp(env, \"false\") == 0) {\n return false;\n }\n int int_env;\n bool has_int = absl::SimpleAtoi(env, &int_env);\n return has_int && int_env != 0;\n}\n\n} \/\/ namespace\n\n\/\/ This function gets pid of a process and checks if that process is using tpu.\n\/\/ It is not able to check processes that are owned by another user.\nbool IsTpuUsed(int64_t pid) {\n std::string path = absl::StrCat(\"\/proc\/\", pid, \"\/fd\");\n DIR* raw_fd_dir = opendir(path.c_str());\n if (!raw_fd_dir) {\n return false;\n }\n std::unique_ptr fd_dir(raw_fd_dir, closedir);\n struct dirent* ent;\n std::string line;\n std::string tpu_dev_path = \"\/dev\/accel0\";\n line.resize(tpu_dev_path.size());\n while ((ent = readdir(raw_fd_dir))) {\n if (!isdigit(*ent->d_name)) continue;\n int64_t fd = strtol(ent->d_name, nullptr, 10);\n path = absl::StrCat(\"\/proc\/\", pid, \"\/fd\/\", fd);\n if (!readlink(path.c_str(), &line[0], line.size())) continue;\n if (line != tpu_dev_path) continue;\n return true;\n }\n return false;\n}\n\n\/\/ This function iterates through all the processes in \/proc and finds out if\n\/\/ any process it was able to check is using the TPU. It does not have\n\/\/ permission to processes owned by another user.\n\/\/ TODO (shahrokhi) use tensorflow\/core\/platform\/filesystem (GetChildren) for\n\/\/ this.\nStatusOr FindLibtpuProcess() {\n DIR* proc = opendir(\"\/proc\");\n\n if (proc == nullptr) {\n return errors::Unavailable(\"was not able to open \/proc\");\n }\n std::unique_ptr proc_dir(proc, closedir);\n struct dirent* ent;\n int64_t pid;\n while ((ent = readdir(proc))) {\n if (!isdigit(*ent->d_name)) continue;\n\n pid = strtol(ent->d_name, nullptr, 10);\n if (IsTpuUsed(pid)) {\n return pid;\n }\n }\n return errors::NotFound(\"did not find which pid uses the libtpu.so\");\n}\n\nStatus TryAcquireTpuLock() {\n static absl::Mutex* mu = new absl::Mutex();\n absl::MutexLock l(mu);\n\n const char* env_value = getenv(\"TPU_LOAD_LIBRARY\");\n if (!env_value) {\n return errors::FailedPrecondition(\n \"TPU_LOAD_LIBRARY environment variable not defined\");\n }\n\n std::string load_library_override = absl::StrCat(env_value);\n\n if (load_library_override == \"1\") {\n return Status::OK();\n } else if (load_library_override == \"0\") {\n return errors::FailedPrecondition(\"TPU_LOAD_LIBRARY=0, not loading libtpu\");\n }\n\n \/\/ If TPU_CHIPS_PER_PROCESS_BOUNDS doesn't include all chips, we assume\n \/\/ we're using different chips in different processes and thus multiple\n \/\/ libtpu loads are ok.\n \/\/ TODO(skyewm): we could make per-chip lock files and look at\n \/\/ TPU_VISIBLE_DEVICES if we wanted to make this really precise.\n std::string chips_per_process_bounds =\n GetEnvVar(\"TPU_CHIPS_PER_PROCESS_BOUNDS\");\n bool allow_multiple_libtpu_load =\n GetEnvBool(\"ALLOW_MULTIPLE_LIBTPU_LOAD\", false);\n \/\/ TODO(skyewm): remove this when TPU_CHIPS_PER_HOST_BOUNDS is fully\n \/\/ deprecated\n if (chips_per_process_bounds.empty()) {\n chips_per_process_bounds = GetEnvVar(\"TPU_CHIPS_PER_HOST_BOUNDS\");\n }\n if ((chips_per_process_bounds.empty() ||\n chips_per_process_bounds == \"2,2,1\") &&\n !allow_multiple_libtpu_load) {\n int fd = open(\"\/tmp\/libtpu_lockfile\", O_CREAT | O_RDWR, 0644);\n\n \/\/ This lock is held until the process exits intentionally. The underlying\n \/\/ TPU device will be held on until it quits.\n if (lockf(fd, F_TLOCK, 0) != 0) {\n auto pid = FindLibtpuProcess();\n if (pid.ok()) {\n return errors::Aborted(absl::StrCat(\n \"libtpu.so is already in use by process with pid \",\n pid.ValueOrDie(),\n \". Not attempting to load libtpu.so in this process.\"));\n } else {\n return errors::Aborted(\n \"libtpu.so already in use by another process probably owned by \"\n \"another user. Run \\\"$ sudo lsof -w \/dev\/accel0\\\" to figure out \"\n \"which process is using the TPU. Not attempting to load \"\n \"libtpu.so in this process.\");\n }\n } else {\n return Status::OK();\n }\n } else {\n VLOG(1) << \"TPU_CHIPS_PER_PROCESS_BOUNDS is not empty or \"\n \"ALLOW_MULTIPLE_LIBTPU_LOAD is set to True, \"\n \"therefore allowing multiple libtpu.so loads.\";\n return Status::OK();\n }\n}\n#if !defined(PLATFORM_GOOGLE)\n#include \"tensorflow\/core\/tpu\/tpu_library_init_fns.inc\"\n\nStatus InitializeTpuLibrary(void* library_handle) {\n Status s = InitializeTpuStructFns(library_handle);\n\n \/\/ Retrieve arguments from environment if applicable\n std::pair, std::vector> args =\n GetLibTpuInitArguments();\n\n \/\/ TPU platform registration must only be performed after the library is\n \/\/ loaded. We do not want to register a TPU platform in XLA without the\n \/\/ supporting library providing the necessary APIs.\n if (s.ok()) {\n void (*initialize_fn)(bool init_library, int num_args, const char** args);\n initialize_fn = reinterpret_cast(\n dlsym(library_handle, \"TfTpu_Initialize\"));\n (*initialize_fn)(\/*init_library=*\/true, args.second.size(),\n args.second.data());\n\n RegisterTpuPlatform();\n }\n\n return s;\n}\n\nnamespace {\nvoid* CreateGcsFilesystemFn() {\n return new tensorflow::RetryingGcsFileSystem();\n}\n\n\/\/ This is a temporary fix for including GCS file system on TPU builds.\n\/\/ Will be removed once b\/176954917 is fully resolved with the build fix.\nvoid InitializeCreateGcsFileSystemFnPtr() {\n int fd = shm_open(absl::StrCat(\"\/tmp_tf_gcs_fs_pointer_\", getpid()).data(),\n O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);\n if (fd == -1) {\n LOG(ERROR) << \"Unable to open shared memory for GCS file system creator.\";\n return;\n }\n\n if (ftruncate(fd, sizeof(tensorflow::FileSystem*)) == -1) {\n LOG(ERROR)\n << \"Unable to allocate shared memory for GCS file system creator.\";\n return;\n }\n\n void* (**fn)() = reinterpret_cast(mmap(\n NULL, sizeof(void* (*)()), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));\n if (fn == MAP_FAILED) {\n LOG(ERROR) << \"Cannot mmap shared memory for GCS file system creator.\";\n return;\n }\n\n *fn = &CreateGcsFilesystemFn;\n\n munmap(fn, sizeof(void* (*)()));\n close(fd);\n\n \/\/ Clean up shared memory on a clean exit.\n atexit([]() {\n shm_unlink(absl::StrCat(\"\/tmp_tf_gcs_fs_pointer_\", getpid()).data());\n });\n}\n} \/\/ namespace\nStatus FindAndLoadTpuLibrary() {\n const char* env_value = getenv(\"TPU_LIBRARY_PATH\");\n const char* libtpu_path =\n env_value && strlen(env_value) > 0 ? env_value : \"libtpu.so\";\n LOG(INFO) << \"Libtpu path is: \" << libtpu_path;\n void* library = dlopen(libtpu_path, RTLD_NOW);\n if (library) {\n \/\/ We can open the shared library which means we are in a TPU environment.\n \/\/ Try to acquire exclusive access.\n TF_RETURN_IF_ERROR(TryAcquireTpuLock());\n TF_RETURN_IF_ERROR(InitializeTpuLibrary(library));\n }\n\n InitializeCreateGcsFileSystemFnPtr();\n return Status::OK();\n}\n\n#elif defined(LIBTPU_STATIC)\n\n#include \"tensorflow\/core\/tpu\/tpu_library_init_fns.inc\"\n\nStatus InitializeTpuLibrary() {\n \/\/ Retrieve arguments from environment if applicable\n std::pair, std::vector> args =\n GetLibTpuInitArguments();\n\n TfTpu_Initialize(\/*init_library*\/ true, args.second.size(),\n args.second.data());\n\n RegisterTpuPlatform();\n return Status::OK();\n}\n\nStatus FindAndLoadTpuLibrary() {\n \/\/ We can open the shared library which means we are in a TPU environment.\n \/\/ Try to acquire exclusive access.\n TF_RETURN_IF_ERROR(TryAcquireTpuLock());\n TF_RETURN_IF_ERROR(InitializeTpuLibrary());\n return Status::OK();\n}\n\n#else \/\/ PLATFORM_GOOGLE\nStatus InitializeTpuLibrary(void* library_handle) {\n return errors::Unimplemented(\"You must statically link in a TPU library.\");\n}\n#endif \/\/ PLATFORM_GOOGLE\nstd::pair, std::vector>\nGetLibTpuInitArguments() {\n \/\/ We make copies of the arguments returned by getenv because the memory\n \/\/ returned may be altered or invalidated by further calls to getenv.\n std::vector args;\n std::vector arg_ptrs;\n\n \/\/ Retrieve arguments from environment if applicable.\n char* env = getenv(\"LIBTPU_INIT_ARGS\");\n if (env != nullptr) {\n \/\/ TODO(frankchn): Handles quotes properly if necessary.\n args = absl::StrSplit(env, ' ');\n }\n\n arg_ptrs.reserve(args.size());\n for (int i = 0; i < args.size(); ++i) {\n arg_ptrs.push_back(args[i].data());\n }\n\n return {std::move(args), std::move(arg_ptrs)};\n}\n\n} \/\/ namespace tpu\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkDCMTKTransformIO.h\"\n#include \"itkDCMTKTransformIOFactory.h\"\n#include \"itkTransformFileReader.h\"\n#include \"itkImageSeriesReader.h\"\n#include \"itkDCMTKImageIO.h\"\n#include \"itkDCMTKSeriesFileNames.h\"\n#include \"itkGDCMImageIO.h\"\n#include \"itkGDCMSeriesFileNames.h\"\n#include \"itkCompositeTransform.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkMetaDataObject.h\"\n#include \"itkResampleImageFilter.h\"\n\n\nint ReadDicomTransformAndResampleExample( int argc, char* argv[] )\n{\n \/\/ Parse command line arguments\n if( argc < 5 )\n {\n std::cerr << \"Usage: \" << argv[0]\n << \" fixedSeriesDirectory movingSeriesDirectory transform fixedImageOutput resampledMovingOutput\" << std::endl;\n return EXIT_FAILURE;\n }\n const char * fixedSeriesDirectory = argv[1];\n const char * movingSeriesDirectory = argv[2];\n const char * transformFileName = argv[3];\n const char * fixedImageOutputFileName = argv[4];\n const char * resampledMovingOutputFileName = argv[5];\n\n\n \/\/ Basic types\n const unsigned int Dimension = 3;\n typedef short PixelType;\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n \/\/ Read the fixed and moving image\n typedef itk::ImageSeriesReader< ImageType > ReaderType;\n ReaderType::Pointer fixedReader = ReaderType::New();\n\n \/\/ DCMTKImageIO does not populate the MetaDataDictionary yet\n \/\/typedef itk::DCMTKImageIO ImageIOType;\n typedef itk::GDCMImageIO ImageIOType;\n ImageIOType::Pointer fixedIO = ImageIOType::New();\n fixedReader->SetImageIO( fixedIO );\n\n \/\/typedef itk::DCMTKSeriesFileNames SeriesFileNamesType;\n typedef itk::GDCMSeriesFileNames SeriesFileNamesType;\n SeriesFileNamesType::Pointer fixedSeriesFileNames = SeriesFileNamesType::New();\n fixedSeriesFileNames->SetInputDirectory( fixedSeriesDirectory );\n typedef SeriesFileNamesType::FileNamesContainerType FileNamesContainerType;\n const FileNamesContainerType & fixedFileNames = fixedSeriesFileNames->GetInputFileNames();\n std::cout << \"There are \" << fixedFileNames.size() << \" fixed image slices.\" << std::endl;\n std::cout << \"First fixed images series UID: \" << fixedSeriesFileNames->GetSeriesUIDs()[0] << \"\\n\" << std::endl;\n fixedReader->SetFileNames( fixedFileNames );\n\n ReaderType::Pointer movingReader = ReaderType::New();\n ImageIOType::Pointer movingIO = ImageIOType::New();\n movingReader->SetImageIO( movingIO );\n\n SeriesFileNamesType::Pointer movingSeriesFileNames = SeriesFileNamesType::New();\n movingSeriesFileNames->SetInputDirectory( movingSeriesDirectory );\n const FileNamesContainerType & movingFileNames = movingSeriesFileNames->GetInputFileNames();\n std::cout << \"There are \" << movingFileNames.size() << \" moving image slices.\" << std::endl;\n std::cout << \"First moving images series UID: \" << movingSeriesFileNames->GetSeriesUIDs()[0] << \"\\n\" << std::endl;\n movingReader->SetFileNames( movingFileNames );\n\n try\n {\n fixedReader->Update();\n movingReader->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Create a DICOM transform reader\n typedef float ScalarType;\n\n itk::DCMTKTransformIOFactory::Pointer dcmtkTransformIOFactory = itk::DCMTKTransformIOFactory::New();\n itk::ObjectFactoryBase::RegisterFactory( dcmtkTransformIOFactory );\n\n typedef itk::TransformFileReaderTemplate< ScalarType > TransformReaderType;\n TransformReaderType::Pointer transformReader = TransformReaderType::New();\n transformReader->SetFileName( transformFileName );\n\n typedef itk::DCMTKTransformIO< ScalarType > TransformIOType;\n TransformIOType::Pointer transformIO = TransformIOType::New();\n transformReader->SetTransformIO( transformIO );\n\n\n \/\/ Read in the fixed image transform\n const ReaderType::DictionaryType & fixedMetaDataDict = fixedIO->GetMetaDataDictionary();\n std::string fixedFrameOfReferenceUID;\n if( ! itk::ExposeMetaData< std::string >( fixedMetaDataDict, \"0020|0052\", fixedFrameOfReferenceUID ) )\n {\n std::cerr << \"Could not find the fixed image frame of reference UID.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Fixed image frame of reference UID: \" << fixedFrameOfReferenceUID << std::endl;\n transformIO->SetFrameOfReferenceUID( fixedFrameOfReferenceUID );\n\n try\n {\n transformReader->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n typedef TransformReaderType::TransformListType TransformListType;\n TransformListType * transformList = transformReader->GetTransformList();\n\n typedef itk::CompositeTransform< ScalarType, Dimension > ReadTransformType;\n TransformListType::const_iterator transformIt = transformList->begin();\n ReadTransformType::Pointer fixedTransform = dynamic_cast< ReadTransformType * >( (*transformIt).GetPointer() );\n if( fixedTransform.IsNull() )\n {\n std::cerr << \"Did not get the expected transform out.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Fixed transform: \" << fixedTransform << std::endl;\n\n\n \/\/ Read in the moving image transform\n const ReaderType::DictionaryType & movingMetaDataDict = movingIO->GetMetaDataDictionary();\n std::string movingFrameOfReferenceUID;\n if( ! itk::ExposeMetaData< std::string >( movingMetaDataDict, \"0020|0052\", movingFrameOfReferenceUID ) )\n {\n std::cerr << \"Could not find the moving image frame of reference UID.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Moving image frame of reference UID: \" << movingFrameOfReferenceUID << std::endl;\n transformIO->SetFrameOfReferenceUID( movingFrameOfReferenceUID );\n\n try\n {\n transformReader->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n transformList = transformReader->GetTransformList();\n transformIt = transformList->begin();\n ReadTransformType::Pointer movingTransform = dynamic_cast< ReadTransformType * >( (*transformIt).GetPointer() );\n if( movingTransform.IsNull() )\n {\n std::cerr << \"Did not get the expected transform out.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Moving transform: \" << movingTransform << std::endl;\n\n\n \/\/ Compose the transform from the fixed to the moving image\n ReadTransformType::Pointer movingTransformInverse = ReadTransformType::New();\n movingTransform->GetInverse( movingTransformInverse );\n\n ReadTransformType::Pointer fixedToMovingTransform = ReadTransformType::New();\n fixedToMovingTransform->AddTransform( fixedTransform );\n fixedToMovingTransform->AddTransform( movingTransformInverse );\n \/\/ Flatten out the two component CompositeTransforms.\n fixedToMovingTransform->FlattenTransformQueue();\n\n typedef itk::ResampleImageFilter< ImageType, ImageType, ScalarType, ScalarType > ResamplerType;\n ResamplerType::Pointer resampler = ResamplerType::New();\n resampler->SetInput( movingReader->GetOutput() );\n resampler->SetUseReferenceImage( true );\n resampler->SetReferenceImage( fixedReader->GetOutput() );\n resampler->SetTransform( fixedToMovingTransform );\n resampler->SetDefaultPixelValue( -1000 );\n\n\n \/\/ Write the fixed image and resampled moving image (should look similar)\n typedef itk::ImageFileWriter< ImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( fixedImageOutputFileName );\n writer->SetInput( fixedReader->GetOutput() );\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n writer->SetInput( resampler->GetOutput() );\n writer->SetFileName( resampledMovingOutputFileName );\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n\n return EXIT_SUCCESS;\n}\nSTYLE: Line wrap example for inclusion in PDF doc.\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkDCMTKTransformIO.h\"\n#include \"itkDCMTKTransformIOFactory.h\"\n#include \"itkTransformFileReader.h\"\n#include \"itkImageSeriesReader.h\"\n#include \"itkDCMTKImageIO.h\"\n#include \"itkDCMTKSeriesFileNames.h\"\n#include \"itkGDCMImageIO.h\"\n#include \"itkGDCMSeriesFileNames.h\"\n#include \"itkCompositeTransform.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkMetaDataObject.h\"\n#include \"itkResampleImageFilter.h\"\n\n\nint ReadDicomTransformAndResampleExample( int argc, char* argv[] )\n{\n \/\/ Parse command line arguments\n if( argc < 5 )\n {\n std::cerr << \"Usage: \" << argv[0]\n << \" fixedSeriesDirectory movingSeriesDirectory\"\n << \" transform fixedImageOutput resampledMovingOutput\"\n << std::endl;\n return EXIT_FAILURE;\n }\n const char * fixedSeriesDirectory = argv[1];\n const char * movingSeriesDirectory = argv[2];\n const char * transformFileName = argv[3];\n const char * fixedImageOutputFileName = argv[4];\n const char * resampledMovingOutputFileName = argv[5];\n\n\n \/\/ Basic types\n const unsigned int Dimension = 3;\n typedef short PixelType;\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n \/\/ Read the fixed and moving image\n typedef itk::ImageSeriesReader< ImageType > ReaderType;\n ReaderType::Pointer fixedReader = ReaderType::New();\n\n \/\/ DCMTKImageIO does not populate the MetaDataDictionary yet\n \/\/typedef itk::DCMTKImageIO ImageIOType;\n typedef itk::GDCMImageIO ImageIOType;\n ImageIOType::Pointer fixedIO = ImageIOType::New();\n fixedReader->SetImageIO( fixedIO );\n\n \/\/typedef itk::DCMTKSeriesFileNames SeriesFileNamesType;\n typedef itk::GDCMSeriesFileNames SeriesFileNamesType;\n SeriesFileNamesType::Pointer fixedSeriesFileNames =\n SeriesFileNamesType::New();\n fixedSeriesFileNames->SetInputDirectory( fixedSeriesDirectory );\n typedef SeriesFileNamesType::FileNamesContainerType FileNamesContainerType;\n const FileNamesContainerType & fixedFileNames =\n fixedSeriesFileNames->GetInputFileNames();\n std::cout << \"There are \"\n << fixedFileNames.size()\n << \" fixed image slices.\"\n << std::endl;\n std::cout << \"First fixed images series UID: \"\n << fixedSeriesFileNames->GetSeriesUIDs()[0]\n << \"\\n\" << std::endl;\n fixedReader->SetFileNames( fixedFileNames );\n\n ReaderType::Pointer movingReader = ReaderType::New();\n ImageIOType::Pointer movingIO = ImageIOType::New();\n movingReader->SetImageIO( movingIO );\n\n SeriesFileNamesType::Pointer movingSeriesFileNames =\n SeriesFileNamesType::New();\n movingSeriesFileNames->SetInputDirectory( movingSeriesDirectory );\n const FileNamesContainerType & movingFileNames =\n movingSeriesFileNames->GetInputFileNames();\n std::cout << \"There are \"\n << movingFileNames.size()\n << \" moving image slices.\"\n << std::endl;\n std::cout << \"First moving images series UID: \"\n << movingSeriesFileNames->GetSeriesUIDs()[0]\n << \"\\n\" << std::endl;\n movingReader->SetFileNames( movingFileNames );\n\n try\n {\n fixedReader->Update();\n movingReader->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Create a DICOM transform reader\n typedef float ScalarType;\n\n itk::DCMTKTransformIOFactory::Pointer dcmtkTransformIOFactory =\n itk::DCMTKTransformIOFactory::New();\n itk::ObjectFactoryBase::RegisterFactory( dcmtkTransformIOFactory );\n\n typedef itk::TransformFileReaderTemplate< ScalarType > TransformReaderType;\n TransformReaderType::Pointer transformReader = TransformReaderType::New();\n transformReader->SetFileName( transformFileName );\n\n typedef itk::DCMTKTransformIO< ScalarType > TransformIOType;\n TransformIOType::Pointer transformIO = TransformIOType::New();\n transformReader->SetTransformIO( transformIO );\n\n\n \/\/ Read in the fixed image transform\n const ReaderType::DictionaryType & fixedMetaDataDict =\n fixedIO->GetMetaDataDictionary();\n std::string fixedFrameOfReferenceUID;\n if( ! itk::ExposeMetaData< std::string >( fixedMetaDataDict,\n \"0020|0052\",\n fixedFrameOfReferenceUID ) )\n {\n std::cerr << \"Could not find the fixed image frame of reference UID.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Fixed image frame of reference UID: \"\n << fixedFrameOfReferenceUID << std::endl;\n transformIO->SetFrameOfReferenceUID( fixedFrameOfReferenceUID );\n\n try\n {\n transformReader->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n typedef TransformReaderType::TransformListType TransformListType;\n TransformListType * transformList = transformReader->GetTransformList();\n\n typedef itk::CompositeTransform< ScalarType, Dimension > ReadTransformType;\n TransformListType::const_iterator transformIt = transformList->begin();\n ReadTransformType::Pointer fixedTransform =\n dynamic_cast< ReadTransformType * >( (*transformIt).GetPointer() );\n if( fixedTransform.IsNull() )\n {\n std::cerr << \"Did not get the expected transform out.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Fixed transform: \" << fixedTransform << std::endl;\n\n\n \/\/ Read in the moving image transform\n const ReaderType::DictionaryType & movingMetaDataDict =\n movingIO->GetMetaDataDictionary();\n std::string movingFrameOfReferenceUID;\n if( ! itk::ExposeMetaData< std::string >( movingMetaDataDict,\n \"0020|0052\",\n movingFrameOfReferenceUID ) )\n {\n std::cerr << \"Could not find the moving image frame of reference UID.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Moving image frame of reference UID: \"\n << movingFrameOfReferenceUID << std::endl;\n transformIO->SetFrameOfReferenceUID( movingFrameOfReferenceUID );\n\n try\n {\n transformReader->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n transformList = transformReader->GetTransformList();\n transformIt = transformList->begin();\n ReadTransformType::Pointer movingTransform =\n dynamic_cast< ReadTransformType * >( (*transformIt).GetPointer() );\n if( movingTransform.IsNull() )\n {\n std::cerr << \"Did not get the expected transform out.\" << std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"Moving transform: \" << movingTransform << std::endl;\n\n\n \/\/ Compose the transform from the fixed to the moving image\n ReadTransformType::Pointer movingTransformInverse = ReadTransformType::New();\n movingTransform->GetInverse( movingTransformInverse );\n\n ReadTransformType::Pointer fixedToMovingTransform = ReadTransformType::New();\n fixedToMovingTransform->AddTransform( fixedTransform );\n fixedToMovingTransform->AddTransform( movingTransformInverse );\n \/\/ Flatten out the two component CompositeTransforms.\n fixedToMovingTransform->FlattenTransformQueue();\n\n typedef itk::ResampleImageFilter< ImageType, ImageType, ScalarType, ScalarType >\n ResamplerType;\n ResamplerType::Pointer resampler = ResamplerType::New();\n resampler->SetInput( movingReader->GetOutput() );\n resampler->SetUseReferenceImage( true );\n resampler->SetReferenceImage( fixedReader->GetOutput() );\n resampler->SetTransform( fixedToMovingTransform );\n resampler->SetDefaultPixelValue( -1000 );\n\n\n \/\/ Write the fixed image and resampled moving image (should look similar)\n typedef itk::ImageFileWriter< ImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( fixedImageOutputFileName );\n writer->SetInput( fixedReader->GetOutput() );\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n writer->SetInput( resampler->GetOutput() );\n writer->SetFileName( resampledMovingOutputFileName );\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & error )\n {\n std::cerr << \"Error: \" << error << std::endl;\n return EXIT_FAILURE;\n }\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#ifdef SYMGS_COLOR\n#include \"ColorSYMGS.hpp\"\n\nclass colouredForwardSweep{\n public:\n local_int_t colors_row;\n local_int_1d_type colors_ind;\n\n local_matrix_type A;\n double_1d_type rv, xv;\n int_1d_type matrixDiagonal;\n\n colouredForwardSweep(const local_int_t colors_row_, const local_int_1d_type& colors_ind_,\n const local_matrix_type& A_, const double_1d_type& rv_, double_1d_type& xv_,\n const int_1d_type matrixDiagonal_):\n colors_row(colors_row_), colors_ind(colors_ind_), A(A_), rv(rv_), xv(xv_),\n matrixDiagonal(matrixDiagonal_) {}\n\n void operator()(const int & i)const{\n local_int_t currentRow = colors_ind(colors_row + i); \/\/ This should tell us what row we're doing SYMGS on.\n int start = A.graph.row_map(currentRow);\n int end = A.graph.row_map(currentRow+1);\n const double currentDiagonal = A.values(matrixDiagonal(currentRow));\n double sum = rv(currentRow);\n for(int j = start; j < end; j++)\n sum -= A.values(j) * xv(A.graph.entries(j));\n sum += xv(currentRow) * currentDiagonal;\n xv(currentRow) = sum\/currentDiagonal;\n }\n};\n\nclass colouredBackSweep{\n public:\n local_int_t colors_row;\n local_int_1d_type colors_ind;\n \n local_matrix_type A;\n double_1d_type rv, xv;\n int_1d_type matrixDiagonal;\n\n colouredBackSweep(const local_int_t colors_row_, const local_int_1d_type& colors_ind_,\n const local_matrix_type& A_, const double_1d_type& rv_, double_1d_type& xv_,\n const int_1d_type matrixDiagonal_):\n colors_row(colors_row_), colors_ind(colors_ind_), A(A_), rv(rv_), xv(xv_),\n matrixDiagonal(matrixDiagonal_) {}\n\n void operator()(const int & i)const{\n local_int_t currentRow = colors_ind(colors_row + i); \/\/ This should tell us what row we're doing SYMGS on.\n int start = A.graph.row_map(currentRow);\n int end = A.graph.row_map(currentRow+1);\n const double currentDiagonal = A.values(matrixDiagonal(currentRow));\n double sum = rv(currentRow);\n for(int j = start; j < end; j++)\n sum -= A.values(j) * xv(A.graph.entries(j));\n sum += xv(currentRow) * currentDiagonal;\n xv(currentRow) = sum\/currentDiagonal;\n }\n};\n\nint ColorSYMGS( const SparseMatrix & A, const Vector & r, Vector & x){\nassert(x.localLength == A.localNumberOfColumns); \/\/ Make sure x contains space for halo values\n\n#ifndef HPCG_NOMPI\n ExchangeHalo(A,x);\n#endif\n\t \/\/ Forward Sweep!\n const int numColors = A.numColors;\n local_int_t dummy = 0;\n for(int i = 0; i < numColors; i++){\n int currentColor = A.f_colors_order(i);\n int start = A.colors_map(currentColor - 1); \/\/ Colors start at 1, i starts at 0\n int end = A.colors_map(currentColor);\n dummy += end - start;\n Kokkos::parallel_for(end - start, colouredForwardSweep(start, A.colors_ind, A.localMatrix, r.values, x.values, A.matrixDiagonal));\n }\n assert(dummy == A.localNumberOfRows);\n \/\/ Back Sweep!\n for(int i = numColors -1; i >= 0; --i){\n int currentColor = A.f_colors_order(i);\n int start = A.colors_map(currentColor - 1); \/\/ Colors start at 1, i starts at 0\n int end = A.colors_map(currentColor);\n Kokkos::parallel_for(end - start, colouredBackSweep(start, A.colors_ind, A.localMatrix, r.values, x.values, A.matrixDiagonal));\n }\n\nreturn(0);\n}\n#endif\nDebugging#ifdef SYMGS_COLOR\n#include \"ColorSYMGS.hpp\"\n\nclass colouredForwardSweep{\n public:\n local_int_t colors_row;\n local_int_1d_type colors_ind;\n\n local_matrix_type A;\n double_1d_type rv, xv;\n int_1d_type matrixDiagonal;\n\n colouredForwardSweep(const local_int_t colors_row_, const local_int_1d_type& colors_ind_,\n const local_matrix_type& A_, const double_1d_type& rv_, double_1d_type& xv_,\n const int_1d_type matrixDiagonal_):\n colors_row(colors_row_), colors_ind(colors_ind_), A(A_), rv(rv_), xv(xv_),\n matrixDiagonal(matrixDiagonal_) {}\n\nKOKKOS_INLINE_FUNCTION\n void operator()(const int & i)const{\n local_int_t currentRow = colors_ind(colors_row + i); \/\/ This should tell us what row we're doing SYMGS on.\n int start = A.graph.row_map(currentRow);\n int end = A.graph.row_map(currentRow+1);\n const double currentDiagonal = A.values(matrixDiagonal(currentRow));\n double sum = rv(currentRow);\n for(int j = start; j < end; j++)\n sum -= A.values(j) * xv(A.graph.entries(j));\n sum += xv(currentRow) * currentDiagonal;\n xv(currentRow) = sum\/currentDiagonal;\n }\n};\n\nclass colouredBackSweep{\n public:\n local_int_t colors_row;\n local_int_1d_type colors_ind;\n \n local_matrix_type A;\n double_1d_type rv, xv;\n int_1d_type matrixDiagonal;\n\n colouredBackSweep(const local_int_t colors_row_, const local_int_1d_type& colors_ind_,\n const local_matrix_type& A_, const double_1d_type& rv_, double_1d_type& xv_,\n const int_1d_type matrixDiagonal_):\n colors_row(colors_row_), colors_ind(colors_ind_), A(A_), rv(rv_), xv(xv_),\n matrixDiagonal(matrixDiagonal_) {}\nKOKKOS_INLINE_FUNCTION\n void operator()(const int & i)const{\n local_int_t currentRow = colors_ind(colors_row + i); \/\/ This should tell us what row we're doing SYMGS on.\n int start = A.graph.row_map(currentRow);\n int end = A.graph.row_map(currentRow+1);\n const double currentDiagonal = A.values(matrixDiagonal(currentRow));\n double sum = rv(currentRow);\n for(int j = start; j < end; j++)\n sum -= A.values(j) * xv(A.graph.entries(j));\n sum += xv(currentRow) * currentDiagonal;\n xv(currentRow) = sum\/currentDiagonal;\n }\n};\n\nint ColorSYMGS( const SparseMatrix & A, const Vector & r, Vector & x){\nassert(x.localLength == A.localNumberOfColumns); \/\/ Make sure x contains space for halo values\n\n#ifndef HPCG_NOMPI\n ExchangeHalo(A,x);\n#endif\n\t \/\/ Forward Sweep!\n const int numColors = A.numColors;\n local_int_t dummy = 0;\n for(int i = 0; i < numColors; i++){\n int currentColor = A.f_colors_order(i);\n int start = A.colors_map(currentColor - 1); \/\/ Colors start at 1, i starts at 0\n int end = A.colors_map(currentColor);\n dummy += end - start;\n Kokkos::parallel_for(end - start, colouredForwardSweep(start, A.colors_ind, A.localMatrix, r.values, x.values, A.matrixDiagonal));\n }\n assert(dummy == A.localNumberOfRows);\n \/\/ Back Sweep!\n for(int i = numColors -1; i >= 0; --i){\n int currentColor = A.f_colors_order(i);\n int start = A.colors_map(currentColor - 1); \/\/ Colors start at 1, i starts at 0\n int end = A.colors_map(currentColor);\n Kokkos::parallel_for(end - start, colouredBackSweep(start, A.colors_ind, A.localMatrix, r.values, x.values, A.matrixDiagonal));\n }\n\nreturn(0);\n}\n#endif\n<|endoftext|>"} {"text":"#include \"CurlClient.h\"\n\n#include \"BasicAuth.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#include \n\nstatic bool is_initialized = false;\n\nclass CurlClient : public HTTPClient {\n public:\n CurlClient(const std::string & _interface, const std::string & _user_agent, bool _enable_cookies = true, bool _enable_keepalive = true)\n : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive),\n interface_name(_interface)\n {\n assert(is_initialized);\n }\n\n ~CurlClient() {\n if (curl) curl_easy_cleanup(curl);\n }\n\n void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) override {\n#if 0\n if (req.getURI().empty()) {\n return HTTPResponse(0, \"empty URI\");\n }\n#endif\n if (!initialize()) {\n \/\/ return HTTPResponse(0, \"Unable to initialize client\");\n return;\n }\n\n \/\/ string ascii_uri = encodeIDN(uri);\n \/\/ if (ascii_uri.empty()) {\n \/\/ cerr << \"failed to convert url \" << uri << endl;\n \/\/ assert(0);\n \/\/ }\n\n struct curl_slist * headers = 0;\n if (req.getType() == HTTPRequest::POST) {\n if (!req.getContentType().empty()) {\n\tstring h = \"Content-type: \";\n\th += req.getContentType();\n\theaders = curl_slist_append(headers, h.c_str());\n }\n }\n \n const BasicAuth * basic = dynamic_cast(&auth);\n if (basic) {\n string s = basic->getUsername();\n s += ':';\n s += basic->getPassword();\n curl_easy_setopt(curl, CURLOPT_USERPWD, s.c_str());\n } else {\n string auth_header = auth.createHeader();\n if (!auth_header.empty()) {\n\tstring s = auth.getHeaderName();\n\ts += \": \";\n\ts += auth_header;\n\theaders = curl_slist_append(headers, s.c_str());\n }\n }\n\n map combined_headers;\n for (auto & hd : default_headers) {\n combined_headers[hd.first] = hd.second; \n }\n for (auto & hd : req.getHeaders()) {\n combined_headers[hd.first] = hd.second;\n }\n for (auto & hd : combined_headers) {\n string s = hd.first;\n s += \": \";\n s += hd.second;\n headers = curl_slist_append(headers, s.c_str());\n }\n \n if (req.getType() == HTTPRequest::POST) {\n curl_easy_setopt(curl, CURLOPT_HTTPGET, 0);\n curl_easy_setopt(curl, CURLOPT_POST, 1);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req.getContent().size());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req.getContent().data());\n } else {\n curl_easy_setopt(curl, CURLOPT_POST, 0);\n curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);\n }\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, req.getFollowLocation());\n curl_easy_setopt(curl, CURLOPT_URL, req.getURI().c_str());\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);\n curl_easy_setopt(curl, CURLOPT_TIMEOUT, req.getTimeout());\n \n curl_easy_setopt(curl, CURLOPT_HEADERDATA, &callback);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, &callback);\n curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &callback);\n\n CURLcode res = curl_easy_perform(curl);\n \/\/ if (res != 0) {\n \/\/ response.setResultCode(500);\n \/\/ response.setErrorText(curl_easy_strerror(res));\n \/\/ }\n \n callback.handleDisconnect();\n \n if (headers) {\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, 0);\n curl_slist_free_all(headers);\n }\n \n curl_easy_setopt(curl, CURLOPT_HEADERDATA, 0);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, 0);\n curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, 0);\n curl_easy_setopt(curl, CURLOPT_USERPWD, 0);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 0);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, 0);\n }\n \n void clearCookies() override {\n if (curl) {\n curl_easy_setopt(curl, CURLOPT_URL, \"ALL\"); \/\/ what does this do?\n }\n }\n \n protected:\n bool initialize() {\n if (!curl) {\n curl = curl_easy_init();\n assert(curl);\n if (curl) {\n#ifndef WIN32\n\tif (!interface_name.empty()) {\n\t int r = curl_easy_setopt(curl, CURLOPT_INTERFACE, interface_name.c_str());\n\t assert(r != CURLE_INTERFACE_FAILED);\n\t}\n#endif\n\tcurl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n\tcurl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());\n\tcurl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_func);\n\tcurl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_func);\n\tcurl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headers_func);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);\n\tcurl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 600);\n\tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 0);\n\tcurl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, \"gzip, deflate\");\n\n\tif (!cookie_jar.empty()) {\n\t curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar.c_str());\n\t curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar.c_str());\n\t} else if (enable_cookies) {\n\t curl_easy_setopt(curl, CURLOPT_COOKIEFILE, \"\");\n\t}\n\tif (!enable_keepalive) {\n\t curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);\n\t curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);\n\t \/\/ curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 10);\n\t}\n }\n }\n \n return curl != 0;\n }\n\n private:\n static size_t write_data_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static size_t headers_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static int progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow);\n\n std::string interface_name;\n CURL * curl = 0;\n};\n \nsize_t\nCurlClient::write_data_func(void * buffer, size_t size, size_t nmemb, void * userp) {\n size_t s = size * nmemb;\n \/\/ Content-Type: multipart\/x-mixed-replace; boundary=myboundary\n\t\t\t\t\t \n HTTPClientInterface * callback = (HTTPClientInterface *)(userp);\n assert(callback);\n return callback->handleChunk(s, (const char *)buffer) ? s : 0; \n}\n\nsize_t\nCurlClient::headers_func(void * buffer, size_t size, size_t nmemb, void *userp) {\n HTTPClientInterface * callback = (HTTPClientInterface *)(userp);\n \n size_t s = size * nmemb;\n bool keep_running = true;\n if (buffer) {\n string input((const char*)buffer, s);\n\n if (input.compare(0, 5, \"HTTP\/\") == 0) {\n auto pos1 = input.find_first_of(' ');\n if (pos1 != string::npos) {\n\tauto pos2 = input.find_first_of(' ', pos1 + 1);\n\tif (pos2 != string::npos) {\n\t auto s2 = input.substr(pos1, pos2 - pos1);\n\t int code = atoi(s2.c_str());\n\t callback->handleResultCode(code);\n\t}\n }\n } else {\n int pos1 = 0;\n for ( ; pos1 < input.size() && input[pos1] != ':'; pos1++) { }\n int pos2 = input[pos1] == ':' ? pos1 + 1 : pos1;\n for (; pos2 < input.size() && isspace(input[pos2]); pos2++) { }\n int pos3 = input.size();\n for (; pos3 > 0 && isspace(input[pos3 - 1]); pos3--) { }\n std::string key = input.substr(0, pos1);\n std::string value = input.substr(pos2, pos3 - pos2);\n\n if (key == \"Location\" && !callback->handleRedirectUrl(value)) {\n\tkeep_running = false;\n } \n callback->handleHeader(key, value);\n }\n }\n\n return keep_running ? s : 0;\n}\n\nint\nCurlClient::progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow) {\n HTTPClientInterface * callback = (HTTPClientInterface *)(clientp);\n assert(callback);\n return callback->onIdle(true) ? 0 : 1;\n}\n\n#ifndef __APPLE__\nstatic pthread_mutex_t *lockarray;\n\n#include \n\nstatic void lock_callback(int mode, int type, const char *file, int line) {\n (void)file;\n (void)line;\n if (mode & CRYPTO_LOCK) {\n pthread_mutex_lock(&(lockarray[type]));\n } else {\n pthread_mutex_unlock(&(lockarray[type]));\n }\n}\n \nstatic unsigned long thread_id(void) {\n unsigned long ret;\n \n#ifdef WIN32\n ret = (unsigned long)(pthread_self().p);\n#else\n ret = (unsigned long)pthread_self();\n#endif\n return(ret);\n}\n \nstatic void init_locks(void) {\n int i;\n \n lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *\n\t\t\t\t\t sizeof(pthread_mutex_t));\n for (i=0; i\n#include \n#include \n\nGCRY_THREAD_OPTION_PTHREAD_IMPL;\n#endif\n\nstd::unique_ptr\nCurlClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {\n return std::unique_ptr(new CurlClient(\"\", _user_agent, _enable_cookies, _enable_keepalive));\n}\n\nvoid\nCurlClientFactory::globalInit() {\n is_initialized = true;\n \n#ifndef __APPLE__\n#if 0\n gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n gnutls_global_init();\n#else\n init_locks();\n#endif\n#endif\n\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n#if 0\n thread_setup();\n#endif\n#if 0\n gnutls_global_init();\n#endif\n}\n\nvoid\nCurlClientFactory::globalCleanup() {\n is_initialized = false;\n \n curl_global_cleanup();\n#ifndef __APPLE__\n kill_locks();\n#endif\n}\ndisable timeout, set connect timeout#include \"CurlClient.h\"\n\n#include \"BasicAuth.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#include \n\nstatic bool is_initialized = false;\n\nclass CurlClient : public HTTPClient {\n public:\n CurlClient(const std::string & _interface, const std::string & _user_agent, bool _enable_cookies = true, bool _enable_keepalive = true)\n : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive),\n interface_name(_interface)\n {\n assert(is_initialized);\n }\n\n ~CurlClient() {\n if (curl) curl_easy_cleanup(curl);\n }\n\n void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) override {\n#if 0\n if (req.getURI().empty()) {\n return HTTPResponse(0, \"empty URI\");\n }\n#endif\n if (!initialize()) {\n \/\/ return HTTPResponse(0, \"Unable to initialize client\");\n return;\n }\n\n \/\/ string ascii_uri = encodeIDN(uri);\n \/\/ if (ascii_uri.empty()) {\n \/\/ cerr << \"failed to convert url \" << uri << endl;\n \/\/ assert(0);\n \/\/ }\n\n struct curl_slist * headers = 0;\n if (req.getType() == HTTPRequest::POST) {\n if (!req.getContentType().empty()) {\n\tstring h = \"Content-type: \";\n\th += req.getContentType();\n\theaders = curl_slist_append(headers, h.c_str());\n }\n }\n \n const BasicAuth * basic = dynamic_cast(&auth);\n if (basic) {\n string s = basic->getUsername();\n s += ':';\n s += basic->getPassword();\n curl_easy_setopt(curl, CURLOPT_USERPWD, s.c_str());\n } else {\n string auth_header = auth.createHeader();\n if (!auth_header.empty()) {\n\tstring s = auth.getHeaderName();\n\ts += \": \";\n\ts += auth_header;\n\theaders = curl_slist_append(headers, s.c_str());\n }\n }\n\n map combined_headers;\n for (auto & hd : default_headers) {\n combined_headers[hd.first] = hd.second; \n }\n for (auto & hd : req.getHeaders()) {\n combined_headers[hd.first] = hd.second;\n }\n for (auto & hd : combined_headers) {\n string s = hd.first;\n s += \": \";\n s += hd.second;\n headers = curl_slist_append(headers, s.c_str());\n }\n \n if (req.getType() == HTTPRequest::POST) {\n curl_easy_setopt(curl, CURLOPT_HTTPGET, 0);\n curl_easy_setopt(curl, CURLOPT_POST, 1);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req.getContent().size());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req.getContent().data());\n } else {\n curl_easy_setopt(curl, CURLOPT_POST, 0);\n curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);\n }\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, req.getFollowLocation());\n curl_easy_setopt(curl, CURLOPT_URL, req.getURI().c_str());\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, req.getConnectTimeout());\n \/\/ curl_easy_setopt(curl, CURLOPT_TIMEOUT, req.getTimeout());\n \n curl_easy_setopt(curl, CURLOPT_HEADERDATA, &callback);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, &callback);\n curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &callback);\n\n CURLcode res = curl_easy_perform(curl);\n \/\/ if (res != 0) {\n \/\/ response.setResultCode(500);\n \/\/ response.setErrorText(curl_easy_strerror(res));\n \/\/ }\n \n callback.handleDisconnect();\n \n if (headers) {\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, 0);\n curl_slist_free_all(headers);\n }\n \n curl_easy_setopt(curl, CURLOPT_HEADERDATA, 0);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, 0);\n curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, 0);\n curl_easy_setopt(curl, CURLOPT_USERPWD, 0);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 0);\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, 0);\n }\n \n void clearCookies() override {\n if (curl) {\n curl_easy_setopt(curl, CURLOPT_URL, \"ALL\"); \/\/ what does this do?\n }\n }\n \n protected:\n bool initialize() {\n if (!curl) {\n curl = curl_easy_init();\n assert(curl);\n if (curl) {\n#ifndef WIN32\n\tif (!interface_name.empty()) {\n\t int r = curl_easy_setopt(curl, CURLOPT_INTERFACE, interface_name.c_str());\n\t assert(r != CURLE_INTERFACE_FAILED);\n\t}\n#endif\n\tcurl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n\tcurl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());\n\tcurl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_func);\n\tcurl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_func);\n\tcurl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headers_func);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);\n\tcurl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 600);\n\tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 0);\n\tcurl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, \"gzip, deflate\");\n\n\tif (!cookie_jar.empty()) {\n\t curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar.c_str());\n\t curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar.c_str());\n\t} else if (enable_cookies) {\n\t curl_easy_setopt(curl, CURLOPT_COOKIEFILE, \"\");\n\t}\n\tif (!enable_keepalive) {\n\t curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);\n\t curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);\n\t \/\/ curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 10);\n\t}\n }\n }\n \n return curl != 0;\n }\n\n private:\n static size_t write_data_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static size_t headers_func(void * buffer, size_t size, size_t nmemb, void *userp);\n static int progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow);\n\n std::string interface_name;\n CURL * curl = 0;\n};\n \nsize_t\nCurlClient::write_data_func(void * buffer, size_t size, size_t nmemb, void * userp) {\n size_t s = size * nmemb;\n \/\/ Content-Type: multipart\/x-mixed-replace; boundary=myboundary\n\t\t\t\t\t \n HTTPClientInterface * callback = (HTTPClientInterface *)(userp);\n assert(callback);\n return callback->handleChunk(s, (const char *)buffer) ? s : 0; \n}\n\nsize_t\nCurlClient::headers_func(void * buffer, size_t size, size_t nmemb, void *userp) {\n HTTPClientInterface * callback = (HTTPClientInterface *)(userp);\n \n size_t s = size * nmemb;\n bool keep_running = true;\n if (buffer) {\n string input((const char*)buffer, s);\n\n if (input.compare(0, 5, \"HTTP\/\") == 0) {\n auto pos1 = input.find_first_of(' ');\n if (pos1 != string::npos) {\n\tauto pos2 = input.find_first_of(' ', pos1 + 1);\n\tif (pos2 != string::npos) {\n\t auto s2 = input.substr(pos1, pos2 - pos1);\n\t int code = atoi(s2.c_str());\n\t callback->handleResultCode(code);\n\t}\n }\n } else {\n int pos1 = 0;\n for ( ; pos1 < input.size() && input[pos1] != ':'; pos1++) { }\n int pos2 = input[pos1] == ':' ? pos1 + 1 : pos1;\n for (; pos2 < input.size() && isspace(input[pos2]); pos2++) { }\n int pos3 = input.size();\n for (; pos3 > 0 && isspace(input[pos3 - 1]); pos3--) { }\n std::string key = input.substr(0, pos1);\n std::string value = input.substr(pos2, pos3 - pos2);\n\n if (key == \"Location\" && !callback->handleRedirectUrl(value)) {\n\tkeep_running = false;\n } \n callback->handleHeader(key, value);\n }\n }\n\n return keep_running ? s : 0;\n}\n\nint\nCurlClient::progress_func(void * clientp, double dltotal, double dlnow, double ultotal, double ulnow) {\n HTTPClientInterface * callback = (HTTPClientInterface *)(clientp);\n assert(callback);\n return callback->onIdle(true) ? 0 : 1;\n}\n\n#ifndef __APPLE__\nstatic pthread_mutex_t *lockarray;\n\n#include \n\nstatic void lock_callback(int mode, int type, const char *file, int line) {\n (void)file;\n (void)line;\n if (mode & CRYPTO_LOCK) {\n pthread_mutex_lock(&(lockarray[type]));\n } else {\n pthread_mutex_unlock(&(lockarray[type]));\n }\n}\n \nstatic unsigned long thread_id(void) {\n unsigned long ret;\n \n#ifdef WIN32\n ret = (unsigned long)(pthread_self().p);\n#else\n ret = (unsigned long)pthread_self();\n#endif\n return(ret);\n}\n \nstatic void init_locks(void) {\n int i;\n \n lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *\n\t\t\t\t\t sizeof(pthread_mutex_t));\n for (i=0; i\n#include \n#include \n\nGCRY_THREAD_OPTION_PTHREAD_IMPL;\n#endif\n\nstd::unique_ptr\nCurlClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {\n return std::unique_ptr(new CurlClient(\"\", _user_agent, _enable_cookies, _enable_keepalive));\n}\n\nvoid\nCurlClientFactory::globalInit() {\n is_initialized = true;\n \n#ifndef __APPLE__\n#if 0\n gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);\n gnutls_global_init();\n#else\n init_locks();\n#endif\n#endif\n\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n#if 0\n thread_setup();\n#endif\n#if 0\n gnutls_global_init();\n#endif\n}\n\nvoid\nCurlClientFactory::globalCleanup() {\n is_initialized = false;\n \n curl_global_cleanup();\n#ifndef __APPLE__\n kill_locks();\n#endif\n}\n<|endoftext|>"} {"text":"\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2015. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"Dispatcher.h\"\n\n#include \"tcpsockets\/TCPAcceptor.h\"\n#include \"tcpsockets\/TCPConnector.h\"\n\nusing namespace nt;\n\n#define DEBUG(str) puts(str)\n\nstd::unique_ptr Dispatcher::m_instance;\n\nstatic NT_Type GetEntryType(unsigned int id) {\n \/\/ TODO\n return NT_UNASSIGNED;\n}\n\nDispatcher::Dispatcher()\n : m_server(false),\n m_active(false),\n m_update_rate(100),\n m_do_flush(false),\n m_do_reconnect(false) {}\n\nDispatcher::~Dispatcher() { Stop(); }\n\nvoid Dispatcher::StartServer(const char* listen_address, unsigned int port) {\n {\n std::lock_guard lock(m_user_mutex);\n if (m_active) return;\n m_active = true;\n }\n m_server = true;\n m_dispatch_thread = std::thread(&Dispatcher::DispatchThreadMain, this);\n m_clientserver_thread =\n std::thread(&Dispatcher::ServerThreadMain, this, listen_address, port);\n}\n\nvoid Dispatcher::StartClient(const char* server_name, unsigned int port) {\n {\n std::lock_guard lock(m_user_mutex);\n if (m_active) return;\n m_active = true;\n }\n m_server = false;\n m_dispatch_thread = std::thread(&Dispatcher::DispatchThreadMain, this);\n m_clientserver_thread =\n std::thread(&Dispatcher::ClientThreadMain, this, server_name, port);\n}\n\nvoid Dispatcher::Stop() {\n {\n std::lock_guard lock(m_user_mutex);\n m_active = false;\n\n \/\/ close all connections\n for (auto& conn : m_connections) conn.net->Stop();\n }\n\n \/\/ wake up dispatch thread with a flush\n m_flush_cv.notify_one();\n\n \/\/ wake up client thread with a reconnect\n ClientReconnect();\n\n \/\/ wake up server thread by shutting down the socket\n if (m_server_acceptor) m_server_acceptor->shutdown();\n\n \/\/ join threads\n if (m_dispatch_thread.joinable()) m_dispatch_thread.join();\n if (m_clientserver_thread.joinable()) m_clientserver_thread.join();\n}\n\nvoid Dispatcher::SetUpdateRate(double interval) {\n \/\/ don't allow update rates faster than 100 ms\n if (interval < 0.1)\n interval = 0.1;\n m_update_rate = interval * 1000;\n}\n\nvoid Dispatcher::SetIdentity(llvm::StringRef name) {\n std::lock_guard lock(m_user_mutex);\n m_identity = name;\n}\n\nvoid Dispatcher::Flush() {\n auto now = std::chrono::steady_clock::now();\n {\n std::lock_guard lock(m_flush_mutex);\n \/\/ don't allow flushes more often than every 100 ms\n if ((now - m_last_flush) < std::chrono::milliseconds(100))\n return;\n m_last_flush = now;\n m_do_flush = true;\n }\n m_flush_cv.notify_one();\n}\n\nvoid Dispatcher::DispatchThreadMain() {\n auto timeout_time = std::chrono::steady_clock::now();\n int count = 0;\n while (m_active) {\n \/\/ handle loop taking too long\n auto start = std::chrono::steady_clock::now();\n if (start > timeout_time)\n timeout_time = start;\n\n \/\/ wait for periodic or when flushed\n timeout_time += std::chrono::milliseconds(m_update_rate);\n std::unique_lock lock(m_flush_mutex);\n m_reconnect_cv.wait_until(lock, timeout_time,\n [&] { return !m_active || m_do_flush; });\n m_do_flush = false;\n lock.unlock();\n if (!m_active) break; \/\/ in case we were woken up to terminate\n\n if (++count > 10) {\n DEBUG(\"dispatch running\");\n count = 0;\n }\n }\n}\n\nvoid Dispatcher::ServerThreadMain(const char* listen_address,\n unsigned int port) {\n m_server_acceptor.reset(\n new TCPAcceptor(static_cast(port), listen_address));\n if (m_server_acceptor->start() != 0) {\n m_active = false;\n return;\n }\n while (m_active) {\n auto stream = m_server_acceptor->accept();\n if (!stream) {\n m_active = false;\n break;\n }\n DEBUG(\"server got a connection\");\n\n \/\/ add to connections list\n Connection conn;\n conn.net.reset(new NetworkConnection(std::move(stream), GetEntryType));\n conn.net->Start();\n AddConnection(std::move(conn));\n }\n}\n\nvoid Dispatcher::ClientThreadMain(const char* server_name, unsigned int port) {\n unsigned int proto_rev = 0x0300;\n while (m_active) {\n \/\/ get identity\n std::string self_id;\n {\n std::lock_guard lock(m_user_mutex);\n self_id = m_identity;\n }\n\n \/\/ sleep between retries\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n\n \/\/ try to connect (with timeout)\n DEBUG(\"client trying to connect\");\n auto stream = TCPConnector::connect(server_name, static_cast(port), 1);\n if (!stream) continue; \/\/ keep retrying\n DEBUG(\"client connected\");\n\n Connection conn;\n conn.net.reset(new NetworkConnection(std::move(stream), GetEntryType));\n conn.net->set_proto_rev(proto_rev);\n conn.net->Start();\n\n \/\/ send client hello\n DEBUG(\"client sending hello\");\n conn.net->outgoing().push(\n NetworkConnection::Outgoing{Message::ClientHello(self_id)});\n\n \/\/ wait for response\n auto msg = conn.net->incoming().pop();\n if (!msg) {\n \/\/ disconnected, retry\n DEBUG(\"client disconnected waiting for first response\");\n proto_rev = 0x0300;\n continue;\n }\n\n if (msg->Is(Message::kProtoUnsup)) {\n \/\/ reconnect with lower protocol (if possible)\n if (proto_rev <= 0x0200) {\n \/\/ no more options, abort (but keep trying to connect)\n proto_rev = 0x0300;\n continue;\n }\n proto_rev = 0x0200;\n continue;\n }\n\n if (proto_rev == 0x0300) {\n \/\/ should be server hello; if not, disconnect, but keep trying to connect\n if (!msg->Is(Message::kServerHello)) continue;\n conn.remote_id = msg->str();\n \/\/ get the next message (blocks)\n msg = conn.net->incoming().pop();\n }\n\n while (true) {\n if (!msg) {\n \/\/ disconnected, retry\n DEBUG(\"client disconnected waiting for initial entries\");\n proto_rev = 0x0300;\n continue;\n }\n if (msg->Is(Message::kServerHelloDone)) break;\n }\n\n \/\/ add to connections list (the dispatcher thread will handle from here)\n AddConnection(std::move(conn));\n\n \/\/ block until told to reconnect\n std::unique_lock lock(m_reconnect_mutex);\n m_reconnect_cv.wait(lock, [&] { return m_do_reconnect; });\n m_do_reconnect = false;\n lock.unlock();\n }\n}\n\nvoid Dispatcher::ClientReconnect() {\n if (m_server) return;\n {\n std::lock_guard lock(m_reconnect_mutex);\n m_do_reconnect = true;\n }\n m_reconnect_cv.notify_one();\n}\n\nvoid Dispatcher::AddConnection(Connection&& conn) {\n std::lock_guard lock(m_user_mutex);\n m_connections.push_back(std::move(conn));\n}\nContinue implementing client.\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2015. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"Dispatcher.h\"\n\n#include \"tcpsockets\/TCPAcceptor.h\"\n#include \"tcpsockets\/TCPConnector.h\"\n\nusing namespace nt;\n\n#define DEBUG(str) puts(str)\n\nstd::unique_ptr Dispatcher::m_instance;\n\nstatic NT_Type GetEntryType(unsigned int id) {\n \/\/ TODO\n return NT_UNASSIGNED;\n}\n\nDispatcher::Dispatcher()\n : m_server(false),\n m_active(false),\n m_update_rate(100),\n m_do_flush(false),\n m_do_reconnect(false) {}\n\nDispatcher::~Dispatcher() { Stop(); }\n\nvoid Dispatcher::StartServer(const char* listen_address, unsigned int port) {\n {\n std::lock_guard lock(m_user_mutex);\n if (m_active) return;\n m_active = true;\n }\n m_server = true;\n m_dispatch_thread = std::thread(&Dispatcher::DispatchThreadMain, this);\n m_clientserver_thread =\n std::thread(&Dispatcher::ServerThreadMain, this, listen_address, port);\n}\n\nvoid Dispatcher::StartClient(const char* server_name, unsigned int port) {\n {\n std::lock_guard lock(m_user_mutex);\n if (m_active) return;\n m_active = true;\n }\n m_server = false;\n m_dispatch_thread = std::thread(&Dispatcher::DispatchThreadMain, this);\n m_clientserver_thread =\n std::thread(&Dispatcher::ClientThreadMain, this, server_name, port);\n}\n\nvoid Dispatcher::Stop() {\n {\n std::lock_guard lock(m_user_mutex);\n m_active = false;\n\n \/\/ close all connections\n for (auto& conn : m_connections) conn.net->Stop();\n }\n\n \/\/ wake up dispatch thread with a flush\n m_flush_cv.notify_one();\n\n \/\/ wake up client thread with a reconnect\n ClientReconnect();\n\n \/\/ wake up server thread by shutting down the socket\n if (m_server_acceptor) m_server_acceptor->shutdown();\n\n \/\/ join threads\n if (m_dispatch_thread.joinable()) m_dispatch_thread.join();\n if (m_clientserver_thread.joinable()) m_clientserver_thread.join();\n}\n\nvoid Dispatcher::SetUpdateRate(double interval) {\n \/\/ don't allow update rates faster than 100 ms\n if (interval < 0.1)\n interval = 0.1;\n m_update_rate = interval * 1000;\n}\n\nvoid Dispatcher::SetIdentity(llvm::StringRef name) {\n std::lock_guard lock(m_user_mutex);\n m_identity = name;\n}\n\nvoid Dispatcher::Flush() {\n auto now = std::chrono::steady_clock::now();\n {\n std::lock_guard lock(m_flush_mutex);\n \/\/ don't allow flushes more often than every 100 ms\n if ((now - m_last_flush) < std::chrono::milliseconds(100))\n return;\n m_last_flush = now;\n m_do_flush = true;\n }\n m_flush_cv.notify_one();\n}\n\nvoid Dispatcher::DispatchThreadMain() {\n auto timeout_time = std::chrono::steady_clock::now();\n int count = 0;\n while (m_active) {\n \/\/ handle loop taking too long\n auto start = std::chrono::steady_clock::now();\n if (start > timeout_time)\n timeout_time = start;\n\n \/\/ wait for periodic or when flushed\n timeout_time += std::chrono::milliseconds(m_update_rate);\n std::unique_lock lock(m_flush_mutex);\n m_reconnect_cv.wait_until(lock, timeout_time,\n [&] { return !m_active || m_do_flush; });\n m_do_flush = false;\n lock.unlock();\n if (!m_active) break; \/\/ in case we were woken up to terminate\n\n if (++count > 10) {\n DEBUG(\"dispatch running\");\n count = 0;\n }\n }\n}\n\nvoid Dispatcher::ServerThreadMain(const char* listen_address,\n unsigned int port) {\n m_server_acceptor.reset(\n new TCPAcceptor(static_cast(port), listen_address));\n if (m_server_acceptor->start() != 0) {\n m_active = false;\n return;\n }\n while (m_active) {\n auto stream = m_server_acceptor->accept();\n if (!stream) {\n m_active = false;\n break;\n }\n DEBUG(\"server got a connection\");\n\n \/\/ add to connections list\n Connection conn;\n conn.net.reset(new NetworkConnection(std::move(stream), GetEntryType));\n conn.net->Start();\n AddConnection(std::move(conn));\n }\n}\n\nvoid Dispatcher::ClientThreadMain(const char* server_name, unsigned int port) {\n unsigned int proto_rev = 0x0300;\n while (m_active) {\n \/\/ get identity\n std::string self_id;\n {\n std::lock_guard lock(m_user_mutex);\n self_id = m_identity;\n }\n\n \/\/ sleep between retries\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n\n \/\/ try to connect (with timeout)\n DEBUG(\"client trying to connect\");\n auto stream = TCPConnector::connect(server_name, static_cast(port), 1);\n if (!stream) continue; \/\/ keep retrying\n DEBUG(\"client connected\");\n\n Connection conn;\n conn.net.reset(new NetworkConnection(std::move(stream), GetEntryType));\n conn.net->set_proto_rev(proto_rev);\n conn.net->Start();\n\n \/\/ send client hello\n DEBUG(\"client sending hello\");\n conn.net->outgoing().push(\n NetworkConnection::Outgoing{Message::ClientHello(self_id)});\n\n \/\/ wait for response\n auto msg = conn.net->incoming().pop();\n if (!msg) {\n \/\/ disconnected, retry\n DEBUG(\"client disconnected waiting for first response\");\n proto_rev = 0x0300;\n continue;\n }\n\n if (msg->Is(Message::kProtoUnsup)) {\n \/\/ reconnect with lower protocol (if possible)\n if (proto_rev <= 0x0200) {\n \/\/ no more options, abort (but keep trying to connect)\n proto_rev = 0x0300;\n continue;\n }\n proto_rev = 0x0200;\n continue;\n }\n\n if (proto_rev >= 0x0300) {\n \/\/ should be server hello; if not, disconnect, but keep trying to connect\n if (!msg->Is(Message::kServerHello)) continue;\n conn.remote_id = msg->str();\n \/\/ get the next message (blocks)\n msg = conn.net->incoming().pop();\n }\n\n \/\/ receive initial assignments\n std::vector> incoming;\n while (true) {\n if (!msg) {\n \/\/ disconnected, retry\n DEBUG(\"client disconnected waiting for initial entries\");\n proto_rev = 0x0300;\n continue;\n }\n if (msg->Is(Message::kServerHelloDone)) break;\n if (!msg->Is(Message::kEntryAssign)) {\n \/\/ unexpected message\n DEBUG(\"received message other than entry assignment during initial handshake\");\n proto_rev = 0x0300;\n continue;\n }\n incoming.push_back(msg);\n \/\/ get the next message (blocks)\n msg = conn.net->incoming().pop();\n }\n\n \/\/ generate outgoing assignments\n NetworkConnection::Outgoing outgoing;\n\n if (proto_rev >= 0x0300)\n outgoing.push_back(Message::ClientHelloDone());\n\n if (!outgoing.empty())\n conn.net->outgoing().push(std::move(outgoing));\n\n \/\/ add to connections list (the dispatcher thread will handle from here)\n AddConnection(std::move(conn));\n\n \/\/ block until told to reconnect\n std::unique_lock lock(m_reconnect_mutex);\n m_reconnect_cv.wait(lock, [&] { return m_do_reconnect; });\n m_do_reconnect = false;\n lock.unlock();\n }\n}\n\nvoid Dispatcher::ClientReconnect() {\n if (m_server) return;\n {\n std::lock_guard lock(m_reconnect_mutex);\n m_do_reconnect = true;\n }\n m_reconnect_cv.notify_one();\n}\n\nvoid Dispatcher::AddConnection(Connection&& conn) {\n std::lock_guard lock(m_user_mutex);\n m_connections.push_back(std::move(conn));\n}\n<|endoftext|>"} {"text":"#include \"Emscripten.h\"\n#include \"SDL.h\"\n#include \"Context.h\"\n#include \n\n\n\n#ifdef __EMSCRIPTEN__\n\nextern Context* _context;\n\n#include \n\nvoid emDeinit();\n\nextern \"C\" void emFilesSyncedShutdown()\n{\n\tSDL_Event event;\n\tevent.type = EVERYTHING_DONE;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emFilesSyncedStartup()\n{\n\tSDL_Event event;\n\tevent.type = EVERYTHING_READY;\n\tSDL_PushEvent(&event);\n}\n\nvoid emSyncFsAndStartup()\n{\n\tEM_ASM(\n\t\tconsole.log(\"Mounting filesystem\");\n\t\t\n\t\tFS.mkdir('\/persistent');\n\t\tFS.mkdir('\/imported');\n\t\tFS.mount(IDBFS, {}, '\/persistent');\n\t\t\n\t\tFS.syncfs(true, function(err) {\n assert(!err);\n\t\t\tconsole.log(\"Filesystem is loaded, starting up\");\n Module.ccall('emFilesSyncedStartup', 'v');\n\t\t});\n\t);\n}\n\n\nvoid emSyncFs()\n{\n\tEM_ASM(\n\t\tconsole.log(\"Syncing filesystem\");\n\t\t\n\t\tFS.syncfs(false, function(err) {\n assert(!err);\n\t\t\tconsole.log(\"Filesystem synced\");\n\t\t});\n\t);\n}\n\n\nvoid emSyncFsAndShutdown()\n{\n\tEM_ASM(\n\t\tconsole.log(\"Saving filesystem\");\n\t\tFS.syncfs(function(err) {\n assert(!err);\n\t\t\tconsole.log(\"Filesystem is saved, shutting down\");\n Module.ccall('emFilesSyncedShutdown', 'v');\n\t\t});\n\t);\n}\n\n\nconst char * emOnBeforeUnload(int eventType, const void *reserved, void *userData)\n{\n\treturn \"\";\n}\n\n\nextern \"C\" void emOnFileImported()\n{\n\tSDL_Event event;\n\tevent.type = SONG_IMPORTED;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emExportFile()\n{\n\tSDL_Event event;\n\tevent.type = EXPORT_SONG;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emPlaySong()\n{\n\tSDL_Event event;\n\tevent.type = PLAY_SONG;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emNewSong()\n{\n\tSDL_Event event;\n\tevent.type = NEW_SONG;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" const char * emRequestSong()\n{\n\treturn _context->mainEditor.getSongBase64().c_str();\n}\n\t\n\t\nextern \"C\" void emAppReady()\n{\n\temscripten_run_script(\"appReady();\");\n}\n\n#else\n\t\nvoid emSyncFsAndShutdown() {}\nvoid emSyncFsAndStartup() {}\n\n#endif\n\n\n\nHTML5 version should run appReady() only if it is defined#include \"Emscripten.h\"\n#include \"SDL.h\"\n#include \"Context.h\"\n#include \n\n\n\n#ifdef __EMSCRIPTEN__\n\nextern Context* _context;\n\n#include \n\nvoid emDeinit();\n\nextern \"C\" void emFilesSyncedShutdown()\n{\n\tSDL_Event event;\n\tevent.type = EVERYTHING_DONE;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emFilesSyncedStartup()\n{\n\tSDL_Event event;\n\tevent.type = EVERYTHING_READY;\n\tSDL_PushEvent(&event);\n}\n\nvoid emSyncFsAndStartup()\n{\n\tEM_ASM(\n\t\tconsole.log(\"Mounting filesystem\");\n\t\t\n\t\tFS.mkdir('\/persistent');\n\t\tFS.mkdir('\/imported');\n\t\tFS.mount(IDBFS, {}, '\/persistent');\n\t\t\n\t\tFS.syncfs(true, function(err) {\n assert(!err);\n\t\t\tconsole.log(\"Filesystem is loaded, starting up\");\n Module.ccall('emFilesSyncedStartup', 'v');\n\t\t});\n\t);\n}\n\n\nvoid emSyncFs()\n{\n\tEM_ASM(\n\t\tconsole.log(\"Syncing filesystem\");\n\t\t\n\t\tFS.syncfs(false, function(err) {\n assert(!err);\n\t\t\tconsole.log(\"Filesystem synced\");\n\t\t});\n\t);\n}\n\n\nvoid emSyncFsAndShutdown()\n{\n\tEM_ASM(\n\t\tconsole.log(\"Saving filesystem\");\n\t\tFS.syncfs(function(err) {\n assert(!err);\n\t\t\tconsole.log(\"Filesystem is saved, shutting down\");\n Module.ccall('emFilesSyncedShutdown', 'v');\n\t\t});\n\t);\n}\n\n\nconst char * emOnBeforeUnload(int eventType, const void *reserved, void *userData)\n{\n\treturn \"\";\n}\n\n\nextern \"C\" void emOnFileImported()\n{\n\tSDL_Event event;\n\tevent.type = SONG_IMPORTED;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emExportFile()\n{\n\tSDL_Event event;\n\tevent.type = EXPORT_SONG;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emPlaySong()\n{\n\tSDL_Event event;\n\tevent.type = PLAY_SONG;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" void emNewSong()\n{\n\tSDL_Event event;\n\tevent.type = NEW_SONG;\n\tSDL_PushEvent(&event);\n}\n\n\nextern \"C\" const char * emRequestSong()\n{\n\treturn _context->mainEditor.getSongBase64().c_str();\n}\n\t\n\t\nextern \"C\" void emAppReady()\n{\n\temscripten_run_script(\"if (typeof appReady === \\\"function\\\") appReady();\");\n}\n\n#else\n\t\nvoid emSyncFsAndShutdown() {}\nvoid emSyncFsAndStartup() {}\n\n#endif\n\n\n\n<|endoftext|>"} {"text":"#include \"Game\/Clock.h\"\n\n#include \n#include \nusing namespace std::chrono_literals;\n#include \n#include \n\n#include \"Game\/Game_Result.h\"\n\nClock::Clock(double duration_seconds,\n size_t moves_to_reset,\n double increment_seconds,\n Color starting_turn,\n std::chrono::system_clock::time_point previous_start_time) noexcept :\n timers({fractional_seconds(duration_seconds), fractional_seconds(duration_seconds)}),\n initial_start_time(Clock::fractional_seconds(duration_seconds)),\n increment_time({Clock::fractional_seconds(increment_seconds), Clock::fractional_seconds(increment_seconds)}),\n move_count_reset(moves_to_reset),\n whose_turn(starting_turn),\n game_start_date_time(previous_start_time)\n{\n assert(whose_turn != NONE);\n}\n\nGame_Result Clock::punch() noexcept\n{\n assert(clocks_running);\n\n auto time_this_punch = std::chrono::steady_clock::now();\n whose_turn = opposite(whose_turn);\n\n if( ! is_in_use())\n {\n return {};\n }\n\n timers[whose_turn] -= (time_this_punch - time_previous_punch);\n\n if(++moves_to_reset_clocks[whose_turn] == move_count_reset)\n {\n timers[whose_turn] += initial_start_time;\n moves_to_reset_clocks[whose_turn] = 0;\n }\n\n time_previous_punch = time_this_punch;\n timers[whose_turn] += increment_time[whose_turn];\n\n if(timers[whose_turn] < 0s)\n {\n return Game_Result(opposite(whose_turn), Game_Result_Type::TIME_FORFEIT);\n }\n else\n {\n return {};\n }\n}\n\nvoid Clock::unpunch() noexcept\n{\n moves_to_reset_clocks[whose_turn] -= 1;\n moves_to_reset_clocks[opposite(whose_turn)] -= 1;\n punch();\n}\n\nvoid Clock::stop() noexcept\n{\n auto time_stop = std::chrono::steady_clock::now();\n timers[whose_turn] -= (time_stop - time_previous_punch);\n clocks_running = false;\n}\n\nvoid Clock::start() noexcept\n{\n static const auto default_game_start_date_time = std::chrono::system_clock::time_point{};\n time_previous_punch = std::chrono::steady_clock::now();\n if(game_start_date_time == default_game_start_date_time)\n {\n game_start_date_time = std::chrono::system_clock::now();\n }\n clocks_running = true;\n}\n\ndouble Clock::time_left(Color color) const noexcept\n{\n if( ! is_in_use())\n {\n return 0.0;\n }\n\n if(whose_turn != color || ! clocks_running)\n {\n return timers[color].count();\n }\n else\n {\n auto now = std::chrono::steady_clock::now();\n return fractional_seconds(timers[color] - (now - time_previous_punch)).count();\n }\n}\n\nsize_t Clock::moves_until_reset(Color color) const noexcept\n{\n if(move_count_reset > 0)\n {\n return move_count_reset - moves_to_reset_clocks[color];\n }\n else\n {\n return std::numeric_limits::max();\n }\n}\n\nColor Clock::running_for() const noexcept\n{\n return whose_turn;\n}\n\nvoid Clock::set_time(Color player, double new_time_seconds) noexcept\n{\n timers[player] = fractional_seconds(new_time_seconds);\n initial_start_time = fractional_seconds(std::max(new_time_seconds, initial_start_time.count()));\n time_previous_punch = std::chrono::steady_clock::now();\n}\n\nvoid Clock::set_increment(Color player, double new_increment_time_seconds) noexcept\n{\n increment_time[player] = fractional_seconds(new_increment_time_seconds);\n}\n\nvoid Clock::set_next_time_reset(size_t moves_to_reset) noexcept\n{\n move_count_reset = moves_to_reset_clocks[running_for()] + moves_to_reset;\n}\n\ndouble Clock::running_time_left() const noexcept\n{\n return time_left(running_for());\n}\n\nbool Clock::is_running() const noexcept\n{\n return clocks_running;\n}\n\nstd::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept\n{\n return game_start_date_time;\n}\n\nsize_t Clock::moves_per_time_period() const noexcept\n{\n return move_count_reset;\n}\n\ndouble Clock::initial_time() const noexcept\n{\n return initial_start_time.count();\n}\n\ndouble Clock::increment(Color color) const noexcept\n{\n return increment_time[color].count();\n}\n\nbool Clock::is_in_use() const noexcept\n{\n return initial_start_time > 0s;\n}\nPut whose_turn switch in punch() back where it was#include \"Game\/Clock.h\"\n\n#include \n#include \nusing namespace std::chrono_literals;\n#include \n#include \n\n#include \"Game\/Game_Result.h\"\n\nClock::Clock(double duration_seconds,\n size_t moves_to_reset,\n double increment_seconds,\n Color starting_turn,\n std::chrono::system_clock::time_point previous_start_time) noexcept :\n timers({fractional_seconds(duration_seconds), fractional_seconds(duration_seconds)}),\n initial_start_time(Clock::fractional_seconds(duration_seconds)),\n increment_time({Clock::fractional_seconds(increment_seconds), Clock::fractional_seconds(increment_seconds)}),\n move_count_reset(moves_to_reset),\n whose_turn(starting_turn),\n game_start_date_time(previous_start_time)\n{\n assert(whose_turn != NONE);\n}\n\nGame_Result Clock::punch() noexcept\n{\n assert(clocks_running);\n\n auto time_this_punch = std::chrono::steady_clock::now();\n\n timers[whose_turn] -= (time_this_punch - time_previous_punch);\n\n if(++moves_to_reset_clocks[whose_turn] == move_count_reset)\n {\n timers[whose_turn] += initial_start_time;\n moves_to_reset_clocks[whose_turn] = 0;\n }\n\n time_previous_punch = time_this_punch;\n timers[whose_turn] += increment_time[whose_turn];\n\n whose_turn = opposite(whose_turn);\n\n if(timers[opposite(whose_turn)] < 0s)\n {\n return Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT);\n }\n else\n {\n return {};\n }\n}\n\nvoid Clock::unpunch() noexcept\n{\n moves_to_reset_clocks[whose_turn] -= 1;\n moves_to_reset_clocks[opposite(whose_turn)] -= 1;\n punch();\n}\n\nvoid Clock::stop() noexcept\n{\n auto time_stop = std::chrono::steady_clock::now();\n timers[whose_turn] -= (time_stop - time_previous_punch);\n clocks_running = false;\n}\n\nvoid Clock::start() noexcept\n{\n static const auto default_game_start_date_time = std::chrono::system_clock::time_point{};\n time_previous_punch = std::chrono::steady_clock::now();\n if(game_start_date_time == default_game_start_date_time)\n {\n game_start_date_time = std::chrono::system_clock::now();\n }\n clocks_running = true;\n}\n\ndouble Clock::time_left(Color color) const noexcept\n{\n if( ! is_in_use())\n {\n return 0.0;\n }\n\n if(whose_turn != color || ! clocks_running)\n {\n return timers[color].count();\n }\n else\n {\n auto now = std::chrono::steady_clock::now();\n return fractional_seconds(timers[color] - (now - time_previous_punch)).count();\n }\n}\n\nsize_t Clock::moves_until_reset(Color color) const noexcept\n{\n if(move_count_reset > 0)\n {\n return move_count_reset - moves_to_reset_clocks[color];\n }\n else\n {\n return std::numeric_limits::max();\n }\n}\n\nColor Clock::running_for() const noexcept\n{\n return whose_turn;\n}\n\nvoid Clock::set_time(Color player, double new_time_seconds) noexcept\n{\n timers[player] = fractional_seconds(new_time_seconds);\n initial_start_time = fractional_seconds(std::max(new_time_seconds, initial_start_time.count()));\n time_previous_punch = std::chrono::steady_clock::now();\n}\n\nvoid Clock::set_increment(Color player, double new_increment_time_seconds) noexcept\n{\n increment_time[player] = fractional_seconds(new_increment_time_seconds);\n}\n\nvoid Clock::set_next_time_reset(size_t moves_to_reset) noexcept\n{\n move_count_reset = moves_to_reset_clocks[running_for()] + moves_to_reset;\n}\n\ndouble Clock::running_time_left() const noexcept\n{\n return time_left(running_for());\n}\n\nbool Clock::is_running() const noexcept\n{\n return clocks_running;\n}\n\nstd::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept\n{\n return game_start_date_time;\n}\n\nsize_t Clock::moves_per_time_period() const noexcept\n{\n return move_count_reset;\n}\n\ndouble Clock::initial_time() const noexcept\n{\n return initial_start_time.count();\n}\n\ndouble Clock::increment(Color color) const noexcept\n{\n return increment_time[color].count();\n}\n\nbool Clock::is_in_use() const noexcept\n{\n return initial_start_time > 0s;\n}\n<|endoftext|>"} {"text":"#include \"Game\/Piece.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Game\/Board.h\"\n#include \"Game\/Piece_Types.h\"\n\n#include \"Moves\/Move.h\"\n#include \"Moves\/Direction.h\"\n#include \"Moves\/Pawn_Move.h\"\n#include \"Moves\/Pawn_Capture.h\"\n#include \"Moves\/Pawn_Double_Move.h\"\n#include \"Moves\/Pawn_Promotion.h\"\n#include \"Moves\/Pawn_Promotion_by_Capture.h\"\n#include \"Moves\/En_Passant.h\"\n#include \"Moves\/Castle.h\"\n\n#include \"Utility\/String.h\"\n\nint Piece::maximum_piece_height = 0;\n\n\/\/! Create a piece.\n\n\/\/! \\param color_in The color of the piece.\n\/\/! \\param type_in The type of piece.\nPiece::Piece(Color color_in, Piece_Type type_in) :\n my_color(color_in),\n my_type(type_in)\n{\n switch(type())\n {\n case PAWN:\n add_pawn_moves();\n add_pawn_art();\n break;\n case ROOK:\n add_rook_moves();\n add_rook_art();\n break;\n case KNIGHT:\n add_knight_moves();\n add_knight_art();\n break;\n case BISHOP:\n add_bishop_moves();\n add_bishop_art();\n break;\n case QUEEN:\n add_bishop_moves();\n add_rook_moves();\n add_queen_art();\n break;\n case KING:\n add_king_moves();\n add_king_art();\n break;\n default:\n throw std::invalid_argument(\"Program bug: Invalid piece type in Piece(): \" + std::to_string(type()));\n }\n}\n\n\/\/! Return a row of the ASCII art representation of the piece.\n\n\/\/! \\param row Which row of the square to return, with 0 being the top.\n\/\/! If the height is above or below the piece's picture, then an\n\/\/! empty string is returned.\n\/\/! \\param square_height The height of the square in characters.\n\/\/! \\returns One row of text that forms a picture of the piece.\n\/\/! \\throws Debug assert fail if the square height is smaller than the piece height.\n\/\/!\n\/\/! Piece design by VK (?) and taken from http:\/\/ascii.co.uk\/art\/chess.\nstd::string Piece::ascii_art(int row, int square_height) const\n{\n assert(square_height >= maximum_piece_height);\n\n int empty_bottom_rows = (square_height - maximum_piece_height)\/2;\n int empty_top_rows = square_height - int(ascii_art_lines.size()) - empty_bottom_rows;\n int line = row - empty_top_rows;\n if(0 <= line && line < int(ascii_art_lines.size()))\n {\n return ascii_art_lines[line];\n }\n return {};\n}\n\n\/\/! The color of the piece.\n\n\/\/! \\returns The Color of the player that controls the piece.\nColor Piece::color() const\n{\n return my_color;\n}\n\n\/\/! Get the PGN symbol for the piece.\n\n\/\/! \\returns The symbol for the moving piece when writing a game record. A pawn is represented by an empty string.\nstd::string Piece::pgn_symbol() const\n{\n return type() == PAWN ? std::string{} : std::string(1, std::toupper(fen_symbol()));\n}\n\n\/\/ Get the piece symbol when writing an FEN string.\n\n\/\/! \\returns A single character symbol for the piece. Uppercase is white, lowercase is black.\nchar Piece::fen_symbol() const\n{\n static auto symbols = \"PRNBQK\";\n auto symbol = symbols[type()];\n return (my_color == WHITE ? symbol : std::tolower(symbol));\n}\n\n\/\/! Check that a piece is allowed to make a certain move.\n\n\/\/! \\param move A pointer to a prospective move.\n\/\/! \\returns Whether or not the piece is allowed to move in the manner described by the parameter.\nbool Piece::can_move(const Move* move) const\n{\n return std::find_if(possible_moves.begin(),\n possible_moves.end(),\n [move](const auto& x){ return x.get() == move; }) != possible_moves.end();\n}\n\n\/\/! Get all possibly legal moves of a piece starting from a given square.\n\n\/\/! \\param file The file of the starting square.\n\/\/! \\param rank The rank of the starting square.\n\/\/! \\returns A list of legal moves starting from that square.\nconst std::vector& Piece::move_list(char file, int rank) const\n{\n return legal_moves[Board::square_index(file, rank)];\n}\n\n\/\/! Get the type of the piece.\n\n\/\/! \\returns The kind of piece, i.e., PAWN, ROOK, etc.\nPiece_Type Piece::type() const\n{\n return my_type;\n}\n\nvoid Piece::add_standard_legal_move(int file_step, int rank_step)\n{\n for(char start_file = 'a'; start_file <= 'h'; ++start_file)\n {\n for(int start_rank = 1; start_rank <= 8; ++start_rank)\n {\n char end_file = start_file + file_step;\n int end_rank = start_rank + rank_step;\n\n if(Board::inside_board(end_file, end_rank))\n {\n add_legal_move(start_file, start_rank,\n end_file, end_rank);\n }\n }\n }\n}\n\nvoid Piece::add_pawn_moves()\n{\n auto base_rank = (color() == WHITE ? 2 : 7);\n auto no_normal_move_rank = (color() == WHITE ? 7 : 2);\n auto direction = (color() == WHITE ? 1 : -1);\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += direction)\n {\n add_legal_move(color(), file, rank);\n }\n }\n\n for(char file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move(color(), file);\n }\n\n auto possible_promotions = {QUEEN, KNIGHT, ROOK, BISHOP};\n\n for(auto dir : {RIGHT, LEFT})\n {\n auto first_file = (dir == RIGHT ? 'a' : 'b');\n auto last_file = (dir == RIGHT ? 'g' : 'h');\n for(char file = first_file; file <= last_file; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += direction)\n {\n add_legal_move(color(), dir, file, rank);\n }\n }\n\n for(char file = first_file; file <= last_file; ++file)\n {\n add_legal_move(color(), dir, file);\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = first_file; file <= last_file; ++file)\n {\n add_legal_move(promote, color(), dir, file);\n }\n }\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move(promote, color(), file);\n }\n }\n}\n\nvoid Piece::add_rook_moves()\n{\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n if(d_file == 0 && d_rank == 0) { continue; }\n if(d_file != 0 && d_rank != 0) { continue; }\n\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(move_size*d_file, move_size*d_rank);\n }\n }\n }\n}\n\nvoid Piece::add_knight_moves()\n{\n for(auto d_file : {1, 2})\n {\n auto d_rank = 3 - d_file;\n for(auto file_direction : {-1, 1})\n {\n for(auto rank_direction : {-1, 1})\n {\n add_standard_legal_move(d_file*file_direction, d_rank*rank_direction);\n }\n }\n }\n}\n\nvoid Piece::add_bishop_moves()\n{\n for(int d_rank : {-1, 1})\n {\n for(int d_file : {-1, 1})\n {\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(move_size*d_file, move_size*d_rank);\n }\n }\n }\n}\n\nvoid Piece::add_king_moves()\n{\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n if(d_rank == 0 && d_file == 0) { continue; }\n\n add_standard_legal_move(d_file, d_rank);\n }\n }\n\n int base_rank = (color() == WHITE ? 1 : 8);\n add_legal_move(base_rank, LEFT);\n add_legal_move(base_rank, RIGHT);\n}\n\nvoid Piece::add_pawn_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"( )\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_rook_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"|U|\");\n ascii_art_lines.push_back(\"| |\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_knight_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"\/\\\")\");\n ascii_art_lines.push_back(\"7 (\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_bishop_art()\n{\n \/\/ ASCII art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"(V)\");\n ascii_art_lines.push_back(\") (\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_queen_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"\\\\^\/\");\n ascii_art_lines.push_back(\") (\");\n ascii_art_lines.push_back(\"(___)\");\n add_color();\n}\n\nvoid Piece::add_king_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"\\\\+\/\");\n ascii_art_lines.push_back(\"| |\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_color()\n{\n maximum_piece_height = std::max(maximum_piece_height, int(ascii_art_lines.size()));\n\n if(color() == WHITE)\n {\n return;\n }\n\n for(auto& line : ascii_art_lines)\n {\n for(auto& c : line)\n {\n if(c == ' ' || c == '_')\n {\n c = '#';\n }\n }\n }\n}\n\n\/\/! Gives a list of moves that are allowed to capture other pieces.\n\n\/\/! \\param file The file of the square where the attacking move starts.\n\/\/! \\param rank The rank of the square where the attacking move starts.\nconst std::vector& Piece::attacking_moves(char file, int rank) const\n{\n return attack_moves[Board::square_index(file, rank)];\n}\nSimpler Piece::can_move()#include \"Game\/Piece.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Game\/Board.h\"\n#include \"Game\/Piece_Types.h\"\n\n#include \"Moves\/Move.h\"\n#include \"Moves\/Direction.h\"\n#include \"Moves\/Pawn_Move.h\"\n#include \"Moves\/Pawn_Capture.h\"\n#include \"Moves\/Pawn_Double_Move.h\"\n#include \"Moves\/Pawn_Promotion.h\"\n#include \"Moves\/Pawn_Promotion_by_Capture.h\"\n#include \"Moves\/En_Passant.h\"\n#include \"Moves\/Castle.h\"\n\n#include \"Utility\/String.h\"\n\nint Piece::maximum_piece_height = 0;\n\n\/\/! Create a piece.\n\n\/\/! \\param color_in The color of the piece.\n\/\/! \\param type_in The type of piece.\nPiece::Piece(Color color_in, Piece_Type type_in) :\n my_color(color_in),\n my_type(type_in)\n{\n switch(type())\n {\n case PAWN:\n add_pawn_moves();\n add_pawn_art();\n break;\n case ROOK:\n add_rook_moves();\n add_rook_art();\n break;\n case KNIGHT:\n add_knight_moves();\n add_knight_art();\n break;\n case BISHOP:\n add_bishop_moves();\n add_bishop_art();\n break;\n case QUEEN:\n add_bishop_moves();\n add_rook_moves();\n add_queen_art();\n break;\n case KING:\n add_king_moves();\n add_king_art();\n break;\n default:\n throw std::invalid_argument(\"Program bug: Invalid piece type in Piece(): \" + std::to_string(type()));\n }\n}\n\n\/\/! Return a row of the ASCII art representation of the piece.\n\n\/\/! \\param row Which row of the square to return, with 0 being the top.\n\/\/! If the height is above or below the piece's picture, then an\n\/\/! empty string is returned.\n\/\/! \\param square_height The height of the square in characters.\n\/\/! \\returns One row of text that forms a picture of the piece.\n\/\/! \\throws Debug assert fail if the square height is smaller than the piece height.\n\/\/!\n\/\/! Piece design by VK (?) and taken from http:\/\/ascii.co.uk\/art\/chess.\nstd::string Piece::ascii_art(int row, int square_height) const\n{\n assert(square_height >= maximum_piece_height);\n\n int empty_bottom_rows = (square_height - maximum_piece_height)\/2;\n int empty_top_rows = square_height - int(ascii_art_lines.size()) - empty_bottom_rows;\n int line = row - empty_top_rows;\n if(0 <= line && line < int(ascii_art_lines.size()))\n {\n return ascii_art_lines[line];\n }\n return {};\n}\n\n\/\/! The color of the piece.\n\n\/\/! \\returns The Color of the player that controls the piece.\nColor Piece::color() const\n{\n return my_color;\n}\n\n\/\/! Get the PGN symbol for the piece.\n\n\/\/! \\returns The symbol for the moving piece when writing a game record. A pawn is represented by an empty string.\nstd::string Piece::pgn_symbol() const\n{\n return type() == PAWN ? std::string{} : std::string(1, std::toupper(fen_symbol()));\n}\n\n\/\/ Get the piece symbol when writing an FEN string.\n\n\/\/! \\returns A single character symbol for the piece. Uppercase is white, lowercase is black.\nchar Piece::fen_symbol() const\n{\n static auto symbols = \"PRNBQK\";\n auto symbol = symbols[type()];\n return (my_color == WHITE ? symbol : std::tolower(symbol));\n}\n\n\/\/! Check that a piece is allowed to make a certain move.\n\n\/\/! \\param move A pointer to a prospective move.\n\/\/! \\returns Whether or not the piece is allowed to move in the manner described by the parameter.\nbool Piece::can_move(const Move* move) const\n{\n const auto& moves = move_list(move->start_file(), move->start_rank());\n return std::find(moves.begin(), moves.end(), move) != moves.end();\n}\n\n\/\/! Get all possibly legal moves of a piece starting from a given square.\n\n\/\/! \\param file The file of the starting square.\n\/\/! \\param rank The rank of the starting square.\n\/\/! \\returns A list of legal moves starting from that square.\nconst std::vector& Piece::move_list(char file, int rank) const\n{\n return legal_moves[Board::square_index(file, rank)];\n}\n\n\/\/! Get the type of the piece.\n\n\/\/! \\returns The kind of piece, i.e., PAWN, ROOK, etc.\nPiece_Type Piece::type() const\n{\n return my_type;\n}\n\nvoid Piece::add_standard_legal_move(int file_step, int rank_step)\n{\n for(char start_file = 'a'; start_file <= 'h'; ++start_file)\n {\n for(int start_rank = 1; start_rank <= 8; ++start_rank)\n {\n char end_file = start_file + file_step;\n int end_rank = start_rank + rank_step;\n\n if(Board::inside_board(end_file, end_rank))\n {\n add_legal_move(start_file, start_rank,\n end_file, end_rank);\n }\n }\n }\n}\n\nvoid Piece::add_pawn_moves()\n{\n auto base_rank = (color() == WHITE ? 2 : 7);\n auto no_normal_move_rank = (color() == WHITE ? 7 : 2);\n auto direction = (color() == WHITE ? 1 : -1);\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += direction)\n {\n add_legal_move(color(), file, rank);\n }\n }\n\n for(char file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move(color(), file);\n }\n\n auto possible_promotions = {QUEEN, KNIGHT, ROOK, BISHOP};\n\n for(auto dir : {RIGHT, LEFT})\n {\n auto first_file = (dir == RIGHT ? 'a' : 'b');\n auto last_file = (dir == RIGHT ? 'g' : 'h');\n for(char file = first_file; file <= last_file; ++file)\n {\n for(int rank = base_rank; rank != no_normal_move_rank; rank += direction)\n {\n add_legal_move(color(), dir, file, rank);\n }\n }\n\n for(char file = first_file; file <= last_file; ++file)\n {\n add_legal_move(color(), dir, file);\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = first_file; file <= last_file; ++file)\n {\n add_legal_move(promote, color(), dir, file);\n }\n }\n }\n\n for(auto promote : possible_promotions)\n {\n for(auto file = 'a'; file <= 'h'; ++file)\n {\n add_legal_move(promote, color(), file);\n }\n }\n}\n\nvoid Piece::add_rook_moves()\n{\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n if(d_file == 0 && d_rank == 0) { continue; }\n if(d_file != 0 && d_rank != 0) { continue; }\n\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(move_size*d_file, move_size*d_rank);\n }\n }\n }\n}\n\nvoid Piece::add_knight_moves()\n{\n for(auto d_file : {1, 2})\n {\n auto d_rank = 3 - d_file;\n for(auto file_direction : {-1, 1})\n {\n for(auto rank_direction : {-1, 1})\n {\n add_standard_legal_move(d_file*file_direction, d_rank*rank_direction);\n }\n }\n }\n}\n\nvoid Piece::add_bishop_moves()\n{\n for(int d_rank : {-1, 1})\n {\n for(int d_file : {-1, 1})\n {\n for(int move_size = 1; move_size <= 7; ++move_size)\n {\n add_standard_legal_move(move_size*d_file, move_size*d_rank);\n }\n }\n }\n}\n\nvoid Piece::add_king_moves()\n{\n for(int d_rank = -1; d_rank <= 1; ++d_rank)\n {\n for(int d_file = -1; d_file <= 1; ++d_file)\n {\n if(d_rank == 0 && d_file == 0) { continue; }\n\n add_standard_legal_move(d_file, d_rank);\n }\n }\n\n int base_rank = (color() == WHITE ? 1 : 8);\n add_legal_move(base_rank, LEFT);\n add_legal_move(base_rank, RIGHT);\n}\n\nvoid Piece::add_pawn_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"( )\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_rook_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"|U|\");\n ascii_art_lines.push_back(\"| |\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_knight_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"\/\\\")\");\n ascii_art_lines.push_back(\"7 (\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_bishop_art()\n{\n \/\/ ASCII art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"(V)\");\n ascii_art_lines.push_back(\") (\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_queen_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"\\\\^\/\");\n ascii_art_lines.push_back(\") (\");\n ascii_art_lines.push_back(\"(___)\");\n add_color();\n}\n\nvoid Piece::add_king_art()\n{\n \/\/ ASCII Art http:\/\/ascii.co.uk\/art\/chess (VK)\n ascii_art_lines.push_back(\"\\\\+\/\");\n ascii_art_lines.push_back(\"| |\");\n ascii_art_lines.push_back(\"\/___\\\\\");\n add_color();\n}\n\nvoid Piece::add_color()\n{\n maximum_piece_height = std::max(maximum_piece_height, int(ascii_art_lines.size()));\n\n if(color() == WHITE)\n {\n return;\n }\n\n for(auto& line : ascii_art_lines)\n {\n for(auto& c : line)\n {\n if(c == ' ' || c == '_')\n {\n c = '#';\n }\n }\n }\n}\n\n\/\/! Gives a list of moves that are allowed to capture other pieces.\n\n\/\/! \\param file The file of the square where the attacking move starts.\n\/\/! \\param rank The rank of the square where the attacking move starts.\nconst std::vector& Piece::attacking_moves(char file, int rank) const\n{\n return attack_moves[Board::square_index(file, rank)];\n}\n<|endoftext|>"} {"text":"#include \"Image.h\"\n\n#include \"..\/File\/File.h\"\n\n#include \"Color.h\"\n#include \n#include \n\n#define PNGSIGSIZE 8\n\nstatic void pngReadData(png_structp pngPointer, png_bytep data, png_size_t length)\n{\n char** fileData = (char**)png_get_io_ptr(pngPointer);\n memcpy(data, *fileData, length);\n *fileData += length;\n}\n\n\/*bool Jatta::Png::isValid(const char* buffer, unsigned int length)\n{\n return png_sig_cmp((png_bytep)buffer, 0, PNGSIGSIZE) == 0;\n}\n\nbool Jatta::Png::isValid(const std::string& fileName)\n{\n \/\/ TODO: clean this up \/ check for errors\n unsigned int size;\n File::getFileSize(fileName, &size);\n char* buffer = new char[size];\n File::getData(fileName, buffer, size);\n bool valid = isValid(buffer, size); \n delete[] buffer;\n return valid;\n}*\/\n\nbool Jatta::Image::loadPng(const std::string& fileName)\n{\n unsigned int size;\n File::getFileSize(fileName, &size);\n char* buffer = new char[size];\n File::getData(fileName, buffer, size);\n\n \/\/if (!isValid(buffer, size))\n \/\/{\n \/\/return false;\n \/\/}\n\n \/\/Here we create the png read struct. The 3 NULL's at the end can be used\n \/\/for your own custom error handling functions, but we'll just use the default.\n \/\/if the function fails, NULL is returned. Always check the return values!\n png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (!pngPtr) {\n std::cerr << \"ERROR: Couldn't initialize png read struct\" << std::endl;\n return false; \/\/Do your own error recovery\/handling here\n }\n\n \/\/Here we create the png info struct.\n \/\/Note that this time, if this function fails, we have to clean up the read struct!\n png_infop infoPtr = png_create_info_struct(pngPtr);\n if (!infoPtr) {\n std::cerr << \"ERROR: Couldn't initialize png info struct\" << std::endl;\n png_destroy_read_struct(&pngPtr, (png_infopp)0, (png_infopp)0);\n return false; \/\/Do your own error recovery\/handling here\n }\n\n \/\/Here I've defined 2 pointers up front, so I can use them in error handling.\n \/\/I will explain these 2 later. Just making sure these get deleted on error.\n png_bytep* rowPtrs = NULL;\n char* data = NULL;\n\n if (setjmp(png_jmpbuf(pngPtr))) {\n \/\/An error occured, so clean up what we have allocated so far...\n png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0);\n if (rowPtrs != NULL) delete [] rowPtrs;\n if (data != NULL) delete [] data;\n\n std::cout << \"ERROR: An error occured while reading the PNG file\\n\";\n\n \/\/Make sure you return here. libPNG will jump to here if something\n \/\/goes wrong, and if you continue with your normal code, you might\n \/\/End up with an infinite loop.\n return false; \/\/ Do your own error handling here.\n }\n\n buffer += 8;\n png_set_read_fn(pngPtr, (png_voidp)&buffer, pngReadData);\n\n \/\/Set the amount signature bytes we've already read:\n \/\/We've defined PNGSIGSIZE as 8;\n png_set_sig_bytes(pngPtr, PNGSIGSIZE);\n\n \/\/Now call png_read_info with our pngPtr as image handle, and infoPtr to receive the file info.\n png_read_info(pngPtr, infoPtr);\n\n\n png_uint_32 imgWidth = png_get_image_width(pngPtr, infoPtr);\n png_uint_32 imgHeight = png_get_image_height(pngPtr, infoPtr);\n\n \/\/bits per CHANNEL! note: not per pixel!\n png_uint_32 bitdepth = png_get_bit_depth(pngPtr, infoPtr);\n \/\/Number of channels\n png_uint_32 channels = png_get_channels(pngPtr, infoPtr);\n \/\/Color type. (RGB, RGBA, Luminance, luminance alpha... palette... etc)\n png_uint_32 color_type = png_get_color_type(pngPtr, infoPtr);\n\n width = imgWidth;\n height = imgHeight;\n\n std::cout << imgWidth << \"x\" << imgHeight << std::endl;\n std::cout << \"Bit Depth: \" << bitdepth << std::endl;\n std::cout << \"Channels: \" << channels << std::endl;\n std::cout << \"Color Type: \" << color_type << std::endl;\n\n png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * imgHeight);\n for (int y = 0; y < imgHeight; y++)\n {\n row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr,infoPtr));\n }\n\n delete[] buffer;\n\n png_read_image(pngPtr, row_pointers);\n\n if (png_get_color_type(pngPtr, infoPtr) == PNG_COLOR_TYPE_RGB)\n {\n colors = (Color*)new char[imgHeight * imgWidth * sizeof(Color)];\n\n for (int y=0; yGhetto fixed something. Will properly fix later.#include \"Image.h\"\n\n#include \"..\/File\/File.h\"\n\n#include \"Color.h\"\n#include \n#include \n\n#define PNGSIGSIZE 8\n\nstatic void pngReadData(png_structp pngPointer, png_bytep data, png_size_t length)\n{\n char** fileData = (char**)png_get_io_ptr(pngPointer);\n memcpy(data, *fileData, length);\n *fileData += length;\n}\n\n\/*bool Jatta::Png::isValid(const char* buffer, unsigned int length)\n{\n return png_sig_cmp((png_bytep)buffer, 0, PNGSIGSIZE) == 0;\n}\n\nbool Jatta::Png::isValid(const std::string& fileName)\n{\n \/\/ TODO: clean this up \/ check for errors\n unsigned int size;\n File::getFileSize(fileName, &size);\n char* buffer = new char[size];\n File::getData(fileName, buffer, size);\n bool valid = isValid(buffer, size);\n delete[] buffer;\n return valid;\n}*\/\n\nbool Jatta::Image::loadPng(const std::string& fileName)\n{\n unsigned int size;\n File::getFileSize(fileName, &size);\n char* buffer = new char[size];\n File::getData(fileName, buffer, size);\n\n \/\/if (!isValid(buffer, size))\n \/\/{\n \/\/return false;\n \/\/}\n\n \/\/Here we create the png read struct. The 3 NULL's at the end can be used\n \/\/for your own custom error handling functions, but we'll just use the default.\n \/\/if the function fails, NULL is returned. Always check the return values!\n png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (!pngPtr) {\n std::cerr << \"ERROR: Couldn't initialize png read struct\" << std::endl;\n return false; \/\/Do your own error recovery\/handling here\n }\n\n \/\/Here we create the png info struct.\n \/\/Note that this time, if this function fails, we have to clean up the read struct!\n png_infop infoPtr = png_create_info_struct(pngPtr);\n if (!infoPtr) {\n std::cerr << \"ERROR: Couldn't initialize png info struct\" << std::endl;\n png_destroy_read_struct(&pngPtr, (png_infopp)0, (png_infopp)0);\n return false; \/\/Do your own error recovery\/handling here\n }\n\n \/\/Here I've defined 2 pointers up front, so I can use them in error handling.\n \/\/I will explain these 2 later. Just making sure these get deleted on error.\n png_bytep* rowPtrs = NULL;\n char* data = NULL;\n\n if (setjmp(png_jmpbuf(pngPtr))) {\n \/\/An error occured, so clean up what we have allocated so far...\n png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0);\n if (rowPtrs != NULL) delete [] rowPtrs;\n if (data != NULL) delete [] data;\n\n std::cout << \"ERROR: An error occured while reading the PNG file\\n\";\n\n \/\/Make sure you return here. libPNG will jump to here if something\n \/\/goes wrong, and if you continue with your normal code, you might\n \/\/End up with an infinite loop.\n return false; \/\/ Do your own error handling here.\n }\n\n buffer += 8;\n png_set_read_fn(pngPtr, (png_voidp)&buffer, pngReadData);\n\n \/\/Set the amount signature bytes we've already read:\n \/\/We've defined PNGSIGSIZE as 8;\n png_set_sig_bytes(pngPtr, PNGSIGSIZE);\n\n \/\/Now call png_read_info with our pngPtr as image handle, and infoPtr to receive the file info.\n png_read_info(pngPtr, infoPtr);\n\n\n png_uint_32 imgWidth = png_get_image_width(pngPtr, infoPtr);\n png_uint_32 imgHeight = png_get_image_height(pngPtr, infoPtr);\n\n \/\/bits per CHANNEL! note: not per pixel!\n png_uint_32 bitdepth = png_get_bit_depth(pngPtr, infoPtr);\n \/\/Number of channels\n png_uint_32 channels = png_get_channels(pngPtr, infoPtr);\n \/\/Color type. (RGB, RGBA, Luminance, luminance alpha... palette... etc)\n png_uint_32 color_type = png_get_color_type(pngPtr, infoPtr);\n\n width = imgWidth;\n height = imgHeight;\n\n std::cout << imgWidth << \"x\" << imgHeight << std::endl;\n std::cout << \"Bit Depth: \" << bitdepth << std::endl;\n std::cout << \"Channels: \" << channels << std::endl;\n std::cout << \"Color Type: \" << color_type << std::endl;\n\n png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * imgHeight);\n for (int y = 0; y < imgHeight; y++)\n {\n row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr,infoPtr));\n }\n\n \/\/delete[] buffer;\n\n png_read_image(pngPtr, row_pointers);\n\n if (png_get_color_type(pngPtr, infoPtr) == PNG_COLOR_TYPE_RGB)\n {\n colors = (Color*)new char[imgHeight * imgWidth * sizeof(Color)];\n\n for (int y=0; y"} {"text":"\/\/\/\n\/\/\/ @file MemoryPool.cpp\n\/\/\/ EratMedium and EratBig may use millions of buckets for\n\/\/\/ storing the sieving primes that are required to cross off\n\/\/\/ multiples. As many memory allocations\/deallocations are\n\/\/\/ bad for performance the MemoryPool initially allocates a\n\/\/\/ large number of buckets (using a single memory allocation)\n\/\/\/ and puts the buckets into its stock. The MemoryPool can\n\/\/\/ then serve buckets to EratMedium and EratBig without\n\/\/\/ doing any memory allocation as long as the MemoryPool's\n\/\/\/ stock is not empty.\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace primesieve {\n\nvoid MemoryPool::allocateBuckets()\n{\n if (memory_.empty())\n memory_.reserve(128);\n\n using std::unique_ptr;\n Bucket* buckets = new Bucket[count_];\n memory_.emplace_back(unique_ptr(buckets));\n\n \/\/ initialize buckets\n for (uint64_t i = 0; i < count_; i++)\n {\n Bucket* next = nullptr;\n if (i + 1 < count_)\n next = &buckets[i + 1];\n\n buckets[i].reset();\n buckets[i].setNext(next);\n }\n\n stock_ = buckets;\n increaseAllocCount();\n}\n\nvoid MemoryPool::increaseAllocCount()\n{\n count_ += count_ \/ 8;\n uint64_t maxCount = config::MAX_ALLOC_BYTES \/ sizeof(Bucket);\n count_ = std::min(count_, maxCount);\n}\n\nvoid MemoryPool::addBucket(Bucket*& list)\n{\n if (!stock_)\n allocateBuckets();\n\n \/\/ get first bucket\n Bucket& bucket = *stock_;\n stock_ = stock_->next();\n bucket.setNext(list);\n list = &bucket;\n}\n\nvoid MemoryPool::freeBucket(Bucket* b)\n{\n Bucket& bucket = *b;\n bucket.reset();\n bucket.setNext(stock_);\n stock_ = &bucket;\n}\n\n} \/\/ namespace\nRefactor\/\/\/\n\/\/\/ @file MemoryPool.cpp\n\/\/\/ EratMedium and EratBig may use millions of buckets for\n\/\/\/ storing the sieving primes that are required to cross off\n\/\/\/ multiples. As many memory allocations\/deallocations are\n\/\/\/ bad for performance the MemoryPool initially allocates a\n\/\/\/ large number of buckets (using a single memory allocation)\n\/\/\/ and puts the buckets into its stock. The MemoryPool can\n\/\/\/ then serve buckets to EratMedium and EratBig without\n\/\/\/ doing any memory allocation as long as the MemoryPool's\n\/\/\/ stock is not empty.\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace primesieve {\n\nvoid MemoryPool::addBucket(Bucket*& list)\n{\n if (!stock_)\n allocateBuckets();\n\n \/\/ get first bucket\n Bucket& bucket = *stock_;\n stock_ = stock_->next();\n bucket.setNext(list);\n list = &bucket;\n}\n\nvoid MemoryPool::freeBucket(Bucket* b)\n{\n Bucket& bucket = *b;\n bucket.reset();\n bucket.setNext(stock_);\n stock_ = &bucket;\n}\n\nvoid MemoryPool::allocateBuckets()\n{\n if (memory_.empty())\n memory_.reserve(128);\n\n using std::unique_ptr;\n Bucket* buckets = new Bucket[count_];\n memory_.emplace_back(unique_ptr(buckets));\n\n \/\/ initialize buckets\n for (uint64_t i = 0; i < count_; i++)\n {\n Bucket* next = nullptr;\n if (i + 1 < count_)\n next = &buckets[i + 1];\n\n buckets[i].reset();\n buckets[i].setNext(next);\n }\n\n stock_ = buckets;\n increaseAllocCount();\n}\n\nvoid MemoryPool::increaseAllocCount()\n{\n count_ += count_ \/ 8;\n uint64_t maxCount = config::MAX_ALLOC_BYTES \/ sizeof(Bucket);\n count_ = std::min(count_, maxCount);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"MobSpawner.h\"\n#include \"Mobs\/IncludeAllMonsters.h\"\n\n\n\n\n\ncMobSpawner::cMobSpawner(cMonster::eFamily a_MonsterFamily, const std::set& a_AllowedTypes) :\n\tm_MonsterFamily(a_MonsterFamily),\n\tm_NewPack(true),\n\tm_MobType(mtInvalidType)\n{\n\tfor (std::set::const_iterator itr = a_AllowedTypes.begin(); itr != a_AllowedTypes.end(); ++itr)\n\t{\n\t\tif (cMonster::FamilyFromType(*itr) == a_MonsterFamily)\n\t\t{\n\t\t\tm_AllowedTypes.insert(*itr);\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cMobSpawner::CheckPackCenter(BLOCKTYPE a_BlockType)\n{\n\t\/\/ Packs of non-water mobs can only be centered on an air block\n\t\/\/ Packs of water mobs can only be centered on a water block\n\tif (m_MonsterFamily == cMonster::mfWater)\n\t{\n\t\treturn IsBlockWater(a_BlockType);\n\t}\n\telse\n\t{\n\t\treturn a_BlockType == E_BLOCK_AIR;\n\t}\n}\n\n\n\n\n\nvoid cMobSpawner::addIfAllowed(eMonsterType toAdd, std::set& toAddIn)\n{\n\tstd::set::iterator itr = m_AllowedTypes.find(toAdd);\n\tif (itr != m_AllowedTypes.end())\n\t{\n\t\ttoAddIn.insert(toAdd);\n\t}\n}\n\n\n\n\n\neMonsterType cMobSpawner::ChooseMobType(EMCSBiome a_Biome)\n{\n\tstd::set allowedMobs;\n\n\tif (a_Biome == biMushroomIsland || a_Biome == biMushroomShore)\n\t{\n\t\taddIfAllowed(mtMooshroom, allowedMobs);\n\t}\n\telse if (a_Biome == biNether)\n\t{\n\t\taddIfAllowed(mtGhast, allowedMobs);\n\t\taddIfAllowed(mtZombiePigman, allowedMobs);\n\t\taddIfAllowed(mtMagmaCube, allowedMobs);\n\t}\n\telse if (a_Biome == biEnd)\n\t{\n\t\taddIfAllowed(mtEnderman, allowedMobs);\n\t}\n\telse\n\t{\n\t\taddIfAllowed(mtBat, allowedMobs);\n\t\taddIfAllowed(mtSpider, allowedMobs);\n\t\taddIfAllowed(mtZombie, allowedMobs);\n\t\taddIfAllowed(mtSkeleton, allowedMobs);\n\t\taddIfAllowed(mtCreeper, allowedMobs);\n\t\taddIfAllowed(mtSquid, allowedMobs);\n\t\t\n\t\tif (a_Biome != biDesert && a_Biome != biBeach && a_Biome != biOcean)\n\t\t{\n\t\t\taddIfAllowed(mtSheep, allowedMobs);\n\t\t\taddIfAllowed(mtPig, allowedMobs);\n\t\t\taddIfAllowed(mtCow, allowedMobs);\n\t\t\taddIfAllowed(mtChicken, allowedMobs);\n\t\t\taddIfAllowed(mtEnderman, allowedMobs);\n\t\t\taddIfAllowed(mtSlime, allowedMobs); \/\/ MG TODO : much more complicated rule\n\t\t\t\n\t\t\tif (a_Biome == biForest || a_Biome == biForestHills || a_Biome == biTaiga || a_Biome == biTaigaHills)\n\t\t\t{\n\t\t\t\taddIfAllowed(mtWolf, allowedMobs);\n\t\t\t}\n\t\t\telse if (a_Biome == biJungle || a_Biome == biJungleHills)\n\t\t\t{\n\t\t\t\taddIfAllowed(mtOcelot, allowedMobs);\n\t\t\t}\n\t\t}\n\t}\n\n\tsize_t allowedMobsSize = allowedMobs.size();\n\tif (allowedMobsSize > 0)\n\t{\n\t\tstd::set::iterator itr = allowedMobs.begin();\n\t\tint iRandom = m_Random.NextInt((int)allowedMobsSize, a_Biome);\n\n\t\tfor (int i = 0; i < iRandom; i++)\n\t\t{\n\t\t\t++itr;\n\t\t}\n\n\t\treturn *itr;\n\t}\n\treturn mtInvalidType;\n}\n\n\n\n\n\nbool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)\n{\n\tcFastRandom Random;\n\tBLOCKTYPE TargetBlock = E_BLOCK_AIR;\n\tif (a_Chunk->UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, TargetBlock))\n\t{\n\t\tif ((a_RelY + 1 > cChunkDef::Height) || (a_RelY - 1 < 0))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tNIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);\n\t\tNIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);\n\t\tBLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);\n\t\tBLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);\n\n\t\tSkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);\n\n\t\tswitch (a_MobType)\n\t\t{\n\t\t\tcase mtSquid:\n\t\t\t{\n\t\t\t\treturn IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);\n\t\t\t}\n\n\t\t\tcase mtBat:\n\t\t\t{\n\t\t\t\treturn (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);\n\t\t\t}\n\n\t\t\tcase mtChicken:\n\t\t\tcase mtCow:\n\t\t\tcase mtPig:\n\t\t\tcase mtHorse:\n\t\t\tcase mtSheep:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(BlockBelow == E_BLOCK_GRASS) &&\n\t\t\t\t\t(SkyLight >= 9)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\t\n\t\t\tcase mtOcelot:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)\n\t\t\t\t\t) &&\n\t\t\t\t\t(a_RelY >= 62) &&\n\t\t\t\t\t(Random.NextInt(3, a_Biome) != 0)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtEnderman:\n\t\t\t{\n\t\t\t\tif (a_RelY < 250)\n\t\t\t\t{\n\t\t\t\t\tBLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);\n\t\t\t\t\tif (BlockTop == E_BLOCK_AIR)\n\t\t\t\t\t{\n\t\t\t\t\t\tBlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t\t\t(BlockTop == E_BLOCK_AIR) &&\n\t\t\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t\t\t(SkyLight <= 7) &&\n\t\t\t\t\t\t\t(BlockLight <= 7)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase mtSpider:\n\t\t\t{\n\t\t\t\tbool CanSpawn = true;\n\t\t\t\tbool HasFloor = false;\n\t\t\t\tfor (int x = 0; x < 2; ++x)\n\t\t\t\t{\n\t\t\t\t\tfor (int z = 0; z < 2; ++z)\n\t\t\t\t\t{\n\t\t\t\t\t\tCanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);\n\t\t\t\t\t\tCanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);\n\t\t\t\t\t\tif (!CanSpawn)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tHasFloor = (\n\t\t\t\t\t\t\tHasFloor ||\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\ta_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&\n\t\t\t\t\t\t\t\t!cBlockInfo::IsTransparent(TargetBlock)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtCreeper:\n\t\t\tcase mtSkeleton:\n\t\t\tcase mtZombie:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(SkyLight <= 7) &&\n\t\t\t\t\t(BlockLight <= 7) &&\n\t\t\t\t\t(Random.NextInt(2, a_Biome) == 0)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase mtMagmaCube:\n\t\t\tcase mtSlime:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(a_RelY <= 40) || (a_Biome == biSwampland)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtGhast:\n\t\t\tcase mtZombiePigman:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(Random.NextInt(20, a_Biome) == 0)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtWolf:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_GRASS) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(a_Biome == biTaiga) ||\n\t\t\t\t\t\t(a_Biome == biTaigaHills) ||\n\t\t\t\t\t\t(a_Biome == biForest) ||\n\t\t\t\t\t\t(a_Biome == biForestHills) ||\n\t\t\t\t\t\t(a_Biome == biColdTaiga) ||\n\t\t\t\t\t\t(a_Biome == biColdTaigaHills) ||\n\t\t\t\t\t\t(a_Biome == biTaigaM) ||\n\t\t\t\t\t\t(a_Biome == biMegaTaiga) ||\n\t\t\t\t\t\t(a_Biome == biMegaTaigaHills)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase mtMooshroom:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(a_Biome == biMushroomShore) ||\n\t\t\t\t\t\t(a_Biome == biMushroomIsland)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tLOGD(\"MG TODO: Write spawning rule for mob type %d\", a_MobType);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\ncMonster* cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int& a_MaxPackSize)\n{\n\tcMonster* toReturn = nullptr;\n\tif (m_NewPack)\n\t{\n\t\tm_MobType = ChooseMobType(a_Biome);\n\t\tif (m_MobType == mtInvalidType)\n\t\t{\n\t\t\treturn toReturn;\n\t\t}\n\t\tif (m_MobType == mtWolf)\n\t\t{\n\t\t\ta_MaxPackSize = 8;\n\t\t}\n\t\telse if (m_MobType == mtGhast)\n\t\t{\n\t\t\ta_MaxPackSize = 1;\n\t\t}\n\t\tm_NewPack = false;\n\t}\n\n\t\/\/ Make sure we are looking at the right chunk to spawn in\n\ta_Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);\n\n\tif ((m_AllowedTypes.find(m_MobType) != m_AllowedTypes.end()) && CanSpawnHere(a_Chunk, a_RelX, a_RelY, a_RelZ, m_MobType, a_Biome))\n\t{\n\t\tcMonster * newMob = cMonster::NewMonsterFromType(m_MobType);\n\t\tif (newMob)\n\t\t{\n\t\t\tm_Spawned.insert(newMob);\n\t\t}\n\t\ttoReturn = newMob;\n\t}\n\treturn toReturn;\n}\n\n\n\n\n\nvoid cMobSpawner::NewPack()\n{\n\tm_NewPack = true;\n}\n\n\n\n\n\ncMobSpawner::tSpawnedContainer & cMobSpawner::getSpawned(void)\n{\n\treturn m_Spawned;\n}\n\n\n\n\n\nbool cMobSpawner::CanSpawnAnything(void)\n{\n\treturn !m_AllowedTypes.empty();\n}\n\n\n\n\nupdated mooshroom check for mycelium\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"MobSpawner.h\"\n#include \"Mobs\/IncludeAllMonsters.h\"\n\n\n\n\n\ncMobSpawner::cMobSpawner(cMonster::eFamily a_MonsterFamily, const std::set& a_AllowedTypes) :\n\tm_MonsterFamily(a_MonsterFamily),\n\tm_NewPack(true),\n\tm_MobType(mtInvalidType)\n{\n\tfor (std::set::const_iterator itr = a_AllowedTypes.begin(); itr != a_AllowedTypes.end(); ++itr)\n\t{\n\t\tif (cMonster::FamilyFromType(*itr) == a_MonsterFamily)\n\t\t{\n\t\t\tm_AllowedTypes.insert(*itr);\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cMobSpawner::CheckPackCenter(BLOCKTYPE a_BlockType)\n{\n\t\/\/ Packs of non-water mobs can only be centered on an air block\n\t\/\/ Packs of water mobs can only be centered on a water block\n\tif (m_MonsterFamily == cMonster::mfWater)\n\t{\n\t\treturn IsBlockWater(a_BlockType);\n\t}\n\telse\n\t{\n\t\treturn a_BlockType == E_BLOCK_AIR;\n\t}\n}\n\n\n\n\n\nvoid cMobSpawner::addIfAllowed(eMonsterType toAdd, std::set& toAddIn)\n{\n\tstd::set::iterator itr = m_AllowedTypes.find(toAdd);\n\tif (itr != m_AllowedTypes.end())\n\t{\n\t\ttoAddIn.insert(toAdd);\n\t}\n}\n\n\n\n\n\neMonsterType cMobSpawner::ChooseMobType(EMCSBiome a_Biome)\n{\n\tstd::set allowedMobs;\n\n\tif (a_Biome == biMushroomIsland || a_Biome == biMushroomShore)\n\t{\n\t\taddIfAllowed(mtMooshroom, allowedMobs);\n\t}\n\telse if (a_Biome == biNether)\n\t{\n\t\taddIfAllowed(mtGhast, allowedMobs);\n\t\taddIfAllowed(mtZombiePigman, allowedMobs);\n\t\taddIfAllowed(mtMagmaCube, allowedMobs);\n\t}\n\telse if (a_Biome == biEnd)\n\t{\n\t\taddIfAllowed(mtEnderman, allowedMobs);\n\t}\n\telse\n\t{\n\t\taddIfAllowed(mtBat, allowedMobs);\n\t\taddIfAllowed(mtSpider, allowedMobs);\n\t\taddIfAllowed(mtZombie, allowedMobs);\n\t\taddIfAllowed(mtSkeleton, allowedMobs);\n\t\taddIfAllowed(mtCreeper, allowedMobs);\n\t\taddIfAllowed(mtSquid, allowedMobs);\n\t\t\n\t\tif (a_Biome != biDesert && a_Biome != biBeach && a_Biome != biOcean)\n\t\t{\n\t\t\taddIfAllowed(mtSheep, allowedMobs);\n\t\t\taddIfAllowed(mtPig, allowedMobs);\n\t\t\taddIfAllowed(mtCow, allowedMobs);\n\t\t\taddIfAllowed(mtChicken, allowedMobs);\n\t\t\taddIfAllowed(mtEnderman, allowedMobs);\n\t\t\taddIfAllowed(mtSlime, allowedMobs); \/\/ MG TODO : much more complicated rule\n\t\t\t\n\t\t\tif (a_Biome == biForest || a_Biome == biForestHills || a_Biome == biTaiga || a_Biome == biTaigaHills)\n\t\t\t{\n\t\t\t\taddIfAllowed(mtWolf, allowedMobs);\n\t\t\t}\n\t\t\telse if (a_Biome == biJungle || a_Biome == biJungleHills)\n\t\t\t{\n\t\t\t\taddIfAllowed(mtOcelot, allowedMobs);\n\t\t\t}\n\t\t}\n\t}\n\n\tsize_t allowedMobsSize = allowedMobs.size();\n\tif (allowedMobsSize > 0)\n\t{\n\t\tstd::set::iterator itr = allowedMobs.begin();\n\t\tint iRandom = m_Random.NextInt((int)allowedMobsSize, a_Biome);\n\n\t\tfor (int i = 0; i < iRandom; i++)\n\t\t{\n\t\t\t++itr;\n\t\t}\n\n\t\treturn *itr;\n\t}\n\treturn mtInvalidType;\n}\n\n\n\n\n\nbool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)\n{\n\tcFastRandom Random;\n\tBLOCKTYPE TargetBlock = E_BLOCK_AIR;\n\tif (a_Chunk->UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, TargetBlock))\n\t{\n\t\tif ((a_RelY + 1 > cChunkDef::Height) || (a_RelY - 1 < 0))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tNIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);\n\t\tNIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);\n\t\tBLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);\n\t\tBLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);\n\n\t\tSkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);\n\n\t\tswitch (a_MobType)\n\t\t{\n\t\t\tcase mtSquid:\n\t\t\t{\n\t\t\t\treturn IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);\n\t\t\t}\n\n\t\t\tcase mtBat:\n\t\t\t{\n\t\t\t\treturn (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);\n\t\t\t}\n\n\t\t\tcase mtChicken:\n\t\t\tcase mtCow:\n\t\t\tcase mtPig:\n\t\t\tcase mtHorse:\n\t\t\tcase mtSheep:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(BlockBelow == E_BLOCK_GRASS) &&\n\t\t\t\t\t(SkyLight >= 9)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\t\n\t\t\tcase mtOcelot:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)\n\t\t\t\t\t) &&\n\t\t\t\t\t(a_RelY >= 62) &&\n\t\t\t\t\t(Random.NextInt(3, a_Biome) != 0)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtEnderman:\n\t\t\t{\n\t\t\t\tif (a_RelY < 250)\n\t\t\t\t{\n\t\t\t\t\tBLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);\n\t\t\t\t\tif (BlockTop == E_BLOCK_AIR)\n\t\t\t\t\t{\n\t\t\t\t\t\tBlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t\t\t(BlockTop == E_BLOCK_AIR) &&\n\t\t\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t\t\t(SkyLight <= 7) &&\n\t\t\t\t\t\t\t(BlockLight <= 7)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase mtSpider:\n\t\t\t{\n\t\t\t\tbool CanSpawn = true;\n\t\t\t\tbool HasFloor = false;\n\t\t\t\tfor (int x = 0; x < 2; ++x)\n\t\t\t\t{\n\t\t\t\t\tfor (int z = 0; z < 2; ++z)\n\t\t\t\t\t{\n\t\t\t\t\t\tCanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);\n\t\t\t\t\t\tCanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);\n\t\t\t\t\t\tif (!CanSpawn)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tHasFloor = (\n\t\t\t\t\t\t\tHasFloor ||\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\ta_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&\n\t\t\t\t\t\t\t\t!cBlockInfo::IsTransparent(TargetBlock)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtCreeper:\n\t\t\tcase mtSkeleton:\n\t\t\tcase mtZombie:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(SkyLight <= 7) &&\n\t\t\t\t\t(BlockLight <= 7) &&\n\t\t\t\t\t(Random.NextInt(2, a_Biome) == 0)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase mtMagmaCube:\n\t\t\tcase mtSlime:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(a_RelY <= 40) || (a_Biome == biSwampland)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtGhast:\n\t\t\tcase mtZombiePigman:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(!cBlockInfo::IsTransparent(BlockBelow)) &&\n\t\t\t\t\t(Random.NextInt(20, a_Biome) == 0)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tcase mtWolf:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_GRASS) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(a_Biome == biTaiga) ||\n\t\t\t\t\t\t(a_Biome == biTaigaHills) ||\n\t\t\t\t\t\t(a_Biome == biForest) ||\n\t\t\t\t\t\t(a_Biome == biForestHills) ||\n\t\t\t\t\t\t(a_Biome == biColdTaiga) ||\n\t\t\t\t\t\t(a_Biome == biColdTaigaHills) ||\n\t\t\t\t\t\t(a_Biome == biTaigaM) ||\n\t\t\t\t\t\t(a_Biome == biMegaTaiga) ||\n\t\t\t\t\t\t(a_Biome == biMegaTaigaHills)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase mtMooshroom:\n\t\t\t{\n\t\t\t\treturn (\n\t\t\t\t\t(TargetBlock == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockAbove == E_BLOCK_AIR) &&\n\t\t\t\t\t(BlockBelow == E_BLOCK_MYCELIUM) &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(a_Biome == biMushroomShore) ||\n\t\t\t\t\t\t(a_Biome == biMushroomIsland)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tLOGD(\"MG TODO: Write spawning rule for mob type %d\", a_MobType);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\ncMonster* cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int& a_MaxPackSize)\n{\n\tcMonster* toReturn = nullptr;\n\tif (m_NewPack)\n\t{\n\t\tm_MobType = ChooseMobType(a_Biome);\n\t\tif (m_MobType == mtInvalidType)\n\t\t{\n\t\t\treturn toReturn;\n\t\t}\n\t\tif (m_MobType == mtWolf)\n\t\t{\n\t\t\ta_MaxPackSize = 8;\n\t\t}\n\t\telse if (m_MobType == mtGhast)\n\t\t{\n\t\t\ta_MaxPackSize = 1;\n\t\t}\n\t\tm_NewPack = false;\n\t}\n\n\t\/\/ Make sure we are looking at the right chunk to spawn in\n\ta_Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);\n\n\tif ((m_AllowedTypes.find(m_MobType) != m_AllowedTypes.end()) && CanSpawnHere(a_Chunk, a_RelX, a_RelY, a_RelZ, m_MobType, a_Biome))\n\t{\n\t\tcMonster * newMob = cMonster::NewMonsterFromType(m_MobType);\n\t\tif (newMob)\n\t\t{\n\t\t\tm_Spawned.insert(newMob);\n\t\t}\n\t\ttoReturn = newMob;\n\t}\n\treturn toReturn;\n}\n\n\n\n\n\nvoid cMobSpawner::NewPack()\n{\n\tm_NewPack = true;\n}\n\n\n\n\n\ncMobSpawner::tSpawnedContainer & cMobSpawner::getSpawned(void)\n{\n\treturn m_Spawned;\n}\n\n\n\n\n\nbool cMobSpawner::CanSpawnAnything(void)\n{\n\treturn !m_AllowedTypes.empty();\n}\n\n\n\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) 2013 Matti Schnurbusch (original code)\n\/\/ Copyright (C) 2015 Michael Kirsche (smaller fixes, extended WPAN startup and management, ported for INET 2.x)\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public License\n\/\/ as published by the Free Software Foundation; either version 2\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, see .\n\/\/\n\n#include \"llc.h\"\n#include \"IPSocket.h\"\n\nbool llc::firstDevice;\n\nDefine_Module(llc);\n\nvoid llc::initialize()\n{\n if (hasPar(\"llcDebug\"))\n llcDebug = par(\"llcDebug\").boolValue();\n else\n llcDebug = false;\n\n \/* This is for Application layers which cannot send out MCPS primitives\n * if a true LLC is available, it will take care of it\n * just make sure the Application is sending cPackets\n *\/\n double seed = dblrand();\n convertingMode = par(\"convertMode\").boolValue();\n\n TXoption = par(\"TXoption\");\n logicalChannel = par(\"LogicalChannel\");\n\n firstDevice = true;\n associateSuccess = false;\n\n WATCH(firstDevice);\n WATCH(associateSuccess);\n\n if (convertingMode)\n {\n \/\/ Check if startWithoutStartRequest was enabled by user\n if (getModuleByPath(\"net.IEEE802154Nodes[0].NIC.MAC.IEEE802154Mac\")->par(\"startWithoutStartReq\").boolValue() == false)\n {\n llcEV << \"Sending Start Request in \" << seed << endl;\n selfMsg = new cMessage(\"LLC-Start\");\n selfMsg->setKind(0);\n scheduleAt(seed, selfMsg);\n }\n else\n {\n llcEV << \"Starting without an explicit Start Request right now (startwithoutStartReq == true) \\n\";\n }\n\n scanChannels = par(\"ScanChannels\");\n scanDuration = par(\"ScanDuration\");\n scanPage = par(\"ScanPage\");\n scanType = par(\"ScanType\");\n pollFreq = par(\"PollFrequency\");\n\n if (TXoption >= 4)\n {\n pollTimer = new cMessage(\"LLC-POLL-Timer\");\n llcEV << \"TXoption set to indirect - starting Poll timer \\n\";\n pollTimer->setKind(1);\n scheduleAt(pollFreq, pollTimer);\n }\n }\n\n}\n\nMACAddressExt* llc::tokenDest(cMessage* msg)\n{\n \/\/ get the IPv6 destination address from the IPv6 Control Info block\n IPv6ControlInfo * controlInfo;\n controlInfo = check_and_cast(msg->getControlInfo());\n\n IPv6Address destAddr = controlInfo->getDestAddr();\n\n if (destAddr.isUnspecified())\n {\n error(\"[802154LLC]: tokenDest ==> no destination address set \/ address unspecified\");\n }\n\n \/\/ Use the internal representation of the IPv6 address to create the 64-bit EUI MAC address\n \/\/ create 8 groups with each 16 bit's (aka 8 tupels)\n uint16_t groups[8] = { uint16_t(*&destAddr.words()[0] >> 16), uint16_t(*&destAddr.words()[0] & 0xffff), uint16_t(*&destAddr.words()[1] >> 16), uint16_t(\n *&destAddr.words()[1] & 0xffff), uint16_t(*&destAddr.words()[2] >> 16), uint16_t(*&destAddr.words()[2] & 0xffff), uint16_t(*&destAddr.words()[3] >> 16), uint16_t(\n *&destAddr.words()[3] & 0xffff) };\n\n std::string destString;\n\n \/\/ take the last four tuples\n for (int i = 4; i < 8; ++i)\n {\n std::string sHelp;\n char cHelp[5];\n\n \/\/ convert uint16_t to hex and to string\n sprintf(cHelp, \"%x\", groups[i]);\n sHelp.append(cHelp);\n\n \/\/ as IPv6 addresses might be compressed, we need to add up \"compressed\" zeros\n while (sHelp.length() < 4)\n {\n sHelp.insert(0, \"0\");\n }\n \/\/ write everything into the destination string\n destString.append(sHelp);\n }\n\n \/\/ create a new 64-bit EUI MAC address from the destination string\n MACAddressExt* dest = new MACAddressExt(destString.c_str());\n llcEV << \"Tokenized Destination Address from IFI \/ IPvXTrafGen is: \" << dest->str() << endl;\n return dest;\n}\n\nvoid llc::genAssoReq()\n{\n AssociationRequest* assoReq = new AssociationRequest(\"MLME-ASSOCIATE.request\");\n MACAddressExt* coordId = new MACAddressExt(coordPANId);\n assoReq->setCoordAddrMode(coordAddrMode);\n assoReq->setCoordPANId(*coordId);\n assoReq->setCoordAddress(coordAddress);\n DevCapability capInfo;\n capInfo.alloShortAddr = true;\n capInfo.FFD = true;\n capInfo.recvOnWhenIdle = true;\n capInfo.secuCapable = false;\n assoReq->setCapabilityInformation(capInfo);\n assoReq->setChannelPage(0);\n assoReq->setLogicalChannel(logicalChannel);\n\n send(assoReq, \"outMngt\");\n}\n\nvoid llc::genPollReq()\n{\n PollRequest* pollReq = new PollRequest(\"MLME-POLL.request\");\n pollReq->setCoordAddrMode(addrShort);\n pollReq->setCoordPANId(coordPANId);\n pollReq->setCoordAddress(coordAddress);\n\n send(pollReq, \"outMngt\");\n}\n\nvoid llc::genScanReq()\n{\n ScanRequest* scanReq = new ScanRequest(\"MLME-SCAN.request\");\n scanReq->setScanType(scanType); \/\/ see enum\n scanReq->setScanChannels(scanChannels); \/\/ 27 bit indicating the channels to be scanned\n scanReq->setScanDuration(scanDuration); \/\/ time spent on scanning each channel\n scanReq->setChannelPage(scanPage);\n\n send(scanReq, \"outMngt\");\n}\n\nvoid llc::genOrphanResp(OrphanIndication* oi)\n{\n OrphanResponse* oR = new OrphanResponse(\"MLME-ORPHAN.response\");\n oR->setOrphanAddress(oi->getOrphanAddress());\n oR->setShortAddress(0xffff);\n oR->setAssociatedMember(false);\n\n send(oR, \"outMngt\");\n}\n\nvoid llc::handleMessage(cMessage *msg)\n{\n llcEV << \"Got Message in LLC - \" << msg->getName() << endl;\n\n if (msg->isSelfMessage())\n {\n if (msg->getKind() == 0)\n {\n llcEV << \"Got Startup Msg - Sending out Scan Request \\n\";\n genScanReq();\n delete (msg);\n }\n else if (msg->getKind() == 1)\n {\n llcEV << \"Got POLL Timer - Sending POLL Request \\n\";\n genPollReq();\n scheduleAt(simTime() + pollFreq, msg);\n }\n return;\n }\n\n if (msg->arrivedOn(\"inApp\"))\n {\n if ((msg->getKind() == IP_C_REGISTER_PROTOCOL))\n {\n llcEV << \"FIXME(!) Register Protocol Message is not handled yet - FullPath: \" << msg->getFullPath() << endl;\n delete (msg);\n return;\n }\n\n if (convertingMode)\n {\n if (!msg->isPacket())\n error(\"[802154LLC]: Application layer in convertingMode has to send out cPackets!\");\n\n cPacket* pack = check_and_cast(msg);\n\n mcpsDataReq* data = new mcpsDataInd(\"MCPS-DATA.indication\");\n data->encapsulate(pack);\n data->setMsduHandle(pack->getId());\n data->setMsduLength(pack->getByteLength());\n data->setTxOptions(TXoption);\n \/\/ try to generate the MAC destination address from the packet's IPvX address destination address\n MACAddressExt* destination = tokenDest(msg);\n data->setDstAddr(*destination);\n\n send(data, \"outData\");\n return;\n }\n else\n {\n send(msg, \"outData\");\n }\n } \/\/ if (msg->arrivedOn(\"inApp\"))\n else if (msg->arrivedOn(\"inMngt\"))\n {\n if (convertingMode)\n {\n if (dynamic_cast(msg))\n {\n if (associateSuccess == false)\n {\n beaconNotify* bN = check_and_cast(msg);\n coordAddrMode = bN->getPANDescriptor().CoordAddrMode;\n coordPANId = bN->getPANDescriptor().CoordPANId;\n coordAddress = bN->getPANDescriptor().CoordAddress; \/\/ shared by both 16 bit short address or 64 bit extended address\n logicalChannel = bN->getPANDescriptor().LogicalChannel;\n llcEV << \"Beacon Notify received an not yet associated -> generate Association Request for the existing PAN Coordinator \\n\";\n genAssoReq();\n }\n else\n {\n llcEV << \"Beacon Notify received and associated - no further processing of the Beacon Notify \\n\";\n }\n }\n\n if (dynamic_cast(msg))\n {\n \/\/ TODO divide between \"started your own PAN\" and \"found a PAN and starting association process\" ??\n llcEV << \"Got MLME-START.confirm from lower layer \\n\";\n }\n\n if (dynamic_cast(msg))\n {\n ScanConfirm* scanConf = check_and_cast(msg);\n\n if (scanConf->getResultListSize() == 0)\n {\n llcEV << \"Got MLME-SCAN.confirm with ResultListSize == 0 \\n\";\n\n if (firstDevice)\n {\n llcEV << \"First global device without results sends out MLME-START for Coordinator \\n\";\n\n startMsg = new StartRequest(\"MLME-START.request\");\n startMsg->setPANId(par(\"PANId\"));\n startMsg->setLogicalChannel(logicalChannel);\n startMsg->setChannelPage(par(\"ChannelPage\"));\n startMsg->setStartTime(par(\"StartTime\"));\n startMsg->setBeaconOrder(par(\"BeaconOrder\"));\n startMsg->setSuperframeOrder(par(\"SuperframeOrder\"));\n startMsg->setBatteryLifeExtension(par(\"BatteryLifeExtension\"));\n startMsg->setPANCoordinator(true);\n startMsg->setCoordRealignment(false); \/\/ override user parameter here since 1st device starts PAN and doesn't realign it\n\n firstDevice = false;\n send(startMsg, \"outMngt\");\n }\n else\n {\n llcEV << \"No results - scan again \\n\";\n genScanReq();\n }\n }\n else\n {\n llcEV << \"Got MLME-SCAN.confirm with ResultListSize > 0 \\n\";\n\n unsigned short panId = par(\"PANId\");\n logicalChannel = par(\"LogicalChannel\");\n unsigned short channelPage = par(\"ChannelPage\");\n unsigned int startTime = par(\"StartTime\");\n unsigned short beaconOrder = par(\"BeaconOrder\");\n unsigned short superframeOrder = par(\"SuperframeOrder\");\n bool batteryLifeExtension = par(\"BatteryLifeExtension\");\n bool coordRealignment = par(\"CoordRealignment\"); \n\n startMsg = new StartRequest(\"MLME-START.request\");\n startMsg->setPANId(panId);\n startMsg->setLogicalChannel(logicalChannel);\n startMsg->setChannelPage(channelPage);\n startMsg->setStartTime(startTime);\n startMsg->setBeaconOrder(beaconOrder);\n startMsg->setSuperframeOrder(superframeOrder);\n startMsg->setBatteryLifeExtension(batteryLifeExtension);\n startMsg->setCoordRealignment(coordRealignment);\n\n startMsg->setPANCoordinator(false);\n send(startMsg, \"outMngt\");\n }\n }\n\n if (dynamic_cast(msg))\n {\n llcEV << \"Association Confirm received - association process was successful \\n\";\n associateSuccess = true;\n }\n\n if (dynamic_cast(msg))\n {\n \/\/ just for convenience of functional tests\n OrphanIndication* oi = check_and_cast(msg);\n genOrphanResp(oi);\n }\n\n \/\/ Since we are converting assume application layer won't understand any MLME messages\n llcEV << \"convertingMode -> deleting MLME Message without forwarding it to higher layer -> \" << msg->getFullName() << endl;\n delete (msg);\n return;\n }\n\n llcEV << \"Forwarding MLME Message (\" << msg->getFullName() << \") to the higher layer \\n\";\n send(msg, \"outApp\");\n\n } \/\/ if (msg->arrivedOn(\"inMngt\"))\n\n if (msg->arrivedOn(\"inData\"))\n {\n if (convertingMode)\n {\n \/\/ this can only be a confirm or indication\n if (dynamic_cast(msg))\n {\n mcpsDataInd* ind = check_and_cast(msg);\n cPacket* payload = ind->decapsulate();\n llcEV << \"Forwarding MCPS-Data.indication to the higher layer \\n\";\n send(payload, \"outApp\");\n }\n else if (dynamic_cast(msg))\n {\n mcpsDataConf* conf = check_and_cast(msg);\n\n llcEV << \"Got a Confirmation from MAC entity with Status: \" << MCPSStatusToString(MCPSStatus(conf->getStatus())) << \" for Message #\" << conf->getMsduHandle() << endl;\n delete (conf);\n return;\n }\n else {\n error (\"[LLC]: Undefined Message arrived on inData gate!\");\n }\n }\n else\n {\n llcEV << \"Forwarding MCPS-Data to the higher layer -> \" << msg->getFullName() << endl;\n send(msg, \"outApp\");\n }\n }\n}\n\nllc::llc()\n{\n\n}\n\nllc::~llc()\n{\n if (TXoption >= 4)\n {\n if (pollTimer)\n cancelAndDelete(pollTimer);\n }\n\n}\nFix for undisposed objects in LLC module Changed generated data message to MCPS-DATA.request (expected at MAC layer)\/\/\n\/\/ Copyright (C) 2013 Matti Schnurbusch (original code)\n\/\/ Copyright (C) 2015 Michael Kirsche (smaller fixes, extended WPAN startup and management, ported for INET 2.x)\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public License\n\/\/ as published by the Free Software Foundation; either version 2\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, see .\n\/\/\n\n#include \"llc.h\"\n#include \"IPSocket.h\"\n\nbool llc::firstDevice;\n\nDefine_Module(llc);\n\nvoid llc::initialize()\n{\n if (hasPar(\"llcDebug\"))\n llcDebug = par(\"llcDebug\").boolValue();\n else\n llcDebug = false;\n\n \/* This is for Application layers which cannot send out MCPS primitives\n * if a true LLC is available, it will take care of it\n * just make sure the Application is sending cPackets\n *\/\n double seed = dblrand();\n convertingMode = par(\"convertMode\").boolValue();\n\n TXoption = par(\"TXoption\");\n logicalChannel = par(\"LogicalChannel\");\n\n firstDevice = true;\n associateSuccess = false;\n\n WATCH(firstDevice);\n WATCH(associateSuccess);\n\n if (convertingMode)\n {\n \/\/ Check if startWithoutStartRequest was enabled by user\n if (getModuleByPath(\"net.IEEE802154Nodes[0].NIC.MAC.IEEE802154Mac\")->par(\"startWithoutStartReq\").boolValue() == false)\n {\n llcEV << \"Sending Start Request in \" << seed << endl;\n selfMsg = new cMessage(\"LLC-Start\");\n selfMsg->setKind(0);\n scheduleAt(seed, selfMsg);\n }\n else\n {\n llcEV << \"Starting without an explicit Start Request right now (startwithoutStartReq == true) \\n\";\n }\n\n scanChannels = par(\"ScanChannels\");\n scanDuration = par(\"ScanDuration\");\n scanPage = par(\"ScanPage\");\n scanType = par(\"ScanType\");\n pollFreq = par(\"PollFrequency\");\n\n if (TXoption >= 4)\n {\n pollTimer = new cMessage(\"LLC-POLL-Timer\");\n llcEV << \"TXoption set to indirect - starting Poll timer \\n\";\n pollTimer->setKind(1);\n scheduleAt(pollFreq, pollTimer);\n }\n }\n\n}\n\nMACAddressExt* llc::tokenDest(cMessage* msg)\n{\n \/\/ get the IPv6 destination address from the IPv6 Control Info block\n IPv6ControlInfo * controlInfo;\n controlInfo = check_and_cast(msg->getControlInfo());\n\n IPv6Address destAddr = controlInfo->getDestAddr();\n\n if (destAddr.isUnspecified())\n {\n error(\"[802154LLC]: tokenDest ==> no destination address set \/ address unspecified\");\n }\n\n \/\/ Use the internal representation of the IPv6 address to create the 64-bit EUI MAC address\n \/\/ create 8 groups with each 16 bit's (aka 8 tupels)\n uint16_t groups[8] = { uint16_t(*&destAddr.words()[0] >> 16), uint16_t(*&destAddr.words()[0] & 0xffff), uint16_t(*&destAddr.words()[1] >> 16), uint16_t(\n *&destAddr.words()[1] & 0xffff), uint16_t(*&destAddr.words()[2] >> 16), uint16_t(*&destAddr.words()[2] & 0xffff), uint16_t(*&destAddr.words()[3] >> 16), uint16_t(\n *&destAddr.words()[3] & 0xffff) };\n\n std::string destString;\n\n \/\/ take the last four tuples\n for (int i = 4; i < 8; ++i)\n {\n std::string sHelp;\n char cHelp[5];\n\n \/\/ convert uint16_t to hex and to string\n sprintf(cHelp, \"%x\", groups[i]);\n sHelp.append(cHelp);\n\n \/\/ as IPv6 addresses might be compressed, we need to add up \"compressed\" zeros\n while (sHelp.length() < 4)\n {\n sHelp.insert(0, \"0\");\n }\n \/\/ write everything into the destination string\n destString.append(sHelp);\n }\n\n \/\/ create a new 64-bit EUI MAC address from the destination string\n MACAddressExt* dest = new MACAddressExt(destString.c_str());\n llcEV << \"Tokenized Destination Address from IFI \/ IPvXTrafGen is: \" << dest->str() << endl;\n return dest;\n}\n\nvoid llc::genAssoReq()\n{\n AssociationRequest* assoReq = new AssociationRequest(\"MLME-ASSOCIATE.request\");\n MACAddressExt* coordId = new MACAddressExt(coordPANId);\n assoReq->setCoordAddrMode(coordAddrMode);\n assoReq->setCoordPANId(*coordId);\n assoReq->setCoordAddress(coordAddress);\n DevCapability capInfo;\n capInfo.alloShortAddr = true;\n capInfo.FFD = true;\n capInfo.recvOnWhenIdle = true;\n capInfo.secuCapable = false;\n assoReq->setCapabilityInformation(capInfo);\n assoReq->setChannelPage(0);\n assoReq->setLogicalChannel(logicalChannel);\n\n send(assoReq, \"outMngt\");\n}\n\nvoid llc::genPollReq()\n{\n PollRequest* pollReq = new PollRequest(\"MLME-POLL.request\");\n pollReq->setCoordAddrMode(addrShort);\n pollReq->setCoordPANId(coordPANId);\n pollReq->setCoordAddress(coordAddress);\n\n send(pollReq, \"outMngt\");\n}\n\nvoid llc::genScanReq()\n{\n ScanRequest* scanReq = new ScanRequest(\"MLME-SCAN.request\");\n scanReq->setScanType(scanType); \/\/ see enum\n scanReq->setScanChannels(scanChannels); \/\/ 27 bit indicating the channels to be scanned\n scanReq->setScanDuration(scanDuration); \/\/ time spent on scanning each channel\n scanReq->setChannelPage(scanPage);\n\n send(scanReq, \"outMngt\");\n}\n\nvoid llc::genOrphanResp(OrphanIndication* oi)\n{\n OrphanResponse* oR = new OrphanResponse(\"MLME-ORPHAN.response\");\n oR->setOrphanAddress(oi->getOrphanAddress());\n oR->setShortAddress(0xffff);\n oR->setAssociatedMember(false);\n\n send(oR, \"outMngt\");\n}\n\nvoid llc::handleMessage(cMessage *msg)\n{\n llcEV << \"Got Message in LLC - \" << msg->getName() << endl;\n\n if (msg->isSelfMessage())\n {\n if (msg->getKind() == 0)\n {\n llcEV << \"Got Startup Msg - Sending out Scan Request \\n\";\n genScanReq();\n delete (msg);\n }\n else if (msg->getKind() == 1)\n {\n llcEV << \"Got POLL Timer - Sending POLL Request \\n\";\n genPollReq();\n scheduleAt(simTime() + pollFreq, msg);\n }\n return;\n }\n\n if (msg->arrivedOn(\"inApp\"))\n {\n if ((msg->getKind() == IP_C_REGISTER_PROTOCOL))\n {\n llcEV << \"FIXME(!) Register Protocol Message is not handled yet - FullPath: \" << msg->getFullPath() << endl;\n delete (msg);\n return;\n }\n\n if (convertingMode)\n {\n if (!msg->isPacket())\n error(\"[802154LLC]: Application layer in convertingMode has to send out cPackets!\");\n\n cPacket* pack = check_and_cast(msg);\n\n mcpsDataReq* data = new mcpsDataReq(\"MCPS-DATA.request\");\n data->encapsulate(pack);\n data->setMsduHandle(pack->getId());\n data->setMsduLength(pack->getByteLength());\n data->setTxOptions(TXoption);\n \/\/ try to generate the MAC destination address from the packet's IPvX address destination address\n MACAddressExt* destination = tokenDest(msg);\n data->setDstAddr(*destination);\n\n send(data, \"outData\");\n return;\n }\n else\n {\n send(msg, \"outData\");\n }\n } \/\/ if (msg->arrivedOn(\"inApp\"))\n else if (msg->arrivedOn(\"inMngt\"))\n {\n if (convertingMode)\n {\n if (dynamic_cast(msg))\n {\n if (associateSuccess == false)\n {\n beaconNotify* bN = check_and_cast(msg);\n coordAddrMode = bN->getPANDescriptor().CoordAddrMode;\n coordPANId = bN->getPANDescriptor().CoordPANId;\n coordAddress = bN->getPANDescriptor().CoordAddress; \/\/ shared by both 16 bit short address or 64 bit extended address\n logicalChannel = bN->getPANDescriptor().LogicalChannel;\n llcEV << \"Beacon Notify received an not yet associated -> generate Association Request for the existing PAN Coordinator \\n\";\n genAssoReq();\n }\n else\n {\n llcEV << \"Beacon Notify received and associated - no further processing of the Beacon Notify \\n\";\n }\n }\n\n if (dynamic_cast(msg))\n {\n \/\/ TODO divide between \"started your own PAN\" and \"found a PAN and starting association process\" ??\n llcEV << \"Got MLME-START.confirm from lower layer \\n\";\n }\n\n if (dynamic_cast(msg))\n {\n ScanConfirm* scanConf = check_and_cast(msg);\n\n if (scanConf->getResultListSize() == 0)\n {\n llcEV << \"Got MLME-SCAN.confirm with ResultListSize == 0 \\n\";\n\n if (firstDevice)\n {\n llcEV << \"First global device without results sends out MLME-START for Coordinator \\n\";\n\n startMsg = new StartRequest(\"MLME-START.request\");\n startMsg->setPANId(par(\"PANId\"));\n startMsg->setLogicalChannel(logicalChannel);\n startMsg->setChannelPage(par(\"ChannelPage\"));\n startMsg->setStartTime(par(\"StartTime\"));\n startMsg->setBeaconOrder(par(\"BeaconOrder\"));\n startMsg->setSuperframeOrder(par(\"SuperframeOrder\"));\n startMsg->setBatteryLifeExtension(par(\"BatteryLifeExtension\"));\n startMsg->setPANCoordinator(true);\n startMsg->setCoordRealignment(false); \/\/ override user parameter here since 1st device starts PAN and doesn't realign it\n\n firstDevice = false;\n send(startMsg, \"outMngt\");\n }\n else\n {\n llcEV << \"No results - scan again \\n\";\n genScanReq();\n }\n }\n else\n {\n llcEV << \"Got MLME-SCAN.confirm with ResultListSize > 0 \\n\";\n\n unsigned short panId = par(\"PANId\");\n logicalChannel = par(\"LogicalChannel\");\n unsigned short channelPage = par(\"ChannelPage\");\n unsigned int startTime = par(\"StartTime\");\n unsigned short beaconOrder = par(\"BeaconOrder\");\n unsigned short superframeOrder = par(\"SuperframeOrder\");\n bool batteryLifeExtension = par(\"BatteryLifeExtension\");\n bool coordRealignment = par(\"CoordRealignment\"); \n\n startMsg = new StartRequest(\"MLME-START.request\");\n startMsg->setPANId(panId);\n startMsg->setLogicalChannel(logicalChannel);\n startMsg->setChannelPage(channelPage);\n startMsg->setStartTime(startTime);\n startMsg->setBeaconOrder(beaconOrder);\n startMsg->setSuperframeOrder(superframeOrder);\n startMsg->setBatteryLifeExtension(batteryLifeExtension);\n startMsg->setCoordRealignment(coordRealignment);\n\n startMsg->setPANCoordinator(false);\n send(startMsg, \"outMngt\");\n }\n }\n\n if (dynamic_cast(msg))\n {\n llcEV << \"Association Confirm received - association process was successful \\n\";\n associateSuccess = true;\n }\n\n if (dynamic_cast(msg))\n {\n \/\/ just for convenience of functional tests\n OrphanIndication* oi = check_and_cast(msg);\n genOrphanResp(oi);\n }\n\n \/\/ Since we are converting assume application layer won't understand any MLME messages\n llcEV << \"convertingMode -> deleting MLME Message without forwarding it to higher layer -> \" << msg->getFullName() << endl;\n delete (msg);\n return;\n }\n\n llcEV << \"Forwarding MLME Message (\" << msg->getFullName() << \") to the higher layer \\n\";\n send(msg, \"outApp\");\n\n } \/\/ if (msg->arrivedOn(\"inMngt\"))\n\n if (msg->arrivedOn(\"inData\"))\n {\n if (convertingMode)\n {\n \/\/ this can only be a confirm or indication\n if (dynamic_cast(msg))\n {\n mcpsDataInd* ind = check_and_cast(msg);\n cPacket* payload = ind->decapsulate();\n llcEV << \"Forwarding MCPS-Data.indication to the higher layer \\n\";\n send(payload, \"outApp\");\n delete(ind); \/\/ XXX fix for undisposed object: (mcpsDataInd) net.IEEE802154Nodes[0].Network.stdLLC.MCPS-DATA.indication\n }\n else if (dynamic_cast(msg))\n {\n mcpsDataConf* conf = check_and_cast(msg);\n\n llcEV << \"Got a Confirmation from MAC entity with Status: \" << MCPSStatusToString(MCPSStatus(conf->getStatus())) << \" for Message #\" << conf->getMsduHandle() << endl;\n delete(conf);\n return;\n }\n else {\n error (\"[LLC]: Undefined Message arrived on inData gate!\");\n }\n }\n else\n {\n llcEV << \"Forwarding MCPS-Data to the higher layer -> \" << msg->getFullName() << endl;\n send(msg, \"outApp\");\n }\n }\n}\n\nllc::llc()\n{\n\n}\n\nllc::~llc()\n{\n if (TXoption >= 4)\n {\n if (pollTimer)\n cancelAndDelete(pollTimer);\n }\n}\n<|endoftext|>"} {"text":"#include \"MoveSystem.h\"\n\n#include \n\nvoid MoveSystem::update(int currentStep)\n{\n const std::vector &uidList = movementNode.uids();\n\tfor(int i = 0; i < uidList.size(); i++)\n\t{\n\t\tMovementNode &n = movementNode.get(uidList.at(i));\n\n\t\tPositionComponent &p = n.position;\n\t\tstd::cout << p.positionX;\n\t}\n}Add: move position component#include \"MoveSystem.h\"\n\n#include \n\nvoid MoveSystem::update(int currentStep)\n{\n const std::vector &uidList = movementNode.uids();\n\tfor(int i = 0; i < uidList.size(); i++)\n\t{\n\t\tMovementNode &n = movementNode.get(uidList.at(i));\n\n\t\tPositionComponent &p = n.position;\n\t\tconst VelocityComponent &v = n.velocity;\n\t\tp.positionX += v.velocityX;\n\t\tstd::cout << p.positionX << \"\\n\";\n\t}\n}<|endoftext|>"} {"text":"\/*\n Copyright (c) 2019, Dimitri Diakopoulos All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Decoders.h\"\n\nusing namespace nqr;\n\n#include \"mpc\/mpcdec.h\"\n#include \"mpc\/reader.h\"\n#include \"musepack\/libmpcdec\/decoder.h\"\n#include \"musepack\/libmpcdec\/internal.h\"\n\n#define MINIMP3_FLOAT_OUTPUT\n#define MINIMP3_IMPLEMENTATION\n#include \"minimp3\/minimp3.h\"\n#include \"minimp3\/minimp3_ex.h\"\n\n#include \n\nvoid mp3_decode_internal(AudioData * d, const std::vector & fileData)\n{\n mp3dec_t mp3d;\n mp3dec_file_info_t info;\n mp3dec_load_buf(&mp3d, (const uint8_t*)fileData.data(), fileData.size(), &info, 0, 0);\n\n d->sampleRate = info.hz;\n d->channelCount = info.channels;\n d->sourceFormat = MakeFormatForBits(32, true, false);\n d->lengthSeconds = ((float)info.samples \/ (float)d->channelCount) \/ (float)d->sampleRate;\n\n if (info.samples == 0) throw std::runtime_error(\"mp3: could not read any data\");\n\n d->samples.resize(info.samples);\n std::memcpy(d->samples.data(), info.buffer, sizeof(float) * info.samples);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public Interface \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Mp3Decoder::LoadFromPath(AudioData * data, const std::string & path)\n{\n auto fileBuffer = nqr::ReadFile(path);\n mp3_decode_internal(data, fileBuffer.buffer);\n}\n\nvoid Mp3Decoder::LoadFromBuffer(AudioData * data, const std::vector & memory)\n{\n mp3_decode_internal(data, memory);\n}\n\nstd::vector Mp3Decoder::GetSupportedFileExtensions()\n{\n return {\"mp3\"};\n}\nFix memory leak when decoding mp3 file.\/*\n Copyright (c) 2019, Dimitri Diakopoulos All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Decoders.h\"\n\nusing namespace nqr;\n\n#include \"mpc\/mpcdec.h\"\n#include \"mpc\/reader.h\"\n#include \"musepack\/libmpcdec\/decoder.h\"\n#include \"musepack\/libmpcdec\/internal.h\"\n\n#define MINIMP3_FLOAT_OUTPUT\n#define MINIMP3_IMPLEMENTATION\n#include \"minimp3\/minimp3.h\"\n#include \"minimp3\/minimp3_ex.h\"\n\n#include \n\nvoid mp3_decode_internal(AudioData * d, const std::vector & fileData)\n{\n mp3dec_t mp3d;\n mp3dec_file_info_t info;\n mp3dec_load_buf(&mp3d, (const uint8_t*)fileData.data(), fileData.size(), &info, 0, 0);\n\n d->sampleRate = info.hz;\n d->channelCount = info.channels;\n d->sourceFormat = MakeFormatForBits(32, true, false);\n d->lengthSeconds = ((float)info.samples \/ (float)d->channelCount) \/ (float)d->sampleRate;\n\n if (info.samples == 0) throw std::runtime_error(\"mp3: could not read any data\");\n\n d->samples.resize(info.samples);\n std::memcpy(d->samples.data(), info.buffer, sizeof(float) * info.samples);\n\n delete info.buffer;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public Interface \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Mp3Decoder::LoadFromPath(AudioData * data, const std::string & path)\n{\n auto fileBuffer = nqr::ReadFile(path);\n mp3_decode_internal(data, fileBuffer.buffer);\n}\n\nvoid Mp3Decoder::LoadFromBuffer(AudioData * data, const std::vector & memory)\n{\n mp3_decode_internal(data, memory);\n}\n\nstd::vector Mp3Decoder::GetSupportedFileExtensions()\n{\n return {\"mp3\"};\n}\n<|endoftext|>"} {"text":"#include \"contractor\/files.hpp\"\n#include \"contractor\/graph_contractor_adaptors.hpp\"\n\n#include \"..\/common\/range_tools.hpp\"\n#include \"..\/common\/temporary_file.hpp\"\n#include \"helper.hpp\"\n\n#include \n\nBOOST_AUTO_TEST_SUITE(tar)\n\nusing namespace osrm;\nusing namespace osrm::contractor;\nusing namespace osrm::unit_test;\n\nBOOST_AUTO_TEST_CASE(read_write_hsgr)\n{\n auto reference_checksum = 0xFF00FF00;\n auto reference_connectivity_checksum = 0xDEADBEEF;\n std::vector edges = {TestEdge{0, 1, 3},\n TestEdge{0, 5, 1},\n TestEdge{1, 3, 3},\n TestEdge{1, 4, 1},\n TestEdge{3, 1, 1},\n TestEdge{4, 3, 1},\n TestEdge{5, 1, 1}};\n auto reference_graph = QueryGraph{6, toEdges(makeGraph(edges))};\n std::vector> reference_filters = {\n {false, false, true, true, false, false, true},\n {true, false, true, false, true, false, true},\n {false, false, false, false, false, false, false},\n {true, true, true, true, true, true, true},\n };\n\n std::unordered_map reference_metrics = {\n {\"duration\", {std::move(reference_graph), std::move(reference_filters)}}};\n\n TemporaryFile tmp{TEST_DATA_DIR \"\/read_write_hsgr_test.osrm.hsgr\"};\n contractor::files::writeGraph(\n tmp.path, reference_checksum, reference_metrics, reference_connectivity_checksum);\n\n unsigned checksum;\n unsigned connectivity_checksum;\n\n std::unordered_map metrics = {{\"duration\", {}}};\n contractor::files::readGraph(tmp.path, checksum, metrics, connectivity_checksum);\n\n BOOST_CHECK_EQUAL(checksum, reference_checksum);\n BOOST_CHECK_EQUAL(connectivity_checksum, reference_connectivity_checksum);\n BOOST_CHECK_EQUAL(metrics[\"duration\"].edge_filter.size(),\n reference_metrics[\"duration\"].edge_filter.size());\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[0],\n reference_metrics[\"duration\"].edge_filter[0]);\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[1],\n reference_metrics[\"duration\"].edge_filter[1]);\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[2],\n reference_metrics[\"duration\"].edge_filter[2]);\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[3],\n reference_metrics[\"duration\"].edge_filter[3]);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nFix unit-test compilation due to broken readGraph#include \"contractor\/files.hpp\"\n#include \"contractor\/graph_contractor_adaptors.hpp\"\n\n#include \"..\/common\/range_tools.hpp\"\n#include \"..\/common\/temporary_file.hpp\"\n#include \"helper.hpp\"\n\n#include \n\nBOOST_AUTO_TEST_SUITE(tar)\n\nusing namespace osrm;\nusing namespace osrm::contractor;\nusing namespace osrm::unit_test;\n\nBOOST_AUTO_TEST_CASE(read_write_hsgr)\n{\n auto reference_connectivity_checksum = 0xDEADBEEF;\n std::vector edges = {TestEdge{0, 1, 3},\n TestEdge{0, 5, 1},\n TestEdge{1, 3, 3},\n TestEdge{1, 4, 1},\n TestEdge{3, 1, 1},\n TestEdge{4, 3, 1},\n TestEdge{5, 1, 1}};\n auto reference_graph = QueryGraph{6, toEdges(makeGraph(edges))};\n std::vector> reference_filters = {\n {false, false, true, true, false, false, true},\n {true, false, true, false, true, false, true},\n {false, false, false, false, false, false, false},\n {true, true, true, true, true, true, true},\n };\n\n std::unordered_map reference_metrics = {\n {\"duration\", {std::move(reference_graph), std::move(reference_filters)}}};\n\n TemporaryFile tmp{TEST_DATA_DIR \"\/read_write_hsgr_test.osrm.hsgr\"};\n contractor::files::writeGraph(tmp.path, reference_metrics, reference_connectivity_checksum);\n\n unsigned connectivity_checksum;\n\n std::unordered_map metrics = {{\"duration\", {}}};\n contractor::files::readGraph(tmp.path, metrics, connectivity_checksum);\n\n BOOST_CHECK_EQUAL(connectivity_checksum, reference_connectivity_checksum);\n BOOST_CHECK_EQUAL(metrics[\"duration\"].edge_filter.size(),\n reference_metrics[\"duration\"].edge_filter.size());\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[0],\n reference_metrics[\"duration\"].edge_filter[0]);\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[1],\n reference_metrics[\"duration\"].edge_filter[1]);\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[2],\n reference_metrics[\"duration\"].edge_filter[2]);\n CHECK_EQUAL_COLLECTIONS(metrics[\"duration\"].edge_filter[3],\n reference_metrics[\"duration\"].edge_filter[3]);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test\/syscalls\/linux\/socket_stream_blocking.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/time\/clock.h\"\n#include \"absl\/time\/time.h\"\n#include \"test\/syscalls\/linux\/socket_test_util.h\"\n#include \"test\/syscalls\/linux\/unix_domain_socket_test_util.h\"\n#include \"test\/util\/test_util.h\"\n#include \"test\/util\/thread_util.h\"\n#include \"test\/util\/timer_util.h\"\n\nnamespace gvisor {\nnamespace testing {\n\nTEST_P(BlockingStreamSocketPairTest, BlockPartialWriteClosed) {\n \/\/ FIXME: gVisor doesn't support SO_SNDBUF on UDS, nor does it\n \/\/ enforce any limit; it will write arbitrary amounts of data without\n \/\/ blocking.\n SKIP_IF(IsRunningOnGvisor());\n\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n int buffer_size;\n socklen_t length = sizeof(buffer_size);\n ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDBUF,\n &buffer_size, &length),\n SyscallSucceeds());\n\n int wfd = sockets->first_fd();\n ScopedThread t([wfd, buffer_size]() {\n std::vector buf(2 * buffer_size);\n \/\/ Write more than fits in the buffer. Blocks then returns partial write\n \/\/ when the other end is closed. The next call returns EPIPE.\n \/\/\n \/\/ N.B. writes occur in chunks, so we may see less than buffer_size from\n \/\/ the first call.\n ASSERT_THAT(write(wfd, buf.data(), buf.size()),\n SyscallSucceedsWithValue(::testing::Gt(0)));\n ASSERT_THAT(write(wfd, buf.data(), buf.size()),\n ::testing::AnyOf(SyscallFailsWithErrno(EPIPE),\n SyscallFailsWithErrno(ECONNRESET)));\n });\n\n \/\/ Leave time for write to become blocked.\n absl::SleepFor(absl::Seconds(1.0));\n\n ASSERT_THAT(close(sockets->release_second_fd()), SyscallSucceeds());\n}\n\nTEST_P(BlockingStreamSocketPairTest, SendMsgTooLarge) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n int sndbuf;\n socklen_t length = sizeof(sndbuf);\n ASSERT_THAT(\n getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDBUF, &sndbuf, &length),\n SyscallSucceeds());\n\n \/\/ Make the call too large to fit in the send buffer.\n const int buffer_size = 3 * sndbuf;\n\n EXPECT_THAT(SendLargeSendMsg(sockets, buffer_size, true \/* reader *\/),\n SyscallSucceedsWithValue(buffer_size));\n}\n\nTEST_P(BlockingStreamSocketPairTest, RecvLessThanBuffer) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n char sent_data[100];\n RandomizeBuffer(sent_data, sizeof(sent_data));\n\n ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n\n char received_data[200] = {};\n ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,\n sizeof(received_data), 0),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n}\n\n\/\/ Test that MSG_WAITALL causes recv to block until all requested data is\n\/\/ received. Random save can interrupt blocking and cause received data to be\n\/\/ returned, even if the amount received is less than the full requested amount.\nTEST_P(BlockingStreamSocketPairTest, RecvLessThanBufferWaitAll_NoRandomSave) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n char sent_data[100];\n RandomizeBuffer(sent_data, sizeof(sent_data));\n\n ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n\n constexpr auto kDuration = absl::Milliseconds(200);\n auto before = Now(CLOCK_MONOTONIC);\n\n const ScopedThread t([&]() {\n absl::SleepFor(kDuration);\n\n \/\/ Don't let saving after the write interrupt the blocking recv.\n const DisableSave ds;\n\n ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n });\n\n char received_data[sizeof(sent_data) * 2] = {};\n ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,\n sizeof(received_data), MSG_WAITALL),\n SyscallSucceedsWithValue(sizeof(received_data)));\n\n auto after = Now(CLOCK_MONOTONIC);\n EXPECT_GE(after - before, kDuration);\n}\n\nTEST_P(BlockingStreamSocketPairTest, SendTimeout) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n struct timeval tv {\n .tv_sec = 0, .tv_usec = 10\n };\n EXPECT_THAT(\n setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),\n SyscallSucceeds());\n\n char buf[100] = {};\n for (;;) {\n int ret;\n ASSERT_THAT(\n ret = RetryEINTR(send)(sockets->first_fd(), buf, sizeof(buf), 0),\n ::testing::AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EAGAIN)));\n if (ret == -1) {\n break;\n }\n }\n}\n\n} \/\/ namespace testing\n} \/\/ namespace gvisor\nDeflake socket_stream_blocking tests.\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test\/syscalls\/linux\/socket_stream_blocking.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/time\/clock.h\"\n#include \"absl\/time\/time.h\"\n#include \"test\/syscalls\/linux\/socket_test_util.h\"\n#include \"test\/syscalls\/linux\/unix_domain_socket_test_util.h\"\n#include \"test\/util\/test_util.h\"\n#include \"test\/util\/thread_util.h\"\n#include \"test\/util\/timer_util.h\"\n\nnamespace gvisor {\nnamespace testing {\n\nTEST_P(BlockingStreamSocketPairTest, BlockPartialWriteClosed) {\n \/\/ FIXME: gVisor doesn't support SO_SNDBUF on UDS, nor does it\n \/\/ enforce any limit; it will write arbitrary amounts of data without\n \/\/ blocking.\n SKIP_IF(IsRunningOnGvisor());\n\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n int buffer_size;\n socklen_t length = sizeof(buffer_size);\n ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDBUF,\n &buffer_size, &length),\n SyscallSucceeds());\n\n int wfd = sockets->first_fd();\n ScopedThread t([wfd, buffer_size]() {\n std::vector buf(2 * buffer_size);\n \/\/ Write more than fits in the buffer. Blocks then returns partial write\n \/\/ when the other end is closed. The next call returns EPIPE.\n \/\/\n \/\/ N.B. writes occur in chunks, so we may see less than buffer_size from\n \/\/ the first call.\n ASSERT_THAT(write(wfd, buf.data(), buf.size()),\n SyscallSucceedsWithValue(::testing::Gt(0)));\n ASSERT_THAT(write(wfd, buf.data(), buf.size()),\n ::testing::AnyOf(SyscallFailsWithErrno(EPIPE),\n SyscallFailsWithErrno(ECONNRESET)));\n });\n\n \/\/ Leave time for write to become blocked.\n absl::SleepFor(absl::Seconds(1));\n\n ASSERT_THAT(close(sockets->release_second_fd()), SyscallSucceeds());\n}\n\n\/\/ Random save may interrupt the call to sendmsg() in SendLargeSendMsg(),\n\/\/ causing the write to be incomplete and the test to hang.\nTEST_P(BlockingStreamSocketPairTest, SendMsgTooLarge_NoRandomSave) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n int sndbuf;\n socklen_t length = sizeof(sndbuf);\n ASSERT_THAT(\n getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDBUF, &sndbuf, &length),\n SyscallSucceeds());\n\n \/\/ Make the call too large to fit in the send buffer.\n const int buffer_size = 3 * sndbuf;\n\n EXPECT_THAT(SendLargeSendMsg(sockets, buffer_size, true \/* reader *\/),\n SyscallSucceedsWithValue(buffer_size));\n}\n\nTEST_P(BlockingStreamSocketPairTest, RecvLessThanBuffer) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n char sent_data[100];\n RandomizeBuffer(sent_data, sizeof(sent_data));\n\n ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n\n char received_data[200] = {};\n ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,\n sizeof(received_data), 0),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n}\n\n\/\/ Test that MSG_WAITALL causes recv to block until all requested data is\n\/\/ received. Random save can interrupt blocking and cause received data to be\n\/\/ returned, even if the amount received is less than the full requested amount.\nTEST_P(BlockingStreamSocketPairTest, RecvLessThanBufferWaitAll_NoRandomSave) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n char sent_data[100];\n RandomizeBuffer(sent_data, sizeof(sent_data));\n\n ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n\n constexpr auto kDuration = absl::Milliseconds(200);\n auto before = Now(CLOCK_MONOTONIC);\n\n const ScopedThread t([&]() {\n absl::SleepFor(kDuration);\n\n \/\/ Don't let saving after the write interrupt the blocking recv.\n const DisableSave ds;\n\n ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n SyscallSucceedsWithValue(sizeof(sent_data)));\n });\n\n char received_data[sizeof(sent_data) * 2] = {};\n ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,\n sizeof(received_data), MSG_WAITALL),\n SyscallSucceedsWithValue(sizeof(received_data)));\n\n auto after = Now(CLOCK_MONOTONIC);\n EXPECT_GE(after - before, kDuration);\n}\n\nTEST_P(BlockingStreamSocketPairTest, SendTimeout) {\n auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n\n struct timeval tv {\n .tv_sec = 0, .tv_usec = 10\n };\n EXPECT_THAT(\n setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),\n SyscallSucceeds());\n\n std::vector buf(kPageSize);\n \/\/ We don't know how much data the socketpair will buffer, so we may do an\n \/\/ arbitrarily large number of writes; saving after each write causes this\n \/\/ test's time to explode.\n const DisableSave ds;\n for (;;) {\n int ret;\n ASSERT_THAT(\n ret = RetryEINTR(send)(sockets->first_fd(), buf.data(), buf.size(), 0),\n ::testing::AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EAGAIN)));\n if (ret == -1) {\n break;\n }\n }\n}\n\n} \/\/ namespace testing\n} \/\/ namespace gvisor\n<|endoftext|>"} {"text":"\/\/===--------------- test_exception_storage_nodynmem.cpp ------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ UNSUPPORTED: libcxxabi-no-exceptions\n\n\/\/ cxa_exception_storage does not use dynamic memory in the single thread mode.\n\/\/ UNSUPPORTED: libcpp-has-no-threads\n\n\/\/ Our overwritten calloc() is not compatible with these sanitizers.\n\/\/ UNSUPPORTED: msan, tsan\n\n#include \n#include \n\nstatic bool OverwrittenCallocCalled = false;\n\n\/\/ Override calloc to simulate exhaustion of dynamic memory\nvoid *calloc(size_t, size_t) {\n OverwrittenCallocCalled = true;\n return 0;\n}\n\nint main(int argc, char *argv[]) {\n \/\/ Run the test a couple of times\n \/\/ to ensure that fallback memory doesn't leak.\n for (int I = 0; I < 1000; ++I)\n try {\n throw 42;\n } catch (...) {\n }\n\n assert(OverwrittenCallocCalled);\n return 0;\n}\n[libc++abi] Remove the test for checking using of fallback malloc in case of dynamic memory exhaustion.<|endoftext|>"} {"text":"\/*****************************************************************************\n * Gap2Seq\n * Copyright (C) Leena Salmela, Kristoffer Sahlin, Veli Mäkinen,\n * Alexandru Tomescu, Riku Walve 2017\n *\n * Contact: leena.salmela@cs.helsinki.fi\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*****************************************************************************\/\n\n#include \n\n#include \n#include \n\n\/\/ GATB-core Bloom filter requires hash1 function for items\ninline u_int64_t hash1(const std::string &key, u_int64_t seed = 0)\n{\n (void) seed;\n return std::hash{}(key);\n}\n\n#include \n\n#include \n\n\/*****************************************************************************\/\n\nstatic const char *STR_ALIGNMENT = \"-bam\";\nstatic const char *STR_OUTPUT = \"-reads\";\n\nstatic const char *STR_MEAN = \"-mean\";\nstatic const char *STR_STD_DEV = \"-std-dev\";\n\nstatic const char *STR_SCAFFOLD = \"-scaffold\";\nstatic const char *STR_GAP_BREAKPOINT = \"-breakpoint\";\n\nstatic const char *STR_FLANK_LENGTH = \"-flank-length\";\n\nstatic const char *STR_GAP_LENGTH = \"-gap-length\";\n\/\/ static const char *STR_THRESHOLD = \"-unmapped\";\n\nstatic const char *STR_ONLY_UNMAPPED = \"-unmapped-only\";\n\n\/*****************************************************************************\/\n\nclass io_t\n{\npublic:\n samFile *sam = NULL;\n bam_hdr_t *header = NULL;\n hts_idx_t *idx = NULL;\n bool loaded = false;\n\n io_t(const std::string &);\n\n void unload()\n {\n bam_hdr_destroy(this->header);\n sam_close(this->sam);\n loaded = false;\n }\n};\n\n\/\/ Loads a bam\/sam file into an IO object\nio_t::io_t(const std::string &samFilename)\n{\n this->sam = sam_open(samFilename.c_str(), \"r\");\n if (this->sam == NULL) {\n return;\n }\n\n this->header = sam_hdr_read(this->sam);\n if (this->header == NULL) {\n return;\n }\n\n this->idx = sam_index_load(this->sam, samFilename.c_str());\n if (this->idx == NULL) {\n return;\n }\n\n this->loaded = true;\n}\n\n\/*****************************************************************************\/\n\ninline uint8_t complement(const uint8_t n)\n{\n switch (n) {\n case 1:\n return 8;\n case 2:\n return 4;\n case 4:\n return 2;\n case 8:\n return 1;\n case 15:\n default:\n return 15;\n }\n}\n\ninline uint8_t querySequence(const uint8_t *query, const int32_t length,\n const int32_t index, const bool reverse)\n{\n if (!reverse) {\n return bam_seqi(query, index);\n }\n\n return complement(bam_seqi(query, length - 1 - index));\n}\n\n\/*****************************************************************************\/\n\n\/\/ Converts an alignment to std::string. Handles reverse complements.\nstd::string convertToString(const uint8_t *query, const int32_t length,\n const bool reverse, char *buffer)\n{\n for (int32_t i = 0; i < length; i++) {\n switch (querySequence(query, length, i, reverse)) {\n case 0x1:\n buffer[i] = 'A';\n break;\n case 0x2:\n buffer[i] = 'C';\n break;\n case 0x4:\n buffer[i] = 'G';\n break;\n case 0x8:\n buffer[i] = 'T';\n break;\n case 0x15:\n default:\n buffer[i] = 'N';\n break;\n }\n }\n\n buffer[length] = '\\0';\n return std::string(buffer);\n}\n\n\/*****************************************************************************\/\n\nstatic inline const std::string bam2string(const bam1_t *bam)\n{\n return std::string(bam_get_qname(bam)) + (((bam->core.flag & BAM_FREAD1) != 0) ? \"\/1\" : \"\/2\");\n}\n\nstatic inline const std::string bam2string_mate(const bam1_t *bam)\n{\n return std::string(bam_get_qname(bam)) + (((bam->core.flag & BAM_FREAD1) != 0) ? \"\/2\" : \"\/1\");\n}\n\n\/*****************************************************************************\/\n\nclass sam_iterator\n{\nprivate:\n samFile *m_sam;\n hts_itr_t *m_iter;\n\npublic:\n bam1_t *bam;\n\n sam_iterator(const io_t io, const int tid, const int start, const int end)\n : m_sam(io.sam), bam(bam_init1())\n {\n m_iter = sam_itr_queryi(io.idx, tid, start, end);\n if (m_iter == NULL) {\n std::cerr << \"WARNING: SAM iterator is NULL!\" << std::endl;\n }\n }\n\n sam_iterator(const io_t io, const char *string)\n : m_sam(io.sam), bam(bam_init1())\n {\n m_iter = sam_itr_querys(io.idx, io.header, string);\n if (m_iter == NULL) {\n std::cerr << \"WARNING: SAM iterator is NULL!\" << std::endl;\n }\n }\n\n ~sam_iterator()\n {\n hts_itr_destroy(m_iter);\n bam_destroy1(bam);\n }\n\n inline bool next()\n {\n if (m_iter == NULL) {\n return false;\n }\n\n return (sam_itr_next(m_sam, m_iter, bam) >= 0);\n }\n};\n\n\/\/ Counts the number of reads by iterating through the alignment file\nuint64_t count_reads(const std::string &filename, int32_t *read_length)\n{\n io_t io(filename);\n sam_iterator iter(io, \".\");\n\n uint64_t count = 0;\n int32_t max_length = 0;\n while (iter.next()) {\n count++;\n max_length = max(max_length, iter.bam->core.l_qseq);\n }\n\n io.unload();\n *read_length = max_length;\n return count;\n}\n\n\/*****************************************************************************\/\n\nclass ReadFilter : public Tool\n{\npublic:\n ReadFilter();\n void execute();\n\n \/\/ Prints an alignment in fasta format\n void print_fasta(const bam1_t *, char *, BankFasta *);\n\n \/\/ Prints all alignments in a region\n void process_region(const io_t &, const int, const int, const int, char *, IBloom *, BankFasta *, int *, int *);\n void process_mates(const io_t &, const int, const int, const int, IBloom *);\n void find_mates(const io_t &, char *, IBloom *, BankFasta *, int *, int *);\n void process_unmapped(const io_t &, char *, IBloom *, BankFasta *, int *);\n};\n\nReadFilter::ReadFilter() : Tool(\"ReadFilter\")\n{\n \/\/ Input \/ output\n getParser()->push_front(new OptionOneParam(STR_ALIGNMENT, \"Aligned BAM file\", true));\n getParser()->push_front(new OptionOneParam(STR_OUTPUT, \"FASTA-formatted output file\", true));\n\n \/\/ Read library parameters\n getParser()->push_front(new OptionOneParam(STR_MEAN, \"Mean insert size\", true));\n getParser()->push_front(new OptionOneParam(STR_STD_DEV, \"Insert size standard deviation\", true));\n\n \/\/ Gap parameters\n getParser()->push_front(new OptionOneParam(STR_SCAFFOLD, \"Scaffold name\", true));\n getParser()->push_front(new OptionOneParam(STR_GAP_BREAKPOINT, \"Gap breakpoint position\", true));\n getParser()->push_front(new OptionOneParam(STR_GAP_LENGTH, \"Gap length (in the scaffold)\", false, \"-1\"));\n getParser()->push_front(new OptionOneParam(STR_FLANK_LENGTH, \"Flank length\", false, \"-1\"));\n\n getParser()->push_front(new OptionNoParam(STR_ONLY_UNMAPPED, \"Output unmapped reads\"));\n}\n\n\/*****************************************************************************\/\n\n\/\/ Output a bam object into GATB fasta bank\nvoid ReadFilter::print_fasta(const bam1_t *bam, char *buffer, BankFasta *bank)\n{\n const std::string sequence = convertToString(bam_get_seq(bam),\n bam->core.l_qseq, bam_is_rev(bam), buffer);\n\n Sequence seq(buffer);\n seq._comment = bam2string(bam);\n bank->insert(seq);\n}\n\n\/\/ Output reads that map to a region in a scaffold and not in the Bloom filter.\nvoid ReadFilter::process_region(const io_t &io, const int tid, const int start,\n const int end, char *buffer, IBloom *bloom, BankFasta *bank,\n int *seqlen, int *num_of_reads)\n{\n sam_iterator iter(io, tid, start, end);\n while (iter.next()) {\n if (!bloom->contains(bam2string(iter.bam))) {\n print_fasta(iter.bam, buffer, bank);\n *seqlen += strlen(buffer);\n (*num_of_reads)++;\n }\n }\n}\n\n\/\/ Add read mates to Bloom filter\nvoid ReadFilter::process_mates(const io_t &io, const int tid, const int start,\n const int end, IBloom *bloom)\n{\n sam_iterator iter(io, tid, start, end);\n while (iter.next()) {\n if ((iter.bam->core.flag & BAM_FMUNMAP) != 0) {\n bloom->insert(bam2string(iter.bam));\n }\n }\n}\n\n\/\/ Output read mates from Bloom filter\nvoid ReadFilter::find_mates(const io_t &io, char *buffer, IBloom *bloom,\n BankFasta *bank, int *seqlen, int *num_of_reads)\n{\n sam_iterator iter(io, \".\");\n while (iter.next()) {\n if (bloom->contains(bam2string_mate(iter.bam))) {\n print_fasta(iter.bam, buffer, bank);\n *seqlen += strlen(buffer);\n (*num_of_reads)++;\n }\n }\n}\n\n\/\/ Output all unmapped reads\nvoid ReadFilter::process_unmapped(const io_t &io, char *buffer,\n IBloom *bloom, BankFasta *bank, int *num_of_reads)\n{\n sam_iterator iter(io, \".\");\n while (iter.next()) {\n if ((iter.bam->core.flag & BAM_FUNMAP) != 0 &&\n !bloom->contains(bam2string(iter.bam))) {\n print_fasta(iter.bam, buffer, bank);\n (*num_of_reads)++;\n }\n }\n}\n\nvoid ReadFilter::execute()\n{\n const std::string alignment = getInput()->getStr(STR_ALIGNMENT);\n const std::string output = getInput()->getStr(STR_OUTPUT);\n\n const int mean_insert = static_cast(getInput()->getInt(STR_MEAN));\n const int std_dev = static_cast(getInput()->getInt(STR_STD_DEV));\n\n const std::string scaffold = getInput()->getStr(STR_SCAFFOLD);\n const int breakpoint = static_cast(getInput()->getInt(STR_GAP_BREAKPOINT));\n const int flank_length = static_cast(getInput()->getInt(STR_FLANK_LENGTH));\n const int gap_length = static_cast(getInput()->getInt(STR_GAP_LENGTH));\n\n const bool unmapped_only = getParser()->saw(STR_ONLY_UNMAPPED);\n\n \/\/ Load alignment file\n io_t io(alignment);\n if (!io.loaded) {\n std::cerr << \"Error loading alignments\" << std::endl;\n return;\n }\n\n \/\/ Use basic Bloom filter from GATB\n int32_t read_length = 0;\n const uint64_t num_of_reads = count_reads(alignment, &read_length);\n IBloom *bloom = new BloomSynchronized(5 * num_of_reads);\n\n \/\/ Allocate memory for string conversions\n char *buffer = new char[read_length + 1];\n\n \/\/ Open output file\n BankFasta reads(output);\n int seqlen = 0, reads_extracted = 0;\n\n if (!unmapped_only) {\n \/\/ Compute scaffold id from scaffold name\n const int tid = bam_name2id(io.header, scaffold.c_str());\n\n \/\/ Extract pairs from the left mappings\n const int left_start = breakpoint - (mean_insert + 3 * std_dev + 2 * read_length);\n const int left_end = breakpoint - (mean_insert - 3 * std_dev + read_length);\n process_mates(io, tid, left_start, left_end, bloom);\n\n \/\/ Extract pairs from the right mappings\n const int right_start = breakpoint + (mean_insert + 3 * std_dev + read_length) + gap_length;\n const int right_end = breakpoint + (mean_insert - 3 * std_dev + read_length) + gap_length;\n process_mates(io, tid, right_start, right_end, bloom);\n\n \/\/ Output reads and count length\n find_mates(io, buffer, bloom, &reads, &seqlen, &reads_extracted);\n\n \/\/ Output overlapping reads\n if (flank_length != -1) {\n const int start = breakpoint - flank_length;\n const int end = breakpoint + flank_length + gap_length;\n process_region(io, tid, start, end, buffer, bloom, &reads, &seqlen, &reads_extracted);\n }\n }\n\n \/\/ Output unmapped reads\n if (unmapped_only) {\n process_unmapped(io, buffer, bloom, &reads, &reads_extracted);\n }\n\n std::cout << \"Extracted \" << reads_extracted << \" out of \" << num_of_reads << \" reads\" << std::endl;\n\n \/\/ Cleanup\n reads.flush();\n delete[] buffer;\n delete bloom;\n io.unload();\n}\n\nint main(int argc, char *argv[])\n{\n try {\n ReadFilter().run(argc, argv);\n } catch (Exception &e) {\n std::cout << \"EXCEPTION: \" << e.getMessage() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\ninclude subset of GATB in ReadFilter to fix definition conflicts\/*****************************************************************************\n * Gap2Seq\n * Copyright (C) Leena Salmela, Kristoffer Sahlin, Veli Mäkinen,\n * Alexandru Tomescu, Riku Walve 2017\n *\n * Contact: leena.salmela@cs.helsinki.fi\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*****************************************************************************\/\n\n#include \n\n#include \n#include \n\n\/\/ GATB-core Bloom filter requires hash1 function for items\ninline u_int64_t hash1(const std::string &key, u_int64_t seed = 0)\n{\n (void) seed;\n return std::hash{}(key);\n}\n\n#include \n#include \n#include \n\n#include \n\nusing namespace gatb::core::tools::misc;\nusing namespace gatb::core::tools::misc::impl;\nusing namespace gatb::core::tools::collections;\nusing namespace gatb::core::tools::collections::impl;\nusing namespace gatb::core::bank;\nusing namespace gatb::core::bank::impl;\n\n\/*****************************************************************************\/\n\nstatic const char *STR_ALIGNMENT = \"-bam\";\nstatic const char *STR_OUTPUT = \"-reads\";\n\nstatic const char *STR_MEAN = \"-mean\";\nstatic const char *STR_STD_DEV = \"-std-dev\";\n\nstatic const char *STR_SCAFFOLD = \"-scaffold\";\nstatic const char *STR_GAP_BREAKPOINT = \"-breakpoint\";\n\nstatic const char *STR_FLANK_LENGTH = \"-flank-length\";\nstatic const char *STR_GAP_LENGTH = \"-gap-length\";\n\nstatic const char *STR_ONLY_UNMAPPED = \"-unmapped-only\";\n\n\/*****************************************************************************\/\n\nclass io_t\n{\npublic:\n samFile *sam = NULL;\n bam_hdr_t *header = NULL;\n hts_idx_t *idx = NULL;\n bool loaded = false;\n\n io_t(const std::string &);\n\n void unload()\n {\n bam_hdr_destroy(this->header);\n sam_close(this->sam);\n loaded = false;\n }\n};\n\n\/\/ Loads a bam\/sam file into an IO object\nio_t::io_t(const std::string &samFilename)\n{\n this->sam = sam_open(samFilename.c_str(), \"r\");\n if (this->sam == NULL) {\n return;\n }\n\n this->header = sam_hdr_read(this->sam);\n if (this->header == NULL) {\n return;\n }\n\n this->idx = sam_index_load(this->sam, samFilename.c_str());\n if (this->idx == NULL) {\n return;\n }\n\n this->loaded = true;\n}\n\n\/*****************************************************************************\/\n\ninline uint8_t complement(const uint8_t n)\n{\n switch (n) {\n case 1:\n return 8;\n case 2:\n return 4;\n case 4:\n return 2;\n case 8:\n return 1;\n case 15:\n default:\n return 15;\n }\n}\n\ninline uint8_t querySequence(const uint8_t *query, const int32_t length,\n const int32_t index, const bool reverse)\n{\n if (!reverse) {\n return bam_seqi(query, index);\n }\n\n return complement(bam_seqi(query, length - 1 - index));\n}\n\n\/*****************************************************************************\/\n\n\/\/ Converts an alignment to std::string. Handles reverse complements.\nstd::string convertToString(const uint8_t *query, const int32_t length,\n const bool reverse, char *buffer)\n{\n for (int32_t i = 0; i < length; i++) {\n switch (querySequence(query, length, i, reverse)) {\n case 0x1:\n buffer[i] = 'A';\n break;\n case 0x2:\n buffer[i] = 'C';\n break;\n case 0x4:\n buffer[i] = 'G';\n break;\n case 0x8:\n buffer[i] = 'T';\n break;\n case 0x15:\n default:\n buffer[i] = 'N';\n break;\n }\n }\n\n buffer[length] = '\\0';\n return std::string(buffer);\n}\n\n\/*****************************************************************************\/\n\nstatic inline const std::string bam2string(const bam1_t *bam)\n{\n return std::string(bam_get_qname(bam)) + (((bam->core.flag & BAM_FREAD1) != 0) ? \"\/1\" : \"\/2\");\n}\n\nstatic inline const std::string bam2string_mate(const bam1_t *bam)\n{\n return std::string(bam_get_qname(bam)) + (((bam->core.flag & BAM_FREAD1) != 0) ? \"\/2\" : \"\/1\");\n}\n\n\/*****************************************************************************\/\n\nclass sam_iterator\n{\nprivate:\n samFile *m_sam;\n hts_itr_t *m_iter;\n\npublic:\n bam1_t *bam;\n\n sam_iterator(const io_t io, const int tid, const int start, const int end)\n : m_sam(io.sam), bam(bam_init1())\n {\n m_iter = sam_itr_queryi(io.idx, tid, start, end);\n if (m_iter == NULL) {\n std::cerr << \"WARNING: SAM iterator is NULL!\" << std::endl;\n }\n }\n\n sam_iterator(const io_t io, const char *string)\n : m_sam(io.sam), bam(bam_init1())\n {\n m_iter = sam_itr_querys(io.idx, io.header, string);\n if (m_iter == NULL) {\n std::cerr << \"WARNING: SAM iterator is NULL!\" << std::endl;\n }\n }\n\n ~sam_iterator()\n {\n hts_itr_destroy(m_iter);\n bam_destroy1(bam);\n }\n\n inline bool next()\n {\n if (m_iter == NULL) {\n return false;\n }\n\n return (sam_itr_next(m_sam, m_iter, bam) >= 0);\n }\n};\n\n\/\/ Counts the number of reads by iterating through the alignment file\nuint64_t count_reads(const std::string &filename, int32_t *read_length)\n{\n io_t io(filename);\n sam_iterator iter(io, \".\");\n\n uint64_t count = 0;\n int32_t max_length = 0;\n while (iter.next()) {\n count++;\n max_length = (iter.bam->core.l_qseq > max_length) ? iter.bam->core.l_qseq : max_length;\n }\n\n io.unload();\n *read_length = max_length;\n return count;\n}\n\n\/*****************************************************************************\/\n\nclass ReadFilter : public Tool\n{\npublic:\n ReadFilter();\n void execute();\n\n \/\/ Prints an alignment in fasta format\n void print_fasta(const bam1_t *, char *, BankFasta *);\n\n \/\/ Prints all alignments in a region\n void process_region(const io_t &, const int, const int, const int, char *, IBloom *, BankFasta *, int *, int *);\n void process_mates(const io_t &, const int, const int, const int, IBloom *);\n void find_mates(const io_t &, char *, IBloom *, BankFasta *, int *, int *);\n void process_unmapped(const io_t &, char *, IBloom *, BankFasta *, int *);\n};\n\nReadFilter::ReadFilter() : Tool(\"ReadFilter\")\n{\n \/\/ Input \/ output\n getParser()->push_front(new OptionOneParam(STR_ALIGNMENT, \"Aligned BAM file\", true));\n getParser()->push_front(new OptionOneParam(STR_OUTPUT, \"FASTA-formatted output file\", true));\n\n \/\/ Read library parameters\n getParser()->push_front(new OptionOneParam(STR_MEAN, \"Mean insert size\", true));\n getParser()->push_front(new OptionOneParam(STR_STD_DEV, \"Insert size standard deviation\", true));\n\n \/\/ Gap parameters\n getParser()->push_front(new OptionOneParam(STR_SCAFFOLD, \"Scaffold name\", true));\n getParser()->push_front(new OptionOneParam(STR_GAP_BREAKPOINT, \"Gap breakpoint position\", true));\n getParser()->push_front(new OptionOneParam(STR_GAP_LENGTH, \"Gap length (in the scaffold)\", false, \"-1\"));\n getParser()->push_front(new OptionOneParam(STR_FLANK_LENGTH, \"Flank length\", false, \"-1\"));\n\n getParser()->push_front(new OptionNoParam(STR_ONLY_UNMAPPED, \"Output unmapped reads\"));\n}\n\n\/*****************************************************************************\/\n\n\/\/ Output a bam object into GATB fasta bank\nvoid ReadFilter::print_fasta(const bam1_t *bam, char *buffer, BankFasta *bank)\n{\n const std::string sequence = convertToString(bam_get_seq(bam),\n bam->core.l_qseq, bam_is_rev(bam), buffer);\n\n Sequence seq(buffer);\n seq._comment = bam2string(bam);\n bank->insert(seq);\n}\n\n\/\/ Output reads that map to a region in a scaffold and not in the Bloom filter.\nvoid ReadFilter::process_region(const io_t &io, const int tid, const int start,\n const int end, char *buffer, IBloom *bloom, BankFasta *bank,\n int *seqlen, int *num_of_reads)\n{\n sam_iterator iter(io, tid, start, end);\n while (iter.next()) {\n if (!bloom->contains(bam2string(iter.bam))) {\n print_fasta(iter.bam, buffer, bank);\n *seqlen += strlen(buffer);\n (*num_of_reads)++;\n }\n }\n}\n\n\/\/ Add read mates to Bloom filter\nvoid ReadFilter::process_mates(const io_t &io, const int tid, const int start,\n const int end, IBloom *bloom)\n{\n sam_iterator iter(io, tid, start, end);\n while (iter.next()) {\n if ((iter.bam->core.flag & BAM_FMUNMAP) != 0) {\n bloom->insert(bam2string(iter.bam));\n }\n }\n}\n\n\/\/ Output read mates from Bloom filter\nvoid ReadFilter::find_mates(const io_t &io, char *buffer, IBloom *bloom,\n BankFasta *bank, int *seqlen, int *num_of_reads)\n{\n sam_iterator iter(io, \".\");\n while (iter.next()) {\n if (bloom->contains(bam2string_mate(iter.bam))) {\n print_fasta(iter.bam, buffer, bank);\n *seqlen += strlen(buffer);\n (*num_of_reads)++;\n }\n }\n}\n\n\/\/ Output all unmapped reads\nvoid ReadFilter::process_unmapped(const io_t &io, char *buffer,\n IBloom *bloom, BankFasta *bank, int *num_of_reads)\n{\n sam_iterator iter(io, \".\");\n while (iter.next()) {\n if ((iter.bam->core.flag & BAM_FUNMAP) != 0 &&\n !bloom->contains(bam2string(iter.bam))) {\n print_fasta(iter.bam, buffer, bank);\n (*num_of_reads)++;\n }\n }\n}\n\nvoid ReadFilter::execute()\n{\n const std::string alignment = getInput()->getStr(STR_ALIGNMENT);\n const std::string output = getInput()->getStr(STR_OUTPUT);\n\n const int mean_insert = static_cast(getInput()->getInt(STR_MEAN));\n const int std_dev = static_cast(getInput()->getInt(STR_STD_DEV));\n\n const std::string scaffold = getInput()->getStr(STR_SCAFFOLD);\n const int breakpoint = static_cast(getInput()->getInt(STR_GAP_BREAKPOINT));\n const int flank_length = static_cast(getInput()->getInt(STR_FLANK_LENGTH));\n const int gap_length = static_cast(getInput()->getInt(STR_GAP_LENGTH));\n\n const bool unmapped_only = getParser()->saw(STR_ONLY_UNMAPPED);\n\n \/\/ Load alignment file\n io_t io(alignment);\n if (!io.loaded) {\n std::cerr << \"Error loading alignments\" << std::endl;\n return;\n }\n\n \/\/ Use basic Bloom filter from GATB\n int32_t read_length = 0;\n const uint64_t num_of_reads = count_reads(alignment, &read_length);\n IBloom *bloom = new BloomSynchronized(5 * num_of_reads);\n\n \/\/ Allocate memory for string conversions\n char *buffer = new char[read_length + 1];\n\n \/\/ Open output file\n BankFasta reads(output);\n int seqlen = 0, reads_extracted = 0;\n\n if (!unmapped_only) {\n \/\/ Compute scaffold id from scaffold name\n const int tid = bam_name2id(io.header, scaffold.c_str());\n\n \/\/ Extract pairs from the left mappings\n const int left_start = breakpoint - (mean_insert + 3 * std_dev + 2 * read_length);\n const int left_end = breakpoint - (mean_insert - 3 * std_dev + read_length);\n process_mates(io, tid, left_start, left_end, bloom);\n\n \/\/ Extract pairs from the right mappings\n const int right_start = breakpoint + (mean_insert + 3 * std_dev + read_length) + gap_length;\n const int right_end = breakpoint + (mean_insert - 3 * std_dev + read_length) + gap_length;\n process_mates(io, tid, right_start, right_end, bloom);\n\n \/\/ Output reads and count length\n find_mates(io, buffer, bloom, &reads, &seqlen, &reads_extracted);\n\n \/\/ Output overlapping reads\n if (flank_length != -1) {\n const int start = breakpoint - flank_length;\n const int end = breakpoint + flank_length + gap_length;\n process_region(io, tid, start, end, buffer, bloom, &reads, &seqlen, &reads_extracted);\n }\n }\n\n \/\/ Output unmapped reads\n if (unmapped_only) {\n process_unmapped(io, buffer, bloom, &reads, &reads_extracted);\n }\n\n std::cout << \"Extracted \" << reads_extracted << \" out of \" << num_of_reads << \" reads\" << std::endl;\n\n \/\/ Cleanup\n reads.flush();\n delete[] buffer;\n delete bloom;\n io.unload();\n}\n\nint main(int argc, char *argv[])\n{\n ReadFilter().run(argc, argv);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"common.h\"\n\nconst char *SVMPointerPassing_test_kernel[] = {\n \"__kernel void verify_char(__global uchar* pChar, volatile __global uint* num_correct, uchar expected)\\n\"\n \"{\\n\"\n \" if(0 == get_global_id(0))\\n\"\n \" {\\n\"\n \" *num_correct = 0;\\n\"\n \" if(*pChar == expected)\\n\"\n \" {\\n\"\n \" *num_correct=1;\\n\"\n \" }\\n\"\n \" }\\n\"\n \"}\\n\"\n};\n\n\n\/\/ Test that arbitrarily aligned char pointers into shared buffers can be passed directly to a kernel.\n\/\/ This iterates through a buffer passing a pointer to each location to the kernel.\n\/\/ The buffer is initialized to known values at each location.\n\/\/ The kernel checks that it finds the expected value at each location.\n\/\/ TODO: possibly make this work across all base types (including typeN?), also check ptr arithmetic ++,--.\nint test_svm_pointer_passing(cl_device_id deviceID, cl_context context2, cl_command_queue queue, int num_elements)\n{\n clContextWrapper context = NULL;\n clProgramWrapper program = NULL;\n cl_uint num_devices = 0;\n cl_int error = CL_SUCCESS;\n clCommandQueueWrapper queues[MAXQ];\n\n error = create_cl_objects(deviceID, &SVMPointerPassing_test_kernel[0], &context, &program, &queues[0], &num_devices, CL_DEVICE_SVM_COARSE_GRAIN_BUFFER);\n if(error) return -1;\n\n clKernelWrapper kernel_verify_char = clCreateKernel(program, \"verify_char\", &error);\n test_error(error,\"clCreateKernel failed\");\n\n size_t bufSize = 256;\n char *pbuf = (char*) clSVMAlloc(context, CL_MEM_READ_WRITE, sizeof(cl_uchar)*bufSize, 0);\n\n cl_int *pNumCorrect = NULL;\n pNumCorrect = (cl_int*) clSVMAlloc(context, CL_MEM_READ_WRITE, sizeof(cl_int), 0);\n\n {\n clMemWrapper buf = clCreateBuffer(context, CL_MEM_USE_HOST_PTR, sizeof(cl_uchar)*bufSize, pbuf, &error);\n test_error(error, \"clCreateBuffer failed.\");\n\n clMemWrapper num_correct = clCreateBuffer(context, CL_MEM_USE_HOST_PTR, sizeof(cl_int), pNumCorrect, &error);\n test_error(error, \"clCreateBuffer failed.\");\n\n error = clSetKernelArg(kernel_verify_char, 1, sizeof(void*), (void *) &num_correct);\n test_error(error, \"clSetKernelArg failed\");\n\n \/\/ put values into buf so that we can expect to see these values in the kernel when we pass a pointer to them.\n cl_command_queue cmdq = queues[0];\n cl_uchar* pBuf = (cl_uchar*) clEnqueueMapBuffer(cmdq, buf, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(cl_uchar)*bufSize, 0, NULL,NULL, &error);\n test_error2(error, pBuf, \"clEnqueueMapBuffer failed\");\n for(int i = 0; i<(int)bufSize; i++)\n {\n pBuf[i]= (cl_uchar)i;\n }\n error = clEnqueueUnmapMemObject(cmdq, buf, pBuf, 0,NULL,NULL);\n test_error(error, \"clEnqueueUnmapMemObject failed.\");\n\n for (cl_uint ii = 0; iiTest SVM: Fix - do not use unmapped pointer. (#661)\/\/\n\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"common.h\"\n\nconst char *SVMPointerPassing_test_kernel[] = {\n \"__kernel void verify_char(__global uchar* pChar, volatile __global uint* num_correct, uchar expected)\\n\"\n \"{\\n\"\n \" if(0 == get_global_id(0))\\n\"\n \" {\\n\"\n \" *num_correct = 0;\\n\"\n \" if(*pChar == expected)\\n\"\n \" {\\n\"\n \" *num_correct=1;\\n\"\n \" }\\n\"\n \" }\\n\"\n \"}\\n\"\n};\n\n\n\/\/ Test that arbitrarily aligned char pointers into shared buffers can be passed directly to a kernel.\n\/\/ This iterates through a buffer passing a pointer to each location to the kernel.\n\/\/ The buffer is initialized to known values at each location.\n\/\/ The kernel checks that it finds the expected value at each location.\n\/\/ TODO: possibly make this work across all base types (including typeN?), also check ptr arithmetic ++,--.\nint test_svm_pointer_passing(cl_device_id deviceID, cl_context context2, cl_command_queue queue, int num_elements)\n{\n clContextWrapper context = NULL;\n clProgramWrapper program = NULL;\n cl_uint num_devices = 0;\n cl_int error = CL_SUCCESS;\n clCommandQueueWrapper queues[MAXQ];\n\n error = create_cl_objects(deviceID, &SVMPointerPassing_test_kernel[0], &context, &program, &queues[0], &num_devices, CL_DEVICE_SVM_COARSE_GRAIN_BUFFER);\n if(error) return -1;\n\n clKernelWrapper kernel_verify_char = clCreateKernel(program, \"verify_char\", &error);\n test_error(error,\"clCreateKernel failed\");\n\n size_t bufSize = 256;\n cl_uchar *pbuf_svm_alloc = (cl_uchar*) clSVMAlloc(context, CL_MEM_READ_WRITE, sizeof(cl_uchar)*bufSize, 0);\n\n cl_int *pNumCorrect = NULL;\n pNumCorrect = (cl_int*) clSVMAlloc(context, CL_MEM_READ_WRITE, sizeof(cl_int), 0);\n\n {\n clMemWrapper buf = clCreateBuffer(context, CL_MEM_USE_HOST_PTR, sizeof(cl_uchar)*bufSize, pbuf_svm_alloc, &error);\n test_error(error, \"clCreateBuffer failed.\");\n\n clMemWrapper num_correct = clCreateBuffer(context, CL_MEM_USE_HOST_PTR, sizeof(cl_int), pNumCorrect, &error);\n test_error(error, \"clCreateBuffer failed.\");\n\n error = clSetKernelArg(kernel_verify_char, 1, sizeof(void*), (void *) &num_correct);\n test_error(error, \"clSetKernelArg failed\");\n\n \/\/ put values into buf so that we can expect to see these values in the kernel when we pass a pointer to them.\n cl_command_queue cmdq = queues[0];\n cl_uchar* pbuf_map_buffer = (cl_uchar*) clEnqueueMapBuffer(cmdq, buf, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(cl_uchar)*bufSize, 0, NULL,NULL, &error);\n test_error2(error, pbuf_map_buffer, \"clEnqueueMapBuffer failed\");\n for(int i = 0; i<(int)bufSize; i++)\n {\n pbuf_map_buffer[i]= (cl_uchar)i;\n }\n error = clEnqueueUnmapMemObject(cmdq, buf, pbuf_map_buffer, 0,NULL,NULL);\n test_error(error, \"clEnqueueUnmapMemObject failed.\");\n\n for (cl_uint ii = 0; ii"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"vcl\/printerinfomanager.hxx\"\n\n#include \"generic\/gendata.hxx\"\n\nusing namespace psp;\nusing namespace osl;\n\nusing ::rtl::OUString;\nusing ::rtl::OString;\nusing ::rtl::OStringToOUString;\nusing ::rtl::OUStringHash;\n\nPrinterInfoManager& PrinterInfoManager::get()\n{\n SalData* pSalData = GetSalData();\n if( ! pSalData->m_pPIManager )\n pSalData->m_pPIManager = new PrinterInfoManager();\n return *pSalData->m_pPIManager;\n}\n\nvoid PrinterInfoManager::release()\n{\n SalData* pSalData = GetSalData();\n delete pSalData->m_pPIManager;\n pSalData->m_pPIManager = NULL;\n}\n\nPrinterInfoManager::PrinterInfoManager( Type eType ) :\n m_pQueueInfo( NULL ),\n m_eType( eType ),\n m_bUseIncludeFeature( false ),\n m_bUseJobPatch( true ),\n m_aSystemDefaultPaper( RTL_CONSTASCII_USTRINGPARAM( \"A4\" ) ),\n m_bDisableCUPS( false )\n{\n \/\/ initSystemDefaultPaper();\n}\n\nvoid PrinterInfoManager::listPrinters( ::std::list< OUString >& rList ) const\n{\n rList.clear();\n}\n\nconst PrinterInfo& PrinterInfoManager::getPrinterInfo( const OUString& \/* rPrinter *\/ ) const\n{\n static PrinterInfo aEmptyInfo;\n\n return aEmptyInfo;\n}\n\nbool PrinterInfoManager::checkFeatureToken( const rtl::OUString& \/* rPrinterName *\/, const char* \/* pToken *\/ ) const\n{\n return false;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nApparently need more (all?) methods\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"vcl\/printerinfomanager.hxx\"\n\n#include \"generic\/gendata.hxx\"\n\nusing namespace psp;\nusing namespace osl;\n\nusing ::rtl::OUString;\nusing ::rtl::OString;\nusing ::rtl::OStringToOUString;\nusing ::rtl::OUStringHash;\n\nPrinterInfoManager& PrinterInfoManager::get()\n{\n SalData* pSalData = GetSalData();\n if( ! pSalData->m_pPIManager )\n pSalData->m_pPIManager = new PrinterInfoManager();\n return *pSalData->m_pPIManager;\n}\n\nvoid PrinterInfoManager::release()\n{\n SalData* pSalData = GetSalData();\n delete pSalData->m_pPIManager;\n pSalData->m_pPIManager = NULL;\n}\n\nPrinterInfoManager::PrinterInfoManager( Type eType ) :\n m_pQueueInfo( NULL ),\n m_eType( eType ),\n m_bUseIncludeFeature( false ),\n m_bUseJobPatch( true ),\n m_aSystemDefaultPaper( RTL_CONSTASCII_USTRINGPARAM( \"A4\" ) ),\n m_bDisableCUPS( false )\n{\n \/\/ initSystemDefaultPaper();\n}\n\nPrinterInfoManager::~PrinterInfoManager()\n{\n\n}\n\nbool PrinterInfoManager::checkPrintersChanged( bool \/* bWait *\/ )\n{\n return false;\n}\n\nvoid PrinterInfoManager::initialize()\n{\n \/\/ ???\n}\n\nvoid PrinterInfoManager::listPrinters( ::std::list< OUString >& rList ) const\n{\n rList.clear();\n}\n\nconst PrinterInfo& PrinterInfoManager::getPrinterInfo( const OUString& \/* rPrinter *\/ ) const\n{\n static PrinterInfo aEmptyInfo;\n\n return aEmptyInfo;\n}\n\nvoid PrinterInfoManager::changePrinterInfo( const OUString& \/* rPrinter *\/, const PrinterInfo& \/* rNewInfo *\/ )\n{\n\n}\n\nbool PrinterInfoManager::writePrinterConfig()\n{\n return false;\n}\n\nbool PrinterInfoManager::addPrinter( const OUString& \/* rPrinterName *\/, const OUString& \/* rDriverName *\/ )\n{\n return false;\n}\n\nbool PrinterInfoManager::removePrinter( const OUString& \/* rPrinterName *\/, bool \/* bCheckOnly *\/ )\n{\n return false;\n}\n\nbool PrinterInfoManager::setDefaultPrinter( const OUString& \/* rPrinterName *\/ )\n{\n return false;\n}\n\nbool PrinterInfoManager::addOrRemovePossible() const\n{\n return false;\n}\n\nvoid PrinterInfoManager::fillFontSubstitutions( PrinterInfo& \/* rInfo *\/ ) const\n{\n\n}\n\nvoid PrinterInfoManager::getSystemPrintCommands( std::list< OUString >& \/* rCommands *\/ )\n{\n\n}\n\nconst std::list< PrinterInfoManager::SystemPrintQueue >& PrinterInfoManager::getSystemPrintQueues()\n{\n return m_aSystemPrintQueues;\n}\n\nbool PrinterInfoManager::checkFeatureToken( const rtl::OUString& \/* rPrinterName *\/, const char* \/* pToken *\/ ) const\n{\n return false;\n}\n\nFILE* PrinterInfoManager::startSpool( const OUString& \/* rPrintername *\/, bool \/* bQuickCommand *\/ )\n{\n return NULL;\n}\n\nint PrinterInfoManager::endSpool( const OUString& \/*rPrintername*\/, const OUString& \/*rJobTitle*\/, FILE* \/* pFile *\/, const JobData& \/*rDocumentJobData*\/, bool \/*bBanner*\/ )\n{\n return true;\n}\n\nvoid PrinterInfoManager::setupJobContextData( JobData& \/* rData *\/ )\n{\n\n}\n\nvoid PrinterInfoManager::setDefaultPaper( PPDContext& \/* rContext *\/ ) const\n{\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"Exif.hxx\"\n\nExif::Exif() :\n maOrientation(TOP_LEFT),\n mbExifPresent(false)\n{}\n\nExif::~Exif()\n{}\n\nOrientation Exif::getOrientation() {\n return maOrientation;\n}\n\nvoid Exif::setOrientation(Orientation aOrientation) {\n maOrientation = aOrientation;\n}\n\nOrientation Exif::convertToOrientation(sal_Int32 value)\n{\n switch(value) {\n case 1: return TOP_LEFT;\n case 2: return TOP_RIGHT;\n case 3: return BOTTOM_RIGHT;\n case 4: return BOTTOM_LEFT;\n case 5: return LEFT_TOP;\n case 6: return RIGHT_TOP;\n case 7: return RIGHT_BOTTOM;\n case 8: return LEFT_BOTTOM;\n }\n return TOP_LEFT;\n}\n\nsal_Int32 Exif::getRotation()\n{\n switch(maOrientation) {\n case TOP_LEFT:\n return 0;\n case BOTTOM_RIGHT:\n return 1800;\n case RIGHT_TOP:\n return 2700;\n case LEFT_BOTTOM:\n return 900;\n default:\n break;\n }\n return 0;\n}\n\nbool Exif::hasExif()\n{\n return mbExifPresent;\n}\n\nbool Exif::read(SvStream& rStream)\n{\n sal_Int32 nStreamPosition = rStream.Tell();\n bool result = processJpeg(rStream, false);\n rStream.Seek( nStreamPosition );\n\n return result;\n}\n\nbool Exif::write(SvStream& rStream)\n{\n sal_Int32 nStreamPosition = rStream.Tell();\n bool result = processJpeg(rStream, true);\n rStream.Seek( nStreamPosition );\n\n return result;\n}\n\nbool Exif::processJpeg(SvStream& rStream, bool bSetValue)\n{\n sal_uInt16 aMagic16;\n sal_uInt16 aLength;\n\n rStream.Seek(STREAM_SEEK_TO_END);\n sal_uInt32 aSize = rStream.Tell();\n rStream.Seek(STREAM_SEEK_TO_BEGIN);\n\n rStream.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );\n rStream >> aMagic16;\n\n \/\/ Compare JPEG magic bytes\n if( 0xFFD8 != aMagic16 )\n {\n return false;\n }\n\n sal_uInt32 aPreviousPosition = STREAM_SEEK_TO_BEGIN;\n\n while(true)\n {\n sal_uInt8 aMarker = 0xD9;\n sal_Int32 aCount;\n\n for (aCount = 0; aCount < 7; aCount++)\n {\n rStream >> aMarker;\n if (aMarker != 0xFF)\n {\n break;\n }\n if (aCount >= 6)\n {\n return false;\n }\n }\n\n rStream >> aLength;\n\n if (aLength < 8)\n {\n return false;\n }\n\n if (aMarker == 0xE1)\n {\n return processExif(rStream, aLength, bSetValue);\n }\n else if (aMarker == 0xD9)\n {\n return false;\n }\n else\n {\n sal_uInt32 aCurrentPosition = rStream.SeekRel(aLength-1);\n if (aCurrentPosition == aPreviousPosition || aCurrentPosition > aSize)\n {\n return false;\n }\n aPreviousPosition = aCurrentPosition;\n }\n }\n return false;\n}\n\nbool Exif::processIFD(sal_uInt8* pExifData, sal_uInt16 aLength, sal_uInt16 aOffset, sal_uInt16 aNumberOfTags, bool bSetValue, bool bMoto)\n{\n ExifIFD* ifd = NULL;\n\n while (aOffset <= aLength - 12 && aNumberOfTags > 0)\n {\n ifd = (ExifIFD*) &pExifData[aOffset];\n sal_uInt16 tag = ifd->tag;\n if (bMoto)\n {\n tag = OSL_SWAPWORD(ifd->tag);\n }\n\n if (tag == ORIENTATION)\n {\n if(bSetValue)\n {\n ifd->tag = ORIENTATION;\n ifd->type = 3;\n ifd->count = 1;\n ifd->offset = maOrientation;\n if (bMoto)\n {\n ifd->tag = OSL_SWAPWORD(ifd->tag);\n ifd->offset = OSL_SWAPWORD(ifd->offset);\n }\n }\n else\n {\n sal_uInt32 nIfdOffset = ifd->offset;\n if (bMoto)\n nIfdOffset = OSL_SWAPWORD(ifd->offset);\n maOrientation = convertToOrientation(nIfdOffset);\n }\n }\n\n aNumberOfTags--;\n aOffset += 12;\n }\n return true;\n}\n\nbool Exif::processExif(SvStream& rStream, sal_uInt16 aSectionLength, bool bSetValue)\n{\n sal_uInt32 aMagic32;\n sal_uInt16 aMagic16;\n\n rStream >> aMagic32;\n rStream >> aMagic16;\n\n \/\/ Compare EXIF magic bytes\n if( 0x45786966 != aMagic32 || 0x0000 != aMagic16)\n {\n return false;\n }\n\n sal_uInt16 aLength = aSectionLength - 6; \/\/ Length = Section - Header\n\n sal_uInt8* aExifData = new sal_uInt8[aLength];\n sal_uInt32 aExifDataBeginPosition = rStream.Tell();\n\n rStream.Read(aExifData, aLength);\n\n \/\/ Exif detected\n mbExifPresent = true;\n\n TiffHeader* aTiffHeader = (TiffHeader*) &aExifData[0];\n\n if(!(\n (0x4949 == aTiffHeader->byteOrder && 0x2A00 != aTiffHeader->tagAlign ) || \/\/ Intel format\n ( 0x4D4D == aTiffHeader->byteOrder && 0x002A != aTiffHeader->tagAlign ) \/\/ Motorola format\n )\n )\n {\n delete[] aExifData;\n return false;\n }\n\n bool bMoto = true; \/\/ Motorola, big-endian by default\n\n if (aTiffHeader->byteOrder == 0x4949)\n {\n bMoto = false; \/\/ little-endian\n }\n\n sal_uInt16 aOffset = 0;\n aOffset = aTiffHeader->offset;\n if (bMoto)\n {\n aOffset = OSL_SWAPDWORD(aTiffHeader->offset);\n }\n\n sal_uInt16 aNumberOfTags = aExifData[aOffset];\n if (bMoto)\n {\n aNumberOfTags = ((aExifData[aOffset] << 8) | aExifData[aOffset+1]);\n }\n\n processIFD(aExifData, aLength, aOffset+2, aNumberOfTags, bSetValue, bMoto);\n\n if (bSetValue)\n {\n rStream.Seek(aExifDataBeginPosition);\n rStream.Write(aExifData, aLength);\n }\n\n delete[] aExifData;\n return true;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nswap if the host endianness doesn't match the file formats\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"Exif.hxx\"\n\nExif::Exif() :\n maOrientation(TOP_LEFT),\n mbExifPresent(false)\n{}\n\nExif::~Exif()\n{}\n\nOrientation Exif::getOrientation() {\n return maOrientation;\n}\n\nvoid Exif::setOrientation(Orientation aOrientation) {\n maOrientation = aOrientation;\n}\n\nOrientation Exif::convertToOrientation(sal_Int32 value)\n{\n switch(value) {\n case 1: return TOP_LEFT;\n case 2: return TOP_RIGHT;\n case 3: return BOTTOM_RIGHT;\n case 4: return BOTTOM_LEFT;\n case 5: return LEFT_TOP;\n case 6: return RIGHT_TOP;\n case 7: return RIGHT_BOTTOM;\n case 8: return LEFT_BOTTOM;\n }\n return TOP_LEFT;\n}\n\nsal_Int32 Exif::getRotation()\n{\n switch(maOrientation) {\n case TOP_LEFT:\n return 0;\n case BOTTOM_RIGHT:\n return 1800;\n case RIGHT_TOP:\n return 2700;\n case LEFT_BOTTOM:\n return 900;\n default:\n break;\n }\n return 0;\n}\n\nbool Exif::hasExif()\n{\n return mbExifPresent;\n}\n\nbool Exif::read(SvStream& rStream)\n{\n sal_Int32 nStreamPosition = rStream.Tell();\n bool result = processJpeg(rStream, false);\n rStream.Seek( nStreamPosition );\n\n return result;\n}\n\nbool Exif::write(SvStream& rStream)\n{\n sal_Int32 nStreamPosition = rStream.Tell();\n bool result = processJpeg(rStream, true);\n rStream.Seek( nStreamPosition );\n\n return result;\n}\n\nbool Exif::processJpeg(SvStream& rStream, bool bSetValue)\n{\n sal_uInt16 aMagic16;\n sal_uInt16 aLength;\n\n rStream.Seek(STREAM_SEEK_TO_END);\n sal_uInt32 aSize = rStream.Tell();\n rStream.Seek(STREAM_SEEK_TO_BEGIN);\n\n rStream.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );\n rStream >> aMagic16;\n\n \/\/ Compare JPEG magic bytes\n if( 0xFFD8 != aMagic16 )\n {\n return false;\n }\n\n sal_uInt32 aPreviousPosition = STREAM_SEEK_TO_BEGIN;\n\n while(true)\n {\n sal_uInt8 aMarker = 0xD9;\n sal_Int32 aCount;\n\n for (aCount = 0; aCount < 7; aCount++)\n {\n rStream >> aMarker;\n if (aMarker != 0xFF)\n {\n break;\n }\n if (aCount >= 6)\n {\n return false;\n }\n }\n\n rStream >> aLength;\n\n if (aLength < 8)\n {\n return false;\n }\n\n if (aMarker == 0xE1)\n {\n return processExif(rStream, aLength, bSetValue);\n }\n else if (aMarker == 0xD9)\n {\n return false;\n }\n else\n {\n sal_uInt32 aCurrentPosition = rStream.SeekRel(aLength-1);\n if (aCurrentPosition == aPreviousPosition || aCurrentPosition > aSize)\n {\n return false;\n }\n aPreviousPosition = aCurrentPosition;\n }\n }\n return false;\n}\n\nbool Exif::processIFD(sal_uInt8* pExifData, sal_uInt16 aLength, sal_uInt16 aOffset, sal_uInt16 aNumberOfTags, bool bSetValue, bool bSwap)\n{\n ExifIFD* ifd = NULL;\n\n while (aOffset <= aLength - 12 && aNumberOfTags > 0)\n {\n ifd = (ExifIFD*) &pExifData[aOffset];\n sal_uInt16 tag = ifd->tag;\n if (bSwap)\n {\n tag = OSL_SWAPWORD(ifd->tag);\n }\n\n if (tag == ORIENTATION)\n {\n if(bSetValue)\n {\n ifd->tag = ORIENTATION;\n ifd->type = 3;\n ifd->count = 1;\n ifd->offset = maOrientation;\n if (bSwap)\n {\n ifd->tag = OSL_SWAPWORD(ifd->tag);\n ifd->offset = OSL_SWAPWORD(ifd->offset);\n }\n }\n else\n {\n sal_uInt32 nIfdOffset = ifd->offset;\n if (bSwap)\n nIfdOffset = OSL_SWAPWORD(ifd->offset);\n maOrientation = convertToOrientation(nIfdOffset);\n }\n }\n\n aNumberOfTags--;\n aOffset += 12;\n }\n return true;\n}\n\nbool Exif::processExif(SvStream& rStream, sal_uInt16 aSectionLength, bool bSetValue)\n{\n sal_uInt32 aMagic32;\n sal_uInt16 aMagic16;\n\n rStream >> aMagic32;\n rStream >> aMagic16;\n\n \/\/ Compare EXIF magic bytes\n if( 0x45786966 != aMagic32 || 0x0000 != aMagic16)\n {\n return false;\n }\n\n sal_uInt16 aLength = aSectionLength - 6; \/\/ Length = Section - Header\n\n sal_uInt8* aExifData = new sal_uInt8[aLength];\n sal_uInt32 aExifDataBeginPosition = rStream.Tell();\n\n rStream.Read(aExifData, aLength);\n\n \/\/ Exif detected\n mbExifPresent = true;\n\n TiffHeader* aTiffHeader = (TiffHeader*) &aExifData[0];\n\n bool bIntel = aTiffHeader->byteOrder == 0x4949; \/\/big-endian\n bool bMotorola = aTiffHeader->byteOrder == 0x4D4D; \/\/little-endian\n\n if (!bIntel && !bMotorola)\n {\n delete[] aExifData;\n return false;\n }\n\n bool bSwap = false;\n\n#ifdef OSL_BIGENDIAN\n if (bIntel)\n bSwap = true;\n#else\n if (bMotorola)\n bSwap = true;\n#endif\n\n if (bSwap)\n {\n aTiffHeader->tagAlign = OSL_SWAPWORD(aTiffHeader->tagAlign);\n aTiffHeader->offset = OSL_SWAPDWORD(aTiffHeader->offset);\n }\n\n if (aTiffHeader->tagAlign != 0x002A) \/\/ TIFF tag\n {\n delete[] aExifData;\n return false;\n }\n\n sal_uInt16 aOffset = aTiffHeader->offset;\n\n sal_uInt16 aNumberOfTags = aExifData[aOffset];\n if (bSwap)\n {\n aNumberOfTags = ((aExifData[aOffset] << 8) | aExifData[aOffset+1]);\n }\n\n processIFD(aExifData, aLength, aOffset+2, aNumberOfTags, bSetValue, bSwap);\n\n if (bSetValue)\n {\n rStream.Seek(aExifDataBeginPosition);\n rStream.Write(aExifData, aLength);\n }\n\n delete[] aExifData;\n return true;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2005 by Andrei Alexandrescu\n\/\/ Copyright (c) 2006 Peter Kmmel\n\/\/ Code covered by the MIT License\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Id$\n\n\n#include \n\n\nnamespace Loki\n{\n\n \/\/ Crude writing method: writes straight to the file, unbuffered\n \/\/ Must be combined with a buffer to work properly (and efficiently)\n\n void write(std::FILE* f, const char* from, const char* to) {\n assert(from <= to);\n ::std::fwrite(from, 1, to - from, f);\n }\n\n \/\/ Write to a string\n\n void write(std::string& s, const char* from, const char* to) {\n assert(from <= to);\n const size_t addCount = to - from;\n if ( s.capacity() <= s.size() + addCount )\n {\n s.reserve( 2 * s.size() + addCount );\n }\n s.append(from, to);\n }\n\n \/\/ Write to a stream\n\n void write(std::ostream& f, const char* from, const char* to) {\n assert(from <= to);\n f.write(from, std::streamsize(to - from));\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ PrintfState class template\n \/\/ Holds the formatting state, and implements operator() to format stuff\n \/\/ Todo: make sure errors are handled properly\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n PrintfState Printf(const char* format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), stdout );\n PrintfState< std::FILE *, char > printState2 = state1.ChangeDevice( stdout );\n return printState2;\n }\n\n PrintfState Printf(const std::string& format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format.c_str() );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), stdout );\n PrintfState< std::FILE *, char > printState2 = state1.ChangeDevice( stdout );\n return printState2;\n }\n\n PrintfState FPrintf(std::FILE* f, const char* format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), f );\n PrintfState< std::FILE *, char > printState2 = state1.ChangeDevice( f );\n return printState2;\n }\n\n PrintfState FPrintf(std::FILE* f, const std::string& format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format.c_str() );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), f );\n PrintfState< std::FILE *, char > printState2 = state1.ChangeDevice( f );\n return printState2;\n }\n\n PrintfState FPrintf(std::ostream& f, const char* format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format );\n f.write( buffer.c_str(), buffer.size() );\n PrintfState< ::std::ostream &, char > printState2 = state1.ChangeDevice< ::std::ostream & >( f );\n return printState2;\n }\n\n PrintfState FPrintf(std::ostream& f, const std::string& format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format.c_str() );\n f.write( buffer.c_str(), buffer.size() );\n PrintfState< std::ostream &, char > printState2 = state1.ChangeDevice< ::std::ostream & >( f );\n return printState2;\n }\n\n PrintfState SPrintf(std::string& s, const char* format) {\n const size_t estimate = ::strlen( format ) + 128;\n s.reserve( estimate );\n return PrintfState(s, format);\n }\n\n PrintfState SPrintf(std::string& s, const std::string& format) {\n const size_t estimate = format.size() + 128;\n s.reserve( estimate );\n return PrintfState(s, format.c_str());\n }\n\n\n} \/\/ end namespace Loki\n\nAdded lines to make type of stdout clear to compiler.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2005 by Andrei Alexandrescu\n\/\/ Copyright (c) 2006 Peter Kmmel\n\/\/ Code covered by the MIT License\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Id$\n\n\n#include \n\n\nnamespace Loki\n{\n\n \/\/ Crude writing method: writes straight to the file, unbuffered\n \/\/ Must be combined with a buffer to work properly (and efficiently)\n\n void write(std::FILE* f, const char* from, const char* to) {\n assert(from <= to);\n ::std::fwrite(from, 1, to - from, f);\n }\n\n \/\/ Write to a string\n\n void write(std::string& s, const char* from, const char* to) {\n assert(from <= to);\n const size_t addCount = to - from;\n if ( s.capacity() <= s.size() + addCount )\n {\n s.reserve( 2 * s.size() + addCount );\n }\n s.append(from, to);\n }\n\n \/\/ Write to a stream\n\n void write(std::ostream& f, const char* from, const char* to) {\n assert(from <= to);\n f.write(from, std::streamsize(to - from));\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ PrintfState class template\n \/\/ Holds the formatting state, and implements operator() to format stuff\n \/\/ Todo: make sure errors are handled properly\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n PrintfState Printf(const char* format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), stdout );\n ::std::FILE * f = stdout;\n PrintfState< std::FILE *, char > printState2( state1.ChangeDevice( f ) );\n return printState2;\n }\n\n PrintfState Printf(const std::string& format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format.c_str() );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), stdout );\n ::std::FILE * f = stdout;\n PrintfState< std::FILE *, char > printState2( state1.ChangeDevice( f ) );\n return printState2;\n }\n\n PrintfState FPrintf(std::FILE* f, const char* format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), f );\n PrintfState< std::FILE *, char > printState2 = state1.ChangeDevice( f );\n return printState2;\n }\n\n PrintfState FPrintf(std::FILE* f, const std::string& format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format.c_str() );\n ::std::fwrite( buffer.c_str(), 1, buffer.size(), f );\n PrintfState< std::FILE *, char > printState2 = state1.ChangeDevice( f );\n return printState2;\n }\n\n PrintfState FPrintf(std::ostream& f, const char* format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format );\n f.write( buffer.c_str(), buffer.size() );\n PrintfState< ::std::ostream &, char > printState2 = state1.ChangeDevice< ::std::ostream & >( f );\n return printState2;\n }\n\n PrintfState FPrintf(std::ostream& f, const std::string& format) {\n ::std::string buffer;\n const PrintfState< ::std::string &, char > state1( buffer, format.c_str() );\n f.write( buffer.c_str(), buffer.size() );\n PrintfState< std::ostream &, char > printState2 = state1.ChangeDevice< ::std::ostream & >( f );\n return printState2;\n }\n\n PrintfState SPrintf(std::string& s, const char* format) {\n const size_t estimate = ::strlen( format ) + 128;\n s.reserve( estimate );\n return PrintfState(s, format);\n }\n\n PrintfState SPrintf(std::string& s, const std::string& format) {\n const size_t estimate = format.size() + 128;\n s.reserve( estimate );\n return PrintfState(s, format.c_str());\n }\n\n\n} \/\/ end namespace Loki\n\n<|endoftext|>"} {"text":"#ifndef VIENNAGRID_STORAGE_INSERTER_HPP\n#define VIENNAGRID_STORAGE_INSERTER_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2013, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#include \"viennagrid\/storage\/container_collection.hpp\"\n#include \"viennagrid\/storage\/container_collection_element.hpp\"\n\nnamespace viennagrid\n{\n namespace storage\n {\n\n template\n class physical_inserter_t\n {\n public:\n typedef container_collection_type physical_container_collection_type;\n typedef id_generator_type_ id_generator_type;\n\n physical_inserter_t() : collection(0), change_counter(0) {}\n physical_inserter_t(container_collection_type & _collection) : collection(&_collection), change_counter(0) {}\n physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator_) : collection(&_collection), change_counter(0), id_generator(id_generator_) {}\n\n physical_inserter_t(container_collection_type & _collection, change_counter_type & change_counter_) :\n collection(&_collection), change_counter(&change_counter_) {}\n physical_inserter_t(container_collection_type & _collection, change_counter_type & change_counter_, id_generator_type id_generator_) :\n collection(&_collection), change_counter(&change_counter_), id_generator(id_generator_) {}\n\n void set_mesh_info(container_collection_type & _collection, change_counter_type & change_counter_)\n {\n collection = &_collection;\n change_counter = &change_counter_;\n }\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n physical_insert( value_type element, inserter_type & inserter )\n {\n typedef typename viennagrid::storage::result_of::container_of::type::iterator iterator;\n typedef typename viennagrid::storage::result_of::container_of::type container_type;\n typedef typename viennagrid::storage::result_of::container_of::type::handle_tag handle_tag;\n typedef typename viennagrid::storage::result_of::container_of::type::handle_type handle_type;\n\n\n container_type & container = viennagrid::storage::collection::get< value_type >( *collection );\n\n if ( generate_id && !container.is_present( element ) )\n viennagrid::storage::id::set_id(element, id_generator( viennagrid::meta::tag() ) );\n\n if (!generate_id)\n id_generator.set_max_id( element.id() );\n\n std::pair ret = container.insert( element );\n if (change_counter) ++(*change_counter);\n\n if (call_callback)\n viennagrid::storage::container_collection_element::insert_callback(\n container.dereference_handle(ret.first),\n ret.second,\n inserter);\n\n inserter.handle_insert( ret.first, viennagrid::meta::tag() );\n\n return ret;\n }\n\n template\n void handle_insert( handle_type, viennagrid::meta::tag ) {}\n\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n insert( const value_type & element )\n {\n return physical_insert( element, *this );\n }\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n operator()( const value_type & element )\n {\n return insert( element );\n }\n\n container_collection_type & get_physical_container_collection() { return *collection; }\n container_collection_type const & get_physical_container_collection() const { return *collection; }\n\n id_generator_type & get_id_generator() { return id_generator; }\n id_generator_type const & get_id_generator() const { return id_generator; }\n\n private:\n container_collection_type * collection;\n change_counter_type * change_counter;\n\n id_generator_type id_generator;\n };\n\n\n\n\n\n\n\n\n template\n class recursive_inserter_t\n {\n public:\n recursive_inserter_t() : view_collection(0), change_counter(0), dependend_inserter(0) {}\n recursive_inserter_t(view_collection_type & collection_) : view_collection(&collection_), change_counter(0), dependend_inserter(0) {}\n\n recursive_inserter_t(view_collection_type & _collection, change_counter_type & change_counter_) :\n view_collection(&_collection), change_counter(&change_counter_) {}\n recursive_inserter_t(view_collection_type & _collection, dependend_inserter_type & dependend_inserter_) :\n view_collection(&_collection), change_counter(0), dependend_inserter(&dependend_inserter_) {}\n\n recursive_inserter_t(view_collection_type & _collection, change_counter_type & change_counter_, dependend_inserter_type & dependend_inserter_) :\n view_collection(&_collection), change_counter(&change_counter_), dependend_inserter(&dependend_inserter_) {}\n\n\n\/\/ recursive_inserter_t(view_collection_type & collection_, dependend_inserter_type & dependend_inserter_) :\n\/\/ view_collection(&collection_), dependend_inserter(&dependend_inserter_) {}\n\n\n void set_mesh_info(view_collection_type & _collection, change_counter_type & change_counter_)\n {\n view_collection = &_collection;\n change_counter = &change_counter_;\n }\n\n\n template\n void handle_insert( handle_type ref, viennagrid::meta::tag )\n {\n viennagrid::storage::container_collection::handle_or_ignore( *view_collection, ref, viennagrid::meta::tag() );\n\n dependend_inserter->handle_insert( ref, viennagrid::meta::tag() );\n if (change_counter) ++(*change_counter);\n }\n\n\n typedef typename dependend_inserter_type::physical_container_collection_type physical_container_collection_type;\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n physical_insert( const value_type & element, inserter_type & inserter )\n {\n return dependend_inserter->template physical_insert( element, inserter );\n }\n\n\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n insert( const value_type & element )\n {\n return physical_insert( element, *this );\n }\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n operator()( const value_type & element )\n {\n return insert( element );\n }\n\n physical_container_collection_type & get_physical_container_collection() { return dependend_inserter->get_physical_container_collection(); }\n physical_container_collection_type const & get_physical_container_collection() const { return dependend_inserter->get_physical_container_collection(); }\n\n typedef typename dependend_inserter_type::id_generator_type id_generator_type;\n id_generator_type & get_id_generator() { return dependend_inserter->get_id_generator(); }\n id_generator_type const & get_id_generator() const { return dependend_inserter->get_id_generator(); }\n\n\n private:\n view_collection_type * view_collection;\n change_counter_type * change_counter;\n\n dependend_inserter_type * dependend_inserter;\n };\n\n\n\n namespace inserter\n {\n template\n recursive_inserter_t get_recursive(\n dependend_inserter_type const & inserter,\n container_collection_type & collection,\n change_counter_type & change_counter)\n {\n return recursive_inserter_t(inserter, change_counter, collection);\n }\n }\n\n\n namespace result_of\n {\n template\n struct recursive_inserter\n {\n typedef recursive_inserter_t type;\n };\n\n template\n struct physical_inserter\n {\n typedef physical_inserter_t type;\n };\n }\n\n }\n}\n\n#endif\nFix: Removed unused code which caused a compilation failure on GCC 4.4#ifndef VIENNAGRID_STORAGE_INSERTER_HPP\n#define VIENNAGRID_STORAGE_INSERTER_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2013, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#include \"viennagrid\/storage\/container_collection.hpp\"\n#include \"viennagrid\/storage\/container_collection_element.hpp\"\n\nnamespace viennagrid\n{\n namespace storage\n {\n\n template\n class physical_inserter_t\n {\n public:\n typedef container_collection_type physical_container_collection_type;\n typedef id_generator_type_ id_generator_type;\n\n physical_inserter_t() : collection(0), change_counter(0) {}\n physical_inserter_t(container_collection_type & _collection) : collection(&_collection), change_counter(0) {}\n physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator_) : collection(&_collection), change_counter(0), id_generator(id_generator_) {}\n\n physical_inserter_t(container_collection_type & _collection, change_counter_type & change_counter_) :\n collection(&_collection), change_counter(&change_counter_) {}\n physical_inserter_t(container_collection_type & _collection, change_counter_type & change_counter_, id_generator_type id_generator_) :\n collection(&_collection), change_counter(&change_counter_), id_generator(id_generator_) {}\n\n void set_mesh_info(container_collection_type & _collection, change_counter_type & change_counter_)\n {\n collection = &_collection;\n change_counter = &change_counter_;\n }\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n physical_insert( value_type element, inserter_type & inserter )\n {\n typedef typename viennagrid::storage::result_of::container_of::type::iterator iterator;\n typedef typename viennagrid::storage::result_of::container_of::type container_type;\n typedef typename viennagrid::storage::result_of::container_of::type::handle_tag handle_tag;\n typedef typename viennagrid::storage::result_of::container_of::type::handle_type handle_type;\n\n\n container_type & container = viennagrid::storage::collection::get< value_type >( *collection );\n\n if ( generate_id && !container.is_present( element ) )\n viennagrid::storage::id::set_id(element, id_generator( viennagrid::meta::tag() ) );\n\n if (!generate_id)\n id_generator.set_max_id( element.id() );\n\n std::pair ret = container.insert( element );\n if (change_counter) ++(*change_counter);\n\n if (call_callback)\n viennagrid::storage::container_collection_element::insert_callback(\n container.dereference_handle(ret.first),\n ret.second,\n inserter);\n\n inserter.handle_insert( ret.first, viennagrid::meta::tag() );\n\n return ret;\n }\n\n template\n void handle_insert( handle_type, viennagrid::meta::tag ) {}\n\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n insert( const value_type & element )\n {\n return physical_insert( element, *this );\n }\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n operator()( const value_type & element )\n {\n return insert( element );\n }\n\n container_collection_type & get_physical_container_collection() { return *collection; }\n container_collection_type const & get_physical_container_collection() const { return *collection; }\n\n id_generator_type & get_id_generator() { return id_generator; }\n id_generator_type const & get_id_generator() const { return id_generator; }\n\n private:\n container_collection_type * collection;\n change_counter_type * change_counter;\n\n id_generator_type id_generator;\n };\n\n\n\n\n\n\n\n\n template\n class recursive_inserter_t\n {\n public:\n recursive_inserter_t() : view_collection(0), change_counter(0), dependend_inserter(0) {}\n recursive_inserter_t(view_collection_type & collection_) : view_collection(&collection_), change_counter(0), dependend_inserter(0) {}\n\n recursive_inserter_t(view_collection_type & _collection, change_counter_type & change_counter_) :\n view_collection(&_collection), change_counter(&change_counter_) {}\n recursive_inserter_t(view_collection_type & _collection, dependend_inserter_type & dependend_inserter_) :\n view_collection(&_collection), change_counter(0), dependend_inserter(&dependend_inserter_) {}\n\n recursive_inserter_t(view_collection_type & _collection, change_counter_type & change_counter_, dependend_inserter_type & dependend_inserter_) :\n view_collection(&_collection), change_counter(&change_counter_), dependend_inserter(&dependend_inserter_) {}\n\n\n\/\/ recursive_inserter_t(view_collection_type & collection_, dependend_inserter_type & dependend_inserter_) :\n\/\/ view_collection(&collection_), dependend_inserter(&dependend_inserter_) {}\n\n\n void set_mesh_info(view_collection_type & _collection, change_counter_type & change_counter_)\n {\n view_collection = &_collection;\n change_counter = &change_counter_;\n }\n\n\n template\n void handle_insert( handle_type ref, viennagrid::meta::tag )\n {\n viennagrid::storage::container_collection::handle_or_ignore( *view_collection, ref, viennagrid::meta::tag() );\n\n dependend_inserter->handle_insert( ref, viennagrid::meta::tag() );\n if (change_counter) ++(*change_counter);\n }\n\n\n typedef typename dependend_inserter_type::physical_container_collection_type physical_container_collection_type;\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n physical_insert( const value_type & element, inserter_type & inserter )\n {\n return dependend_inserter->template physical_insert( element, inserter );\n }\n\n\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n insert( const value_type & element )\n {\n return physical_insert( element, *this );\n }\n\n template\n std::pair<\n typename viennagrid::storage::result_of::container_of::type::handle_type,\n bool\n >\n operator()( const value_type & element )\n {\n return insert( element );\n }\n\n physical_container_collection_type & get_physical_container_collection() { return dependend_inserter->get_physical_container_collection(); }\n physical_container_collection_type const & get_physical_container_collection() const { return dependend_inserter->get_physical_container_collection(); }\n\n typedef typename dependend_inserter_type::id_generator_type id_generator_type;\n id_generator_type & get_id_generator() { return dependend_inserter->get_id_generator(); }\n id_generator_type const & get_id_generator() const { return dependend_inserter->get_id_generator(); }\n\n\n private:\n view_collection_type * view_collection;\n change_counter_type * change_counter;\n\n dependend_inserter_type * dependend_inserter;\n };\n\n\n namespace result_of\n {\n template\n struct recursive_inserter\n {\n typedef recursive_inserter_t type;\n };\n\n template\n struct physical_inserter\n {\n typedef physical_inserter_t type;\n };\n }\n\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\/\/macros\n\/\/http:\/\/d.hatena.ne.jp\/torutk\/20090420\/p1\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)\/\/ Win32 API\n#ifndef\tOS_WINDOWS\n#define\tOS_WINDOWS 1\n#endif\t\/\/OS_WINDOWS\n#elif defined (__CYGWIN__)\n#ifndef OS_CYGWIN\n#define OS_CYGWIN 1\n#endif\/\/OS_CYGWIN \n#else\n#ifndef OS_UNIX\n#define OS_UNIX 1\n#endif\/\/OS_UNIX\n#if defined (__APPLE__)\n#ifndef OS_MAC\n#define OS_MAC 1\n#endif\/\/OS_MAC\n#elif defined(__linux__)\n#ifndef OS_LINUX\n#define OS_LINUX 1\n#endif\/\/OS_LINUX\n#else\n#ifndef OS_UNKNOWN\n#define OS_UNKNOWN 1\n#endif\/\/OS_UNKNOWN\n#endif\/\/if defined __APPLE__ __linux\n#endif\/\/if defined \n\n#if defined OS_WINDOWS \n#include \n#include \n#include \n#include \n#pragma comment(lib, \"psapi.lib\")\n#elif defined OS_CYGWIN\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#endif\/\/\n\nnamespace mi\n{\n\tnamespace sys {\n#ifdef OS_WINDOWS\n\t\tstd::string get_cpu_name ( void ) {\n\t\t\tchar CPUString[0x20];\n\t\t\tchar CPUBrandString[0x40];\n\t\t\tint CPUInfo[4] = { -1};\n\t\t\t__cpuid ( CPUInfo, 0 );\n\t\t\tunsigned int nIds = CPUInfo[0];\n\t\t\tmemset ( CPUString, 0, sizeof ( CPUString ) );\n\t\t\t* ( ( int* ) CPUString ) = CPUInfo[1];\n\t\t\t* ( ( int* ) ( CPUString + 4 ) ) = CPUInfo[3];\n\t\t\t* ( ( int* ) ( CPUString + 8 ) ) = CPUInfo[2];\n\t\t\t\/\/ Calling __cpuid with 0x80000000 as the InfoType argument\n\t\t\t\/\/ gets the number of valid extended IDs.\n\t\t\t__cpuid ( CPUInfo, 0x80000000 );\n\t\t\tunsigned int nExIds = CPUInfo[0];\n\t\t\tmemset ( CPUBrandString, 0, sizeof ( CPUBrandString ) );\n\t\t\t\n\t\t\t\/\/ Get the information associated with each extended ID.\n\t\t\tfor ( unsigned int i = 0x80000000; i <= nExIds; ++i ) {\n\t\t\t\t__cpuid ( CPUInfo, i );\n\t\t\t\t\n\t\t\t\t\/\/ Interpret CPU brand string and cache information.\n\t\t\t\tif ( i == 0x80000002 ) {\n\t\t\t\t\tmemcpy ( CPUBrandString, CPUInfo, sizeof ( CPUInfo ) );\n\t\t\t\t} else if ( i == 0x80000003 ) {\n\t\t\t\t\tmemcpy ( CPUBrandString + 16, CPUInfo, sizeof ( CPUInfo ) );\n\t\t\t\t} else if ( i == 0x80000004 ) {\n\t\t\t\t\tmemcpy ( CPUBrandString + 32, CPUInfo, sizeof ( CPUInfo ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::string name;\n\t\t\t\n\t\t\tif ( nExIds >= 0x80000004 ) {\n\t\t\t\tname = std::string ( CPUBrandString );\n\t\t\t}\n\t\t\t\n\t\t\treturn name;\n\t\t}\n\t\t\n\t\tdouble get_memory_size() {\n\t\t\tMEMORYSTATUSEX stat;\n\t\t\tstat.dwLength = sizeof ( MEMORYSTATUSEX );\n\t\t\t\n\t\t\tif ( GlobalMemoryStatusEx ( &stat ) == 0 ) {\n\t\t\t\tstd::cerr << \"error while calling GlobalMemoryStatusEx()\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/\/ @note The retrun value is somewhat smaller than actual size.\n\t\t\treturn static_cast ( stat.ullTotalPhys \/ 1024.0 \/ 1024 \/ 1024 ) ;\n\t\t}\n\n\t\tint get_num_cores(){\n\t\t\tSYSTEM_INFO sysinfo;\n\t\t\tGetSystemInfo ( &sysinfo );\n\t\t\treturn static_cast ( sysinfo.dwNumberOfProcessors );\n\t\t}\n\t\t\n\t\tstd::string get_date() {\n\t\t\tSYSTEMTIME systime;\n\t\t\tGetLocalTime ( &systime );\n\t\t\tstd::stringstream ss;\n\t\t\tss << systime.wYear << \"-\" << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wMonth << \"-\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wDay << \"-\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wHour << \":\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wMinute << \":\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wSecond;\n\t\t\treturn ss.str();\n\t\t}\n\t\tdouble get_peak_memory( void ) {\n\t\t\tdouble peakMemory = 0;\n\t\t\tPROCESS_MEMORY_COUNTERS pmc = { 0 };\n\t\t\tHANDLE hProcess = OpenProcess ( PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId() );\n\t\t\tif ( GetProcessMemoryInfo ( hProcess, &pmc, sizeof ( pmc ) ) ) {\n\t\t\t\tpeakMemory = static_cast ( pmc.PeakWorkingSetSize );\n\t\t\t}\n\t\t\t\n\t\t\tCloseHandle ( hProcess );\n\t\t\treturn peakMemory;\n\t\t}\n#elif defined (OS_CYGWIN) \n\t\tstd::string get_cpu_name_cygwin ( void ) {\n\t\t\tstd::string name;\n\t\t\treturn name;\n\t\t}\n\t\t\n\t\tdouble get_memory_size_cygwin() {\n\t\t\treturn static_cast ( 0 ) ;\n\t\t}\n\n\t\tint get_num_core_cygwin(){\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tstd::string get_date_cygwin() {\n\t\t\tSYSTEMTIME systime;\n\t\t\tGetLocalTime ( &systime );\n\t\t\tstd::stringstream ss;\n\t\t\tss << systime.wYear << \"-\" << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wMonth << \"-\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wDay << \"-\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wHour << \":\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wMinute << \":\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wSecond;\n\t\t\treturn ss.str();\n\t\t}\n\t\tdouble get_peak_memory_cygwin( void ) {\n\t\t\tdouble peakMemory = 0;\n\t\t\t\/\/\/@todo Add something here\n\t\t\treturn peakMemory;\n\t\t}\n#else \/\/ unix like system\n\t\tstatic std::string get_sysctl ( const std::string& key ) {\n\t\t\tchar result[256];\n\t\t\tsize_t size = 256;\n\t\t\tsysctlbyname ( key.c_str(), &result[0], &size, NULL, 0 );\n\t\t\treturn std::string ( result );\n\t\t}\n\t\tstatic double get_sysctl_double ( const std::string& key ) {\n\t\t\tuint64_t result;\n\t\t\tsize_t size = sizeof ( result );\n\t\t\tsysctlbyname ( key.c_str(), &result, &size, NULL, 0 );\n\t\t\treturn static_cast ( result );\n\t\t}\n\t\t\n\t\tstatic int get_sysctl_int ( const std::string& key ) {\n\t\t\tint result;\n\t\t\tsize_t size = sizeof ( result );\n\t\t\tsysctlbyname ( key.c_str(), &result, &size, NULL, 0 );\n\t\t\treturn result;\n\t\t}\n\t\tdouble get_peak_memory_unix( void ) {\n\t\t\tdouble peakMemory = 0;\n\t\t\tstruct rusage rusage;\n\t\t\tgetrusage ( RUSAGE_SELF, &rusage ); \/\/\/@todo The result somewhat strange on Mac.\n\t\t\tpeakMemory = static_cast ( rusage.ru_maxrss );\n\t\t\treturn peakMemory;\n\t\t}\n#endif\n\t}\n\t\n\t\n\t\n std::string\n SystemInfo::getCpuName ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_cpu_name();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_cpu_time_cygwin();\n#else\n return mi::sys::get_sysctl ( \"machdep.cpu.brand_string\" );\n#endif\n }\n\n double\n SystemInfo::getMemorySize ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_memory_size();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_memory_size();\n#else\n return mi::sys::get_sysctl_double ( \"hw.memsize\" ) * 1.0 \/ 1024.0 \/ 1024.0 \/ 1024.0;\n#endif\n }\n\n\n int\n SystemInfo::getNumCores ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_num_cores();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_num_cores_cygwin();\n#else\n return mi::sys::get_sysctl_int ( \"machdep.cpu.core_count\" );\n#endif\n }\n\n std::string\n SystemInfo::getDate ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_date();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_date_cygwin();\n#else\n time_t rawtime = std::time ( NULL );\n struct tm* timeinfo = localtime ( &rawtime );\n char buffer [80];\n strftime ( buffer, 80, \"%F-%X\", timeinfo );\n std::string result ( buffer );\n return result;\n#endif\n }\n void\n SystemInfo::print ( std::ostream& out )\n {\n out << \"date: \" << mi::SystemInfo::getDate() << std::endl;\n out << \"cpu: \" << mi::SystemInfo::getCpuName() << \"(\" << mi::SystemInfo::getNumCores() << \"cores)\" << std::endl;\n out << \"memory:\" << mi::SystemInfo::getMemorySize() << \"[gb]\" << std::endl;\n }\n\n double\n SystemInfo::getPeakMemorySize ( const SIZE_TYPE type )\n {\n double peakMemory = 0;\n#if defined(OS_WINDOWS)\n\t\tpeakMemory = mi::sys::get_peak_memory();\n#elif defined OS_CYGWIN\n\t\tpeakMemory = mi::sys::get_peak_memory_cygwin();\n#else \/\/ MAC or Linux\n\t\tpeakMemory = mi::sys::get_peak_memory_unix();\n#endif \/\/ WIN32\n\n if ( type == MI_GIGA_BYTE ) {\n peakMemory \/= 1024 * 1024 * 1024 ;\n } else if ( type == MI_MEGA_BYTE ) {\n peakMemory \/= 1024 * 1024;\n } else if ( type == MI_KILO_BYTE ) {\n peakMemory \/= 1024;\n }\n return peakMemory;\n }\n}\n\nCygwin confirmed (incomplete)#include \n#include \n#include \n#include \n#include \n#include \n\/\/macros\n\/\/http:\/\/d.hatena.ne.jp\/torutk\/20090420\/p1\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)\/\/ Win32 API\n#ifndef\tOS_WINDOWS\n#define\tOS_WINDOWS 1\n#endif\t\/\/OS_WINDOWS\n#elif defined (__CYGWIN__)\n#ifndef OS_CYGWIN\n#define OS_CYGWIN 1\n#endif\/\/OS_CYGWIN \n#else\n#ifndef OS_UNIX\n#define OS_UNIX 1\n#endif\/\/OS_UNIX\n#if defined (__APPLE__)\n#ifndef OS_MAC\n#define OS_MAC 1\n#endif\/\/OS_MAC\n#elif defined(__linux__)\n#ifndef OS_LINUX\n#define OS_LINUX 1\n#endif\/\/OS_LINUX\n#else\n#ifndef OS_UNKNOWN\n#define OS_UNKNOWN 1\n#endif\/\/OS_UNKNOWN\n#endif\/\/if defined __APPLE__ __linux\n#endif\/\/if defined \n\n#if defined OS_WINDOWS \n#include \n#include \n#include \n#include \n#pragma comment(lib, \"psapi.lib\")\n#elif defined OS_CYGWIN\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#endif\/\/\n\nnamespace mi\n{\n\tnamespace sys {\n#if defined OS_WINDOWS\n\t\tstd::string get_cpu_name ( void ) {\n\t\t\tchar CPUString[0x20];\n\t\t\tchar CPUBrandString[0x40];\n\t\t\tint CPUInfo[4] = { -1};\n\t\t\t__cpuid ( CPUInfo, 0 );\n\t\t\tunsigned int nIds = CPUInfo[0];\n\t\t\tmemset ( CPUString, 0, sizeof ( CPUString ) );\n\t\t\t* ( ( int* ) CPUString ) = CPUInfo[1];\n\t\t\t* ( ( int* ) ( CPUString + 4 ) ) = CPUInfo[3];\n\t\t\t* ( ( int* ) ( CPUString + 8 ) ) = CPUInfo[2];\n\t\t\t\/\/ Calling __cpuid with 0x80000000 as the InfoType argument\n\t\t\t\/\/ gets the number of valid extended IDs.\n\t\t\t__cpuid ( CPUInfo, 0x80000000 );\n\t\t\tunsigned int nExIds = CPUInfo[0];\n\t\t\tmemset ( CPUBrandString, 0, sizeof ( CPUBrandString ) );\n\t\t\t\n\t\t\t\/\/ Get the information associated with each extended ID.\n\t\t\tfor ( unsigned int i = 0x80000000; i <= nExIds; ++i ) {\n\t\t\t\t__cpuid ( CPUInfo, i );\n\t\t\t\t\n\t\t\t\t\/\/ Interpret CPU brand string and cache information.\n\t\t\t\tif ( i == 0x80000002 ) {\n\t\t\t\t\tmemcpy ( CPUBrandString, CPUInfo, sizeof ( CPUInfo ) );\n\t\t\t\t} else if ( i == 0x80000003 ) {\n\t\t\t\t\tmemcpy ( CPUBrandString + 16, CPUInfo, sizeof ( CPUInfo ) );\n\t\t\t\t} else if ( i == 0x80000004 ) {\n\t\t\t\t\tmemcpy ( CPUBrandString + 32, CPUInfo, sizeof ( CPUInfo ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::string name;\n\t\t\t\n\t\t\tif ( nExIds >= 0x80000004 ) {\n\t\t\t\tname = std::string ( CPUBrandString );\n\t\t\t}\n\t\t\t\n\t\t\treturn name;\n\t\t}\n\t\t\n\t\tdouble get_memory_size() {\n\t\t\tMEMORYSTATUSEX stat;\n\t\t\tstat.dwLength = sizeof ( MEMORYSTATUSEX );\n\t\t\t\n\t\t\tif ( GlobalMemoryStatusEx ( &stat ) == 0 ) {\n\t\t\t\tstd::cerr << \"error while calling GlobalMemoryStatusEx()\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/\/ @note The retrun value is somewhat smaller than actual size.\n\t\t\treturn static_cast ( stat.ullTotalPhys \/ 1024.0 \/ 1024 \/ 1024 ) ;\n\t\t}\n\n\t\tint get_num_cores(){\n\t\t\tSYSTEM_INFO sysinfo;\n\t\t\tGetSystemInfo ( &sysinfo );\n\t\t\treturn static_cast ( sysinfo.dwNumberOfProcessors );\n\t\t}\n\t\t\n\t\tstd::string get_date() {\n\t\t\tSYSTEMTIME systime;\n\t\t\tGetLocalTime ( &systime );\n\t\t\tstd::stringstream ss;\n\t\t\tss << systime.wYear << \"-\" << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wMonth << \"-\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wDay << \"-\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wHour << \":\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wMinute << \":\"\n\t\t\t << std::setw ( 2 ) << std::setfill ( '0' ) << systime.wSecond;\n\t\t\treturn ss.str();\n\t\t}\n\t\tdouble get_peak_memory( void ) {\n\t\t\tdouble peakMemory = 0;\n\t\t\tPROCESS_MEMORY_COUNTERS pmc = { 0 };\n\t\t\tHANDLE hProcess = OpenProcess ( PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId() );\n\t\t\tif ( GetProcessMemoryInfo ( hProcess, &pmc, sizeof ( pmc ) ) ) {\n\t\t\t\tpeakMemory = static_cast ( pmc.PeakWorkingSetSize );\n\t\t\t}\n\t\t\t\n\t\t\tCloseHandle ( hProcess );\n\t\t\treturn peakMemory;\n\t\t}\n#elif defined (OS_CYGWIN) \n\t\tstd::string get_cpu_name_cygwin ( void ) {\n\t\t\tstd::string name;\n\t\t\treturn name;\n\t\t}\n\t\t\n\t\tdouble get_memory_size_cygwin() {\n\t\t\treturn static_cast ( 0 ) ;\n\t\t}\n\n\t\tint get_num_cores_cygwin(){\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tstd::string get_date_cygwin() {\n\t\t\treturn std::string();\n\t\t}\n\t\tdouble get_peak_memory_cygwin( void ) {\n\t\t\tdouble peakMemory = 0;\n\t\t\t\/\/\/@todo Add something here\n\t\t\treturn peakMemory;\n\t\t}\n#else \/\/ unix like system\n\t\tstatic std::string get_sysctl ( const std::string& key ) {\n\t\t\tchar result[256];\n\t\t\tsize_t size = 256;\n\t\t\tsysctlbyname ( key.c_str(), &result[0], &size, NULL, 0 );\n\t\t\treturn std::string ( result );\n\t\t}\n\t\tstatic double get_sysctl_double ( const std::string& key ) {\n\t\t\tuint64_t result;\n\t\t\tsize_t size = sizeof ( result );\n\t\t\tsysctlbyname ( key.c_str(), &result, &size, NULL, 0 );\n\t\t\treturn static_cast ( result );\n\t\t}\n\t\t\n\t\tstatic int get_sysctl_int ( const std::string& key ) {\n\t\t\tint result;\n\t\t\tsize_t size = sizeof ( result );\n\t\t\tsysctlbyname ( key.c_str(), &result, &size, NULL, 0 );\n\t\t\treturn result;\n\t\t}\n\t\tdouble get_peak_memory_unix( void ) {\n\t\t\tdouble peakMemory = 0;\n\t\t\tstruct rusage rusage;\n\t\t\tgetrusage ( RUSAGE_SELF, &rusage ); \/\/\/@todo The result somewhat strange on Mac.\n\t\t\tpeakMemory = static_cast ( rusage.ru_maxrss );\n\t\t\treturn peakMemory;\n\t\t}\n#endif\n\t}\n\t\n\t\n\t\n std::string\n SystemInfo::getCpuName ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_cpu_name();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_cpu_name_cygwin();\n#else\n return mi::sys::get_sysctl ( \"machdep.cpu.brand_string\" );\n#endif\n }\n\n double\n SystemInfo::getMemorySize ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_memory_size();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_memory_size_cygwin();\n#else\n return mi::sys::get_sysctl_double ( \"hw.memsize\" ) * 1.0 \/ 1024.0 \/ 1024.0 \/ 1024.0;\n#endif\n }\n\n\n int\n SystemInfo::getNumCores ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_num_cores();\n#elif defined OS_CYGWIN\n\t\treturn mi::sys::get_num_cores_cygwin();\n#else\n return mi::sys::get_sysctl_int ( \"machdep.cpu.core_count\" );\n#endif\n }\n\n std::string\n SystemInfo::getDate ( void )\n {\n#ifdef OS_WINDOWS\n\t\treturn mi::sys::get_date();\n#else\n time_t rawtime = std::time ( NULL );\n struct tm* timeinfo = localtime ( &rawtime );\n char buffer [80];\n strftime ( buffer, 80, \"%F-%X\", timeinfo );\n std::string result ( buffer );\n return result;\n#endif\n }\n void\n SystemInfo::print ( std::ostream& out )\n {\n out << \"date: \" << mi::SystemInfo::getDate() << std::endl;\n out << \"cpu: \" << mi::SystemInfo::getCpuName() << \"(\" << mi::SystemInfo::getNumCores() << \"cores)\" << std::endl;\n out << \"memory:\" << mi::SystemInfo::getMemorySize() << \"[gb]\" << std::endl;\n }\n\n double\n SystemInfo::getPeakMemorySize ( const SIZE_TYPE type )\n {\n double peakMemory = 0;\n#if defined(OS_WINDOWS)\n\t\tpeakMemory = mi::sys::get_peak_memory();\n#elif defined OS_CYGWIN\n\t\tpeakMemory = mi::sys::get_peak_memory_cygwin();\n#else \/\/ MAC or Linux\n\t\tpeakMemory = mi::sys::get_peak_memory_unix();\n#endif \/\/ WIN32\n\n if ( type == MI_GIGA_BYTE ) {\n peakMemory \/= 1024 * 1024 * 1024 ;\n } else if ( type == MI_MEGA_BYTE ) {\n peakMemory \/= 1024 * 1024;\n } else if ( type == MI_KILO_BYTE ) {\n peakMemory \/= 1024;\n }\n return peakMemory;\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d);\n\nint main(int argc, char * argv[]) {\n bool reInit = true;\n unsigned int nrIterations = 0;\n unsigned int samplingFactor = 100;\n unsigned int clPlatformID = 0;\n unsigned int clDeviceID = 0;\n unsigned int vectorSize = 0;\n unsigned int maxThreads = 0;\n unsigned int maxItems = 0;\n unsigned int maxVector = 0;\n unsigned int inputSize = 0;\n\n try {\n isa::utils::ArgumentList args(argc, argv);\n\n clPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n clDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n if ( args.getSwitch(\"-sampling\") ) {\n samplingFactor = args.getSwitchArgument< unsigned int >(\"-factor\");\n }\n nrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n vectorSize = args.getSwitchArgument< unsigned int >(\"-vector\");\n maxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n maxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n maxVector = args.getSwitchArgument< unsigned int >(\"-max_vector\");\n inputSize = args.getSwitchArgument< unsigned int >(\"-input_size\");\n } catch ( isa::utils::EmptyCommandLine & err ) {\n std::cerr << argv[0] << \" -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -max_threads ... -max_items ... -max_vector ... -input_size ... \" << std::endl;\n return 1;\n } catch ( std::exception & err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n }\n\n cl::Context clContext;\n std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;\n\n \/\/ Allocate host memory\n std::vector< inputDataType > A(inputSize), B(inputSize), C(inputSize), C_control(inputSize);\n cl::Buffer A_d, B_d, C_d;\n\n srand(time(0));\n for ( unsigned int item = 0; item < A.size(); item++ ) {\n A[item] = rand() % factor;\n B[item] = rand() % factor;\n }\n std::fill(C.begin(), C.end(), factor);\n std::fill(C_control.begin(), C_control.end(), factor);\n\n \/\/ Run the control\n TuneBench::triad(A, B, C_control, static_cast< inputDataType >(factor));\n\n \/\/ Generate tuning configurations\n std::vector configurations;\n for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) {\n for ( unsigned int items = 1; items <= maxItems; items++ ) {\n for ( unsigned int vector = 1; vector <= maxVector; vector++ ) {\n if ( inputSize % (threads * items * vector) != 0 ) {\n continue;\n } else if ( items * vector > maxItems ) {\n break;\n }\n TuneBench::TriadConf configuration;\n configuration.setNrThreadsD0(threads);\n configuration.setNrItemsD0(items);\n configuration.setVector(vector);\n configurations.push_back(configuration);\n }\n }\n }\n\n std::cout << std::fixed << std::endl;\n std::cout << \"# inputSize *configuration* GB\/s time stdDeviation COV\" << std::endl << std::endl;\n\n for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) {\n if ( samplingFactor < 100 ) {\n \/\/ Sample the configurations\n std::random_device randomDevice;\n std::default_random_engine randomEngine(randomDevice());\n std::uniform_int_distribution uniformDistribution(0, 99);\n unsigned int randomValue = uniformDistribution(randomEngine);\n\n if ( randomValue >= samplingFactor ) {\n continue;\n }\n }\n \/\/ Generate kernel\n double gbytes = isa::utils::giga(static_cast< uint64_t >(inputSize) * sizeof(inputDataType) * 3.0);\n cl::Event clEvent;\n cl::Kernel * kernel;\n isa::utils::Timer timer;\n std::string * code = TuneBench::getTriadOpenCL(*configuration, inputDataName, factor);\n\n if ( reInit ) {\n delete clQueues;\n clQueues = new std::vector< std::vector< cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &A, &A_d, &B, &B_d, &C_d);\n } catch ( cl::Error & err ) {\n return -1;\n }\n reInit = false;\n }\n try {\n kernel = isa::OpenCL::compile(\"triad\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n } catch ( isa::OpenCL::OpenCLError & err ) {\n std::cerr << err.what() << std::endl;\n delete code;\n break;\n }\n delete code;\n\n cl::NDRange global(inputSize \/ ((*configuration).getNrItemsD0() * (*configuration).getVector()));\n cl::NDRange local((*configuration).getNrThreadsD0());\n\n kernel->setArg(0, A_d);\n kernel->setArg(1, B_d);\n kernel->setArg(2, C_d);\n\n try {\n \/\/ Warm-up run\n clQueues->at(clDeviceID)[0].finish();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n clEvent.wait();\n \/\/ Tuning runs\n for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n timer.start();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n clEvent.wait();\n timer.stop();\n }\n clQueues->at(clDeviceID)[0].enqueueReadBuffer(C_d, CL_TRUE, 0, C.size() * sizeof(inputDataType), reinterpret_cast< void * >(C.data()), 0, &clEvent);\n clEvent.wait();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL kernel execution error (\";\n std::cerr << (*configuration).print();\n std::cerr << \"), (\";\n std::cerr << isa::utils::toString(inputSize \/ (*configuration).getNrItemsD0()) << \"): \";\n std::cerr << isa::utils::toString(err.err()) << std::endl;\n delete kernel;\n if ( err.err() == -4 || err.err() == -61 ) {\n return -1;\n }\n reInit = true;\n break;\n }\n delete kernel;\n\n bool error = false;\n for ( unsigned int item = 0; item < C.size(); item++ ) {\n if ( !isa::utils::same(C[item], C_control[item]) ) {\n std::cerr << \"Output error (\" << (*configuration).print() << \").\" << std::endl;\n error = true;\n break;\n }\n }\n if ( error ) {\n continue;\n }\n\n std::cout << inputSize << \" \";\n std::cout << (*configuration).print() << \" \";\n std::cout << std::setprecision(3);\n std::cout << gbytes \/ timer.getAverageTime() << \" \";\n std::cout << std::setprecision(6);\n std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \" << timer.getCoefficientOfVariation() << std::endl;\n }\n std::cout << std::endl;\n\n return 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d) {\n try {\n *A_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, A->size() * sizeof(inputDataType), 0, 0);\n *B_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, B->size() * sizeof(inputDataType), 0, 0);\n *C_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, A->size() * sizeof(inputDataType), 0, 0);\n clQueue->enqueueWriteBuffer(*A_d, CL_FALSE, 0, A->size() * sizeof(inputDataType), reinterpret_cast< void * >(A->data()));\n clQueue->enqueueWriteBuffer(*B_d, CL_FALSE, 0, B->size() * sizeof(inputDataType), reinterpret_cast< void * >(B->data()));\n clQueue->finish();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error (memory initialization): \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n throw;\n }\n}\n\nUsing a more C++ way for sampling. Also now we get the same number of configurations for every execution.\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d);\n\nint main(int argc, char * argv[]) {\n bool reInit = true;\n unsigned int nrIterations = 0;\n unsigned int samplingFactor = 100;\n unsigned int clPlatformID = 0;\n unsigned int clDeviceID = 0;\n unsigned int vectorSize = 0;\n unsigned int maxThreads = 0;\n unsigned int maxItems = 0;\n unsigned int maxVector = 0;\n unsigned int inputSize = 0;\n \/\/ Random number generation\n std::random_device randomDevice;\n std::default_random_engine randomEngine(randomDevice());\n std::uniform_int_distribution uniformDistribution(0, factor);\n\n try {\n isa::utils::ArgumentList args(argc, argv);\n\n clPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n clDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n if ( args.getSwitch(\"-sampling\") ) {\n samplingFactor = args.getSwitchArgument< unsigned int >(\"-factor\");\n }\n nrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n vectorSize = args.getSwitchArgument< unsigned int >(\"-vector\");\n maxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n maxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n maxVector = args.getSwitchArgument< unsigned int >(\"-max_vector\");\n inputSize = args.getSwitchArgument< unsigned int >(\"-input_size\");\n } catch ( isa::utils::EmptyCommandLine & err ) {\n std::cerr << argv[0] << \" -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -max_threads ... -max_items ... -max_vector ... -input_size ... \" << std::endl;\n return 1;\n } catch ( std::exception & err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n }\n\n cl::Context clContext;\n std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;\n\n \/\/ Allocate host memory\n std::vector< inputDataType > A(inputSize), B(inputSize), C(inputSize), C_control(inputSize);\n cl::Buffer A_d, B_d, C_d;\n\n std::generate(A.begin(), A.end(), uniformDistribution(randomEngine));\n std::generate(B.begin(), B.end(), uniformDistribution(randomEngine));\n std::fill(C.begin(), C.end(), factor);\n std::fill(C_control.begin(), C_control.end(), factor);\n\n \/\/ Run the control\n TuneBench::triad(A, B, C_control, static_cast< inputDataType >(factor));\n\n \/\/ Generate tuning configurations\n std::vector configurations;\n for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) {\n for ( unsigned int items = 1; items <= maxItems; items++ ) {\n for ( unsigned int vector = 1; vector <= maxVector; vector++ ) {\n if ( inputSize % (threads * items * vector) != 0 ) {\n continue;\n } else if ( items * vector > maxItems ) {\n break;\n }\n TuneBench::TriadConf configuration;\n configuration.setNrThreadsD0(threads);\n configuration.setNrItemsD0(items);\n configuration.setVector(vector);\n configurations.push_back(configuration);\n }\n }\n }\n if ( samplingFactor < 100 ) {\n unsigned int newSize = static_cast((configurations.size() * samplingFactor) \/ 100.0);\n std::shuffle(configurations.begin(), configurations.end(), randomEngine);\n configuration.resize(newSize);\n }\n\n std::cout << std::fixed << std::endl;\n std::cout << \"# inputSize *configuration* GB\/s time stdDeviation COV\" << std::endl << std::endl;\n\n for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) {\n \/\/ Generate kernel\n double gbytes = isa::utils::giga(static_cast< uint64_t >(inputSize) * sizeof(inputDataType) * 3.0);\n cl::Event clEvent;\n cl::Kernel * kernel;\n isa::utils::Timer timer;\n std::string * code = TuneBench::getTriadOpenCL(*configuration, inputDataName, factor);\n\n if ( reInit ) {\n delete clQueues;\n clQueues = new std::vector< std::vector< cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &A, &A_d, &B, &B_d, &C_d);\n } catch ( cl::Error & err ) {\n return -1;\n }\n reInit = false;\n }\n try {\n kernel = isa::OpenCL::compile(\"triad\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n } catch ( isa::OpenCL::OpenCLError & err ) {\n std::cerr << err.what() << std::endl;\n delete code;\n break;\n }\n delete code;\n\n cl::NDRange global(inputSize \/ ((*configuration).getNrItemsD0() * (*configuration).getVector()));\n cl::NDRange local((*configuration).getNrThreadsD0());\n\n kernel->setArg(0, A_d);\n kernel->setArg(1, B_d);\n kernel->setArg(2, C_d);\n\n try {\n \/\/ Warm-up run\n clQueues->at(clDeviceID)[0].finish();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n clEvent.wait();\n \/\/ Tuning runs\n for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n timer.start();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n clEvent.wait();\n timer.stop();\n }\n clQueues->at(clDeviceID)[0].enqueueReadBuffer(C_d, CL_TRUE, 0, C.size() * sizeof(inputDataType), reinterpret_cast< void * >(C.data()), 0, &clEvent);\n clEvent.wait();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL kernel execution error (\";\n std::cerr << (*configuration).print();\n std::cerr << \"), (\";\n std::cerr << isa::utils::toString(inputSize \/ (*configuration).getNrItemsD0()) << \"): \";\n std::cerr << isa::utils::toString(err.err()) << std::endl;\n delete kernel;\n if ( err.err() == -4 || err.err() == -61 ) {\n return -1;\n }\n reInit = true;\n break;\n }\n delete kernel;\n\n bool error = false;\n for ( unsigned int item = 0; item < C.size(); item++ ) {\n if ( !isa::utils::same(C[item], C_control[item]) ) {\n std::cerr << \"Output error (\" << (*configuration).print() << \").\" << std::endl;\n error = true;\n break;\n }\n }\n if ( error ) {\n continue;\n }\n\n std::cout << inputSize << \" \";\n std::cout << (*configuration).print() << \" \";\n std::cout << std::setprecision(3);\n std::cout << gbytes \/ timer.getAverageTime() << \" \";\n std::cout << std::setprecision(6);\n std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \" << timer.getCoefficientOfVariation() << std::endl;\n }\n std::cout << std::endl;\n\n return 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d) {\n try {\n *A_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, A->size() * sizeof(inputDataType), 0, 0);\n *B_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, B->size() * sizeof(inputDataType), 0, 0);\n *C_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, A->size() * sizeof(inputDataType), 0, 0);\n clQueue->enqueueWriteBuffer(*A_d, CL_FALSE, 0, A->size() * sizeof(inputDataType), reinterpret_cast< void * >(A->data()));\n clQueue->enqueueWriteBuffer(*B_d, CL_FALSE, 0, B->size() * sizeof(inputDataType), reinterpret_cast< void * >(B->data()));\n clQueue->finish();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error (memory initialization): \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n throw;\n }\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n\nclass GLWindow : public Window\n{\npublic:\n GLWindow(const char* title, const int width, const int height, Root* parent = NULL)\n : Window(title, width, height)\n {\n m_ActiveVisualizer = 0;\n\n m_HUD = new HUD(getViewport());\n m_HUD->bind(parent->context());\n\n m_Parent = parent;\n }\n\n virtual ~GLWindow()\n {\n SAFE_DELETE(m_HUD);\n }\n\n virtual void draw(Context* context)\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n {\n if (visualizer->view() != NULL)\n visualizer->view()->draw();\n if (visualizer->controller() != NULL)\n visualizer->controller()->draw();\n }\n\n m_HUD->draw(context);\n }\n\n virtual void idle(Context* context)\n {\n (void) context;\n \n m_HUD->idle();\n\n for (auto visualizer : m_Visualizers)\n {\n if (visualizer->view() != NULL)\n visualizer->view()->idle();\n if (visualizer->controller() != NULL)\n visualizer->controller()->idle();\n }\n }\n\n \/\/ ----- TODO : VisualizerManager -----\n\n inline void addVisualizer(EntityVisualizer* visualizer)\n {\n m_Visualizers.push_back(visualizer);\n }\n\n inline EntityVisualizer* getActiveVisualizer()\n {\n if (m_Visualizers.empty())\n return NULL;\n return m_Visualizers[m_ActiveVisualizer];\n }\n\n inline void selectNextVisualizer()\n {\n if (!m_Visualizers.empty())\n m_ActiveVisualizer = (m_ActiveVisualizer + 1) % m_Visualizers.size();\n }\n\n \/\/ ----- Window Events -----\n\n void onWindowSize(int width, int height) override\n {\n m_HUD->reshape(getViewport());\n\n for (auto visualizer : m_Visualizers)\n if (visualizer->controller())\n visualizer->controller()->onWindowSize(width, height);\n }\n\n void onSetFramebufferSize(int width, int height) override\n {\n m_HUD->reshape(getViewport());\n\n for (auto visualizer : m_Visualizers)\n if (visualizer->controller())\n visualizer->controller()->onSetFramebufferSize(width, height);\n }\n\n void onCursorPos(double xpos, double ypos) override\n {\n m_HUD->onCursorPos(xpos, ypos);\n\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onCursorPos(xpos, ypos);\n }\n\n void onMouseButton(int button, int action, int mods) override\n {\n m_HUD->onMouseButton(button, action, mods);\n\n if (m_HUD->getWidgetPick() == NULL)\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onMouseButton(button, action, mods); \n }\n }\n\n void onKey(int key, int scancode, int action, int mods) override\n { \n m_HUD->onKey(key, scancode, action, mods);\n \n if (key == GLFW_KEY_N && action == 1 \/* DOWN *\/)\n selectNextVisualizer();\n else if (key == GLFW_KEY_M && action == 1 \/* DOWN *\/)\n {\n Geometry::getMetrics().dump();\n Geometry::getMetrics().reset();\n ResourceManager::getInstance().dump();\n }\n else\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onKey(key, scancode, action, mods);\n }\n }\n\n void onScroll(double xoffset, double yoffset) override\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onScroll(xoffset, yoffset);\n }\n\n inline HUD* hud() { return m_HUD; }\n\n inline Root* getParent() { return m_Parent; }\n\nprivate:\n Root* m_Parent;\n std::vector m_Visualizers;\n int m_ActiveVisualizer;\n HUD* m_HUD;\n};\nFixed resizing bug#pragma once\n\n#include \n#include \n\n#include \n\nclass GLWindow : public Window\n{\npublic:\n GLWindow(const char* title, const int width, const int height, Root* parent = NULL)\n : Window(title, width, height)\n {\n m_ActiveVisualizer = 0;\n\n m_HUD = new HUD(getViewport());\n m_HUD->bind(parent->context());\n\n m_Parent = parent;\n }\n\n virtual ~GLWindow()\n {\n SAFE_DELETE(m_HUD);\n }\n\n virtual void draw(Context* context)\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n {\n if (visualizer->view() != NULL)\n visualizer->view()->draw();\n if (visualizer->controller() != NULL)\n visualizer->controller()->draw();\n }\n\n m_HUD->draw(context);\n }\n\n virtual void idle(Context* context)\n {\n (void) context;\n \n m_HUD->idle();\n\n for (auto visualizer : m_Visualizers)\n {\n if (visualizer->view() != NULL)\n visualizer->view()->idle();\n if (visualizer->controller() != NULL)\n visualizer->controller()->idle();\n }\n }\n\n \/\/ ----- TODO : VisualizerManager -----\n\n inline void addVisualizer(EntityVisualizer* visualizer)\n {\n m_Visualizers.push_back(visualizer);\n }\n\n inline EntityVisualizer* getActiveVisualizer()\n {\n if (m_Visualizers.empty())\n return NULL;\n return m_Visualizers[m_ActiveVisualizer];\n }\n\n inline void selectNextVisualizer()\n {\n if (!m_Visualizers.empty())\n m_ActiveVisualizer = (m_ActiveVisualizer + 1) % m_Visualizers.size();\n }\n\n \/\/ ----- Window Events -----\n\n void onWindowSize(int width, int height) override\n {\n m_HUD->reshape(getViewport());\n\n for (auto visualizer : m_Visualizers)\n if (visualizer->controller())\n visualizer->controller()->onWindowSize(width, height);\n }\n\n void onSetFramebufferSize(int width, int height) override\n {\n glViewport(0, 0, width, height);\n\n m_HUD->reshape(getViewport());\n\n for (auto visualizer : m_Visualizers)\n if (visualizer->controller())\n visualizer->controller()->onSetFramebufferSize(width, height);\n }\n\n void onCursorPos(double xpos, double ypos) override\n {\n m_HUD->onCursorPos(xpos, ypos);\n\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onCursorPos(xpos, ypos);\n }\n\n void onMouseButton(int button, int action, int mods) override\n {\n m_HUD->onMouseButton(button, action, mods);\n\n if (m_HUD->getWidgetPick() == NULL)\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onMouseButton(button, action, mods); \n }\n }\n\n void onKey(int key, int scancode, int action, int mods) override\n { \n m_HUD->onKey(key, scancode, action, mods);\n \n if (key == GLFW_KEY_N && action == 1 \/* DOWN *\/)\n selectNextVisualizer();\n else if (key == GLFW_KEY_M && action == 1 \/* DOWN *\/)\n {\n Geometry::getMetrics().dump();\n Geometry::getMetrics().reset();\n ResourceManager::getInstance().dump();\n }\n else\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onKey(key, scancode, action, mods);\n }\n }\n\n void onScroll(double xoffset, double yoffset) override\n {\n auto visualizer = getActiveVisualizer();\n if (visualizer)\n visualizer->controller()->onScroll(xoffset, yoffset);\n }\n\n inline HUD* hud() { return m_HUD; }\n\n inline Root* getParent() { return m_Parent; }\n\nprivate:\n Root* m_Parent;\n std::vector m_Visualizers;\n int m_ActiveVisualizer;\n HUD* m_HUD;\n};\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/events\/gestures\/gesture_recognizer_impl.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/time\/time.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/events\/event_constants.h\"\n#include \"ui\/events\/event_switches.h\"\n#include \"ui\/events\/event_utils.h\"\n#include \"ui\/events\/gestures\/gesture_configuration.h\"\n#include \"ui\/events\/gestures\/gesture_sequence.h\"\n#include \"ui\/events\/gestures\/gesture_types.h\"\n\nnamespace ui {\n\nnamespace {\n\ntemplate \nvoid TransferConsumer(GestureConsumer* current_consumer,\n GestureConsumer* new_consumer,\n std::map* map) {\n if (map->count(current_consumer)) {\n (*map)[new_consumer] = (*map)[current_consumer];\n map->erase(current_consumer);\n }\n}\n\nbool RemoveConsumerFromMap(GestureConsumer* consumer,\n GestureRecognizerImpl::TouchIdToConsumerMap* map) {\n bool consumer_removed = false;\n for (GestureRecognizerImpl::TouchIdToConsumerMap::iterator i = map->begin();\n i != map->end();) {\n if (i->second == consumer) {\n map->erase(i++);\n consumer_removed = true;\n } else {\n ++i;\n }\n }\n return consumer_removed;\n}\n\nvoid TransferTouchIdToConsumerMap(\n GestureConsumer* old_consumer,\n GestureConsumer* new_consumer,\n GestureRecognizerImpl::TouchIdToConsumerMap* map) {\n for (GestureRecognizerImpl::TouchIdToConsumerMap::iterator i = map->begin();\n i != map->end(); ++i) {\n if (i->second == old_consumer)\n i->second = new_consumer;\n }\n}\n\nGestureProviderAura* CreateGestureProvider(GestureProviderAuraClient* client) {\n return new GestureProviderAura(client);\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GestureRecognizerImpl, public:\n\nGestureRecognizerImpl::GestureRecognizerImpl() {\n \/\/ Default to using the unified gesture detector.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n const std::string unified_gd_enabled_switch =\n command_line.HasSwitch(switches::kUnifiedGestureDetector) ?\n command_line.GetSwitchValueASCII(switches::kUnifiedGestureDetector) :\n switches::kUnifiedGestureDetectorAuto;\n\n const bool kUseUnifiedGestureDetectorByDefault = true;\n if (unified_gd_enabled_switch.empty() ||\n unified_gd_enabled_switch == switches::kUnifiedGestureDetectorEnabled) {\n use_unified_gesture_detector_ = true;\n } else if (unified_gd_enabled_switch ==\n switches::kUnifiedGestureDetectorDisabled) {\n use_unified_gesture_detector_ = false;\n } else if (unified_gd_enabled_switch ==\n switches::kUnifiedGestureDetectorAuto) {\n use_unified_gesture_detector_ = kUseUnifiedGestureDetectorByDefault;\n } else {\n LOG(ERROR) << \"Invalid --unified-gesture-detector option: \"\n << unified_gd_enabled_switch;\n use_unified_gesture_detector_ = false;\n }\n}\n\nGestureRecognizerImpl::~GestureRecognizerImpl() {\n STLDeleteValues(&consumer_sequence_);\n STLDeleteValues(&consumer_gesture_provider_);\n}\n\n\/\/ Checks if this finger is already down, if so, returns the current target.\n\/\/ Otherwise, returns NULL.\nGestureConsumer* GestureRecognizerImpl::GetTouchLockedTarget(\n const TouchEvent& event) {\n return touch_id_target_[event.touch_id()];\n}\n\nGestureConsumer* GestureRecognizerImpl::GetTargetForGestureEvent(\n const GestureEvent& event) {\n GestureConsumer* target = NULL;\n int touch_id = event.GetLowestTouchId();\n target = touch_id_target_for_gestures_[touch_id];\n return target;\n}\n\nGestureConsumer* GestureRecognizerImpl::GetTargetForLocation(\n const gfx::PointF& location, int source_device_id) {\n const int max_distance =\n GestureConfiguration::max_separation_for_gesture_touches_in_pixels();\n\n if (!use_unified_gesture_detector_) {\n const GesturePoint* closest_point = NULL;\n int64 closest_distance_squared = 0;\n std::map::iterator i;\n for (i = consumer_sequence_.begin(); i != consumer_sequence_.end(); ++i) {\n const GesturePoint* points = i->second->points();\n for (int j = 0; j < GestureSequence::kMaxGesturePoints; ++j) {\n if (!points[j].in_use() ||\n source_device_id != points[j].source_device_id()) {\n continue;\n }\n gfx::Vector2dF delta = points[j].last_touch_position() - location;\n \/\/ Relative distance is all we need here, so LengthSquared() is\n \/\/ appropriate, and cheaper than Length().\n int64 distance_squared = delta.LengthSquared();\n if (!closest_point || distance_squared < closest_distance_squared) {\n closest_point = &points[j];\n closest_distance_squared = distance_squared;\n }\n }\n }\n\n if (closest_distance_squared < max_distance * max_distance && closest_point)\n return touch_id_target_[closest_point->touch_id()];\n else\n return NULL;\n } else {\n gfx::PointF closest_point;\n int closest_touch_id;\n float closest_distance_squared = std::numeric_limits::infinity();\n\n std::map::iterator i;\n for (i = consumer_gesture_provider_.begin();\n i != consumer_gesture_provider_.end();\n ++i) {\n const MotionEventAura& pointer_state = i->second->pointer_state();\n for (size_t j = 0; j < pointer_state.GetPointerCount(); ++j) {\n if (source_device_id != pointer_state.GetSourceDeviceId(j))\n continue;\n gfx::PointF point(pointer_state.GetX(j), pointer_state.GetY(j));\n \/\/ Relative distance is all we need here, so LengthSquared() is\n \/\/ appropriate, and cheaper than Length().\n float distance_squared = (point - location).LengthSquared();\n if (distance_squared < closest_distance_squared) {\n closest_point = point;\n closest_touch_id = pointer_state.GetPointerId(j);\n closest_distance_squared = distance_squared;\n }\n }\n }\n\n if (closest_distance_squared < max_distance * max_distance)\n return touch_id_target_[closest_touch_id];\n else\n return NULL;\n }\n}\n\nvoid GestureRecognizerImpl::TransferEventsTo(GestureConsumer* current_consumer,\n GestureConsumer* new_consumer) {\n \/\/ Send cancel to all those save |new_consumer| and |current_consumer|.\n \/\/ Don't send a cancel to |current_consumer|, unless |new_consumer| is NULL.\n \/\/ Dispatching a touch-cancel event can end up altering |touch_id_target_|\n \/\/ (e.g. when the target of the event is destroyed, causing it to be removed\n \/\/ from |touch_id_target_| in |CleanupStateForConsumer()|). So create a list\n \/\/ of the touch-ids that need to be cancelled, and dispatch the cancel events\n \/\/ for them at the end.\n std::vector > ids;\n for (TouchIdToConsumerMap::iterator i = touch_id_target_.begin();\n i != touch_id_target_.end(); ++i) {\n if (i->second && i->second != new_consumer &&\n (i->second != current_consumer || new_consumer == NULL) &&\n i->second) {\n ids.push_back(std::make_pair(i->first, i->second));\n }\n }\n\n CancelTouches(&ids);\n\n \/\/ Transfer events from |current_consumer| to |new_consumer|.\n if (current_consumer && new_consumer) {\n TransferTouchIdToConsumerMap(current_consumer, new_consumer,\n &touch_id_target_);\n TransferTouchIdToConsumerMap(current_consumer, new_consumer,\n &touch_id_target_for_gestures_);\n if (!use_unified_gesture_detector_)\n TransferConsumer(current_consumer, new_consumer, &consumer_sequence_);\n else\n TransferConsumer(\n current_consumer, new_consumer, &consumer_gesture_provider_);\n }\n}\n\nbool GestureRecognizerImpl::GetLastTouchPointForTarget(\n GestureConsumer* consumer,\n gfx::PointF* point) {\n if (!use_unified_gesture_detector_) {\n if (consumer_sequence_.count(consumer) == 0)\n return false;\n *point = consumer_sequence_[consumer]->last_touch_location();\n return true;\n } else {\n if (consumer_gesture_provider_.count(consumer) == 0)\n return false;\n const MotionEvent& pointer_state =\n consumer_gesture_provider_[consumer]->pointer_state();\n *point = gfx::PointF(pointer_state.GetX(), pointer_state.GetY());\n return true;\n }\n}\n\nbool GestureRecognizerImpl::CancelActiveTouches(GestureConsumer* consumer) {\n std::vector > ids;\n for (TouchIdToConsumerMap::const_iterator i = touch_id_target_.begin();\n i != touch_id_target_.end(); ++i) {\n if (i->second == consumer)\n ids.push_back(std::make_pair(i->first, i->second));\n }\n bool cancelled_touch = !ids.empty();\n CancelTouches(&ids);\n return cancelled_touch;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GestureRecognizerImpl, protected:\n\nGestureSequence* GestureRecognizerImpl::CreateSequence(\n GestureSequenceDelegate* delegate) {\n return new GestureSequence(delegate);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GestureRecognizerImpl, private:\n\nGestureSequence* GestureRecognizerImpl::GetGestureSequenceForConsumer(\n GestureConsumer* consumer) {\n GestureSequence* gesture_sequence = consumer_sequence_[consumer];\n if (!gesture_sequence) {\n gesture_sequence = CreateSequence(this);\n consumer_sequence_[consumer] = gesture_sequence;\n }\n return gesture_sequence;\n}\n\nGestureProviderAura* GestureRecognizerImpl::GetGestureProviderForConsumer(\n GestureConsumer* consumer) {\n GestureProviderAura* gesture_provider = consumer_gesture_provider_[consumer];\n if (!gesture_provider) {\n gesture_provider = CreateGestureProvider(this);\n consumer_gesture_provider_[consumer] = gesture_provider;\n }\n return gesture_provider;\n}\n\nvoid GestureRecognizerImpl::SetupTargets(const TouchEvent& event,\n GestureConsumer* target) {\n if (event.type() == ui::ET_TOUCH_RELEASED ||\n event.type() == ui::ET_TOUCH_CANCELLED) {\n touch_id_target_.erase(event.touch_id());\n } else if (event.type() == ui::ET_TOUCH_PRESSED) {\n touch_id_target_[event.touch_id()] = target;\n if (target)\n touch_id_target_for_gestures_[event.touch_id()] = target;\n }\n}\n\nvoid GestureRecognizerImpl::CancelTouches(\n std::vector >* touches) {\n while (!touches->empty()) {\n int touch_id = touches->begin()->first;\n GestureConsumer* target = touches->begin()->second;\n TouchEvent touch_event(ui::ET_TOUCH_CANCELLED, gfx::PointF(0, 0),\n ui::EF_IS_SYNTHESIZED, touch_id,\n ui::EventTimeForNow(), 0.0f, 0.0f, 0.0f, 0.0f);\n GestureEventHelper* helper = FindDispatchHelperForConsumer(target);\n if (helper)\n helper->DispatchCancelTouchEvent(&touch_event);\n touches->erase(touches->begin());\n }\n}\n\nvoid GestureRecognizerImpl::DispatchGestureEvent(GestureEvent* event) {\n GestureConsumer* consumer = GetTargetForGestureEvent(*event);\n if (consumer) {\n GestureEventHelper* helper = FindDispatchHelperForConsumer(consumer);\n if (helper)\n helper->DispatchGestureEvent(event);\n }\n}\n\nScopedVector* GestureRecognizerImpl::ProcessTouchEventForGesture(\n const TouchEvent& event,\n ui::EventResult result,\n GestureConsumer* target) {\n SetupTargets(event, target);\n\n if (!use_unified_gesture_detector_) {\n GestureSequence* gesture_sequence = GetGestureSequenceForConsumer(target);\n return gesture_sequence->ProcessTouchEventForGesture(event, result);\n } else {\n GestureProviderAura* gesture_provider =\n GetGestureProviderForConsumer(target);\n \/\/ TODO(tdresser) - detect gestures eagerly.\n if (!(result & ER_CONSUMED)) {\n if (gesture_provider->OnTouchEvent(event)) {\n gesture_provider->OnTouchEventAck(result != ER_UNHANDLED);\n return gesture_provider->GetAndResetPendingGestures();\n }\n }\n return NULL;\n }\n}\n\nbool GestureRecognizerImpl::CleanupStateForConsumer(\n GestureConsumer* consumer) {\n bool state_cleaned_up = false;\n\n if (!use_unified_gesture_detector_) {\n if (consumer_sequence_.count(consumer)) {\n state_cleaned_up = true;\n delete consumer_sequence_[consumer];\n consumer_sequence_.erase(consumer);\n }\n } else {\n if (consumer_gesture_provider_.count(consumer)) {\n state_cleaned_up = true;\n delete consumer_gesture_provider_[consumer];\n consumer_gesture_provider_.erase(consumer);\n }\n }\n\n state_cleaned_up |= RemoveConsumerFromMap(consumer, &touch_id_target_);\n state_cleaned_up |=\n RemoveConsumerFromMap(consumer, &touch_id_target_for_gestures_);\n return state_cleaned_up;\n}\n\nvoid GestureRecognizerImpl::AddGestureEventHelper(GestureEventHelper* helper) {\n helpers_.push_back(helper);\n}\n\nvoid GestureRecognizerImpl::RemoveGestureEventHelper(\n GestureEventHelper* helper) {\n std::vector::iterator it = std::find(helpers_.begin(),\n helpers_.end(), helper);\n if (it != helpers_.end())\n helpers_.erase(it);\n}\n\nvoid GestureRecognizerImpl::DispatchPostponedGestureEvent(GestureEvent* event) {\n DispatchGestureEvent(event);\n}\n\nvoid GestureRecognizerImpl::OnGestureEvent(GestureEvent* event) {\n DispatchGestureEvent(event);\n}\n\nGestureEventHelper* GestureRecognizerImpl::FindDispatchHelperForConsumer(\n GestureConsumer* consumer) {\n std::vector::iterator it;\n for (it = helpers_.begin(); it != helpers_.end(); ++it) {\n if ((*it)->CanDispatchToConsumer(consumer))\n return (*it);\n }\n return NULL;\n}\n\n\/\/ GestureRecognizer, static\nGestureRecognizer* GestureRecognizer::Create() {\n return new GestureRecognizerImpl();\n}\n\nstatic GestureRecognizerImpl* g_gesture_recognizer_instance = NULL;\n\n\/\/ GestureRecognizer, static\nGestureRecognizer* GestureRecognizer::Get() {\n if (!g_gesture_recognizer_instance)\n g_gesture_recognizer_instance = new GestureRecognizerImpl();\n return g_gesture_recognizer_instance;\n}\n\n\/\/ GestureRecognizer, static\nvoid GestureRecognizer::Reset() {\n delete g_gesture_recognizer_instance;\n g_gesture_recognizer_instance = NULL;\n}\n\nvoid SetGestureRecognizerForTesting(GestureRecognizer* gesture_recognizer) {\n \/\/ Transfer helpers to the new GR.\n std::vector& helpers =\n g_gesture_recognizer_instance->helpers();\n std::vector::iterator it;\n for (it = helpers.begin(); it != helpers.end(); ++it)\n gesture_recognizer->AddGestureEventHelper(*it);\n\n helpers.clear();\n g_gesture_recognizer_instance =\n static_cast(gesture_recognizer);\n}\n\n} \/\/ namespace ui\nDisable unified gesture detector\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/events\/gestures\/gesture_recognizer_impl.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/time\/time.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/events\/event_constants.h\"\n#include \"ui\/events\/event_switches.h\"\n#include \"ui\/events\/event_utils.h\"\n#include \"ui\/events\/gestures\/gesture_configuration.h\"\n#include \"ui\/events\/gestures\/gesture_sequence.h\"\n#include \"ui\/events\/gestures\/gesture_types.h\"\n\nnamespace ui {\n\nnamespace {\n\ntemplate \nvoid TransferConsumer(GestureConsumer* current_consumer,\n GestureConsumer* new_consumer,\n std::map* map) {\n if (map->count(current_consumer)) {\n (*map)[new_consumer] = (*map)[current_consumer];\n map->erase(current_consumer);\n }\n}\n\nbool RemoveConsumerFromMap(GestureConsumer* consumer,\n GestureRecognizerImpl::TouchIdToConsumerMap* map) {\n bool consumer_removed = false;\n for (GestureRecognizerImpl::TouchIdToConsumerMap::iterator i = map->begin();\n i != map->end();) {\n if (i->second == consumer) {\n map->erase(i++);\n consumer_removed = true;\n } else {\n ++i;\n }\n }\n return consumer_removed;\n}\n\nvoid TransferTouchIdToConsumerMap(\n GestureConsumer* old_consumer,\n GestureConsumer* new_consumer,\n GestureRecognizerImpl::TouchIdToConsumerMap* map) {\n for (GestureRecognizerImpl::TouchIdToConsumerMap::iterator i = map->begin();\n i != map->end(); ++i) {\n if (i->second == old_consumer)\n i->second = new_consumer;\n }\n}\n\nGestureProviderAura* CreateGestureProvider(GestureProviderAuraClient* client) {\n return new GestureProviderAura(client);\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GestureRecognizerImpl, public:\n\nGestureRecognizerImpl::GestureRecognizerImpl() {\n \/\/ Default to not using the unified gesture detector.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n const std::string unified_gd_enabled_switch =\n command_line.HasSwitch(switches::kUnifiedGestureDetector) ?\n command_line.GetSwitchValueASCII(switches::kUnifiedGestureDetector) :\n switches::kUnifiedGestureDetectorAuto;\n\n const bool kUseUnifiedGestureDetectorByDefault = false;\n if (unified_gd_enabled_switch.empty() ||\n unified_gd_enabled_switch == switches::kUnifiedGestureDetectorEnabled) {\n use_unified_gesture_detector_ = true;\n } else if (unified_gd_enabled_switch ==\n switches::kUnifiedGestureDetectorDisabled) {\n use_unified_gesture_detector_ = false;\n } else if (unified_gd_enabled_switch ==\n switches::kUnifiedGestureDetectorAuto) {\n use_unified_gesture_detector_ = kUseUnifiedGestureDetectorByDefault;\n } else {\n LOG(ERROR) << \"Invalid --unified-gesture-detector option: \"\n << unified_gd_enabled_switch;\n use_unified_gesture_detector_ = false;\n }\n}\n\nGestureRecognizerImpl::~GestureRecognizerImpl() {\n STLDeleteValues(&consumer_sequence_);\n STLDeleteValues(&consumer_gesture_provider_);\n}\n\n\/\/ Checks if this finger is already down, if so, returns the current target.\n\/\/ Otherwise, returns NULL.\nGestureConsumer* GestureRecognizerImpl::GetTouchLockedTarget(\n const TouchEvent& event) {\n return touch_id_target_[event.touch_id()];\n}\n\nGestureConsumer* GestureRecognizerImpl::GetTargetForGestureEvent(\n const GestureEvent& event) {\n GestureConsumer* target = NULL;\n int touch_id = event.GetLowestTouchId();\n target = touch_id_target_for_gestures_[touch_id];\n return target;\n}\n\nGestureConsumer* GestureRecognizerImpl::GetTargetForLocation(\n const gfx::PointF& location, int source_device_id) {\n const int max_distance =\n GestureConfiguration::max_separation_for_gesture_touches_in_pixels();\n\n if (!use_unified_gesture_detector_) {\n const GesturePoint* closest_point = NULL;\n int64 closest_distance_squared = 0;\n std::map::iterator i;\n for (i = consumer_sequence_.begin(); i != consumer_sequence_.end(); ++i) {\n const GesturePoint* points = i->second->points();\n for (int j = 0; j < GestureSequence::kMaxGesturePoints; ++j) {\n if (!points[j].in_use() ||\n source_device_id != points[j].source_device_id()) {\n continue;\n }\n gfx::Vector2dF delta = points[j].last_touch_position() - location;\n \/\/ Relative distance is all we need here, so LengthSquared() is\n \/\/ appropriate, and cheaper than Length().\n int64 distance_squared = delta.LengthSquared();\n if (!closest_point || distance_squared < closest_distance_squared) {\n closest_point = &points[j];\n closest_distance_squared = distance_squared;\n }\n }\n }\n\n if (closest_distance_squared < max_distance * max_distance && closest_point)\n return touch_id_target_[closest_point->touch_id()];\n else\n return NULL;\n } else {\n gfx::PointF closest_point;\n int closest_touch_id;\n float closest_distance_squared = std::numeric_limits::infinity();\n\n std::map::iterator i;\n for (i = consumer_gesture_provider_.begin();\n i != consumer_gesture_provider_.end();\n ++i) {\n const MotionEventAura& pointer_state = i->second->pointer_state();\n for (size_t j = 0; j < pointer_state.GetPointerCount(); ++j) {\n if (source_device_id != pointer_state.GetSourceDeviceId(j))\n continue;\n gfx::PointF point(pointer_state.GetX(j), pointer_state.GetY(j));\n \/\/ Relative distance is all we need here, so LengthSquared() is\n \/\/ appropriate, and cheaper than Length().\n float distance_squared = (point - location).LengthSquared();\n if (distance_squared < closest_distance_squared) {\n closest_point = point;\n closest_touch_id = pointer_state.GetPointerId(j);\n closest_distance_squared = distance_squared;\n }\n }\n }\n\n if (closest_distance_squared < max_distance * max_distance)\n return touch_id_target_[closest_touch_id];\n else\n return NULL;\n }\n}\n\nvoid GestureRecognizerImpl::TransferEventsTo(GestureConsumer* current_consumer,\n GestureConsumer* new_consumer) {\n \/\/ Send cancel to all those save |new_consumer| and |current_consumer|.\n \/\/ Don't send a cancel to |current_consumer|, unless |new_consumer| is NULL.\n \/\/ Dispatching a touch-cancel event can end up altering |touch_id_target_|\n \/\/ (e.g. when the target of the event is destroyed, causing it to be removed\n \/\/ from |touch_id_target_| in |CleanupStateForConsumer()|). So create a list\n \/\/ of the touch-ids that need to be cancelled, and dispatch the cancel events\n \/\/ for them at the end.\n std::vector > ids;\n for (TouchIdToConsumerMap::iterator i = touch_id_target_.begin();\n i != touch_id_target_.end(); ++i) {\n if (i->second && i->second != new_consumer &&\n (i->second != current_consumer || new_consumer == NULL) &&\n i->second) {\n ids.push_back(std::make_pair(i->first, i->second));\n }\n }\n\n CancelTouches(&ids);\n\n \/\/ Transfer events from |current_consumer| to |new_consumer|.\n if (current_consumer && new_consumer) {\n TransferTouchIdToConsumerMap(current_consumer, new_consumer,\n &touch_id_target_);\n TransferTouchIdToConsumerMap(current_consumer, new_consumer,\n &touch_id_target_for_gestures_);\n if (!use_unified_gesture_detector_)\n TransferConsumer(current_consumer, new_consumer, &consumer_sequence_);\n else\n TransferConsumer(\n current_consumer, new_consumer, &consumer_gesture_provider_);\n }\n}\n\nbool GestureRecognizerImpl::GetLastTouchPointForTarget(\n GestureConsumer* consumer,\n gfx::PointF* point) {\n if (!use_unified_gesture_detector_) {\n if (consumer_sequence_.count(consumer) == 0)\n return false;\n *point = consumer_sequence_[consumer]->last_touch_location();\n return true;\n } else {\n if (consumer_gesture_provider_.count(consumer) == 0)\n return false;\n const MotionEvent& pointer_state =\n consumer_gesture_provider_[consumer]->pointer_state();\n *point = gfx::PointF(pointer_state.GetX(), pointer_state.GetY());\n return true;\n }\n}\n\nbool GestureRecognizerImpl::CancelActiveTouches(GestureConsumer* consumer) {\n std::vector > ids;\n for (TouchIdToConsumerMap::const_iterator i = touch_id_target_.begin();\n i != touch_id_target_.end(); ++i) {\n if (i->second == consumer)\n ids.push_back(std::make_pair(i->first, i->second));\n }\n bool cancelled_touch = !ids.empty();\n CancelTouches(&ids);\n return cancelled_touch;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GestureRecognizerImpl, protected:\n\nGestureSequence* GestureRecognizerImpl::CreateSequence(\n GestureSequenceDelegate* delegate) {\n return new GestureSequence(delegate);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GestureRecognizerImpl, private:\n\nGestureSequence* GestureRecognizerImpl::GetGestureSequenceForConsumer(\n GestureConsumer* consumer) {\n GestureSequence* gesture_sequence = consumer_sequence_[consumer];\n if (!gesture_sequence) {\n gesture_sequence = CreateSequence(this);\n consumer_sequence_[consumer] = gesture_sequence;\n }\n return gesture_sequence;\n}\n\nGestureProviderAura* GestureRecognizerImpl::GetGestureProviderForConsumer(\n GestureConsumer* consumer) {\n GestureProviderAura* gesture_provider = consumer_gesture_provider_[consumer];\n if (!gesture_provider) {\n gesture_provider = CreateGestureProvider(this);\n consumer_gesture_provider_[consumer] = gesture_provider;\n }\n return gesture_provider;\n}\n\nvoid GestureRecognizerImpl::SetupTargets(const TouchEvent& event,\n GestureConsumer* target) {\n if (event.type() == ui::ET_TOUCH_RELEASED ||\n event.type() == ui::ET_TOUCH_CANCELLED) {\n touch_id_target_.erase(event.touch_id());\n } else if (event.type() == ui::ET_TOUCH_PRESSED) {\n touch_id_target_[event.touch_id()] = target;\n if (target)\n touch_id_target_for_gestures_[event.touch_id()] = target;\n }\n}\n\nvoid GestureRecognizerImpl::CancelTouches(\n std::vector >* touches) {\n while (!touches->empty()) {\n int touch_id = touches->begin()->first;\n GestureConsumer* target = touches->begin()->second;\n TouchEvent touch_event(ui::ET_TOUCH_CANCELLED, gfx::PointF(0, 0),\n ui::EF_IS_SYNTHESIZED, touch_id,\n ui::EventTimeForNow(), 0.0f, 0.0f, 0.0f, 0.0f);\n GestureEventHelper* helper = FindDispatchHelperForConsumer(target);\n if (helper)\n helper->DispatchCancelTouchEvent(&touch_event);\n touches->erase(touches->begin());\n }\n}\n\nvoid GestureRecognizerImpl::DispatchGestureEvent(GestureEvent* event) {\n GestureConsumer* consumer = GetTargetForGestureEvent(*event);\n if (consumer) {\n GestureEventHelper* helper = FindDispatchHelperForConsumer(consumer);\n if (helper)\n helper->DispatchGestureEvent(event);\n }\n}\n\nScopedVector* GestureRecognizerImpl::ProcessTouchEventForGesture(\n const TouchEvent& event,\n ui::EventResult result,\n GestureConsumer* target) {\n SetupTargets(event, target);\n\n if (!use_unified_gesture_detector_) {\n GestureSequence* gesture_sequence = GetGestureSequenceForConsumer(target);\n return gesture_sequence->ProcessTouchEventForGesture(event, result);\n } else {\n GestureProviderAura* gesture_provider =\n GetGestureProviderForConsumer(target);\n \/\/ TODO(tdresser) - detect gestures eagerly.\n if (!(result & ER_CONSUMED)) {\n if (gesture_provider->OnTouchEvent(event)) {\n gesture_provider->OnTouchEventAck(result != ER_UNHANDLED);\n return gesture_provider->GetAndResetPendingGestures();\n }\n }\n return NULL;\n }\n}\n\nbool GestureRecognizerImpl::CleanupStateForConsumer(\n GestureConsumer* consumer) {\n bool state_cleaned_up = false;\n\n if (!use_unified_gesture_detector_) {\n if (consumer_sequence_.count(consumer)) {\n state_cleaned_up = true;\n delete consumer_sequence_[consumer];\n consumer_sequence_.erase(consumer);\n }\n } else {\n if (consumer_gesture_provider_.count(consumer)) {\n state_cleaned_up = true;\n delete consumer_gesture_provider_[consumer];\n consumer_gesture_provider_.erase(consumer);\n }\n }\n\n state_cleaned_up |= RemoveConsumerFromMap(consumer, &touch_id_target_);\n state_cleaned_up |=\n RemoveConsumerFromMap(consumer, &touch_id_target_for_gestures_);\n return state_cleaned_up;\n}\n\nvoid GestureRecognizerImpl::AddGestureEventHelper(GestureEventHelper* helper) {\n helpers_.push_back(helper);\n}\n\nvoid GestureRecognizerImpl::RemoveGestureEventHelper(\n GestureEventHelper* helper) {\n std::vector::iterator it = std::find(helpers_.begin(),\n helpers_.end(), helper);\n if (it != helpers_.end())\n helpers_.erase(it);\n}\n\nvoid GestureRecognizerImpl::DispatchPostponedGestureEvent(GestureEvent* event) {\n DispatchGestureEvent(event);\n}\n\nvoid GestureRecognizerImpl::OnGestureEvent(GestureEvent* event) {\n DispatchGestureEvent(event);\n}\n\nGestureEventHelper* GestureRecognizerImpl::FindDispatchHelperForConsumer(\n GestureConsumer* consumer) {\n std::vector::iterator it;\n for (it = helpers_.begin(); it != helpers_.end(); ++it) {\n if ((*it)->CanDispatchToConsumer(consumer))\n return (*it);\n }\n return NULL;\n}\n\n\/\/ GestureRecognizer, static\nGestureRecognizer* GestureRecognizer::Create() {\n return new GestureRecognizerImpl();\n}\n\nstatic GestureRecognizerImpl* g_gesture_recognizer_instance = NULL;\n\n\/\/ GestureRecognizer, static\nGestureRecognizer* GestureRecognizer::Get() {\n if (!g_gesture_recognizer_instance)\n g_gesture_recognizer_instance = new GestureRecognizerImpl();\n return g_gesture_recognizer_instance;\n}\n\n\/\/ GestureRecognizer, static\nvoid GestureRecognizer::Reset() {\n delete g_gesture_recognizer_instance;\n g_gesture_recognizer_instance = NULL;\n}\n\nvoid SetGestureRecognizerForTesting(GestureRecognizer* gesture_recognizer) {\n \/\/ Transfer helpers to the new GR.\n std::vector& helpers =\n g_gesture_recognizer_instance->helpers();\n std::vector::iterator it;\n for (it = helpers.begin(); it != helpers.end(); ++it)\n gesture_recognizer->AddGestureEventHelper(*it);\n\n helpers.clear();\n g_gesture_recognizer_instance =\n static_cast(gesture_recognizer);\n}\n\n} \/\/ namespace ui\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n\n#include \"UsbHandler.h\"\n#include \"LibusbDevice.h\"\n\n#include \"logging.h\"\n\n#include \n\nnamespace tcam\n{\n\nUsbHandler& UsbHandler::get_instance ()\n{\n static UsbHandler instance;\n\n return instance;\n}\n\n\nUsbHandler::UsbHandler ():\n session(new UsbSession())\n{}\n\n\nUsbHandler::~UsbHandler()\n{}\n\n\nstruct libusb_device_handle* UsbHandler::open_device (const std::string& serial)\n{\n struct libusb_device_handle* ret = nullptr;\n\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209)\n continue;\n\n r = libusb_open(devs[i], &ret);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n char tmp_str[sizeof(tcam_device_info::serial_number)];\n\n libusb_get_string_descriptor_ascii(ret, desc.iSerialNumber,\n (unsigned char*)tmp_str,\n sizeof(tcam_device_info::serial_number));\n if (serial.compare(tmp_str) == 0)\n {\n\n break;\n }\n\n libusb_close(ret);\n\n }\n\n libusb_free_device_list(devs, 1);\n\n\n return ret;\n}\n\n\nstd::vector UsbHandler::get_device_list ()\n{\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n std::vector ret;\n ret.reserve(5);\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209)\n continue;\n\n tcam_device_info d = { };\n\n d.type = TCAM_DEVICE_TYPE_LIBUSB;\n\n \/\/ d.idVendor = desc.idVendor;\n \/\/ d.idProduct = desc.idProduct;\n\n \/\/ strcpy(d.name, \"AFU050\");\n \/\/ strcpy(d.serial_number, \"47614135\");\n \/\/ strcpy(d.additional_identifier, \"9209\");\n\n libusb_device_handle* dh;\n r = libusb_open(devs[i], &dh);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n libusb_get_string_descriptor_ascii(dh, desc.iProduct, (unsigned char*)d.name, sizeof(d.name));\n\n \/\/ libusb_get_string_descriptor_ascii(dh, desc.iManufacturer, (unsigned char*)d.manufacturer, sizeof(d.manufacturer));\n \/\/ int lib_ret = libusb_get_port_numbers(dh, (uint8_t*)d.identifier, sizeof(d.identifier))\n\n libusb_get_string_descriptor_ascii(dh, desc.idProduct, (unsigned char*)d.additional_identifier, sizeof(d.additional_identifier));\n libusb_get_string_descriptor_ascii(dh, desc.iSerialNumber, (unsigned char*)d.serial_number, sizeof(d.serial_number));\n\n libusb_close(dh);\n ret.push_back(DeviceInfo(d));\n }\n\n libusb_free_device_list(devs, 1);\n\n return ret;\n}\n\n\n\/\/ std::shared_ptr UsbHandler::open_camera (std::string serial_number)\n\/\/ {\n\/\/ auto list = get_device_list();\n\/\/ device_info d;\n\n\/\/ for (auto& dev : list)\n\/\/ {\n\/\/ \/\/ std::cout << \"Comparing |\" << dev.serial << \"|\" << (unsigned char*)serial_number.c_str() << \"|\" << std::endl;\n\/\/ if (serial_number.compare(dev.serial) == 0)\n\/\/ {\n\/\/ \/\/ std::cout << \"dev.serial \" << dev.serial << \";serial \" << serial_number << std::endl;\n\/\/ d = dev;\n\/\/ break;\n\/\/ }\n\/\/ }\n\n\/\/ camera_type t = find_camera_type(d.idVendor, d.idProduct);\n\n\n\/\/ switch(t.camera_type)\n\/\/ {\n\/\/ case USB33:\n\/\/ return std::make_shared(this->session, d);\n\/\/ case USB3:\n\/\/ return std::make_shared(this->session, d);\n\/\/ case USB2:\n\/\/ return std::make_shared(this->session, d);\n\/\/ case UNKNOWN:\n\/\/ default:\n\/\/ return nullptr;\n\/\/ }\n\/\/ }\n\n\nstd::shared_ptr UsbHandler::get_session ()\n{\n return this->session;\n}\n\n}; \/* namespace tis *\/\nAdd afu420 device listing and libusb_device_handle opening\/*\n * Copyright 2014 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n\n#include \"UsbHandler.h\"\n#include \"LibusbDevice.h\"\n\n#include \"logging.h\"\n\n#include \n\nnamespace tcam\n{\n\nUsbHandler& UsbHandler::get_instance ()\n{\n static UsbHandler instance;\n\n return instance;\n}\n\n\nUsbHandler::UsbHandler ():\n session(new UsbSession())\n{}\n\n\nUsbHandler::~UsbHandler()\n{}\n\n\nstruct libusb_device_handle* UsbHandler::open_device (const std::string& serial)\n{\n struct libusb_device_handle* ret = nullptr;\n\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209 && desc.idProduct != 0x0804)\n continue;\n\n r = libusb_open(devs[i], &ret);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n char tmp_str[sizeof(tcam_device_info::serial_number)];\n\n libusb_get_string_descriptor_ascii(ret, desc.iSerialNumber,\n (unsigned char*)tmp_str,\n sizeof(tcam_device_info::serial_number));\n if (serial.compare(tmp_str) == 0)\n {\n\n break;\n }\n\n libusb_close(ret);\n\n }\n\n libusb_free_device_list(devs, 1);\n\n\n return ret;\n}\n\n\nstd::vector UsbHandler::get_device_list ()\n{\n libusb_device** devs;\n\n int cnt = libusb_get_device_list(this->session->get_session(), &devs);\n\n if (cnt < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device list. \" + std::to_string(cnt));\n }\n\n std::vector ret;\n ret.reserve(5);\n\n for (ssize_t i = 0; i < cnt; i++)\n {\n libusb_device_descriptor desc;\n int r = libusb_get_device_descriptor(devs[i], &desc);\n if (r < 0)\n {\n throw std::runtime_error(\"Unable to retrieve device descriptor. \" + std::to_string(cnt));\n }\n\n \/\/ ignore all devices that are not from TIS or otherwise needed\n if (desc.idVendor != 0x199e)\n continue;\n\n if (desc.idProduct != 0x8209 && desc.idProduct != 0x0804)\n continue;\n\n tcam_device_info d = { };\n\n d.type = TCAM_DEVICE_TYPE_LIBUSB;\n\n \/\/ d.idVendor = desc.idVendor;\n \/\/ d.idProduct = desc.idProduct;\n\n \/\/ strcpy(d.name, \"AFU050\");\n \/\/ strcpy(d.serial_number, \"47614135\");\n \/\/ strcpy(d.additional_identifier, \"9209\");\n\n libusb_device_handle* dh;\n r = libusb_open(devs[i], &dh);\n\n if (r < 0)\n {\n tcam_log(TCAM_LOG_ERROR, \"Unable to open device.\");\n continue;\n }\n\n libusb_get_string_descriptor_ascii(dh, desc.iProduct, (unsigned char*)d.name, sizeof(d.name));\n\n \/\/ libusb_get_string_descriptor_ascii(dh, desc.iManufacturer, (unsigned char*)d.manufacturer, sizeof(d.manufacturer));\n \/\/ int lib_ret = libusb_get_port_numbers(dh, (uint8_t*)d.identifier, sizeof(d.identifier))\n\n libusb_get_string_descriptor_ascii(dh, desc.idProduct, (unsigned char*)d.additional_identifier, sizeof(d.additional_identifier));\n libusb_get_string_descriptor_ascii(dh, desc.iSerialNumber, (unsigned char*)d.serial_number, sizeof(d.serial_number));\n\n libusb_close(dh);\n ret.push_back(DeviceInfo(d));\n }\n\n libusb_free_device_list(devs, 1);\n\n return ret;\n}\n\n\n\/\/ std::shared_ptr UsbHandler::open_camera (std::string serial_number)\n\/\/ {\n\/\/ auto list = get_device_list();\n\/\/ device_info d;\n\n\/\/ for (auto& dev : list)\n\/\/ {\n\/\/ \/\/ std::cout << \"Comparing |\" << dev.serial << \"|\" << (unsigned char*)serial_number.c_str() << \"|\" << std::endl;\n\/\/ if (serial_number.compare(dev.serial) == 0)\n\/\/ {\n\/\/ \/\/ std::cout << \"dev.serial \" << dev.serial << \";serial \" << serial_number << std::endl;\n\/\/ d = dev;\n\/\/ break;\n\/\/ }\n\/\/ }\n\n\/\/ camera_type t = find_camera_type(d.idVendor, d.idProduct);\n\n\n\/\/ switch(t.camera_type)\n\/\/ {\n\/\/ case USB33:\n\/\/ return std::make_shared(this->session, d);\n\/\/ case USB3:\n\/\/ return std::make_shared(this->session, d);\n\/\/ case USB2:\n\/\/ return std::make_shared(this->session, d);\n\/\/ case UNKNOWN:\n\/\/ default:\n\/\/ return nullptr;\n\/\/ }\n\/\/ }\n\n\nstd::shared_ptr UsbHandler::get_session ()\n{\n return this->session;\n}\n\n}; \/* namespace tis *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"analog.pb.h\"\n#include \"analogchan.h\"\n#include \"matStor.h\"\n#include \"analogwriter.h\"\n\n#define u64 unsigned long long\n#define i64 long long\n#define u32 unsigned int\n\n\/\/#define _LARGEFILE_SOURCE enabled by default.\n#define _FILE_OFFSET_BITS 64\n\nusing namespace std;\nusing namespace google::protobuf;\nusing namespace gtkclient;\n\nint main(int argn, char **argc)\n{\n\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\tifstream in;\n\n\tif (argn != 3 && argn != 2) {\n\t\tprintf(\"usage: analog2mat infile.dat outfile.mat\\n\");\n\t\tprintf(\" or just: analog2mat infile.dat\\n\");\n\t\texit(0);\n\t}\n\n\t\/\/ in file\n\tin.open(argc[1]);\n\tif (!in.good()) {\n\t\tfprintf(stderr,\"Could not open %s\\n\", argc[1]);\n\t\texit(0);\n\t}\n\n\t\/\/ out file\n\tint nn = strlen(argc[1]);\n\tif (nn < 5 || nn > 511) {\n\t\tprintf(\" infile not .bin?\\n\");\n\t\texit(0);\n\t}\n\tchar s[512];\n\tif (argn == 2) {\n\t\tstrncpy(s, argc[1], 512);\n\t\ts[nn-3] = 'm';\n\t\ts[nn-2] = 'a';\n\t\ts[nn-1] = 't';\n\t} else {\n\t\tstrncpy(s, argc[2], 512);\n\t}\n\tMatStor ms(s);\n\n\tunsigned long packets=0;\n\tmap analchans;\n\n\twhile (!in.eof()) {\n\n\t\t\/\/ read magic\n\t\tunsigned int magic;\n\t\tin.read((char *) &magic, sizeof(magic));\n\t\tif (in.eof())\n\t\t\tbreak;\n\t\tif (in.fail() || in.gcount() != sizeof (magic)) {\n\t\t\tfprintf(stderr,\n\t\t\t \"read magic failure. gcount: %ld at %d\\n\",\n\t\t\t in.gcount(), (int) in.tellg());\n\t\t\texit(0);\n\t\t}\n\t\tif (magic != ANALOG_MAGIC) {\n\t\t\tfprintf(stderr, \"packet %ld: magic value, %X, does not match expected value, %X.\\n\", packets+1, magic, ANALOG_MAGIC);\n\t\t\texit(0);\n\t\t}\n\n\t\t\/\/ read size\n\t\tunsigned int sz;\n\t\tin.read((char *) &sz, sizeof (sz));\n\t\tif (in.eof())\n\t\t\texit(0);\n\t\tif (in.fail() || in.gcount() != sizeof (sz)) {\n\t\t\tfprintf(stderr, \"read size failure. gcount: %ld at %d\\n\",\n\t\t\t in.gcount(), (int) in.tellg());\n\t\t\texit(0);\n\t\t}\n\t\tif (sz > 131072) { \/\/ hardcoded for now xxx\n\t\t\tfprintf(stderr, \"single packet too long for buffer: %u.\\n\", sz);\n\t\t\texit(0);\n\t\t}\n\n\t\t\/\/ read protobuf packet\n\t\tchar buf[131072]; \/\/ xxx\n\t\tin.read(buf, sz);\n\t\tif (in.fail() || in.eof() || in.gcount() != sz) {\n\t\t\tfprintf(stderr, \"read protobuf packet failure\\n\");\n\t\t\texit(0);\n\t\t}\n\n\t\t\/\/ parse protobuf\n\t\tAnalog a;\n\t\ta.Clear();\n\t\tif (!a.ParseFromArray(buf, sz)) {\n\t\t\tfprintf(stderr, \"failed to parse protobuf packet %ld (%d bytes). aborting here.\\n\",\n\t\t\t packets+1, sz);\n\t\t\tbreak;\n\t\t}\n\n\t\tunsigned int ch = a.chan();\n\n\t\t\/\/ try to find the analog chan in our map\n\t\tAnalogChan *ac = NULL;\n\t\tif (analchans.find(ch) == analchans.end()) {\n\t\t\t\/\/ not found, it is a new chan\n\t\t\tac = new AnalogChan();\n\t\t\tif (!ac) {\n\t\t\t\tfprintf(stderr, \"Out of memory\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tanalchans[ch] = ac;\n\t\t\tac->chan = ch;\n\t\t} else {\n\t\t\t\/\/ found, set pointer to exisiting analog chan\n\t\t\tac = analchans[ch];\n\t\t}\n\n\t\tif (a.tick_size() != a.sample_size()) {\n\t\t\tfprintf(stderr, \"samples and ticks dont align!\\n\");\n\t\t\texit(0);\n\t\t}\n\n\t\tfor (int i=0; iadd_sample(a.ts(i), a.tick(i), a.sample(i)))\n\t\t\t\tfprintf(stderr, \"Error adding sample for analog chan %u (packet %lu)\\n\", ch, packets);\n\n\t\tpackets++;\n\t\t\/\/printf(\"parsed %ld packets\\n\", packets);\n\n\t}\n\tin.close();\n\n\tShutdownProtobufLibrary();\n\n\n\tprintf(\"Parsing complete. %lu total packets from %lu analog chans.\\n\",\n\t packets, analchans.size());\n\n\t\/\/ now write each stim chan\n\tmap::iterator it;\n\tfor (it = analchans.begin(); it != analchans.end(); it++) {\n\t\tprintf(\"analog ch: %d\\n\", (*it).second->chan);\n\t\t(*it).second->save(&ms);\n\t}\n\n\tms.save();\n\n\treturn 0;\n}change some instances to packets+1 since counting from zero doesnt make sense for this#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"analog.pb.h\"\n#include \"analogchan.h\"\n#include \"matStor.h\"\n#include \"analogwriter.h\"\n\n#define u64 unsigned long long\n#define i64 long long\n#define u32 unsigned int\n\n\/\/#define _LARGEFILE_SOURCE enabled by default.\n#define _FILE_OFFSET_BITS 64\n\nusing namespace std;\nusing namespace google::protobuf;\nusing namespace gtkclient;\n\nint main(int argn, char **argc)\n{\n\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\tifstream in;\n\n\tif (argn != 3 && argn != 2) {\n\t\tprintf(\"usage: analog2mat infile.dat outfile.mat\\n\");\n\t\tprintf(\" or just: analog2mat infile.dat\\n\");\n\t\texit(0);\n\t}\n\n\t\/\/ in file\n\tin.open(argc[1]);\n\tif (!in.good()) {\n\t\tfprintf(stderr,\"Could not open %s\\n\", argc[1]);\n\t\texit(0);\n\t}\n\n\t\/\/ out file\n\tint nn = strlen(argc[1]);\n\tif (nn < 5 || nn > 511) {\n\t\tprintf(\" infile not .bin?\\n\");\n\t\texit(0);\n\t}\n\tchar s[512];\n\tif (argn == 2) {\n\t\tstrncpy(s, argc[1], 512);\n\t\ts[nn-3] = 'm';\n\t\ts[nn-2] = 'a';\n\t\ts[nn-1] = 't';\n\t} else {\n\t\tstrncpy(s, argc[2], 512);\n\t}\n\tMatStor ms(s);\n\n\tunsigned long packets=0;\n\tmap analchans;\n\n\twhile (!in.eof()) {\n\n\t\t\/\/ read magic\n\t\tunsigned int magic;\n\t\tin.read((char *) &magic, sizeof(magic));\n\t\tif (in.eof())\n\t\t\tbreak;\n\t\tif (in.fail() || in.gcount() != sizeof (magic)) {\n\t\t\tfprintf(stderr,\n\t\t\t \"read magic failure. gcount: %ld at %d\\n\",\n\t\t\t in.gcount(), (int) in.tellg());\n\t\t\texit(0);\n\t\t}\n\t\tif (magic != ANALOG_MAGIC) {\n\t\t\tfprintf(stderr, \"packet %ld: magic value, %X, does not match expected value, %X. aborting here.\\n\",\n\t\t\t packets+1, magic, ANALOG_MAGIC);\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ read size\n\t\tunsigned int sz;\n\t\tin.read((char *) &sz, sizeof (sz));\n\t\tif (in.eof())\n\t\t\texit(0);\n\t\tif (in.fail() || in.gcount() != sizeof (sz)) {\n\t\t\tfprintf(stderr, \"read size failure. gcount: %ld at %d\\n\",\n\t\t\t in.gcount(), (int) in.tellg());\n\t\t\texit(0);\n\t\t}\n\t\tif (sz > 131072) { \/\/ hardcoded for now xxx\n\t\t\tfprintf(stderr, \"single packet too long for buffer: %u.\\n\", sz);\n\t\t\texit(0);\n\t\t}\n\n\t\t\/\/ read protobuf packet\n\t\t\/\/ max int32 is 2,147,483,647\n\t\t\/\/ max uint32 is 4,294,967,295\n\t\tchar buf[131072]; \/\/ xxx\n\t\tin.read(buf, sz);\n\t\tif (in.fail() || in.eof() || in.gcount() != sz) {\n\t\t\tfprintf(stderr, \"read protobuf packet failure\\n\");\n\t\t\texit(0);\n\t\t}\n\n\t\t\/\/ parse protobuf\n\t\tAnalog a;\n\t\ta.Clear();\n\t\tif (!a.ParseFromArray(buf, sz)) {\n\t\t\tfprintf(stderr, \"failed to parse protobuf packet %ld (%d bytes). aborting here.\\n\",\n\t\t\t packets+1, sz);\n\t\t\tbreak;\n\t\t}\n\n\t\tunsigned int ch = a.chan();\n\n\t\t\/\/ try to find the analog chan in our map\n\t\tAnalogChan *ac = NULL;\n\t\tif (analchans.find(ch) == analchans.end()) {\n\t\t\t\/\/ not found, it is a new chan\n\t\t\tac = new AnalogChan();\n\t\t\tif (!ac) {\n\t\t\t\tfprintf(stderr, \"Out of memory\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tanalchans[ch] = ac;\n\t\t\tac->chan = ch;\n\t\t} else {\n\t\t\t\/\/ found, set pointer to exisiting analog chan\n\t\t\tac = analchans[ch];\n\t\t}\n\n\t\tif (a.tick_size() != a.sample_size()) {\n\t\t\tfprintf(stderr, \"samples and ticks dont align!\\n\");\n\t\t\texit(0);\n\t\t}\n\n\t\tfor (int i=0; iadd_sample(a.ts(i), a.tick(i), a.sample(i)))\n\t\t\t\tfprintf(stderr, \"Error adding sample for analog chan %u (packet %lu)\\n\", ch, packets+1);\n\n\t\tpackets++;\n\t\t\/\/printf(\"parsed %ld packets\\n\", packets);\n\n\t}\n\tin.close();\n\n\tShutdownProtobufLibrary();\n\n\n\tprintf(\"Parsing complete. %lu total packets from %lu analog chans.\\n\",\n\t packets+1, analchans.size());\n\n\t\/\/ now write each stim chan\n\tmap::iterator it;\n\tfor (it = analchans.begin(); it != analchans.end(); it++) {\n\t\tprintf(\"analog ch: %d\\n\", (*it).second->chan);\n\t\t(*it).second->save(&ms);\n\t}\n\n\tms.save();\n\n\treturn 0;\n}<|endoftext|>"} {"text":"\/\/\n\/\/ rv-meta.cc\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"util.h\"\n#include \"cmdline.h\"\n#include \"model.h\"\n#include \"gen.h\"\n\nconst ssize_t kMaxInstructionWidth = 32;\n\nconst char* kCHeader =\nR\"C(\/\/\n\/\/ %s\n\/\/\n\/\/ DANGER - This is machine generated code\n\/\/\n\n)C\";\n\nvoid rv_codec_node::clear()\n{\n\tbits.clear();\n\tvals.clear();\n\tval_opcodes.clear();\n\tval_decodes.clear();\n}\n\nrv_gen::rv_gen()\n{\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n}\n\nvoid rv_gen::generate(int argc, const char *argv[])\n{\n\tstd::string isa_spec = \"\";\n\tbool help_or_error = false;\n\n\t\/\/ get generator command line options\n\tstd::vector options = {\n\t\t{ \"-h\", \"--help\", cmdline_arg_type_none,\n\t\t\t\"Show help\",\n\t\t\t[&](std::string s) { return (help_or_error = true); } },\n\t\t{ \"-I\", \"--isa-subset\", cmdline_arg_type_string,\n\t\t\t\"ISA subset (e.g. RV32IMA, RV32G, RV32GSC, RV64IMA, RV64G, RV64GSC)\",\n\t\t\t[&](std::string s) { isa_spec = s; return true; } },\n\t\t{ \"-r\", \"--read-isa\", cmdline_arg_type_string,\n\t\t\t\"Read instruction set metadata from directory\",\n\t\t\t[&](std::string s) { return read_metadata(s); } },\n\t\t{ \"-N\", \"--no-comment\", cmdline_arg_type_none,\n\t\t\t\"Don't emit comments in generated source\",\n\t\t\t[&](std::string s) { return set_option(\"no_comment\"); } },\n\t\t{ \"-0\", \"--numeric-constants\", cmdline_arg_type_none,\n\t\t\t\"Use numeric constants in generated source\",\n\t\t\t[&](std::string s) { return set_option(\"zero_not_oh\"); } },\n\t};\n\tfor (auto &gen : generators) {\n\t\tauto gen_opts = gen->get_cmdline_options();\n\t\tstd::copy(gen_opts.begin(), gen_opts.end(), std::back_inserter(options));\n\t}\n\toptions.push_back(\n\t\t{ nullptr, nullptr, cmdline_arg_type_none, nullptr, nullptr }\n\t);\n\n\tauto result = cmdline_option::process_options(options.data(), argc, argv);\n\tif (!result.second) {\n\t\thelp_or_error = true;\n\t} else if (result.first.size() != 0) {\n\t\tprintf(\"%s: wrong number of arguments\\n\", argv[0]);\n\t\thelp_or_error = true;\n\t}\n\tif (help_or_error) {\n\t\tprintf(\"usage: %s []\\n\", argv[0]);\n\t\tcmdline_option::print_options(options.data());\n\t\texit(9);\n\t}\n\n\text_subset = decode_isa_extensions(isa_spec);\n\tgenerate_map();\n\n\tfor (auto &gen : generators) {\n\t\tgen->generate();\n\t}\n}\n\nvoid rv_gen::generate_map()\n{\n\tfor (auto &opcode : all_opcodes) {\n\t\tfor (auto &mask : opcode->masks) {\n\t\t\tssize_t msb = mask.first.msb;\n\t\t\tssize_t lsb = mask.first.lsb;\n\t\t\tssize_t val = mask.second;\n\t\t\tfor (ssize_t bit = msb; bit >= lsb; bit--) {\n\t\t\t\topcode->mask |= (1ULL << bit);\n\t\t\t\topcode->match |= ((uint64_t(val) >> (bit - lsb)) & 1) << bit;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid rv_gen::generate_codec()\n{\n\t\/\/ make list of opcodes to include\n\trv_opcode_list opcodes_copy;\n\tfor (auto &opcode : all_opcodes) {\n\t\tif (opcode->is_pseudo()) continue;\n\t\topcodes_copy.push_back(opcode);\n\t}\n\n\t\/\/ generate decode\n\troot_node.clear();\n\tgenerate_codec_node(root_node, opcodes_copy);\n}\n\nvoid rv_gen::generate_codec_node(rv_codec_node &node, rv_opcode_list &opcode_list)\n{\n\t\/\/ calculate row coverage for each column\n\tstd::vector sum;\n\tsum.resize(32);\n\tfor (auto &opcode : opcode_list) {\n\t\tfor (ssize_t bit = kMaxInstructionWidth-1; bit >= 0; bit--) {\n\t\t\tif ((opcode->mask & (1 << bit)) && !(opcode->done & (1 << bit))) sum[bit]++;\n\t\t}\n\t}\n\n\t\/\/ find column with maximum row coverage\n\tssize_t max_rows = 0;\n\tfor (ssize_t bit = kMaxInstructionWidth-1; bit >= 0; bit--) {\n\t\tif (sum[bit] > max_rows) max_rows = sum[bit];\n\t}\n\n\tif (max_rows == 0) return; \/\/ no bits to match\n\n\t\/\/ select bits that cover maximum number of rows\n\tfor (ssize_t bit = kMaxInstructionWidth-1; bit >= 0; bit--) {\n\t\tif (sum[bit] == max_rows) node.bits.push_back(bit);\n\t}\n\n\t\/\/ find distinct values for the chosen bits\n\tfor (auto &opcode : opcode_list) {\n\n\t\tssize_t val = 0;\n\t\tbool partial_match = false;\n\t\tfor (auto &bit : node.bits) {\n\t\t\tif (!(opcode->mask & (1 << bit))) {\n\t\t\t\tpartial_match = true;\n\t\t\t} else {\n\t\t\t\tval = (val << 1) | ((opcode->match & (1 << bit)) ? 1 : 0);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ partial match is default in switch containing more specific masks\n\t\tif (partial_match) {\n\t\t\tval = DEFAULT;\n\t\t}\n\n\t\t\/\/ add value to list\n\t\tif (std::find(node.vals.begin(), node.vals.end(), val) == node.vals.end()) {\n\t\t\tnode.vals.push_back(val);\n\t\t}\n\n\t\t\/\/ create opcode list for this value and add opcode to the list\n\t\tauto val_opcode_list_i = node.val_opcodes.find(val);\n\t\tif (val_opcode_list_i == node.val_opcodes.end()) {\n\t\t\tval_opcode_list_i = node.val_opcodes.insert(node.val_opcodes.begin(),\n\t\t\t\tstd::pair(val, rv_opcode_list()));\n\t\t}\n\t\tval_opcode_list_i->second.push_back(opcode);\n\t}\n\n\t\/\/ sort values\n\tstd::sort(node.vals.begin(), node.vals.end());\n\n\t\/\/ mark chosen bits as done\n\tfor (auto &opcode : opcode_list) {\n\t\tfor (auto &bit : node.bits) {\n\t\t\topcode->done |= (1 << bit);\n\t\t}\n\t}\n\n\t\/\/ recurse\n\tfor (auto &val : node.vals) {\n\t\tif (node.val_decodes.find(val) == node.val_decodes.end()) {\n\t\t\tnode.val_decodes.insert(node.val_decodes.begin(),\n\t\t\t\tstd::pair(val, rv_codec_node()));\n\t\t}\n\t\tgenerate_codec_node(node.val_decodes[val], node.val_opcodes[val]);\n\t}\n}\n\n\/* main *\/\n\nint main(int argc, const char *argv[])\n{\n\trv_gen gen;\n\tgen.generate(argc, argv);\n\texit(0);\n}\nRemove include from rv-meta\/\/\n\/\/ rv-meta.cc\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"util.h\"\n#include \"cmdline.h\"\n#include \"model.h\"\n#include \"gen.h\"\n\nconst ssize_t kMaxInstructionWidth = 32;\n\nconst char* kCHeader =\nR\"C(\/\/\n\/\/ %s\n\/\/\n\/\/ DANGER - This is machine generated code\n\/\/\n\n)C\";\n\nvoid rv_codec_node::clear()\n{\n\tbits.clear();\n\tvals.clear();\n\tval_opcodes.clear();\n\tval_decodes.clear();\n}\n\nrv_gen::rv_gen()\n{\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n\tgenerators.push_back(std::make_shared(this));\n}\n\nvoid rv_gen::generate(int argc, const char *argv[])\n{\n\tstd::string isa_spec = \"\";\n\tbool help_or_error = false;\n\n\t\/\/ get generator command line options\n\tstd::vector options = {\n\t\t{ \"-h\", \"--help\", cmdline_arg_type_none,\n\t\t\t\"Show help\",\n\t\t\t[&](std::string s) { return (help_or_error = true); } },\n\t\t{ \"-I\", \"--isa-subset\", cmdline_arg_type_string,\n\t\t\t\"ISA subset (e.g. RV32IMA, RV32G, RV32GSC, RV64IMA, RV64G, RV64GSC)\",\n\t\t\t[&](std::string s) { isa_spec = s; return true; } },\n\t\t{ \"-r\", \"--read-isa\", cmdline_arg_type_string,\n\t\t\t\"Read instruction set metadata from directory\",\n\t\t\t[&](std::string s) { return read_metadata(s); } },\n\t\t{ \"-N\", \"--no-comment\", cmdline_arg_type_none,\n\t\t\t\"Don't emit comments in generated source\",\n\t\t\t[&](std::string s) { return set_option(\"no_comment\"); } },\n\t\t{ \"-0\", \"--numeric-constants\", cmdline_arg_type_none,\n\t\t\t\"Use numeric constants in generated source\",\n\t\t\t[&](std::string s) { return set_option(\"zero_not_oh\"); } },\n\t};\n\tfor (auto &gen : generators) {\n\t\tauto gen_opts = gen->get_cmdline_options();\n\t\tstd::copy(gen_opts.begin(), gen_opts.end(), std::back_inserter(options));\n\t}\n\toptions.push_back(\n\t\t{ nullptr, nullptr, cmdline_arg_type_none, nullptr, nullptr }\n\t);\n\n\tauto result = cmdline_option::process_options(options.data(), argc, argv);\n\tif (!result.second) {\n\t\thelp_or_error = true;\n\t} else if (result.first.size() != 0) {\n\t\tprintf(\"%s: wrong number of arguments\\n\", argv[0]);\n\t\thelp_or_error = true;\n\t}\n\tif (help_or_error) {\n\t\tprintf(\"usage: %s []\\n\", argv[0]);\n\t\tcmdline_option::print_options(options.data());\n\t\texit(9);\n\t}\n\n\text_subset = decode_isa_extensions(isa_spec);\n\tgenerate_map();\n\n\tfor (auto &gen : generators) {\n\t\tgen->generate();\n\t}\n}\n\nvoid rv_gen::generate_map()\n{\n\tfor (auto &opcode : all_opcodes) {\n\t\tfor (auto &mask : opcode->masks) {\n\t\t\tssize_t msb = mask.first.msb;\n\t\t\tssize_t lsb = mask.first.lsb;\n\t\t\tssize_t val = mask.second;\n\t\t\tfor (ssize_t bit = msb; bit >= lsb; bit--) {\n\t\t\t\topcode->mask |= (1ULL << bit);\n\t\t\t\topcode->match |= ((uint64_t(val) >> (bit - lsb)) & 1) << bit;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid rv_gen::generate_codec()\n{\n\t\/\/ make list of opcodes to include\n\trv_opcode_list opcodes_copy;\n\tfor (auto &opcode : all_opcodes) {\n\t\tif (opcode->is_pseudo()) continue;\n\t\topcodes_copy.push_back(opcode);\n\t}\n\n\t\/\/ generate decode\n\troot_node.clear();\n\tgenerate_codec_node(root_node, opcodes_copy);\n}\n\nvoid rv_gen::generate_codec_node(rv_codec_node &node, rv_opcode_list &opcode_list)\n{\n\t\/\/ calculate row coverage for each column\n\tstd::vector sum;\n\tsum.resize(32);\n\tfor (auto &opcode : opcode_list) {\n\t\tfor (ssize_t bit = kMaxInstructionWidth-1; bit >= 0; bit--) {\n\t\t\tif ((opcode->mask & (1 << bit)) && !(opcode->done & (1 << bit))) sum[bit]++;\n\t\t}\n\t}\n\n\t\/\/ find column with maximum row coverage\n\tssize_t max_rows = 0;\n\tfor (ssize_t bit = kMaxInstructionWidth-1; bit >= 0; bit--) {\n\t\tif (sum[bit] > max_rows) max_rows = sum[bit];\n\t}\n\n\tif (max_rows == 0) return; \/\/ no bits to match\n\n\t\/\/ select bits that cover maximum number of rows\n\tfor (ssize_t bit = kMaxInstructionWidth-1; bit >= 0; bit--) {\n\t\tif (sum[bit] == max_rows) node.bits.push_back(bit);\n\t}\n\n\t\/\/ find distinct values for the chosen bits\n\tfor (auto &opcode : opcode_list) {\n\n\t\tssize_t val = 0;\n\t\tbool partial_match = false;\n\t\tfor (auto &bit : node.bits) {\n\t\t\tif (!(opcode->mask & (1 << bit))) {\n\t\t\t\tpartial_match = true;\n\t\t\t} else {\n\t\t\t\tval = (val << 1) | ((opcode->match & (1 << bit)) ? 1 : 0);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ partial match is default in switch containing more specific masks\n\t\tif (partial_match) {\n\t\t\tval = DEFAULT;\n\t\t}\n\n\t\t\/\/ add value to list\n\t\tif (std::find(node.vals.begin(), node.vals.end(), val) == node.vals.end()) {\n\t\t\tnode.vals.push_back(val);\n\t\t}\n\n\t\t\/\/ create opcode list for this value and add opcode to the list\n\t\tauto val_opcode_list_i = node.val_opcodes.find(val);\n\t\tif (val_opcode_list_i == node.val_opcodes.end()) {\n\t\t\tval_opcode_list_i = node.val_opcodes.insert(node.val_opcodes.begin(),\n\t\t\t\tstd::pair(val, rv_opcode_list()));\n\t\t}\n\t\tval_opcode_list_i->second.push_back(opcode);\n\t}\n\n\t\/\/ sort values\n\tstd::sort(node.vals.begin(), node.vals.end());\n\n\t\/\/ mark chosen bits as done\n\tfor (auto &opcode : opcode_list) {\n\t\tfor (auto &bit : node.bits) {\n\t\t\topcode->done |= (1 << bit);\n\t\t}\n\t}\n\n\t\/\/ recurse\n\tfor (auto &val : node.vals) {\n\t\tif (node.val_decodes.find(val) == node.val_decodes.end()) {\n\t\t\tnode.val_decodes.insert(node.val_decodes.begin(),\n\t\t\t\tstd::pair(val, rv_codec_node()));\n\t\t}\n\t\tgenerate_codec_node(node.val_decodes[val], node.val_opcodes[val]);\n\t}\n}\n\n\/* main *\/\n\nint main(int argc, const char *argv[])\n{\n\trv_gen gen;\n\tgen.generate(argc, argv);\n\texit(0);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017-2018 ARM Limited\n * All rights reserved.\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __BASE_REFCNT_HH__\n#define __BASE_REFCNT_HH__\n\n#include \n\n\/**\n * @file base\/refcnt.hh\n *\n * Classes for managing reference counted objects.\n *\/\n\n\/**\n * Derive from RefCounted if you want to enable reference counting of\n * this class. If you want to use automatic reference counting, you\n * should use RefCountingPtr instead of regular pointers.\n *\/\nclass RefCounted\n{\n private:\n \/\/ The reference count is mutable because one may want to\n \/\/ reference count a const pointer. This really is OK because\n \/\/ const is about logical constness of the object not really about\n \/\/ strictly disallowing an object to change.\n mutable int count;\n\n private:\n \/\/ Don't allow a default copy constructor or copy operator on\n \/\/ these objects because the default operation will copy the\n \/\/ reference count as well and we certainly don't want that.\n RefCounted(const RefCounted &);\n RefCounted &operator=(const RefCounted &);\n\n public:\n \/**\n * We initialize the reference count to zero and the first object\n * to take ownership of it must increment it to one.\n *\n * @attention A memory leak will occur if you never assign a newly\n * constructed object to a reference counting pointer.\n *\/\n RefCounted() : count(0) {}\n\n \/**\n * We make the destructor virtual because we're likely to have\n * virtual functions on reference counted objects.\n *\n * @todo Even if this were true, does it matter? Shouldn't the\n * derived class indicate this? This only matters if we would\n * ever choose to delete a \"RefCounted *\" which I doubt we'd ever\n * do. We don't ever delete a \"void *\".\n *\/\n virtual ~RefCounted() {}\n\n \/\/\/ Increment the reference count\n void incref() const { ++count; }\n\n \/\/\/ Decrement the reference count and destroy the object if all\n \/\/\/ references are gone.\n void decref() const { if (--count <= 0) delete this; }\n};\n\n\/**\n * If you want a reference counting pointer to a mutable object,\n * create it like this:\n * @code\n * typedef RefCountingPtr FooPtr;\n * @endcode\n *\n * @attention Do not use \"const FooPtr\"\n * To create a reference counting pointer to a const object, use this:\n * @code\n * typedef RefCountingPtr ConstFooPtr;\n * @endcode\n *\n * These two usages are analogous to iterator and const_iterator in the stl.\n *\/\ntemplate \nclass RefCountingPtr\n{\n public:\n using PtrType = T*;\n\n protected:\n \/** Convenience aliases for const\/non-const versions of T w\/ friendship. *\/\n \/** @{ *\/\n static constexpr auto TisConst = std::is_const::value;\n using ConstT = typename std::conditional,\n RefCountingPtr::type>>::type;\n friend ConstT;\n using NonConstT = typename std::conditional::type>,\n RefCountingPtr>::type;\n friend NonConstT;\n \/** @} *\/\n \/\/\/ The stored pointer.\n \/\/\/ Arguably this should be private.\n T *data;\n\n \/**\n * Copy a new pointer value and increment the reference count if\n * it is a valid pointer. Note, this does not delete the\n * reference any existing object.\n * @param d Pointer to store.\n *\/\n void\n copy(T *d)\n {\n data = d;\n if (data)\n data->incref();\n }\n\n \/**\n * Delete the reference to any existing object if it is non NULL.\n * @attention this doesn't clear the pointer value, so a double\n * decref could happen if not careful.\n *\/\n void\n del()\n {\n if (data)\n data->decref();\n }\n\n \/**\n * Drop the old reference and change it to something new.\n *\/\n void\n set(T *d)\n {\n \/\/ Need to check if we're actually changing because otherwise\n \/\/ we could delete the last reference before adding the new\n \/\/ reference.\n if (data != d) {\n del();\n copy(d);\n }\n }\n\n public:\n \/\/\/ Create an empty reference counting pointer.\n RefCountingPtr() : data(0) {}\n\n \/\/\/ Create a new reference counting pointer to some object\n \/\/\/ (probably something newly created). Adds a reference.\n RefCountingPtr(T *data) { copy(data); }\n\n \/\/\/ Create a new reference counting pointer by copying another\n \/\/\/ one. Adds a reference.\n RefCountingPtr(const RefCountingPtr &r) { copy(r.data); }\n\n \/** Move-constructor.\n * Does not add a reference.\n *\/\n RefCountingPtr(RefCountingPtr&& r)\n {\n data = r.data;\n r.data = nullptr;\n }\n\n template \n RefCountingPtr(const NonConstT &r) { copy(r.data); }\n\n \/\/\/ Destroy the pointer and any reference it may hold.\n ~RefCountingPtr() { del(); }\n\n \/\/ The following pointer access functions are const because they\n \/\/ don't actually change the pointer, though the user could change\n \/\/ what is pointed to. This is analagous to a \"Foo * const\".\n\n \/\/\/ Access a member variable.\n T *operator->() const { return data; }\n\n \/\/\/ Dereference the pointer.\n T &operator*() const { return *data; }\n\n \/\/\/ Directly access the pointer itself without taking a reference.\n T *get() const { return data; }\n\n template \n operator RefCountingPtr>()\n {\n return RefCountingPtr(*this);\n }\n\n \/\/\/ Assign a new value to the pointer\n const RefCountingPtr &operator=(T *p) { set(p); return *this; }\n\n \/\/\/ Copy the pointer from another RefCountingPtr\n const RefCountingPtr &operator=(const RefCountingPtr &r)\n { return operator=(r.data); }\n\n \/\/\/ Move-assign the pointer from another RefCountingPtr\n const RefCountingPtr &operator=(RefCountingPtr&& r)\n {\n \/* This happens regardless of whether the pointer is the same or not,\n * because of the move semantics, the rvalue needs to be 'destroyed'.\n *\/\n del();\n data = r.data;\n r.data = nullptr;\n return *this;\n }\n\n \/\/\/ Check if the pointer is empty\n bool operator!() const { return data == 0; }\n\n \/\/\/ Check if the pointer is non-empty\n operator bool() const { return data != 0; }\n};\n\n\/\/\/ Check for equality of two reference counting pointers.\ntemplate\ninline bool operator==(const RefCountingPtr &l, const RefCountingPtr &r)\n{ return l.get() == r.get(); }\n\n\/\/\/ Check for equality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool operator==(const RefCountingPtr &l, const T *r)\n{ return l.get() == r; }\n\n\/\/\/ Check for equality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool operator==(const T *l, const RefCountingPtr &r)\n{ return l == r.get(); }\n\n\/\/\/ Check for inequality of two reference counting pointers.\ntemplate\ninline bool operator!=(const RefCountingPtr &l, const RefCountingPtr &r)\n{ return l.get() != r.get(); }\n\n\/\/\/ Check for inequality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool operator!=(const RefCountingPtr &l, const T *r)\n{ return l.get() != r; }\n\n\/\/\/ Check for inequality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool operator!=(const T *l, const RefCountingPtr &r)\n{ return l != r.get(); }\n\n#endif \/\/ __BASE_REFCNT_HH__\nbase: Style fixes in base\/refcnt.hh\/*\n * Copyright (c) 2017-2018 ARM Limited\n * All rights reserved.\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __BASE_REFCNT_HH__\n#define __BASE_REFCNT_HH__\n\n#include \n\n\/**\n * @file base\/refcnt.hh\n *\n * Classes for managing reference counted objects.\n *\/\n\n\/**\n * Derive from RefCounted if you want to enable reference counting of\n * this class. If you want to use automatic reference counting, you\n * should use RefCountingPtr instead of regular pointers.\n *\/\nclass RefCounted\n{\n private:\n \/\/ The reference count is mutable because one may want to\n \/\/ reference count a const pointer. This really is OK because\n \/\/ const is about logical constness of the object not really about\n \/\/ strictly disallowing an object to change.\n mutable int count;\n\n private:\n \/\/ Don't allow a default copy constructor or copy operator on\n \/\/ these objects because the default operation will copy the\n \/\/ reference count as well and we certainly don't want that.\n RefCounted(const RefCounted &);\n RefCounted &operator=(const RefCounted &);\n\n public:\n \/**\n * We initialize the reference count to zero and the first object\n * to take ownership of it must increment it to one.\n *\n * @attention A memory leak will occur if you never assign a newly\n * constructed object to a reference counting pointer.\n *\/\n RefCounted() : count(0) {}\n\n \/**\n * We make the destructor virtual because we're likely to have\n * virtual functions on reference counted objects.\n *\n * @todo Even if this were true, does it matter? Shouldn't the\n * derived class indicate this? This only matters if we would\n * ever choose to delete a \"RefCounted *\" which I doubt we'd ever\n * do. We don't ever delete a \"void *\".\n *\/\n virtual ~RefCounted() {}\n\n \/\/\/ Increment the reference count\n void incref() const { ++count; }\n\n \/\/\/ Decrement the reference count and destroy the object if all\n \/\/\/ references are gone.\n void\n decref() const\n {\n if (--count <= 0)\n delete this;\n }\n};\n\n\/**\n * If you want a reference counting pointer to a mutable object,\n * create it like this:\n * @code\n * typedef RefCountingPtr FooPtr;\n * @endcode\n *\n * @attention Do not use \"const FooPtr\"\n * To create a reference counting pointer to a const object, use this:\n * @code\n * typedef RefCountingPtr ConstFooPtr;\n * @endcode\n *\n * These two usages are analogous to iterator and const_iterator in the stl.\n *\/\ntemplate \nclass RefCountingPtr\n{\n public:\n using PtrType = T*;\n\n protected:\n \/** Convenience aliases for const\/non-const versions of T w\/ friendship. *\/\n \/** @{ *\/\n static constexpr auto TisConst = std::is_const::value;\n using ConstT = typename std::conditional,\n RefCountingPtr::type>>::type;\n friend ConstT;\n using NonConstT = typename std::conditional::type>,\n RefCountingPtr>::type;\n friend NonConstT;\n \/** @} *\/\n \/\/\/ The stored pointer.\n \/\/\/ Arguably this should be private.\n T *data;\n\n \/**\n * Copy a new pointer value and increment the reference count if\n * it is a valid pointer. Note, this does not delete the\n * reference any existing object.\n * @param d Pointer to store.\n *\/\n void\n copy(T *d)\n {\n data = d;\n if (data)\n data->incref();\n }\n\n \/**\n * Delete the reference to any existing object if it is non NULL.\n * @attention this doesn't clear the pointer value, so a double\n * decref could happen if not careful.\n *\/\n void\n del()\n {\n if (data)\n data->decref();\n }\n\n \/**\n * Drop the old reference and change it to something new.\n *\/\n void\n set(T *d)\n {\n \/\/ Need to check if we're actually changing because otherwise\n \/\/ we could delete the last reference before adding the new\n \/\/ reference.\n if (data != d) {\n del();\n copy(d);\n }\n }\n\n public:\n \/\/\/ Create an empty reference counting pointer.\n RefCountingPtr() : data(0) {}\n\n \/\/\/ Create a new reference counting pointer to some object\n \/\/\/ (probably something newly created). Adds a reference.\n RefCountingPtr(T *data) { copy(data); }\n\n \/\/\/ Create a new reference counting pointer by copying another\n \/\/\/ one. Adds a reference.\n RefCountingPtr(const RefCountingPtr &r) { copy(r.data); }\n\n \/** Move-constructor.\n * Does not add a reference.\n *\/\n RefCountingPtr(RefCountingPtr&& r)\n {\n data = r.data;\n r.data = nullptr;\n }\n\n template \n RefCountingPtr(const NonConstT &r) { copy(r.data); }\n\n \/\/\/ Destroy the pointer and any reference it may hold.\n ~RefCountingPtr() { del(); }\n\n \/\/ The following pointer access functions are const because they\n \/\/ don't actually change the pointer, though the user could change\n \/\/ what is pointed to. This is analagous to a \"Foo * const\".\n\n \/\/\/ Access a member variable.\n T *operator->() const { return data; }\n\n \/\/\/ Dereference the pointer.\n T &operator*() const { return *data; }\n\n \/\/\/ Directly access the pointer itself without taking a reference.\n T *get() const { return data; }\n\n template \n operator RefCountingPtr>()\n {\n return RefCountingPtr(*this);\n }\n\n \/\/\/ Assign a new value to the pointer\n const RefCountingPtr &operator=(T *p) { set(p); return *this; }\n\n \/\/\/ Copy the pointer from another RefCountingPtr\n const RefCountingPtr &\n operator=(const RefCountingPtr &r)\n {\n return operator=(r.data);\n }\n\n \/\/\/ Move-assign the pointer from another RefCountingPtr\n const RefCountingPtr &\n operator=(RefCountingPtr&& r)\n {\n \/* This happens regardless of whether the pointer is the same or not,\n * because of the move semantics, the rvalue needs to be 'destroyed'.\n *\/\n del();\n data = r.data;\n r.data = nullptr;\n return *this;\n }\n\n \/\/\/ Check if the pointer is empty\n bool operator!() const { return data == 0; }\n\n \/\/\/ Check if the pointer is non-empty\n operator bool() const { return data != 0; }\n};\n\n\/\/\/ Check for equality of two reference counting pointers.\ntemplate\ninline bool\noperator==(const RefCountingPtr &l, const RefCountingPtr &r)\n{\n return l.get() == r.get();\n}\n\n\/\/\/ Check for equality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool\noperator==(const RefCountingPtr &l, const T *r)\n{\n return l.get() == r;\n}\n\n\/\/\/ Check for equality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool\noperator==(const T *l, const RefCountingPtr &r)\n{\n return l == r.get();\n}\n\n\/\/\/ Check for inequality of two reference counting pointers.\ntemplate\ninline bool\noperator!=(const RefCountingPtr &l, const RefCountingPtr &r)\n{\n return l.get() != r.get();\n}\n\n\/\/\/ Check for inequality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool\noperator!=(const RefCountingPtr &l, const T *r)\n{\n return l.get() != r;\n}\n\n\/\/\/ Check for inequality of of a reference counting pointers and a\n\/\/\/ regular pointer\ntemplate\ninline bool\noperator!=(const T *l, const RefCountingPtr &r)\n{\n return l != r.get();\n}\n\n#endif \/\/ __BASE_REFCNT_HH__\n<|endoftext|>"} {"text":"#include \n#include \n#include \"RandomNumberGenerator.h\"\n\n#include \"RJObject.h\"\n\nusing namespace std;\nusing namespace DNest3;\n\nRJObject::RJObject(int num_dimensions, int max_num_components)\n:num_dimensions(num_dimensions)\n,max_num_components(max_num_components)\n,positions(max_num_components, vector(num_dimensions))\n,masses(max_num_components)\n{\n\n}\n\nvoid RJObject::fromPrior()\n{\n\t\/\/ Generate from {0, 1, 2, ..., max_num_components}\n\tnum_components = randInt(max_num_components + 1);\n\n\t\/\/ Assign positions and masses\n\tfor(int i=0; i 1.)\n\t{\n\t\tcerr<<\"# WARNING: Attempted to call inverse CDF on \";\n\t\tcerr<<\"an argument not in [0, 1].\"<Fixed segfault (forgot to initialise DNest's RNG), made output sensible#include \n#include \n#include \n#include \"RandomNumberGenerator.h\"\n\n#include \"RJObject.h\"\n\nusing namespace std;\nusing namespace DNest3;\n\nRJObject::RJObject(int num_dimensions, int max_num_components)\n:num_dimensions(num_dimensions)\n,max_num_components(max_num_components)\n,positions(max_num_components, vector(num_dimensions))\n,masses(max_num_components)\n{\n\n}\n\nvoid RJObject::fromPrior()\n{\n\t\/\/ Generate from {0, 1, 2, ..., max_num_components}\n\tnum_components = randInt(max_num_components + 1);\n\n\t\/\/ Assign positions and masses\n\tfor(int i=0; i 1.)\n\t{\n\t\tcerr<<\"# WARNING: Attempted to call inverse CDF on \";\n\t\tcerr<<\"an argument not in [0, 1].\"<\n\/\/ Demonstration of the class\nint main()\n{\n\tRandomNumberGenerator::initialise_instance();\n\tRandomNumberGenerator::get_instance().set_seed(time(0));\n\n\tRJObject r(2, 100);\n\tr.fromPrior();\n\tcout<"} {"text":"#include \"RJObject.h\"\n\nImplement constructor#include \"RJObject.h\"\n\nusing namespace std;\n\nRJObject::RJObject(int num_dimensions, int max_num_objects)\n:positions(max_num_objects, vector(num_dimensions))\n,masses(max_num_objects)\n{\n\n}\n\n<|endoftext|>"} {"text":"#include \"Renderer.h\"\n\nfloat Renderer::TileScale;\nfloat Renderer::SpriteScale;\n\nvoid Renderer::GetWallTile(Field *field, std::size_t x, std::size_t y,\n\t\tint &index, int &rotation, bool &flip)\n{\n\tuint8_t neighborhood = 0x00;\n\tuint8_t edges = 0x00;\n\tfield->NeighborhoodInfo(\n\t\t\tx, y, Field::Wall, Field::Edge, neighborhood, edges);\n\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tif (((neighborhood & 0xD5) == 0x41)\n\t\t\t\t&& ((edges & 0x06) == 0x06))\n\t\t{\n\t\t\tindex = 1;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (neighborhood == 0x47)\n\t\t{\n\t\t\tindex = 2;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (neighborhood == 0x5C)\n\t\t{\n\t\t\tindex = 2;\n\t\t\trotation = i;\n\t\t\tflip = true;\n\t\t\treturn;\n\t\t}\n\t\telse if ((neighborhood & 0x45) == 0x01)\n\t\t{\n\t\t\tindex = 3;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\tif ((edges & 0x08) == 0x08)\n\t\t\t{\n\t\t\t\trotation = (2 + i) % 4;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if ((neighborhood & 0x5F) == 0x1F)\n\t\t{\n\t\t\tindex = 4;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (((neighborhood & 0x55) == 0x14)\n\t\t\t\t&& ((edges & 0x09) == 0x00))\n\t\t{\n\t\t\tindex = 5;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (neighborhood == 0x7F)\n\t\t{\n\t\t\tindex = 6;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\n\t\tneighborhood = (neighborhood << 2) + (neighborhood >> 6);\n\t\tedges = ((edges << 1) + (edges >> 3)) & 0x0F;\n\t}\n\n\tindex = 0;\n\trotation = 0;\n\tflip = false;\n}\n\nvoid Renderer::GetBoxTile(Field *field, std::size_t x, std::size_t y,\n\t\tint &index, int &rotation, bool &flip)\n{\n\tuint8_t neighborhood = 0x00;\n\tuint8_t edges = 0x00;\n\tfield->NeighborhoodInfo(\n\t\t\tx, y, Field::GhostBox, Field::GhostZone, neighborhood, edges);\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tif (((neighborhood & 0x55) == 0x14)\n\t\t\t\t&& ((edges & 0x09) == 0x00))\n\t\t{\n\t\t\tindex = 7;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if ((neighborhood & 0x45) == 0x01)\n\t\t{\n\t\t\tindex = 3;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\tif ((edges & 0x08) == 0x08)\n\t\t\t{\n\t\t\t\trotation = (2 + i) % 4;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tneighborhood = (neighborhood << 2) + (neighborhood >> 6);\n\t\tedges = ((edges << 1) + (edges >> 3)) & 0x0F;\n\t}\n}\nExplicitly defined bitfield for neighborhood#include \"Renderer.h\"\n\nfloat Renderer::TileScale;\nfloat Renderer::SpriteScale;\n\n#define NB_N 0x00\n#define NB_R 0x01\n#define NB_UR 0x02\n#define NB_U 0x04\n#define NB_UL 0x08\n#define NB_L 0x10\n#define NB_DL 0x20\n#define NB_D 0x40\n#define NB_DR 0x80\n#define ED_N 0x00\n#define ED_R 0x01\n#define ED_U 0x02\n#define ED_L 0x04\n#define ED_D 0x08\n\nvoid Renderer::GetWallTile(Field *field, std::size_t x, std::size_t y,\n\t\tint &index, int &rotation, bool &flip)\n{\n\tuint8_t neighborhood = 0x00;\n\tuint8_t edges = 0x00;\n\tfield->NeighborhoodInfo(\n\t\t\tx, y, Field::Wall, Field::Edge, neighborhood, edges);\n\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tif (((neighborhood & (NB_R|NB_U|NB_UL)) == (NB_R|NB_D))\n\t\t\t\t&& ((edges & (ED_U|ED_L)) == (ED_U|ED_L)))\n\t\t{\n\t\t\tindex = 1;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (neighborhood == (NB_R|NB_UR|NB_U|NB_D))\n\t\t{\n\t\t\tindex = 2;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (neighborhood == (NB_U|NB_UL|NB_L|NB_D))\n\t\t{\n\t\t\tindex = 2;\n\t\t\trotation = i;\n\t\t\tflip = true;\n\t\t\treturn;\n\t\t}\n\t\telse if ((neighborhood & (NB_R|NB_U|NB_D)) == NB_R)\n\t\t{\n\t\t\tindex = 3;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\tif ((edges & ED_D) == ED_D)\n\t\t\t{\n\t\t\t\trotation = (2 + i) % 4;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if ((neighborhood & (NB_R|NB_UR|NB_L|NB_UL|NB_L|NB_D))\n\t\t\t\t== (NB_R|NB_UR|NB_L|NB_UL|NB_L))\n\t\t{\n\t\t\tindex = 4;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (((neighborhood & (NB_R|NB_U|NB_L|NB_D)) == (NB_U|NB_L))\n\t\t\t\t&& ((edges & (ED_R|ED_D)) == ED_N))\n\t\t{\n\t\t\tindex = 5;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if (neighborhood == (NB_R|NB_UR|NB_U|NB_UL|NB_L|NB_DL|NB_D))\n\t\t{\n\t\t\tindex = 6;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\n\t\tneighborhood = (neighborhood << 2) + (neighborhood >> 6);\n\t\tedges = ((edges << 1) + (edges >> 3)) & 0x0F;\n\t}\n\n\tindex = 0;\n\trotation = 0;\n\tflip = false;\n}\n\nvoid Renderer::GetBoxTile(Field *field, std::size_t x, std::size_t y,\n\t\tint &index, int &rotation, bool &flip)\n{\n\tuint8_t neighborhood;\n\tuint8_t edges;\n\tfield->NeighborhoodInfo(\n\t\t\tx, y, Field::GhostBox, Field::GhostZone, neighborhood, edges);\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tif (((neighborhood & (NB_R|NB_U|NB_L|NB_D)) == (NB_U|NB_L))\n\t\t\t\t&& ((edges & (ED_R|ED_D)) == (ED_N)))\n\t\t{\n\t\t\tindex = 7;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\treturn;\n\t\t}\n\t\telse if ((neighborhood & (NB_R|NB_U|NB_D)) == NB_R)\n\t\t{\n\t\t\tindex = 3;\n\t\t\trotation = i;\n\t\t\tflip = false;\n\t\t\tif ((edges & ED_D) == ED_D)\n\t\t\t{\n\t\t\t\trotation = (2 + i) % 4;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tneighborhood = (neighborhood << 2) + (neighborhood >> 6);\n\t\tedges = ((edges << 1) + (edges >> 3)) & 0x0F;\n\t}\n}\n<|endoftext|>"} {"text":"\n\/*\n * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL\n *\/\n\n#include \n#include \n#include \n#include \n\ntypedef VALUE(*ARGS)(...);\ntypedef int(*ITERATOR)(...);\n\nstatic VALUE rb_mQAR;\nstatic VALUE rb_cQARHash;\nstatic VALUE rb_cQARParamList;\nstatic VALUE rb_cQARResource;\n\nnamespace Symbol\n{\n const ID all = rb_intern(\"all\");\n const ID at = rb_intern(\"at\");\n const ID first = rb_intern(\"first\");\n const ID follow_redirects = rb_intern(\"follow_redirects\");\n const ID method_missing = rb_intern(\"method_missing\");\n const ID New = rb_intern(\"new\");\n const ID one = rb_intern(\"one\");\n const ID params = rb_intern(\"params\");\n const ID to_s = rb_intern(\"to_s\");\n const ID last = rb_intern(\"last\");\n}\n\nstatic QString to_s(VALUE value)\n{\n VALUE s = rb_funcall(value, Symbol::to_s, 0);\n return QString::fromUtf8(StringValuePtr(s));\n}\n\nstatic VALUE to_value(const QVariant &v)\n{\n switch(v.type())\n {\n case QVariant::Hash:\n {\n VALUE value = rb_funcall(rb_cQARHash, Symbol::New, 0);\n QHash hash = v.toHash();\n\n for(QHash::ConstIterator it = hash.begin(); it != hash.end(); ++it)\n {\n rb_hash_aset(value, ID2SYM(rb_intern(it.key().toUtf8())), to_value(it.value()));\n }\n\n return value;\n }\n case QVariant::List:\n {\n VALUE value = rb_ary_new();\n\n foreach(QVariant element, v.toList())\n {\n rb_ary_push(value, to_value(element));\n }\n\n return value;\n }\n case QVariant::Invalid:\n return Qnil;\n case QVariant::Bool:\n return v.toBool() ? Qtrue : Qfalse;\n case QVariant::Int:\n return rb_int_new(v.toInt());\n case QVariant::Double:\n return rb_float_new(v.toDouble());\n case QVariant::DateTime:\n {\n return rb_funcall(rb_cTime, Symbol::at, 1, rb_int_new(v.toDateTime().toTime_t()));\n }\n default:\n return rb_str_new2(v.toString().toUtf8());\n }\n}\n\n\/*\n * Hash\n *\/\n\nstatic VALUE hash_method_missing(VALUE self, VALUE method)\n{\n VALUE value = rb_hash_aref(self, method);\n return (value == Qnil) ?\n rb_funcall(rb_cHash, ID2SYM(Symbol::method_missing), 1, method) : value;\n}\n\n\/*\n * Resource\n *\/\n\nstatic void resource_mark(QActiveResource::Resource *) {}\nstatic void resource_free(QActiveResource::Resource *resource)\n{\n delete resource;\n}\n\nstatic VALUE resource_allocate(VALUE klass)\n{\n QActiveResource::Resource *resource = new QActiveResource::Resource;\n return Data_Wrap_Struct(klass, resource_mark, resource_free, resource);\n}\n\nstatic VALUE resource_initialize(VALUE self, VALUE base, VALUE resource)\n{\n QActiveResource::Resource *r = 0;\n Data_Get_Struct(self, QActiveResource::Resource, r);\n r->setBase(QString::fromUtf8(rb_string_value_ptr(&base)));\n r->setResource(QString::fromUtf8(rb_string_value_ptr(&resource)));\n}\n\n\/*\n * ParamList\n *\/\n\nstatic VALUE param_list_mark(QActiveResource::ParamList *) {}\nstatic VALUE param_list_free(QActiveResource::ParamList *params)\n{\n delete params;\n}\n\nstatic VALUE param_list_allocate(VALUE klass)\n{\n QActiveResource::ParamList *params = new QActiveResource::ParamList();\n return Data_Wrap_Struct(klass, param_list_mark, param_list_free, params);\n}\n\nstatic int params_hash_iterator(VALUE key, VALUE value, VALUE params)\n{\n QActiveResource::ParamList *params_pointer;\n Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);\n params_pointer->append(QActiveResource::Param(to_s(key), to_s(value)));\n}\n\nstatic VALUE resource_find(int argc, VALUE *argv, VALUE self)\n{\n QActiveResource::Resource *resource = 0;\n Data_Get_Struct(self, class QActiveResource::Resource, resource);\n\n VALUE params = param_list_allocate(rb_cData);\n\n if(argc >= 2 && TYPE(argv[1]) == T_HASH)\n {\n VALUE params_hash = rb_hash_aref(argv[1], ID2SYM(Symbol::params));\n\n if(params_hash != Qnil)\n {\n rb_hash_foreach(params_hash, (ITERATOR) params_hash_iterator, params);\n }\n\n VALUE follow_redirects = rb_hash_aref(argv[1], ID2SYM(Symbol::follow_redirects));\n resource->setFollowRedirects(follow_redirects == Qtrue);\n }\n\n QActiveResource::ParamList *params_pointer;\n Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);\n\n QString from;\n\n if(argc >= 1)\n {\n ID current = SYM2ID(argv[0]);\n\n if(current == Symbol::one)\n {\n return to_value(resource->find(QActiveResource::FindOne, from, *params_pointer));\n }\n else if(current == Symbol::first)\n {\n return to_value(resource->find(QActiveResource::FindFirst, from, *params_pointer));\n }\n else if(current == Symbol::last)\n {\n return to_value(resource->find(QActiveResource::FindLast, from, *params_pointer));\n }\n else if(current != Symbol::all)\n {\n return to_value(resource->find(to_s(argv[0])));\n }\n }\n\n QActiveResource::RecordList records =\n resource->find(QActiveResource::FindAll, from, *params_pointer);\n\n VALUE array = rb_ary_new2(records.length());\n\n for(int i = 0; i < records.length(); i++)\n {\n rb_ary_store(array, i, to_value(records[i]));\n }\n\n return array;\n}\n\n\/*\n * QAR\n *\/\n\nVALUE qar_extended(VALUE self, VALUE base)\n{\n return Qnil;\n}\n\nextern \"C\"\n{\n void Init_QAR(void)\n {\n rb_mQAR = rb_define_module(\"QAR\");\n\n rb_cQARHash = rb_define_class_under(rb_mQAR, \"Hash\", rb_cHash);\n rb_define_method(rb_cQARHash, \"method_missing\", (ARGS) hash_method_missing, 1);\n\n rb_cQARParamList = rb_define_class_under(rb_mQAR, \"ParamList\", rb_cObject);\n rb_define_alloc_func(rb_cQARParamList, param_list_allocate);\n\n rb_cQARResource = rb_define_class_under(rb_mQAR, \"Resource\", rb_cObject);\n rb_define_alloc_func(rb_cQARResource, resource_allocate);\n rb_define_method(rb_cQARResource, \"initialize\", (ARGS) resource_initialize, 2);\n rb_define_method(rb_cQARResource, \"find\", (ARGS) resource_find, -1);\n\n rb_define_singleton_method(rb_mQAR, \"extended\", (ARGS) qar_extended, 1);\n }\n}\nMake static\n\/*\n * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL\n *\/\n\n#include \n#include \n#include \n#include \n\ntypedef VALUE(*ARGS)(...);\ntypedef int(*ITERATOR)(...);\n\nstatic VALUE rb_mQAR;\nstatic VALUE rb_cQARHash;\nstatic VALUE rb_cQARParamList;\nstatic VALUE rb_cQARResource;\n\nnamespace Symbol\n{\n const ID all = rb_intern(\"all\");\n const ID at = rb_intern(\"at\");\n const ID first = rb_intern(\"first\");\n const ID follow_redirects = rb_intern(\"follow_redirects\");\n const ID method_missing = rb_intern(\"method_missing\");\n const ID New = rb_intern(\"new\");\n const ID one = rb_intern(\"one\");\n const ID params = rb_intern(\"params\");\n const ID to_s = rb_intern(\"to_s\");\n const ID last = rb_intern(\"last\");\n}\n\nstatic QString to_s(VALUE value)\n{\n VALUE s = rb_funcall(value, Symbol::to_s, 0);\n return QString::fromUtf8(StringValuePtr(s));\n}\n\nstatic VALUE to_value(const QVariant &v)\n{\n switch(v.type())\n {\n case QVariant::Hash:\n {\n VALUE value = rb_funcall(rb_cQARHash, Symbol::New, 0);\n QHash hash = v.toHash();\n\n for(QHash::ConstIterator it = hash.begin(); it != hash.end(); ++it)\n {\n rb_hash_aset(value, ID2SYM(rb_intern(it.key().toUtf8())), to_value(it.value()));\n }\n\n return value;\n }\n case QVariant::List:\n {\n VALUE value = rb_ary_new();\n\n foreach(QVariant element, v.toList())\n {\n rb_ary_push(value, to_value(element));\n }\n\n return value;\n }\n case QVariant::Invalid:\n return Qnil;\n case QVariant::Bool:\n return v.toBool() ? Qtrue : Qfalse;\n case QVariant::Int:\n return rb_int_new(v.toInt());\n case QVariant::Double:\n return rb_float_new(v.toDouble());\n case QVariant::DateTime:\n {\n return rb_funcall(rb_cTime, Symbol::at, 1, rb_int_new(v.toDateTime().toTime_t()));\n }\n default:\n return rb_str_new2(v.toString().toUtf8());\n }\n}\n\n\/*\n * Hash\n *\/\n\nstatic VALUE hash_method_missing(VALUE self, VALUE method)\n{\n VALUE value = rb_hash_aref(self, method);\n return (value == Qnil) ?\n rb_funcall(rb_cHash, ID2SYM(Symbol::method_missing), 1, method) : value;\n}\n\n\/*\n * Resource\n *\/\n\nstatic void resource_mark(QActiveResource::Resource *) {}\nstatic void resource_free(QActiveResource::Resource *resource)\n{\n delete resource;\n}\n\nstatic VALUE resource_allocate(VALUE klass)\n{\n QActiveResource::Resource *resource = new QActiveResource::Resource;\n return Data_Wrap_Struct(klass, resource_mark, resource_free, resource);\n}\n\nstatic VALUE resource_initialize(VALUE self, VALUE base, VALUE resource)\n{\n QActiveResource::Resource *r = 0;\n Data_Get_Struct(self, QActiveResource::Resource, r);\n r->setBase(QString::fromUtf8(rb_string_value_ptr(&base)));\n r->setResource(QString::fromUtf8(rb_string_value_ptr(&resource)));\n}\n\n\/*\n * ParamList\n *\/\n\nstatic VALUE param_list_mark(QActiveResource::ParamList *) {}\nstatic VALUE param_list_free(QActiveResource::ParamList *params)\n{\n delete params;\n}\n\nstatic VALUE param_list_allocate(VALUE klass)\n{\n QActiveResource::ParamList *params = new QActiveResource::ParamList();\n return Data_Wrap_Struct(klass, param_list_mark, param_list_free, params);\n}\n\nstatic int params_hash_iterator(VALUE key, VALUE value, VALUE params)\n{\n QActiveResource::ParamList *params_pointer;\n Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);\n params_pointer->append(QActiveResource::Param(to_s(key), to_s(value)));\n}\n\nstatic VALUE resource_find(int argc, VALUE *argv, VALUE self)\n{\n QActiveResource::Resource *resource = 0;\n Data_Get_Struct(self, class QActiveResource::Resource, resource);\n\n VALUE params = param_list_allocate(rb_cData);\n\n if(argc >= 2 && TYPE(argv[1]) == T_HASH)\n {\n VALUE params_hash = rb_hash_aref(argv[1], ID2SYM(Symbol::params));\n\n if(params_hash != Qnil)\n {\n rb_hash_foreach(params_hash, (ITERATOR) params_hash_iterator, params);\n }\n\n VALUE follow_redirects = rb_hash_aref(argv[1], ID2SYM(Symbol::follow_redirects));\n resource->setFollowRedirects(follow_redirects == Qtrue);\n }\n\n QActiveResource::ParamList *params_pointer;\n Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);\n\n QString from;\n\n if(argc >= 1)\n {\n ID current = SYM2ID(argv[0]);\n\n if(current == Symbol::one)\n {\n return to_value(resource->find(QActiveResource::FindOne, from, *params_pointer));\n }\n else if(current == Symbol::first)\n {\n return to_value(resource->find(QActiveResource::FindFirst, from, *params_pointer));\n }\n else if(current == Symbol::last)\n {\n return to_value(resource->find(QActiveResource::FindLast, from, *params_pointer));\n }\n else if(current != Symbol::all)\n {\n return to_value(resource->find(to_s(argv[0])));\n }\n }\n\n QActiveResource::RecordList records =\n resource->find(QActiveResource::FindAll, from, *params_pointer);\n\n VALUE array = rb_ary_new2(records.length());\n\n for(int i = 0; i < records.length(); i++)\n {\n rb_ary_store(array, i, to_value(records[i]));\n }\n\n return array;\n}\n\n\/*\n * QAR\n *\/\n\nstatic VALUE qar_extended(VALUE self, VALUE base)\n{\n return Qnil;\n}\n\nextern \"C\"\n{\n void Init_QAR(void)\n {\n rb_mQAR = rb_define_module(\"QAR\");\n\n rb_cQARHash = rb_define_class_under(rb_mQAR, \"Hash\", rb_cHash);\n rb_define_method(rb_cQARHash, \"method_missing\", (ARGS) hash_method_missing, 1);\n\n rb_cQARParamList = rb_define_class_under(rb_mQAR, \"ParamList\", rb_cObject);\n rb_define_alloc_func(rb_cQARParamList, param_list_allocate);\n\n rb_cQARResource = rb_define_class_under(rb_mQAR, \"Resource\", rb_cObject);\n rb_define_alloc_func(rb_cQARResource, resource_allocate);\n rb_define_method(rb_cQARResource, \"initialize\", (ARGS) resource_initialize, 2);\n rb_define_method(rb_cQARResource, \"find\", (ARGS) resource_find, -1);\n\n rb_define_singleton_method(rb_mQAR, \"extended\", (ARGS) qar_extended, 1);\n }\n}\n<|endoftext|>"} {"text":"#include \"TFTKanji.h\"\n\n#define DBGLOG 0\n\nTFTKanji::TFTKanji(ITKScreen* tft) :tft(tft) {\n}\n\nTFTKanji::~TFTKanji() {\n close();\n}\n\nint TFTKanji::open(SdFatBase* sd, const char* kanjifile, const char* ankfile) {\n int ret = kanjiFont.open(sd, kanjifile);\n#if DBGLOG\n Serial.print(\"kanjiFont.open()=\");\n Serial.println(ret);\n#endif\n if (ret != 0) {\n return ret;\n }\n\n ret = ankFont.open(sd, ankfile);\n#if DBGLOG\n Serial.print(\"ankFont.open()=\");\n Serial.println(ret);\n#endif\n if (ret != 0) {\n return ret;\n }\n return 0;\n}\n\nbool TFTKanji::close() {\n ankFont.close();\n return kanjiFont.close();\n}\n\n\/\/ cf. Adafruit_GFX::drawBitmap()\nvoid drawBitmap(ITKScreen* tft, int16_t x, int16_t y,\n const uint8_t *bitmap, int16_t w, int16_t h,\n uint16_t color) {\n\n int16_t i, j, byteWidth = (w + 7) \/ 8;\n\n for (j=0; j> (i & 7))) {\n tft->drawPixel(x + i, y + j, color);\n }\n }\n }\n}\n\nint loadFontAndDraw(ITKScreen* tft, int16_t x, int16_t y,\n Fontx2* font, uint16_t code, uint16_t color, uint16_t bgcolor) {\n int len = font->bitmapLen();\n uint8_t buf[len];\n int ret = font->load(code, buf, len);\n if (ret == 0) {\n \/\/ bgcolorがcolorと同じ場合はbgcolorでのfillは行わない。フラグ不要にするため\n \/\/ cf. Adafruit_GFX::setTextColor()\n if (bgcolor != color) {\n tft->fillRect(x, y, font->width(), font->height(), bgcolor);\n }\n drawBitmap(tft, x, y, buf, font->width(), font->height(), color);\n }\n return ret;\n}\n\nint TFTKanji::drawText(int16_t* x, int16_t* y, const char* str, uint16_t color, uint16_t bgcolor\n#if WRAP_LONGLINE\n , bool wrap\n#endif\n ) {\n uint16_t sjis1 = 0;\n const char* p = str;\n for (; *p != '\\0'; p++) {\n uint8_t ch = (uint8_t)*p;\n uint16_t code;\n Fontx2* font;\n#if DBGLOG\n Serial.print(ch, HEX);\n#endif\n if (sjis1) { \/\/ SJIS 2nd byte\n code = (sjis1 << 8) | ch;\n sjis1 = 0;\n font = &kanjiFont;\n } else if (issjis1(ch)) { \/\/ SJIS 1st byte\n sjis1 = ch;\n continue;\n } else {\n#if WRAP_NEWLINE\n if (ch == '\\n') {\n *y += height();\n *x = 0;\n if (*y >= tft->height()) {\n break;\n } else {\n continue;\n }\n } else if (ch == '\\r') { \/\/ ignore\n continue;\n }\n#endif\n code = ch;\n font = &ankFont;\n }\n\n int16_t tftWidth = tft->width();\n#if WRAP_LONGLINE\n if (wrap && *x + font->width() > tftWidth) {\n *y += height();\n *x = 0;\n if (*y >= tft->height()) {\n break;\n }\n }\n#endif\n int ret = loadFontAndDraw(tft, *x, *y, font, code, color, bgcolor);\n if (ret < -1) {\n return ret;\n } \/\/ -1の場合、指定した文字のフォントデータ無し\n *x += font->width();\n if (*x >= tftWidth) {\n break;\n }\n }\n return p - str;\n}\n改行での折り返し処理時の\\r無視処理を削除。 スケッチサイズを減らすため。#include \"TFTKanji.h\"\n\n#define DBGLOG 0\n\nTFTKanji::TFTKanji(ITKScreen* tft) :tft(tft) {\n}\n\nTFTKanji::~TFTKanji() {\n close();\n}\n\nint TFTKanji::open(SdFatBase* sd, const char* kanjifile, const char* ankfile) {\n int ret = kanjiFont.open(sd, kanjifile);\n#if DBGLOG\n Serial.print(\"kanjiFont.open()=\");\n Serial.println(ret);\n#endif\n if (ret != 0) {\n return ret;\n }\n\n ret = ankFont.open(sd, ankfile);\n#if DBGLOG\n Serial.print(\"ankFont.open()=\");\n Serial.println(ret);\n#endif\n if (ret != 0) {\n return ret;\n }\n return 0;\n}\n\nbool TFTKanji::close() {\n ankFont.close();\n return kanjiFont.close();\n}\n\n\/\/ cf. Adafruit_GFX::drawBitmap()\nvoid drawBitmap(ITKScreen* tft, int16_t x, int16_t y,\n const uint8_t *bitmap, int16_t w, int16_t h,\n uint16_t color) {\n\n int16_t i, j, byteWidth = (w + 7) \/ 8;\n\n for (j=0; j> (i & 7))) {\n tft->drawPixel(x + i, y + j, color);\n }\n }\n }\n}\n\nint loadFontAndDraw(ITKScreen* tft, int16_t x, int16_t y,\n Fontx2* font, uint16_t code, uint16_t color, uint16_t bgcolor) {\n int len = font->bitmapLen();\n uint8_t buf[len];\n int ret = font->load(code, buf, len);\n if (ret == 0) {\n \/\/ bgcolorがcolorと同じ場合はbgcolorでのfillは行わない。フラグ不要にするため\n \/\/ cf. Adafruit_GFX::setTextColor()\n if (bgcolor != color) {\n tft->fillRect(x, y, font->width(), font->height(), bgcolor);\n }\n drawBitmap(tft, x, y, buf, font->width(), font->height(), color);\n }\n return ret;\n}\n\nstatic int wrapline(int16_t tftHeight, int fontHeight, int16_t* x, int16_t* y) {\n *y += fontHeight;\n *x = 0;\n if (*y >= tftHeight) {\n return 1;\n }\n return 0;\n}\n\nint TFTKanji::drawText(int16_t* x, int16_t* y, const char* str, uint16_t color, uint16_t bgcolor\n#if WRAP_LONGLINE\n , bool wrap\n#endif\n ) {\n uint16_t sjis1 = 0;\n const char* p = str;\n for (; *p != '\\0'; p++) {\n uint8_t ch = (uint8_t)*p;\n uint16_t code;\n Fontx2* font;\n#if DBGLOG\n Serial.print(ch, HEX);\n#endif\n if (sjis1) { \/\/ SJIS 2nd byte\n code = (sjis1 << 8) | ch;\n sjis1 = 0;\n font = &kanjiFont;\n } else if (issjis1(ch)) { \/\/ SJIS 1st byte\n sjis1 = ch;\n continue;\n } else {\n#if WRAP_NEWLINE\n if (ch == '\\n') {\n if (wrapline(tft->height(), height(), x, y)) {\n break;\n } else {\n continue;\n }\n }\n#endif\n code = ch;\n font = &ankFont;\n }\n\n int16_t tftWidth = tft->width();\n#if WRAP_LONGLINE\n if (wrap && *x + font->width() > tftWidth) {\n if (wrapline(tft->height(), height(), x, y)) {\n break;\n }\n }\n#endif\n int ret = loadFontAndDraw(tft, *x, *y, font, code, color, bgcolor);\n if (ret < -1) {\n return ret;\n } \/\/ -1の場合、指定した文字のフォントデータ無し\n *x += font->width();\n if (*x >= tftWidth) {\n break;\n }\n }\n return p - str;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"blif_error.hpp\"\n#include \"blifparse.hpp\"\n\nnamespace blifparse {\n\n\/\/We wrap the actual blif_error to issolate custom handlers from vaargs\nvoid blif_error_wrap(Callback& callback, const int line_no, const std::string& near_text, const char* fmt, ...) {\n va_list args;\n va_start(args, fmt);\n\n \/\/We need to copy the args so we don't change them before the true formating\n va_list args_copy;\n va_copy(args_copy, args);\n\n \/\/Determine the formatted length using a copy of the args\n int len = std::vsnprintf(nullptr, 0, fmt, args_copy); \n\n va_end(args_copy); \/\/Clean-up\n\n \/\/Negative if there is a problem with the format string\n assert(len >= 0 && \"Problem decoding format string\");\n\n size_t buf_size = len + 1; \/\/For terminator\n\n \/\/Allocate a buffer\n \/\/ unique_ptr will free buffer automatically\n std::unique_ptr buf(new char[buf_size]);\n\n \/\/Format into the buffer using the original args\n len = std::vsnprintf(buf.get(), buf_size, fmt, args);\n\n va_end(args); \/\/Clean-up\n\n assert(len >= 0 && \"Problem decoding format string\");\n assert(static_cast(len) == buf_size - 1);\n\n \/\/Build the string from the buffer\n std::string msg(buf.get(), len);\n\n \/\/Call the error handler\n callback.parse_error(line_no, near_text, msg);\n}\n\n}\nEscape line endings in error message near text#include \n#include \n#include \"blif_error.hpp\"\n#include \"blifparse.hpp\"\n\nnamespace blifparse {\n\nstd::string escape_string(const std::string& near_text);\n\n\/\/We wrap the actual blif_error to issolate custom handlers from vaargs\nvoid blif_error_wrap(Callback& callback, const int line_no, const std::string& near_text, const char* fmt, ...) {\n va_list args;\n va_start(args, fmt);\n\n \/\/We need to copy the args so we don't change them before the true formating\n va_list args_copy;\n va_copy(args_copy, args);\n\n \/\/Determine the formatted length using a copy of the args\n int len = std::vsnprintf(nullptr, 0, fmt, args_copy); \n\n va_end(args_copy); \/\/Clean-up\n\n \/\/Negative if there is a problem with the format string\n assert(len >= 0 && \"Problem decoding format string\");\n\n size_t buf_size = len + 1; \/\/For terminator\n\n \/\/Allocate a buffer\n \/\/ unique_ptr will free buffer automatically\n std::unique_ptr buf(new char[buf_size]);\n\n \/\/Format into the buffer using the original args\n len = std::vsnprintf(buf.get(), buf_size, fmt, args);\n\n va_end(args); \/\/Clean-up\n\n assert(len >= 0 && \"Problem decoding format string\");\n assert(static_cast(len) == buf_size - 1);\n\n \/\/Build the string from the buffer\n std::string msg(buf.get(), len);\n\n \/\/TODO: escape near_text\n std::string escaped_near_text = escape_string(near_text);\n\n \/\/Call the error handler\n callback.parse_error(line_no, escaped_near_text, msg);\n}\n\nstd::string escape_string(const std::string& near_text) {\n std::string escaped_text;\n\n for(char c : near_text) {\n\n if(c == '\\n') {\n escaped_text += \"\\\\n\";\n } else if(c == '\\r') {\n escaped_text += \"\\\\r\";\n } else {\n escaped_text += c;\n }\n }\n\n return escaped_text;\n}\n\n\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n * Template of a read routine\n *\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n\n#include \n#include \n#include \n\nNRRDIO_API\nint NrrdReader(const char* filename)\n{\n\t\n\tNrrd *nrrd = nrrdNew();\n\tif ( nrrdLoad( nrrd, filename, NULL ) )\n\t\tthrow biffGetDone(NRRD);\n \n if ( nrrd->dim > 3 )\n\t{\n\t\ttheMsg->printf(\"ERROR: for now, nrrd input can only handle data with dimension 3 or less.\");\n\t\treturn 0;\n\t}\n\t\n const int dims[3] = \n\t{ \n\t\t(nrrd->dim > 0) ? nrrd->axis[0].size : 1,\n\t\t(nrrd->dim > 1) ? nrrd->axis[1].size : 1,\n\t\t(nrrd->dim > 2) ? nrrd->axis[2].size : 1 \n\t};\n\t\n\tHxUniformScalarField3* field = NULL;\n\t\n\tswitch ( nrrd->type )\n\t{\n\t\tcase nrrdTypeUChar: field = new HxUniformScalarField3(dims,MC_UINT8,nrrd->data); break;\n\t\tcase nrrdTypeChar: field = new HxUniformScalarField3(dims,MC_INT8,nrrd->data); break;\n\t\tcase nrrdTypeUShort: field = new HxUniformScalarField3(dims,MC_UINT16,nrrd->data); break;\n\t\tcase nrrdTypeShort: field = new HxUniformScalarField3(dims,MC_INT16,nrrd->data); break;\n\t\tcase nrrdTypeInt: field = new HxUniformScalarField3(dims,MC_INT32,nrrd->data); break;\n\t\tcase nrrdTypeFloat: field = new HxUniformScalarField3(dims,MC_FLOAT,nrrd->data); break;\n\t\tcase nrrdTypeDouble: field = new HxUniformScalarField3(dims,MC_DOUBLE,nrrd->data); break;\n\t\tdefault: break;\n\t}\n\t\n\tif(field == NULL)\n\t{\n\t\ttheMsg->printf(\"ERROR: unknown nrrd input type.\");\n\t\treturn 0;\n\t}\n\t\n\t\/\/ First fetch axis spacing\n\tdouble spacing[3] = { 1.0, 1.0, 1.0 };\n\tfor ( size_t ax = 0; ax < nrrd->dim; ++ax )\n\t{\n\t\tswitch ( nrrdSpacingCalculate( nrrd, ax, spacing+ax, nrrd->axis[ax].spaceDirection ) )\n\t\t{\n\t\t\tcase nrrdSpacingStatusScalarNoSpace:\n\t\t\t\tbreak;\n\t\t\tcase nrrdSpacingStatusDirection:\n\t\t\t\tbreak;\n\t\t\tcase nrrdSpacingStatusScalarWithSpace:\n\t\t\t\ttheMsg->printf(\"WARNING: nrrdSpacingCalculate returned nrrdSpacingStatusScalarWithSpace\\n\");\n\t\t\t\tspacing[ax] = nrrd->axis[ax].spacing;\n\t\t\t\tbreak;\n\t\t\tcase nrrdSpacingStatusNone:\n\t\t\tdefault:\n\t\t\t\ttheMsg->printf(\"WARNING: no pixel spacings in Nrrd for axis %d ; setting to 1.0\\n\",ax);\n\t\t\t\tspacing[ax] = 1.0;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/ Now let's set the physical dimensions\n\t\/\/ This is done by defining the bounding box, the range of the voxel centres\n\t\/\/ given in the order: xmin,xmax,ymin ...\n\tfloat *bbox = field->bbox();\n\tbbox[0] = isnan(nrrd->spaceOrigin[0])?0.0f:(float) nrrd->spaceOrigin[0];\n\tbbox[2] = isnan(nrrd->spaceOrigin[1])?0.0f:(float) nrrd->spaceOrigin[1];\n\tbbox[4] = isnan(nrrd->spaceOrigin[2])?0.0f:(float) nrrd->spaceOrigin[2];\n\t\n\t\/\/ When a dimension is 1, Amira still seems to have a defined spacing\n\tbbox[1] = bbox[0] + (float) spacing[0] * ( dims[0] == 1 ? 1 : (dims[0] - 1) );\n\tbbox[3] = bbox[2] + (float) spacing[1] * ( dims[1] == 1 ? 1 : (dims[1] - 1) );\n\tbbox[5] = bbox[4] + (float) spacing[2] * ( dims[2] == 1 ? 1 : (dims[2] - 1) );\n\t\n\t\/\/ Shouldn't need to check for data loading\n\tHxData::registerData(field, filename);\n\t\n return 1;\n}\n\ndoc: Add a proper file header and mention GPL>=3 license\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n * Amira Reader for the nrrd (Nearly Raw Raster Data) format:\n * http:\/\/teem.sourceforge.net\/nrrd\/format.html\n * Currently only supports 3d single channel data\n * Copyright 2009 Gregory Jefferis. All rights reserved.\n * License GPL >=3\n * Certain portions of this code were copied\/amended from the CMTK\n * library: http:\/\/www.nitrc.org\/projects\/cmtk\/\n *\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n\n#include \n#include \n#include \n\nNRRDIO_API\nint NrrdReader(const char* filename)\n{\n\t\n\tNrrd *nrrd = nrrdNew();\n\tif ( nrrdLoad( nrrd, filename, NULL ) )\n\t\tthrow biffGetDone(NRRD);\n \n if ( nrrd->dim > 3 )\n\t{\n\t\ttheMsg->printf(\"ERROR: for now, nrrd input can only handle data with dimension 3 or less.\");\n\t\treturn 0;\n\t}\n\t\n const int dims[3] = \n\t{ \n\t\t(nrrd->dim > 0) ? nrrd->axis[0].size : 1,\n\t\t(nrrd->dim > 1) ? nrrd->axis[1].size : 1,\n\t\t(nrrd->dim > 2) ? nrrd->axis[2].size : 1 \n\t};\n\t\n\tHxUniformScalarField3* field = NULL;\n\t\n\tswitch ( nrrd->type )\n\t{\n\t\tcase nrrdTypeUChar: field = new HxUniformScalarField3(dims,MC_UINT8,nrrd->data); break;\n\t\tcase nrrdTypeChar: field = new HxUniformScalarField3(dims,MC_INT8,nrrd->data); break;\n\t\tcase nrrdTypeUShort: field = new HxUniformScalarField3(dims,MC_UINT16,nrrd->data); break;\n\t\tcase nrrdTypeShort: field = new HxUniformScalarField3(dims,MC_INT16,nrrd->data); break;\n\t\tcase nrrdTypeInt: field = new HxUniformScalarField3(dims,MC_INT32,nrrd->data); break;\n\t\tcase nrrdTypeFloat: field = new HxUniformScalarField3(dims,MC_FLOAT,nrrd->data); break;\n\t\tcase nrrdTypeDouble: field = new HxUniformScalarField3(dims,MC_DOUBLE,nrrd->data); break;\n\t\tdefault: break;\n\t}\n\t\n\tif(field == NULL)\n\t{\n\t\ttheMsg->printf(\"ERROR: unknown nrrd input type.\");\n\t\treturn 0;\n\t}\n\t\n\t\/\/ First fetch axis spacing\n\tdouble spacing[3] = { 1.0, 1.0, 1.0 };\n\tfor ( size_t ax = 0; ax < nrrd->dim; ++ax )\n\t{\n\t\tswitch ( nrrdSpacingCalculate( nrrd, ax, spacing+ax, nrrd->axis[ax].spaceDirection ) )\n\t\t{\n\t\t\tcase nrrdSpacingStatusScalarNoSpace:\n\t\t\t\tbreak;\n\t\t\tcase nrrdSpacingStatusDirection:\n\t\t\t\tbreak;\n\t\t\tcase nrrdSpacingStatusScalarWithSpace:\n\t\t\t\ttheMsg->printf(\"WARNING: nrrdSpacingCalculate returned nrrdSpacingStatusScalarWithSpace\\n\");\n\t\t\t\tspacing[ax] = nrrd->axis[ax].spacing;\n\t\t\t\tbreak;\n\t\t\tcase nrrdSpacingStatusNone:\n\t\t\tdefault:\n\t\t\t\ttheMsg->printf(\"WARNING: no pixel spacings in Nrrd for axis %d ; setting to 1.0\\n\",ax);\n\t\t\t\tspacing[ax] = 1.0;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/ Now let's set the physical dimensions\n\t\/\/ This is done by defining the bounding box, the range of the voxel centres\n\t\/\/ given in the order: xmin,xmax,ymin ...\n\tfloat *bbox = field->bbox();\n\tbbox[0] = isnan(nrrd->spaceOrigin[0])?0.0f:(float) nrrd->spaceOrigin[0];\n\tbbox[2] = isnan(nrrd->spaceOrigin[1])?0.0f:(float) nrrd->spaceOrigin[1];\n\tbbox[4] = isnan(nrrd->spaceOrigin[2])?0.0f:(float) nrrd->spaceOrigin[2];\n\t\n\t\/\/ When a dimension is 1, Amira still seems to have a defined spacing\n\tbbox[1] = bbox[0] + (float) spacing[0] * ( dims[0] == 1 ? 1 : (dims[0] - 1) );\n\tbbox[3] = bbox[2] + (float) spacing[1] * ( dims[1] == 1 ? 1 : (dims[1] - 1) );\n\tbbox[5] = bbox[4] + (float) spacing[2] * ( dims[2] == 1 ? 1 : (dims[2] - 1) );\n\t\n\t\/\/ Shouldn't need to check for data loading\n\tHxData::registerData(field, filename);\n\t\n return 1;\n}\n\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n * Template of a write routine\n *\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n\n#include \n#include \n#include \n\nNRRDIO_API\nint NrrdWriter(HxUniformScalarField3* data, const char* filename)\n{\n FILE* fp = fopen(filename,\"wb\");\n \n if (!fp) {\n\ttheMsg->ioError(filename);\n\treturn 0;\n }\n\n \/*\n * Write data into file ...\n *\/\n \n fclose(fp);\n \n return 1; \n}\nFirst functional version of NrrdWriter\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*\n * Template of a write routine\n *\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n\n#include \n#include \n#include \n#include \n\nNRRDIO_API\nint NrrdWriter(HxUniformScalarField3* field, const char* filename)\n{\n\tint compressed = 0;\n\t\/\/ Identify data type\n\tint nrrdType = nrrdTypeUnknown;\n\tswitch ( field->primType() )\n {\n\t\tcase McPrimType::mc_uint8: nrrdType = nrrdTypeUChar; break;\n\t\tcase McPrimType::mc_int8: nrrdType = nrrdTypeChar; break;\n\t\tcase McPrimType::mc_uint16: nrrdType = nrrdTypeUShort; break;\n\t\tcase McPrimType::mc_int16: nrrdType = nrrdTypeShort; break;\n\t\tcase McPrimType::mc_int32: nrrdType = nrrdTypeInt; break;\n\t\tcase McPrimType::mc_float: nrrdType = nrrdTypeFloat; break;\n\t\tcase McPrimType::mc_double: nrrdType = nrrdTypeDouble; break;\n\t\tdefault: break;\n }\n\n\tif(nrrdType == nrrdTypeUnknown)\n\t{\n\t\ttheMsg->printf(\"ERROR: unsupported output type: %s for nrrd\",field->primType().getName());\n\t\treturn 0;\n\t}\n\n\tvoid* data = field->lattice.dataPtr();\n\n\tNrrd *nrrd = nrrdNew();\n\tNrrdIoState *nios = nrrdIoStateNew();\n\n\tif ( compressed ) {\n\t\tif (nrrdEncodingGzip->available() )\n\t\t{\n\t\t\tnrrdIoStateEncodingSet( nios, nrrdEncodingGzip );\n\t\t\tnrrdIoStateSet( nios, nrrdIoStateZlibLevel, 9 );\n\t\t}\n\t\telse theMsg->printf(\"WARNING: Nrrd library does not support Gzip compression encoding.\\nPlease add -DTEEM_ZLIB to compiler options when building Nrrd library.\\n\");\n\t}\n\n\ttry\n\t{\n\t\tif ( nrrdWrap_va( nrrd, data, nrrdType, (size_t)3,\n\t\t (size_t)field->lattice.dimsInt()[0],\n\t\t (size_t)field->lattice.dimsInt()[1],\n\t\t (size_t)field->lattice.dimsInt()[2] ) )\n\t\t{\n\t\t\tthrow( biffGetDone(NRRD) );\n\t\t}\n\n\t\tnrrdSpaceDimensionSet( nrrd, 3 );\n\n\t\t\/\/ TODO: Would be nice to set space units. How does Amira store this?\n\/\/\t\tif ( writeVolume->MetaKeyExists(CMTK_META_SPACE_UNITS_STRING) )\n\/\/\t\t{\n\/\/\t\t\tnrrd->spaceUnits[0] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() );\n\/\/\t\t\tnrrd->spaceUnits[1] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() );\n\/\/\t\t\tnrrd->spaceUnits[2] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() );\n\/\/\t\t}\n\n\t\tint kind[NRRD_DIM_MAX] = { nrrdKindDomain, nrrdKindDomain, nrrdKindDomain };\n\t\tnrrdAxisInfoSet_nva( nrrd, nrrdAxisInfoKind, kind );\n\n\t\t\/\/ TODO: Would be nice to write some kind of space if this exists\n\n\t\t\/\/ Fetch bounding box information and voxel size\n\t\tfloat* bbox = field->bbox();\n\t\tMcVec3f voxelSize = field->getVoxelSize();\n\n\t\t\/\/ Just deal with space directions orthogonal to data axes\n\t\t\/\/ TODO: Fetch transformation and use that\n\t\tdouble spaceDir[NRRD_DIM_MAX][NRRD_SPACE_DIM_MAX];\n\t\tfor ( int i = 0; i < 3; ++i )\n\t\t{\n\t\t\tfor ( int j = 0; j < 3; ++j )\n\t\t\t{\n\t\t\t\tif (i == j) spaceDir[i][j] = (double) voxelSize[i];\n\t\t\t}\n\t\t}\n\t\tnrrdAxisInfoSet_nva( nrrd, nrrdAxisInfoSpaceDirection, spaceDir );\n\n\t\tdouble origin[NRRD_DIM_MAX] = { bbox[0], bbox[2], bbox[4] };\n\t\tif ( nrrdSpaceOriginSet( nrrd, origin ) )\n\t\t{\n\t\t\tthrow( biffGetDone(NRRD) );\n\t\t}\n\n\t\tnrrdAxisInfoSet_va( nrrd, nrrdAxisInfoLabel, \"x\", \"y\", \"z\" );\n\n\t\tif ( nrrdSave( filename, nrrd, nios ) )\n\t\t{\n\t\t\tthrow( biffGetDone(NRRD) );\n\t\t}\n }\n\tcatch ( char* err )\n {\n\t\ttheMsg->printf(\"ERROR: NrrdIO library returned error '%s'\\n\", err);\n\t\tfree( err );\n\t\treturn 0;\n }\n\n\tnrrdIoStateNix( nios );\n\tnrrdNix(nrrd);\n\n return 1; \n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace fnord;\n\nnamespace tsdb {\n\nRefPtr StreamChunk::create(\n const SHA1Hash& partition_key,\n const String& stream_key,\n StreamConfig* config,\n TSDBNodeRef* node) {\n return RefPtr(\n new StreamChunk(\n partition_key,\n stream_key,\n config,\n node));\n}\n\nRefPtr StreamChunk::reopen(\n const SHA1Hash& partition_key,\n const StreamChunkState& state,\n StreamConfig* config,\n TSDBNodeRef* node) {\n return RefPtr(\n new StreamChunk(\n partition_key,\n state,\n config,\n node));\n}\n\nStreamChunk::StreamChunk(\n const SHA1Hash& partition_key,\n const String& stream_key,\n StreamConfig* config,\n TSDBNodeRef* node) :\n stream_key_(stream_key),\n key_(partition_key),\n config_(config),\n node_(node),\n records_(\n FileUtil::joinPaths(\n node->db_path,\n StringUtil::stripShell(stream_key) + \".\")),\n last_compaction_(0) {\n records_.setMaxDatafileSize(config_->max_sstable_size());\n}\n\nStreamChunk::StreamChunk(\n const SHA1Hash& partition_key,\n const StreamChunkState& state,\n StreamConfig* config,\n TSDBNodeRef* node) :\n stream_key_(state.stream_key),\n key_(partition_key),\n config_(config),\n node_(node),\n records_(\n FileUtil::joinPaths(\n node->db_path,\n StringUtil::stripShell(state.stream_key) + \".\"),\n state.record_state),\n repl_offsets_(state.repl_offsets),\n last_compaction_(0) {\n scheduleCompaction();\n node_->compactionq.insert(this, WallClock::unixMicros());\n node_->replicationq.insert(this, WallClock::unixMicros());\n records_.setMaxDatafileSize(config_->max_sstable_size());\n}\n\nvoid StreamChunk::insertRecord(\n const SHA1Hash& record_id,\n const Buffer& record) {\n std::unique_lock lk(mutex_);\n\n fnord::logTrace(\n \"tsdb\",\n \"Insert 1 record into stream='$0'\",\n stream_key_);\n\n auto old_ver = records_.version();\n records_.addRecord(record_id, record);\n if (records_.version() != old_ver) {\n commitState();\n }\n\n scheduleCompaction();\n}\n\nvoid StreamChunk::insertRecords(const Vector& records) {\n std::unique_lock lk(mutex_);\n\n fnord::logTrace(\n \"tsdb\",\n \"Insert $0 records into stream='$1'\",\n records.size(),\n stream_key_);\n\n auto old_ver = records_.version();\n records_.addRecords(records);\n if (records_.version() != old_ver) {\n commitState();\n }\n\n scheduleCompaction();\n}\n\nvoid StreamChunk::scheduleCompaction() {\n auto now = WallClock::unixMicros();\n auto interval = config_->compaction_interval();\n auto last = last_compaction_.unixMicros();\n uint64_t compaction_delay = 0;\n\n if (last + interval > now) {\n compaction_delay = (last + interval) - now;\n }\n\n node_->compactionq.insert(this, now + compaction_delay);\n}\n\nvoid StreamChunk::compact() {\n std::unique_lock lk(mutex_);\n last_compaction_ = DateTime::now();\n lk.unlock();\n\n fnord::logDebug(\n \"tsdb.replication\",\n \"Compacting partition; stream='$0' partition='$1'\",\n stream_key_,\n key_.toString());\n\n Set deleted_files;\n records_.compact(&deleted_files);\n\n lk.lock();\n commitState();\n lk.unlock();\n\n node_->replicationq.insert(this, WallClock::unixMicros());\n\n for (const auto& f : deleted_files) {\n FileUtil::rm(f);\n }\n}\n\nvoid StreamChunk::replicate() {\n std::unique_lock lk(replication_mutex_);\n\n auto cur_offset = records_.lastOffset();\n auto replicas = node_->replication_scheme->replicasFor(key_);\n bool dirty = false;\n bool needs_replication = false;\n bool has_error = false;\n\n for (const auto& r : replicas) {\n auto& off = repl_offsets_[r.unique_id];\n\n if (off < cur_offset) {\n try {\n auto rep_offset = replicateTo(r.addr, off);\n dirty = true;\n off = rep_offset;\n if (off < cur_offset) {\n needs_replication = true;\n }\n } catch (const std::exception& e) {\n has_error = true;\n\n fnord::logError(\n \"tsdb.replication\",\n e,\n \"Error while replicating stream '$0' to '$1'\",\n stream_key_,\n r.addr);\n }\n }\n }\n\n for (auto cur = repl_offsets_.begin(); cur != repl_offsets_.end(); ) {\n bool found;\n for (const auto& r : replicas) {\n if (r.unique_id == cur->first) {\n found = true;\n break;\n }\n }\n\n if (found) {\n ++cur;\n } else {\n cur = repl_offsets_.erase(cur);\n dirty = true;\n }\n }\n\n if (dirty) {\n std::unique_lock lk(mutex_);\n commitState();\n }\n\n if (needs_replication) {\n node_->replicationq.insert(this, WallClock::unixMicros());\n } else if (has_error) {\n node_->replicationq.insert(\n this,\n WallClock::unixMicros() + 30 * kMicrosPerSecond);\n }\n}\n\nuint64_t StreamChunk::replicateTo(const String& addr, uint64_t offset) {\n size_t batch_size = 1024;\n util::BinaryMessageWriter batch;\n\n auto start_offset = records_.firstOffset();\n if (start_offset > offset) {\n offset = start_offset;\n }\n\n size_t n = 0;\n records_.fetchRecords(offset, batch_size, [this, &batch, &n] (\n const SHA1Hash& record_id,\n const void* record_data,\n size_t record_size) {\n ++n;\n\n batch.append(record_id.data(), record_id.size());\n batch.appendVarUInt(record_size);\n batch.append(record_data, record_size);\n });\n\n fnord::logDebug(\n \"tsdb.replication\",\n \"Replicating to $0; stream='$1' partition='$2' offset=$3\",\n addr,\n stream_key_,\n key_.toString(),\n offset);\n\n URI uri(StringUtil::format(\n \"http:\/\/$0\/tsdb\/replicate?stream=$1&chunk=$2\",\n addr,\n URI::urlEncode(stream_key_),\n URI::urlEncode(key_.toString())));\n\n http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());\n req.addHeader(\"Host\", uri.hostAndPort());\n req.addHeader(\"Content-Type\", \"application\/fnord-msg\");\n req.addBody(batch.data(), batch.size());\n\n auto res = node_->http->executeRequest(req);\n res.wait();\n\n const auto& r = res.get();\n if (r.statusCode() != 201) {\n RAISEF(kRuntimeError, \"received non-201 response: $0\", r.body().toString());\n }\n\n return offset + n;\n}\n\nVector StreamChunk::listFiles() const {\n return records_.listDatafiles();\n}\n\nPartitionInfo StreamChunk::partitionInfo() const {\n PartitionInfo pi;\n pi.set_partition_key(key_.toString());\n pi.set_stream_key(stream_key_);\n pi.set_version(records_.version());\n pi.set_exists(true);\n return pi;\n}\n\nvoid StreamChunk::commitState() {\n StreamChunkState state;\n state.record_state = records_.getState();\n state.stream_key = stream_key_;\n state.repl_offsets = repl_offsets_;\n\n util::BinaryMessageWriter buf;\n state.encode(&buf);\n\n auto txn = node_->db->startTransaction(false);\n txn->update(key_.data(), key_.size(), buf.data(), buf.size());\n txn->commit();\n}\n\nvoid StreamChunkState::encode(\n util::BinaryMessageWriter* writer) const {\n writer->appendLenencString(stream_key);\n record_state.encode(writer);\n\n writer->appendVarUInt(repl_offsets.size());\n for (const auto& ro : repl_offsets) {\n writer->appendVarUInt(ro.first);\n writer->appendVarUInt(ro.second);\n }\n\n writer->appendVarUInt(record_state.version);\n}\n\nvoid StreamChunkState::decode(util::BinaryMessageReader* reader) {\n stream_key = reader->readLenencString();\n record_state.decode(reader);\n\n auto nrepl_offsets = reader->readVarUInt();\n for (int i = 0; i < nrepl_offsets; ++i) {\n auto id = reader->readVarUInt();\n auto off = reader->readVarUInt();\n repl_offsets.emplace(id, off);\n }\n\n record_state.version = reader->readVarUInt();\n}\n\n}\nfetch replicas for partition key\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace fnord;\n\nnamespace tsdb {\n\nRefPtr StreamChunk::create(\n const SHA1Hash& partition_key,\n const String& stream_key,\n StreamConfig* config,\n TSDBNodeRef* node) {\n return RefPtr(\n new StreamChunk(\n partition_key,\n stream_key,\n config,\n node));\n}\n\nRefPtr StreamChunk::reopen(\n const SHA1Hash& partition_key,\n const StreamChunkState& state,\n StreamConfig* config,\n TSDBNodeRef* node) {\n return RefPtr(\n new StreamChunk(\n partition_key,\n state,\n config,\n node));\n}\n\nStreamChunk::StreamChunk(\n const SHA1Hash& partition_key,\n const String& stream_key,\n StreamConfig* config,\n TSDBNodeRef* node) :\n stream_key_(stream_key),\n key_(partition_key),\n config_(config),\n node_(node),\n records_(\n FileUtil::joinPaths(\n node->db_path,\n StringUtil::stripShell(stream_key) + \".\")),\n last_compaction_(0) {\n records_.setMaxDatafileSize(config_->max_sstable_size());\n}\n\nStreamChunk::StreamChunk(\n const SHA1Hash& partition_key,\n const StreamChunkState& state,\n StreamConfig* config,\n TSDBNodeRef* node) :\n stream_key_(state.stream_key),\n key_(partition_key),\n config_(config),\n node_(node),\n records_(\n FileUtil::joinPaths(\n node->db_path,\n StringUtil::stripShell(state.stream_key) + \".\"),\n state.record_state),\n repl_offsets_(state.repl_offsets),\n last_compaction_(0) {\n scheduleCompaction();\n node_->compactionq.insert(this, WallClock::unixMicros());\n node_->replicationq.insert(this, WallClock::unixMicros());\n records_.setMaxDatafileSize(config_->max_sstable_size());\n}\n\nvoid StreamChunk::insertRecord(\n const SHA1Hash& record_id,\n const Buffer& record) {\n std::unique_lock lk(mutex_);\n\n fnord::logTrace(\n \"tsdb\",\n \"Insert 1 record into stream='$0'\",\n stream_key_);\n\n auto old_ver = records_.version();\n records_.addRecord(record_id, record);\n if (records_.version() != old_ver) {\n commitState();\n }\n\n scheduleCompaction();\n}\n\nvoid StreamChunk::insertRecords(const Vector& records) {\n std::unique_lock lk(mutex_);\n\n fnord::logTrace(\n \"tsdb\",\n \"Insert $0 records into stream='$1'\",\n records.size(),\n stream_key_);\n\n auto old_ver = records_.version();\n records_.addRecords(records);\n if (records_.version() != old_ver) {\n commitState();\n }\n\n scheduleCompaction();\n}\n\nvoid StreamChunk::scheduleCompaction() {\n auto now = WallClock::unixMicros();\n auto interval = config_->compaction_interval();\n auto last = last_compaction_.unixMicros();\n uint64_t compaction_delay = 0;\n\n if (last + interval > now) {\n compaction_delay = (last + interval) - now;\n }\n\n node_->compactionq.insert(this, now + compaction_delay);\n}\n\nvoid StreamChunk::compact() {\n std::unique_lock lk(mutex_);\n last_compaction_ = DateTime::now();\n lk.unlock();\n\n fnord::logDebug(\n \"tsdb.replication\",\n \"Compacting partition; stream='$0' partition='$1'\",\n stream_key_,\n key_.toString());\n\n Set deleted_files;\n records_.compact(&deleted_files);\n\n lk.lock();\n commitState();\n lk.unlock();\n\n node_->replicationq.insert(this, WallClock::unixMicros());\n\n for (const auto& f : deleted_files) {\n FileUtil::rm(f);\n }\n}\n\nvoid StreamChunk::replicate() {\n std::unique_lock lk(replication_mutex_);\n\n auto cur_offset = records_.lastOffset();\n auto replicas = node_->replication_scheme->replicasFor(\n String((char*) key_.data(), key_.size()));\n\n bool dirty = false;\n bool needs_replication = false;\n bool has_error = false;\n\n for (const auto& r : replicas) {\n auto& off = repl_offsets_[r.unique_id];\n\n if (off < cur_offset) {\n try {\n auto rep_offset = replicateTo(r.addr, off);\n dirty = true;\n off = rep_offset;\n if (off < cur_offset) {\n needs_replication = true;\n }\n } catch (const std::exception& e) {\n has_error = true;\n\n fnord::logError(\n \"tsdb.replication\",\n e,\n \"Error while replicating stream '$0' to '$1'\",\n stream_key_,\n r.addr);\n }\n }\n }\n\n for (auto cur = repl_offsets_.begin(); cur != repl_offsets_.end(); ) {\n bool found;\n for (const auto& r : replicas) {\n if (r.unique_id == cur->first) {\n found = true;\n break;\n }\n }\n\n if (found) {\n ++cur;\n } else {\n cur = repl_offsets_.erase(cur);\n dirty = true;\n }\n }\n\n if (dirty) {\n std::unique_lock lk(mutex_);\n commitState();\n }\n\n if (needs_replication) {\n node_->replicationq.insert(this, WallClock::unixMicros());\n } else if (has_error) {\n node_->replicationq.insert(\n this,\n WallClock::unixMicros() + 30 * kMicrosPerSecond);\n }\n}\n\nuint64_t StreamChunk::replicateTo(const String& addr, uint64_t offset) {\n size_t batch_size = 1024;\n util::BinaryMessageWriter batch;\n\n auto start_offset = records_.firstOffset();\n if (start_offset > offset) {\n offset = start_offset;\n }\n\n size_t n = 0;\n records_.fetchRecords(offset, batch_size, [this, &batch, &n] (\n const SHA1Hash& record_id,\n const void* record_data,\n size_t record_size) {\n ++n;\n\n batch.append(record_id.data(), record_id.size());\n batch.appendVarUInt(record_size);\n batch.append(record_data, record_size);\n });\n\n fnord::logDebug(\n \"tsdb.replication\",\n \"Replicating to $0; stream='$1' partition='$2' offset=$3\",\n addr,\n stream_key_,\n key_.toString(),\n offset);\n\n URI uri(StringUtil::format(\n \"http:\/\/$0\/tsdb\/replicate?stream=$1&chunk=$2\",\n addr,\n URI::urlEncode(stream_key_),\n URI::urlEncode(key_.toString())));\n\n http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());\n req.addHeader(\"Host\", uri.hostAndPort());\n req.addHeader(\"Content-Type\", \"application\/fnord-msg\");\n req.addBody(batch.data(), batch.size());\n\n auto res = node_->http->executeRequest(req);\n res.wait();\n\n const auto& r = res.get();\n if (r.statusCode() != 201) {\n RAISEF(kRuntimeError, \"received non-201 response: $0\", r.body().toString());\n }\n\n return offset + n;\n}\n\nVector StreamChunk::listFiles() const {\n return records_.listDatafiles();\n}\n\nPartitionInfo StreamChunk::partitionInfo() const {\n PartitionInfo pi;\n pi.set_partition_key(key_.toString());\n pi.set_stream_key(stream_key_);\n pi.set_version(records_.version());\n pi.set_exists(true);\n return pi;\n}\n\nvoid StreamChunk::commitState() {\n StreamChunkState state;\n state.record_state = records_.getState();\n state.stream_key = stream_key_;\n state.repl_offsets = repl_offsets_;\n\n util::BinaryMessageWriter buf;\n state.encode(&buf);\n\n auto txn = node_->db->startTransaction(false);\n txn->update(key_.data(), key_.size(), buf.data(), buf.size());\n txn->commit();\n}\n\nvoid StreamChunkState::encode(\n util::BinaryMessageWriter* writer) const {\n writer->appendLenencString(stream_key);\n record_state.encode(writer);\n\n writer->appendVarUInt(repl_offsets.size());\n for (const auto& ro : repl_offsets) {\n writer->appendVarUInt(ro.first);\n writer->appendVarUInt(ro.second);\n }\n\n writer->appendVarUInt(record_state.version);\n}\n\nvoid StreamChunkState::decode(util::BinaryMessageReader* reader) {\n stream_key = reader->readLenencString();\n record_state.decode(reader);\n\n auto nrepl_offsets = reader->readVarUInt();\n for (int i = 0; i < nrepl_offsets; ++i) {\n auto id = reader->readVarUInt();\n auto off = reader->readVarUInt();\n repl_offsets.emplace(id, off);\n }\n\n record_state.version = reader->readVarUInt();\n}\n\n}\n<|endoftext|>"} {"text":"\/\/=============================================================================\n\/\/ ■ audio.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 提供声音支持。\n\/\/=============================================================================\n\n#include \"global.hpp\"\n\nnamespace Audio {\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 全局变量\n\t\/\/-------------------------------------------------------------------------\n\tconst size_t vf_buffer_size = 4096;\n\tPaStream* wave_stream;\n\tstruct callback_data data;\n\tstruct active_sound* active_sounds[16] = {NULL};\n\tsize_t active_sound_count = 0;\n\t\/\/ 为了避免反复计算,将正弦值存储在这里。其分布为\n\t\/\/ [0] = sin 0\n\t\/\/ [64] = sin ⅛π\n\t\/\/ [128] = sin ¼π\n\t\/\/ [192] = sin ⅜π\n\tfloat sine_table[256];\n\tconst size_t sine_table_size = ARRAY_SIZE(sine_table);\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 初始化\n\t\/\/-------------------------------------------------------------------------\n\tvoid init() {\n\t\tensure_no_error(Pa_Initialize());\n\t\tpopulate_sine_table();\n\t\tdata.type = 0;\n\t\t\/\/ 44100Hz\n\t\tdata.sample_rate = 44100.0d;\n\t\tensure_no_error(Pa_OpenDefaultStream(\n\t\t\t&wave_stream,\n\t\t\t\/\/ 无声输入 - 立体声输出、32位浮点数\n\t\t\t0, 2, paFloat32,\n\t\t\tdata.sample_rate,\n\t\t\t\/\/ 256格缓冲区\n\t\t\t256,\n\t\t\tplay_callback, &data\n\t\t));\n\t\tensure_no_error(Pa_StartStream(wave_stream));\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 释放\n\t\/\/-------------------------------------------------------------------------\n\tvoid wobuzhidaozhegefangfayinggaijiaoshenmemingzi() {\n\t\tensure_no_error(Pa_StopStream(wave_stream));\n\t\tensure_no_error(Pa_CloseStream(wave_stream));\n\t\tPa_Terminate();\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 统一处理错误\n\t\/\/-------------------------------------------------------------------------\n\tvoid ensure_no_error(PaError err) {\n\t\tif (err >= 0) return;\n\t\tPa_Terminate();\n\t\trb_raise(\n\t\t\trb_eRuntimeError,\n\t\t\t\"PortAudio error %d: %s\",\n\t\t\terr, Pa_GetErrorText(err)\n\t\t);\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 内部使用的回调函数\n\t\/\/-------------------------------------------------------------------------\n\tint play_callback(\n\t\tconst void* input_buffer UNUSED,\n\t\tvoid* output_buffer,\n\t\tunsigned long frame_count,\n\t\tconst PaStreamCallbackTimeInfo* time_info UNUSED,\n\t\tPaStreamCallbackFlags status_flags UNUSED,\n\t\tvoid* user_data\n\t) {\n\t\tfloat* output = (float*) output_buffer;\n\t\tstruct callback_data* data = (struct callback_data*) user_data;\n\t\t\/\/ Magic. 吔屎啦PortAudio!\n\t\t#define FEED_AUDIO_DATA(value) do { \\\n\t\t\t*output++ = (value); \\\n\t\t\t*output++ = (value); \\\n\t\t\tframe_count--; \\\n\t\t} while (false)\n\t\twhile (frame_count > 0) switch (data->type) {\n\t\t\tcase 0:\n\t\t\t\tFEED_AUDIO_DATA(.0f);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tget_next_triangle_value(&data->data.triangle);\n\t\t\t\tFEED_AUDIO_DATA(data->data.triangle.value);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tdefault:\n\t\t\t\tget_next_sine_value(&data->data.sine);\n\t\t\t\tFEED_AUDIO_DATA(data->data.sine.value);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t*((float*) 0) = .0f; \/\/ 音频就是爆炸!\n\t\t\t\tFEED_AUDIO_DATA(.0f);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tFEED_AUDIO_DATA((float) (\n\t\t\t\t\t(double) rand() \/ (double) RAND_MAX * 2.0d - 1.0d\n\t\t\t\t));\n\t\t\t\tbreak;\n\t\t}\n\t\t#undef FEED_AUDIO_DATA\n\t\treturn paContinue;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 停止播放\n\t\/\/-------------------------------------------------------------------------\n\tvoid stop() {\n\t\tdata.type = 0;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放三角波\n\t\/\/ freq : 频率(Hz)\n\t\/\/-------------------------------------------------------------------------\n\tvoid play_triangle(float freq) {\n\t\tdata.data.triangle.value = -1.0f;\n\t\tdata.data.triangle.delta = 2.0f \/ ((float) data.sample_rate \/ freq \/ 2);\n\t\tdata.type = 1;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 计算下一个值使输出呈三角波形\n\t\/\/-------------------------------------------------------------------------\n\tvoid get_next_triangle_value(struct triangle_data* data) {\n\t\tdata->value += data->delta;\n\t\tif (data->value > 1.0f) {\n\t\t\tdata->value = 2.0f - data->value;\n\t\t\tdata->delta = -data->delta;\n\t\t} else if (data->value < -1.0f) {\n\t\t\tdata->value = -2.0f - data->value;\n\t\t\tdata->delta = -data->delta;\n\t\t}\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放正弦波\n\t\/\/ freq : 频率(Hz)\n\t\/\/-------------------------------------------------------------------------\n\tvoid play_sine(float freq) {\n\t\tdata.data.sine.index = .0f;\n\t\tdata.data.sine.index_delta =\n\t\t\tsine_table_size \/ ((float) data.sample_rate \/ 4 \/ freq);\n\t\tdata.data.sine.minus = false;\n\t\tdata.type = 2;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 向正弦表中填充数据\n\t\/\/-------------------------------------------------------------------------\n\tvoid populate_sine_table() {\n\t\tfloat k = 0.5f \/ (float) sine_table_size * Util::PIf;\n\t\tfor (size_t i = 0; i < sine_table_size; i++) sine_table[i] = sin(i * k);\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 计算正弦函数的下一值\n\t\/\/-------------------------------------------------------------------------\n\tvoid get_next_sine_value(struct sine_data* data) {\n\t\tdata->index += data->index_delta;\n\t\tif (data->index > (float) sine_table_size) {\n\t\t\tdata->index = sine_table_size * 2.0f - data->index;\n\t\t\tdata->index_delta = -data->index_delta;\n\t\t} else if (data->index < 0) {\n\t\t\tdata->index = -data->index;\n\t\t\tdata->index_delta = -data->index_delta;\n\t\t\tdata->minus = !data->minus;\n\t\t}\n\t\tdata->value = sine_table[(size_t) (int) data->index];\n\t\tif (data->minus) data->value = -data->value;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放声音\n\t\/\/-------------------------------------------------------------------------\n\tvoid play_sound(const char* filename) {\n\t\tcompact_active_sounds_array();\n\t\tlog(\"play sound %s\", filename);\n\t\tstruct active_sound* sound = new struct active_sound;\n\t\tsound->stream = NULL;\n\t\t\/\/ sound->file\n\t\tsound->file = fopen(filename, \"rb\");\n\t\tif (!sound->file) {\n\t\t\tdelete sound;\n\t\t\trb_raise(rb_eIOError, \"can't open this file: %s\", filename);\n\t\t}\n\t\t\/\/ sound->vf\n\t\tif (ov_open_callbacks(\n\t\t\tsound->file, &sound->vf,\n\t\t\tNULL, 0, OV_CALLBACKS_NOCLOSE\n\t\t) < 0) {\n\t\t\tdelete sound;\n\t\t\tfclose(sound->file);\n\t\t\trb_raise(rb_eRuntimeError, \"can't open ogg vorbis file: %s\", filename);\n\t\t}\n\t\t\/\/ sound->stream\n\t\tensure_no_error(Pa_OpenDefaultStream(\n\t\t\t&sound->stream, 0, 2, paFloat32, 44100,\n\t\t\t256, play_sound_callback, sound\n\t\t));\n\t\t\/\/ sound->*_head\n\t\tsound->play_head = 0;\n\t\tsound->load_head = 0;\n\t\t\/\/ etc\n\t\tsound->eof = false;\n\t\tactive_sounds[active_sound_count] = sound;\n\t\tactive_sound_count++;\n\t\tdecode_vorbis(sound);\n\t\t\/\/ sound->decode_thread\n\t\tsound->decode_thread = new thread(decode_vorbis_thread, sound);\n\t\tensure_no_error(Pa_StartStream(sound->stream));\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 扔掉active_sounds中已经播放完的条目\n\t\/\/-------------------------------------------------------------------------\n\tvoid compact_active_sounds_array() {\n\t\tsize_t size = ARRAY_SIZE(active_sounds);\n\t\tfor (size_t i = 0; i < size; i++) {\n\t\t\tif (!active_sounds[i]) continue;\n\t\t\tPaError active = Pa_IsStreamActive(active_sounds[i]->stream);\n\t\t\tensure_no_error(active);\n\t\t\tif (!active) {\n\t\t\t\tPa_CloseStream(active_sounds[i]->stream);\n\t\t\t\tov_clear(&active_sounds[i]->vf);\n\t\t\t\tfclose(active_sounds[i]->file);\n\t\t\t\tactive_sounds[i]->decode_thread->join();\n\t\t\t\tdelete active_sounds[i]->decode_thread;\n\t\t\t\tdelete active_sounds[i];\n\t\t\t\tactive_sounds[i] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放声音的回调函数\n\t\/\/-------------------------------------------------------------------------\n\tint play_sound_callback(\n\t\tconst void* input_buffer UNUSED,\n\t\tvoid* output_buffer,\n\t\tunsigned long frame_count,\n\t\tconst PaStreamCallbackTimeInfo* time_info UNUSED,\n\t\tPaStreamCallbackFlags status_flags UNUSED,\n\t\tvoid* user_data\n\t) {\n\t\tfloat* output = (float*) output_buffer;\n\t\tstruct active_sound* sound = (struct active_sound*) user_data;\n\t\twhile (frame_count > 0) {\n\t\t\tif (sound->play_head < sound->load_head) {\n\t\t\t\tsize_t index = sound->play_head % vf_buffer_size;\n\t\t\t\t*output++ = sound->vf_buffer[0][index];\n\t\t\t\t*output++ = sound->vf_buffer[1][index];\n\t\t\t\tsound->play_head++;\n\t\t\t} else {\n\t\t\t\tTWICE *output++ = .0f;\n\t\t\t}\n\t\t\tframe_count--;\n\t\t}\n\t\treturn sound->eof ? paComplete : paContinue;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 解码文件来填active_sound结构中的缓冲区\n\t\/\/-------------------------------------------------------------------------\n\tvoid decode_vorbis(struct active_sound* sound) {\n\t\twhile (sound->load_head - sound->play_head < vf_buffer_size) {\n\t\t\t\/\/ After ov_read_float(), tmp_buffer will be changed.\n\t\t\tfloat** tmp_buffer;\n\t\t\tlong ret = ov_read_float(\n\t\t\t\t&sound->vf,\n\t\t\t\t&tmp_buffer,\n\t\t\t\tvf_buffer_size,\n\t\t\t\t&sound->bitstream\n\t\t\t);\n\t\t\tif (ret > 0) {\n\t\t\t\tfor (long i = 0; i < ret; i++) {\n\t\t\t\t\tsize_t j = (sound->load_head + i) % vf_buffer_size;\n\t\t\t\t\tsound->vf_buffer[0][j] = tmp_buffer[0][i];\n\t\t\t\t\tsound->vf_buffer[1][j] = tmp_buffer[1][i];\n\t\t\t\t}\n\t\t\t\tsound->load_head += ret;\n\t\t\t} else if (ret == 0) {\n\t\t\t\twhile (sound->load_head - sound->play_head < vf_buffer_size) {\n\t\t\t\t\tsize_t j = sound->load_head % vf_buffer_size;\n\t\t\t\t\tsound->vf_buffer[0][j] = .0f;\n\t\t\t\t\tsound->vf_buffer[1][j] = .0f;\n\t\t\t\t\tsound->load_head++;\n\t\t\t\t}\n\t\t\t\tsound->eof = true;\n\t\t\t\tbreak;\n\t\t\t} else if (ret == OV_EBADLINK) {\n\t\t\t\trb_raise(rb_eIOError, \"bad vorbis data (OV_EBADLINK)\");\n\t\t\t} else if (ret == OV_EINVAL) {\n\t\t\t\trb_raise(rb_eIOError, \"bad vorbis data (OV_EINVAL)\");\n\t\t\t}\n\t\t\t\/\/ We must not free(tmp_buffer). It isn't ours.\n\t\t}\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 解码线程函数\n\t\/\/-------------------------------------------------------------------------\n\tvoid decode_vorbis_thread(struct active_sound* sound) {\n\t\twhile (!sound->eof) {\n\t\t\tdecode_vorbis(sound);\n\t\t}\n\t}\n}\nAudio.play_sound艹成了!\/\/=============================================================================\n\/\/ ■ audio.cpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 提供声音支持。\n\/\/=============================================================================\n\n#include \"global.hpp\"\n\nnamespace Audio {\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 全局变量\n\t\/\/-------------------------------------------------------------------------\n\tconst size_t vf_buffer_size = 4096;\n\tPaStream* wave_stream;\n\tstruct callback_data data;\n\tstruct active_sound* active_sounds[16] = {NULL};\n\tsize_t active_sound_count = 0;\n\t\/\/ 为了避免反复计算,将正弦值存储在这里。其分布为\n\t\/\/ [0] = sin 0\n\t\/\/ [64] = sin ⅛π\n\t\/\/ [128] = sin ¼π\n\t\/\/ [192] = sin ⅜π\n\tfloat sine_table[256];\n\tconst size_t sine_table_size = ARRAY_SIZE(sine_table);\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 初始化\n\t\/\/-------------------------------------------------------------------------\n\tvoid init() {\n\t\tensure_no_error(Pa_Initialize());\n\t\tpopulate_sine_table();\n\t\tdata.type = 0;\n\t\t\/\/ 44100Hz\n\t\tdata.sample_rate = 44100.0d;\n\t\tensure_no_error(Pa_OpenDefaultStream(\n\t\t\t&wave_stream,\n\t\t\t\/\/ 无声输入 - 立体声输出、32位浮点数\n\t\t\t0, 2, paFloat32,\n\t\t\tdata.sample_rate,\n\t\t\t\/\/ 256格缓冲区\n\t\t\t256,\n\t\t\tplay_callback, &data\n\t\t));\n\t\tensure_no_error(Pa_StartStream(wave_stream));\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 释放\n\t\/\/-------------------------------------------------------------------------\n\tvoid wobuzhidaozhegefangfayinggaijiaoshenmemingzi() {\n\t\tensure_no_error(Pa_StopStream(wave_stream));\n\t\tensure_no_error(Pa_CloseStream(wave_stream));\n\t\tPa_Terminate();\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 统一处理错误\n\t\/\/-------------------------------------------------------------------------\n\tvoid ensure_no_error(PaError err) {\n\t\tif (err >= 0) return;\n\t\tPa_Terminate();\n\t\trb_raise(\n\t\t\trb_eRuntimeError,\n\t\t\t\"PortAudio error %d: %s\",\n\t\t\terr, Pa_GetErrorText(err)\n\t\t);\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放波形时使用的回调函数\n\t\/\/-------------------------------------------------------------------------\n\tint play_callback(\n\t\tconst void* input_buffer UNUSED,\n\t\tvoid* output_buffer,\n\t\tunsigned long frame_count,\n\t\tconst PaStreamCallbackTimeInfo* time_info UNUSED,\n\t\tPaStreamCallbackFlags status_flags UNUSED,\n\t\tvoid* user_data\n\t) {\n\t\tfloat* output = (float*) output_buffer;\n\t\tstruct callback_data* data = (struct callback_data*) user_data;\n\t\t\/\/ Magic. 吔屎啦PortAudio!\n\t\t#define FEED_AUDIO_DATA(value) do { \\\n\t\t\t*output++ = (value); \\\n\t\t\t*output++ = (value); \\\n\t\t\tframe_count--; \\\n\t\t} while (false)\n\t\twhile (frame_count > 0) switch (data->type) {\n\t\t\tcase 0:\n\t\t\t\tFEED_AUDIO_DATA(.0f);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tget_next_triangle_value(&data->data.triangle);\n\t\t\t\tFEED_AUDIO_DATA(data->data.triangle.value);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tdefault:\n\t\t\t\tget_next_sine_value(&data->data.sine);\n\t\t\t\tFEED_AUDIO_DATA(data->data.sine.value);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t*((float*) 0) = .0f; \/\/ 音频就是爆炸!\n\t\t\t\tFEED_AUDIO_DATA(.0f);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tFEED_AUDIO_DATA((float) (\n\t\t\t\t\t(double) rand() \/ (double) RAND_MAX * 2.0d - 1.0d\n\t\t\t\t));\n\t\t\t\tbreak;\n\t\t}\n\t\t#undef FEED_AUDIO_DATA\n\t\treturn paContinue;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 停止播放\n\t\/\/-------------------------------------------------------------------------\n\tvoid stop() {\n\t\tdata.type = 0;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放三角波\n\t\/\/ freq : 频率(Hz)\n\t\/\/-------------------------------------------------------------------------\n\tvoid play_triangle(float freq) {\n\t\tdata.data.triangle.value = -1.0f;\n\t\tdata.data.triangle.delta = 2.0f \/ ((float) data.sample_rate \/ freq \/ 2);\n\t\tdata.type = 1;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 计算下一个值使输出呈三角波形\n\t\/\/-------------------------------------------------------------------------\n\tvoid get_next_triangle_value(struct triangle_data* data) {\n\t\tdata->value += data->delta;\n\t\tif (data->value > 1.0f) {\n\t\t\tdata->value = 2.0f - data->value;\n\t\t\tdata->delta = -data->delta;\n\t\t} else if (data->value < -1.0f) {\n\t\t\tdata->value = -2.0f - data->value;\n\t\t\tdata->delta = -data->delta;\n\t\t}\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放正弦波\n\t\/\/ freq : 频率(Hz)\n\t\/\/-------------------------------------------------------------------------\n\tvoid play_sine(float freq) {\n\t\tdata.data.sine.index = .0f;\n\t\tdata.data.sine.index_delta =\n\t\t\tsine_table_size \/ ((float) data.sample_rate \/ 4 \/ freq);\n\t\tdata.data.sine.minus = false;\n\t\tdata.type = 2;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 向正弦表中填充数据\n\t\/\/-------------------------------------------------------------------------\n\tvoid populate_sine_table() {\n\t\tfloat k = 0.5f \/ (float) sine_table_size * Util::PIf;\n\t\tfor (size_t i = 0; i < sine_table_size; i++) sine_table[i] = sin(i * k);\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 计算正弦函数的下一值\n\t\/\/-------------------------------------------------------------------------\n\tvoid get_next_sine_value(struct sine_data* data) {\n\t\tdata->index += data->index_delta;\n\t\tif (data->index > (float) sine_table_size) {\n\t\t\tdata->index = sine_table_size * 2.0f - data->index;\n\t\t\tdata->index_delta = -data->index_delta;\n\t\t} else if (data->index < 0) {\n\t\t\tdata->index = -data->index;\n\t\t\tdata->index_delta = -data->index_delta;\n\t\t\tdata->minus = !data->minus;\n\t\t}\n\t\tdata->value = sine_table[(size_t) (int) data->index];\n\t\tif (data->minus) data->value = -data->value;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放声音\n\t\/\/-------------------------------------------------------------------------\n\tvoid play_sound(const char* filename) {\n\t\tcompact_active_sounds_array();\n\t\tlog(\"play sound %s\", filename);\n\t\tstruct active_sound* sound = new struct active_sound;\n\t\tsound->stream = NULL;\n\t\t\/\/ sound->file\n\t\tsound->file = fopen(filename, \"rb\");\n\t\tif (!sound->file) {\n\t\t\tdelete sound;\n\t\t\trb_raise(rb_eIOError, \"can't open this file: %s\", filename);\n\t\t}\n\t\t\/\/ sound->vf\n\t\tif (ov_open_callbacks(\n\t\t\tsound->file, &sound->vf,\n\t\t\tNULL, 0, OV_CALLBACKS_NOCLOSE\n\t\t) < 0) {\n\t\t\tdelete sound;\n\t\t\tfclose(sound->file);\n\t\t\trb_raise(rb_eRuntimeError, \"can't open ogg vorbis file: %s\", filename);\n\t\t}\n\t\t\/\/ sound->stream\n\t\tensure_no_error(Pa_OpenDefaultStream(\n\t\t\t&sound->stream, 0, 2, paFloat32, 44100,\n\t\t\t256, play_sound_callback, sound\n\t\t));\n\t\t\/\/ sound->*_head\n\t\tsound->play_head = 0;\n\t\tsound->load_head = 0;\n\t\t\/\/ etc\n\t\tsound->eof = false;\n\t\tactive_sounds[active_sound_count] = sound;\n\t\tactive_sound_count++;\n\t\tdecode_vorbis(sound);\n\t\t\/\/ sound->decode_thread\n\t\tsound->decode_thread = new thread(decode_vorbis_thread, sound);\n\t\tensure_no_error(Pa_StartStream(sound->stream));\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 扔掉active_sounds中已经播放完的条目\n\t\/\/-------------------------------------------------------------------------\n\tvoid compact_active_sounds_array() {\n\t\tsize_t size = ARRAY_SIZE(active_sounds);\n\t\tfor (size_t i = 0; i < size; i++) {\n\t\t\tif (!active_sounds[i]) continue;\n\t\t\tPaError active = Pa_IsStreamActive(active_sounds[i]->stream);\n\t\t\tensure_no_error(active);\n\t\t\tif (!active) {\n\t\t\t\tPa_CloseStream(active_sounds[i]->stream);\n\t\t\t\tov_clear(&active_sounds[i]->vf);\n\t\t\t\tfclose(active_sounds[i]->file);\n\t\t\t\tactive_sounds[i]->decode_thread->join();\n\t\t\t\tdelete active_sounds[i]->decode_thread;\n\t\t\t\tdelete active_sounds[i];\n\t\t\t\tactive_sounds[i] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 播放声音的回调函数\n\t\/\/-------------------------------------------------------------------------\n\tint play_sound_callback(\n\t\tconst void* input_buffer UNUSED,\n\t\tvoid* output_buffer,\n\t\tunsigned long frame_count,\n\t\tconst PaStreamCallbackTimeInfo* time_info UNUSED,\n\t\tPaStreamCallbackFlags status_flags UNUSED,\n\t\tvoid* user_data\n\t) {\n\t\tfloat* output = (float*) output_buffer;\n\t\tstruct active_sound* sound = (struct active_sound*) user_data;\n\t\twhile (frame_count > 0) {\n\t\t\tif (sound->play_head < sound->load_head) {\n\t\t\t\tsize_t index = sound->play_head % vf_buffer_size;\n\t\t\t\t*output++ = sound->vf_buffer[0][index];\n\t\t\t\t*output++ = sound->vf_buffer[1][index];\n\t\t\t\tsound->play_head++;\n\t\t\t} else {\n\t\t\t\tTWICE *output++ = .0f;\n\t\t\t}\n\t\t\tframe_count--;\n\t\t}\n\t\treturn sound->eof ? paComplete : paContinue;\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 解码文件来填active_sound结构中的缓冲区\n\t\/\/-------------------------------------------------------------------------\n\tvoid decode_vorbis(struct active_sound* sound) {\n\t\t#ifdef DEBUG\n\t\t\tFILE* f = fopen(\"rubbish.raw\", \"wb\");\n\t\t#endif\n\t\tsize_t t;\n\t\twhile ((t = sound->load_head - sound->play_head) < vf_buffer_size) {\n\t\t\t\/\/ After ov_read_float(), tmp_buffer will be changed.\n\t\t\tfloat** tmp_buffer;\n\t\t\tlong ret = ov_read_float(\n\t\t\t\t&sound->vf,\n\t\t\t\t&tmp_buffer,\n\t\t\t\tvf_buffer_size - t,\n\t\t\t\t&sound->bitstream\n\t\t\t);\n\t\t\tif (ret > 0) {\n\t\t\t\tfor (long i = 0; i < ret; i++) {\n\t\t\t\t\tsize_t j = (sound->load_head + i) % vf_buffer_size;\n\t\t\t\t\tsound->vf_buffer[0][j] = tmp_buffer[0][i];\n\t\t\t\t\tsound->vf_buffer[1][j] = tmp_buffer[1][i];\n\t\t\t\t\t#ifdef DEBUG\n\t\t\t\t\t\tfprintf(f, \"%ld %zu\\r\\n\", i, j);\n\t\t\t\t\t\tfwrite(&tmp_buffer[0][i], sizeof(float), 1, f);\n\t\t\t\t\t#endif\n\t\t\t\t}\n\t\t\t\tsound->load_head += ret;\n\t\t\t} else if (ret == 0) {\n\t\t\t\twhile (sound->load_head - sound->play_head < vf_buffer_size) {\n\t\t\t\t\tsize_t j = sound->load_head % vf_buffer_size;\n\t\t\t\t\tsound->vf_buffer[0][j] = .0f;\n\t\t\t\t\tsound->vf_buffer[1][j] = .0f;\n\t\t\t\t\tsound->load_head++;\n\t\t\t\t}\n\t\t\t\tsound->eof = true;\n\t\t\t\tbreak;\n\t\t\t} else if (ret == OV_EBADLINK) {\n\t\t\t\trb_raise(rb_eIOError, \"bad vorbis data (OV_EBADLINK)\");\n\t\t\t} else if (ret == OV_EINVAL) {\n\t\t\t\trb_raise(rb_eIOError, \"bad vorbis data (OV_EINVAL)\");\n\t\t\t}\n\t\t\t\/\/ We must not free(tmp_buffer). It isn't ours.\n\t\t}\n\t\t#ifdef DEBUG\n\t\t\tfclose(f);\n\t\t\texit(10);\n\t\t#endif\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 解码线程函数\n\t\/\/-------------------------------------------------------------------------\n\tvoid decode_vorbis_thread(struct active_sound* sound) {\n\t\twhile (!sound->eof) decode_vorbis(sound);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ RUN: %srcroot\/test\/runtime\/run-scheduler-test.py %s -gxx \"%gxx\" -llvmgcc \"%llvmgcc\" -projbindir \"%projbindir\" -ternruntime \"%ternruntime\" -ternbcruntime \"%ternbcruntime\" \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define N 100\n\npthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;\n\nstruct timespec oldts;\nstruct timeval oldtv;\ntime_t oldtt;\n\n\/\/ require mu hold before calling this function\nvoid check_time(bool init = false)\n{ \n struct timespec ts;\n struct timeval tv;\n time_t tt;\n gettimeofday(&tv, NULL);\n clock_gettime(CLOCK_REALTIME, &ts);\n time(&tt);\n \n if (!init)\n {\n if (tv.tv_sec < oldtv.tv_sec || \n tv.tv_sec == oldtv.tv_sec && tv.tv_usec < oldtv.tv_usec)\n assert(0 && \"gettimeofday is not monotonic\");\n \n if (ts.tv_sec < oldts.tv_sec || \n ts.tv_sec == oldts.tv_sec && ts.tv_nsec < oldts.tv_nsec)\n assert(0 && \"clock_gettime is not monotonic\");\n \n if (tt < oldtt)\n assert(0 && \"time is not monotonic\");\n }\n\n oldts = ts;\n oldtv = tv;\n oldtt = tt;\n}\n\nvoid* thread_func(void*) {\n for(unsigned i=0;i<100;++i)\n sched_yield();\n\n pthread_mutex_lock(&mu);\n\n check_time();\n\n pthread_mutex_unlock(&mu);\n}\n\n\nint main(int argc, char *argv[], char *env[]) {\n int ret;\n pthread_t th[N];\n\n check_time(true);\n for (int i = 0; i < N; ++i)\n pthread_create(&th[i], NULL, thread_func, NULL);\n\n for (int i = 0; i < N; ++i)\n pthread_join(th[i], NULL);\n\n printf(\"test done\\n\");\n\n return 0;\n}\n\n\/\/ CHECK indicates expected output checked by FileCheck; auto-generated by appending -gen to the RUN command above.\n\/\/ CHECK: test done\nadd sleep:w into sleep-gettime-test.cpp\/\/ RUN: %srcroot\/test\/runtime\/run-scheduler-test.py %s -gxx \"%gxx\" -llvmgcc \"%llvmgcc\" -projbindir \"%projbindir\" -ternruntime \"%ternruntime\" -ternbcruntime \"%ternbcruntime\" \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define N 100\n\npthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;\n\nstruct timespec oldts;\nstruct timeval oldtv;\ntime_t oldtt;\n\n\/\/ require mu hold before calling this function\nvoid check_time(bool init = false)\n{ \n struct timespec ts;\n struct timeval tv;\n time_t tt;\n gettimeofday(&tv, NULL);\n clock_gettime(CLOCK_REALTIME, &ts);\n time(&tt);\n \n if (!init)\n {\n if (tv.tv_sec < oldtv.tv_sec || \n tv.tv_sec == oldtv.tv_sec && tv.tv_usec < oldtv.tv_usec)\n assert(0 && \"gettimeofday is not monotonic\");\n \n if (ts.tv_sec < oldts.tv_sec || \n ts.tv_sec == oldts.tv_sec && ts.tv_nsec < oldts.tv_nsec)\n assert(0 && \"clock_gettime is not monotonic\");\n \n if (tt < oldtt)\n assert(0 && \"time is not monotonic\");\n }\n\n oldts = ts;\n oldtv = tv;\n oldtt = tt;\n}\n\nvoid* thread_func(void*) {\n for(unsigned i=0;i<100;++i)\n sched_yield();\n\n pthread_mutex_lock(&mu);\n\n check_time();\n usleep(10);\n\n pthread_mutex_unlock(&mu);\n}\n\n\nint main(int argc, char *argv[], char *env[]) {\n int ret;\n pthread_t th[N];\n\n check_time(true);\n for (int i = 0; i < N; ++i)\n pthread_create(&th[i], NULL, thread_func, NULL);\n\n for (int i = 0; i < N; ++i)\n pthread_join(th[i], NULL);\n\n printf(\"test done\\n\");\n\n return 0;\n}\n\n\/\/ CHECK indicates expected output checked by FileCheck; auto-generated by appending -gen to the RUN command above.\n\/\/ CHECK: test done\n<|endoftext|>"} {"text":"\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrDrawState.h\"\n\n#include \"GrBlend.h\"\n#include \"GrOptDrawState.h\"\n#include \"GrPaint.h\"\n#include \"GrProcOptInfo.h\"\n#include \"GrXferProcessor.h\"\n#include \"effects\/GrPorterDuffXferProcessor.h\"\n\nbool GrDrawState::isEqual(const GrDrawState& that) const {\n if (this->getRenderTarget() != that.getRenderTarget() ||\n this->fColorStages.count() != that.fColorStages.count() ||\n this->fCoverageStages.count() != that.fCoverageStages.count() ||\n !this->fViewMatrix.cheapEqualTo(that.fViewMatrix) ||\n this->fFlagBits != that.fFlagBits ||\n this->fStencilSettings != that.fStencilSettings ||\n this->fDrawFace != that.fDrawFace) {\n return false;\n }\n\n bool explicitLocalCoords = this->hasLocalCoordAttribute();\n if (this->hasGeometryProcessor()) {\n if (!that.hasGeometryProcessor()) {\n return false;\n } else if (!this->getGeometryProcessor()->isEqual(*that.getGeometryProcessor())) {\n return false;\n }\n } else if (that.hasGeometryProcessor()) {\n return false;\n }\n\n if (!this->getXPFactory()->isEqual(*that.getXPFactory())) {\n return false;\n }\n\n for (int i = 0; i < this->numColorStages(); i++) {\n if (!GrFragmentStage::AreCompatible(this->getColorStage(i), that.getColorStage(i),\n explicitLocalCoords)) {\n return false;\n }\n }\n for (int i = 0; i < this->numCoverageStages(); i++) {\n if (!GrFragmentStage::AreCompatible(this->getCoverageStage(i), that.getCoverageStage(i),\n explicitLocalCoords)) {\n return false;\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/s\n\nGrDrawState::GrDrawState(const GrDrawState& state, const SkMatrix& preConcatMatrix) {\n SkDEBUGCODE(fBlockEffectRemovalCnt = 0;)\n *this = state;\n if (!preConcatMatrix.isIdentity()) {\n for (int i = 0; i < this->numColorStages(); ++i) {\n fColorStages[i].localCoordChange(preConcatMatrix);\n }\n for (int i = 0; i < this->numCoverageStages(); ++i) {\n fCoverageStages[i].localCoordChange(preConcatMatrix);\n }\n }\n}\n\nGrDrawState& GrDrawState::operator=(const GrDrawState& that) {\n fRenderTarget.reset(SkSafeRef(that.fRenderTarget.get()));\n fViewMatrix = that.fViewMatrix;\n fFlagBits = that.fFlagBits;\n fStencilSettings = that.fStencilSettings;\n fDrawFace = that.fDrawFace;\n fGeometryProcessor.reset(SkSafeRef(that.fGeometryProcessor.get()));\n fXPFactory.reset(SkRef(that.getXPFactory()));\n fColorStages = that.fColorStages;\n fCoverageStages = that.fCoverageStages;\n\n fHints = that.fHints;\n\n fColorProcInfoValid = that.fColorProcInfoValid;\n fCoverageProcInfoValid = that.fCoverageProcInfoValid;\n if (fColorProcInfoValid) {\n fColorProcInfo = that.fColorProcInfo;\n }\n if (fCoverageProcInfoValid) {\n fCoverageProcInfo = that.fCoverageProcInfo;\n }\n return *this;\n}\n\nvoid GrDrawState::onReset(const SkMatrix* initialViewMatrix) {\n SkASSERT(0 == fBlockEffectRemovalCnt || 0 == this->numTotalStages());\n fRenderTarget.reset(NULL);\n\n fGeometryProcessor.reset(NULL);\n fXPFactory.reset(GrPorterDuffXPFactory::Create(SkXfermode::kSrc_Mode));\n fColorStages.reset();\n fCoverageStages.reset();\n\n if (NULL == initialViewMatrix) {\n fViewMatrix.reset();\n } else {\n fViewMatrix = *initialViewMatrix;\n }\n fFlagBits = 0x0;\n fStencilSettings.setDisabled();\n fDrawFace = kBoth_DrawFace;\n\n fHints = 0;\n\n fColorProcInfoValid = false;\n fCoverageProcInfoValid = false;\n}\n\nbool GrDrawState::setIdentityViewMatrix() {\n if (this->numFragmentStages()) {\n SkMatrix invVM;\n if (!fViewMatrix.invert(&invVM)) {\n \/\/ sad trombone sound\n return false;\n }\n for (int s = 0; s < this->numColorStages(); ++s) {\n fColorStages[s].localCoordChange(invVM);\n }\n for (int s = 0; s < this->numCoverageStages(); ++s) {\n fCoverageStages[s].localCoordChange(invVM);\n }\n }\n fViewMatrix.reset();\n return true;\n}\n\nvoid GrDrawState::setFromPaint(const GrPaint& paint, const SkMatrix& vm, GrRenderTarget* rt) {\n SkASSERT(0 == fBlockEffectRemovalCnt || 0 == this->numTotalStages());\n\n fGeometryProcessor.reset(NULL);\n fColorStages.reset();\n fCoverageStages.reset();\n\n for (int i = 0; i < paint.numColorStages(); ++i) {\n fColorStages.push_back(paint.getColorStage(i));\n }\n\n for (int i = 0; i < paint.numCoverageStages(); ++i) {\n fCoverageStages.push_back(paint.getCoverageStage(i));\n }\n\n fXPFactory.reset(SkRef(paint.getXPFactory()));\n\n this->setRenderTarget(rt);\n\n fViewMatrix = vm;\n\n \/\/ These have no equivalent in GrPaint, set them to defaults\n fDrawFace = kBoth_DrawFace;\n fStencilSettings.setDisabled();\n fFlagBits = 0;\n fHints = 0;\n\n \/\/ Enable the clip bit\n this->enableState(GrDrawState::kClip_StateBit);\n\n this->setState(GrDrawState::kDither_StateBit, paint.isDither());\n this->setState(GrDrawState::kHWAntialias_StateBit, paint.isAntiAlias());\n\n fColorProcInfoValid = false;\n fCoverageProcInfoValid = false;\n\n fColorCache = GrColor_ILLEGAL;\n fCoverageCache = GrColor_ILLEGAL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool GrDrawState::canUseFracCoveragePrimProc(GrColor color, const GrDrawTargetCaps& caps) const {\n if (caps.dualSourceBlendingSupport()) {\n return true;\n }\n\n this->calcColorInvariantOutput(color);\n\n \/\/ The coverage isn't actually white, its unknown, but this will produce the same effect\n \/\/ TODO we want to cache the result of this call, but we can probably clean up the interface\n \/\/ so we don't have to pass in a seemingly known coverage\n this->calcCoverageInvariantOutput(GrColor_WHITE);\n return fXPFactory->canApplyCoverage(fColorProcInfo, fCoverageProcInfo,\n this->isCoverageDrawing(), this->isColorWriteDisabled());\n}\n\nbool GrDrawState::hasSolidCoverage(GrColor coverage) const {\n \/\/ If we're drawing coverage directly then coverage is effectively treated as color.\n if (this->isCoverageDrawing()) {\n return true;\n }\n\n if (this->numCoverageStages() > 0) {\n return false;\n }\n\n this->calcCoverageInvariantOutput(coverage);\n return fCoverageProcInfo.isSolidWhite();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/s\n\nbool GrDrawState::willEffectReadDstColor(GrColor color, GrColor coverage) const {\n this->calcColorInvariantOutput(color);\n this->calcCoverageInvariantOutput(coverage);\n \/\/ TODO: Remove need to create the XP here.\n \/\/ Also once all custom blends are turned into XPs we can remove the need\n \/\/ to check other stages since only xp's will be able to read dst\n SkAutoTUnref xferProcessor(fXPFactory->createXferProcessor(fColorProcInfo,\n fCoverageProcInfo));\n if (xferProcessor && xferProcessor->willReadDstColor()) {\n return true;\n }\n\n if (!this->isColorWriteDisabled()) {\n if (fColorProcInfo.readsDst()) {\n return true;\n }\n }\n return fCoverageProcInfo.readsDst();\n}\n\nvoid GrDrawState::AutoRestoreEffects::set(GrDrawState* ds) {\n if (fDrawState) {\n \/\/ See the big comment on the class definition about GPs.\n if (SK_InvalidUniqueID == fOriginalGPID) {\n fDrawState->fGeometryProcessor.reset(NULL);\n } else {\n SkASSERT(fDrawState->getGeometryProcessor()->getUniqueID() ==\n fOriginalGPID);\n fOriginalGPID = SK_InvalidUniqueID;\n }\n\n int m = fDrawState->numColorStages() - fColorEffectCnt;\n SkASSERT(m >= 0);\n fDrawState->fColorStages.pop_back_n(m);\n\n int n = fDrawState->numCoverageStages() - fCoverageEffectCnt;\n SkASSERT(n >= 0);\n fDrawState->fCoverageStages.pop_back_n(n);\n if (m + n > 0) {\n fDrawState->fColorProcInfoValid = false;\n fDrawState->fCoverageProcInfoValid = false;\n }\n SkDEBUGCODE(--fDrawState->fBlockEffectRemovalCnt;)\n }\n fDrawState = ds;\n if (NULL != ds) {\n SkASSERT(SK_InvalidUniqueID == fOriginalGPID);\n if (NULL != ds->getGeometryProcessor()) {\n fOriginalGPID = ds->getGeometryProcessor()->getUniqueID();\n }\n fColorEffectCnt = ds->numColorStages();\n fCoverageEffectCnt = ds->numCoverageStages();\n SkDEBUGCODE(++ds->fBlockEffectRemovalCnt;)\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Some blend modes allow folding a fractional coverage value into the color's alpha channel, while\n\/\/ others will blend incorrectly.\nbool GrDrawState::canTweakAlphaForCoverage() const {\n return fXPFactory->canTweakAlphaForCoverage(this->isCoverageDrawing());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid GrDrawState::AutoViewMatrixRestore::restore() {\n if (fDrawState) {\n SkDEBUGCODE(--fDrawState->fBlockEffectRemovalCnt;)\n fDrawState->fViewMatrix = fViewMatrix;\n SkASSERT(fDrawState->numColorStages() >= fNumColorStages);\n int numCoverageStages = fSavedCoordChanges.count() - fNumColorStages;\n SkASSERT(fDrawState->numCoverageStages() >= numCoverageStages);\n\n int i = 0;\n for (int s = 0; s < fNumColorStages; ++s, ++i) {\n fDrawState->fColorStages[s].restoreCoordChange(fSavedCoordChanges[i]);\n }\n for (int s = 0; s < numCoverageStages; ++s, ++i) {\n fDrawState->fCoverageStages[s].restoreCoordChange(fSavedCoordChanges[i]);\n }\n fDrawState = NULL;\n }\n}\n\nvoid GrDrawState::AutoViewMatrixRestore::set(GrDrawState* drawState,\n const SkMatrix& preconcatMatrix) {\n this->restore();\n\n SkASSERT(NULL == fDrawState);\n if (NULL == drawState || preconcatMatrix.isIdentity()) {\n return;\n }\n fDrawState = drawState;\n\n fViewMatrix = drawState->getViewMatrix();\n drawState->fViewMatrix.preConcat(preconcatMatrix);\n\n this->doEffectCoordChanges(preconcatMatrix);\n SkDEBUGCODE(++fDrawState->fBlockEffectRemovalCnt;)\n}\n\nbool GrDrawState::AutoViewMatrixRestore::setIdentity(GrDrawState* drawState) {\n this->restore();\n\n if (NULL == drawState) {\n return false;\n }\n\n if (drawState->getViewMatrix().isIdentity()) {\n return true;\n }\n\n fViewMatrix = drawState->getViewMatrix();\n if (0 == drawState->numFragmentStages()) {\n drawState->fViewMatrix.reset();\n fDrawState = drawState;\n fNumColorStages = 0;\n fSavedCoordChanges.reset(0);\n SkDEBUGCODE(++fDrawState->fBlockEffectRemovalCnt;)\n return true;\n } else {\n SkMatrix inv;\n if (!fViewMatrix.invert(&inv)) {\n return false;\n }\n drawState->fViewMatrix.reset();\n fDrawState = drawState;\n this->doEffectCoordChanges(inv);\n SkDEBUGCODE(++fDrawState->fBlockEffectRemovalCnt;)\n return true;\n }\n}\n\nvoid GrDrawState::AutoViewMatrixRestore::doEffectCoordChanges(const SkMatrix& coordChangeMatrix) {\n fSavedCoordChanges.reset(fDrawState->numFragmentStages());\n int i = 0;\n\n fNumColorStages = fDrawState->numColorStages();\n for (int s = 0; s < fNumColorStages; ++s, ++i) {\n fDrawState->getColorStage(s).saveCoordChange(&fSavedCoordChanges[i]);\n fDrawState->fColorStages[s].localCoordChange(coordChangeMatrix);\n }\n\n int numCoverageStages = fDrawState->numCoverageStages();\n for (int s = 0; s < numCoverageStages; ++s, ++i) {\n fDrawState->getCoverageStage(s).saveCoordChange(&fSavedCoordChanges[i]);\n fDrawState->fCoverageStages[s].localCoordChange(coordChangeMatrix);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrDrawState::~GrDrawState() {\n SkASSERT(0 == fBlockEffectRemovalCnt);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool GrDrawState::srcAlphaWillBeOne(GrColor color, GrColor coverage) const {\n this->calcColorInvariantOutput(color);\n if (this->isCoverageDrawing()) {\n this->calcCoverageInvariantOutput(coverage);\n return (fColorProcInfo.isOpaque() && fCoverageProcInfo.isOpaque());\n }\n return fColorProcInfo.isOpaque();\n}\n\nbool GrDrawState::willBlendWithDst(GrColor color, GrColor coverage) const {\n this->calcColorInvariantOutput(color);\n this->calcCoverageInvariantOutput(coverage);\n return fXPFactory->willBlendWithDst(fColorProcInfo, fCoverageProcInfo,\n this->isCoverageDrawing(), this->isColorWriteDisabled());\n}\n\nvoid GrDrawState::calcColorInvariantOutput(GrColor color) const {\n if (!fColorProcInfoValid || color != fColorCache) {\n GrColorComponentFlags flags;\n if (this->hasColorVertexAttribute()) {\n if (fHints & kVertexColorsAreOpaque_Hint) {\n flags = kA_GrColorComponentFlag;\n color = 0xFF << GrColor_SHIFT_A;\n } else {\n flags = static_cast(0);\n color = 0;\n }\n } else {\n flags = kRGBA_GrColorComponentFlags;\n }\n fColorProcInfo.calcWithInitialValues(fColorStages.begin(), this->numColorStages(),\n color, flags, false);\n fColorProcInfoValid = true;\n fColorCache = color;\n }\n}\n\nvoid GrDrawState::calcCoverageInvariantOutput(GrColor coverage) const {\n if (!fCoverageProcInfoValid || coverage != fCoverageCache) {\n GrColorComponentFlags flags;\n \/\/ Check if per-vertex or constant color may have partial alpha\n if (this->hasCoverageVertexAttribute()) {\n flags = static_cast(0);\n coverage = 0;\n } else {\n flags = kRGBA_GrColorComponentFlags;\n }\n fCoverageProcInfo.calcWithInitialValues(fCoverageStages.begin(), this->numCoverageStages(),\n coverage, flags, true, fGeometryProcessor.get());\n fCoverageProcInfoValid = true;\n fCoverageCache = coverage;\n }\n}\nfix for valgrind uninit variables\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrDrawState.h\"\n\n#include \"GrBlend.h\"\n#include \"GrOptDrawState.h\"\n#include \"GrPaint.h\"\n#include \"GrProcOptInfo.h\"\n#include \"GrXferProcessor.h\"\n#include \"effects\/GrPorterDuffXferProcessor.h\"\n\nbool GrDrawState::isEqual(const GrDrawState& that) const {\n if (this->getRenderTarget() != that.getRenderTarget() ||\n this->fColorStages.count() != that.fColorStages.count() ||\n this->fCoverageStages.count() != that.fCoverageStages.count() ||\n !this->fViewMatrix.cheapEqualTo(that.fViewMatrix) ||\n this->fFlagBits != that.fFlagBits ||\n this->fStencilSettings != that.fStencilSettings ||\n this->fDrawFace != that.fDrawFace) {\n return false;\n }\n\n bool explicitLocalCoords = this->hasLocalCoordAttribute();\n if (this->hasGeometryProcessor()) {\n if (!that.hasGeometryProcessor()) {\n return false;\n } else if (!this->getGeometryProcessor()->isEqual(*that.getGeometryProcessor())) {\n return false;\n }\n } else if (that.hasGeometryProcessor()) {\n return false;\n }\n\n if (!this->getXPFactory()->isEqual(*that.getXPFactory())) {\n return false;\n }\n\n for (int i = 0; i < this->numColorStages(); i++) {\n if (!GrFragmentStage::AreCompatible(this->getColorStage(i), that.getColorStage(i),\n explicitLocalCoords)) {\n return false;\n }\n }\n for (int i = 0; i < this->numCoverageStages(); i++) {\n if (!GrFragmentStage::AreCompatible(this->getCoverageStage(i), that.getCoverageStage(i),\n explicitLocalCoords)) {\n return false;\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/s\n\nGrDrawState::GrDrawState(const GrDrawState& state, const SkMatrix& preConcatMatrix) {\n SkDEBUGCODE(fBlockEffectRemovalCnt = 0;)\n *this = state;\n if (!preConcatMatrix.isIdentity()) {\n for (int i = 0; i < this->numColorStages(); ++i) {\n fColorStages[i].localCoordChange(preConcatMatrix);\n }\n for (int i = 0; i < this->numCoverageStages(); ++i) {\n fCoverageStages[i].localCoordChange(preConcatMatrix);\n }\n }\n}\n\nGrDrawState& GrDrawState::operator=(const GrDrawState& that) {\n fRenderTarget.reset(SkSafeRef(that.fRenderTarget.get()));\n fViewMatrix = that.fViewMatrix;\n fFlagBits = that.fFlagBits;\n fStencilSettings = that.fStencilSettings;\n fDrawFace = that.fDrawFace;\n fGeometryProcessor.reset(SkSafeRef(that.fGeometryProcessor.get()));\n fXPFactory.reset(SkRef(that.getXPFactory()));\n fColorStages = that.fColorStages;\n fCoverageStages = that.fCoverageStages;\n\n fHints = that.fHints;\n\n fColorProcInfoValid = that.fColorProcInfoValid;\n fCoverageProcInfoValid = that.fCoverageProcInfoValid;\n if (fColorProcInfoValid) {\n fColorProcInfo = that.fColorProcInfo;\n }\n if (fCoverageProcInfoValid) {\n fCoverageProcInfo = that.fCoverageProcInfo;\n }\n return *this;\n}\n\nvoid GrDrawState::onReset(const SkMatrix* initialViewMatrix) {\n SkASSERT(0 == fBlockEffectRemovalCnt || 0 == this->numTotalStages());\n fRenderTarget.reset(NULL);\n\n fGeometryProcessor.reset(NULL);\n fXPFactory.reset(GrPorterDuffXPFactory::Create(SkXfermode::kSrc_Mode));\n fColorStages.reset();\n fCoverageStages.reset();\n\n if (NULL == initialViewMatrix) {\n fViewMatrix.reset();\n } else {\n fViewMatrix = *initialViewMatrix;\n }\n fFlagBits = 0x0;\n fStencilSettings.setDisabled();\n fDrawFace = kBoth_DrawFace;\n\n fHints = 0;\n\n fColorProcInfoValid = false;\n fCoverageProcInfoValid = false;\n\n fColorCache = GrColor_ILLEGAL;\n fCoverageCache = GrColor_ILLEGAL;\n}\n\nbool GrDrawState::setIdentityViewMatrix() {\n if (this->numFragmentStages()) {\n SkMatrix invVM;\n if (!fViewMatrix.invert(&invVM)) {\n \/\/ sad trombone sound\n return false;\n }\n for (int s = 0; s < this->numColorStages(); ++s) {\n fColorStages[s].localCoordChange(invVM);\n }\n for (int s = 0; s < this->numCoverageStages(); ++s) {\n fCoverageStages[s].localCoordChange(invVM);\n }\n }\n fViewMatrix.reset();\n return true;\n}\n\nvoid GrDrawState::setFromPaint(const GrPaint& paint, const SkMatrix& vm, GrRenderTarget* rt) {\n SkASSERT(0 == fBlockEffectRemovalCnt || 0 == this->numTotalStages());\n\n fGeometryProcessor.reset(NULL);\n fColorStages.reset();\n fCoverageStages.reset();\n\n for (int i = 0; i < paint.numColorStages(); ++i) {\n fColorStages.push_back(paint.getColorStage(i));\n }\n\n for (int i = 0; i < paint.numCoverageStages(); ++i) {\n fCoverageStages.push_back(paint.getCoverageStage(i));\n }\n\n fXPFactory.reset(SkRef(paint.getXPFactory()));\n\n this->setRenderTarget(rt);\n\n fViewMatrix = vm;\n\n \/\/ These have no equivalent in GrPaint, set them to defaults\n fDrawFace = kBoth_DrawFace;\n fStencilSettings.setDisabled();\n fFlagBits = 0;\n fHints = 0;\n\n \/\/ Enable the clip bit\n this->enableState(GrDrawState::kClip_StateBit);\n\n this->setState(GrDrawState::kDither_StateBit, paint.isDither());\n this->setState(GrDrawState::kHWAntialias_StateBit, paint.isAntiAlias());\n\n fColorProcInfoValid = false;\n fCoverageProcInfoValid = false;\n\n fColorCache = GrColor_ILLEGAL;\n fCoverageCache = GrColor_ILLEGAL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool GrDrawState::canUseFracCoveragePrimProc(GrColor color, const GrDrawTargetCaps& caps) const {\n if (caps.dualSourceBlendingSupport()) {\n return true;\n }\n\n this->calcColorInvariantOutput(color);\n\n \/\/ The coverage isn't actually white, its unknown, but this will produce the same effect\n \/\/ TODO we want to cache the result of this call, but we can probably clean up the interface\n \/\/ so we don't have to pass in a seemingly known coverage\n this->calcCoverageInvariantOutput(GrColor_WHITE);\n return fXPFactory->canApplyCoverage(fColorProcInfo, fCoverageProcInfo,\n this->isCoverageDrawing(), this->isColorWriteDisabled());\n}\n\nbool GrDrawState::hasSolidCoverage(GrColor coverage) const {\n \/\/ If we're drawing coverage directly then coverage is effectively treated as color.\n if (this->isCoverageDrawing()) {\n return true;\n }\n\n if (this->numCoverageStages() > 0) {\n return false;\n }\n\n this->calcCoverageInvariantOutput(coverage);\n return fCoverageProcInfo.isSolidWhite();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/s\n\nbool GrDrawState::willEffectReadDstColor(GrColor color, GrColor coverage) const {\n this->calcColorInvariantOutput(color);\n this->calcCoverageInvariantOutput(coverage);\n \/\/ TODO: Remove need to create the XP here.\n \/\/ Also once all custom blends are turned into XPs we can remove the need\n \/\/ to check other stages since only xp's will be able to read dst\n SkAutoTUnref xferProcessor(fXPFactory->createXferProcessor(fColorProcInfo,\n fCoverageProcInfo));\n if (xferProcessor && xferProcessor->willReadDstColor()) {\n return true;\n }\n\n if (!this->isColorWriteDisabled()) {\n if (fColorProcInfo.readsDst()) {\n return true;\n }\n }\n return fCoverageProcInfo.readsDst();\n}\n\nvoid GrDrawState::AutoRestoreEffects::set(GrDrawState* ds) {\n if (fDrawState) {\n \/\/ See the big comment on the class definition about GPs.\n if (SK_InvalidUniqueID == fOriginalGPID) {\n fDrawState->fGeometryProcessor.reset(NULL);\n } else {\n SkASSERT(fDrawState->getGeometryProcessor()->getUniqueID() ==\n fOriginalGPID);\n fOriginalGPID = SK_InvalidUniqueID;\n }\n\n int m = fDrawState->numColorStages() - fColorEffectCnt;\n SkASSERT(m >= 0);\n fDrawState->fColorStages.pop_back_n(m);\n\n int n = fDrawState->numCoverageStages() - fCoverageEffectCnt;\n SkASSERT(n >= 0);\n fDrawState->fCoverageStages.pop_back_n(n);\n if (m + n > 0) {\n fDrawState->fColorProcInfoValid = false;\n fDrawState->fCoverageProcInfoValid = false;\n }\n SkDEBUGCODE(--fDrawState->fBlockEffectRemovalCnt;)\n }\n fDrawState = ds;\n if (NULL != ds) {\n SkASSERT(SK_InvalidUniqueID == fOriginalGPID);\n if (NULL != ds->getGeometryProcessor()) {\n fOriginalGPID = ds->getGeometryProcessor()->getUniqueID();\n }\n fColorEffectCnt = ds->numColorStages();\n fCoverageEffectCnt = ds->numCoverageStages();\n SkDEBUGCODE(++ds->fBlockEffectRemovalCnt;)\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Some blend modes allow folding a fractional coverage value into the color's alpha channel, while\n\/\/ others will blend incorrectly.\nbool GrDrawState::canTweakAlphaForCoverage() const {\n return fXPFactory->canTweakAlphaForCoverage(this->isCoverageDrawing());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid GrDrawState::AutoViewMatrixRestore::restore() {\n if (fDrawState) {\n SkDEBUGCODE(--fDrawState->fBlockEffectRemovalCnt;)\n fDrawState->fViewMatrix = fViewMatrix;\n SkASSERT(fDrawState->numColorStages() >= fNumColorStages);\n int numCoverageStages = fSavedCoordChanges.count() - fNumColorStages;\n SkASSERT(fDrawState->numCoverageStages() >= numCoverageStages);\n\n int i = 0;\n for (int s = 0; s < fNumColorStages; ++s, ++i) {\n fDrawState->fColorStages[s].restoreCoordChange(fSavedCoordChanges[i]);\n }\n for (int s = 0; s < numCoverageStages; ++s, ++i) {\n fDrawState->fCoverageStages[s].restoreCoordChange(fSavedCoordChanges[i]);\n }\n fDrawState = NULL;\n }\n}\n\nvoid GrDrawState::AutoViewMatrixRestore::set(GrDrawState* drawState,\n const SkMatrix& preconcatMatrix) {\n this->restore();\n\n SkASSERT(NULL == fDrawState);\n if (NULL == drawState || preconcatMatrix.isIdentity()) {\n return;\n }\n fDrawState = drawState;\n\n fViewMatrix = drawState->getViewMatrix();\n drawState->fViewMatrix.preConcat(preconcatMatrix);\n\n this->doEffectCoordChanges(preconcatMatrix);\n SkDEBUGCODE(++fDrawState->fBlockEffectRemovalCnt;)\n}\n\nbool GrDrawState::AutoViewMatrixRestore::setIdentity(GrDrawState* drawState) {\n this->restore();\n\n if (NULL == drawState) {\n return false;\n }\n\n if (drawState->getViewMatrix().isIdentity()) {\n return true;\n }\n\n fViewMatrix = drawState->getViewMatrix();\n if (0 == drawState->numFragmentStages()) {\n drawState->fViewMatrix.reset();\n fDrawState = drawState;\n fNumColorStages = 0;\n fSavedCoordChanges.reset(0);\n SkDEBUGCODE(++fDrawState->fBlockEffectRemovalCnt;)\n return true;\n } else {\n SkMatrix inv;\n if (!fViewMatrix.invert(&inv)) {\n return false;\n }\n drawState->fViewMatrix.reset();\n fDrawState = drawState;\n this->doEffectCoordChanges(inv);\n SkDEBUGCODE(++fDrawState->fBlockEffectRemovalCnt;)\n return true;\n }\n}\n\nvoid GrDrawState::AutoViewMatrixRestore::doEffectCoordChanges(const SkMatrix& coordChangeMatrix) {\n fSavedCoordChanges.reset(fDrawState->numFragmentStages());\n int i = 0;\n\n fNumColorStages = fDrawState->numColorStages();\n for (int s = 0; s < fNumColorStages; ++s, ++i) {\n fDrawState->getColorStage(s).saveCoordChange(&fSavedCoordChanges[i]);\n fDrawState->fColorStages[s].localCoordChange(coordChangeMatrix);\n }\n\n int numCoverageStages = fDrawState->numCoverageStages();\n for (int s = 0; s < numCoverageStages; ++s, ++i) {\n fDrawState->getCoverageStage(s).saveCoordChange(&fSavedCoordChanges[i]);\n fDrawState->fCoverageStages[s].localCoordChange(coordChangeMatrix);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrDrawState::~GrDrawState() {\n SkASSERT(0 == fBlockEffectRemovalCnt);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool GrDrawState::srcAlphaWillBeOne(GrColor color, GrColor coverage) const {\n this->calcColorInvariantOutput(color);\n if (this->isCoverageDrawing()) {\n this->calcCoverageInvariantOutput(coverage);\n return (fColorProcInfo.isOpaque() && fCoverageProcInfo.isOpaque());\n }\n return fColorProcInfo.isOpaque();\n}\n\nbool GrDrawState::willBlendWithDst(GrColor color, GrColor coverage) const {\n this->calcColorInvariantOutput(color);\n this->calcCoverageInvariantOutput(coverage);\n return fXPFactory->willBlendWithDst(fColorProcInfo, fCoverageProcInfo,\n this->isCoverageDrawing(), this->isColorWriteDisabled());\n}\n\nvoid GrDrawState::calcColorInvariantOutput(GrColor color) const {\n if (!fColorProcInfoValid || color != fColorCache) {\n GrColorComponentFlags flags;\n if (this->hasColorVertexAttribute()) {\n if (fHints & kVertexColorsAreOpaque_Hint) {\n flags = kA_GrColorComponentFlag;\n color = 0xFF << GrColor_SHIFT_A;\n } else {\n flags = static_cast(0);\n color = 0;\n }\n } else {\n flags = kRGBA_GrColorComponentFlags;\n }\n fColorProcInfo.calcWithInitialValues(fColorStages.begin(), this->numColorStages(),\n color, flags, false);\n fColorProcInfoValid = true;\n fColorCache = color;\n }\n}\n\nvoid GrDrawState::calcCoverageInvariantOutput(GrColor coverage) const {\n if (!fCoverageProcInfoValid || coverage != fCoverageCache) {\n GrColorComponentFlags flags;\n \/\/ Check if per-vertex or constant color may have partial alpha\n if (this->hasCoverageVertexAttribute()) {\n flags = static_cast(0);\n coverage = 0;\n } else {\n flags = kRGBA_GrColorComponentFlags;\n }\n fCoverageProcInfo.calcWithInitialValues(fCoverageStages.begin(), this->numCoverageStages(),\n coverage, flags, true, fGeometryProcessor.get());\n fCoverageProcInfoValid = true;\n fCoverageCache = coverage;\n }\n}\n<|endoftext|>"} {"text":"\n *\n * This source file is subject to the MIT license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace hhpack\\performance\\reporter;\n\nuse hhpack\\performance\\Writer;\nuse hhpack\\performance\\WatchedResult;\nuse hhpack\\performance\\ResultReporter;\nuse hhpack\\performance\\result\\BenchmarkedResult;\nuse hhpack\\performance\\writer\\StdoutWriter;\n\nfinal class TextReporter implements ResultReporter\n{\n\n private Vector> $results;\n private Map $paddingLength;\n\n public function __construct(\n private Writer $writer = new StdoutWriter()\n )\n {\n $this->results = Vector {};\n $this->paddingLength = Map {};\n }\n\n public function onStop(BenchmarkedResult $result) : void\n {\n $watchedResult = $result->map(($value) ==> (string) $value);\n\n foreach ($watchedResult as $key => $value) {\n $length = strlen((string) $value);\n $paddingLength = $this->paddingLength->get($key);\n $paddingLength = ($paddingLength === null) ? 0 : $paddingLength;\n $this->paddingLength->set($key, ($length > $paddingLength) ? $length : $paddingLength);\n }\n\n $this->results->add($watchedResult);\n }\n\n public function onFinish() : void\n {\n $this->writeHeader();\n $this->writeBody();\n $this->writeFooter();\n }\n\n <<__Memoize>>\n private function header() : string\n {\n $columns = $this->paddingLength->mapWithKey(($key, $value) ==> {\n return str_pad($key, $value, ' ', STR_PAD_RIGHT);\n })->values()->toArray();\n\n return '| ' . implode(' | ', $columns) . ' |';\n }\n\n private function writeHeader() : void\n {\n $headerLength = strlen($this->header());\n $headerSeparator = str_pad('', $headerLength, '-');\n\n $this->writer->writeln($headerSeparator);\n $this->writer->writeln($this->header());\n $this->writer->writeln($headerSeparator);\n }\n\n private function writeBody() : void\n {\n foreach ($this->results as $result) {\n $columns = $result->mapWithKey(($key, $value) ==> {\n $max = $this->paddingLength->at($key);\n return str_pad($value, $max, ' ', STR_PAD_LEFT);\n })->values()->toArray();\n $this->writer->writeln('| ' . implode(' | ', $columns) . ' |');\n }\n }\n\n private function writeFooter() : void\n {\n $headerLength = strlen($this->header());\n $headerSeparator = str_pad('', $headerLength, '-');\n $this->writer->writeln(str_pad('', $headerLength, '-'));\n }\n\n}\nadd order number to report\n *\n * This source file is subject to the MIT license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace hhpack\\performance\\reporter;\n\nuse hhpack\\performance\\Writer;\nuse hhpack\\performance\\WatchedResult;\nuse hhpack\\performance\\ResultReporter;\nuse hhpack\\performance\\result\\BenchmarkedResult;\nuse hhpack\\performance\\writer\\StdoutWriter;\n\nfinal class TextReporter implements ResultReporter\n{\n\n private Vector> $results;\n private Map $paddingLength;\n\n public function __construct(\n private Writer $writer = new StdoutWriter()\n )\n {\n $this->results = Vector {};\n $this->paddingLength = Map {};\n }\n\n public function onStop(BenchmarkedResult $result) : void\n {\n $orderedResult = Map { 'order' => (string) $result->orderNumber() };\n\n $watchedResult = $result->map(($value) ==> (string) $value);\n $watchedResult = $orderedResult->addAll( $watchedResult->items() )->toImmMap();\n\n foreach ($watchedResult as $key => $value) {\n $length = strlen((string) $value);\n $paddingLength = $this->paddingLength->get($key);\n $paddingLength = ($paddingLength === null) ? 0 : $paddingLength;\n $this->paddingLength->set($key, ($length > $paddingLength) ? $length : $paddingLength);\n }\n\n $this->results->add($watchedResult);\n }\n\n public function onFinish() : void\n {\n $this->writeHeader();\n $this->writeBody();\n $this->writeFooter();\n }\n\n <<__Memoize>>\n private function header() : string\n {\n $this->paddingLength = $this->paddingLength->mapWithKey(($key, $value) ==> {\n return strlen($key) <= $value ? $value : strlen($key);\n });\n\n $columns = $this->paddingLength->mapWithKey(($key, $value) ==> {\n return str_pad($key, $value, ' ', STR_PAD_RIGHT);\n })->values()->toArray();\n\n return '| ' . implode(' | ', $columns) . ' |';\n }\n\n private function writeHeader() : void\n {\n $headerLength = strlen($this->header());\n $headerSeparator = str_pad('', $headerLength, '-');\n\n $this->writer->writeln($headerSeparator);\n $this->writer->writeln($this->header());\n $this->writer->writeln($headerSeparator);\n }\n\n private function writeBody() : void\n {\n foreach ($this->results as $result) {\n $columns = $result->mapWithKey(($key, $value) ==> {\n $max = $this->paddingLength->at($key);\n return str_pad($value, $max, ' ', STR_PAD_LEFT);\n })->values()->toArray();\n $this->writer->writeln('| ' . implode(' | ', $columns) . ' |');\n }\n }\n\n private function writeFooter() : void\n {\n $headerLength = strlen($this->header());\n $headerSeparator = str_pad('', $headerLength, '-');\n $this->writer->writeln(str_pad('', $headerLength, '-'));\n }\n\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n\n#include \"event_loop.hpp\"\n#include \"libevent.hpp\"\n#include \"synchronized.hpp\"\n\nnamespace process {\n\nstruct event_base* base = NULL;\n\n\nvoid* EventLoop::run(void*)\n{\n do {\n int result = event_base_loop(base, EVLOOP_ONCE);\n if (result < 0) {\n LOG(FATAL) << \"Failed to run event loop\";\n } else if (result == 1) {\n VLOG(1) << \"All events handled, continuing event loop\";\n continue;\n } else if (event_base_got_break(base)) {\n break;\n } else if (event_base_got_exit(base)) {\n break;\n }\n } while (true);\n return NULL;\n}\n\n\nnamespace internal {\n\nstruct Delay\n{\n lambda::function function;\n event* timer;\n};\n\nvoid handle_delay(int, short, void* arg)\n{\n Delay* delay = reinterpret_cast(arg);\n delay->function();\n delete delay;\n}\n\n} \/\/ namespace internal {\n\n\nvoid EventLoop::delay(\n const Duration& duration,\n const lambda::function& function)\n{\n internal::Delay* delay = new internal::Delay();\n delay->timer = evtimer_new(base, &internal::handle_delay, delay);\n if (delay->timer == NULL) {\n LOG(FATAL) << \"Failed to delay, evtimer_new\";\n }\n\n delay->function = function;\n\n timeval t{0, 0};\n if (duration > Seconds(0)) {\n t = duration.timeval();\n }\n\n evtimer_add(delay->timer, &t);\n}\n\n\ndouble EventLoop::time()\n{\n \/\/ Get the cached time if running the event loop, or call\n \/\/ gettimeofday() to get the current time. Since a lot of logic in\n \/\/ libprocess depends on time math, we want to log fatal rather than\n \/\/ cause logic errors if the time fails.\n timeval t;\n if (event_base_gettimeofday_cached(base, &t) < 0) {\n LOG(FATAL) << \"Failed to get time, event_base_gettimeofday_cached\";\n }\n\n return Duration(t).secs();\n}\n\n\nvoid EventLoop::initialize()\n{\n if (evthread_use_pthreads() < 0) {\n LOG(FATAL) << \"Failed to initialize, evthread_use_pthreads\";\n }\n\n \/\/ This enables debugging of libevent calls. We can remove this\n \/\/ when the implementation settles and after we gain confidence.\n event_enable_debug_mode();\n\n base = event_base_new();\n if (base == NULL) {\n LOG(FATAL) << \"Failed to initialize, event_base_new\";\n }\n}\n\n} \/\/ namespace process {\nMESOS-2377: Fix leak in libevent EventLoop::handle_delay.#include \n\n#include \n#include \n\n#include \n\n#include \"event_loop.hpp\"\n#include \"libevent.hpp\"\n#include \"synchronized.hpp\"\n\nnamespace process {\n\nstruct event_base* base = NULL;\n\n\nvoid* EventLoop::run(void*)\n{\n do {\n int result = event_base_loop(base, EVLOOP_ONCE);\n if (result < 0) {\n LOG(FATAL) << \"Failed to run event loop\";\n } else if (result == 1) {\n VLOG(1) << \"All events handled, continuing event loop\";\n continue;\n } else if (event_base_got_break(base)) {\n break;\n } else if (event_base_got_exit(base)) {\n break;\n }\n } while (true);\n return NULL;\n}\n\n\nnamespace internal {\n\nstruct Delay\n{\n lambda::function function;\n event* timer;\n};\n\nvoid handle_delay(int, short, void* arg)\n{\n Delay* delay = reinterpret_cast(arg);\n delay->function();\n event_free(delay->timer);\n delete delay;\n}\n\n} \/\/ namespace internal {\n\n\nvoid EventLoop::delay(\n const Duration& duration,\n const lambda::function& function)\n{\n internal::Delay* delay = new internal::Delay();\n delay->timer = evtimer_new(base, &internal::handle_delay, delay);\n if (delay->timer == NULL) {\n LOG(FATAL) << \"Failed to delay, evtimer_new\";\n }\n\n delay->function = function;\n\n timeval t{0, 0};\n if (duration > Seconds(0)) {\n t = duration.timeval();\n }\n\n evtimer_add(delay->timer, &t);\n}\n\n\ndouble EventLoop::time()\n{\n \/\/ Get the cached time if running the event loop, or call\n \/\/ gettimeofday() to get the current time. Since a lot of logic in\n \/\/ libprocess depends on time math, we want to log fatal rather than\n \/\/ cause logic errors if the time fails.\n timeval t;\n if (event_base_gettimeofday_cached(base, &t) < 0) {\n LOG(FATAL) << \"Failed to get time, event_base_gettimeofday_cached\";\n }\n\n return Duration(t).secs();\n}\n\n\nvoid EventLoop::initialize()\n{\n if (evthread_use_pthreads() < 0) {\n LOG(FATAL) << \"Failed to initialize, evthread_use_pthreads\";\n }\n\n \/\/ This enables debugging of libevent calls. We can remove this\n \/\/ when the implementation settles and after we gain confidence.\n event_enable_debug_mode();\n\n base = event_base_new();\n if (base == NULL) {\n LOG(FATAL) << \"Failed to initialize, event_base_new\";\n }\n}\n\n} \/\/ namespace process {\n<|endoftext|>"} {"text":"#include \"ROOT\/TDataFrame.hxx\"\n#include \"TRandom.h\"\n#include \"gtest\/gtest.h\"\n#include \nusing namespace ROOT::Experimental;\nusing namespace ROOT::Experimental::TDF;\nusing namespace ROOT::Detail::TDF;\n\n\/********* FIXTURES *********\/\n\/\/ fixture that provides a TDF with no data-source and a single column \"x\" containing normal-distributed doubles\nclass TDFCallbacks : public ::testing::Test {\nprotected:\n const ULong64_t nEvents = 8ull; \/\/ must be initialized before fLoopManager\n\nprivate:\n TDataFrame fLoopManager;\n TInterface DefineRandomCol()\n {\n TRandom r;\n return fLoopManager.Define(\"x\", [r]() mutable { return r.Gaus(); });\n }\n\nprotected:\n TDFCallbacks() : fLoopManager(nEvents), tdf(DefineRandomCol()) {}\n TInterface tdf;\n};\n\n\/********* TESTS *********\/\nTEST_F(TDFCallbacks, Histo1DWithFillTOHelper)\n{\n \/\/ Histo1D + OnPartialResult + FillTOHelper\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, JittedHisto1DWithFillTOHelper)\n{\n \/\/ Histo1D + Jitting + OnPartialResult + FillTOHelper\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, Histo1DWithFillHelper)\n{\n \/\/ Histo1D + OnPartialResult + FillHelper\n auto h = tdf.Histo1D(\"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, JittedHisto1DWithFillHelper)\n{\n \/\/ Histo1D + Jitting + OnPartialResult + FillHelper\n auto h = tdf.Histo1D(\"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, Min)\n{\n \/\/ Min + OnPartialResult\n auto m = tdf.Min(\"x\");\n double runningMin = std::numeric_limits::max();\n m.OnPartialResult(2, [&runningMin](double x) {\n EXPECT_LE(x, runningMin);\n runningMin = x;\n });\n EXPECT_DOUBLE_EQ(runningMin, *m);\n}\n\nTEST_F(TDFCallbacks, JittedMin)\n{\n \/\/ Min + Jitting + OnPartialResult\n auto m = tdf.Min(\"x\");\n double runningMin = std::numeric_limits::max();\n m.OnPartialResult(2, [&runningMin](double x) {\n EXPECT_LE(x, runningMin);\n runningMin = x;\n });\n EXPECT_DOUBLE_EQ(runningMin, *m);\n}\n\nTEST_F(TDFCallbacks, Max)\n{\n \/\/ Max + OnPartialResult\n auto m = tdf.Max(\"x\");\n double runningMax = std::numeric_limits::lowest();\n m.OnPartialResult(2, [&runningMax](double x) {\n EXPECT_GE(x, runningMax);\n runningMax = x;\n });\n EXPECT_DOUBLE_EQ(runningMax, *m);\n}\n\nTEST_F(TDFCallbacks, JittedMax)\n{\n \/\/ Max + Jitting + OnPartialResult\n auto m = tdf.Max(\"x\");\n double runningMax = std::numeric_limits::lowest();\n m.OnPartialResult(2, [&runningMax](double x) {\n EXPECT_GE(x, runningMax);\n runningMax = x;\n });\n EXPECT_DOUBLE_EQ(runningMax, *m);\n}\n\nTEST_F(TDFCallbacks, Mean)\n{\n \/\/ Mean + OnPartialResult\n auto m = tdf.Mean(\"x\");\n \/\/ TODO find a better way to check that the running mean makes sense\n bool called = false;\n m.OnPartialResult(nEvents \/ 2, [&called](double) { called = true; });\n *m;\n EXPECT_TRUE(called);\n}\n\nTEST_F(TDFCallbacks, JittedMean)\n{\n \/\/ Mean + Jitting + OnPartialResult\n auto m = tdf.Mean(\"x\");\n \/\/ TODO find a better way to check that the running mean makes sense\n bool called = false;\n m.OnPartialResult(nEvents \/ 2, [&called](double) { called = true; });\n *m;\n EXPECT_TRUE(called);\n}\n\nTEST_F(TDFCallbacks, Take)\n{\n \/\/ Take + OnPartialResult\n auto t = tdf.Take(\"x\");\n unsigned int i = 0u;\n t.OnPartialResult(1, [&](decltype(t)::Value_t &t_) {\n ++i;\n EXPECT_EQ(t_.size(), i);\n });\n *t;\n}\n\nTEST_F(TDFCallbacks, Count)\n{\n \/\/ Count + OnPartialResult\n auto c = tdf.Count();\n ULong64_t i = 0ull;\n c.OnPartialResult(1, [&](decltype(c)::Value_t c_) {\n ++i;\n EXPECT_EQ(c_, i);\n });\n EXPECT_EQ(*c, i);\n}\n\nTEST_F(TDFCallbacks, Reduce)\n{\n \/\/ Reduce + OnPartialResult\n double runningMin;\n auto m = tdf.Min(\"x\").OnPartialResult(1, [&runningMin](double m_) { runningMin = m_; });\n auto r = tdf.Reduce([](double x1, double x2) { return std::min(x1, x2); }, {\"x\"}, 0.);\n r.OnPartialResult(1, [&runningMin](double r_) { EXPECT_DOUBLE_EQ(r_, runningMin); });\n *r;\n}\n\nTEST_F(TDFCallbacks, Chaining)\n{\n \/\/ Chaining of multiple OnPartialResult[Slot] calls\n unsigned int i = 0u;\n auto c = tdf.Count()\n .OnPartialResult(1, [&i](ULong64_t) { ++i; })\n .OnPartialResultSlot(1, [&i](unsigned int, ULong64_t) {++i; });\n *c;\n EXPECT_EQ(i, nEvents * 2);\n}\n\nTEST_F(TDFCallbacks, OrderOfExecution)\n{\n \/\/ Test that callbacks are executed in the order they are registered\n unsigned int i = 0u;\n auto c = tdf.Count();\n c.OnPartialResult(1, [&i](ULong64_t) {\n EXPECT_EQ(i, 0u);\n i = 42u;\n });\n c.OnPartialResultSlot(1, [&i](unsigned int slot, ULong64_t) {\n if (slot == 0u) {\n EXPECT_EQ(i, 42u);\n i = 0u;\n }\n });\n *c;\n EXPECT_EQ(i, 0u);\n}\n\nTEST_F(TDFCallbacks, MultipleCallbacks)\n{\n \/\/ registration of multiple callbacks on the same partial result\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t everyN = 1ull;\n ULong64_t i = 0ull;\n h.OnPartialResult(everyN, [&i, everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), i);\n });\n\n everyN = 2ull;\n ULong64_t i2 = 0ull;\n h.OnPartialResult(everyN, [&i2, everyN](value_t &h_) {\n i2 += everyN;\n EXPECT_EQ(h_.GetEntries(), i2);\n });\n\n *h;\n}\n\nTEST_F(TDFCallbacks, MultipleEventLoops)\n{\n \/\/ callbacks must be de-registered after the event-loop is run\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n h.OnPartialResult(1ull, [&i](value_t &) { ++i; });\n *h;\n\n auto h2 = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n *h2;\n\n EXPECT_EQ(i, nEvents);\n}\n\nclass FunctorClass {\n unsigned int &i_;\n\npublic:\n FunctorClass(unsigned int &i) : i_(i) {}\n void operator()(ULong64_t) { ++i_; }\n};\n\nTEST_F(TDFCallbacks, FunctorClass)\n{\n unsigned int i = 0;\n *(tdf.Count().OnPartialResult(1, FunctorClass(i)));\n EXPECT_EQ(i, nEvents);\n}\n\nunsigned int freeFunctionCounter = 0;\nvoid FreeFunction(ULong64_t)\n{\n freeFunctionCounter++;\n}\n\nTEST_F(TDFCallbacks, FreeFunction)\n{\n *(tdf.Count().OnPartialResult(1, FreeFunction));\n EXPECT_EQ(freeFunctionCounter, nEvents);\n}\n[TDF] Add test for calling a callback once, with and without IMT#include \"ROOT\/TDataFrame.hxx\"\n#include \"TRandom.h\"\n#include \"TROOT.h\"\n#include \"gtest\/gtest.h\"\n#include \nusing namespace ROOT::Experimental;\nusing namespace ROOT::Experimental::TDF;\nusing namespace ROOT::Detail::TDF;\n\n\/********* FIXTURES *********\/\n\/\/ fixture that provides a TDF with no data-source and a single column \"x\" containing normal-distributed doubles\nclass TDFCallbacks : public ::testing::Test {\nprotected:\n const ULong64_t nEvents = 8ull; \/\/ must be initialized before fLoopManager\n\nprivate:\n TDataFrame fLoopManager;\n TInterface DefineRandomCol()\n {\n TRandom r;\n return fLoopManager.Define(\"x\", [r]() mutable { return r.Gaus(); });\n }\n\nprotected:\n TDFCallbacks() : fLoopManager(nEvents), tdf(DefineRandomCol()) {}\n TInterface tdf;\n};\n\n\/\/ fixture that enables implicit MT and provides a TDF with no data-source and a single column \"x\" containing\n\/\/ normal-distributed doubles\nclass TDFCallbacksMT : public ::testing::Test {\n class TIMTEnabler {\n public:\n TIMTEnabler(unsigned int nSlots) {\n ROOT::EnableImplicitMT(nSlots);\n }\n ~TIMTEnabler() {\n ROOT::DisableImplicitMT();\n }\n };\n\nprotected:\n const ULong64_t nEvents = 8ull; \/\/ must be initialized before fLoopManager\n const unsigned int nSlots = 4u;\n\nprivate:\n TIMTEnabler fIMTEnabler;\n TDataFrame fLoopManager;\n TInterface DefineRandomCol()\n {\n std::vector rs;\n return fLoopManager.DefineSlot(\"x\", [rs](unsigned int slot) mutable { return rs[slot].Gaus(); });\n }\n\nprotected:\n TDFCallbacksMT() : fIMTEnabler(nSlots), fLoopManager(nEvents), tdf(DefineRandomCol()) {}\n TInterface tdf;\n};\n\n\n\/********* TESTS *********\/\nTEST_F(TDFCallbacks, Histo1DWithFillTOHelper)\n{\n \/\/ Histo1D + OnPartialResult + FillTOHelper\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, JittedHisto1DWithFillTOHelper)\n{\n \/\/ Histo1D + Jitting + OnPartialResult + FillTOHelper\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, Histo1DWithFillHelper)\n{\n \/\/ Histo1D + OnPartialResult + FillHelper\n auto h = tdf.Histo1D(\"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, JittedHisto1DWithFillHelper)\n{\n \/\/ Histo1D + Jitting + OnPartialResult + FillHelper\n auto h = tdf.Histo1D(\"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n ULong64_t everyN = 1ull;\n h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), everyN * i);\n });\n *h;\n EXPECT_EQ(nEvents, everyN * i);\n}\n\nTEST_F(TDFCallbacks, Min)\n{\n \/\/ Min + OnPartialResult\n auto m = tdf.Min(\"x\");\n double runningMin = std::numeric_limits::max();\n m.OnPartialResult(2, [&runningMin](double x) {\n EXPECT_LE(x, runningMin);\n runningMin = x;\n });\n EXPECT_DOUBLE_EQ(runningMin, *m);\n}\n\nTEST_F(TDFCallbacks, JittedMin)\n{\n \/\/ Min + Jitting + OnPartialResult\n auto m = tdf.Min(\"x\");\n double runningMin = std::numeric_limits::max();\n m.OnPartialResult(2, [&runningMin](double x) {\n EXPECT_LE(x, runningMin);\n runningMin = x;\n });\n EXPECT_DOUBLE_EQ(runningMin, *m);\n}\n\nTEST_F(TDFCallbacks, Max)\n{\n \/\/ Max + OnPartialResult\n auto m = tdf.Max(\"x\");\n double runningMax = std::numeric_limits::lowest();\n m.OnPartialResult(2, [&runningMax](double x) {\n EXPECT_GE(x, runningMax);\n runningMax = x;\n });\n EXPECT_DOUBLE_EQ(runningMax, *m);\n}\n\nTEST_F(TDFCallbacks, JittedMax)\n{\n \/\/ Max + Jitting + OnPartialResult\n auto m = tdf.Max(\"x\");\n double runningMax = std::numeric_limits::lowest();\n m.OnPartialResult(2, [&runningMax](double x) {\n EXPECT_GE(x, runningMax);\n runningMax = x;\n });\n EXPECT_DOUBLE_EQ(runningMax, *m);\n}\n\nTEST_F(TDFCallbacks, Mean)\n{\n \/\/ Mean + OnPartialResult\n auto m = tdf.Mean(\"x\");\n \/\/ TODO find a better way to check that the running mean makes sense\n bool called = false;\n m.OnPartialResult(nEvents \/ 2, [&called](double) { called = true; });\n *m;\n EXPECT_TRUE(called);\n}\n\nTEST_F(TDFCallbacks, JittedMean)\n{\n \/\/ Mean + Jitting + OnPartialResult\n auto m = tdf.Mean(\"x\");\n \/\/ TODO find a better way to check that the running mean makes sense\n bool called = false;\n m.OnPartialResult(nEvents \/ 2, [&called](double) { called = true; });\n *m;\n EXPECT_TRUE(called);\n}\n\nTEST_F(TDFCallbacks, Take)\n{\n \/\/ Take + OnPartialResult\n auto t = tdf.Take(\"x\");\n unsigned int i = 0u;\n t.OnPartialResult(1, [&](decltype(t)::Value_t &t_) {\n ++i;\n EXPECT_EQ(t_.size(), i);\n });\n *t;\n}\n\nTEST_F(TDFCallbacks, Count)\n{\n \/\/ Count + OnPartialResult\n auto c = tdf.Count();\n ULong64_t i = 0ull;\n c.OnPartialResult(1, [&](decltype(c)::Value_t c_) {\n ++i;\n EXPECT_EQ(c_, i);\n });\n EXPECT_EQ(*c, i);\n}\n\nTEST_F(TDFCallbacks, Reduce)\n{\n \/\/ Reduce + OnPartialResult\n double runningMin;\n auto m = tdf.Min(\"x\").OnPartialResult(1, [&runningMin](double m_) { runningMin = m_; });\n auto r = tdf.Reduce([](double x1, double x2) { return std::min(x1, x2); }, {\"x\"}, 0.);\n r.OnPartialResult(1, [&runningMin](double r_) { EXPECT_DOUBLE_EQ(r_, runningMin); });\n *r;\n}\n\nTEST_F(TDFCallbacks, Chaining)\n{\n \/\/ Chaining of multiple OnPartialResult[Slot] calls\n unsigned int i = 0u;\n auto c = tdf.Count()\n .OnPartialResult(1, [&i](ULong64_t) { ++i; })\n .OnPartialResultSlot(1, [&i](unsigned int, ULong64_t) {++i; });\n *c;\n EXPECT_EQ(i, nEvents * 2);\n}\n\nTEST_F(TDFCallbacks, OrderOfExecution)\n{\n \/\/ Test that callbacks are executed in the order they are registered\n unsigned int i = 0u;\n auto c = tdf.Count();\n c.OnPartialResult(1, [&i](ULong64_t) {\n EXPECT_EQ(i, 0u);\n i = 42u;\n });\n c.OnPartialResultSlot(1, [&i](unsigned int slot, ULong64_t) {\n if (slot == 0u) {\n EXPECT_EQ(i, 42u);\n i = 0u;\n }\n });\n *c;\n EXPECT_EQ(i, 0u);\n}\n\nTEST_F(TDFCallbacks, ExecuteOnce)\n{\n \/\/ OnPartialResult(kOnce)\n auto c = tdf.Count();\n unsigned int callCount = 0;\n c.OnPartialResult(0, [&callCount](ULong64_t) { callCount++; });\n *c;\n EXPECT_EQ(callCount, 1u);\n}\n\nTEST_F(TDFCallbacksMT, ExecuteOncePerSlot)\n{\n \/\/ OnPartialResultSlot(kOnce)\n auto c = tdf.Count();\n std::atomic_uint callCount(0u);\n c.OnPartialResultSlot(c.kOnce, [&callCount](unsigned int, ULong64_t) { callCount++; });\n *c;\n EXPECT_EQ(callCount, nSlots);\n}\n\nTEST_F(TDFCallbacks, MultipleCallbacks)\n{\n \/\/ registration of multiple callbacks on the same partial result\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t everyN = 1ull;\n ULong64_t i = 0ull;\n h.OnPartialResult(everyN, [&i, everyN](value_t &h_) {\n i += everyN;\n EXPECT_EQ(h_.GetEntries(), i);\n });\n\n everyN = 2ull;\n ULong64_t i2 = 0ull;\n h.OnPartialResult(everyN, [&i2, everyN](value_t &h_) {\n i2 += everyN;\n EXPECT_EQ(h_.GetEntries(), i2);\n });\n\n *h;\n}\n\nTEST_F(TDFCallbacks, MultipleEventLoops)\n{\n \/\/ callbacks must be de-registered after the event-loop is run\n auto h = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n using value_t = typename decltype(h)::Value_t;\n ULong64_t i = 0ull;\n h.OnPartialResult(1ull, [&i](value_t &) { ++i; });\n *h;\n\n auto h2 = tdf.Histo1D({\"\", \"\", 128, -2., 2.}, \"x\");\n *h2;\n\n EXPECT_EQ(i, nEvents);\n}\n\nclass FunctorClass {\n unsigned int &i_;\n\npublic:\n FunctorClass(unsigned int &i) : i_(i) {}\n void operator()(ULong64_t) { ++i_; }\n};\n\nTEST_F(TDFCallbacks, FunctorClass)\n{\n unsigned int i = 0;\n *(tdf.Count().OnPartialResult(1, FunctorClass(i)));\n EXPECT_EQ(i, nEvents);\n}\n\nunsigned int freeFunctionCounter = 0;\nvoid FreeFunction(ULong64_t)\n{\n freeFunctionCounter++;\n}\n\nTEST_F(TDFCallbacks, FreeFunction)\n{\n *(tdf.Count().OnPartialResult(1, FreeFunction));\n EXPECT_EQ(freeFunctionCounter, nEvents);\n}\n<|endoftext|>"} {"text":"Water balance error corrected<|endoftext|>"} {"text":"\/*\n * main.cpp\n * Program: kalarm\n * (C) 2001 - 2003 by David Jarvie software@astrojar.org.uk\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \"kalarm.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kalarmapp.h\"\n\n#define PROGRAM_NAME \"kalarm\"\n\nQCString execArguments; \/\/ argument to --exec option\n\nstatic KCmdLineOptions options[] =\n{\n\t{ \"a\", 0, 0 },\n\t{ \"ack-confirm\", I18N_NOOP(\"Prompt for confirmation when alarm is acknowledged\"), 0 },\n\t{ \"A\", 0, 0 },\n\t{ \"attach \", I18N_NOOP(\"Attach file to email (repeat as needed)\"), 0 },\n\t{ \"bcc\", I18N_NOOP(\"Blind copy email to self\"), 0 },\n\t{ \"b\", 0, 0 },\n\t{ \"beep\", I18N_NOOP(\"Beep when message is displayed\"), 0 },\n\t{ \"colour\", 0, 0 },\n\t{ \"c\", 0, 0 },\n\t{ \"color \", I18N_NOOP(\"Message background color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"calendarURL \", I18N_NOOP(\"URL of calendar file\"), 0 },\n\t{ \"cancelEvent \", I18N_NOOP(\"Cancel alarm with the specified event ID\"), 0 },\n\t{ \"e\", 0, 0 },\n\t{ \"exec \", I18N_NOOP(\"Execute a shell command line\"), 0 },\n\t{ \"f\", 0, 0 },\n\t{ \"file \", I18N_NOOP(\"File to display\"), 0 },\n\t{ \"handleEvent \", I18N_NOOP(\"Trigger or cancel alarm with the specified event ID\"), 0 },\n\t{ \"i\", 0, 0 },\n\t{ \"interval \", I18N_NOOP(\"Interval between alarm recurrences\"), 0 },\n\t{ \"l\", 0, 0 },\n\t{ \"late-cancel\", I18N_NOOP(\"Cancel alarm if it cannot be triggered on time\"), 0 },\n\t{ \"L\", 0, 0 },\n\t{ \"login\", I18N_NOOP(\"Repeat alarm at every login\"), 0 },\n\t{ \"m\", 0, 0 },\n\t{ \"mail
\", I18N_NOOP(\"Send an email to the given address (repeat as needed)\"), 0 },\n\t{ \"recurrence \", I18N_NOOP(\"Specify alarm recurrence in RFC2445 format\"), 0 },\n\t{ \"R\", 0, 0 },\n\t{ \"reminder \", I18N_NOOP(\"Display reminder in advance of alarm\"), 0 },\n\t{ \"r\", 0, 0 },\n\t{ \"repeat \", I18N_NOOP(\"Number of times to repeat alarm (after the initial occasion)\"), 0 },\n\t{ \"reset\", I18N_NOOP(\"Reset the alarm scheduling daemon\"), 0 },\n\t{ \"s\", 0, 0 },\n\t{ \"sound \", I18N_NOOP(\"Audio file to play\"), 0 },\n\t{ \"stop\", I18N_NOOP(\"Stop the alarm scheduling daemon\"), 0 },\n\t{ \"S\", 0, 0 },\n\t{ \"subject \", I18N_NOOP(\"Email subject line\"), 0 },\n\t{ \"t\", 0, 0 },\n\t{ \"time