commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
dab7095fc5510c78eef150346cda15cc090fd689
|
test/cpp/interop/server.cc
|
test/cpp/interop/server.cc
|
/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <memory>
#include <sstream>
#include <thread>
#include <google/gflags.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include "test/core/end2end/data/ssl_test_data.h"
#include <grpc++/config.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include "test/cpp/interop/test.pb.h"
#include "test/cpp/interop/empty.pb.h"
#include "test/cpp/interop/messages.pb.h"
DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls.");
DEFINE_int32(port, 0, "Server port.");
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCredentials;
using grpc::ServerCredentialsFactory;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::SslServerCredentialsOptions;
using grpc::testing::Payload;
using grpc::testing::PayloadType;
using grpc::testing::SimpleRequest;
using grpc::testing::SimpleResponse;
using grpc::testing::StreamingInputCallRequest;
using grpc::testing::StreamingInputCallResponse;
using grpc::testing::StreamingOutputCallRequest;
using grpc::testing::StreamingOutputCallResponse;
using grpc::testing::TestService;
using grpc::Status;
bool SetPayload(PayloadType type, int size, Payload* payload) {
PayloadType response_type = type;
// TODO(yangg): Support UNCOMPRESSABLE payload.
if (type != PayloadType::COMPRESSABLE) {
return false;
}
payload->set_type(response_type);
std::unique_ptr<char[]> body(new char[size]());
payload->set_body(body.get(), size);
return true;
}
class TestServiceImpl : public TestService::Service {
public:
Status EmptyCall(ServerContext* context, const grpc::testing::Empty* request,
grpc::testing::Empty* response) {
return Status::OK;
}
Status UnaryCall(ServerContext* context, const SimpleRequest* request,
SimpleResponse* response) {
if (request->has_response_size() && request->response_size() > 0) {
if (!SetPayload(request->response_type(), request->response_size(),
response->mutable_payload())) {
return Status(grpc::StatusCode::INTERNAL, "Error creating payload.");
}
}
return Status::OK;
}
Status StreamingOutputCall(
ServerContext* context, const StreamingOutputCallRequest* request,
ServerWriter<StreamingOutputCallResponse>* writer) {
StreamingOutputCallResponse response;
bool write_success = true;
response.mutable_payload()->set_type(request->response_type());
for (int i = 0; write_success && i < request->response_parameters_size();
i++) {
response.mutable_payload()->set_body(
grpc::string(request->response_parameters(i).size(), '\0'));
write_success = writer->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status StreamingInputCall(ServerContext* context,
ServerReader<StreamingInputCallRequest>* reader,
StreamingInputCallResponse* response) {
StreamingInputCallRequest request;
int aggregated_payload_size = 0;
while (reader->Read(&request)) {
if (request.has_payload() && request.payload().has_body()) {
aggregated_payload_size += request.payload().body().size();
}
}
response->set_aggregated_payload_size(aggregated_payload_size);
return Status::OK;
}
Status FullDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
StreamingOutputCallRequest request;
StreamingOutputCallResponse response;
bool write_success = true;
while (write_success && stream->Read(&request)) {
response.mutable_payload()->set_type(request.payload().type());
if (request.response_parameters_size() == 0) {
return Status(grpc::StatusCode::INTERNAL,
"Request does not have response parameters.");
}
response.mutable_payload()->set_body(
grpc::string(request.response_parameters(0).size(), '\0'));
write_success = stream->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status HalfDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
std::vector<StreamingOutputCallRequest> requests;
StreamingOutputCallRequest request;
while (stream->Read(&request)) {
requests.push_back(request);
}
StreamingOutputCallResponse response;
bool write_success = true;
for (unsigned int i = 0; write_success && i < requests.size(); i++) {
response.mutable_payload()->set_type(requests[i].payload().type());
if (requests[i].response_parameters_size() == 0) {
return Status(grpc::StatusCode::INTERNAL,
"Request does not have response parameters.");
}
response.mutable_payload()->set_body(
grpc::string(requests[i].response_parameters(0).size(), '\0'));
write_success = stream->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
};
void RunServer() {
std::ostringstream server_address;
server_address << "localhost:" << FLAGS_port;
TestServiceImpl service;
SimpleRequest request;
SimpleResponse response;
ServerBuilder builder;
builder.AddPort(server_address.str());
builder.RegisterService(service.service());
if (FLAGS_enable_ssl) {
SslServerCredentialsOptions ssl_opts = {
"", {{test_server1_key, test_server1_cert}}};
std::shared_ptr<ServerCredentials> creds =
ServerCredentialsFactory::SslCredentials(ssl_opts);
builder.SetCredentials(creds);
}
std::unique_ptr<Server> server(builder.BuildAndStart());
gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str());
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
int main(int argc, char** argv) {
grpc_init();
google::ParseCommandLineFlags(&argc, &argv, true);
GPR_ASSERT(FLAGS_port != 0);
RunServer();
grpc_shutdown();
return 0;
}
|
/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <memory>
#include <sstream>
#include <thread>
#include <google/gflags.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include "test/core/end2end/data/ssl_test_data.h"
#include <grpc++/config.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include "test/cpp/interop/test.pb.h"
#include "test/cpp/interop/empty.pb.h"
#include "test/cpp/interop/messages.pb.h"
DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls.");
DEFINE_int32(port, 0, "Server port.");
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCredentials;
using grpc::ServerCredentialsFactory;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::SslServerCredentialsOptions;
using grpc::testing::Payload;
using grpc::testing::PayloadType;
using grpc::testing::SimpleRequest;
using grpc::testing::SimpleResponse;
using grpc::testing::StreamingInputCallRequest;
using grpc::testing::StreamingInputCallResponse;
using grpc::testing::StreamingOutputCallRequest;
using grpc::testing::StreamingOutputCallResponse;
using grpc::testing::TestService;
using grpc::Status;
bool SetPayload(PayloadType type, int size, Payload* payload) {
PayloadType response_type = type;
// TODO(yangg): Support UNCOMPRESSABLE payload.
if (type != PayloadType::COMPRESSABLE) {
return false;
}
payload->set_type(response_type);
std::unique_ptr<char[]> body(new char[size]());
payload->set_body(body.get(), size);
return true;
}
class TestServiceImpl : public TestService::Service {
public:
Status EmptyCall(ServerContext* context, const grpc::testing::Empty* request,
grpc::testing::Empty* response) {
return Status::OK;
}
Status UnaryCall(ServerContext* context, const SimpleRequest* request,
SimpleResponse* response) {
if (request->has_response_size() && request->response_size() > 0) {
if (!SetPayload(request->response_type(), request->response_size(),
response->mutable_payload())) {
return Status(grpc::StatusCode::INTERNAL, "Error creating payload.");
}
}
return Status::OK;
}
Status StreamingOutputCall(
ServerContext* context, const StreamingOutputCallRequest* request,
ServerWriter<StreamingOutputCallResponse>* writer) {
StreamingOutputCallResponse response;
bool write_success = true;
response.mutable_payload()->set_type(request->response_type());
for (int i = 0; write_success && i < request->response_parameters_size();
i++) {
response.mutable_payload()->set_body(
grpc::string(request->response_parameters(i).size(), '\0'));
write_success = writer->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status StreamingInputCall(ServerContext* context,
ServerReader<StreamingInputCallRequest>* reader,
StreamingInputCallResponse* response) {
StreamingInputCallRequest request;
int aggregated_payload_size = 0;
while (reader->Read(&request)) {
if (request.has_payload() && request.payload().has_body()) {
aggregated_payload_size += request.payload().body().size();
}
}
response->set_aggregated_payload_size(aggregated_payload_size);
return Status::OK;
}
Status FullDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
StreamingOutputCallRequest request;
StreamingOutputCallResponse response;
bool write_success = true;
while (write_success && stream->Read(&request)) {
response.mutable_payload()->set_type(request.payload().type());
if (request.response_parameters_size() == 0) {
return Status(grpc::StatusCode::INTERNAL,
"Request does not have response parameters.");
}
response.mutable_payload()->set_body(
grpc::string(request.response_parameters(0).size(), '\0'));
write_success = stream->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status HalfDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
std::vector<StreamingOutputCallRequest> requests;
StreamingOutputCallRequest request;
while (stream->Read(&request)) {
requests.push_back(request);
}
StreamingOutputCallResponse response;
bool write_success = true;
for (unsigned int i = 0; write_success && i < requests.size(); i++) {
response.mutable_payload()->set_type(requests[i].payload().type());
if (requests[i].response_parameters_size() == 0) {
return Status(grpc::StatusCode::INTERNAL,
"Request does not have response parameters.");
}
response.mutable_payload()->set_body(
grpc::string(requests[i].response_parameters(0).size(), '\0'));
write_success = stream->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
};
void RunServer() {
std::ostringstream server_address;
server_address << "0.0.0.0:" << FLAGS_port;
TestServiceImpl service;
SimpleRequest request;
SimpleResponse response;
ServerBuilder builder;
builder.AddPort(server_address.str());
builder.RegisterService(service.service());
if (FLAGS_enable_ssl) {
SslServerCredentialsOptions ssl_opts = {
"", {{test_server1_key, test_server1_cert}}};
std::shared_ptr<ServerCredentials> creds =
ServerCredentialsFactory::SslCredentials(ssl_opts);
builder.SetCredentials(creds);
}
std::unique_ptr<Server> server(builder.BuildAndStart());
gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str());
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
int main(int argc, char** argv) {
grpc_init();
google::ParseCommandLineFlags(&argc, &argv, true);
GPR_ASSERT(FLAGS_port != 0);
RunServer();
grpc_shutdown();
return 0;
}
|
Make interop server listen on 0.0.0.0.
|
Make interop server listen on 0.0.0.0.
|
C++
|
apache-2.0
|
sreecha/grpc,ejona86/grpc,tengyifei/grpc,tamihiro/grpc,LuminateWireless/grpc,dklempner/grpc,maxwell-demon/grpc,jboeuf/grpc,meisterpeeps/grpc,soltanmm-google/grpc,apolcyn/grpc,sreecha/grpc,JoeWoo/grpc,cgvarela/grpc,adelez/grpc,firebase/grpc,MakMukhi/grpc,vsco/grpc,firebase/grpc,Crevil/grpc,kumaralokgithub/grpc,ananthonline/grpc,dklempner/grpc,geffzhang/grpc,mzhaom/grpc,ppietrasa/grpc,tatsuhiro-t/grpc,thunderboltsid/grpc,Crevil/grpc,miselin/grpc,zeliard/grpc,w4-sjcho/grpc,philcleveland/grpc,rjshade/grpc,ppietrasa/grpc,muxi/grpc,grani/grpc,jboeuf/grpc,dgquintas/grpc,muxi/grpc,mehrdada/grpc,bjori/grpc,ejona86/grpc,makdharma/grpc,w4-sjcho/grpc,yang-g/grpc,sreecha/grpc,vjpai/grpc,doubi-workshop/grpc,JoeWoo/grpc,miselin/grpc,sidrakesh93/grpc,quizlet/grpc,stanley-cheung/grpc,w4-sjcho/grpc,podsvirov/grpc,chenbaihu/grpc,jcanizales/grpc,ksophocleous/grpc,baylabs/grpc,makdharma/grpc,ncteisen/grpc,ctiller/grpc,hstefan/grpc,MakMukhi/grpc,yugui/grpc,vsco/grpc,ofrobots/grpc,grpc/grpc,ncteisen/grpc,wangyikai/grpc,Juzley/grpc,MakMukhi/grpc,kpayson64/grpc,iMilind/grpc,rjshade/grpc,ncteisen/grpc,tengyifei/grpc,maxwell-demon/grpc,Crevil/grpc,quizlet/grpc,VcamX/grpc,tamihiro/grpc,nmittler/grpc,dgquintas/grpc,donnadionne/grpc,zeliard/grpc,dgquintas/grpc,msmania/grpc,grani/grpc,jcanizales/grpc,sreecha/grpc,makdharma/grpc,royalharsh/grpc,goldenbull/grpc,muxi/grpc,LuminateWireless/grpc,baylabs/grpc,zhimingxie/grpc,sidrakesh93/grpc,carl-mastrangelo/grpc,leifurhauks/grpc,ejona86/grpc,y-zeng/grpc,sreecha/grpc,PeterFaiman/ruby-grpc-minimal,gpndata/grpc,fichter/grpc,crast/grpc,msiedlarek/grpc,fichter/grpc,thinkerou/grpc,perumaalgoog/grpc,carl-mastrangelo/grpc,kpayson64/grpc,hstefan/grpc,ppietrasa/grpc,rjshade/grpc,dgquintas/grpc,fichter/grpc,yongni/grpc,iMilind/grpc,y-zeng/grpc,larsonmpdx/grpc,leifurhauks/grpc,VcamX/grpc,mway08/grpc,crast/grpc,yongni/grpc,quizlet/grpc,royalharsh/grpc,simonkuang/grpc,yangjae/grpc,xtopsoft/grpc,nicolasnoble/grpc,vjpai/grpc,msmania/grpc,ejona86/grpc,kskalski/grpc,hstefan/grpc,doubi-workshop/grpc,yugui/grpc,pszemus/grpc,ipylypiv/grpc,xtopsoft/grpc,nicolasnoble/grpc,meisterpeeps/grpc,goldenbull/grpc,makdharma/grpc,ksophocleous/grpc,xtopsoft/grpc,msmania/grpc,bogdandrutu/grpc,larsonmpdx/grpc,stanley-cheung/grpc,simonkuang/grpc,donnadionne/grpc,larsonmpdx/grpc,Juzley/grpc,perumaalgoog/grpc,tempbottle/grpc,pszemus/grpc,msmania/grpc,thinkerou/grpc,murgatroid99/grpc,VcamX/grpc,mehrdada/grpc,jboeuf/grpc,wangyikai/grpc,mehrdada/grpc,royalharsh/grpc,arkmaxim/grpc,MakMukhi/grpc,quizlet/grpc,yinsu/grpc,a-veitch/grpc,doubi-workshop/grpc,chenbaihu/grpc,y-zeng/grpc,infinit/grpc,surround-io/grpc,pmarks-net/grpc,kpayson64/grpc,stanley-cheung/grpc,gpndata/grpc,zeliard/grpc,stanley-cheung/grpc,grpc/grpc,firebase/grpc,royalharsh/grpc,soltanmm-google/grpc,msiedlarek/grpc,mehrdada/grpc,a11r/grpc,andrewpollock/grpc,stanley-cheung/grpc,jtattermusch/grpc,iMilind/grpc,kskalski/grpc,yonglehou/grpc,Vizerai/grpc,meisterpeeps/grpc,matt-kwong/grpc,infinit/grpc,chenbaihu/grpc,thunderboltsid/grpc,kriswuollett/grpc,Vizerai/grpc,a11r/grpc,grpc/grpc,simonkuang/grpc,a-veitch/grpc,geffzhang/grpc,chenbaihu/grpc,a11r/grpc,w4-sjcho/grpc,makdharma/grpc,ananthonline/grpc,7anner/grpc,nmittler/grpc,chrisdunelm/grpc,carl-mastrangelo/grpc,makdharma/grpc,mway08/grpc,7anner/grpc,dklempner/grpc,w4-sjcho/grpc,andrewpollock/grpc,simonkuang/grpc,xtopsoft/grpc,vjpai/grpc,mzhaom/grpc,tengyifei/grpc,crast/grpc,ofrobots/grpc,leifurhauks/grpc,leifurhauks/grpc,bjori/grpc,ksophocleous/grpc,perumaalgoog/grpc,ncteisen/grpc,malexzx/grpc,adelez/grpc,bogdandrutu/grpc,baylabs/grpc,fuchsia-mirror/third_party-grpc,miselin/grpc,cgvarela/grpc,msiedlarek/grpc,pszemus/grpc,podsvirov/grpc,w4-sjcho/grpc,ncteisen/grpc,simonkuang/grpc,tengyifei/grpc,ksophocleous/grpc,tatsuhiro-t/grpc,tatsuhiro-t/grpc,fichter/grpc,perumaalgoog/grpc,malexzx/grpc,thinkerou/grpc,chrisdunelm/grpc,vsco/grpc,zhimingxie/grpc,fuchsia-mirror/third_party-grpc,podsvirov/grpc,greasypizza/grpc,vjpai/grpc,kriswuollett/grpc,ejona86/grpc,yongni/grpc,makdharma/grpc,greasypizza/grpc,nmittler/grpc,andrewpollock/grpc,7anner/grpc,maxwell-demon/grpc,tempbottle/grpc,kpayson64/grpc,bjori/grpc,dklempner/grpc,yonglehou/grpc,Vizerai/grpc,msmania/grpc,grani/grpc,tamihiro/grpc,donnadionne/grpc,soltanmm-google/grpc,yonglehou/grpc,bogdandrutu/grpc,PeterFaiman/ruby-grpc-minimal,matt-kwong/grpc,wcevans/grpc,yonglehou/grpc,chrisdunelm/grpc,miselin/grpc,wkubiak/grpc,wkubiak/grpc,yang-g/grpc,meisterpeeps/grpc,wcevans/grpc,zhimingxie/grpc,sidrakesh93/grpc,infinit/grpc,philcleveland/grpc,deepaklukose/grpc,sreecha/grpc,larsonmpdx/grpc,kriswuollett/grpc,arkmaxim/grpc,rjshade/grpc,kpayson64/grpc,nathanielmanistaatgoogle/grpc,andrewpollock/grpc,ananthonline/grpc,adelez/grpc,ipylypiv/grpc,thunderboltsid/grpc,nicolasnoble/grpc,daniel-j-born/grpc,podsvirov/grpc,a-veitch/grpc,surround-io/grpc,iMilind/grpc,jboeuf/grpc,bogdandrutu/grpc,infinit/grpc,andrewpollock/grpc,dklempner/grpc,grani/grpc,soltanmm-google/grpc,thunderboltsid/grpc,madongfly/grpc,apolcyn/grpc,JoeWoo/grpc,madongfly/grpc,nathanielmanistaatgoogle/grpc,ejona86/grpc,tempbottle/grpc,kskalski/grpc,ctiller/grpc,chrisdunelm/grpc,vjpai/grpc,pszemus/grpc,wangyikai/grpc,jtattermusch/grpc,yongni/grpc,wangyikai/grpc,jboeuf/grpc,ksophocleous/grpc,jtattermusch/grpc,y-zeng/grpc,maxwell-demon/grpc,mway08/grpc,adelez/grpc,chrisdunelm/grpc,nicolasnoble/grpc,vsco/grpc,nicolasnoble/grpc,murgatroid99/grpc,nathanielmanistaatgoogle/grpc,yangjae/grpc,a11r/grpc,arkmaxim/grpc,yonglehou/grpc,surround-io/grpc,soltanmm/grpc,dgquintas/grpc,muxi/grpc,7anner/grpc,jtattermusch/grpc,geffzhang/grpc,msiedlarek/grpc,ctiller/grpc,VcamX/grpc,ananthonline/grpc,ofrobots/grpc,ofrobots/grpc,simonkuang/grpc,ipylypiv/grpc,sreecha/grpc,quizlet/grpc,nathanielmanistaatgoogle/grpc,carl-mastrangelo/grpc,Crevil/grpc,podsvirov/grpc,ctiller/grpc,philcleveland/grpc,a11r/grpc,soltanmm/grpc,greasypizza/grpc,yang-g/grpc,yangjae/grpc,geffzhang/grpc,ananthonline/grpc,dgquintas/grpc,nicolasnoble/grpc,maxwell-demon/grpc,greasypizza/grpc,yinsu/grpc,donnadionne/grpc,crast/grpc,a-veitch/grpc,LuminateWireless/grpc,Crevil/grpc,mway08/grpc,maxwell-demon/grpc,apolcyn/grpc,vjpai/grpc,PeterFaiman/ruby-grpc-minimal,y-zeng/grpc,crast/grpc,gpndata/grpc,wcevans/grpc,wcevans/grpc,msmania/grpc,mway08/grpc,zhimingxie/grpc,nmittler/grpc,daniel-j-born/grpc,a-veitch/grpc,bogdandrutu/grpc,ncteisen/grpc,perumaalgoog/grpc,hstefan/grpc,soltanmm/grpc,wkubiak/grpc,mzhaom/grpc,sreecha/grpc,ctiller/grpc,meisterpeeps/grpc,zeliard/grpc,yang-g/grpc,donnadionne/grpc,thunderboltsid/grpc,muxi/grpc,fichter/grpc,goldenbull/grpc,royalharsh/grpc,grpc/grpc,chrisdunelm/grpc,grpc/grpc,kriswuollett/grpc,leifurhauks/grpc,apolcyn/grpc,kpayson64/grpc,surround-io/grpc,firebase/grpc,fichter/grpc,dklempner/grpc,w4-sjcho/grpc,meisterpeeps/grpc,kskalski/grpc,meisterpeeps/grpc,makdharma/grpc,carl-mastrangelo/grpc,infinit/grpc,JoeWoo/grpc,mzhaom/grpc,VcamX/grpc,jcanizales/grpc,kskalski/grpc,ipylypiv/grpc,fuchsia-mirror/third_party-grpc,mway08/grpc,mehrdada/grpc,firebase/grpc,rjshade/grpc,vjpai/grpc,kriswuollett/grpc,yinsu/grpc,donnadionne/grpc,quizlet/grpc,Juzley/grpc,carl-mastrangelo/grpc,daniel-j-born/grpc,murgatroid99/grpc,deepaklukose/grpc,philcleveland/grpc,mzhaom/grpc,yinsu/grpc,JoeWoo/grpc,perumaalgoog/grpc,murgatroid99/grpc,vsco/grpc,thunderboltsid/grpc,donnadionne/grpc,goldenbull/grpc,iMilind/grpc,murgatroid99/grpc,rjshade/grpc,MakMukhi/grpc,Juzley/grpc,JoeWoo/grpc,firebase/grpc,madongfly/grpc,Vizerai/grpc,nicolasnoble/grpc,fuchsia-mirror/third_party-grpc,wkubiak/grpc,geffzhang/grpc,pmarks-net/grpc,gpndata/grpc,mehrdada/grpc,jcanizales/grpc,surround-io/grpc,xtopsoft/grpc,7anner/grpc,adelez/grpc,Vizerai/grpc,kskalski/grpc,madongfly/grpc,firebase/grpc,perumaalgoog/grpc,7anner/grpc,Vizerai/grpc,pszemus/grpc,ipylypiv/grpc,tamihiro/grpc,wangyikai/grpc,nicolasnoble/grpc,matt-kwong/grpc,PeterFaiman/ruby-grpc-minimal,kpayson64/grpc,rjshade/grpc,jtattermusch/grpc,dklempner/grpc,stanley-cheung/grpc,deepaklukose/grpc,ofrobots/grpc,bjori/grpc,yinsu/grpc,thinkerou/grpc,nicolasnoble/grpc,ipylypiv/grpc,sreecha/grpc,Juzley/grpc,yinsu/grpc,yongni/grpc,firebase/grpc,yongni/grpc,chenbaihu/grpc,kumaralokgithub/grpc,doubi-workshop/grpc,tempbottle/grpc,ofrobots/grpc,sidrakesh93/grpc,y-zeng/grpc,rjshade/grpc,grpc/grpc,nmittler/grpc,jtattermusch/grpc,wkubiak/grpc,zhimingxie/grpc,leifurhauks/grpc,fuchsia-mirror/third_party-grpc,Vizerai/grpc,surround-io/grpc,tengyifei/grpc,larsonmpdx/grpc,greasypizza/grpc,wcevans/grpc,cgvarela/grpc,thinkerou/grpc,apolcyn/grpc,tempbottle/grpc,stanley-cheung/grpc,soltanmm/grpc,yonglehou/grpc,vsco/grpc,yugui/grpc,gpndata/grpc,jtattermusch/grpc,matt-kwong/grpc,geffzhang/grpc,VcamX/grpc,ofrobots/grpc,madongfly/grpc,donnadionne/grpc,vjpai/grpc,philcleveland/grpc,bjori/grpc,philcleveland/grpc,yongni/grpc,iMilind/grpc,msmania/grpc,sreecha/grpc,royalharsh/grpc,apolcyn/grpc,madongfly/grpc,thinkerou/grpc,jcanizales/grpc,Crevil/grpc,perumaalgoog/grpc,kriswuollett/grpc,chrisdunelm/grpc,tatsuhiro-t/grpc,nathanielmanistaatgoogle/grpc,ksophocleous/grpc,kumaralokgithub/grpc,geffzhang/grpc,miselin/grpc,arkmaxim/grpc,carl-mastrangelo/grpc,kumaralokgithub/grpc,yugui/grpc,ananthonline/grpc,yinsu/grpc,dgquintas/grpc,bogdandrutu/grpc,chrisdunelm/grpc,carl-mastrangelo/grpc,doubi-workshop/grpc,muxi/grpc,stanley-cheung/grpc,deepaklukose/grpc,nicolasnoble/grpc,mehrdada/grpc,yugui/grpc,pmarks-net/grpc,yongni/grpc,muxi/grpc,wcevans/grpc,royalharsh/grpc,soltanmm-google/grpc,simonkuang/grpc,matt-kwong/grpc,ofrobots/grpc,madongfly/grpc,cgvarela/grpc,pmarks-net/grpc,mzhaom/grpc,Vizerai/grpc,MakMukhi/grpc,daniel-j-born/grpc,donnadionne/grpc,grpc/grpc,maxwell-demon/grpc,fuchsia-mirror/third_party-grpc,jcanizales/grpc,gpndata/grpc,zhimingxie/grpc,pmarks-net/grpc,ksophocleous/grpc,yang-g/grpc,vsco/grpc,yonglehou/grpc,PeterFaiman/ruby-grpc-minimal,tamihiro/grpc,thinkerou/grpc,sidrakesh93/grpc,PeterFaiman/ruby-grpc-minimal,carl-mastrangelo/grpc,ctiller/grpc,ejona86/grpc,meisterpeeps/grpc,ncteisen/grpc,kriswuollett/grpc,jboeuf/grpc,muxi/grpc,royalharsh/grpc,yang-g/grpc,yangjae/grpc,iMilind/grpc,yonglehou/grpc,baylabs/grpc,sidrakesh93/grpc,w4-sjcho/grpc,ctiller/grpc,deepaklukose/grpc,daniel-j-born/grpc,a11r/grpc,jtattermusch/grpc,JoeWoo/grpc,MakMukhi/grpc,andrewpollock/grpc,sreecha/grpc,ppietrasa/grpc,greasypizza/grpc,LuminateWireless/grpc,PeterFaiman/ruby-grpc-minimal,vjpai/grpc,baylabs/grpc,arkmaxim/grpc,soltanmm-google/grpc,jboeuf/grpc,LuminateWireless/grpc,soltanmm/grpc,gpndata/grpc,PeterFaiman/ruby-grpc-minimal,wangyikai/grpc,tatsuhiro-t/grpc,surround-io/grpc,zhimingxie/grpc,madongfly/grpc,cgvarela/grpc,bogdandrutu/grpc,tengyifei/grpc,sidrakesh93/grpc,ppietrasa/grpc,wcevans/grpc,doubi-workshop/grpc,stanley-cheung/grpc,chrisdunelm/grpc,deepaklukose/grpc,soltanmm-google/grpc,ananthonline/grpc,deepaklukose/grpc,ppietrasa/grpc,apolcyn/grpc,fuchsia-mirror/third_party-grpc,matt-kwong/grpc,simonkuang/grpc,tamihiro/grpc,ejona86/grpc,doubi-workshop/grpc,daniel-j-born/grpc,Vizerai/grpc,jtattermusch/grpc,murgatroid99/grpc,pmarks-net/grpc,kskalski/grpc,wcevans/grpc,chenbaihu/grpc,mway08/grpc,apolcyn/grpc,stanley-cheung/grpc,nathanielmanistaatgoogle/grpc,tempbottle/grpc,arkmaxim/grpc,infinit/grpc,zeliard/grpc,cgvarela/grpc,pmarks-net/grpc,yang-g/grpc,philcleveland/grpc,yang-g/grpc,ofrobots/grpc,wangyikai/grpc,bogdandrutu/grpc,tengyifei/grpc,zeliard/grpc,ksophocleous/grpc,wcevans/grpc,geffzhang/grpc,mehrdada/grpc,Juzley/grpc,yangjae/grpc,leifurhauks/grpc,ejona86/grpc,pszemus/grpc,ipylypiv/grpc,matt-kwong/grpc,a11r/grpc,ipylypiv/grpc,podsvirov/grpc,zhimingxie/grpc,grpc/grpc,kriswuollett/grpc,andrewpollock/grpc,daniel-j-born/grpc,yangjae/grpc,grani/grpc,tempbottle/grpc,kumaralokgithub/grpc,LuminateWireless/grpc,grpc/grpc,VcamX/grpc,ctiller/grpc,zeliard/grpc,chrisdunelm/grpc,murgatroid99/grpc,goldenbull/grpc,jboeuf/grpc,donnadionne/grpc,nmittler/grpc,Vizerai/grpc,quizlet/grpc,yugui/grpc,muxi/grpc,kpayson64/grpc,infinit/grpc,deepaklukose/grpc,quizlet/grpc,daniel-j-born/grpc,y-zeng/grpc,ejona86/grpc,madongfly/grpc,pszemus/grpc,arkmaxim/grpc,yinsu/grpc,soltanmm-google/grpc,soltanmm/grpc,pszemus/grpc,PeterFaiman/ruby-grpc-minimal,tatsuhiro-t/grpc,greasypizza/grpc,hstefan/grpc,chenbaihu/grpc,yugui/grpc,nmittler/grpc,tengyifei/grpc,fichter/grpc,donnadionne/grpc,greasypizza/grpc,hstefan/grpc,ppietrasa/grpc,bjori/grpc,LuminateWireless/grpc,tamihiro/grpc,Crevil/grpc,ppietrasa/grpc,LuminateWireless/grpc,simonkuang/grpc,chenbaihu/grpc,a-veitch/grpc,jtattermusch/grpc,andrewpollock/grpc,soltanmm/grpc,adelez/grpc,thinkerou/grpc,jboeuf/grpc,grpc/grpc,miselin/grpc,sreecha/grpc,grani/grpc,iMilind/grpc,kpayson64/grpc,muxi/grpc,msmania/grpc,nicolasnoble/grpc,dklempner/grpc,malexzx/grpc,jcanizales/grpc,carl-mastrangelo/grpc,tempbottle/grpc,kumaralokgithub/grpc,jboeuf/grpc,jtattermusch/grpc,JoeWoo/grpc,nicolasnoble/grpc,daniel-j-born/grpc,vjpai/grpc,malexzx/grpc,ananthonline/grpc,grpc/grpc,msiedlarek/grpc,podsvirov/grpc,ncteisen/grpc,infinit/grpc,larsonmpdx/grpc,soltanmm/grpc,tamihiro/grpc,murgatroid99/grpc,fuchsia-mirror/third_party-grpc,podsvirov/grpc,jcanizales/grpc,crast/grpc,malexzx/grpc,kpayson64/grpc,msiedlarek/grpc,grani/grpc,msmania/grpc,vsco/grpc,larsonmpdx/grpc,ipylypiv/grpc,malexzx/grpc,apolcyn/grpc,mehrdada/grpc,wangyikai/grpc,msiedlarek/grpc,dgquintas/grpc,jboeuf/grpc,thinkerou/grpc,fuchsia-mirror/third_party-grpc,tengyifei/grpc,7anner/grpc,leifurhauks/grpc,podsvirov/grpc,pszemus/grpc,doubi-workshop/grpc,wkubiak/grpc,rjshade/grpc,andrewpollock/grpc,mzhaom/grpc,maxwell-demon/grpc,wkubiak/grpc,jboeuf/grpc,a-veitch/grpc,thinkerou/grpc,perumaalgoog/grpc,kumaralokgithub/grpc,vsco/grpc,fichter/grpc,7anner/grpc,bjori/grpc,stanley-cheung/grpc,philcleveland/grpc,nmittler/grpc,a-veitch/grpc,arkmaxim/grpc,yang-g/grpc,baylabs/grpc,deepaklukose/grpc,malexzx/grpc,yangjae/grpc,dgquintas/grpc,a11r/grpc,a11r/grpc,greasypizza/grpc,zhimingxie/grpc,grpc/grpc,crast/grpc,matt-kwong/grpc,muxi/grpc,jtattermusch/grpc,donnadionne/grpc,msiedlarek/grpc,vjpai/grpc,dklempner/grpc,murgatroid99/grpc,tatsuhiro-t/grpc,miselin/grpc,yongni/grpc,grani/grpc,hstefan/grpc,murgatroid99/grpc,ctiller/grpc,gpndata/grpc,malexzx/grpc,xtopsoft/grpc,ncteisen/grpc,y-zeng/grpc,wkubiak/grpc,ejona86/grpc,iMilind/grpc,ncteisen/grpc,xtopsoft/grpc,goldenbull/grpc,goldenbull/grpc,thunderboltsid/grpc,Crevil/grpc,kskalski/grpc,hstefan/grpc,a-veitch/grpc,baylabs/grpc,bogdandrutu/grpc,stanley-cheung/grpc,w4-sjcho/grpc,goldenbull/grpc,crast/grpc,ctiller/grpc,quizlet/grpc,pmarks-net/grpc,msiedlarek/grpc,infinit/grpc,goldenbull/grpc,Juzley/grpc,kumaralokgithub/grpc,thunderboltsid/grpc,muxi/grpc,Crevil/grpc,baylabs/grpc,matt-kwong/grpc,carl-mastrangelo/grpc,bjori/grpc,miselin/grpc,surround-io/grpc,dgquintas/grpc,arkmaxim/grpc,cgvarela/grpc,pszemus/grpc,Juzley/grpc,malexzx/grpc,mehrdada/grpc,tatsuhiro-t/grpc,bjori/grpc,Vizerai/grpc,ctiller/grpc,chrisdunelm/grpc,tamihiro/grpc,MakMukhi/grpc,sidrakesh93/grpc,leifurhauks/grpc,adelez/grpc,VcamX/grpc,kskalski/grpc,ncteisen/grpc,zeliard/grpc,7anner/grpc,adelez/grpc,yinsu/grpc,firebase/grpc,grani/grpc,philcleveland/grpc,nathanielmanistaatgoogle/grpc,baylabs/grpc,ananthonline/grpc,pszemus/grpc,kpayson64/grpc,yugui/grpc,mehrdada/grpc,geffzhang/grpc,royalharsh/grpc,PeterFaiman/ruby-grpc-minimal,xtopsoft/grpc,yugui/grpc,thinkerou/grpc,miselin/grpc,maxwell-demon/grpc,mehrdada/grpc,ppietrasa/grpc,kumaralokgithub/grpc,firebase/grpc,pmarks-net/grpc,hstefan/grpc,thinkerou/grpc,y-zeng/grpc,larsonmpdx/grpc,doubi-workshop/grpc,ctiller/grpc,cgvarela/grpc,larsonmpdx/grpc,makdharma/grpc,adelez/grpc,jcanizales/grpc,pszemus/grpc,dgquintas/grpc,mzhaom/grpc,yangjae/grpc,JoeWoo/grpc,soltanmm/grpc,nathanielmanistaatgoogle/grpc,VcamX/grpc,mway08/grpc,ejona86/grpc,firebase/grpc,vjpai/grpc,fuchsia-mirror/third_party-grpc,MakMukhi/grpc,thunderboltsid/grpc,ncteisen/grpc,wangyikai/grpc,soltanmm-google/grpc,carl-mastrangelo/grpc,kriswuollett/grpc,LuminateWireless/grpc,firebase/grpc
|
08240682ef0de9e5fcc89ca9409ab3ff803ff497
|
stromx/runtime/test/ZipFileOutputTest.cpp
|
stromx/runtime/test/ZipFileOutputTest.cpp
|
/*
* Copyright 2012 Matthias Fuchs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stromx/runtime/Exception.h"
#include "stromx/runtime/ZipFileOutput.h"
#include "stromx/runtime/ZipFileInput.h"
#include "stromx/runtime/test/ZipFileOutputTest.h"
CPPUNIT_TEST_SUITE_REGISTRATION (stromx::runtime::ZipFileOutputTest);
namespace stromx
{
namespace runtime
{
void ZipFileOutputTest::testText()
{
ZipFileOutput output("ZipFileOutputTest_testText.zip");
CPPUNIT_ASSERT_THROW(output.text(), WrongState);
output.initialize("");
output.text() << "Test";
CPPUNIT_ASSERT_EQUAL(std::string("Test"), output.getText());
}
void ZipFileOutputTest::testFile()
{
ZipFileOutput output("ZipFileOutputTest_testFile.zip");
CPPUNIT_ASSERT_THROW(output.file(), WrongState);
// first file
output.initialize("testFile1");
CPPUNIT_ASSERT_THROW(output.file(), WrongState);
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 5;
// try a second file
output.initialize("testFile2");
output.openFile(".txt", OutputProvider::TEXT);
output.file() << 6;
}
void ZipFileOutputTest::testFileDuplicate()
{
ZipFileOutput output("ZipFileOutputTest_testFileDuplicate.zip");
// first file
output.initialize("testFile");
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 5;
// try a second file with the same name
output.initialize("testFile");
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 6;
}
void ZipFileOutputTest::testGetFilename()
{
ZipFileOutput output("ZipFileOutputTest_testGetFilename.zip");
CPPUNIT_ASSERT_THROW(output.getFilename(), WrongState);
output.initialize("testGetFilename");
CPPUNIT_ASSERT_EQUAL(std::string(""), output.getFilename());
output.openFile(".bin", OutputProvider::BINARY);
CPPUNIT_ASSERT_EQUAL(std::string("testGetFilename.bin"), output.getFilename());
}
void ZipFileOutputTest::testNoAccess()
{
bool exceptionWasThrown = false;
// FIXME: Apparently either the constructor (on openSUSE Factory) or
// or the member close() (on all other systems) of ZipFileOutput
// throws a FileAccessFailed exception. This is due to the varying
// behavior of libzip on different distributions.
try
{
ZipFileOutput output("/root/test/ZipFileOutputTest_testNoAccess.zip");
output.initialize("testFile");
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 5;
output.close();
}
catch (FileAccessFailed &)
{
exceptionWasThrown = true;
}
CPPUNIT_ASSERT(exceptionWasThrown);
}
void ZipFileOutputTest::testOverwrite()
{
{
ZipFileOutput output("ZipFileOutputTest_testOverwrite.zip");
output.initialize("testFile1");
output.openFile(".bin", OutputProvider::BINARY);
}
{
ZipFileOutput output("ZipFileOutputTest_testOverwrite.zip");
output.initialize("testFile1");
output.openFile(".bin", OutputProvider::BINARY);
}
}
}
}
|
/*
* Copyright 2012 Matthias Fuchs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stromx/runtime/Exception.h"
#include "stromx/runtime/ZipFileOutput.h"
#include "stromx/runtime/ZipFileInput.h"
#include "stromx/runtime/test/ZipFileOutputTest.h"
CPPUNIT_TEST_SUITE_REGISTRATION (stromx::runtime::ZipFileOutputTest);
namespace stromx
{
namespace runtime
{
void ZipFileOutputTest::testText()
{
ZipFileOutput output("ZipFileOutputTest_testText.zip");
CPPUNIT_ASSERT_THROW(output.text(), WrongState);
output.initialize("");
output.text() << "Test";
CPPUNIT_ASSERT_EQUAL(std::string("Test"), output.getText());
}
void ZipFileOutputTest::testFile()
{
ZipFileOutput output("ZipFileOutputTest_testFile.zip");
CPPUNIT_ASSERT_THROW(output.file(), WrongState);
// first file
output.initialize("testFile1");
CPPUNIT_ASSERT_THROW(output.file(), WrongState);
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 5;
// try a second file
output.initialize("testFile2");
output.openFile(".txt", OutputProvider::TEXT);
output.file() << 6;
}
void ZipFileOutputTest::testFileDuplicate()
{
ZipFileOutput output("ZipFileOutputTest_testFileDuplicate.zip");
// first file
output.initialize("testFile");
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 5;
// try a second file with the same name
output.initialize("testFile");
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 6;
}
void ZipFileOutputTest::testGetFilename()
{
ZipFileOutput output("ZipFileOutputTest_testGetFilename.zip");
CPPUNIT_ASSERT_THROW(output.getFilename(), WrongState);
output.initialize("testGetFilename");
CPPUNIT_ASSERT_EQUAL(std::string(""), output.getFilename());
output.openFile(".bin", OutputProvider::BINARY);
CPPUNIT_ASSERT_EQUAL(std::string("testGetFilename.bin"), output.getFilename());
}
void ZipFileOutputTest::testNoAccess()
{
bool exceptionWasThrown = false;
// FIXME: Apparently either the constructor (on openSUSE Factory) or
// or the member close() (on all other systems) of ZipFileOutput
// throws a FileAccessFailed exception. This is due to the varying
// behavior of different versions of libzip.
try
{
ZipFileOutput output("/root/test/ZipFileOutputTest_testNoAccess.zip");
output.initialize("testFile");
output.openFile(".bin", OutputProvider::BINARY);
output.file() << 5;
output.close();
}
catch (FileAccessFailed &)
{
exceptionWasThrown = true;
}
CPPUNIT_ASSERT(exceptionWasThrown);
}
void ZipFileOutputTest::testOverwrite()
{
{
ZipFileOutput output("ZipFileOutputTest_testOverwrite.zip");
output.initialize("testFile1");
output.openFile(".bin", OutputProvider::BINARY);
}
{
ZipFileOutput output("ZipFileOutputTest_testOverwrite.zip");
output.initialize("testFile1");
output.openFile(".bin", OutputProvider::BINARY);
}
}
}
}
|
Fix comment
|
Fix comment
|
C++
|
apache-2.0
|
uboot/stromx,uboot/stromx
|
b51d736268160909964ae7b95d0ea8db073bd2df
|
include/mantella_bits/optimisationProblem/roboticsOptimisationProblem/robotModel.hpp
|
include/mantella_bits/optimisationProblem/roboticsOptimisationProblem/robotModel.hpp
|
#pragma once
// Armadillo
#include <armadillo>
// Mantella
#include <mantella_bits/helper/printable.hpp>
namespace mant {
namespace robotics {
class RobotModel : public Printable {
public:
arma::uword numberOfActiveJoints_;
arma::uword numberOfRedundantJoints_;
explicit RobotModel(
const arma::uword numberOfActiveJoints,
const arma::uword numberOfRedundantJoint);
void setMinimalActiveJointsActuation(
const arma::Row<double> minimalActiveJointsActuation);
void setMaximalActiveJointsActuation(
const arma::Row<double> maximalActiveJointsActuation);
arma::Row<double> getMinimalActiveJointsActuation() const;
arma::Row<double> getMaximalActiveJointsActuation() const;
void setMinimalRedundantJointsActuation(
const arma::Row<double> minimalRedundantJointsActuation);
void setMaximalRedundantJointsActuation(
const arma::Row<double> maximalRedundantJointsActuation);
arma::Row<double> getMinimalRedundantJointsActuation() const;
arma::Row<double> getMaximalRedundantJointsActuation() const;
arma::Cube<double> getModel(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const;
arma::Row<double> getActuation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const;
double getEndEffectorPoseError(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const;
virtual ~RobotModel() = default;
protected:
arma::Row<double> minimalActiveJointsActuation_;
arma::Row<double> maximalActiveJointsActuation_;
arma::Row<double> minimalRedundantJointsActuation_;
arma::Row<double> maximalRedundantJointsActuation_;
virtual arma::Cube<double> getModelImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const = 0;
virtual arma::Row<double> getActuationImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const = 0;
virtual double getEndEffectorPoseErrorImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const = 0;
};
}
}
|
#pragma once
// Armadillo
#include <armadillo>
// Mantella
#include <mantella_bits/helper/printable.hpp>
namespace mant {
namespace robotics {
class RobotModel : public Printable {
public:
const arma::uword numberOfActiveJoints_;
const arma::uword numberOfRedundantJoints_;
explicit RobotModel(
const arma::uword numberOfActiveJoints,
const arma::uword numberOfRedundantJoint);
void setMinimalActiveJointsActuation(
const arma::Row<double> minimalActiveJointsActuation);
void setMaximalActiveJointsActuation(
const arma::Row<double> maximalActiveJointsActuation);
arma::Row<double> getMinimalActiveJointsActuation() const;
arma::Row<double> getMaximalActiveJointsActuation() const;
void setMinimalRedundantJointsActuation(
const arma::Row<double> minimalRedundantJointsActuation);
void setMaximalRedundantJointsActuation(
const arma::Row<double> maximalRedundantJointsActuation);
arma::Row<double> getMinimalRedundantJointsActuation() const;
arma::Row<double> getMaximalRedundantJointsActuation() const;
arma::Cube<double> getModel(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const;
arma::Row<double> getActuation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const;
double getEndEffectorPoseError(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const;
virtual ~RobotModel() = default;
protected:
arma::Row<double> minimalActiveJointsActuation_;
arma::Row<double> maximalActiveJointsActuation_;
arma::Row<double> minimalRedundantJointsActuation_;
arma::Row<double> maximalRedundantJointsActuation_;
virtual arma::Cube<double> getModelImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const = 0;
virtual arma::Row<double> getActuationImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const = 0;
virtual double getEndEffectorPoseErrorImplementation(
const arma::Col<double>& endEffectorPose,
const arma::Row<double>& redundantJointsActuation) const = 0;
};
}
}
|
Set numberOfActiveJoints_ and numberOfRedundantJoints_ to be const again
|
Set numberOfActiveJoints_ and numberOfRedundantJoints_ to be const again
|
C++
|
mit
|
SebastianNiemann/Mantella,SebastianNiemann/Mantella,Mantella/Mantella,Mantella/Mantella,Mantella/Mantella,SebastianNiemann/Mantella
|
d6652a8814c428c232064c2c76ae2c1554bca431
|
Wangscape/Main.cpp
|
Wangscape/Main.cpp
|
#include <iostream>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <fstream>
#include <istream>
#include "Options.h"
#include "TilesetGenerator.h"
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cout << "Usage: Wangscape rel/path/to/options.json\n";
exit(1);
}
else
{
std::string filename(argv[1]);
std::ifstream ifs(filename);
if (!ifs.good())
{
std::cout << "Could not read file: " << filename.c_str() << "\n";
exit(1);
}
rapidjson::IStreamWrapper isw(ifs);
rapidjson::Document options_document;
options_document.ParseStream(isw);
if (options_document.HasParseError())
{
std::cout << "Options document has parse error at offset "<< (unsigned)options_document.GetErrorOffset() <<":\n";
std::cout << GetParseError_En(options_document.GetParseError()) << "\n";
}
// At present *no* validation is performed!
//OptionsValidator ov(&options_document);
//if (ov.hasError())
//{
// std::cout << "Could not generate tileset.\n";
// std::cout << ov.getError().c_str();
//}
const Options options(options_document);
TilesetGenerator tg;
tg.generate(options);
}
}
|
#include <iostream>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <fstream>
#include <istream>
#include "Options.h"
#include "TilesetGenerator.h"
#include "TileGenerator.h"
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cout << "Usage: Wangscape rel/path/to/options.json\n";
exit(1);
}
else
{
std::string filename(argv[1]);
std::ifstream ifs(filename);
if (!ifs.good())
{
std::cout << "Could not read file: " << filename.c_str() << "\n";
exit(1);
}
rapidjson::IStreamWrapper isw(ifs);
rapidjson::Document options_document;
options_document.ParseStream(isw);
if (options_document.HasParseError())
{
std::cout << "Options document has parse error at offset "<< (unsigned)options_document.GetErrorOffset() <<":\n";
std::cout << GetParseError_En(options_document.GetParseError()) << "\n";
}
// At present *no* validation is performed!
//OptionsValidator ov(&options_document);
//if (ov.hasError())
//{
// std::cout << "Could not generate tileset.\n";
// std::cout << ov.getError().c_str();
//}
const Options options(options_document);
TilesetGenerator tg;
tg.generate(options,TileGenerator::generate);
}
}
|
Fix building
|
Fix building
|
C++
|
mit
|
serin-delaunay/Wangscape,Wangscape/Wangscape,Wangscape/Wangscape,serin-delaunay/Wangscape,Wangscape/Wangscape
|
a33ebf055eecf32560e4265041c3392a1760e176
|
modules/perception/obstacle/fusion/probabilistic_fusion/probabilistic_fusion_test.cc
|
modules/perception/obstacle/fusion/probabilistic_fusion/probabilistic_fusion_test.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/fusion/probabilistic_fusion/probabilistic_fusion.h"
#include <gtest/gtest.h>
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/obstacle/base/object.h"
#include "modules/perception/obstacle/fusion/interface/base_fusion.h"
namespace apollo {
namespace perception {
TEST(ProbabilisticFusionTest, probabilistic_fusion_test) {
FLAGS_work_root = "modules/perception";
FLAGS_config_manager_path = "./conf/config_manager.config";
AERROR << "start probabilistic_fusion_test\n";
ProbabilisticFusion *probabilistic_fusion = new ProbabilisticFusion();
EXPECT_TRUE(probabilistic_fusion->Init());
AERROR << "After fusion init";
std::vector<SensorObjects> sensor_objects;
std::vector<ObjectPtr> fused_objects;
sensor_objects.resize(1);
sensor_objects[0].sensor_type = VELODYNE_64;
sensor_objects[0].seq_num = 0;
sensor_objects[0].timestamp = 0.0;
sensor_objects[0].sensor2world_pose = Eigen::Matrix4d::Identity();
EXPECT_TRUE(probabilistic_fusion->Fuse(sensor_objects, &fused_objects));
double timestamp = 0;
ObjectPtr moc_obj(new Object());
Eigen::Vector3d position(20, 0, 0);
Eigen::Vector3d dir(1, 0, 0);
Eigen::Vector3d velocity(10, 0, 0);
ObjectType type = VEHICLE;
moc_obj->center = position;
moc_obj->anchor_point = position;
moc_obj->length = 4;
moc_obj->width = 2;
moc_obj->height = 2;
moc_obj->velocity = velocity;
moc_obj->track_id = 1;
moc_obj->type = type;
moc_obj->polygon.resize(1);
moc_obj->polygon.points[0].x = position(0);
moc_obj->polygon.points[0].y = position(1);
moc_obj->polygon.points[0].z = position(2);
std::vector<SensorObjects> sensor_objects2;
sensor_objects2.resize(1);
sensor_objects2[0].sensor_type = RADAR;
sensor_objects2[0].seq_num = 0;
sensor_objects2[0].sensor2world_pose = Eigen::Matrix4d::Identity();
ObjectPtr obj(new Object());
ObjectPtr radar_obj(new Object());
obj->clone(*moc_obj);
for (int i = 0; i < 10; i++) {
AERROR << "test " << i;
position = position + velocity * 0.05;
timestamp += 0.05;
radar_obj->center = position;
radar_obj->anchor_point = position;
radar_obj->velocity = velocity;
radar_obj->track_id = 1;
radar_obj->polygon.resize(1);
radar_obj->polygon.points[0].x = position(0);
radar_obj->polygon.points[0].y = position(1);
radar_obj->polygon.points[0].z = position(2);
sensor_objects2[0].timestamp = timestamp;
sensor_objects2[0].objects.resize(1);
sensor_objects2[0].objects[0] = radar_obj;
EXPECT_TRUE(probabilistic_fusion->Fuse(sensor_objects2, &fused_objects));
obj->clone(*moc_obj);
position = position + velocity * 0.05;
timestamp += 0.05;
sensor_objects[0].timestamp = timestamp;
obj->center = position;
obj->anchor_point = position;
obj->polygon.points[0].x = position(0);
obj->polygon.points[0].y = position(1);
obj->polygon.points[0].z = position(2);
sensor_objects[0].objects.resize(1);
sensor_objects[0].objects[0] = obj;
EXPECT_TRUE(probabilistic_fusion->Fuse(sensor_objects, &fused_objects));
EXPECT_EQ(fused_objects.size(), 1);
EXPECT_DOUBLE_EQ(fused_objects[0]->length, obj->length);
EXPECT_DOUBLE_EQ(fused_objects[0]->width, obj->width);
EXPECT_DOUBLE_EQ(fused_objects[0]->height, obj->height);
EXPECT_TRUE((fused_objects[0]->center - obj->center).norm() < 1.0e-2);
EXPECT_TRUE((fused_objects[0]->velocity - obj->velocity).norm() < 1.0e-2);
}
AINFO << "end probabilistic_fusion_test\n";
}
} // namespace perception
} // namespace apollo
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/fusion/probabilistic_fusion/probabilistic_fusion.h"
#include <gtest/gtest.h>
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/obstacle/base/object.h"
#include "modules/perception/obstacle/fusion/interface/base_fusion.h"
namespace apollo {
namespace perception {
TEST(ProbabilisticFusionTest, probabilistic_fusion_test) {
FLAGS_work_root = "modules/perception";
FLAGS_config_manager_path = "./conf/config_manager.config";
AINFO << "start probabilistic_fusion_test\n";
ProbabilisticFusion *probabilistic_fusion = new ProbabilisticFusion();
EXPECT_TRUE(probabilistic_fusion->Init());
AINFO << "After fusion init";
std::vector<SensorObjects> sensor_objects;
std::vector<ObjectPtr> fused_objects;
sensor_objects.resize(1);
sensor_objects[0].sensor_type = VELODYNE_64;
sensor_objects[0].seq_num = 0;
sensor_objects[0].timestamp = 0.0;
sensor_objects[0].sensor2world_pose = Eigen::Matrix4d::Identity();
EXPECT_TRUE(probabilistic_fusion->Fuse(sensor_objects, &fused_objects));
double timestamp = 0;
ObjectPtr moc_obj(new Object());
Eigen::Vector3d position(20, 0, 0);
Eigen::Vector3d dir(1, 0, 0);
Eigen::Vector3d velocity(10, 0, 0);
ObjectType type = VEHICLE;
moc_obj->center = position;
moc_obj->anchor_point = position;
moc_obj->length = 4;
moc_obj->width = 2;
moc_obj->height = 2;
moc_obj->velocity = velocity;
moc_obj->track_id = 1;
moc_obj->type = type;
moc_obj->polygon.resize(1);
moc_obj->polygon.points[0].x = position(0);
moc_obj->polygon.points[0].y = position(1);
moc_obj->polygon.points[0].z = position(2);
std::vector<SensorObjects> sensor_objects2;
sensor_objects2.resize(1);
sensor_objects2[0].sensor_type = RADAR;
sensor_objects2[0].seq_num = 0;
sensor_objects2[0].sensor2world_pose = Eigen::Matrix4d::Identity();
ObjectPtr obj(new Object());
ObjectPtr radar_obj(new Object());
obj->clone(*moc_obj);
for (int i = 0; i < 10; i++) {
position = position + velocity * 0.05;
timestamp += 0.05;
radar_obj->center = position;
radar_obj->anchor_point = position;
radar_obj->velocity = velocity;
radar_obj->track_id = 1;
radar_obj->polygon.resize(1);
radar_obj->polygon.points[0].x = position(0);
radar_obj->polygon.points[0].y = position(1);
radar_obj->polygon.points[0].z = position(2);
sensor_objects2[0].timestamp = timestamp;
sensor_objects2[0].objects.resize(1);
sensor_objects2[0].objects[0] = radar_obj;
EXPECT_TRUE(probabilistic_fusion->Fuse(sensor_objects2, &fused_objects));
obj->clone(*moc_obj);
position = position + velocity * 0.05;
timestamp += 0.05;
sensor_objects[0].timestamp = timestamp;
obj->center = position;
obj->anchor_point = position;
obj->polygon.points[0].x = position(0);
obj->polygon.points[0].y = position(1);
obj->polygon.points[0].z = position(2);
sensor_objects[0].objects.resize(1);
sensor_objects[0].objects[0] = obj;
EXPECT_TRUE(probabilistic_fusion->Fuse(sensor_objects, &fused_objects));
EXPECT_EQ(fused_objects.size(), 1);
EXPECT_DOUBLE_EQ(fused_objects[0]->length, obj->length);
EXPECT_DOUBLE_EQ(fused_objects[0]->width, obj->width);
EXPECT_DOUBLE_EQ(fused_objects[0]->height, obj->height);
EXPECT_TRUE((fused_objects[0]->center - obj->center).norm() < 1.0e-2);
EXPECT_TRUE((fused_objects[0]->velocity - obj->velocity).norm() < 1.0e-2);
}
AINFO << "end probabilistic_fusion_test\n";
}
} // namespace perception
} // namespace apollo
|
remove test debug log.
|
perception: remove test debug log.
|
C++
|
apache-2.0
|
startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo
|
4230da6fc517ee2a0568dba969060cb90a9ac87c
|
lib/Analysis/GRState.cpp
|
lib/Analysis/GRState.cpp
|
//= GRState*cpp - Path-Sens. "State" for tracking valuues -----*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines SymbolID, ExprBindKey, and GRState*
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/GRStateTrait.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
// Give the vtable for ConstraintManager somewhere to live.
ConstraintManager::~ConstraintManager() {}
GRStateManager::~GRStateManager() {
for (std::vector<GRState::Printer*>::iterator I=Printers.begin(),
E=Printers.end(); I!=E; ++I)
delete *I;
for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
I!=E; ++I)
I->second.second(I->second.first);
}
const GRState*
GRStateManager::RemoveDeadBindings(const GRState* St, Stmt* Loc,
const LiveVariables& Liveness,
DeadSymbolsTy& DSymbols) {
// This code essentially performs a "mark-and-sweep" of the VariableBindings.
// The roots are any Block-level exprs and Decls that our liveness algorithm
// tells us are live. We then see what Decls they may reference, and keep
// those around. This code more than likely can be made faster, and the
// frequency of which this method is called should be experimented with
// for optimum performance.
llvm::SmallVector<const MemRegion*, 10> RegionRoots;
StoreManager::LiveSymbolsTy LSymbols;
GRState NewSt = *St;
NewSt.Env =
EnvMgr.RemoveDeadBindings(NewSt.Env, Loc, Liveness, RegionRoots, LSymbols);
// Clean up the store.
DSymbols.clear();
NewSt.St = StoreMgr->RemoveDeadBindings(St->getStore(), Loc, Liveness,
RegionRoots, LSymbols, DSymbols);
return ConstraintMgr->RemoveDeadBindings(getPersistentState(NewSt),
LSymbols, DSymbols);
}
const GRState* GRStateManager::BindLoc(const GRState* St, Loc LV, SVal V) {
Store OldStore = St->getStore();
Store NewStore = StoreMgr->Bind(OldStore, LV, V);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
const GRState* GRStateManager::BindDecl(const GRState* St, const VarDecl* VD,
Expr* Ex, unsigned Count) {
Store OldStore = St->getStore();
Store NewStore;
if (Ex)
NewStore = StoreMgr->BindDecl(OldStore, VD, Ex, GetSVal(St, Ex), Count);
else
NewStore = StoreMgr->BindDecl(OldStore, VD, Ex);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
/// BindCompoundLiteral - Return the store that has the bindings currently
/// in 'store' plus the bindings for the CompoundLiteral. 'R' is the region
/// for the compound literal and 'BegInit' and 'EndInit' represent an
/// array of initializer values.
const GRState*
GRStateManager::BindCompoundLiteral(const GRState* state,
const CompoundLiteralRegion* R,
const SVal* BegInit, const SVal* EndInit) {
Store oldStore = state->getStore();
Store newStore = StoreMgr->BindCompoundLiteral(oldStore, R, BegInit, EndInit);
if (newStore == oldStore)
return state;
GRState newState = *state;
newState.St = newStore;
return getPersistentState(newState);
}
const GRState* GRStateManager::Unbind(const GRState* St, Loc LV) {
Store OldStore = St->getStore();
Store NewStore = StoreMgr->Remove(OldStore, LV);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
const GRState* GRStateManager::getInitialState() {
GRState StateImpl(EnvMgr.getInitialEnvironment(),
StoreMgr->getInitialStore(),
GDMFactory.GetEmptyMap());
return getPersistentState(StateImpl);
}
const GRState* GRStateManager::getPersistentState(GRState& State) {
llvm::FoldingSetNodeID ID;
State.Profile(ID);
void* InsertPos;
if (GRState* I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
return I;
GRState* I = (GRState*) Alloc.Allocate<GRState>();
new (I) GRState(State);
StateSet.InsertNode(I, InsertPos);
return I;
}
//===----------------------------------------------------------------------===//
// State pretty-printing.
//===----------------------------------------------------------------------===//
void GRState::print(std::ostream& Out, StoreManager& StoreMgr,
ConstraintManager& ConstraintMgr,
Printer** Beg, Printer** End,
const char* nl, const char* sep) const {
// Print the store.
StoreMgr.print(getStore(), Out, nl, sep);
// Print Subexpression bindings.
bool isFirst = true;
for (seb_iterator I = seb_begin(), E = seb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Sub-Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
// Print block-expression bindings.
isFirst = true;
for (beb_iterator I = beb_begin(), E = beb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Block-level Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
ConstraintMgr.print(this, Out, nl, sep);
// Print checker-specific data.
for ( ; Beg != End ; ++Beg) (*Beg)->Print(Out, this, nl, sep);
}
void GRStateRef::printDOT(std::ostream& Out) const {
print(Out, "\\l", "\\|");
}
void GRStateRef::printStdErr() const {
print(*llvm::cerr);
}
void GRStateRef::print(std::ostream& Out, const char* nl, const char* sep)const{
GRState::Printer **beg = Mgr->Printers.empty() ? 0 : &Mgr->Printers[0];
GRState::Printer **end = !beg ? 0 : beg + Mgr->Printers.size();
St->print(Out, *Mgr->StoreMgr, *Mgr->ConstraintMgr, beg, end, nl, sep);
}
//===----------------------------------------------------------------------===//
// Generic Data Map.
//===----------------------------------------------------------------------===//
void* const* GRState::FindGDM(void* K) const {
return GDM.lookup(K);
}
void*
GRStateManager::FindGDMContext(void* K,
void* (*CreateContext)(llvm::BumpPtrAllocator&),
void (*DeleteContext)(void*)) {
std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
if (!p.first) {
p.first = CreateContext(Alloc);
p.second = DeleteContext;
}
return p.first;
}
const GRState* GRStateManager::addGDM(const GRState* St, void* Key, void* Data){
GRState::GenericDataMap M1 = St->getGDM();
GRState::GenericDataMap M2 = GDMFactory.Add(M1, Key, Data);
if (M1 == M2)
return St;
GRState NewSt = *St;
NewSt.GDM = M2;
return getPersistentState(NewSt);
}
//===----------------------------------------------------------------------===//
// Queries.
//===----------------------------------------------------------------------===//
bool GRStateManager::isEqual(const GRState* state, Expr* Ex,
const llvm::APSInt& Y) {
SVal V = GetSVal(state, Ex);
if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::SymbolVal* X = dyn_cast<nonloc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
if (loc::SymbolVal* X = dyn_cast<loc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
return false;
}
bool GRStateManager::isEqual(const GRState* state, Expr* Ex, uint64_t x) {
return isEqual(state, Ex, BasicVals.getValue(x, Ex->getType()));
}
//===----------------------------------------------------------------------===//
// Persistent values for indexing into the Generic Data Map.
int GRState::NullDerefTag::TagInt = 0;
|
//= GRState*cpp - Path-Sens. "State" for tracking valuues -----*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines SymbolID, ExprBindKey, and GRState*
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/GRStateTrait.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
// Give the vtable for ConstraintManager somewhere to live.
ConstraintManager::~ConstraintManager() {}
GRStateManager::~GRStateManager() {
for (std::vector<GRState::Printer*>::iterator I=Printers.begin(),
E=Printers.end(); I!=E; ++I)
delete *I;
for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
I!=E; ++I)
I->second.second(I->second.first);
}
const GRState*
GRStateManager::RemoveDeadBindings(const GRState* St, Stmt* Loc,
const LiveVariables& Liveness,
DeadSymbolsTy& DSymbols) {
// This code essentially performs a "mark-and-sweep" of the VariableBindings.
// The roots are any Block-level exprs and Decls that our liveness algorithm
// tells us are live. We then see what Decls they may reference, and keep
// those around. This code more than likely can be made faster, and the
// frequency of which this method is called should be experimented with
// for optimum performance.
llvm::SmallVector<const MemRegion*, 10> RegionRoots;
StoreManager::LiveSymbolsTy LSymbols;
GRState NewSt = *St;
NewSt.Env =
EnvMgr.RemoveDeadBindings(NewSt.Env, Loc, Liveness, RegionRoots, LSymbols);
// Clean up the store.
DSymbols.clear();
NewSt.St = StoreMgr->RemoveDeadBindings(St->getStore(), Loc, Liveness,
RegionRoots, LSymbols, DSymbols);
return ConstraintMgr->RemoveDeadBindings(getPersistentState(NewSt),
LSymbols, DSymbols);
}
const GRState* GRStateManager::BindLoc(const GRState* St, Loc LV, SVal V) {
Store OldStore = St->getStore();
Store NewStore = StoreMgr->Bind(OldStore, LV, V);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
const GRState* GRStateManager::BindDecl(const GRState* St, const VarDecl* VD,
Expr* Ex, unsigned Count) {
Store OldStore = St->getStore();
Store NewStore;
if (Ex)
NewStore = StoreMgr->BindDecl(OldStore, VD, Ex, GetSVal(St, Ex), Count);
else
NewStore = StoreMgr->BindDecl(OldStore, VD, Ex);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
/// BindCompoundLiteral - Return the store that has the bindings currently
/// in 'store' plus the bindings for the CompoundLiteral. 'R' is the region
/// for the compound literal and 'BegInit' and 'EndInit' represent an
/// array of initializer values.
const GRState*
GRStateManager::BindCompoundLiteral(const GRState* state,
const CompoundLiteralRegion* R,
const SVal* BegInit, const SVal* EndInit) {
Store oldStore = state->getStore();
Store newStore = StoreMgr->BindCompoundLiteral(oldStore, R, BegInit, EndInit);
if (newStore == oldStore)
return state;
GRState newState = *state;
newState.St = newStore;
return getPersistentState(newState);
}
const GRState* GRStateManager::Unbind(const GRState* St, Loc LV) {
Store OldStore = St->getStore();
Store NewStore = StoreMgr->Remove(OldStore, LV);
if (NewStore == OldStore)
return St;
GRState NewSt = *St;
NewSt.St = NewStore;
return getPersistentState(NewSt);
}
const GRState* GRStateManager::getInitialState() {
GRState StateImpl(EnvMgr.getInitialEnvironment(),
StoreMgr->getInitialStore(),
GDMFactory.GetEmptyMap());
return getPersistentState(StateImpl);
}
const GRState* GRStateManager::getPersistentState(GRState& State) {
llvm::FoldingSetNodeID ID;
State.Profile(ID);
void* InsertPos;
if (GRState* I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
return I;
GRState* I = (GRState*) Alloc.Allocate<GRState>();
new (I) GRState(State);
StateSet.InsertNode(I, InsertPos);
return I;
}
//===----------------------------------------------------------------------===//
// State pretty-printing.
//===----------------------------------------------------------------------===//
void GRState::print(std::ostream& Out, StoreManager& StoreMgr,
ConstraintManager& ConstraintMgr,
Printer** Beg, Printer** End,
const char* nl, const char* sep) const {
// Print the store.
StoreMgr.print(getStore(), Out, nl, sep);
// Print Subexpression bindings.
bool isFirst = true;
for (seb_iterator I = seb_begin(), E = seb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Sub-Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
// Print block-expression bindings.
isFirst = true;
for (beb_iterator I = beb_begin(), E = beb_end(); I != E; ++I) {
if (isFirst) {
Out << nl << nl << "Block-level Expressions:" << nl;
isFirst = false;
}
else { Out << nl; }
Out << " (" << (void*) I.getKey() << ") ";
llvm::raw_os_ostream OutS(Out);
I.getKey()->printPretty(OutS);
OutS.flush();
Out << " : ";
I.getData().print(Out);
}
ConstraintMgr.print(this, Out, nl, sep);
// Print checker-specific data.
for ( ; Beg != End ; ++Beg) (*Beg)->Print(Out, this, nl, sep);
}
void GRStateRef::printDOT(std::ostream& Out) const {
print(Out, "\\l", "\\|");
}
void GRStateRef::printStdErr() const {
print(*llvm::cerr);
}
void GRStateRef::print(std::ostream& Out, const char* nl, const char* sep)const{
GRState::Printer **beg = Mgr->Printers.empty() ? 0 : &Mgr->Printers[0];
GRState::Printer **end = !beg ? 0 : beg + Mgr->Printers.size();
St->print(Out, *Mgr->StoreMgr, *Mgr->ConstraintMgr, beg, end, nl, sep);
}
//===----------------------------------------------------------------------===//
// Generic Data Map.
//===----------------------------------------------------------------------===//
void* const* GRState::FindGDM(void* K) const {
return GDM.lookup(K);
}
void*
GRStateManager::FindGDMContext(void* K,
void* (*CreateContext)(llvm::BumpPtrAllocator&),
void (*DeleteContext)(void*)) {
std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
if (!p.first) {
p.first = CreateContext(Alloc);
p.second = DeleteContext;
}
return p.first;
}
const GRState* GRStateManager::addGDM(const GRState* St, void* Key, void* Data){
GRState::GenericDataMap M1 = St->getGDM();
GRState::GenericDataMap M2 = GDMFactory.Add(M1, Key, Data);
if (M1 == M2)
return St;
GRState NewSt = *St;
NewSt.GDM = M2;
return getPersistentState(NewSt);
}
//===----------------------------------------------------------------------===//
// Queries.
//===----------------------------------------------------------------------===//
bool GRStateManager::isEqual(const GRState* state, Expr* Ex,
const llvm::APSInt& Y) {
SVal V = GetSVal(state, Ex);
if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
return X->getValue() == Y;
if (nonloc::SymbolVal* X = dyn_cast<nonloc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
if (loc::SymbolVal* X = dyn_cast<loc::SymbolVal>(&V))
return ConstraintMgr->isEqual(state, X->getSymbol(), Y);
return false;
}
bool GRStateManager::isEqual(const GRState* state, Expr* Ex, uint64_t x) {
return isEqual(state, Ex, BasicVals.getValue(x, Ex->getType()));
}
//===----------------------------------------------------------------------===//
// Persistent values for indexing into the Generic Data Map.
int GRState::NullDerefTag::TagInt = 0;
|
Fix 80-col violations.
|
Fix 80-col violations.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@58596 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
|
9aa7a30a32ceda2d1a522048c9768800b9c4ca86
|
tutorials/histfactory/example.C
|
tutorials/histfactory/example.C
|
#include "RooStats/HistFactory/Measurement.h"
#include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h"
#include "TFile.h"
#include "TRoot.h"
using namespace RooStats;
using namespace HistFactory;
/*
A ROOT script demonstrating
an example of writing a HistFactory
model using c++ only.
This example was written to match
the example.xml analysis in
$ROOTSYS/tutorials/histfactory/
Written by George Lewis
*/
void example() {
std::string InputFile = "./data/example.root";
// in case the file is not found
TFile * ifile = TFile::Open(InputFile.c_str());
if (!ifile) {
std::cout << "Input file is not found - run prepareHistFactory script " << std::endl;
gROOT->ProcessLine(".! prepareHistFactory .");
}
// Create the measurement
Measurement meas("meas", "meas");
meas.SetOutputFilePrefix( "./results/example_UsingC" );
meas.SetPOI( "SigXsecOverSM" );
meas.AddConstantParam("alpha_syst1");
meas.AddConstantParam("Lumi");
meas.SetLumi( 1.0 );
meas.SetLumiRelErr( 0.10 );
meas.SetExportOnly( false );
meas.SetBinHigh( 2 );
// Create a channel
Channel chan( "channel1" );
chan.SetData( "data", InputFile );
chan.SetStatErrorConfig( 0.05, "Poisson" );
// Now, create some samples
// Create the signal sample
Sample signal( "signal", "signal", InputFile );
signal.AddOverallSys( "syst1", 0.95, 1.05 );
signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 );
chan.AddSample( signal );
// Background 1
Sample background1( "background1", "background1", InputFile );
background1.ActivateStatError( "background1_statUncert", InputFile );
background1.AddOverallSys( "syst2", 0.95, 1.05 );
chan.AddSample( background1 );
// Background 1
Sample background2( "background2", "background2", InputFile );
background2.ActivateStatError();
background2.AddOverallSys( "syst3", 0.95, 1.05 );
chan.AddSample( background2 );
// Done with this channel
// Add it to the measurement:
meas.AddChannel( chan );
// Collect the histograms from their files,
// print some output,
meas.CollectHistograms();
meas.PrintTree();
// One can print XML code to an
// output directory:
// meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() );
// Now, do the measurement
MakeModelAndMeasurementFast( meas );
}
|
#include "RooStats/HistFactory/Measurement.h"
#include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h"
#include "TFile.h"
#include "TROOT.h"
using namespace RooStats;
using namespace HistFactory;
/*
A ROOT script demonstrating
an example of writing a HistFactory
model using c++ only.
This example was written to match
the example.xml analysis in
$ROOTSYS/tutorials/histfactory/
Written by George Lewis
*/
void example() {
std::string InputFile = "./data/example.root";
// in case the file is not found
TFile * ifile = TFile::Open(InputFile.c_str());
if (!ifile) {
std::cout << "Input file is not found - run prepareHistFactory script " << std::endl;
gROOT->ProcessLine(".! prepareHistFactory .");
}
// Create the measurement
Measurement meas("meas", "meas");
meas.SetOutputFilePrefix( "./results/example_UsingC" );
meas.SetPOI( "SigXsecOverSM" );
meas.AddConstantParam("alpha_syst1");
meas.AddConstantParam("Lumi");
meas.SetLumi( 1.0 );
meas.SetLumiRelErr( 0.10 );
meas.SetExportOnly( false );
meas.SetBinHigh( 2 );
// Create a channel
Channel chan( "channel1" );
chan.SetData( "data", InputFile );
chan.SetStatErrorConfig( 0.05, "Poisson" );
// Now, create some samples
// Create the signal sample
Sample signal( "signal", "signal", InputFile );
signal.AddOverallSys( "syst1", 0.95, 1.05 );
signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 );
chan.AddSample( signal );
// Background 1
Sample background1( "background1", "background1", InputFile );
background1.ActivateStatError( "background1_statUncert", InputFile );
background1.AddOverallSys( "syst2", 0.95, 1.05 );
chan.AddSample( background1 );
// Background 1
Sample background2( "background2", "background2", InputFile );
background2.ActivateStatError();
background2.AddOverallSys( "syst3", 0.95, 1.05 );
chan.AddSample( background2 );
// Done with this channel
// Add it to the measurement:
meas.AddChannel( chan );
// Collect the histograms from their files,
// print some output,
meas.CollectHistograms();
meas.PrintTree();
// One can print XML code to an
// output directory:
// meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() );
// Now, do the measurement
MakeModelAndMeasurementFast( meas );
}
|
fix an include
|
fix an include
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@44637 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT
|
0e610cfed68c3dfa8ded4e5617f339914c550bcb
|
test/unit/math/mix/fun/tan_test.cpp
|
test/unit/math/mix/fun/tan_test.cpp
|
#include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, tan) {
auto f = [](const auto& x) {
using stan::math::tan;
return tan(x);
};
stan::test::expect_common_nonzero_unary_vectorized(f);
stan::test::expect_unary_vectorized(f, -2, -0.5, 0.5, 1.5, 3, 4.4);
stan::test::expect_complex_common(f);
}
TEST(mathMixMatFun, sinh_varmat) {
using stan::test::expect_ad_matvar;
auto f = [](const auto& x1) {
using stan::math::sinh;
return sinh(x1);
};
Eigen::MatrixXd A(2, 3);
A << -2, -0.5, 0.5, 1.5, 3, 4.4;
expect_ad_matvar(f, A);
std::vector<Eigen::MatrixXd> A_vec;
A_vec.push_back(A);
A_vec.push_back(A);
A_vec.push_back(A);
stan::test::expect_ad_matvar(f, A_vec);
}
|
#include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, tan) {
auto f = [](const auto& x) {
using stan::math::tan;
return tan(x);
};
stan::test::expect_common_nonzero_unary_vectorized(f);
stan::test::expect_unary_vectorized(f, -2, -0.5, 0.5, 1.5, 3, 4.4);
stan::test::expect_complex_common(f);
}
TEST(mathMixMatFun, tan_varmat) {
using stan::test::expect_ad_matvar;
auto f = [](const auto& x1) {
using stan::math::tan;
return tan(x1);
};
Eigen::MatrixXd A(2, 3);
A << -2, -0.5, 0.5, 1.5, 3, 4.4;
expect_ad_matvar(f, A);
std::vector<Eigen::MatrixXd> A_vec;
A_vec.push_back(A);
A_vec.push_back(A);
A_vec.push_back(A);
stan::test::expect_ad_matvar(f, A_vec);
}
|
update tan test
|
update tan test
|
C++
|
bsd-3-clause
|
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
|
18e56026d32469f5ed7fa1ecd340005aeec8d10f
|
tools/proto_merger/proto_file_serializer.cc
|
tools/proto_merger/proto_file_serializer.cc
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/proto_merger/proto_file_serializer.h"
#include "perfetto/ext/base/string_utils.h"
namespace perfetto {
namespace proto_merger {
namespace {
std::string DeletedComment(const std::string& prefix) {
std::string output;
output += "\n";
output += prefix + " //\n";
output += prefix;
output +=
" // The following enums/messages/fields are not present upstream\n";
output += prefix + " //\n";
return output;
}
std::string SerializeComments(const std::string& prefix,
const std::vector<std::string>& lines) {
std::string output;
for (const auto& line : lines) {
output.append(prefix);
output.append("//");
output.append(line);
output.append("\n");
}
return output;
}
std::string SerializeLeadingComments(const std::string& prefix,
const ProtoFile::Member& member,
bool prefix_newline_if_comment = true) {
if (member.leading_comments.empty())
return "";
std::string output;
if (prefix_newline_if_comment) {
output += "\n";
}
output += SerializeComments(prefix, member.leading_comments);
return output;
}
std::string SerializeTrailingComments(const std::string& prefix,
const ProtoFile::Member& member) {
return SerializeComments(prefix, member.trailing_comments);
}
std::string SerializeOptions(const std::vector<ProtoFile::Option>& options) {
if (options.empty())
return "";
std::string output;
output += " [";
for (const auto& option : options) {
output += option.key + " = " + option.value;
}
output += "]";
return output;
}
std::string SerializeEnumValue(size_t indent,
const ProtoFile::Enum::Value& value) {
std::string prefix(indent * 2, ' ');
std::string output;
output += SerializeLeadingComments(prefix, value, false);
output += prefix + value.name + " = " + std::to_string(value.number);
output += SerializeOptions(value.options);
output += ";\n";
output += SerializeTrailingComments(prefix, value);
return output;
}
std::string SerializeEnum(size_t indent, const ProtoFile::Enum& en) {
std::string prefix(indent * 2, ' ');
++indent;
std::string output;
output += SerializeLeadingComments(prefix, en);
output += prefix + "enum " + en.name + " {\n";
for (const auto& value : en.values) {
output += SerializeEnumValue(indent, value);
}
output += prefix + "}\n";
output += SerializeTrailingComments(prefix, en);
return output;
}
std::string SerializeField(size_t indent,
const ProtoFile::Field& field,
bool write_label) {
std::string prefix(indent * 2, ' ');
std::string output;
output += SerializeLeadingComments(prefix, field);
std::string label;
if (write_label) {
label = field.label + " ";
}
output += prefix + label + field.type + " " + field.name + " = " +
std::to_string(field.number);
output += SerializeOptions(field.options);
output += ";\n";
output += SerializeTrailingComments(prefix, field);
return output;
}
std::string SerializeOneof(size_t indent, const ProtoFile::Oneof& oneof) {
std::string prefix(indent * 2, ' ');
++indent;
std::string output;
output += SerializeLeadingComments(prefix, oneof);
output += prefix + "oneof " + oneof.name + " {\n";
for (const auto& field : oneof.fields) {
output += SerializeField(indent, field, false);
}
output += prefix + "}\n";
output += SerializeTrailingComments(prefix, oneof);
return output;
}
std::string SerializeMessage(size_t indent, const ProtoFile::Message& message) {
std::string prefix(indent * 2, ' ');
++indent;
std::string output;
output += SerializeLeadingComments(prefix, message);
output += prefix + "message " + message.name + " {\n";
for (const auto& en : message.enums) {
output += SerializeEnum(indent, en);
}
for (const auto& nested : message.nested_messages) {
output += SerializeMessage(indent, nested);
}
for (const auto& oneof : message.oneofs) {
output += SerializeOneof(indent, oneof);
}
for (const auto& field : message.fields) {
output += SerializeField(indent, field, true);
}
if (message.deleted_enums.size() || message.deleted_fields.size() ||
message.deleted_nested_messages.size() || message.deleted_oneofs.size()) {
output += DeletedComment(prefix);
for (const auto& en : message.deleted_enums) {
output += SerializeEnum(indent, en);
}
for (const auto& nested : message.deleted_nested_messages) {
output += SerializeMessage(indent, nested);
}
for (const auto& oneof : message.deleted_oneofs) {
output += SerializeOneof(indent, oneof);
}
for (const auto& field : message.deleted_fields) {
output += SerializeField(indent, field, true);
}
}
output += prefix + "}\n";
output += SerializeTrailingComments(prefix, message);
return output;
}
} // namespace
std::string ProtoFileToDotProto(const ProtoFile& proto_file) {
std::string output;
for (const auto& en : proto_file.enums) {
output += SerializeEnum(0, en);
}
for (const auto& message : proto_file.messages) {
output += SerializeMessage(0, message);
}
if (proto_file.deleted_enums.size() || proto_file.deleted_enums.size()) {
output += DeletedComment("");
for (const auto& en : proto_file.deleted_enums) {
output += SerializeEnum(0, en);
}
for (const auto& nested : proto_file.deleted_messages) {
output += SerializeMessage(0, nested);
}
}
return output;
}
} // namespace proto_merger
} // namespace perfetto
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/proto_merger/proto_file_serializer.h"
#include "perfetto/ext/base/string_utils.h"
namespace perfetto {
namespace proto_merger {
namespace {
std::string DeletedComment(const std::string& prefix) {
std::string output;
output += "\n";
output += prefix + " //\n";
output += prefix;
output +=
" // The following enums/messages/fields are not present upstream\n";
output += prefix + " //\n";
return output;
}
std::string SerializeComments(const std::string& prefix,
const std::vector<std::string>& lines) {
std::string output;
for (const auto& line : lines) {
output.append(prefix);
output.append("//");
output.append(line);
output.append("\n");
}
return output;
}
std::string SerializeLeadingComments(const std::string& prefix,
const ProtoFile::Member& member,
bool prefix_newline_if_comment = true) {
if (member.leading_comments.empty())
return "";
std::string output;
if (prefix_newline_if_comment) {
output += "\n";
}
output += SerializeComments(prefix, member.leading_comments);
return output;
}
std::string SerializeTrailingComments(const std::string& prefix,
const ProtoFile::Member& member) {
return SerializeComments(prefix, member.trailing_comments);
}
std::string SerializeOptions(const std::vector<ProtoFile::Option>& options) {
if (options.empty())
return "";
std::string output;
output += " [";
for (const auto& option : options) {
output += option.key + " = " + option.value;
}
output += "]";
return output;
}
std::string SerializeEnumValue(size_t indent,
const ProtoFile::Enum::Value& value) {
std::string prefix(indent * 2, ' ');
std::string output;
output += SerializeLeadingComments(prefix, value, false);
output += prefix + value.name + " = " + std::to_string(value.number);
output += SerializeOptions(value.options);
output += ";\n";
output += SerializeTrailingComments(prefix, value);
return output;
}
std::string SerializeEnum(size_t indent, const ProtoFile::Enum& en) {
std::string prefix(indent * 2, ' ');
++indent;
std::string output;
output += SerializeLeadingComments(prefix, en);
output += prefix + "enum " + en.name + " {\n";
for (const auto& value : en.values) {
output += SerializeEnumValue(indent, value);
}
output += prefix + "}\n";
output += SerializeTrailingComments(prefix, en);
return output;
}
std::string SerializeField(size_t indent,
const ProtoFile::Field& field,
bool write_label) {
std::string prefix(indent * 2, ' ');
std::string output;
output += SerializeLeadingComments(prefix, field);
std::string label;
if (write_label) {
label = field.label + " ";
}
output += prefix + label + field.type + " " + field.name + " = " +
std::to_string(field.number);
output += SerializeOptions(field.options);
output += ";\n";
output += SerializeTrailingComments(prefix, field);
return output;
}
std::string SerializeOneof(size_t indent, const ProtoFile::Oneof& oneof) {
std::string prefix(indent * 2, ' ');
++indent;
std::string output;
output += SerializeLeadingComments(prefix, oneof);
output += prefix + "oneof " + oneof.name + " {\n";
for (const auto& field : oneof.fields) {
output += SerializeField(indent, field, false);
}
output += prefix + "}\n";
output += SerializeTrailingComments(prefix, oneof);
return output;
}
std::string SerializeMessage(size_t indent, const ProtoFile::Message& message) {
std::string prefix(indent * 2, ' ');
++indent;
std::string output;
output += SerializeLeadingComments(prefix, message);
output += prefix + "message " + message.name + " {\n";
for (const auto& en : message.enums) {
output += SerializeEnum(indent, en);
}
for (const auto& nested : message.nested_messages) {
output += SerializeMessage(indent, nested);
}
for (const auto& oneof : message.oneofs) {
output += SerializeOneof(indent, oneof);
}
for (const auto& field : message.fields) {
output += SerializeField(indent, field, true);
}
if (message.deleted_enums.size() || message.deleted_fields.size() ||
message.deleted_nested_messages.size() || message.deleted_oneofs.size()) {
output += DeletedComment(prefix);
for (const auto& en : message.deleted_enums) {
output += SerializeEnum(indent, en);
}
for (const auto& nested : message.deleted_nested_messages) {
output += SerializeMessage(indent, nested);
}
for (const auto& oneof : message.deleted_oneofs) {
output += SerializeOneof(indent, oneof);
}
for (const auto& field : message.deleted_fields) {
output += SerializeField(indent, field, true);
}
}
output += prefix + "}\n";
output += SerializeTrailingComments(prefix, message);
return output;
}
} // namespace
std::string ProtoFileToDotProto(const ProtoFile& proto_file) {
std::string output;
for (const auto& en : proto_file.enums) {
output += SerializeEnum(0, en);
}
for (const auto& message : proto_file.messages) {
output += SerializeMessage(0, message);
}
if (proto_file.deleted_enums.size() || proto_file.deleted_messages.size()) {
output += DeletedComment("");
for (const auto& en : proto_file.deleted_enums) {
output += SerializeEnum(0, en);
}
for (const auto& nested : proto_file.deleted_messages) {
output += SerializeMessage(0, nested);
}
}
return output;
}
} // namespace proto_merger
} // namespace perfetto
|
Fix small bug in ProtoFileToDotProto am: a5221eeff1 am: a9a2fd14c9 am: 7995163897 am: 99e0cc588c
|
tools: Fix small bug in ProtoFileToDotProto am: a5221eeff1 am: a9a2fd14c9 am: 7995163897 am: 99e0cc588c
Original change: https://android-review.googlesource.com/c/platform/external/perfetto/+/1775025
Change-Id: I8fea572578d8c133914cbf887264cd3235033bcd
|
C++
|
apache-2.0
|
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
|
795d22b8a29b2fae3ed8d11981619130562568fd
|
lib/SILPasses/Passes.cpp
|
lib/SILPasses/Passes.cpp
|
//===-------- Passes.cpp - Swift Compiler SIL Pass Entrypoints ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides implementations of a few helper functions
/// which provide abstracted entrypoints to the SILPasses stage.
///
/// \note The actual SIL passes should be implemented in per-pass source files,
/// not in this file.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-optimizer"
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/PassManager.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILAnalysis/Analysis.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/SILOptions.h"
#include "swift/SIL/SILModule.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
static void registerAnalysisPasses(SILPassManager &PM, SILModule *Mod) {
PM.registerAnalysis(createCallGraphAnalysis(Mod));
PM.registerAnalysis(createAliasAnalysis(Mod));
PM.registerAnalysis(createDominanceAnalysis(Mod));
}
bool swift::runSILDiagnosticPasses(SILModule &Module,
const SILOptions &Options) {
// If we parsed a .sil file that is already in canonical form, don't rerun
// the diagnostic passes.
if (Module.getStage() == SILStage::Canonical)
return false;
auto &Ctx = Module.getASTContext();
SILPassManager PM(&Module, Options);
registerAnalysisPasses(PM, &Module);
// If we are asked do debug serialization, instead of running all diagnostic
// passes, just run mandatory inlining with dead transparent function cleanup
// disabled.
PM.add(createMandatoryInlining());
if (Options.DebugSerialization) {
PM.run();
return Ctx.hadError();
}
// Otherwise run the rest of diagnostics.
PM.add(createCapturePromotion());
PM.add(createAllocBoxToStack());
PM.add(createInOutDeshadowing());
PM.add(createNoReturnFolding());
PM.add(createDefiniteInitialization());
PM.add(createPredictableMemoryOptimizations());
PM.add(createDiagnosticConstantPropagation());
PM.add(createDiagnoseUnreachable());
PM.add(createEmitDFDiagnostics());
PM.run();
// Generate diagnostics.
Module.setStage(SILStage::Canonical);
// If errors were produced during SIL analysis, return true.
return Ctx.hadError();
}
void ConstructSSAPassManager(SILPassManager &PM, SILModule &Module,
bool useEarlyInliner) {
registerAnalysisPasses(PM, &Module);
PM.add(createSimplifyCFG());
PM.add(createAllocBoxToStack());
PM.add(createLowerAggregate());
PM.add(createSILCombine());
PM.add(createSROA());
PM.add(createMem2Reg());
// Perform classsic SSA optimizations.
PM.add(createPerformanceConstantPropagation());
PM.add(createDCE());
PM.add(createCSE());
PM.add(createSILCombine());
PM.add(createSimplifyCFG());
// Perform retain/release code motion and run the first ARC optimizer.
PM.add(createLoadStoreOpts());
PM.add(createCodeMotion());
PM.add(createEnumSimplification());
PM.add(createGlobalARCOpts());
// Devirtualize.
PM.add(createDevirtualization());
PM.add(createGenericSpecializer());
PM.add(createSILLinker());
// Use either the early inliner that does not inline functions with defined
// semantics or the late performance inliner that inlines everything.
PM.add(useEarlyInliner ? createEarlyInliner() :createPerfInliner());
PM.add(createGlobalARCOpts());
}
void swift::runSILOptimizationPasses(SILModule &Module,
const SILOptions &Options) {
if (Options.DebugSerialization) {
SILPassManager PM(&Module, Options);
registerAnalysisPasses(PM, &Module);
PM.add(createSILLinker());
PM.run();
return;
}
// Start by specializing generics and by cloning functions from stdlib.
SILPassManager GenericsPM(&Module, Options);
registerAnalysisPasses(GenericsPM, &Module);
GenericsPM.add(createSILLinker());
GenericsPM.add(createGenericSpecializer());
GenericsPM.run();
// Construct SSA pass manager.
SILPassManager SSAPM(&Module, Options);
ConstructSSAPassManager(SSAPM, Module, false);
// Run three iteration of the SSA pass mananger.
SSAPM.runOneIteration();
SSAPM.runOneIteration();
SSAPM.runOneIteration();
// Perform lowering optimizations.
SILPassManager LoweringPM(&Module, Options);
registerAnalysisPasses(LoweringPM, &Module);
LoweringPM.add(createDeadFunctionElimination());
LoweringPM.add(createDeadObjectElimination());
// Hoist globals out of loops.
LoweringPM.add(createGlobalOpt());
// Insert inline caches for virtual calls.
LoweringPM.add(createDevirtualization());
LoweringPM.add(createInlineCaches());
LoweringPM.run();
// Run another iteration of the SSA optimizations to optimize the
// devirtualized inline caches.
SSAPM.invalidateAnalysis(SILAnalysis::InvalidationKind::All);
SSAPM.runOneIteration();
// Invalidate the SILLoader and allow it to drop references to SIL functions.
Module.invalidateSILLoader();
performSILElimination(&Module);
// Gather instruction counts if we are asked to do so.
if (Options.PrintInstCounts) {
SILPassManager PrinterPM(&Module, Options);
PrinterPM.add(createSILInstCount());
PrinterPM.runOneIteration();
}
DEBUG(Module.verify());
}
|
//===-------- Passes.cpp - Swift Compiler SIL Pass Entrypoints ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides implementations of a few helper functions
/// which provide abstracted entrypoints to the SILPasses stage.
///
/// \note The actual SIL passes should be implemented in per-pass source files,
/// not in this file.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-optimizer"
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/PassManager.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILAnalysis/Analysis.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/SILOptions.h"
#include "swift/SIL/SILModule.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
static void registerAnalysisPasses(SILPassManager &PM, SILModule *Mod) {
PM.registerAnalysis(createCallGraphAnalysis(Mod));
PM.registerAnalysis(createAliasAnalysis(Mod));
PM.registerAnalysis(createDominanceAnalysis(Mod));
}
bool swift::runSILDiagnosticPasses(SILModule &Module,
const SILOptions &Options) {
// If we parsed a .sil file that is already in canonical form, don't rerun
// the diagnostic passes.
if (Module.getStage() == SILStage::Canonical)
return false;
auto &Ctx = Module.getASTContext();
SILPassManager PM(&Module, Options);
registerAnalysisPasses(PM, &Module);
// If we are asked do debug serialization, instead of running all diagnostic
// passes, just run mandatory inlining with dead transparent function cleanup
// disabled.
PM.add(createMandatoryInlining());
if (Options.DebugSerialization) {
PM.run();
return Ctx.hadError();
}
// Otherwise run the rest of diagnostics.
PM.add(createCapturePromotion());
PM.add(createAllocBoxToStack());
PM.add(createInOutDeshadowing());
PM.add(createNoReturnFolding());
PM.add(createDefiniteInitialization());
PM.add(createPredictableMemoryOptimizations());
PM.add(createDiagnosticConstantPropagation());
PM.add(createDiagnoseUnreachable());
PM.add(createEmitDFDiagnostics());
PM.run();
// Generate diagnostics.
Module.setStage(SILStage::Canonical);
// If errors were produced during SIL analysis, return true.
return Ctx.hadError();
}
void ConstructSSAPassManager(SILPassManager &PM, SILModule &Module,
bool useEarlyInliner) {
registerAnalysisPasses(PM, &Module);
PM.add(createSimplifyCFG());
PM.add(createAllocBoxToStack());
PM.add(createLowerAggregate());
PM.add(createSILCombine());
PM.add(createSROA());
PM.add(createMem2Reg());
// Perform classsic SSA optimizations.
PM.add(createPerformanceConstantPropagation());
PM.add(createDCE());
PM.add(createCSE());
PM.add(createSILCombine());
PM.add(createSimplifyCFG());
// Perform retain/release code motion and run the first ARC optimizer.
PM.add(createLoadStoreOpts());
PM.add(createCodeMotion());
PM.add(createEnumSimplification());
PM.add(createGlobalARCOpts());
// Devirtualize.
PM.add(createDevirtualization());
PM.add(createGenericSpecializer());
PM.add(createSILLinker());
// Use either the early inliner that does not inline functions with defined
// semantics or the late performance inliner that inlines everything.
PM.add(useEarlyInliner ? createEarlyInliner() :createPerfInliner());
PM.add(createSimplifyCFG());
PM.add(createGlobalARCOpts());
}
void swift::runSILOptimizationPasses(SILModule &Module,
const SILOptions &Options) {
if (Options.DebugSerialization) {
SILPassManager PM(&Module, Options);
registerAnalysisPasses(PM, &Module);
PM.add(createSILLinker());
PM.run();
return;
}
// Start by specializing generics and by cloning functions from stdlib.
SILPassManager GenericsPM(&Module, Options);
registerAnalysisPasses(GenericsPM, &Module);
GenericsPM.add(createSILLinker());
GenericsPM.add(createGenericSpecializer());
GenericsPM.run();
// Construct SSA pass manager.
SILPassManager SSAPM(&Module, Options);
ConstructSSAPassManager(SSAPM, Module, false);
// Run three iteration of the SSA pass mananger.
SSAPM.runOneIteration();
SSAPM.runOneIteration();
SSAPM.runOneIteration();
// Perform lowering optimizations.
SILPassManager LoweringPM(&Module, Options);
registerAnalysisPasses(LoweringPM, &Module);
LoweringPM.add(createDeadFunctionElimination());
LoweringPM.add(createDeadObjectElimination());
// Hoist globals out of loops.
LoweringPM.add(createGlobalOpt());
// Insert inline caches for virtual calls.
LoweringPM.add(createDevirtualization());
LoweringPM.add(createInlineCaches());
LoweringPM.run();
// Run another iteration of the SSA optimizations to optimize the
// devirtualized inline caches.
SSAPM.invalidateAnalysis(SILAnalysis::InvalidationKind::All);
SSAPM.runOneIteration();
// Invalidate the SILLoader and allow it to drop references to SIL functions.
Module.invalidateSILLoader();
performSILElimination(&Module);
// Gather instruction counts if we are asked to do so.
if (Options.PrintInstCounts) {
SILPassManager PrinterPM(&Module, Options);
PrinterPM.add(createSILInstCount());
PrinterPM.runOneIteration();
}
DEBUG(Module.verify());
}
|
Add another pass of CFG simplification after inlining.
|
Add another pass of CFG simplification after inlining.
Inlining exposes more opportunities for CFG simplifications, and this
could be beneficial before ARC opts.
Because we create inline "caches" fairly late we also need this in order
to clean up redundant checked_cast_br instructions that are exposed as a
result of inlining since we only run the SSA passes once after the
inline cache pass.
The change to actually optimize the checked_cast_br is forthcoming.
Swift SVN r19557
|
C++
|
apache-2.0
|
CodaFi/swift,devincoughlin/swift,ben-ng/swift,cbrentharris/swift,johnno1962d/swift,shahmishal/swift,SwiftAndroid/swift,sschiau/swift,glessard/swift,codestergit/swift,swiftix/swift,practicalswift/swift,kusl/swift,slavapestov/swift,OscarSwanros/swift,gribozavr/swift,harlanhaskins/swift,felix91gr/swift,jopamer/swift,kperryua/swift,kentya6/swift,khizkhiz/swift,ahoppen/swift,hooman/swift,milseman/swift,emilstahl/swift,calebd/swift,Jnosh/swift,OscarSwanros/swift,zisko/swift,djwbrown/swift,tinysun212/swift-windows,cbrentharris/swift,bitjammer/swift,apple/swift,hooman/swift,huonw/swift,dreamsxin/swift,calebd/swift,hughbe/swift,lorentey/swift,tjw/swift,ahoppen/swift,jckarter/swift,kusl/swift,codestergit/swift,shahmishal/swift,gmilos/swift,tardieu/swift,stephentyrone/swift,aschwaighofer/swift,apple/swift,gregomni/swift,emilstahl/swift,rudkx/swift,djwbrown/swift,nathawes/swift,dduan/swift,zisko/swift,allevato/swift,adrfer/swift,benlangmuir/swift,cbrentharris/swift,calebd/swift,tkremenek/swift,roambotics/swift,amraboelela/swift,shahmishal/swift,brentdax/swift,kstaring/swift,danielmartin/swift,danielmartin/swift,gottesmm/swift,karwa/swift,allevato/swift,IngmarStein/swift,natecook1000/swift,parkera/swift,dreamsxin/swift,manavgabhawala/swift,glessard/swift,tkremenek/swift,xwu/swift,ken0nek/swift,swiftix/swift.old,xedin/swift,jmgc/swift,KrishMunot/swift,zisko/swift,airspeedswift/swift,frootloops/swift,harlanhaskins/swift,ken0nek/swift,parkera/swift,milseman/swift,jopamer/swift,milseman/swift,calebd/swift,arvedviehweger/swift,xwu/swift,johnno1962d/swift,airspeedswift/swift,Ivacker/swift,OscarSwanros/swift,natecook1000/swift,mightydeveloper/swift,SwiftAndroid/swift,MukeshKumarS/Swift,gottesmm/swift,airspeedswift/swift,practicalswift/swift,slavapestov/swift,Ivacker/swift,xedin/swift,bitjammer/swift,IngmarStein/swift,stephentyrone/swift,shajrawi/swift,sschiau/swift,gmilos/swift,deyton/swift,ben-ng/swift,rudkx/swift,gribozavr/swift,MukeshKumarS/Swift,russbishop/swift,zisko/swift,LeoShimonaka/swift,return/swift,kperryua/swift,glessard/swift,devincoughlin/swift,zisko/swift,parkera/swift,brentdax/swift,airspeedswift/swift,sdulal/swift,glessard/swift,ken0nek/swift,shajrawi/swift,harlanhaskins/swift,ben-ng/swift,xedin/swift,gmilos/swift,slavapestov/swift,adrfer/swift,deyton/swift,MukeshKumarS/Swift,atrick/swift,gribozavr/swift,MukeshKumarS/Swift,kperryua/swift,devincoughlin/swift,benlangmuir/swift,frootloops/swift,mightydeveloper/swift,karwa/swift,tkremenek/swift,kentya6/swift,alblue/swift,benlangmuir/swift,russbishop/swift,huonw/swift,JGiola/swift,modocache/swift,apple/swift,nathawes/swift,jmgc/swift,ben-ng/swift,LeoShimonaka/swift,jmgc/swift,brentdax/swift,uasys/swift,ahoppen/swift,gottesmm/swift,arvedviehweger/swift,brentdax/swift,LeoShimonaka/swift,therealbnut/swift,kstaring/swift,hooman/swift,swiftix/swift.old,JaSpa/swift,djwbrown/swift,return/swift,harlanhaskins/swift,brentdax/swift,tjw/swift,parkera/swift,LeoShimonaka/swift,SwiftAndroid/swift,SwiftAndroid/swift,lorentey/swift,therealbnut/swift,LeoShimonaka/swift,adrfer/swift,sdulal/swift,kstaring/swift,khizkhiz/swift,alblue/swift,tjw/swift,benlangmuir/swift,JaSpa/swift,nathawes/swift,russbishop/swift,tinysun212/swift-windows,practicalswift/swift,codestergit/swift,rudkx/swift,mightydeveloper/swift,KrishMunot/swift,atrick/swift,glessard/swift,hughbe/swift,practicalswift/swift,amraboelela/swift,tkremenek/swift,karwa/swift,kusl/swift,amraboelela/swift,IngmarStein/swift,sschiau/swift,Jnosh/swift,jtbandes/swift,KrishMunot/swift,LeoShimonaka/swift,kusl/swift,swiftix/swift.old,practicalswift/swift,devincoughlin/swift,jmgc/swift,hughbe/swift,danielmartin/swift,therealbnut/swift,calebd/swift,manavgabhawala/swift,natecook1000/swift,arvedviehweger/swift,jckarter/swift,lorentey/swift,jckarter/swift,karwa/swift,mightydeveloper/swift,milseman/swift,shajrawi/swift,IngmarStein/swift,slavapestov/swift,glessard/swift,hughbe/swift,benlangmuir/swift,adrfer/swift,CodaFi/swift,devincoughlin/swift,apple/swift,jopamer/swift,modocache/swift,roambotics/swift,shahmishal/swift,xwu/swift,MukeshKumarS/Swift,kperryua/swift,emilstahl/swift,therealbnut/swift,allevato/swift,aschwaighofer/swift,swiftix/swift.old,codestergit/swift,Ivacker/swift,hughbe/swift,kentya6/swift,austinzheng/swift,Jnosh/swift,therealbnut/swift,deyton/swift,jckarter/swift,austinzheng/swift,aschwaighofer/swift,ben-ng/swift,JaSpa/swift,MukeshKumarS/Swift,tjw/swift,swiftix/swift.old,huonw/swift,dduan/swift,lorentey/swift,kperryua/swift,johnno1962d/swift,rudkx/swift,slavapestov/swift,danielmartin/swift,KrishMunot/swift,kentya6/swift,Jnosh/swift,zisko/swift,djwbrown/swift,russbishop/swift,JGiola/swift,hughbe/swift,deyton/swift,sschiau/swift,cbrentharris/swift,gottesmm/swift,allevato/swift,khizkhiz/swift,karwa/swift,lorentey/swift,xedin/swift,SwiftAndroid/swift,CodaFi/swift,shajrawi/swift,roambotics/swift,lorentey/swift,tjw/swift,jmgc/swift,bitjammer/swift,modocache/swift,IngmarStein/swift,dduan/swift,therealbnut/swift,amraboelela/swift,stephentyrone/swift,frootloops/swift,gribozavr/swift,SwiftAndroid/swift,brentdax/swift,huonw/swift,dduan/swift,jopamer/swift,tjw/swift,johnno1962d/swift,return/swift,roambotics/swift,gmilos/swift,Jnosh/swift,alblue/swift,hughbe/swift,jopamer/swift,uasys/swift,kentya6/swift,manavgabhawala/swift,LeoShimonaka/swift,felix91gr/swift,codestergit/swift,lorentey/swift,KrishMunot/swift,tkremenek/swift,practicalswift/swift,alblue/swift,tardieu/swift,mightydeveloper/swift,OscarSwanros/swift,jtbandes/swift,austinzheng/swift,allevato/swift,austinzheng/swift,shajrawi/swift,jckarter/swift,gmilos/swift,danielmartin/swift,jckarter/swift,parkera/swift,kentya6/swift,manavgabhawala/swift,arvedviehweger/swift,OscarSwanros/swift,shahmishal/swift,tinysun212/swift-windows,jckarter/swift,ahoppen/swift,brentdax/swift,Jnosh/swift,return/swift,gottesmm/swift,jmgc/swift,airspeedswift/swift,ahoppen/swift,frootloops/swift,jtbandes/swift,uasys/swift,hooman/swift,gmilos/swift,tinysun212/swift-windows,arvedviehweger/swift,huonw/swift,khizkhiz/swift,kusl/swift,deyton/swift,ben-ng/swift,milseman/swift,kstaring/swift,russbishop/swift,manavgabhawala/swift,felix91gr/swift,natecook1000/swift,amraboelela/swift,KrishMunot/swift,ken0nek/swift,swiftix/swift,amraboelela/swift,ahoppen/swift,gribozavr/swift,airspeedswift/swift,codestergit/swift,rudkx/swift,parkera/swift,karwa/swift,jopamer/swift,kperryua/swift,shajrawi/swift,shahmishal/swift,karwa/swift,atrick/swift,felix91gr/swift,uasys/swift,cbrentharris/swift,gribozavr/swift,russbishop/swift,kentya6/swift,modocache/swift,JGiola/swift,tkremenek/swift,apple/swift,jmgc/swift,gregomni/swift,austinzheng/swift,lorentey/swift,modocache/swift,djwbrown/swift,emilstahl/swift,tinysun212/swift-windows,JGiola/swift,emilstahl/swift,parkera/swift,tardieu/swift,sdulal/swift,parkera/swift,Ivacker/swift,kperryua/swift,airspeedswift/swift,codestergit/swift,harlanhaskins/swift,swiftix/swift,gregomni/swift,swiftix/swift,cbrentharris/swift,stephentyrone/swift,return/swift,shajrawi/swift,uasys/swift,JaSpa/swift,milseman/swift,karwa/swift,hooman/swift,shajrawi/swift,KrishMunot/swift,harlanhaskins/swift,frootloops/swift,modocache/swift,xwu/swift,mightydeveloper/swift,nathawes/swift,calebd/swift,johnno1962d/swift,arvedviehweger/swift,cbrentharris/swift,modocache/swift,adrfer/swift,CodaFi/swift,alblue/swift,uasys/swift,SwiftAndroid/swift,sschiau/swift,hooman/swift,Ivacker/swift,OscarSwanros/swift,mightydeveloper/swift,jtbandes/swift,MukeshKumarS/Swift,gregomni/swift,dduan/swift,slavapestov/swift,nathawes/swift,devincoughlin/swift,roambotics/swift,OscarSwanros/swift,amraboelela/swift,aschwaighofer/swift,nathawes/swift,manavgabhawala/swift,Jnosh/swift,gregomni/swift,gmilos/swift,apple/swift,swiftix/swift.old,sschiau/swift,swiftix/swift.old,bitjammer/swift,emilstahl/swift,sdulal/swift,Ivacker/swift,kentya6/swift,johnno1962d/swift,aschwaighofer/swift,tinysun212/swift-windows,arvedviehweger/swift,practicalswift/swift,johnno1962d/swift,tardieu/swift,calebd/swift,kusl/swift,deyton/swift,khizkhiz/swift,deyton/swift,gribozavr/swift,ben-ng/swift,tjw/swift,jtbandes/swift,stephentyrone/swift,atrick/swift,roambotics/swift,frootloops/swift,benlangmuir/swift,ken0nek/swift,tardieu/swift,adrfer/swift,xedin/swift,jopamer/swift,xedin/swift,austinzheng/swift,allevato/swift,sschiau/swift,jtbandes/swift,kstaring/swift,aschwaighofer/swift,practicalswift/swift,JaSpa/swift,shahmishal/swift,xwu/swift,IngmarStein/swift,CodaFi/swift,bitjammer/swift,atrick/swift,therealbnut/swift,xwu/swift,rudkx/swift,huonw/swift,natecook1000/swift,gottesmm/swift,bitjammer/swift,austinzheng/swift,tardieu/swift,hooman/swift,tardieu/swift,swiftix/swift,emilstahl/swift,manavgabhawala/swift,natecook1000/swift,sschiau/swift,xedin/swift,cbrentharris/swift,swiftix/swift,adrfer/swift,kusl/swift,felix91gr/swift,djwbrown/swift,sdulal/swift,return/swift,JGiola/swift,felix91gr/swift,kstaring/swift,devincoughlin/swift,kstaring/swift,xwu/swift,harlanhaskins/swift,gribozavr/swift,tinysun212/swift-windows,kusl/swift,devincoughlin/swift,felix91gr/swift,ken0nek/swift,allevato/swift,swiftix/swift,JaSpa/swift,djwbrown/swift,gottesmm/swift,CodaFi/swift,mightydeveloper/swift,khizkhiz/swift,khizkhiz/swift,tkremenek/swift,JaSpa/swift,milseman/swift,frootloops/swift,huonw/swift,Ivacker/swift,bitjammer/swift,danielmartin/swift,emilstahl/swift,nathawes/swift,xedin/swift,stephentyrone/swift,sdulal/swift,LeoShimonaka/swift,ken0nek/swift,aschwaighofer/swift,alblue/swift,slavapestov/swift,dduan/swift,russbishop/swift,Ivacker/swift,atrick/swift,shahmishal/swift,sdulal/swift,jtbandes/swift,return/swift,CodaFi/swift,JGiola/swift,uasys/swift,IngmarStein/swift,alblue/swift,stephentyrone/swift,natecook1000/swift,danielmartin/swift,zisko/swift,gregomni/swift,sdulal/swift,swiftix/swift.old,dduan/swift
|
085045c4cae1f25e994f1f3607b01a6bb76cab17
|
test/helper/TestHelper.hpp
|
test/helper/TestHelper.hpp
|
#pragma once
#include <zmqpp/zmqpp.hpp>
#include "FakeGPIO.hpp"
#include <boost/property_tree/ptree.hpp>
#include "gtest/gtest.h"
#include "core/MessageBus.hpp"
/**
* Helper function that create an object of type ModuleType (using conventional parameter) and run it.
*/
template<typename ModuleType>
bool test_run_module(zmqpp::context *ctx, zmqpp::socket *pipe, const boost::property_tree::ptree &cfg)
{
ModuleType module(*ctx, pipe, cfg);
pipe->send(zmqpp::signal::ok);
module.run();
return true;
}
/**
* Part of the `bus_read()` stuff.
*/
bool bus_read_extract(zmqpp::message * m)
{
return true;
}
/**
* Default frame extraction function.
*/
template<typename T, typename ...Content>
bool bus_read_extract(zmqpp::message *m, T first_arg, Content... content)
{
T value;
*m >> value;
if (value != first_arg)
return false;
return bus_read_extract(m, content...);
}
/**
* Frame extraction method specialized (thanks to overloading) for `const char *`
*/
template<typename ...Content>
bool bus_read_extract(zmqpp::message *m, const char *first_arg, Content... content)
{
std::string value;
*m >> value;
if (strcmp(value.c_str(), first_arg) != 0)
return false;
return bus_read_extract(m, content...);
}
/**
* Make a blocking read on the bus, return true if content match the message.
* false otherwise.
*/
template<typename ...Content>
bool bus_read(zmqpp::socket &sub, Content... content)
{
zmqpp::message msg;
if (!sub.receive(msg))
return false;
return bus_read_extract(&msg, content...);
}
/**
* Base class for test fixtures, it defines a ZMQ context, a BUS and a sub socket connect to the bus.
*/
class TestHelper : public ::testing::Test
{
private:
/**
* Called in the module's actor's thread.
* Override this: Construct configuration for the module then `run_test_module()` with appropriate parameters.
*/
virtual bool run_module(zmqpp::socket *pipe) = 0;
public:
TestHelper() :
ctx_(),
bus_(ctx_),
bus_sub_(ctx_, zmqpp::socket_type::sub),
bus_push_(ctx_, zmqpp::socket_type::push),
module_actor_(nullptr)
{
bus_sub_.connect("inproc://zmq-bus-pub");
bus_push_.connect("inproc://zmq-bus-pull");
}
virtual ~TestHelper()
{
delete module_actor_;
}
/**
* We need this 2-step initialization to prevent calling virtual method (run_module) in constructor.
*/
virtual void SetUp() override final
{
module_actor_ = new zmqpp::actor(std::bind(&TestHelper::run_module, this, std::placeholders::_1));
}
/**
* A context for the test case
*/
zmqpp::context ctx_;
/**
* A BUS identical to the one spawned by core.
*/
MessageBus bus_;
/**
* A SUB socket connected to the previous bus.
*/
zmqpp::socket bus_sub_;
/**
* A PUSH socket to write on the bus.
*/
zmqpp::socket bus_push_;
/**
* An actor, to run the module code the same way it would be run by the core.
* Does NOT subscribe to anything.
*/
zmqpp::actor *module_actor_;
};
|
#pragma once
#include <zmqpp/zmqpp.hpp>
#include "FakeGPIO.hpp"
#include <boost/property_tree/ptree.hpp>
#include "gtest/gtest.h"
#include "core/MessageBus.hpp"
extern thread_local zmqpp::socket *tl_log_socket;
/**
* Helper function that create an object of type ModuleType (using conventional parameter) and run it.
* This runs in "module"'s thread.
*/
template<typename ModuleType>
bool test_run_module(zmqpp::context *ctx, zmqpp::socket *pipe, const boost::property_tree::ptree &cfg)
{
//create log socket for module thread
tl_log_socket = new zmqpp::socket(*ctx, zmqpp::socket_type::push);
tl_log_socket->connect("inproc://log-sink");
ModuleType module(*ctx, pipe, cfg);
pipe->send(zmqpp::signal::ok);
module.run();
delete tl_log_socket;
return true;
}
/**
* Part of the `bus_read()` stuff.
*/
bool bus_read_extract(zmqpp::message *)
{
return true;
}
/**
* Default frame extraction function.
*/
template<typename T, typename ...Content>
bool bus_read_extract(zmqpp::message *m, T first_arg, Content... content)
{
T value;
*m >> value;
if (value != first_arg)
return false;
return bus_read_extract(m, content...);
}
/**
* Frame extraction method specialized (thanks to overloading) for `const char *`
*/
template<typename ...Content>
bool bus_read_extract(zmqpp::message *m, const char *first_arg, Content... content)
{
std::string value;
*m >> value;
if (strcmp(value.c_str(), first_arg) != 0)
return false;
return bus_read_extract(m, content...);
}
/**
* Make a blocking read on the bus, return true if content match the message.
* false otherwise.
*/
template<typename ...Content>
bool bus_read(zmqpp::socket &sub, Content... content)
{
zmqpp::message msg;
if (!sub.receive(msg))
return false;
return bus_read_extract(&msg, content...);
}
/**
* Base class for test fixtures, it defines a ZMQ context, a BUS and a sub socket connect to the bus.
*/
class TestHelper : public ::testing::Test
{
private:
/**
* Called in the module's actor's thread.
* Override this: Construct configuration for the module then `run_test_module()` with appropriate parameters.
*/
virtual bool run_module(zmqpp::socket *pipe) = 0;
public:
TestHelper() :
ctx_(),
bus_(ctx_),
bus_sub_(ctx_, zmqpp::socket_type::sub),
bus_push_(ctx_, zmqpp::socket_type::push),
module_actor_(nullptr)
{
// create the log socket for main thread.
tl_log_socket = new zmqpp::socket(ctx_, zmqpp::socket_type::push);
tl_log_socket->connect("inproc://log-sink");
bus_sub_.connect("inproc://zmq-bus-pub");
bus_push_.connect("inproc://zmq-bus-pull");
}
virtual ~TestHelper()
{
delete tl_log_socket;
delete module_actor_;
}
/**
* We need this 2-step initialization to prevent calling virtual method (run_module) in constructor.
*/
virtual void SetUp() override final
{
module_actor_ = new zmqpp::actor(std::bind(&TestHelper::run_module, this, std::placeholders::_1));
}
/**
* A context for the test case
*/
zmqpp::context ctx_;
/**
* A BUS identical to the one spawned by core.
*/
MessageBus bus_;
/**
* A SUB socket connected to the previous bus.
*/
zmqpp::socket bus_sub_;
/**
* A PUSH socket to write on the bus.
*/
zmqpp::socket bus_push_;
/**
* An actor, to run the module code the same way it would be run by the core.
* Does NOT subscribe to anything.
*/
zmqpp::actor *module_actor_;
};
|
fix unittest helper
|
fix unittest helper
Former-commit-id: 23a0dd5f8231dae295f1c6ead41f81b08290dcd2
Former-commit-id: b7bf381bd9f93f5cdebcdf758d288356f66ca9ad
|
C++
|
agpl-3.0
|
leosac/leosac,islog/leosac,islog/leosac,leosac/leosac,leosac/leosac,islog/leosac
|
85008d22ebe02ccc9570536f92b833400505eebe
|
plugins/robots/generators/generatorBase/src/structuralControlFlowGenerator.cpp
|
plugins/robots/generators/generatorBase/src/structuralControlFlowGenerator.cpp
|
/* Copyright 2017 QReal Research Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "structuralControlFlowGenerator.h"
#include <QtCore/QQueue>
#include <QtCore/QDebug>
#include <algorithm>
#include "generatorBase/parts/subprograms.h"
#include "generatorBase/parts/threads.h"
using namespace qReal;
using namespace generatorBase;
using namespace semantics;
StructuralControlFlowGenerator::StructuralControlFlowGenerator(const qrRepo::RepoApi &repo
, ErrorReporterInterface &errorReporter
, GeneratorCustomizer &customizer
, PrimaryControlFlowValidator &validator
, const Id &diagramId
, QObject *parent
, bool isThisDiagramMain)
: ControlFlowGeneratorBase(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)
, mCantBeGeneratedIntoStructuredCode(false)
, mStructurizator(new Structurizator(this))
, mVerticesNumber(0)
, mStructurizationWasPerformed(false)
{
}
ControlFlowGeneratorBase *StructuralControlFlowGenerator::cloneFor(const Id &diagramId, bool cloneForNewDiagram)
{
StructuralControlFlowGenerator * const copy = new StructuralControlFlowGenerator(mRepo
, mErrorReporter, mCustomizer, (cloneForNewDiagram ? *mValidator.clone() : mValidator)
, diagramId, parent(), false);
return copy;
}
void StructuralControlFlowGenerator::beforeSearch()
{
}
void StructuralControlFlowGenerator::visit(const Id &id, QList<LinkInfo> &links)
{
if (mIds.isEmpty()) {
mStartVertex = id;
}
if (!mIds.contains(id)) {
appendVertex(id);
}
ControlFlowGeneratorBase::visit(id, links);
for (const LinkInfo &link : links) {
const qReal::Id otherVertex = link.target;
if (!mIds.contains(otherVertex)) {
appendVertex(otherVertex);
}
addEdgeIntoGraph(id, otherVertex);
}
}
void StructuralControlFlowGenerator::visitConditional(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitLoop(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitSwitch(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitUnknown(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::afterSearch()
{
}
bool StructuralControlFlowGenerator::cantBeGeneratedIntoStructuredCode() const
{
return mCantBeGeneratedIntoStructuredCode;
}
void StructuralControlFlowGenerator::performGeneration()
{
ControlFlowGeneratorBase::performGeneration();
myUtils::IntermediateNode *tree = mStructurizator->performStructurization(mIds, mVertexNumber[mStartVertex], mFollowers, mVertexNumber, mVerticesNumber);
if (tree) {
obtainSemanticTree(tree);
mStructurizationWasPerformed = true;
ControlFlowGeneratorBase::performGeneration();
} else {
mCantBeGeneratedIntoStructuredCode = true;
}
if (mCantBeGeneratedIntoStructuredCode) {
mSemanticTree = nullptr;
}
}
bool StructuralControlFlowGenerator::applyRuleWhileVisiting(SemanticTransformationRule * const rule)
{
if (mStructurizationWasPerformed) {
return ControlFlowGeneratorBase::applyRuleWhileVisiting(rule);
}
return false;
}
void StructuralControlFlowGenerator::obtainSemanticTree(myUtils::IntermediateNode *root)
{
root->analyzeBreak();
SemanticNode * semanticNode = transformNode(root);
mSemanticTree->setRoot(new RootNode(semanticNode, mSemanticTree));
}
void StructuralControlFlowGenerator::checkAndAppendBlock(ZoneNode *zone, myUtils::IntermediateNode *node)
{
if (node->type() == myUtils::IntermediateNode::simple) {
myUtils::SimpleNode *simpleNode = static_cast<myUtils::SimpleNode *>(node);
switch (semanticsOf(simpleNode->id())) {
case enums::semantics::conditionalBlock:
case enums::semantics::switchBlock:
break;
default:
zone->appendChild(transformSimple(simpleNode));
}
} else {
zone->appendChild(transformNode(node));
}
}
// maybe use strategy to recursively handle this situation?
SemanticNode *StructuralControlFlowGenerator::transformNode(myUtils::IntermediateNode *node)
{
switch (node->type()) {
case myUtils::IntermediateNode::Type::simple: {
myUtils::SimpleNode *simpleNode = static_cast<myUtils::SimpleNode *>(node);
return transformSimple(simpleNode);
}
case myUtils::IntermediateNode::Type::block: {
myUtils::BlockNode *blockNode = static_cast<myUtils::BlockNode *>(node);
return transformBlock(blockNode);
}
case myUtils::IntermediateNode::Type::ifThenElseCondition: {
myUtils::IfNode *ifNode = static_cast<myUtils::IfNode *>(node);
return transformIfThenElse(ifNode);
}
case myUtils::IntermediateNode::Type::switchCondition: {
myUtils::SwitchNode *switchNode = static_cast<myUtils::SwitchNode *>(node);
return transformSwitch(switchNode);
}
case myUtils::IntermediateNode::Type::infiniteloop: {
myUtils::SelfLoopNode *selfLoopNode = static_cast<myUtils::SelfLoopNode *>(node);
return transformSelfLoop(selfLoopNode);
}
case myUtils::IntermediateNode::Type::whileloop: {
myUtils::WhileNode *whileNode = static_cast<myUtils::WhileNode *>(node);
return transformWhileLoop(whileNode);
}
case myUtils::IntermediateNode::Type::breakNode: {
return transformBreakNode();
}
case myUtils::IntermediateNode::Type::fakeCycleHead: {
return transformFakeCycleHead();
}
case myUtils::IntermediateNode::Type::nodeWithBreaks: {
return createConditionWithBreaks(static_cast<myUtils::NodeWithBreaks *>(node));
}
default:
qDebug() << "Undefined type of Intermediate node!";
mCantBeGeneratedIntoStructuredCode = true;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
}
SemanticNode *StructuralControlFlowGenerator::transformSimple(myUtils::SimpleNode *simpleNode)
{
return mSemanticTree->produceNodeFor(simpleNode->id());
}
SemanticNode *StructuralControlFlowGenerator::transformBlock(myUtils::BlockNode *blockNode)
{
ZoneNode *zone = new ZoneNode(mSemanticTree);
checkAndAppendBlock(zone, blockNode->firstNode());
checkAndAppendBlock(zone, blockNode->secondNode());
return zone;
}
SemanticNode *StructuralControlFlowGenerator::transformIfThenElse(myUtils::IfNode *ifNode)
{
if (ifNode->condition()->type() == myUtils::IntermediateNode::nodeWithBreaks) {
myUtils::NodeWithBreaks *nodeWithBreaks = static_cast<myUtils::NodeWithBreaks *>(ifNode->condition());
nodeWithBreaks->setRestBranches({ifNode->thenBranch(), ifNode->elseBranch()});
return createConditionWithBreaks(nodeWithBreaks);
}
const qReal::Id conditionId = ifNode->condition()->firstId();
switch (semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock: {
return createSemanticIfNode(conditionId, ifNode->thenBranch(), ifNode->elseBranch());
}
case enums::semantics::switchBlock: {
QList<myUtils::IntermediateNode *> branches = { ifNode->thenBranch() };
if (ifNode->elseBranch()) {
branches.append(ifNode->elseBranch());
}
return createSemanticSwitchNode(conditionId, branches, ifNode->hasBreakInside());
}
default:
break;
}
qDebug() << "Problem: couldn't transform if-then-else";
mCantBeGeneratedIntoStructuredCode = true;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::transformSelfLoop(myUtils::SelfLoopNode *selfLoopNode)
{
LoopNode *semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(selfLoopNode->bodyNode()));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformWhileLoop(myUtils::WhileNode *whileNode)
{
myUtils::IntermediateNode *headNode = whileNode->headNode();
myUtils::IntermediateNode *bodyNode = whileNode->bodyNode();
myUtils::IntermediateNode *exitNode = whileNode->exitNode();
LoopNode *semanticLoop = nullptr;
const qReal::Id conditionId = headNode->firstId();
if (headNode->type() == myUtils::IntermediateNode::Type::simple) {
switch(semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock:
case enums::semantics::loopBlock: {
semanticLoop = new LoopNode(conditionId, mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(bodyNode));
return semanticLoop;
}
case enums::semantics::switchBlock: {
QList<myUtils::IntermediateNode *> exitBranches;
exitBranches.append(new myUtils::BreakNode(exitNode->firstId(), mStructurizator));
myUtils::NodeWithBreaks *nodeWithBreaks = new myUtils::NodeWithBreaks(headNode, exitBranches, mStructurizator);
nodeWithBreaks->setRestBranches( { bodyNode } );
semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(createConditionWithBreaks(nodeWithBreaks));
return semanticLoop;
}
default:
break;
}
}
semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(headNode));
semanticLoop->bodyZone()->appendChild(transformNode(bodyNode));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformSwitch(myUtils::SwitchNode *switchNode)
{
const qReal::Id &conditionId = switchNode->condition()->firstId();
QList<myUtils::IntermediateNode *> branches = switchNode->branches();
if (switchNode->condition()->type() == myUtils::IntermediateNode::nodeWithBreaks) {
myUtils::NodeWithBreaks *nodeWithBreaks = static_cast<myUtils::NodeWithBreaks *>(switchNode->condition());
nodeWithBreaks->setRestBranches(branches);
return createConditionWithBreaks(nodeWithBreaks);
}
if (semanticsOf(conditionId) == enums::semantics::switchBlock) {
return createSemanticSwitchNode(conditionId, branches, switchNode->hasBreakInside());
}
qDebug() << "Problem: couldn't identidy semantics id for switchNode";
mCantBeGeneratedIntoStructuredCode = true;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::transformBreakNode()
{
return semantics::SimpleNode::createBreakNode(mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::transformFakeCycleHead()
{
return new SimpleNode(qReal::Id(), mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::createConditionWithBreaks(myUtils::NodeWithBreaks *nodeWithBreaks)
{
const qReal::Id conditionId = nodeWithBreaks->firstId();
QList<myUtils::IntermediateNode *> exitBranches = nodeWithBreaks->exitBranches();
QList<myUtils::IntermediateNode *> restBranches = nodeWithBreaks->restBranches();
switch(semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock: {
return createSemanticIfNode(conditionId, exitBranches.first(), nullptr);
}
case enums::semantics::switchBlock: {
QList<myUtils::IntermediateNode *> allBranches = restBranches + exitBranches;
return createSemanticSwitchNode(conditionId, allBranches, true);
}
default:
qDebug() << "Problem in createConditionWithBreaks";
mCantBeGeneratedIntoStructuredCode = false;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
}
SemanticNode *StructuralControlFlowGenerator::createSemanticIfNode(const Id &conditionId, myUtils::IntermediateNode *thenNode, myUtils::IntermediateNode *elseNode)
{
IfNode *semanticIf = new IfNode(conditionId, mSemanticTree);
QPair<LinkInfo, LinkInfo> links = ifBranchesFor(conditionId);
if (links.first.target != thenNode->firstId()) {
semanticIf->invertCondition();
}
semanticIf->thenZone()->appendChild(transformNode(thenNode));
if (elseNode) {
semanticIf->elseZone()->appendChild(transformNode(elseNode));
}
return semanticIf;
}
SemanticNode *StructuralControlFlowGenerator::createSemanticSwitchNode(const Id &conditionId, const QList<myUtils::IntermediateNode *> &branches, bool generateIfs)
{
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
QMap<qReal::Id, SemanticNode *> visitedBranch;
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
if (visitedBranch.contains(otherVertex)) {
NonZoneNode * const target = static_cast<NonZoneNode *>(visitedBranch[otherVertex]);
semanticSwitch->mergeBranch(expression, target);
} else {
bool branchNodeWasFound = false;
SemanticNode *semanticNodeForBranch = nullptr;
for (myUtils::IntermediateNode *branchNode : branches) {
if (branchNode->firstId() == otherVertex) {
semanticNodeForBranch = transformNode(branchNode);
branchNodeWasFound = true;
break;
}
}
if (!branchNodeWasFound) {
semanticNodeForBranch = new SimpleNode(qReal::Id(), this);
}
semanticSwitch->addBranch(expression, semanticNodeForBranch);
visitedBranch[otherVertex] = semanticNodeForBranch;
}
}
if (generateIfs) {
semanticSwitch->setGenerateIfs();
}
return semanticSwitch;
}
void StructuralControlFlowGenerator::appendVertex(const Id &vertex)
{
mIds.insert(vertex);
mVerticesNumber++;
mVertexNumber[vertex] = mVerticesNumber;
}
void StructuralControlFlowGenerator::addEdgeIntoGraph(const Id &from, const Id &to)
{
mFollowers[mVertexNumber[from]].insert(mVertexNumber[to]);
}
|
/* Copyright 2017 QReal Research Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "structuralControlFlowGenerator.h"
#include <QtCore/QQueue>
#include <QtCore/QDebug>
#include <algorithm>
#include "generatorBase/parts/subprograms.h"
#include "generatorBase/parts/threads.h"
using namespace qReal;
using namespace generatorBase;
using namespace semantics;
StructuralControlFlowGenerator::StructuralControlFlowGenerator(const qrRepo::RepoApi &repo
, ErrorReporterInterface &errorReporter
, GeneratorCustomizer &customizer
, PrimaryControlFlowValidator &validator
, const Id &diagramId
, QObject *parent
, bool isThisDiagramMain)
: ControlFlowGeneratorBase(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)
, mCantBeGeneratedIntoStructuredCode(false)
, mStructurizator(new Structurizator(this))
, mVerticesNumber(0)
, mStructurizationWasPerformed(false)
{
}
ControlFlowGeneratorBase *StructuralControlFlowGenerator::cloneFor(const Id &diagramId, bool cloneForNewDiagram)
{
StructuralControlFlowGenerator * const copy = new StructuralControlFlowGenerator(mRepo
, mErrorReporter, mCustomizer, (cloneForNewDiagram ? *mValidator.clone() : mValidator)
, diagramId, parent(), false);
return copy;
}
void StructuralControlFlowGenerator::beforeSearch()
{
}
void StructuralControlFlowGenerator::visit(const Id &id, QList<LinkInfo> &links)
{
if (mIds.isEmpty()) {
mStartVertex = id;
}
if (!mIds.contains(id)) {
appendVertex(id);
}
ControlFlowGeneratorBase::visit(id, links);
for (const LinkInfo &link : links) {
const qReal::Id otherVertex = link.target;
if (!mIds.contains(otherVertex)) {
appendVertex(otherVertex);
}
addEdgeIntoGraph(id, otherVertex);
}
}
void StructuralControlFlowGenerator::visitConditional(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitLoop(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitSwitch(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitUnknown(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::afterSearch()
{
}
bool StructuralControlFlowGenerator::cantBeGeneratedIntoStructuredCode() const
{
return mCantBeGeneratedIntoStructuredCode;
}
void StructuralControlFlowGenerator::performGeneration()
{
ControlFlowGeneratorBase::performGeneration();
myUtils::IntermediateNode *tree = mStructurizator->performStructurization(mIds, mVertexNumber[mStartVertex], mFollowers, mVertexNumber, mVerticesNumber);
if (tree) {
obtainSemanticTree(tree);
mStructurizationWasPerformed = true;
ControlFlowGeneratorBase::performGeneration();
} else {
mCantBeGeneratedIntoStructuredCode = true;
}
if (mCantBeGeneratedIntoStructuredCode) {
mSemanticTree = nullptr;
}
}
bool StructuralControlFlowGenerator::applyRuleWhileVisiting(SemanticTransformationRule * const rule)
{
if (mStructurizationWasPerformed) {
return ControlFlowGeneratorBase::applyRuleWhileVisiting(rule);
}
return false;
}
void StructuralControlFlowGenerator::obtainSemanticTree(myUtils::IntermediateNode *root)
{
root->analyzeBreak();
SemanticNode * semanticNode = transformNode(root);
mSemanticTree->setRoot(new RootNode(semanticNode, mSemanticTree));
}
void StructuralControlFlowGenerator::checkAndAppendBlock(ZoneNode *zone, myUtils::IntermediateNode *node)
{
if (node->type() == myUtils::IntermediateNode::simple) {
myUtils::SimpleNode *simpleNode = static_cast<myUtils::SimpleNode *>(node);
switch (semanticsOf(simpleNode->id())) {
case enums::semantics::conditionalBlock:
case enums::semantics::switchBlock:
break;
default:
zone->appendChild(transformSimple(simpleNode));
}
} else {
zone->appendChild(transformNode(node));
}
}
// maybe use strategy to recursively handle this situation?
SemanticNode *StructuralControlFlowGenerator::transformNode(myUtils::IntermediateNode *node)
{
switch (node->type()) {
case myUtils::IntermediateNode::Type::simple: {
myUtils::SimpleNode *simpleNode = static_cast<myUtils::SimpleNode *>(node);
return transformSimple(simpleNode);
}
case myUtils::IntermediateNode::Type::block: {
myUtils::BlockNode *blockNode = static_cast<myUtils::BlockNode *>(node);
return transformBlock(blockNode);
}
case myUtils::IntermediateNode::Type::ifThenElseCondition: {
myUtils::IfNode *ifNode = static_cast<myUtils::IfNode *>(node);
return transformIfThenElse(ifNode);
}
case myUtils::IntermediateNode::Type::switchCondition: {
myUtils::SwitchNode *switchNode = static_cast<myUtils::SwitchNode *>(node);
return transformSwitch(switchNode);
}
case myUtils::IntermediateNode::Type::infiniteloop: {
myUtils::SelfLoopNode *selfLoopNode = static_cast<myUtils::SelfLoopNode *>(node);
return transformSelfLoop(selfLoopNode);
}
case myUtils::IntermediateNode::Type::whileloop: {
myUtils::WhileNode *whileNode = static_cast<myUtils::WhileNode *>(node);
return transformWhileLoop(whileNode);
}
case myUtils::IntermediateNode::Type::breakNode: {
return transformBreakNode();
}
case myUtils::IntermediateNode::Type::fakeCycleHead: {
return transformFakeCycleHead();
}
case myUtils::IntermediateNode::Type::nodeWithBreaks: {
return createConditionWithBreaks(static_cast<myUtils::NodeWithBreaks *>(node));
}
default:
qDebug() << "Undefined type of Intermediate node!";
mCantBeGeneratedIntoStructuredCode = true;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
}
SemanticNode *StructuralControlFlowGenerator::transformSimple(myUtils::SimpleNode *simpleNode)
{
return mSemanticTree->produceNodeFor(simpleNode->id());
}
SemanticNode *StructuralControlFlowGenerator::transformBlock(myUtils::BlockNode *blockNode)
{
ZoneNode *zone = new ZoneNode(mSemanticTree);
checkAndAppendBlock(zone, blockNode->firstNode());
checkAndAppendBlock(zone, blockNode->secondNode());
return zone;
}
SemanticNode *StructuralControlFlowGenerator::transformIfThenElse(myUtils::IfNode *ifNode)
{
if (ifNode->condition()->type() == myUtils::IntermediateNode::nodeWithBreaks) {
myUtils::NodeWithBreaks *nodeWithBreaks = static_cast<myUtils::NodeWithBreaks *>(ifNode->condition());
nodeWithBreaks->setRestBranches({ifNode->thenBranch(), ifNode->elseBranch()});
return createConditionWithBreaks(nodeWithBreaks);
}
const qReal::Id conditionId = ifNode->condition()->firstId();
switch (semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock: {
return createSemanticIfNode(conditionId, ifNode->thenBranch(), ifNode->elseBranch());
}
case enums::semantics::switchBlock: {
QList<myUtils::IntermediateNode *> branches = { ifNode->thenBranch() };
if (ifNode->elseBranch()) {
branches.append(ifNode->elseBranch());
}
return createSemanticSwitchNode(conditionId, branches, ifNode->hasBreakInside());
}
default:
break;
}
qDebug() << "Problem: couldn't transform if-then-else";
mCantBeGeneratedIntoStructuredCode = true;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::transformSelfLoop(myUtils::SelfLoopNode *selfLoopNode)
{
LoopNode *semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(selfLoopNode->bodyNode()));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformWhileLoop(myUtils::WhileNode *whileNode)
{
myUtils::IntermediateNode *headNode = whileNode->headNode();
myUtils::IntermediateNode *bodyNode = whileNode->bodyNode();
myUtils::IntermediateNode *exitNode = whileNode->exitNode();
LoopNode *semanticLoop = nullptr;
const qReal::Id conditionId = headNode->firstId();
if (headNode->type() == myUtils::IntermediateNode::Type::simple) {
switch(semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock:
case enums::semantics::loopBlock: {
semanticLoop = new LoopNode(conditionId, mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(bodyNode));
return semanticLoop;
}
case enums::semantics::switchBlock: {
QList<myUtils::IntermediateNode *> exitBranches;
exitBranches.append(new myUtils::BreakNode(exitNode->firstId(), mStructurizator));
myUtils::NodeWithBreaks *nodeWithBreaks = new myUtils::NodeWithBreaks(headNode, exitBranches, mStructurizator);
nodeWithBreaks->setRestBranches( { bodyNode } );
semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(createConditionWithBreaks(nodeWithBreaks));
return semanticLoop;
}
default:
break;
}
}
semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(headNode));
semanticLoop->bodyZone()->appendChild(transformNode(bodyNode));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformSwitch(myUtils::SwitchNode *switchNode)
{
const qReal::Id &conditionId = switchNode->condition()->firstId();
QList<myUtils::IntermediateNode *> branches = switchNode->branches();
if (switchNode->condition()->type() == myUtils::IntermediateNode::nodeWithBreaks) {
myUtils::NodeWithBreaks *nodeWithBreaks = static_cast<myUtils::NodeWithBreaks *>(switchNode->condition());
nodeWithBreaks->setRestBranches(branches);
return createConditionWithBreaks(nodeWithBreaks);
}
if (semanticsOf(conditionId) == enums::semantics::switchBlock) {
return createSemanticSwitchNode(conditionId, branches, switchNode->hasBreakInside());
}
qDebug() << "Problem: couldn't identidy semantics id for switchNode";
mCantBeGeneratedIntoStructuredCode = true;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::transformBreakNode()
{
return semantics::SimpleNode::createBreakNode(mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::transformFakeCycleHead()
{
return new SimpleNode(qReal::Id(), mSemanticTree);
}
SemanticNode *StructuralControlFlowGenerator::createConditionWithBreaks(myUtils::NodeWithBreaks *nodeWithBreaks)
{
const qReal::Id conditionId = nodeWithBreaks->firstId();
QList<myUtils::IntermediateNode *> exitBranches = nodeWithBreaks->exitBranches();
QList<myUtils::IntermediateNode *> restBranches = nodeWithBreaks->restBranches();
switch(semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock: {
return createSemanticIfNode(conditionId, exitBranches.first(), nullptr);
}
case enums::semantics::switchBlock: {
QList<myUtils::IntermediateNode *> allBranches = restBranches + exitBranches;
return createSemanticSwitchNode(conditionId, allBranches, true);
}
default:
qDebug() << "Problem in createConditionWithBreaks";
mCantBeGeneratedIntoStructuredCode = false;
return new SimpleNode(qReal::Id(), mSemanticTree);
}
}
SemanticNode *StructuralControlFlowGenerator::createSemanticIfNode(const Id &conditionId, myUtils::IntermediateNode *thenNode, myUtils::IntermediateNode *elseNode)
{
IfNode *semanticIf = new IfNode(conditionId, mSemanticTree);
QPair<LinkInfo, LinkInfo> links = ifBranchesFor(conditionId);
if (links.first.target != thenNode->firstId()) {
if (elseNode) {
myUtils::IntermediateNode *tmp = thenNode;
thenNode = elseNode;
elseNode = tmp;
} else {
semanticIf->invertCondition();
}
}
semanticIf->thenZone()->appendChild(transformNode(thenNode));
if (elseNode) {
semanticIf->elseZone()->appendChild(transformNode(elseNode));
}
return semanticIf;
}
SemanticNode *StructuralControlFlowGenerator::createSemanticSwitchNode(const Id &conditionId, const QList<myUtils::IntermediateNode *> &branches, bool generateIfs)
{
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
QMap<qReal::Id, SemanticNode *> visitedBranch;
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
if (visitedBranch.contains(otherVertex)) {
NonZoneNode * const target = static_cast<NonZoneNode *>(visitedBranch[otherVertex]);
semanticSwitch->mergeBranch(expression, target);
} else {
bool branchNodeWasFound = false;
SemanticNode *semanticNodeForBranch = nullptr;
for (myUtils::IntermediateNode *branchNode : branches) {
if (branchNode->firstId() == otherVertex) {
semanticNodeForBranch = transformNode(branchNode);
branchNodeWasFound = true;
break;
}
}
if (!branchNodeWasFound) {
semanticNodeForBranch = new SimpleNode(qReal::Id(), this);
}
semanticSwitch->addBranch(expression, semanticNodeForBranch);
visitedBranch[otherVertex] = semanticNodeForBranch;
}
}
if (generateIfs) {
semanticSwitch->setGenerateIfs();
}
return semanticSwitch;
}
void StructuralControlFlowGenerator::appendVertex(const Id &vertex)
{
mIds.insert(vertex);
mVerticesNumber++;
mVertexNumber[vertex] = mVerticesNumber;
}
void StructuralControlFlowGenerator::addEdgeIntoGraph(const Id &from, const Id &to)
{
mFollowers[mVertexNumber[from]].insert(mVertexNumber[to]);
}
|
Fix bug with if-then-else. Excess invertion of condition
|
Fix bug with if-then-else. Excess invertion of condition
|
C++
|
apache-2.0
|
iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal
|
759595acc9475be16d2474ea83dfa34c90dedf60
|
src/database/DatabaseServer.cpp
|
src/database/DatabaseServer.cpp
|
#include "core/global.h"
#include "core/RoleFactory.h"
#include "DBEngineFactory.h"
#include "IDatabaseEngine.h"
#include <fstream>
ConfigVariable<channel_t> control_channel("control", 0);
ConfigVariable<unsigned int> id_min("generate/min", 0);
ConfigVariable<unsigned int> id_max("generate/max", UINT_MAX);
ConfigVariable<std::string> engine_type("engine/type", "filesystem");
class DatabaseServer : public Role
{
private:
IDatabaseEngine *m_db_engine;
LogCategory *m_log;
public:
DatabaseServer(RoleConfig roleconfig) : Role(roleconfig),
m_db_engine(DBEngineFactory::singleton.instantiate(
engine_type.get_rval(roleconfig),
roleconfig["engine"],
id_min.get_rval(roleconfig)))
{
std::stringstream ss;
ss << "Database(" << control_channel.get_rval(m_roleconfig) << ")";
m_log = new LogCategory("db", ss.str());
if(!m_db_engine)
{
m_log->fatal() << "No database engine of type '" << engine_type.get_rval(roleconfig) << "' exists." << std::endl;
exit(1);
}
subscribe_channel(control_channel.get_rval(m_roleconfig));
}
virtual void handle_datagram(Datagram &in_dg, DatagramIterator &dgi)
{
channel_t sender = dgi.read_uint64();
unsigned short msg_type = dgi.read_uint16();
switch(msg_type)
{
case DBSERVER_CREATE_STORED_OBJECT:
{
unsigned int context = dgi.read_uint32();
Datagram resp;
resp.add_server_header(sender, control_channel.get_rval(m_roleconfig), DBSERVER_CREATE_STORED_OBJECT_RESP);
resp.add_uint32(context);
unsigned short dc_id = dgi.read_uint16();
DCClass *dcc = gDCF->get_class(dc_id);
if(!dcc)
{
m_log->error() << "Invalid DCClass when creating object. #" << dc_id << std::endl;
resp.add_uint32(0);
send(resp);
return;
}
unsigned short field_count = dgi.read_uint16();
unsigned int do_id = m_db_engine->get_next_id();
if(do_id > id_max.get_rval(m_roleconfig) || do_id == 0)
{
m_log->error() << "Ran out of DistributedObject ids while creating new object." << std::endl;
resp.add_uint32(0);
send(resp);
return;
}
DatabaseObject dbo;
dbo.do_id = do_id;
dbo.dc_id = dc_id;
m_log->spam() << "Unpacking fields..." << std::endl;
try
{
for(unsigned int i = 0; i < field_count; ++i)
{
unsigned short field_id = dgi.read_uint16();
DCField *field = dcc->get_field_by_index(field_id);
if(field)
{
if(field->is_db())
{
dgi.unpack_field(field, dbo.fields[field]);
}
else
{
std::string tmp;
dgi.unpack_field(field, tmp);
}
}
}
}
catch(std::exception &e)
{
m_log->error() << "Error while unpacking fields, msg may be truncated. e.what(): "
<< e.what() << std::endl;
resp.add_uint32(0);
send(resp);
return;
}
m_log->spam() << "Checking all required fields exist..." << std::endl;
for(int i = 0; i < dcc->get_num_inherited_fields(); ++i)
{
DCField *field = dcc->get_inherited_field(i);
if(field->is_required() && field->is_db() && !field->as_molecular_field())
{
if(dbo.fields.find(field) == dbo.fields.end())
{
if(!field->has_default_value())
{
m_log->error() << "Field " << field->get_name() << " missing when trying to create "
"object of type " << dcc->get_name();
resp.add_uint32(0);
send(resp);
return;
}
else
{
dbo.fields[field] = field->get_default_value();
}
}
}
}
m_log->spam() << "Creating stored object with ID: " << do_id << " ..." << std::endl;
if(m_db_engine->create_object(dbo))
{
resp.add_uint32(do_id);
}
else
{
resp.add_uint32(0);
}
send(resp);
}
break;
case DBSERVER_SELECT_STORED_OBJECT_ALL:
{
unsigned int context = dgi.read_uint32();
Datagram resp;
resp.add_server_header(sender, control_channel.get_rval(m_roleconfig), DBSERVER_SELECT_STORED_OBJECT_ALL_RESP);
resp.add_uint32(context);
DatabaseObject dbo;
dbo.do_id = dgi.read_uint32();
if(m_db_engine->get_object(dbo))
{
resp.add_uint8(1);
resp.add_uint16(dbo.dc_id);
resp.add_uint16(dbo.fields.size());
for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it)
{
resp.add_uint16(it->first->get_number());
resp.add_data(it->second);
}
}
else
{
resp.add_uint8(0);
}
send(resp);
}
break;
case DBSERVER_DELETE_STORED_OBJECT:
{
if(dgi.read_uint32() == DBSERVER_DELETE_STORED_OBJECT_VERIFY_CODE)
{
unsigned int do_id = dgi.read_uint32();
m_db_engine->delete_object(do_id);
}
else
{
m_log->warning() << "Wrong delete verify code." << std::endl;
}
}
break;
default:
m_log->error() << "Recieved unknown MsgType: " << msg_type << std::endl;
};
}
};
RoleFactoryItem<DatabaseServer> dbserver_fact("database");
|
#include "core/global.h"
#include "core/RoleFactory.h"
#include "DBEngineFactory.h"
#include "IDatabaseEngine.h"
#include <fstream>
ConfigVariable<channel_t> control_channel("control", 0);
ConfigVariable<unsigned int> id_min("generate/min", 0);
ConfigVariable<unsigned int> id_max("generate/max", UINT_MAX);
ConfigVariable<std::string> engine_type("engine/type", "filesystem");
class DatabaseServer : public Role
{
private:
IDatabaseEngine *m_db_engine;
LogCategory *m_log;
channel_t m_control_channel;
unsigned int m_id_min, m_id_max;
public:
DatabaseServer(RoleConfig roleconfig) : Role(roleconfig),
m_db_engine(DBEngineFactory::singleton.instantiate(
engine_type.get_rval(roleconfig),
roleconfig["engine"],
id_min.get_rval(roleconfig))),
m_control_channel(control_channel.get_rval(roleconfig)),
m_id_min(id_min.get_rval(roleconfig)),
m_id_max(id_max.get_rval(roleconfig))
{
std::stringstream ss;
ss << "Database(" << m_control_channel << ")";
m_log = new LogCategory("db", ss.str());
if(!m_db_engine)
{
m_log->fatal() << "No database engine of type '" << engine_type.get_rval(roleconfig) << "' exists." << std::endl;
exit(1);
}
subscribe_channel(m_control_channel);
}
virtual void handle_datagram(Datagram &in_dg, DatagramIterator &dgi)
{
channel_t sender = dgi.read_uint64();
unsigned short msg_type = dgi.read_uint16();
switch(msg_type)
{
case DBSERVER_CREATE_STORED_OBJECT:
{
unsigned int context = dgi.read_uint32();
Datagram resp;
resp.add_server_header(sender, m_control_channel, DBSERVER_CREATE_STORED_OBJECT_RESP);
resp.add_uint32(context);
unsigned short dc_id = dgi.read_uint16();
DCClass *dcc = gDCF->get_class(dc_id);
if(!dcc)
{
m_log->error() << "Invalid DCClass when creating object. #" << dc_id << std::endl;
resp.add_uint32(0);
send(resp);
return;
}
unsigned short field_count = dgi.read_uint16();
unsigned int do_id = m_db_engine->get_next_id();
if(do_id > m_id_max || do_id == 0)
{
m_log->error() << "Ran out of DistributedObject ids while creating new object." << std::endl;
resp.add_uint32(0);
send(resp);
return;
}
DatabaseObject dbo;
dbo.do_id = do_id;
dbo.dc_id = dc_id;
m_log->spam() << "Unpacking fields..." << std::endl;
try
{
for(unsigned int i = 0; i < field_count; ++i)
{
unsigned short field_id = dgi.read_uint16();
DCField *field = dcc->get_field_by_index(field_id);
if(field)
{
if(field->is_db())
{
dgi.unpack_field(field, dbo.fields[field]);
}
else
{
std::string tmp;
dgi.unpack_field(field, tmp);
}
}
}
}
catch(std::exception &e)
{
m_log->error() << "Error while unpacking fields, msg may be truncated. e.what(): "
<< e.what() << std::endl;
resp.add_uint32(0);
send(resp);
return;
}
m_log->spam() << "Checking all required fields exist..." << std::endl;
for(int i = 0; i < dcc->get_num_inherited_fields(); ++i)
{
DCField *field = dcc->get_inherited_field(i);
if(field->is_required() && field->is_db() && !field->as_molecular_field())
{
if(dbo.fields.find(field) == dbo.fields.end())
{
if(!field->has_default_value())
{
m_log->error() << "Field " << field->get_name() << " missing when trying to create "
"object of type " << dcc->get_name();
resp.add_uint32(0);
send(resp);
return;
}
else
{
dbo.fields[field] = field->get_default_value();
}
}
}
}
m_log->spam() << "Creating stored object with ID: " << do_id << " ..." << std::endl;
if(m_db_engine->create_object(dbo))
{
resp.add_uint32(do_id);
}
else
{
resp.add_uint32(0);
}
send(resp);
}
break;
case DBSERVER_SELECT_STORED_OBJECT_ALL:
{
unsigned int context = dgi.read_uint32();
Datagram resp;
resp.add_server_header(sender, m_control_channel, DBSERVER_SELECT_STORED_OBJECT_ALL_RESP);
resp.add_uint32(context);
DatabaseObject dbo;
dbo.do_id = dgi.read_uint32();
if(m_db_engine->get_object(dbo))
{
resp.add_uint8(1);
resp.add_uint16(dbo.dc_id);
resp.add_uint16(dbo.fields.size());
for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it)
{
resp.add_uint16(it->first->get_number());
resp.add_data(it->second);
}
}
else
{
resp.add_uint8(0);
}
send(resp);
}
break;
case DBSERVER_DELETE_STORED_OBJECT:
{
if(dgi.read_uint32() == DBSERVER_DELETE_STORED_OBJECT_VERIFY_CODE)
{
unsigned int do_id = dgi.read_uint32();
m_db_engine->delete_object(do_id);
}
else
{
m_log->warning() << "Wrong delete verify code." << std::endl;
}
}
break;
default:
m_log->error() << "Recieved unknown MsgType: " << msg_type << std::endl;
};
}
};
RoleFactoryItem<DatabaseServer> dbserver_fact("database");
|
Store config values in member variables for performance, and for the eventual structure to allow multiple DBServers per daemon.
|
DBServer: Store config values in member variables for performance, and for the eventual structure to allow multiple DBServers per daemon.
|
C++
|
bsd-3-clause
|
pizcogirl/Astron,ketoo/Astron,pizcogirl/Astron,pizcogirl/Astron,ketoo/Astron,blindsighttf2/Astron,ketoo/Astron,blindsighttf2/Astron,blindsighttf2/Astron,blindsighttf2/Astron,pizcogirl/Astron,ketoo/Astron
|
ee2814b87d2bd67245f20f933b58b9da2b72dbaf
|
wildcard_matching.cpp
|
wildcard_matching.cpp
|
/////////////////////////////////////
// File Name : wildcard matching
//////////////////////////////////////
#include <string>
#include <vector>
#include <iostream>
#include <bitset>
#include <fstream>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;
/////////// Description ///////////////////////////////////////////////////////////////////////////////////////////////
// Program maps the arbitrary wildcard rules (includes '0', '1', and '*') into two different parts: bitMask, and wildMask.
// bitMask: parse the '*' and '0' into '0', the '1' into '1'.
// wildMask: parse the '*' into '0', the '0' and '1' into '1'.
// ruleMatch: Bool (Incoming packet & wildMask == bitMask), if true, then match, if false, don't match
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// Input File Format ////////////////////////////////////////////////////////////////////////////////////////////
/* Rules */
// *11*0110 drop
// **1010** port1
// 0011*110 port2
// 0011010* port3
// 10101100 port4
/* Incoming packets */
// 01110110
// 10001010
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Test whether the incoming packet match the rule table */
vector<int> ruleMatches( string packet, vector< vector<int> > bitMask, /* return to a int value */
vector< vector<int> > wildMask) /* 2-dim vector */
{
vector<int> result;
for(int j = 0; j < bitMask.size(); j++) /* when using vector, don't need to declare the size of vector, use .size() */
{
int match = 1;
for (int i = 0; i < packet.size(); ++i)
{
if(((packet[i]-'0') & wildMask[j][i]) != bitMask[j][i]){
match = 0;
}
}
if(match)
result.push_back(j);
}
if(result.empty())
result.push_back(-1);
return result;
}
/* Parse the rules into wildmask. */
/* retrun int vector. */
vector< vector<int> > parseWildmask(vector<string> &ruleArray)
{
vector< vector<int> > wildMask(ruleArray.size(), vector<int>(ruleArray[0].size()));
for(int i = 0; i < ruleArray.size(); i++)
{
for (int j = 0; j < ruleArray[0].size(); j++)
{
if (ruleArray[i][j] == '*')
wildMask[i][j] = 0;
else
wildMask[i][j] = 1;
}
}
return wildMask;
}
/* Parse the rules into bitmask. */
/* retrun int vector. */
vector< vector<int> > parseBitmask(vector<string> &ruleArray)
{
vector< vector<int> > bitMask(ruleArray.size(), vector<int>(ruleArray[0].size()));
for(int i = 0; i < ruleArray.size(); i++)
{
for (int j = 0; j < ruleArray[0].size(); j++)
{
if (ruleArray[i][j] == '0' || ruleArray[i][j]=='*')
bitMask[i][j] = 0;
if (ruleArray[i][j] == '1')
bitMask[i][j] = 1;
}
}
return bitMask;
}
/* Main function */
int main(int argc, char* argv[])
{
/* Read the rules from an input file */
string line;
ifstream file ("ping_test.txt");
vector<string> ruleArray;
int i = 0;
if(file.is_open()) {
while(!file.eof()) {
getline(file, line); /* Read lines as long as the file is */
if(!line.empty())
ruleArray.push_back(line); /* Push the input file into ruleArray */
}
}
file.close();
for(int j = 0; j < ruleArray.size(); j++) {
cout << ruleArray[j] << endl; /* get the ruleArray table */
}
vector< vector<int> > wildMask = parseWildmask(ruleArray); /* get the wildmask rule table */
vector< vector<int> > bitMask = parseBitmask(ruleArray); /* get the bitmask rule table */
cout <<endl;
/* Output the wildmask rule table. */
for(int i = 0; i < wildMask.size(); i++) {
for(int j = 0; j < wildMask[0].size(); j++)
cout << wildMask[i][j];
cout << endl;
}
cout <<endl;
/* Output the bitmask rule table. */
for(int i = 0; i < bitMask.size(); i++) {
for(int j = 0; j < bitMask[0].size(); j++)
cout <<bitMask[i][j];
cout <<endl;
}
string packet = "00110110"; /* Incoming packet */
vector<int> result;
result = ruleMatches(packet, bitMask, wildMask);
for(int i = 0; i < result.size(); i++)
cout << result[i] << endl;
return 0;
}
|
/////////////////////////////////////
// File Name : wildcard matching
//////////////////////////////////////
#include <string>
#include <vector>
#include <iostream>
#include <bitset>
#include <fstream>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;
/////////// Description ///////////////////////////////////////////////////////////////////////////////////////////////
// Program maps the arbitrary wildcard rules (includes '0', '1', and '*') into two different parts: bitMask, and wildMask.
// bitMask: parse the '*' and '0' into '0', the '1' into '1'.
// wildMask: parse the '*' into '0', the '0' and '1' into '1'.
// ruleMatch: Bool (Incoming packet & wildMask == bitMask), if true, then match, if false, don't match
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// Input File Format ////////////////////////////////////////////////////////////////////////////////////////////
/* Rules */
// *11*0110 drop
// **1010** port1
// 0011*110 port2
// 0011010* port3
// 10101100 port4
/* Incoming packets */
// 01110110
// 10001010
typedef vector<int> vInt;
typedef vector<string> vString;
/* Test whether the incoming packet match the rule table */
vInt ruleMatches( int const &packet, vector<vInt> const &bitMask, vector<vInt> const &wildMask) /* return to a int value, 2-dim vector */
{
vector<int> result;
for(int j = 0; j < bitMask.size(); j++)
{
int match = 1;
if(packet & wildMask[j] != bitMask[j])
match = 0;
if(match)
result.push_back(j);
}
if(result.empty())
result.push_back(-1);
return result;
}
/* Parse the rules into wildmask. */
/* retrun int vector. */
vector<vInt> parseWildmask(vString &ruleArray)
{
vector<vInt> wildMask(ruleArray.size(), vector<int>(ruleArray[0].size()));
for(int i = 0; i < ruleArray.size(); i++)
{
for (int j = 0; j < ruleArray[0].size(); j++)
{
if (ruleArray[i][j] == '*')
wildMask[i][j] = 0;
else
wildMask[i][j] = 1;
}
}
return wildMask;
}
/* Parse the rules into bitmask. */
/* retrun int vector. */
vector<vInt> parseBitmask(vString &ruleArray)
{
vector<vInt> bitMask(ruleArray.size(), vector<int>(ruleArray[0].size()));
for(int i = 0; i < ruleArray.size(); i++)
{
for (int j = 0; j < ruleArray[0].size(); j++)
{
if (ruleArray[i][j] == '0' || ruleArray[i][j]=='*')
bitMask[i][j] = 0;
if (ruleArray[i][j] == '1')
bitMask[i][j] = 1;
}
}
return bitMask;
}
/* Main function */
int main(int argc, char* argv[])
{
/* Read the rules from an input file */
string line;
ifstream file ("ping_test.txt");
vString ruleArray;
int i = 0;
if(file.is_open())
{
while(!file.eof())
{
getline(file, line); /* Read lines as long as the file is */
if(!line.empty())
ruleArray.push_back(line); /* Push the input file into ruleArray */
}
}
file.close();
for(int j = 0; j < ruleArray.size(); j++)
{
cout << ruleArray[j] << endl; /* get the ruleArray table */
}
vector<vInt> wildMask = parseWildmask(ruleArray); /* get the wildmask rule table */
vector<vInt> bitMask = parseBitmask(ruleArray); /* get the bitmask rule table */
cout <<endl;
/* Output the wildmask rule table. */
for(int i = 0; i < wildMask.size(); i++)
{
for(int j = 0; j < wildMask[0].size(); j++)
cout << wildMask[i][j];
cout << endl;
}
cout <<endl;
/* Output the bitmask rule table. */
for(int i = 0; i < bitMask.size(); i++)
{
for(int j = 0; j < bitMask[0].size(); j++)
cout <<bitMask[i][j];
cout <<endl;
}
int packet = 00110110; /* Incoming packet */
vector<int> result;
result = ruleMatches(packet, bitMask, wildMask);
for(int i = 0; i < result.size(); i++)
cout << result[i] << endl;
return 0;
}
|
update wildcard_matching
|
update wildcard_matching
|
C++
|
apache-2.0
|
flowgrammable/libmatch,flowgrammable/libmatch
|
77378a3845d182af66488e720eca21d164a8ba56
|
lib/libport/option-parser.cc
|
lib/libport/option-parser.cc
|
#include <boost/format.hpp>
#include <libport/foreach.hh>
#include <libport/markup-ostream.hh>
#include <libport/option-parser.hh>
namespace libport
{
/*------.
| Error |
`------*/
Error::Error(const std::string& msg)
: errors_()
{
errors_.push_back(msg);
}
Error::Error(const errors_type& errors)
: errors_(errors)
{}
Error::~Error() throw ()
{}
const Error::errors_type&
Error::errors() const
{
return errors_;
}
const char*
Error::what() const throw ()
{
std::string res;
foreach (const std::string error, errors_)
res += error + "\n";
return res.c_str();
}
/*-------.
| Option |
`-------*/
Option::Option(const std::string& doc)
: documentation_(doc)
, callback_(0)
{}
Option::~Option()
{}
void
Option::set_callback(boost::function0<void>* callback)
{
callback_ = callback;
}
void
Option::usage(std::ostream& output) const
{
if (!documentation_.empty())
usage_(output);
}
void
Option::doc(std::ostream& output) const
{
if (!documentation_.empty())
doc_(output);
}
void
Option::callback() const
{
if (callback_)
(*callback_)();
}
/*------------.
| OptionNamed |
`------------*/
OptionNamed::OptionNamed(const std::string& doc,
const std::string& name_long,
char name_short)
: Option(doc)
, name_long_(name_long)
, name_short_(name_short)
{}
bool
OptionNamed::test_name(const std::string& arg) const
{
return arg == "--" + name_long_
|| (name_short_ && arg == std::string("-") + name_short_);
}
void
OptionNamed::usage_(std::ostream& output) const
{
output << "--" << name_long_;
}
void
OptionNamed::doc_(std::ostream& output) const
{
if (name_short_)
output << " -" << name_short_ << ", ";
else
output << " ";
output << "--" << name_long_;
}
/*-----------.
| OptionFlag |
`-----------*/
OptionFlag::OptionFlag(const std::string& doc,
const std::string& name_long,
char name_short)
: OptionNamed(doc, name_long, name_short)
, value_(false)
{}
void
OptionFlag::init()
{
value_ = false;
}
bool
OptionFlag::test(cli_args_type& args)
{
std::string arg = args[0];
bool res = false;
if (test_name(arg))
{
args.erase(args.begin());
res = true;
}
else if (name_short_ && arg[0] == '-' && arg[1] != '-')
{
size_t pos = arg.find(name_short_);
if (pos != std::string::npos)
{
args[0] = arg.substr(0, pos) + arg.substr(pos + 1, std::string::npos);
res = true;
}
}
value_ = value_ || res;
return res;
}
bool
OptionFlag::get() const
{
return value_;
};
void
OptionFlag::usage_(std::ostream& output) const
{
output << " [";
OptionNamed::usage_(output);
output << "]";
}
void
OptionFlag::doc_(std::ostream& output) const
{
OptionNamed::doc_(output);
output << " " << col << documentation_;
}
/*-------------.
| OptionValued |
`-------------*/
OptionValued::OptionValued(const std::string& doc,
const std::string& name_long,
const std::string& formal,
char name_short)
: OptionNamed(doc, name_long, name_short)
, callback1_(0)
{
formal_ = formal.empty() ? name_long : formal;
}
void
OptionValued::set_callback(boost::function1<void, const std::string&>* callback)
{
callback1_ = callback;
}
void
OptionValued::usage_(std::ostream& output) const
{
output << " [";
OptionNamed::usage_(output);
output << "=" << formal_ << "]";
}
void
OptionValued::doc_(std::ostream& output) const
{
OptionNamed::doc_(output);
output << "=" << formal_ << " " << col << documentation_;
}
OptionValued::ostring
OptionValued::test_option(cli_args_type& args)
{
size_t pos = args[0].find("=");
std::string name;
ostring res;
if (pos != std::string::npos)
name = args[0].substr(0, pos);
else
name = args[0];
if (test_name(name))
{
if (pos != std::string::npos)
res = args[0].substr(pos + 1, std::string::npos);
else
{
if (args.size() < 2)
throw Error(str(boost::format("--%s takes one argument")
% name_long_));
args.erase(args.begin());
res = args[0];
}
args.erase(args.begin());
}
if (res && callback1_)
(*callback1_)(res.get());
return res;
}
/*------------.
| OptionValue |
`------------*/
OptionValue::OptionValue(const std::string& doc,
const std::string& name_long,
char name_short,
const std::string& formal)
: OptionValued(doc, name_long, formal, name_short)
, filled_(false)
, value_()
{}
void
OptionValue::init()
{
filled_ = false;
value_ = "";
}
bool
OptionValue::test(cli_args_type& args)
{
ostring res = test_option(args);
if (res)
{
filled_ = true;
value_ = res.get();
return true;
}
return false;
}
bool
OptionValue::filled() const
{
return filled_;
}
std::string
OptionValue::value(const boost::optional<std::string>& def) const
{
if (!filled_)
{
assert(def);
return def.get();
}
return value_;
};
std::string
OptionValue::value(const char* def) const
{
return value(std::string(def));
};
/*-------------.
| OptionValues |
`-------------*/
OptionValues::OptionValues(const std::string& doc,
const std::string& name_long,
char name_short,
const std::string& formal)
: OptionValued(doc, name_long, formal, name_short)
, values_()
{}
void
OptionValues::init()
{
values_.clear();
}
bool
OptionValues::test(cli_args_type& args)
{
ostring res = test_option(args);
if (res)
{
values_.push_back(res.get());
return true;
}
return false;
}
const OptionValues::values_type&
OptionValues::get() const
{
return values_;
};
/*-----------.
| OptionsEnd |
`-----------*/
OptionsEnd::OptionsEnd()
: Option("")
{}
bool
OptionsEnd::test(cli_args_type& args)
{
if (args[0] != "--")
return false;
values_.insert(values_.end(), args.begin() + 1, args.end());
args.clear();
return true;
}
void
OptionsEnd::init()
{
values_.clear();
}
const OptionsEnd::values_type&
OptionsEnd::get() const
{
return values_;
}
void OptionsEnd::usage_(std::ostream&) const
{}
void OptionsEnd::doc_(std::ostream&) const
{}
/*-------------.
| OptionParser |
`-------------*/
cli_args_type
OptionParser::operator() (const cli_args_type& _args)
{
cli_args_type args(_args);
cli_args_type remainder;
foreach (Option* opt, options_)
opt->init();
while (!args.empty())
{
foreach (Option* opt, options_)
try
{
if (opt->test(args))
{
opt->callback();
goto end;
}
}
catch (Error& e)
{
errors_.push_back(e.errors().front());
}
remainder.push_back(args.front());
args.erase(args.begin());
end: ;
}
if (!errors_.empty())
throw Error(errors_);
return remainder;
}
OptionParser&
OptionParser::operator << (Option& opt)
{
options_.push_back(&opt);
doc_.push_back("");
return *this;
}
OptionParser&
OptionParser::operator << (const std::string& doc)
{
doc_.push_back(doc);
return *this;
}
void
OptionParser::usage(std::ostream& output)
{
output << program_name();
foreach (Option* opt, options_)
opt->usage(output);
}
void
OptionParser::options_doc(std::ostream& output)
{
MarkupOStream stream(output);
stream << table;
std::vector<Option*>::iterator it = options_.begin();
foreach (std::string& str, doc_)
{
stream << row;
if (str.empty())
(*it++)->doc(stream);
else
stream << etable << row << str << table;
}
// foreach (Option* opt, options_)
// {
// stream << row;
// opt->doc(stream);
// }
stream << etable;
}
namespace opts
{
OptionFlag
help("display this message and exit successfully", "help", 'h'),
verbose("be more verbose", "verbose", 'v'),
version("display version information", "version");
OptionValue
host("address to connect to", "host", 'H', "HOST"),
port("port to connect to", "port", 'P', "PORT"),
host_l("address to listen on", "host", 'H', "HOST"),
port_l("port to listen on", "port", 'P', "PORT");
OptionValues
files("load file", "file", 'f', "FILE");
}
}
|
#include <boost/format.hpp>
#include <libport/foreach.hh>
#include <libport/markup-ostream.hh>
#include <libport/option-parser.hh>
namespace libport
{
/*--------.
| Error. |
`--------*/
Error::Error(const std::string& msg)
: errors_()
{
errors_.push_back(msg);
}
Error::Error(const errors_type& errors)
: errors_(errors)
{}
Error::~Error() throw ()
{}
const Error::errors_type&
Error::errors() const
{
return errors_;
}
const char*
Error::what() const throw ()
{
std::string res;
foreach (const std::string error, errors_)
res += error + "\n";
return res.c_str();
}
/*---------.
| Option. |
`---------*/
Option::Option(const std::string& doc)
: documentation_(doc)
, callback_(0)
{}
Option::~Option()
{}
void
Option::set_callback(boost::function0<void>* callback)
{
callback_ = callback;
}
void
Option::usage(std::ostream& output) const
{
if (!documentation_.empty())
usage_(output);
}
void
Option::doc(std::ostream& output) const
{
if (!documentation_.empty())
doc_(output);
}
void
Option::callback() const
{
if (callback_)
(*callback_)();
}
/*--------------.
| OptionNamed. |
`--------------*/
OptionNamed::OptionNamed(const std::string& doc,
const std::string& name_long,
char name_short)
: Option(doc)
, name_long_(name_long)
, name_short_(name_short)
{}
bool
OptionNamed::test_name(const std::string& arg) const
{
return arg == "--" + name_long_
|| (name_short_ && arg == std::string("-") + name_short_);
}
void
OptionNamed::usage_(std::ostream& output) const
{
output << "--" << name_long_;
}
void
OptionNamed::doc_(std::ostream& output) const
{
if (name_short_)
output << " -" << name_short_ << ", ";
else
output << " ";
output << "--" << name_long_;
}
/*-------------.
| OptionFlag. |
`-------------*/
OptionFlag::OptionFlag(const std::string& doc,
const std::string& name_long,
char name_short)
: OptionNamed(doc, name_long, name_short)
, value_(false)
{}
void
OptionFlag::init()
{
value_ = false;
}
bool
OptionFlag::test(cli_args_type& args)
{
std::string arg = args[0];
bool res = false;
if (test_name(arg))
{
args.erase(args.begin());
res = true;
}
else if (name_short_ && arg[0] == '-' && arg[1] != '-')
{
size_t pos = arg.find(name_short_);
if (pos != std::string::npos)
{
args[0] = arg.substr(0, pos) + arg.substr(pos + 1, std::string::npos);
res = true;
}
}
value_ = value_ || res;
return res;
}
bool
OptionFlag::get() const
{
return value_;
};
void
OptionFlag::usage_(std::ostream& output) const
{
output << " [";
OptionNamed::usage_(output);
output << "]";
}
void
OptionFlag::doc_(std::ostream& output) const
{
OptionNamed::doc_(output);
output << " " << col << documentation_;
}
/*---------------.
| OptionValued. |
`---------------*/
OptionValued::OptionValued(const std::string& doc,
const std::string& name_long,
const std::string& formal,
char name_short)
: OptionNamed(doc, name_long, name_short)
, callback1_(0)
{
formal_ = formal.empty() ? name_long : formal;
}
void
OptionValued::set_callback(boost::function1<void, const std::string&>* callback)
{
callback1_ = callback;
}
void
OptionValued::usage_(std::ostream& output) const
{
output << " [";
OptionNamed::usage_(output);
output << "=" << formal_ << "]";
}
void
OptionValued::doc_(std::ostream& output) const
{
OptionNamed::doc_(output);
output << "=" << formal_ << " " << col << documentation_;
}
OptionValued::ostring
OptionValued::test_option(cli_args_type& args)
{
size_t pos = args[0].find("=");
std::string name;
ostring res;
if (pos != std::string::npos)
name = args[0].substr(0, pos);
else
name = args[0];
if (test_name(name))
{
if (pos != std::string::npos)
res = args[0].substr(pos + 1, std::string::npos);
else
{
if (args.size() < 2)
throw Error(str(boost::format("--%s takes one argument")
% name_long_));
args.erase(args.begin());
res = args[0];
}
args.erase(args.begin());
}
if (res && callback1_)
(*callback1_)(res.get());
return res;
}
/*--------------.
| OptionValue. |
`--------------*/
OptionValue::OptionValue(const std::string& doc,
const std::string& name_long,
char name_short,
const std::string& formal)
: OptionValued(doc, name_long, formal, name_short)
, filled_(false)
, value_()
{}
void
OptionValue::init()
{
filled_ = false;
value_ = "";
}
bool
OptionValue::test(cli_args_type& args)
{
ostring res = test_option(args);
if (res)
{
filled_ = true;
value_ = res.get();
return true;
}
return false;
}
bool
OptionValue::filled() const
{
return filled_;
}
std::string
OptionValue::value(const boost::optional<std::string>& def) const
{
if (!filled_)
{
assert(def);
return def.get();
}
return value_;
};
std::string
OptionValue::value(const char* def) const
{
return value(std::string(def));
};
/*---------------.
| OptionValues. |
`---------------*/
OptionValues::OptionValues(const std::string& doc,
const std::string& name_long,
char name_short,
const std::string& formal)
: OptionValued(doc, name_long, formal, name_short)
, values_()
{}
void
OptionValues::init()
{
values_.clear();
}
bool
OptionValues::test(cli_args_type& args)
{
ostring res = test_option(args);
if (res)
{
values_.push_back(res.get());
return true;
}
return false;
}
const OptionValues::values_type&
OptionValues::get() const
{
return values_;
};
/*-------------.
| OptionsEnd. |
`-------------*/
OptionsEnd::OptionsEnd()
: Option("")
{}
bool
OptionsEnd::test(cli_args_type& args)
{
if (args[0] != "--")
return false;
values_.insert(values_.end(), args.begin() + 1, args.end());
args.clear();
return true;
}
void
OptionsEnd::init()
{
values_.clear();
}
const OptionsEnd::values_type&
OptionsEnd::get() const
{
return values_;
}
void OptionsEnd::usage_(std::ostream&) const
{}
void OptionsEnd::doc_(std::ostream&) const
{}
/*---------------.
| OptionParser. |
`---------------*/
cli_args_type
OptionParser::operator() (const cli_args_type& _args)
{
cli_args_type args(_args);
cli_args_type remainder;
foreach (Option* opt, options_)
opt->init();
while (!args.empty())
{
foreach (Option* opt, options_)
try
{
if (opt->test(args))
{
opt->callback();
goto end;
}
}
catch (Error& e)
{
errors_.push_back(e.errors().front());
}
remainder.push_back(args.front());
args.erase(args.begin());
end: ;
}
if (!errors_.empty())
throw Error(errors_);
return remainder;
}
OptionParser&
OptionParser::operator << (Option& opt)
{
options_.push_back(&opt);
doc_.push_back("");
return *this;
}
OptionParser&
OptionParser::operator << (const std::string& doc)
{
doc_.push_back(doc);
return *this;
}
void
OptionParser::usage(std::ostream& output)
{
output << program_name();
foreach (Option* opt, options_)
opt->usage(output);
}
void
OptionParser::options_doc(std::ostream& output)
{
MarkupOStream stream(output);
stream << table;
std::vector<Option*>::iterator it = options_.begin();
foreach (std::string& str, doc_)
{
stream << row;
if (str.empty())
(*it++)->doc(stream);
else
stream << etable << row << str << table;
}
// foreach (Option* opt, options_)
// {
// stream << row;
// opt->doc(stream);
// }
stream << etable;
}
namespace opts
{
OptionFlag
help("display this message and exit successfully", "help", 'h'),
verbose("be more verbose", "verbose", 'v'),
version("display version information", "version");
OptionValue
host("address to connect to", "host", 'H', "HOST"),
port("port to connect to", "port", 'P', "PORT"),
host_l("address to listen on", "host", 'H', "HOST"),
port_l("port to listen on", "port", 'P', "PORT");
OptionValues
files("load file", "file", 'f', "FILE");
}
}
|
Comment changes.
|
Comment changes.
|
C++
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
eb05fb1708f092243819b3e62f5b818b8d8738f9
|
winbuild/realpath.cpp
|
winbuild/realpath.cpp
|
/* Copyright 2014-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
#include "Win32Handle.h"
using watchman::Win32Handle;
char *realpath(const char *filename, char *target) {
#if 1 /* Requires Vista or later */
std::wstring wchar;
DWORD err, len;
char *utf8;
char *func_name;
wchar.resize(WATCHMAN_NAME_MAX);
if (target) {
// The only sane way is to set target = NULL
w_log(W_LOG_FATAL, "realpath called with target!=NULL");
}
int filename_len = (int)strlen(filename);
if (filename_len == 0) {
// Special case for "" -> cwd
func_name = "GetCurrentDirectoryW";
len = GetCurrentDirectoryW(wchar.size(), &wchar[0]);
err = GetLastError();
} else {
auto wfilename = w_string_piece(filename, filename_len).asWideUNC();
func_name = "CreateFileW";
Win32Handle h(intptr_t(CreateFileW(
wfilename.c_str(),
0 /* query metadata */,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
nullptr)));
err = GetLastError();
if (h) {
func_name = "GetFinalPathNameByHandleW";
len = GetFinalPathNameByHandleW(
(HANDLE)h.handle(),
&wchar[0],
wchar.size(),
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
err = GetLastError();
if (len >= wchar.size()) {
// Grow it
wchar.resize(len);
len = GetFinalPathNameByHandleW(
(HANDLE)h.handle(),
&wchar[0],
len,
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
err = GetLastError();
}
} else {
len = 0;
}
}
if (len == 0) {
errno = map_win32_err(err);
return nullptr;
}
w_string result(wchar.data(), len);
return strdup(result.c_str());
#else
char full_buf[WATCHMAN_NAME_MAX];
char long_buf[WATCHMAN_NAME_MAX];
char *base = NULL;
DWORD full_len, long_len;
printf("realpath called with '%s'\n", filename);
if (!strlen(filename)) {
// Special case for "" -> cwd
full_len = GetCurrentDirectory(sizeof(full_buf), full_buf);
} else {
full_len = GetFullPathName(filename, sizeof(full_buf), full_buf, &base);
}
if (full_len > sizeof(full_buf)-1) {
w_log(W_LOG_FATAL, "GetFullPathName needs %lu chars\n", full_len);
}
full_buf[full_len] = 0;
printf("full: %s\n", full_buf);
long_len = GetLongPathName(full_buf, long_buf, sizeof(long_buf));
if (long_len > sizeof(long_buf)-1) {
w_log(W_LOG_FATAL, "GetLongPathName needs %lu chars\n", long_len);
}
long_buf[long_len] = 0;
printf("long: %s\n", long_buf);
if (target) {
// Pray they passed in a big enough buffer
strcpy(target, long_buf);
return target;
}
return strdup(long_buf);
#endif
}
/* vim:ts=2:sw=2:et:
*/
|
/* Copyright 2014-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
#include "Win32Handle.h"
using watchman::Win32Handle;
char *realpath(const char *filename, char *target) {
std::wstring wchar;
DWORD err, len;
char *utf8;
char *func_name;
wchar.resize(WATCHMAN_NAME_MAX);
if (target) {
// The only sane way is to set target = NULL
w_log(W_LOG_FATAL, "realpath called with target!=NULL");
}
int filename_len = (int)strlen(filename);
if (filename_len == 0) {
// Special case for "" -> cwd
func_name = "GetCurrentDirectoryW";
len = GetCurrentDirectoryW(wchar.size(), &wchar[0]);
err = GetLastError();
} else {
auto wfilename = w_string_piece(filename, filename_len).asWideUNC();
func_name = "CreateFileW";
Win32Handle h(intptr_t(CreateFileW(
wfilename.c_str(),
0 /* query metadata */,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
nullptr)));
err = GetLastError();
if (h) {
func_name = "GetFinalPathNameByHandleW";
len = GetFinalPathNameByHandleW(
(HANDLE)h.handle(),
&wchar[0],
wchar.size(),
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
err = GetLastError();
if (len >= wchar.size()) {
// Grow it
wchar.resize(len);
len = GetFinalPathNameByHandleW(
(HANDLE)h.handle(),
&wchar[0],
len,
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
err = GetLastError();
}
} else {
len = 0;
}
}
if (len == 0) {
errno = map_win32_err(err);
return nullptr;
}
w_string result(wchar.data(), len);
return strdup(result.c_str());
}
/* vim:ts=2:sw=2:et:
*/
|
remove unused windows realpath implementation
|
remove unused windows realpath implementation
Summary: This is just dead code
Reviewed By: farnz
Differential Revision: D4334330
fbshipit-source-id: ec4499da219016ce70b1d499817adb8490d8eacf
|
C++
|
mit
|
facebook/watchman,kwlzn/watchman,nodakai/watchman,kwlzn/watchman,facebook/watchman,wez/watchman,wez/watchman,nodakai/watchman,nodakai/watchman,facebook/watchman,facebook/watchman,kwlzn/watchman,nodakai/watchman,facebook/watchman,wez/watchman,wez/watchman,nodakai/watchman,nodakai/watchman,facebook/watchman,kwlzn/watchman,facebook/watchman,facebook/watchman,kwlzn/watchman,wez/watchman,kwlzn/watchman,wez/watchman,nodakai/watchman,wez/watchman,nodakai/watchman,wez/watchman,nodakai/watchman,facebook/watchman,wez/watchman,kwlzn/watchman
|
15f8e86665023849eafbd34fdb674c9809e6f5a5
|
src/core/product_quadrature.hpp
|
src/core/product_quadrature.hpp
|
#pragma once
#include <vector>
#include <math.h>
#include <iostream>
#include "angle.hpp"
#include "global_config.hpp"
#include "error.hpp"
#include "blitz_typedefs.hpp"
using namespace mocc;
// Produce a vector of <theta,weight> pairs of size n_polar with Yamamoto
// quadrature within (0, PI/2). All weights sum to 1. Currently, only npol=3
// is supported.
std::vector<std::pair<real_t,real_t>> GenYamamoto( int n_polar ){
std::vector<std::pair<real_t,real_t>> thetaWeightPairVec;
if ( n_polar != 3 ) {
throw EXCEPT("Only support Yamamoto quadrature when npol=3");
}
thetaWeightPairVec.emplace_back(0.167429147795000,4.623300000000000E-002);
thetaWeightPairVec.emplace_back(0.567715121084000,0.283619000000000);
thetaWeightPairVec.emplace_back(1.20253314678900,0.670148000000000);
return thetaWeightPairVec;
}
// Produce a vector of <alpha,weight> pairs of size n_azimuthal with Chebyshev
// quadrature within (0, PI/2). All weights sum to 1.
std::vector<std::pair<real_t,real_t>> GenChebyshev( int n_azimuthal ) {
std::vector<std::pair<real_t,real_t>> alphaWeightPairVec;
real_t weight = 1.0/n_azimuthal;
real_t alpha;
real_t delAlpha = 0.5*PI/(2*n_azimuthal);
for( int i=0; i<n_azimuthal; i++ ) {
alpha = delAlpha*(2*i+1);
alphaWeightPairVec.emplace_back(alpha,weight);
}
return alphaWeightPairVec;
}
// Produce a vector of <theta,weight> pairs of size n_polar with Gaussian
// quadrature within (0, PI/2). All weights sum to 1.
std::vector<std::pair<real_t,real_t>> GenGauss( int n_polar ){
std::vector<std::pair<real_t,real_t>> thetaWeightPairVec;
int N = n_polar*2 - 1;
int N1 = n_polar*2;
int N2 = n_polar*2 + 1;
ArrayB1 xu(N1),y(N1),w(N1);
real_t delxu=2.0/N;
// Initial guess for y
for( int i=0; i<N1; i++ ) {
xu(i)=-1.0+i*delxu;
y(i)=cos( (2*i+1)*PI/(2*N1) ) + 0.27/N1*sin(PI*xu(i)*N/N2);
}
// Legendre-Gauss Vandermonde Matrix
ArrayB2 L(N1,N2);
// Derivative of LGVM
ArrayB1 Lg(N1);
// Compute the zeros of the N+1 Legendre Polynomial using the recursion
// relation and the Newton-Paphson method
ArrayB1 y0(N1),Lp(N1);
y0=2;
// Iterate until new pioints are uniformly within epsilon of old points
while( max(abs(y-y0))>FLOAT_EPS ) {
L(blitz::Range::all(),0)=1;
L(blitz::Range::all(),1)=y;
for( int k=1; k<N1; k++ ) {
for( int m=0; m<N1; m++ ) {
L(m,k+1) = ( (2*k+1)*y(m)*L(m,k)-k*L(m,k-1) )/(k+1);
}
}
for( int i=0; i<N1; i++ ) {
Lp(i) = N2*(L(i,N1-1)-y(i)*L(i,N2-1))/(1-y(i)*y(i));
}
y0=y;
for( int i=0; i<N1; i++ ) {
y(i) = y0(i)-L(i,N2-1)/Lp(i);
}
}
//weight sum is 1.0;
for( int i=0; i<N1; i++ ) {
w(i)=1.0/((1-y(i)*y(i))*Lp(i)*Lp(i))*N2*N2/(N1*N1);
}
// y should be scaled from (-1,1) to (-PI/2, PI/2)
y=y*PI/2.0;
// reverse order of y;
real_t t=0;
for( int i=0; i<n_polar; i++ ) {
t=y(i);
y(i)=y(N1-1-i);
y(N1-1-i)=t;
}
for( int i=n_polar; i<N1; i++ ) {
thetaWeightPairVec.emplace_back(y(i),w(i));
}
return thetaWeightPairVec;
}
// Produce a vector of angles with azi and pol pair vectors to represent a
// product quadrature set.
std::vector<Angle> GenProduct(const std::vector<std::pair<real_t,real_t>>
&azi, const std::vector<std::pair<real_t,real_t>> &pol){
std::vector<Angle> angles;
int n_azimuthal=azi.size();
int n_polar=pol.size();
real_t wsum=0.0;
for( int i=0; i<n_azimuthal; i++ ) {
for( int j=0; j<n_polar; j++ ) {
Angle angle( azi[i].first,
pol[j].first,
azi[i].second*pol[j].second );
angles.push_back(angle);
wsum += azi[i].second*pol[j].second;
}
}
// Product quadrature ensures this in nature, so this may be unnecessary.
for( auto &a: angles ) {
a.weight /= wsum;
}
return angles;
}
|
#pragma once
#include <vector>
#include <math.h>
#include <iostream>
#include "angle.hpp"
#include "global_config.hpp"
#include "error.hpp"
#include "blitz_typedefs.hpp"
using namespace mocc;
// Produce a vector of <theta,weight> pairs of size n_polar with Yamamoto
// quadrature within (0, PI/2). All weights sum to 1. Currently, only npol=3
// is supported.
std::vector<std::pair<real_t,real_t>> GenYamamoto( int n_polar ){
std::vector<std::pair<real_t,real_t>> thetaWeightPairVec;
if ( n_polar != 3 ) {
throw EXCEPT("Only support Yamamoto quadrature when npol=3");
}
thetaWeightPairVec.emplace_back(0.167429147795000,4.623300000000000E-002);
thetaWeightPairVec.emplace_back(0.567715121084000,0.283619000000000);
thetaWeightPairVec.emplace_back(1.20253314678900,0.670148000000000);
return thetaWeightPairVec;
}
// Produce a vector of <alpha,weight> pairs of size n_azimuthal with Chebyshev
// quadrature within (0, PI/2). All weights sum to 1.
std::vector<std::pair<real_t,real_t>> GenChebyshev( int n_azimuthal ) {
std::vector<std::pair<real_t,real_t>> alphaWeightPairVec;
real_t weight = 1.0/n_azimuthal;
real_t alpha;
real_t delAlpha = 0.5*PI/(2*n_azimuthal);
for( int i=0; i<n_azimuthal; i++ ) {
alpha = delAlpha*(2*i+1);
alphaWeightPairVec.emplace_back(alpha,weight);
}
return alphaWeightPairVec;
}
// Produce a vector of <theta,weight> pairs of size n_polar with Gaussian
// quadrature within (0, PI/2). All weights sum to 1.
std::vector<std::pair<real_t,real_t>> GenGauss( int n_polar ){
std::vector<std::pair<real_t,real_t>> thetaWeightPairVec;
int N = n_polar*2 - 1;
int N1 = n_polar*2;
int N2 = n_polar*2 + 1;
ArrayB1 xu(N1),y(N1),w(N1);
real_t delxu=2.0/N;
// Initial guess for y
for( int i=0; i<N1; i++ ) {
xu(i)=-1.0+i*delxu;
y(i)=cos( (2*i+1)*PI/(2*N1) ) + 0.27/N1*sin(PI*xu(i)*N/N2);
}
// Legendre-Gauss Vandermonde Matrix
ArrayB2 L(N1,N2);
// Derivative of LGVM
ArrayB1 Lg(N1);
// Compute the zeros of the N+1 Legendre Polynomial using the recursion
// relation and the Newton-Paphson method
ArrayB1 y0(N1),Lp(N1);
y0=2;
// Iterate until new pioints are uniformly within epsilon of old points
while( max(abs(y-y0))>FLOAT_EPS ) {
L(blitz::Range::all(),0)=1;
L(blitz::Range::all(),1)=y;
for( int k=1; k<N1; k++ ) {
for( int m=0; m<N1; m++ ) {
L(m,k+1) = ( (2*k+1)*y(m)*L(m,k)-k*L(m,k-1) )/(k+1);
}
}
for( int i=0; i<N1; i++ ) {
Lp(i) = N2*(L(i,N1-1)-y(i)*L(i,N2-1))/(1-y(i)*y(i));
}
y0=y;
for( int i=0; i<N1; i++ ) {
y(i) = y0(i)-L(i,N2-1)/Lp(i);
}
}
//weight sum is 1.0;
for( int i=0; i<N1; i++ ) {
w(i)=1.0/((1-y(i)*y(i))*Lp(i)*Lp(i))*N2*N2/(N1*N1);
}
// y is distributed in cos(theta) space. Take arccos(y) to get angle in
// radians
y = acos(y);
// reverse order of y;
real_t t=0;
for( int i=0; i<n_polar; i++ ) {
t=y(i);
y(i)=y(N1-1-i);
y(N1-1-i)=t;
}
for( int i=n_polar; i<N1; i++ ) {
thetaWeightPairVec.emplace_back(y(i),w(i));
}
return thetaWeightPairVec;
}
// Produce a vector of angles with azi and pol pair vectors to represent a
// product quadrature set.
std::vector<Angle> GenProduct(const std::vector<std::pair<real_t,real_t>>
&azi, const std::vector<std::pair<real_t,real_t>> &pol){
std::vector<Angle> angles;
int n_azimuthal=azi.size();
int n_polar=pol.size();
real_t wsum=0.0;
for( int i=0; i<n_azimuthal; i++ ) {
for( int j=0; j<n_polar; j++ ) {
Angle angle( azi[i].first,
pol[j].first,
azi[i].second*pol[j].second );
angles.push_back(angle);
wsum += azi[i].second*pol[j].second;
}
}
// Product quadrature ensures this in nature, so this may be unnecessary.
for( auto &a: angles ) {
a.weight /= wsum;
}
return angles;
}
|
Fix issue with Gauss quadrature (add acos)
|
Fix issue with Gauss quadrature (add acos)
|
C++
|
apache-2.0
|
youngmit/mocc,youngmit/mocc,youngmit/mocc,youngmit/mocc
|
dac6b09cc8e246c6a90c2c680527ae79e0b7c183
|
unittests/ADT/STLExtrasTest.cpp
|
unittests/ADT/STLExtrasTest.cpp
|
//===- STLExtrasTest.cpp - Unit tests for STL extras ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h"
#include <vector>
using namespace llvm;
namespace {
int f(rank<0>) { return 0; }
int f(rank<1>) { return 1; }
int f(rank<2>) { return 2; }
int f(rank<4>) { return 4; }
TEST(STLExtrasTest, Rank) {
// We shouldn't get ambiguities and should select the overload of the same
// rank as the argument.
EXPECT_EQ(0, f(rank<0>()));
EXPECT_EQ(1, f(rank<1>()));
EXPECT_EQ(2, f(rank<2>()));
// This overload is missing so we end up back at 2.
EXPECT_EQ(2, f(rank<3>()));
// But going past 3 should work fine.
EXPECT_EQ(4, f(rank<4>()));
// And we can even go higher and just fall back to the last overload.
EXPECT_EQ(4, f(rank<5>()));
EXPECT_EQ(4, f(rank<6>()));
}
TEST(STLExtrasTest, EnumerateLValue) {
// Test that a simple LValue can be enumerated and gives correct results with
// multiple types, including the empty container.
std::vector<char> foo = {'a', 'b', 'c'};
typedef std::pair<std::size_t, char> CharPairType;
std::vector<CharPairType> CharResults;
for (auto X : llvm::enumerate(foo)) {
CharResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, CharResults.size());
EXPECT_EQ(CharPairType(0u, 'a'), CharResults[0]);
EXPECT_EQ(CharPairType(1u, 'b'), CharResults[1]);
EXPECT_EQ(CharPairType(2u, 'c'), CharResults[2]);
// Test a const range of a different type.
typedef std::pair<std::size_t, int> IntPairType;
std::vector<IntPairType> IntResults;
const std::vector<int> bar = {1, 2, 3};
for (auto X : llvm::enumerate(bar)) {
IntResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, IntResults.size());
EXPECT_EQ(IntPairType(0u, 1), IntResults[0]);
EXPECT_EQ(IntPairType(1u, 2), IntResults[1]);
EXPECT_EQ(IntPairType(2u, 3), IntResults[2]);
// Test an empty range.
IntResults.clear();
const std::vector<int> baz;
for (auto X : llvm::enumerate(baz)) {
IntResults.emplace_back(X.Index, X.Value);
}
EXPECT_TRUE(IntResults.empty());
}
TEST(STLExtrasTest, EnumerateModifyLValue) {
// Test that you can modify the underlying entries of an lvalue range through
// the enumeration iterator.
std::vector<char> foo = {'a', 'b', 'c'};
for (auto X : llvm::enumerate(foo)) {
++X.Value;
}
EXPECT_EQ('b', foo[0]);
EXPECT_EQ('c', foo[1]);
EXPECT_EQ('d', foo[2]);
}
TEST(STLExtrasTest, EnumerateRValueRef) {
// Test that an rvalue can be enumerated.
typedef std::pair<std::size_t, int> PairType;
std::vector<PairType> Results;
auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3});
for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) {
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, 1), Results[0]);
EXPECT_EQ(PairType(1u, 2), Results[1]);
EXPECT_EQ(PairType(2u, 3), Results[2]);
}
TEST(STLExtrasTest, EnumerateModifyRValue) {
// Test that when enumerating an rvalue, modification still works (even if
// this isn't terribly useful, it at least shows that we haven't snuck an
// extra const in there somewhere.
typedef std::pair<std::size_t, char> PairType;
std::vector<PairType> Results;
for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
++X.Value;
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, '2'), Results[0]);
EXPECT_EQ(PairType(1u, '3'), Results[1]);
EXPECT_EQ(PairType(2u, '4'), Results[2]);
}
template <bool B> struct CanMove {};
template <> struct CanMove<false> {
CanMove(CanMove &&) = delete;
CanMove() = default;
CanMove(const CanMove &) = default;
};
template <bool B> struct CanCopy {};
template <> struct CanCopy<false> {
CanCopy(const CanCopy &) = delete;
CanCopy() = default;
CanCopy(CanCopy &&) = default;
};
template <bool Moveable, bool Copyable>
struct Range : CanMove<Moveable>, CanCopy<Copyable> {
explicit Range(int &C, int &M, int &D) : C(C), M(M), D(D) {}
Range(const Range &R) : CanCopy<Copyable>(R), C(R.C), M(R.M), D(R.D) { ++C; }
Range(Range &&R) : CanMove<Moveable>(std::move(R)), C(R.C), M(R.M), D(R.D) {
++M;
}
~Range() { ++D; }
int &C;
int &M;
int &D;
int *begin() { return nullptr; }
int *end() { return nullptr; }
};
TEST(STLExtrasTest, EnumerateLifetimeSemantics) {
// Test that when enumerating lvalues and rvalues, there are no surprise
// copies or moves.
// With an rvalue, it should not be destroyed until the end of the scope.
int Copies = 0;
int Moves = 0;
int Destructors = 0;
{
auto E1 = enumerate(Range<true, false>(Copies, Moves, Destructors));
// Doesn't compile. rvalue ranges must be moveable.
// auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(1, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(2, Destructors);
Copies = Moves = Destructors = 0;
// With an lvalue, it should not be destroyed even after the end of the scope.
// lvalue ranges need be neither copyable nor moveable.
Range<false, false> R(Copies, Moves, Destructors);
{
auto Enumerator = enumerate(R);
(void)Enumerator;
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
}
|
//===- STLExtrasTest.cpp - Unit tests for STL extras ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h"
#include <vector>
using namespace llvm;
namespace {
int f(rank<0>) { return 0; }
int f(rank<1>) { return 1; }
int f(rank<2>) { return 2; }
int f(rank<4>) { return 4; }
TEST(STLExtrasTest, Rank) {
// We shouldn't get ambiguities and should select the overload of the same
// rank as the argument.
EXPECT_EQ(0, f(rank<0>()));
EXPECT_EQ(1, f(rank<1>()));
EXPECT_EQ(2, f(rank<2>()));
// This overload is missing so we end up back at 2.
EXPECT_EQ(2, f(rank<3>()));
// But going past 3 should work fine.
EXPECT_EQ(4, f(rank<4>()));
// And we can even go higher and just fall back to the last overload.
EXPECT_EQ(4, f(rank<5>()));
EXPECT_EQ(4, f(rank<6>()));
}
TEST(STLExtrasTest, EnumerateLValue) {
// Test that a simple LValue can be enumerated and gives correct results with
// multiple types, including the empty container.
std::vector<char> foo = {'a', 'b', 'c'};
typedef std::pair<std::size_t, char> CharPairType;
std::vector<CharPairType> CharResults;
for (auto X : llvm::enumerate(foo)) {
CharResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, CharResults.size());
EXPECT_EQ(CharPairType(0u, 'a'), CharResults[0]);
EXPECT_EQ(CharPairType(1u, 'b'), CharResults[1]);
EXPECT_EQ(CharPairType(2u, 'c'), CharResults[2]);
// Test a const range of a different type.
typedef std::pair<std::size_t, int> IntPairType;
std::vector<IntPairType> IntResults;
const std::vector<int> bar = {1, 2, 3};
for (auto X : llvm::enumerate(bar)) {
IntResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, IntResults.size());
EXPECT_EQ(IntPairType(0u, 1), IntResults[0]);
EXPECT_EQ(IntPairType(1u, 2), IntResults[1]);
EXPECT_EQ(IntPairType(2u, 3), IntResults[2]);
// Test an empty range.
IntResults.clear();
const std::vector<int> baz;
for (auto X : llvm::enumerate(baz)) {
IntResults.emplace_back(X.Index, X.Value);
}
EXPECT_TRUE(IntResults.empty());
}
TEST(STLExtrasTest, EnumerateModifyLValue) {
// Test that you can modify the underlying entries of an lvalue range through
// the enumeration iterator.
std::vector<char> foo = {'a', 'b', 'c'};
for (auto X : llvm::enumerate(foo)) {
++X.Value;
}
EXPECT_EQ('b', foo[0]);
EXPECT_EQ('c', foo[1]);
EXPECT_EQ('d', foo[2]);
}
TEST(STLExtrasTest, EnumerateRValueRef) {
// Test that an rvalue can be enumerated.
typedef std::pair<std::size_t, int> PairType;
std::vector<PairType> Results;
auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3});
for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) {
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, 1), Results[0]);
EXPECT_EQ(PairType(1u, 2), Results[1]);
EXPECT_EQ(PairType(2u, 3), Results[2]);
}
TEST(STLExtrasTest, EnumerateModifyRValue) {
// Test that when enumerating an rvalue, modification still works (even if
// this isn't terribly useful, it at least shows that we haven't snuck an
// extra const in there somewhere.
typedef std::pair<std::size_t, char> PairType;
std::vector<PairType> Results;
for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
++X.Value;
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, '2'), Results[0]);
EXPECT_EQ(PairType(1u, '3'), Results[1]);
EXPECT_EQ(PairType(2u, '4'), Results[2]);
}
template <bool B> struct CanMove {};
template <> struct CanMove<false> {
CanMove(CanMove &&) = delete;
CanMove() = default;
CanMove(const CanMove &) = default;
};
template <bool B> struct CanCopy {};
template <> struct CanCopy<false> {
CanCopy(const CanCopy &) = delete;
CanCopy() = default;
// FIXME: Use '= default' when we drop MSVC 2013.
CanCopy(CanCopy &&) {};
};
template <bool Moveable, bool Copyable>
struct Range : CanMove<Moveable>, CanCopy<Copyable> {
explicit Range(int &C, int &M, int &D) : C(C), M(M), D(D) {}
Range(const Range &R) : CanCopy<Copyable>(R), C(R.C), M(R.M), D(R.D) { ++C; }
Range(Range &&R) : CanMove<Moveable>(std::move(R)), C(R.C), M(R.M), D(R.D) {
++M;
}
~Range() { ++D; }
int &C;
int &M;
int &D;
int *begin() { return nullptr; }
int *end() { return nullptr; }
};
TEST(STLExtrasTest, EnumerateLifetimeSemantics) {
// Test that when enumerating lvalues and rvalues, there are no surprise
// copies or moves.
// With an rvalue, it should not be destroyed until the end of the scope.
int Copies = 0;
int Moves = 0;
int Destructors = 0;
{
auto E1 = enumerate(Range<true, false>(Copies, Moves, Destructors));
// Doesn't compile. rvalue ranges must be moveable.
// auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(1, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(2, Destructors);
Copies = Moves = Destructors = 0;
// With an lvalue, it should not be destroyed even after the end of the scope.
// lvalue ranges need be neither copyable nor moveable.
Range<false, false> R(Copies, Moves, Destructors);
{
auto Enumerator = enumerate(R);
(void)Enumerator;
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
}
|
Fix the build with MSVC 2013, still cannot default move ctors yet
|
Fix the build with MSVC 2013, still cannot default move ctors yet
Ten days.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@283394 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit 87bf0196f2d0dac7a2bad45eb457e647afbed9e7)
|
C++
|
apache-2.0
|
apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm
|
3e3953aeae38a406c6bbb15444b30fec39d5bd69
|
unittests/ADT/STLExtrasTest.cpp
|
unittests/ADT/STLExtrasTest.cpp
|
//===- STLExtrasTest.cpp - Unit tests for STL extras ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h"
#include <vector>
using namespace llvm;
namespace {
int f(rank<0>) { return 0; }
int f(rank<1>) { return 1; }
int f(rank<2>) { return 2; }
int f(rank<4>) { return 4; }
TEST(STLExtrasTest, Rank) {
// We shouldn't get ambiguities and should select the overload of the same
// rank as the argument.
EXPECT_EQ(0, f(rank<0>()));
EXPECT_EQ(1, f(rank<1>()));
EXPECT_EQ(2, f(rank<2>()));
// This overload is missing so we end up back at 2.
EXPECT_EQ(2, f(rank<3>()));
// But going past 3 should work fine.
EXPECT_EQ(4, f(rank<4>()));
// And we can even go higher and just fall back to the last overload.
EXPECT_EQ(4, f(rank<5>()));
EXPECT_EQ(4, f(rank<6>()));
}
TEST(STLExtrasTest, EnumerateLValue) {
// Test that a simple LValue can be enumerated and gives correct results with
// multiple types, including the empty container.
std::vector<char> foo = {'a', 'b', 'c'};
typedef std::pair<std::size_t, char> CharPairType;
std::vector<CharPairType> CharResults;
for (auto X : llvm::enumerate(foo)) {
CharResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, CharResults.size());
EXPECT_EQ(CharPairType(0u, 'a'), CharResults[0]);
EXPECT_EQ(CharPairType(1u, 'b'), CharResults[1]);
EXPECT_EQ(CharPairType(2u, 'c'), CharResults[2]);
// Test a const range of a different type.
typedef std::pair<std::size_t, int> IntPairType;
std::vector<IntPairType> IntResults;
const std::vector<int> bar = {1, 2, 3};
for (auto X : llvm::enumerate(bar)) {
IntResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, IntResults.size());
EXPECT_EQ(IntPairType(0u, 1), IntResults[0]);
EXPECT_EQ(IntPairType(1u, 2), IntResults[1]);
EXPECT_EQ(IntPairType(2u, 3), IntResults[2]);
// Test an empty range.
IntResults.clear();
const std::vector<int> baz;
for (auto X : llvm::enumerate(baz)) {
IntResults.emplace_back(X.Index, X.Value);
}
EXPECT_TRUE(IntResults.empty());
}
TEST(STLExtrasTest, EnumerateModifyLValue) {
// Test that you can modify the underlying entries of an lvalue range through
// the enumeration iterator.
std::vector<char> foo = {'a', 'b', 'c'};
for (auto X : llvm::enumerate(foo)) {
++X.Value;
}
EXPECT_EQ('b', foo[0]);
EXPECT_EQ('c', foo[1]);
EXPECT_EQ('d', foo[2]);
}
TEST(STLExtrasTest, EnumerateRValueRef) {
// Test that an rvalue can be enumerated.
typedef std::pair<std::size_t, int> PairType;
std::vector<PairType> Results;
auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3});
for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) {
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, 1), Results[0]);
EXPECT_EQ(PairType(1u, 2), Results[1]);
EXPECT_EQ(PairType(2u, 3), Results[2]);
}
TEST(STLExtrasTest, EnumerateModifyRValue) {
// Test that when enumerating an rvalue, modification still works (even if
// this isn't terribly useful, it at least shows that we haven't snuck an
// extra const in there somewhere.
typedef std::pair<std::size_t, char> PairType;
std::vector<PairType> Results;
for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
++X.Value;
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, '2'), Results[0]);
EXPECT_EQ(PairType(1u, '3'), Results[1]);
EXPECT_EQ(PairType(2u, '4'), Results[2]);
}
template <bool B> struct CanMove {};
template <> struct CanMove<false> {
CanMove(CanMove &&) = delete;
CanMove() = default;
CanMove(const CanMove &) = default;
};
template <bool B> struct CanCopy {};
template <> struct CanCopy<false> {
CanCopy(const CanCopy &) = delete;
CanCopy() = default;
// FIXME: Use '= default' when we drop MSVC 2013.
CanCopy(CanCopy &&) {};
};
template <bool Moveable, bool Copyable>
struct Range : CanMove<Moveable>, CanCopy<Copyable> {
explicit Range(int &C, int &M, int &D) : C(C), M(M), D(D) {}
Range(const Range &R) : CanCopy<Copyable>(R), C(R.C), M(R.M), D(R.D) { ++C; }
Range(Range &&R) : CanMove<Moveable>(std::move(R)), C(R.C), M(R.M), D(R.D) {
++M;
}
~Range() { ++D; }
int &C;
int &M;
int &D;
int *begin() { return nullptr; }
int *end() { return nullptr; }
};
TEST(STLExtrasTest, EnumerateLifetimeSemantics) {
// Test that when enumerating lvalues and rvalues, there are no surprise
// copies or moves.
// With an rvalue, it should not be destroyed until the end of the scope.
int Copies = 0;
int Moves = 0;
int Destructors = 0;
{
auto E1 = enumerate(Range<true, false>(Copies, Moves, Destructors));
// Doesn't compile. rvalue ranges must be moveable.
// auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(1, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(2, Destructors);
Copies = Moves = Destructors = 0;
// With an lvalue, it should not be destroyed even after the end of the scope.
// lvalue ranges need be neither copyable nor moveable.
Range<false, false> R(Copies, Moves, Destructors);
{
auto Enumerator = enumerate(R);
(void)Enumerator;
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
}
|
//===- STLExtrasTest.cpp - Unit tests for STL extras ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h"
#include <vector>
using namespace llvm;
namespace {
int f(rank<0>) { return 0; }
int f(rank<1>) { return 1; }
int f(rank<2>) { return 2; }
int f(rank<4>) { return 4; }
TEST(STLExtrasTest, Rank) {
// We shouldn't get ambiguities and should select the overload of the same
// rank as the argument.
EXPECT_EQ(0, f(rank<0>()));
EXPECT_EQ(1, f(rank<1>()));
EXPECT_EQ(2, f(rank<2>()));
// This overload is missing so we end up back at 2.
EXPECT_EQ(2, f(rank<3>()));
// But going past 3 should work fine.
EXPECT_EQ(4, f(rank<4>()));
// And we can even go higher and just fall back to the last overload.
EXPECT_EQ(4, f(rank<5>()));
EXPECT_EQ(4, f(rank<6>()));
}
TEST(STLExtrasTest, EnumerateLValue) {
// Test that a simple LValue can be enumerated and gives correct results with
// multiple types, including the empty container.
std::vector<char> foo = {'a', 'b', 'c'};
typedef std::pair<std::size_t, char> CharPairType;
std::vector<CharPairType> CharResults;
for (auto X : llvm::enumerate(foo)) {
CharResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, CharResults.size());
EXPECT_EQ(CharPairType(0u, 'a'), CharResults[0]);
EXPECT_EQ(CharPairType(1u, 'b'), CharResults[1]);
EXPECT_EQ(CharPairType(2u, 'c'), CharResults[2]);
// Test a const range of a different type.
typedef std::pair<std::size_t, int> IntPairType;
std::vector<IntPairType> IntResults;
const std::vector<int> bar = {1, 2, 3};
for (auto X : llvm::enumerate(bar)) {
IntResults.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, IntResults.size());
EXPECT_EQ(IntPairType(0u, 1), IntResults[0]);
EXPECT_EQ(IntPairType(1u, 2), IntResults[1]);
EXPECT_EQ(IntPairType(2u, 3), IntResults[2]);
// Test an empty range.
IntResults.clear();
const std::vector<int> baz;
for (auto X : llvm::enumerate(baz)) {
IntResults.emplace_back(X.Index, X.Value);
}
EXPECT_TRUE(IntResults.empty());
}
TEST(STLExtrasTest, EnumerateModifyLValue) {
// Test that you can modify the underlying entries of an lvalue range through
// the enumeration iterator.
std::vector<char> foo = {'a', 'b', 'c'};
for (auto X : llvm::enumerate(foo)) {
++X.Value;
}
EXPECT_EQ('b', foo[0]);
EXPECT_EQ('c', foo[1]);
EXPECT_EQ('d', foo[2]);
}
TEST(STLExtrasTest, EnumerateRValueRef) {
// Test that an rvalue can be enumerated.
typedef std::pair<std::size_t, int> PairType;
std::vector<PairType> Results;
auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3});
for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) {
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, 1), Results[0]);
EXPECT_EQ(PairType(1u, 2), Results[1]);
EXPECT_EQ(PairType(2u, 3), Results[2]);
}
TEST(STLExtrasTest, EnumerateModifyRValue) {
// Test that when enumerating an rvalue, modification still works (even if
// this isn't terribly useful, it at least shows that we haven't snuck an
// extra const in there somewhere.
typedef std::pair<std::size_t, char> PairType;
std::vector<PairType> Results;
for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
++X.Value;
Results.emplace_back(X.Index, X.Value);
}
ASSERT_EQ(3u, Results.size());
EXPECT_EQ(PairType(0u, '2'), Results[0]);
EXPECT_EQ(PairType(1u, '3'), Results[1]);
EXPECT_EQ(PairType(2u, '4'), Results[2]);
}
template <bool B> struct CanMove {};
template <> struct CanMove<false> {
CanMove(CanMove &&) = delete;
CanMove() = default;
CanMove(const CanMove &) = default;
};
template <bool B> struct CanCopy {};
template <> struct CanCopy<false> {
CanCopy(const CanCopy &) = delete;
CanCopy() = default;
// FIXME: Use '= default' when we drop MSVC 2013.
CanCopy(CanCopy &&) {}
};
template <bool Moveable, bool Copyable>
struct Range : CanMove<Moveable>, CanCopy<Copyable> {
explicit Range(int &C, int &M, int &D) : C(C), M(M), D(D) {}
Range(const Range &R) : CanCopy<Copyable>(R), C(R.C), M(R.M), D(R.D) { ++C; }
Range(Range &&R) : CanMove<Moveable>(std::move(R)), C(R.C), M(R.M), D(R.D) {
++M;
}
~Range() { ++D; }
int &C;
int &M;
int &D;
int *begin() { return nullptr; }
int *end() { return nullptr; }
};
TEST(STLExtrasTest, EnumerateLifetimeSemantics) {
// Test that when enumerating lvalues and rvalues, there are no surprise
// copies or moves.
// With an rvalue, it should not be destroyed until the end of the scope.
int Copies = 0;
int Moves = 0;
int Destructors = 0;
{
auto E1 = enumerate(Range<true, false>(Copies, Moves, Destructors));
// Doesn't compile. rvalue ranges must be moveable.
// auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(1, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(1, Moves);
EXPECT_EQ(2, Destructors);
Copies = Moves = Destructors = 0;
// With an lvalue, it should not be destroyed even after the end of the scope.
// lvalue ranges need be neither copyable nor moveable.
Range<false, false> R(Copies, Moves, Destructors);
{
auto Enumerator = enumerate(R);
(void)Enumerator;
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
EXPECT_EQ(0, Copies);
EXPECT_EQ(0, Moves);
EXPECT_EQ(0, Destructors);
}
}
|
Remove extra semicolon
|
Remove extra semicolon
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@283395 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit 81e3914a008a38f0636dc576b34b3de126cc40d2)
|
C++
|
apache-2.0
|
apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm
|
b1500ee8d5de31b6c15925cf477737b0f38a4254
|
unittests/Support/TimerTest.cpp
|
unittests/Support/TimerTest.cpp
|
//===- unittests/TimerTest.cpp - Timer tests ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Timer.h"
#include "llvm/Support/Thread.h"
#include "gtest/gtest.h"
#include <chrono>
using namespace llvm;
namespace {
TEST(Timer, Additivity) {
Timer T1("T1");
EXPECT_TRUE(T1.isInitialized());
T1.startTimer();
T1.stopTimer();
auto TR1 = T1.getTotalTime();
T1.startTimer();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
T1.stopTimer();
auto TR2 = T1.getTotalTime();
EXPECT_TRUE(TR1 < TR2);
}
TEST(Timer, CheckIfTriggered) {
Timer T1("T1");
EXPECT_FALSE(T1.hasTriggered());
T1.startTimer();
EXPECT_TRUE(T1.hasTriggered());
T1.stopTimer();
EXPECT_TRUE(T1.hasTriggered());
T1.clear();
EXPECT_FALSE(T1.hasTriggered());
}
} // end anon namespace
|
//===- unittests/TimerTest.cpp - Timer tests ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Timer.h"
#include "llvm/Support/thread.h"
#include "gtest/gtest.h"
#include <chrono>
using namespace llvm;
namespace {
TEST(Timer, Additivity) {
Timer T1("T1");
EXPECT_TRUE(T1.isInitialized());
T1.startTimer();
T1.stopTimer();
auto TR1 = T1.getTotalTime();
T1.startTimer();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
T1.stopTimer();
auto TR2 = T1.getTotalTime();
EXPECT_TRUE(TR1 < TR2);
}
TEST(Timer, CheckIfTriggered) {
Timer T1("T1");
EXPECT_FALSE(T1.hasTriggered());
T1.startTimer();
EXPECT_TRUE(T1.hasTriggered());
T1.stopTimer();
EXPECT_TRUE(T1.hasTriggered());
T1.clear();
EXPECT_FALSE(T1.hasTriggered());
}
} // end anon namespace
|
Use Support/thread.h instead of <thread> (second try)
|
[unittest] Use Support/thread.h instead of <thread> (second try)
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@256292 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm
|
135d04cc9518d758d7bf4b3b353cb7757d7853b5
|
unsupported/test/sparse_llt.cpp
|
unsupported/test/sparse_llt.cpp
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "sparse.h"
#include <Eigen/SparseExtra>
#ifdef EIGEN_CHOLMOD_SUPPORT
#include <Eigen/CholmodSupport>
#endif
template<typename Scalar> void sparse_llt(int rows, int cols)
{
double density = std::max(8./(rows*cols), 0.01);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
// TODO fix the issue with complex (see SparseLLT::solveInPlace)
SparseMatrix<Scalar> m2(rows, cols);
DenseMatrix refMat2(rows, cols);
DenseVector b = DenseVector::Random(cols);
DenseVector ref_x(cols), x(cols);
DenseMatrix B = DenseMatrix::Random(rows,cols);
DenseMatrix ref_X(rows,cols), X(rows,cols);
initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, 0, 0);
for(int i=0; i<rows; ++i)
m2.coeffRef(i,i) = refMat2(i,i) = internal::abs(internal::real(refMat2(i,i)));
ref_x = refMat2.template selfadjointView<Lower>().llt().solve(b);
if (!NumTraits<Scalar>::IsComplex)
{
x = b;
SparseLLT<SparseMatrix<Scalar> > (m2).solveInPlace(x);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: default");
}
#ifdef EIGEN_CHOLMOD_SUPPORT
// legacy API
{
// Cholmod, as configured in CholmodSupport.h, only supports self-adjoint matrices
SparseMatrix<Scalar> m3 = m2.adjoint()*m2;
DenseMatrix refMat3 = refMat2.adjoint()*refMat2;
ref_x = refMat3.template selfadjointView<Lower>().llt().solve(b);
x = b;
SparseLLT<SparseMatrix<Scalar>, Cholmod>(m3).solveInPlace(x);
VERIFY((m3*x).isApprox(b,test_precision<Scalar>()) && "LLT legacy: cholmod solveInPlace");
x = SparseLLT<SparseMatrix<Scalar>, Cholmod>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT legacy: cholmod solve");
}
// new API
{
// Cholmod, as configured in CholmodSupport.h, only supports self-adjoint matrices
SparseMatrix<Scalar> m3 = m2 * m2.adjoint(), m3_lo(rows,rows), m3_up(rows,rows);
DenseMatrix refMat3 = refMat2 * refMat2.adjoint();
m3_lo.template selfadjointView<Lower>().rankUpdate(m2,0);
m3_up.template selfadjointView<Upper>().rankUpdate(m2,0);
// with a single vector as the rhs
ref_x = refMat3.template selfadjointView<Lower>().llt().solve(b);
x = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3_lo).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3_up).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
// with multiple rhs
ref_X = refMat3.template selfadjointView<Lower>().llt().solve(B);
X = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(B);
VERIFY(ref_X.isApprox(X,test_precision<Scalar>()) && "LLT: cholmod solve, multiple dense rhs");
X = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(B);
VERIFY(ref_X.isApprox(X,test_precision<Scalar>()) && "LLT: cholmod solve, multiple dense rhs");
// with a sparse rhs
SparseMatrix<Scalar> spB(rows,cols), spX(rows,cols);
B.diagonal().array() += 1;
spB = B.sparseView(0.5,1);
ref_X = refMat3.template selfadjointView<Lower>().llt().solve(DenseMatrix(spB));
spX = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(spB);
VERIFY(ref_X.isApprox(spX.toDense(),test_precision<Scalar>()) && "LLT: cholmod solve, multiple sparse rhs");
spX = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(spB);
VERIFY(ref_X.isApprox(spX.toDense(),test_precision<Scalar>()) && "LLT: cholmod solve, multiple sparse rhs");
}
#endif
}
void test_sparse_llt()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(sparse_llt<double>(8, 8) );
int s = internal::random<int>(1,300);
CALL_SUBTEST_2(sparse_llt<std::complex<double> >(s,s) );
CALL_SUBTEST_1(sparse_llt<double>(s,s) );
}
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "sparse.h"
#include <Eigen/SparseExtra>
#ifdef EIGEN_CHOLMOD_SUPPORT
#include <Eigen/CholmodSupport>
#endif
template<typename Scalar> void sparse_llt(int rows, int cols)
{
double density = std::max(8./(rows*cols), 0.01);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
// TODO fix the issue with complex (see SparseLLT::solveInPlace)
SparseMatrix<Scalar> m2(rows, cols);
DenseMatrix refMat2(rows, cols);
DenseVector b = DenseVector::Random(cols);
DenseVector ref_x(cols), x(cols);
DenseMatrix B = DenseMatrix::Random(rows,cols);
DenseMatrix ref_X(rows,cols), X(rows,cols);
initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, 0, 0);
for(int i=0; i<rows; ++i)
m2.coeffRef(i,i) = refMat2(i,i) = internal::abs(internal::real(refMat2(i,i)));
ref_x = refMat2.template selfadjointView<Lower>().llt().solve(b);
if (!NumTraits<Scalar>::IsComplex)
{
x = b;
SparseLLT<SparseMatrix<Scalar> > (m2).solveInPlace(x);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: default");
}
#ifdef EIGEN_CHOLMOD_SUPPORT
// legacy API
{
// Cholmod, as configured in CholmodSupport.h, only supports self-adjoint matrices
SparseMatrix<Scalar> m3 = m2.adjoint()*m2;
DenseMatrix refMat3 = refMat2.adjoint()*refMat2;
ref_x = refMat3.template selfadjointView<Lower>().llt().solve(b);
x = b;
SparseLLT<SparseMatrix<Scalar>, Cholmod>(m3).solveInPlace(x);
VERIFY((m3*x).isApprox(b,test_precision<Scalar>()) && "LLT legacy: cholmod solveInPlace");
x = SparseLLT<SparseMatrix<Scalar>, Cholmod>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT legacy: cholmod solve");
}
// new API
{
// Cholmod, as configured in CholmodSupport.h, only supports self-adjoint matrices
SparseMatrix<Scalar> m3 = m2 * m2.adjoint(), m3_lo(rows,rows), m3_up(rows,rows);
DenseMatrix refMat3 = refMat2 * refMat2.adjoint();
m3_lo.template selfadjointView<Lower>().rankUpdate(m2,0);
m3_up.template selfadjointView<Upper>().rankUpdate(m2,0);
// with a single vector as the rhs
ref_x = refMat3.template selfadjointView<Lower>().llt().solve(b);
x = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3_lo).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3_up).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
// with multiple rhs
ref_X = refMat3.template selfadjointView<Lower>().llt().solve(B);
#ifndef EIGEN_DEFAULT_TO_ROW_MAJOR
// TODO make sure the API is properly documented about this fact
X = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(B);
VERIFY(ref_X.isApprox(X,test_precision<Scalar>()) && "LLT: cholmod solve, multiple dense rhs");
X = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(B);
VERIFY(ref_X.isApprox(X,test_precision<Scalar>()) && "LLT: cholmod solve, multiple dense rhs");
#endif
// with a sparse rhs
SparseMatrix<Scalar> spB(rows,cols), spX(rows,cols);
B.diagonal().array() += 1;
spB = B.sparseView(0.5,1);
ref_X = refMat3.template selfadjointView<Lower>().llt().solve(DenseMatrix(spB));
spX = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(spB);
VERIFY(ref_X.isApprox(spX.toDense(),test_precision<Scalar>()) && "LLT: cholmod solve, multiple sparse rhs");
spX = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(spB);
VERIFY(ref_X.isApprox(spX.toDense(),test_precision<Scalar>()) && "LLT: cholmod solve, multiple sparse rhs");
}
#endif
}
void test_sparse_llt()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(sparse_llt<double>(8, 8) );
int s = internal::random<int>(1,300);
CALL_SUBTEST_2(sparse_llt<std::complex<double> >(s,s) );
CALL_SUBTEST_1(sparse_llt<double>(s,s) );
}
}
|
fix compilation when defaulting to row major
|
fix compilation when defaulting to row major
|
C++
|
bsd-3-clause
|
pasuka/eigen,Zefz/eigen,Zefz/eigen,TSC21/Eigen,ritsu1228/eigen,ritsu1228/eigen,toastedcrumpets/eigen,TSC21/Eigen,Zefz/eigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,TSC21/Eigen,toastedcrumpets/eigen,ritsu1228/eigen,toastedcrumpets/eigen,ritsu1228/eigen,ROCmSoftwarePlatform/hipeigen,toastedcrumpets/eigen,TSC21/Eigen,Zefz/eigen,pasuka/eigen,ritsu1228/eigen,ROCmSoftwarePlatform/hipeigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,pasuka/eigen
|
5a842595acbc9ee20c9a2976d328ce216e30bc45
|
c++/samples/calculator-server.c++
|
c++/samples/calculator-server.c++
|
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "calculator.capnp.h"
#include <kj/debug.h>
#include <capnp/ez-rpc.h>
#include <capnp/message.h>
#include <iostream>
typedef unsigned int uint;
kj::Promise<double> readValue(Calculator::Value::Client value) {
// Helper function to asynchronously call read() on a Calculator::Value and
// return a promise for the result. (In the future, the generated code might
// include something like this automatically.)
return value.readRequest().send()
.then([](capnp::Response<Calculator::Value::ReadResults> result) {
return result.getValue();
});
}
kj::Promise<double> evaluateImpl(
Calculator::Expression::Reader expression,
capnp::List<double>::Reader params = capnp::List<double>::Reader()) {
// Implementation of CalculatorImpl::evaluate(), also shared by
// FunctionImpl::call(). In the latter case, `params` are the parameter
// values passed to the function; in the former case, `params` is just an
// empty list.
switch (expression.which()) {
case Calculator::Expression::LITERAL:
return expression.getLiteral();
case Calculator::Expression::PREVIOUS_RESULT:
return readValue(expression.getPreviousResult());
case Calculator::Expression::PARAMETER: {
KJ_REQUIRE(expression.getParameter() < params.size(),
"Parameter index out-of-range.");
return params[expression.getParameter()];
}
case Calculator::Expression::CALL: {
auto call = expression.getCall();
auto func = call.getFunction();
// Evaluate each parameter.
kj::Array<kj::Promise<double>> paramPromises =
KJ_MAP(param, call.getParams()) {
return evaluateImpl(param, params);
};
// Join the array of promises into a promise for an array.
kj::Promise<kj::Array<double>> joinedParams =
kj::joinPromises(kj::mv(paramPromises));
// When the parameters are complete, call the function.
return joinedParams.then([func](kj::Array<double>&& paramValues) mutable {
auto request = func.callRequest();
request.setParams(paramValues);
return request.send().then(
[](capnp::Response<Calculator::Function::CallResults>&& result) {
return result.getValue();
});
});
}
default:
// Throw an exception.
KJ_FAIL_REQUIRE("Unknown expression type.");
}
}
class ValueImpl final: public Calculator::Value::Server {
// Simple implementation of the Calculator.Value Cap'n Proto interface.
public:
ValueImpl(double value): value(value) {}
kj::Promise<void> read(ReadContext context) {
context.getResults().setValue(value);
return kj::READY_NOW;
}
private:
double value;
};
class FunctionImpl final: public Calculator::Function::Server {
// Implementation of the Calculator.Function Cap'n Proto interface, where the
// function is defined by a Calculator.Expression.
public:
FunctionImpl(uint paramCount, Calculator::Expression::Reader body)
: paramCount(paramCount) {
this->body.setRoot(body);
}
kj::Promise<void> call(CallContext context) {
auto params = context.getParams().getParams();
KJ_REQUIRE(params.size() == paramCount, "Wrong number of parameters.");
return evaluateImpl(body.getRoot<Calculator::Expression>(), params)
.then([context](double value) mutable {
context.getResults().setValue(value);
});
}
private:
uint paramCount;
// The function's arity.
capnp::MallocMessageBuilder body;
// Stores a permanent copy of the function body.
};
class OperatorImpl final: public Calculator::Function::Server {
// Implementation of the Calculator.Function Cap'n Proto interface, wrapping
// basic binary arithmetic operators.
public:
OperatorImpl(Calculator::Operator op): op(op) {}
kj::Promise<void> call(CallContext context) {
auto params = context.getParams().getParams();
KJ_REQUIRE(params.size() == 2, "Wrong number of parameters.");
double result;
switch (op) {
case Calculator::Operator::ADD: result = params[0] + params[1]; break;
case Calculator::Operator::SUBTRACT:result = params[0] - params[1]; break;
case Calculator::Operator::MULTIPLY:result = params[0] * params[1]; break;
case Calculator::Operator::DIVIDE: result = params[0] / params[1]; break;
default:
KJ_FAIL_REQUIRE("Unknown operator.");
}
context.getResults().setValue(result);
return kj::READY_NOW;
}
private:
Calculator::Operator op;
};
class CalculatorImpl final: public Calculator::Server {
// Implementation of the Calculator Cap'n Proto interface.
public:
kj::Promise<void> evaluate(EvaluateContext context) override {
return evaluateImpl(context.getParams().getExpression())
.then([context](double value) mutable {
context.getResults().setValue(kj::heap<ValueImpl>(value));
});
}
kj::Promise<void> defFunction(DefFunctionContext context) override {
auto params = context.getParams();
context.getResults().setFunc(kj::heap<FunctionImpl>(
params.getParamCount(), params.getBody()));
return kj::READY_NOW;
}
kj::Promise<void> getOperator(GetOperatorContext context) override {
context.getResults().setFunc(kj::heap<OperatorImpl>(
context.getParams().getOp()));
return kj::READY_NOW;
}
};
int main(int argc, const char* argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " ADDRESS[:PORT]\n"
"Runs the server bound to the given address/port.\n"
"ADDRESS may be '*' to bind to all local addresses.\n"
":PORT may be omitted to choose a port automatically." << std::endl;
return 1;
}
// Set up a server.
capnp::EzRpcServer server(kj::heap<CalculatorImpl>(), argv[1]);
// Write the port number to stdout, in case it was chosen automatically.
auto& waitScope = server.getWaitScope();
uint port = server.getPort().wait(waitScope);
if (port == 0) {
// The address format "unix:/path/to/socket" opens a unix domain socket,
// in which case the port will be zero.
std::cout << "Listening on Unix socket..." << std::endl;
} else {
std::cout << "Listening on port " << port << "..." << std::endl;
}
// Run forever, accepting connections and handling requests.
kj::NEVER_DONE.wait(waitScope);
}
|
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "calculator.capnp.h"
#include <kj/debug.h>
#include <capnp/ez-rpc.h>
#include <capnp/message.h>
#include <iostream>
typedef unsigned int uint;
kj::Promise<double> readValue(Calculator::Value::Client value) {
// Helper function to asynchronously call read() on a Calculator::Value and
// return a promise for the result. (In the future, the generated code might
// include something like this automatically.)
return value.readRequest().send()
.then([](capnp::Response<Calculator::Value::ReadResults> result) {
return result.getValue();
});
}
kj::Promise<double> evaluateImpl(
Calculator::Expression::Reader expression,
capnp::List<double>::Reader params = capnp::List<double>::Reader()) {
// Implementation of CalculatorImpl::evaluate(), also shared by
// FunctionImpl::call(). In the latter case, `params` are the parameter
// values passed to the function; in the former case, `params` is just an
// empty list.
switch (expression.which()) {
case Calculator::Expression::LITERAL:
return expression.getLiteral();
case Calculator::Expression::PREVIOUS_RESULT:
return readValue(expression.getPreviousResult());
case Calculator::Expression::PARAMETER: {
KJ_REQUIRE(expression.getParameter() < params.size(),
"Parameter index out-of-range.");
return params[expression.getParameter()];
}
case Calculator::Expression::CALL: {
auto call = expression.getCall();
auto func = call.getFunction();
// Evaluate each parameter.
kj::Array<kj::Promise<double>> paramPromises =
KJ_MAP(param, call.getParams()) {
return evaluateImpl(param, params);
};
// Join the array of promises into a promise for an array.
kj::Promise<kj::Array<double>> joinedParams =
kj::joinPromises(kj::mv(paramPromises));
// When the parameters are complete, call the function.
return joinedParams.then([KJ_CPCAP(func)](kj::Array<double>&& paramValues) mutable {
auto request = func.callRequest();
request.setParams(paramValues);
return request.send().then(
[](capnp::Response<Calculator::Function::CallResults>&& result) {
return result.getValue();
});
});
}
default:
// Throw an exception.
KJ_FAIL_REQUIRE("Unknown expression type.");
}
}
class ValueImpl final: public Calculator::Value::Server {
// Simple implementation of the Calculator.Value Cap'n Proto interface.
public:
ValueImpl(double value): value(value) {}
kj::Promise<void> read(ReadContext context) {
context.getResults().setValue(value);
return kj::READY_NOW;
}
private:
double value;
};
class FunctionImpl final: public Calculator::Function::Server {
// Implementation of the Calculator.Function Cap'n Proto interface, where the
// function is defined by a Calculator.Expression.
public:
FunctionImpl(uint paramCount, Calculator::Expression::Reader body)
: paramCount(paramCount) {
this->body.setRoot(body);
}
kj::Promise<void> call(CallContext context) {
auto params = context.getParams().getParams();
KJ_REQUIRE(params.size() == paramCount, "Wrong number of parameters.");
return evaluateImpl(body.getRoot<Calculator::Expression>(), params)
.then([KJ_CPCAP(context)](double value) mutable {
context.getResults().setValue(value);
});
}
private:
uint paramCount;
// The function's arity.
capnp::MallocMessageBuilder body;
// Stores a permanent copy of the function body.
};
class OperatorImpl final: public Calculator::Function::Server {
// Implementation of the Calculator.Function Cap'n Proto interface, wrapping
// basic binary arithmetic operators.
public:
OperatorImpl(Calculator::Operator op): op(op) {}
kj::Promise<void> call(CallContext context) {
auto params = context.getParams().getParams();
KJ_REQUIRE(params.size() == 2, "Wrong number of parameters.");
double result;
switch (op) {
case Calculator::Operator::ADD: result = params[0] + params[1]; break;
case Calculator::Operator::SUBTRACT:result = params[0] - params[1]; break;
case Calculator::Operator::MULTIPLY:result = params[0] * params[1]; break;
case Calculator::Operator::DIVIDE: result = params[0] / params[1]; break;
default:
KJ_FAIL_REQUIRE("Unknown operator.");
}
context.getResults().setValue(result);
return kj::READY_NOW;
}
private:
Calculator::Operator op;
};
class CalculatorImpl final: public Calculator::Server {
// Implementation of the Calculator Cap'n Proto interface.
public:
kj::Promise<void> evaluate(EvaluateContext context) override {
return evaluateImpl(context.getParams().getExpression())
.then([KJ_CPCAP(context)](double value) mutable {
context.getResults().setValue(kj::heap<ValueImpl>(value));
});
}
kj::Promise<void> defFunction(DefFunctionContext context) override {
auto params = context.getParams();
context.getResults().setFunc(kj::heap<FunctionImpl>(
params.getParamCount(), params.getBody()));
return kj::READY_NOW;
}
kj::Promise<void> getOperator(GetOperatorContext context) override {
context.getResults().setFunc(kj::heap<OperatorImpl>(
context.getParams().getOp()));
return kj::READY_NOW;
}
};
int main(int argc, const char* argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " ADDRESS[:PORT]\n"
"Runs the server bound to the given address/port.\n"
"ADDRESS may be '*' to bind to all local addresses.\n"
":PORT may be omitted to choose a port automatically." << std::endl;
return 1;
}
// Set up a server.
capnp::EzRpcServer server(kj::heap<CalculatorImpl>(), argv[1]);
// Write the port number to stdout, in case it was chosen automatically.
auto& waitScope = server.getWaitScope();
uint port = server.getPort().wait(waitScope);
if (port == 0) {
// The address format "unix:/path/to/socket" opens a unix domain socket,
// in which case the port will be zero.
std::cout << "Listening on Unix socket..." << std::endl;
} else {
std::cout << "Listening on port " << port << "..." << std::endl;
}
// Run forever, accepting connections and handling requests.
kj::NEVER_DONE.wait(waitScope);
}
|
Work around MSVC mutable copy capture bug
|
Work around MSVC mutable copy capture bug
|
C++
|
mit
|
mologie/capnproto,mologie/capnproto,mologie/capnproto
|
5ddefe2a65f0b7b18e80abf537e6aadf5d6d3451
|
src/import/chips/p9/procedures/hwp/memory/lib/dimm/mrs_load.H
|
src/import/chips/p9/procedures/hwp/memory/lib/dimm/mrs_load.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/mrs_load.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs_load.H
/// @brief Code to support mrs_loads
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_MRS_LOAD_H_
#define _MSS_MRS_LOAD_H_
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <lib/utils/c_str.H>
#include <lib/shared/mss_kind.H>
#include <lib/ccs/ccs.H>
namespace mss
{
///
/// @brief MR Parameter Error Values
/// A set of enumerations allowing one error xml/code to represent all bad parameters
/// for MR encoding. The error info will take which MR has bad encoding, one of these
/// enumerations to indicate which field was incorrect, and then the incorrect value.
///
enum mrs_bad_field
{
WRITE_CMD_LATENCY = 0,
WRITE_RECOVERY = 1,
CAS_LATENCY = 2,
OUTPUT_IMPEDANCE = 3,
CAS_WRITE_LATENCY = 4,
CS_CMD_LATENCY = 5,
CA_PARITY_LATENCY = 6,
RTT_PARK = 7,
TCCD = 8,
RANK = 9,
RTT_NOM = 10
};
///
/// @brief A structure to represent an MRS operation
/// @tparam T, the target type of the CCS engine chiplet
///
template< fapi2::TargetType T >
struct mrs_data
{
// Which MRS# this is
fapi2::buffer<uint8_t> iv_mrs;
// The attribute getter. For MRS we pass in the ARR0 of the CCS instruction
// as that allows us to encapsulate the attribute processing and the bit
// manipulation in one function.
fapi2::ReturnCode (*iv_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, ccs::instruction_t<T>&, const uint64_t);
fapi2::ReturnCode (*iv_dumper)(const ccs::instruction_t<T>&, const uint64_t);
// The delay needed after this MRS word is written
uint64_t iv_delay;
mrs_data( const uint64_t i_mrs,
fapi2::ReturnCode (*i_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, ccs::instruction_t<T>&, const uint64_t),
fapi2::ReturnCode (*i_dumper)(const ccs::instruction_t<T>&, const uint64_t),
const uint64_t i_delay ):
iv_mrs(i_mrs),
iv_func(i_func),
iv_dumper(i_dumper),
iv_delay(i_delay)
{}
};
///
/// @brief Perform the mrs_load operations
/// @tparam T, the fapi2::TargetType of i_target
/// @param[in] i_target, a fapi2::Target
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< fapi2::TargetType T >
fapi2::ReturnCode mrs_load( const fapi2::Target<T>& i_target );
//
// Implement the polymorphism for mrs_load
//
// -# Register the API.
/// -# Define the template parameters for the overloaded function
/// @note the first argument is the api name, and the rest are the api's template parameters.
/// @note this creates __api_name##_overload
template< mss::kind_t K >
struct perform_mrs_load_overload
{
static const bool available = false;
};
/// -# Register the specific overloads. The first parameter is the name
/// of the api, the second is the kind of the element which is being
/// overloaded - an RDIMM, an LRDIMM, etc. The remaining parameters
/// indicate the specialization of the api itself.
/// @note You need to define the "DEFAULT_KIND" here as an overload. This
/// allows the mechanism to find the "base" implementation for things which
/// have no specific overload.
template<>
struct perform_mrs_load_overload< DEFAULT_KIND >
{
static const bool available = true;
};
template<>
struct perform_mrs_load_overload< KIND_RDIMM_DDR4 >
{
static const bool available = true;
};
template<>
struct perform_mrs_load_overload< KIND_LRDIMM_DDR4 >
{
static const bool available = true;
};
///
/// -# Define the default case for overloaded calls. enable_if states that
/// if there is a DEFAULT_KIND overload for this TargetType, then this
/// entry point will be defined. Note the general case below is enabled if
/// there is no overload defined for this TargetType
///
///
/// @brief Perform the mrs_load operations
/// @tparam K, the kind of DIMM we're operating on (derived)
/// @param[in] i_target, a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< mss::kind_t K = FORCE_DISPATCH >
typename std::enable_if< perform_mrs_load_overload<DEFAULT_KIND>::available, fapi2::ReturnCode>::type
perform_mrs_load( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst);
//
// We know we registered overloads for perform_mrs_load, so we need the entry point to
// the dispatcher. Add a set of these for all TargetTypes which get overloads
// for this API
//
template<>
fapi2::ReturnCode perform_mrs_load<FORCE_DISPATCH>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst);
template<>
fapi2::ReturnCode perform_mrs_load<DEFAULT_KIND>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst);
//
// Boilerplate dispatcher
//
template< kind_t K, bool B = perform_mrs_load_overload<K>::available >
inline fapi2::ReturnCode perform_mrs_load_dispatch( const kind_t& i_kind,
const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
// We dispatch to another kind if:
// We don't have an overload defined (B == false)
// Or, if we do have an overload (B == true) and this is not out kind.
if ((B == false) || ((B == true) && (K != i_kind)))
{
return perform_mrs_load_dispatch < (kind_t)(K - 1) > (i_kind, i_target, io_inst);
}
// Otherwise, we call the overload.
return perform_mrs_load<K>(i_target, io_inst);
}
// DEFAULT_KIND is 0 so this is the end of the recursion
template<>
inline fapi2::ReturnCode perform_mrs_load_dispatch<DEFAULT_KIND>(const kind_t&,
const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
return perform_mrs_load<DEFAULT_KIND>(i_target, io_inst);
}
}
#endif
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/mrs_load.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs_load.H
/// @brief Code to support mrs_loads
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_MRS_LOAD_H_
#define _MSS_MRS_LOAD_H_
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <c_str.H>
#include <lib/shared/mss_kind.H>
#include <lib/ccs/ccs.H>
namespace mss
{
///
/// @brief MR Parameter Error Values
/// A set of enumerations allowing one error xml/code to represent all bad parameters
/// for MR encoding. The error info will take which MR has bad encoding, one of these
/// enumerations to indicate which field was incorrect, and then the incorrect value.
///
enum mrs_bad_field
{
WRITE_CMD_LATENCY = 0,
WRITE_RECOVERY = 1,
CAS_LATENCY = 2,
OUTPUT_IMPEDANCE = 3,
CAS_WRITE_LATENCY = 4,
CS_CMD_LATENCY = 5,
CA_PARITY_LATENCY = 6,
RTT_PARK = 7,
TCCD = 8,
RANK = 9,
RTT_NOM = 10
};
///
/// @brief A structure to represent an MRS operation
/// @tparam T, the target type of the CCS engine chiplet
///
template< fapi2::TargetType T >
struct mrs_data
{
// Which MRS# this is
fapi2::buffer<uint8_t> iv_mrs;
// The attribute getter. For MRS we pass in the ARR0 of the CCS instruction
// as that allows us to encapsulate the attribute processing and the bit
// manipulation in one function.
fapi2::ReturnCode (*iv_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, ccs::instruction_t<T>&, const uint64_t);
fapi2::ReturnCode (*iv_dumper)(const ccs::instruction_t<T>&, const uint64_t);
// The delay needed after this MRS word is written
uint64_t iv_delay;
mrs_data( const uint64_t i_mrs,
fapi2::ReturnCode (*i_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, ccs::instruction_t<T>&, const uint64_t),
fapi2::ReturnCode (*i_dumper)(const ccs::instruction_t<T>&, const uint64_t),
const uint64_t i_delay ):
iv_mrs(i_mrs),
iv_func(i_func),
iv_dumper(i_dumper),
iv_delay(i_delay)
{}
};
///
/// @brief Perform the mrs_load operations
/// @tparam T, the fapi2::TargetType of i_target
/// @param[in] i_target, a fapi2::Target
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< fapi2::TargetType T >
fapi2::ReturnCode mrs_load( const fapi2::Target<T>& i_target );
//
// Implement the polymorphism for mrs_load
//
// -# Register the API.
/// -# Define the template parameters for the overloaded function
/// @note the first argument is the api name, and the rest are the api's template parameters.
/// @note this creates __api_name##_overload
template< mss::kind_t K >
struct perform_mrs_load_overload
{
static const bool available = false;
};
/// -# Register the specific overloads. The first parameter is the name
/// of the api, the second is the kind of the element which is being
/// overloaded - an RDIMM, an LRDIMM, etc. The remaining parameters
/// indicate the specialization of the api itself.
/// @note You need to define the "DEFAULT_KIND" here as an overload. This
/// allows the mechanism to find the "base" implementation for things which
/// have no specific overload.
template<>
struct perform_mrs_load_overload< DEFAULT_KIND >
{
static const bool available = true;
};
template<>
struct perform_mrs_load_overload< KIND_RDIMM_DDR4 >
{
static const bool available = true;
};
template<>
struct perform_mrs_load_overload< KIND_LRDIMM_DDR4 >
{
static const bool available = true;
};
///
/// -# Define the default case for overloaded calls. enable_if states that
/// if there is a DEFAULT_KIND overload for this TargetType, then this
/// entry point will be defined. Note the general case below is enabled if
/// there is no overload defined for this TargetType
///
///
/// @brief Perform the mrs_load operations
/// @tparam K, the kind of DIMM we're operating on (derived)
/// @param[in] i_target, a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< mss::kind_t K = FORCE_DISPATCH >
typename std::enable_if< perform_mrs_load_overload<DEFAULT_KIND>::available, fapi2::ReturnCode>::type
perform_mrs_load( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst);
//
// We know we registered overloads for perform_mrs_load, so we need the entry point to
// the dispatcher. Add a set of these for all TargetTypes which get overloads
// for this API
//
template<>
fapi2::ReturnCode perform_mrs_load<FORCE_DISPATCH>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst);
template<>
fapi2::ReturnCode perform_mrs_load<DEFAULT_KIND>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst);
//
// Boilerplate dispatcher
//
template< kind_t K, bool B = perform_mrs_load_overload<K>::available >
inline fapi2::ReturnCode perform_mrs_load_dispatch( const kind_t& i_kind,
const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
// We dispatch to another kind if:
// We don't have an overload defined (B == false)
// Or, if we do have an overload (B == true) and this is not out kind.
if ((B == false) || ((B == true) && (K != i_kind)))
{
return perform_mrs_load_dispatch < (kind_t)(K - 1) > (i_kind, i_target, io_inst);
}
// Otherwise, we call the overload.
return perform_mrs_load<K>(i_target, io_inst);
}
// DEFAULT_KIND is 0 so this is the end of the recursion
template<>
inline fapi2::ReturnCode perform_mrs_load_dispatch<DEFAULT_KIND>(const kind_t&,
const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
return perform_mrs_load<DEFAULT_KIND>(i_target, io_inst);
}
}
#endif
|
Add c_str generic API and update makefiles
|
Add c_str generic API and update makefiles
Change-Id: I927538d4f17e27427b3b4b43d8d5d89b65b27316
Original-Change-Id: I95e3b9013d3ab0c352d3614c12ee4ef0d26965d0
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/35924
Tested-by: Jenkins Server <[email protected]>
Reviewed-by: Louis Stermole <[email protected]>
Reviewed-by: STEPHEN GLANCY <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Brian R. Silver <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
54d2f568bcaedc9b212b1412f751ee59679b9b88
|
caffe2/operators/pool_op_cudnn.cc
|
caffe2/operators/pool_op_cudnn.cc
|
#include "caffe2/core/common_cudnn.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/operators/conv_pool_op_base.h"
namespace caffe2 {
namespace {
template <typename T>
void setTensorDescriptor(
const int size,
const StorageOrder order,
const int N,
const int C,
const int H,
const int W,
const int D,
cudnnTensorDescriptor_t& desc) {
if (size == 4) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
desc,
GetCudnnTensorFormat(order),
cudnnTypeWrapper<T>::type,
N,
C,
H,
W));
} else {
vector<int> dims = {N, C, H, W, D};
vector<int> strides;
order == NCHW
? strides.insert(strides.end(), {C * H * W * D, H * W * D, W * D, D, 1})
: strides.insert(
strides.end(), {H * W * D * C, 1, W * D * C, D * C, C});
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
desc,
cudnnTypeWrapper<T>::type,
size > 3 ? size : 4,
dims.data(),
strides.data()));
}
}
} // namespace
class CuDNNPoolOp : public ConvPoolOpBase<CUDAContext> {
public:
CuDNNPoolOp(const OperatorDef& operator_def, Workspace* ws)
: ConvPoolOpBase<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_) {
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_));
CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_));
// Figure out the pooling descriptor.
if (def().type().substr(0, 7) == "MaxPool") {
#if CUDNN_VERSION_MIN(6,0,0)
mode_ = CUDNN_POOLING_MAX_DETERMINISTIC;
#else
mode_ = CUDNN_POOLING_MAX;
#endif
} else if (def().type().substr(0, 11) == "AveragePool") {
mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
} else {
LOG(FATAL) << "Unsupported pooling method: " << def().type();
}
}
~CuDNNPoolOp() {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_));
CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_));
}
template <typename T, typename M>
bool DoRunWithType() {
auto& X = Input(0);
auto* Y = Output(0);
int N = 0, C = 0, H = 0, W = 0, D = 0;
int H_out = 0, W_out = 0, D_out = 0;
// cuDNN pooling support only 2 and 3 spatial dimensions.
CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5);
switch (order_) {
case StorageOrder::NHWC:
N = X.dim32(0);
H = X.dim32(1);
W = X.ndim() > 3 ? X.dim32(2) : 1;
D = X.ndim() > 4 ? X.dim32(3) : 1;
C = X.dim32(X.ndim() - 1);
ConvPoolOpBase::SetOutputSize(X, Y, C);
H_out = Y->dim32(1);
W_out = Y->ndim() > 3 ? Y->dim32(2) : 1;
D_out = Y->ndim() > 4 ? Y->dim32(3) : 1;
break;
case StorageOrder::NCHW:
N = X.dim32(0);
C = X.dim32(1);
H = X.dim32(2);
W = X.ndim() > 3 ? X.dim32(3) : 1;
D = X.ndim() > 4 ? X.dim32(4) : 1;
ConvPoolOpBase::SetOutputSize(X, Y, C);
H_out = Y->dim32(2);
W_out = Y->ndim() > 3 ? Y->dim32(3) : 1;
D_out = Y->ndim() > 4 ? Y->dim32(4) : 1;
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
if (cudnn_input_dims_ != X.dims()) {
// Dimensions changed; we will need to re-initialize things.
VLOG(1) << "Changing the cudnn descriptor configurations.";
cudnn_input_dims_ = X.dims();
setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_);
setTensorDescriptor<T>(
Y->ndim(), order_, N, C, H_out, W_out, D_out, top_desc_);
if (pad_t() != pad_l() || pad_l() != pad_r()) {
CAFFE_ENFORCE(
legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING,
"Cudnn pooling only supports even padding on both sides, with "
"the only exception of the caffe legacy pooling case where we "
"try to preserve backward compatibility with Caffe.");
}
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetPooling2dDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_h(),
kernel_w(),
pad_t(),
pad_l(),
stride_h(),
stride_w()));
} else {
CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_.size(),
kernel_.data(),
pads_.data(),
stride_.data()));
}
}
// Carry out the pooling computation.
CUDNN_ENFORCE(cudnnPoolingForward(
cudnn_wrapper_.inline_cudnn_handle(),
pooling_desc_,
cudnnTypeWrapper<T>::kOne(),
bottom_desc_,
X.template data<T>(),
cudnnTypeWrapper<T>::kZero(),
top_desc_,
Y->template mutable_data<T>()));
return true;
}
bool RunOnDevice() final {
auto& X = Input(0);
auto* Y = Output(0);
if (X.IsType<float>()) {
return DoRunWithType<float,float>();
} else if (X.IsType<float16>()) {
return DoRunWithType<float16,float>();
} else {
LOG(FATAL) << "Unsupported input types";
}
return true;
}
protected:
vector<TIndex> cudnn_input_dims_;
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t bottom_desc_;
cudnnTensorDescriptor_t top_desc_;
cudnnPoolingDescriptor_t pooling_desc_;
cudnnPoolingMode_t mode_;
private:
};
class CuDNNPoolGradientOp : public ConvPoolOpBase<CUDAContext> {
public:
CuDNNPoolGradientOp(const OperatorDef& operator_def, Workspace* ws)
: ConvPoolOpBase<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_) {
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_));
CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_));
// Figure out the pooling descriptor.
if (def().type() == "MaxPoolGradient") {
mode_ = CUDNN_POOLING_MAX;
} else if (def().type() == "AveragePoolGradient") {
mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
} else {
LOG(FATAL) << "Unsupported pooling method: " << def().type();
}
}
~CuDNNPoolGradientOp() {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_));
CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_));
}
template <typename T, typename M>
bool DoRunWithType() {
auto& X = Input(0);
auto& Y = Input(1);
auto& dY = Input(2);
auto* dX = Output(0);
// cuDNN pooling support only 2 and 3 spatial dimensions.
CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5);
dX->ResizeLike(X);
int N = 0, C = 0, H = 0, W = 0, D = 0;
int H_out = 0, W_out = 0, D_out = 0;
switch (order_) {
case StorageOrder::NHWC:
N = X.dim32(0);
H = X.dim32(1);
W = X.ndim() > 3 ? X.dim32(2) : 1;
D = X.ndim() > 4 ? X.dim32(3) : 1;
C = X.dim32(X.ndim() - 1);
H_out = Y.dim32(1);
W_out = Y.ndim() > 3 ? Y.dim32(2) : 1;
D_out = Y.ndim() > 4 ? Y.dim32(3) : 1;
break;
case StorageOrder::NCHW:
N = X.dim32(0);
C = X.dim32(1);
H = X.dim32(2);
W = X.ndim() > 3 ? X.dim32(3) : 1;
D = X.ndim() > 4 ? X.dim32(4) : 1;
H_out = Y.dim32(2);
W_out = Y.ndim() > 3 ? Y.dim32(3) : 1;
D_out = Y.ndim() > 4 ? Y.dim32(4) : 1;
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
if (kernel_.size() == 1) {
ConvPoolOpBase<CUDAContext>::ComputePads({H});
} else if (kernel_.size() == 2) {
ConvPoolOpBase<CUDAContext>::ComputePads({H, W});
} else if (kernel_.size() == 3) {
ConvPoolOpBase<CUDAContext>::ComputePads({H, W, D});
} else {
CAFFE_THROW("Unsupported kernel size :", kernel_.size());
}
if (cudnn_input_dims_ != X.dims()) {
// Dimensions changed; we will need to re-initialize things.
VLOG(1) << "Changing the cudnn descriptor configurations.";
cudnn_input_dims_ = X.dims();
setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_);
setTensorDescriptor<T>(
Y.ndim(), order_, N, C, H_out, W_out, D_out, top_desc_);
if (pad_t() != pad_l() || pad_l() != pad_r()) {
CAFFE_ENFORCE(
legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING,
"Cudnn pooling only supports even padding on both sides, with "
"the only exception of the caffe legacy pooling case where we "
"try to preserve backward compatibility with Caffe.");
}
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetPooling2dDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_h(),
kernel_w(),
pad_t(),
pad_l(),
stride_h(),
stride_w()));
} else {
CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_.size(),
kernel_.data(),
pads_.data(),
stride_.data()));
}
}
// Carry out the pooling computation.
CUDNN_ENFORCE(cudnnPoolingBackward(
cudnn_wrapper_.inline_cudnn_handle(),
pooling_desc_,
cudnnTypeWrapper<T>::kOne(),
top_desc_,
Y.template data<T>(),
top_desc_,
dY.template data<T>(),
bottom_desc_,
X.template data<T>(),
cudnnTypeWrapper<T>::kZero(),
bottom_desc_,
dX->template mutable_data<T>()));
return true;
}
bool RunOnDevice() final {
auto& X = Input(0);
auto& Y = Input(1);
auto& dY = Input(2);
auto* dX = Output(0);
dX->ResizeLike(X);
if (X.IsType<float>()) {
return DoRunWithType<float,float>();
} else if (X.IsType<float16>()) {
return DoRunWithType<float16,float>();
} else {
LOG(FATAL) << "Unsupported input types";
}
return true;
}
protected:
vector<TIndex> cudnn_input_dims_;
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t bottom_desc_;
cudnnTensorDescriptor_t top_desc_;
cudnnPoolingDescriptor_t pooling_desc_;
cudnnPoolingMode_t mode_;
// Input: X, Y, dY
// Output: dX
INPUT_TAGS(IN, OUT, OUT_GRAD);
};
namespace {
REGISTER_CUDNN_OPERATOR(AveragePool, CuDNNPoolOp);
REGISTER_CUDNN_OPERATOR(AveragePoolGradient, CuDNNPoolGradientOp);
REGISTER_CUDNN_OPERATOR(MaxPool, CuDNNPoolOp);
REGISTER_CUDNN_OPERATOR(MaxPoolGradient, CuDNNPoolGradientOp);
} // namespace
} // namespace caffe2
|
#include "caffe2/core/common_cudnn.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/operators/conv_pool_op_base.h"
namespace caffe2 {
namespace {
template <typename T>
void setTensorDescriptor(
const int size,
const StorageOrder order,
const int N,
const int C,
const int H,
const int W,
const int D,
cudnnTensorDescriptor_t& desc) {
if (size == 4) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
desc,
GetCudnnTensorFormat(order),
cudnnTypeWrapper<T>::type,
N,
C,
H,
W));
} else {
vector<int> dims = {N, C, H, W, D};
vector<int> strides;
order == NCHW
? strides.insert(strides.end(), {C * H * W * D, H * W * D, W * D, D, 1})
: strides.insert(
strides.end(), {H * W * D * C, 1, W * D * C, D * C, C});
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
desc,
cudnnTypeWrapper<T>::type,
size > 3 ? size : 4,
dims.data(),
strides.data()));
}
}
} // namespace
class CuDNNPoolOp : public ConvPoolOpBase<CUDAContext> {
public:
CuDNNPoolOp(const OperatorDef& operator_def, Workspace* ws)
: ConvPoolOpBase<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_) {
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_));
CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_));
// Figure out the pooling descriptor.
if (def().type().substr(0, 7) == "MaxPool") {
#if CUDNN_VERSION_MIN(6,0,0)
mode_ = CUDNN_POOLING_MAX_DETERMINISTIC;
#else
mode_ = CUDNN_POOLING_MAX;
#endif
} else if (def().type().substr(0, 11) == "AveragePool") {
mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
} else {
LOG(FATAL) << "Unsupported pooling method: " << def().type();
}
}
~CuDNNPoolOp() {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_));
CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_));
}
template <typename T, typename M>
bool DoRunWithType() {
auto& X = Input(0);
auto* Y = Output(0);
int N = 0, C = 0, H = 0, W = 0, D = 0;
int H_out = 0, W_out = 0, D_out = 0;
// cuDNN pooling support only 2 and 3 spatial dimensions.
CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5);
switch (order_) {
case StorageOrder::NHWC:
N = X.dim32(0);
H = X.dim32(1);
W = X.ndim() > 3 ? X.dim32(2) : 1;
D = X.ndim() > 4 ? X.dim32(3) : 1;
C = X.dim32(X.ndim() - 1);
ConvPoolOpBase::SetOutputSize(X, Y, C);
H_out = Y->dim32(1);
W_out = Y->ndim() > 3 ? Y->dim32(2) : 1;
D_out = Y->ndim() > 4 ? Y->dim32(3) : 1;
break;
case StorageOrder::NCHW:
N = X.dim32(0);
C = X.dim32(1);
H = X.dim32(2);
W = X.ndim() > 3 ? X.dim32(3) : 1;
D = X.ndim() > 4 ? X.dim32(4) : 1;
ConvPoolOpBase::SetOutputSize(X, Y, C);
H_out = Y->dim32(2);
W_out = Y->ndim() > 3 ? Y->dim32(3) : 1;
D_out = Y->ndim() > 4 ? Y->dim32(4) : 1;
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
if (cudnn_input_dims_ != X.dims()) {
// Dimensions changed; we will need to re-initialize things.
VLOG(1) << "Changing the cudnn descriptor configurations.";
cudnn_input_dims_ = X.dims();
setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_);
setTensorDescriptor<T>(
Y->ndim(), order_, N, C, H_out, W_out, D_out, top_desc_);
for (int i = 0; i < kernel_.size(); ++i) {
if (pads_[i] != pads_[kernel_.size() + i]) {
CAFFE_ENFORCE(
legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING,
"Cudnn pooling only supports even padding on both sides, with "
"the only exception of the caffe legacy pooling case where we "
"try to preserve backward compatibility with Caffe.");
}
}
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetPooling2dDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_h(),
kernel_w(),
pad_t(),
pad_l(),
stride_h(),
stride_w()));
} else {
CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_.size(),
kernel_.data(),
pads_.data(),
stride_.data()));
}
}
// Carry out the pooling computation.
CUDNN_ENFORCE(cudnnPoolingForward(
cudnn_wrapper_.inline_cudnn_handle(),
pooling_desc_,
cudnnTypeWrapper<T>::kOne(),
bottom_desc_,
X.template data<T>(),
cudnnTypeWrapper<T>::kZero(),
top_desc_,
Y->template mutable_data<T>()));
return true;
}
bool RunOnDevice() final {
auto& X = Input(0);
auto* Y = Output(0);
if (X.IsType<float>()) {
return DoRunWithType<float,float>();
} else if (X.IsType<float16>()) {
return DoRunWithType<float16,float>();
} else {
LOG(FATAL) << "Unsupported input types";
}
return true;
}
protected:
vector<TIndex> cudnn_input_dims_;
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t bottom_desc_;
cudnnTensorDescriptor_t top_desc_;
cudnnPoolingDescriptor_t pooling_desc_;
cudnnPoolingMode_t mode_;
private:
};
class CuDNNPoolGradientOp : public ConvPoolOpBase<CUDAContext> {
public:
CuDNNPoolGradientOp(const OperatorDef& operator_def, Workspace* ws)
: ConvPoolOpBase<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_) {
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_));
CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_));
// Figure out the pooling descriptor.
if (def().type() == "MaxPoolGradient") {
mode_ = CUDNN_POOLING_MAX;
} else if (def().type() == "AveragePoolGradient") {
mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
} else {
LOG(FATAL) << "Unsupported pooling method: " << def().type();
}
}
~CuDNNPoolGradientOp() {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_));
CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_));
}
template <typename T, typename M>
bool DoRunWithType() {
auto& X = Input(0);
auto& Y = Input(1);
auto& dY = Input(2);
auto* dX = Output(0);
// cuDNN pooling support only 2 and 3 spatial dimensions.
CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5);
dX->ResizeLike(X);
int N = 0, C = 0, H = 0, W = 0, D = 0;
int H_out = 0, W_out = 0, D_out = 0;
switch (order_) {
case StorageOrder::NHWC:
N = X.dim32(0);
H = X.dim32(1);
W = X.ndim() > 3 ? X.dim32(2) : 1;
D = X.ndim() > 4 ? X.dim32(3) : 1;
C = X.dim32(X.ndim() - 1);
H_out = Y.dim32(1);
W_out = Y.ndim() > 3 ? Y.dim32(2) : 1;
D_out = Y.ndim() > 4 ? Y.dim32(3) : 1;
break;
case StorageOrder::NCHW:
N = X.dim32(0);
C = X.dim32(1);
H = X.dim32(2);
W = X.ndim() > 3 ? X.dim32(3) : 1;
D = X.ndim() > 4 ? X.dim32(4) : 1;
H_out = Y.dim32(2);
W_out = Y.ndim() > 3 ? Y.dim32(3) : 1;
D_out = Y.ndim() > 4 ? Y.dim32(4) : 1;
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
if (kernel_.size() == 1) {
ConvPoolOpBase<CUDAContext>::ComputePads({H});
} else if (kernel_.size() == 2) {
ConvPoolOpBase<CUDAContext>::ComputePads({H, W});
} else if (kernel_.size() == 3) {
ConvPoolOpBase<CUDAContext>::ComputePads({H, W, D});
} else {
CAFFE_THROW("Unsupported kernel size :", kernel_.size());
}
if (cudnn_input_dims_ != X.dims()) {
// Dimensions changed; we will need to re-initialize things.
VLOG(1) << "Changing the cudnn descriptor configurations.";
cudnn_input_dims_ = X.dims();
setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_);
setTensorDescriptor<T>(
Y.ndim(), order_, N, C, H_out, W_out, D_out, top_desc_);
if (pad_t() != pad_l() || pad_l() != pad_r()) {
CAFFE_ENFORCE(
legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING,
"Cudnn pooling only supports even padding on both sides, with "
"the only exception of the caffe legacy pooling case where we "
"try to preserve backward compatibility with Caffe.");
}
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetPooling2dDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_h(),
kernel_w(),
pad_t(),
pad_l(),
stride_h(),
stride_w()));
} else {
CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor(
pooling_desc_,
mode_,
CUDNN_NOT_PROPAGATE_NAN,
kernel_.size(),
kernel_.data(),
pads_.data(),
stride_.data()));
}
}
// Carry out the pooling computation.
CUDNN_ENFORCE(cudnnPoolingBackward(
cudnn_wrapper_.inline_cudnn_handle(),
pooling_desc_,
cudnnTypeWrapper<T>::kOne(),
top_desc_,
Y.template data<T>(),
top_desc_,
dY.template data<T>(),
bottom_desc_,
X.template data<T>(),
cudnnTypeWrapper<T>::kZero(),
bottom_desc_,
dX->template mutable_data<T>()));
return true;
}
bool RunOnDevice() final {
auto& X = Input(0);
auto& Y = Input(1);
auto& dY = Input(2);
auto* dX = Output(0);
dX->ResizeLike(X);
if (X.IsType<float>()) {
return DoRunWithType<float,float>();
} else if (X.IsType<float16>()) {
return DoRunWithType<float16,float>();
} else {
LOG(FATAL) << "Unsupported input types";
}
return true;
}
protected:
vector<TIndex> cudnn_input_dims_;
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t bottom_desc_;
cudnnTensorDescriptor_t top_desc_;
cudnnPoolingDescriptor_t pooling_desc_;
cudnnPoolingMode_t mode_;
// Input: X, Y, dY
// Output: dX
INPUT_TAGS(IN, OUT, OUT_GRAD);
};
namespace {
REGISTER_CUDNN_OPERATOR(AveragePool, CuDNNPoolOp);
REGISTER_CUDNN_OPERATOR(AveragePoolGradient, CuDNNPoolGradientOp);
REGISTER_CUDNN_OPERATOR(MaxPool, CuDNNPoolOp);
REGISTER_CUDNN_OPERATOR(MaxPoolGradient, CuDNNPoolGradientOp);
} // namespace
} // namespace caffe2
|
Fix Pooling ND non-symmetric padding check.
|
Fix Pooling ND non-symmetric padding check.
Reviewed By: dutran
Differential Revision: D5270021
fbshipit-source-id: bbad8e9f07af26f7e7522844eb35bf5631883107
|
C++
|
apache-2.0
|
bwasti/caffe2,Yangqing/caffe2,davinwang/caffe2,davinwang/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,sf-wind/caffe2,Yangqing/caffe2,Yangqing/caffe2,Yangqing/caffe2,xzturn/caffe2,pietern/caffe2,pietern/caffe2,pietern/caffe2,xzturn/caffe2,Yangqing/caffe2,davinwang/caffe2,sf-wind/caffe2,sf-wind/caffe2,pietern/caffe2,bwasti/caffe2,caffe2/caffe2,sf-wind/caffe2,bwasti/caffe2,bwasti/caffe2,xzturn/caffe2,xzturn/caffe2,bwasti/caffe2,davinwang/caffe2,xzturn/caffe2
|
87c90ed4b1489d9aba4871a0c833879a0ab09708
|
src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C
|
src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file rcd_load.C
/// @brief Run and manage the RCD_LOAD engine
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/rcd_load.H>
#include <lib/dimm/rcd_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCBIST specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCBIST>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
// A vector of CCS instructions. We'll ask the targets to fill it, and then we'll execute it
ccs::program<TARGET_TYPE_MCBIST> l_program;
for (auto c : i_target.getChildren<TARGET_TYPE_MCS>())
{
for (auto p : c.getChildren<TARGET_TYPE_MCA>())
{
for (auto d : p.getChildren<TARGET_TYPE_DIMM>())
{
FAPI_DBG("rcd load for %s", mss::c_str(d));
FAPI_TRY( perform_rcd_load(d, l_program.iv_instructions) );
}
// We have to configure the CCS engine to let it know which port these instructions are
// going out (or whether it's broadcast ...) so lets execute the instructions we presently
// have so that we kind of do this by port
FAPI_TRY( ccs::execute(i_target, l_program, p) );
}
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - unknown DIMM case
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to (unused)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
// If we're here, we have a problem. The DIMM kind (type and/or generation) wasn't know
// to our dispatcher. We have a DIMM plugged in we don't know how to deal with.
FAPI_ASSERT(false,
fapi2::MSS_UNKNOWN_DIMM()
.set_DIMM_TYPE(l_type)
.set_DRAM_GEN(l_gen)
.set_DIMM_IN_ERROR(i_target),
"Unable to perform rcd load on %s: unknown type (%d) or generation (%d)",
mss::c_str(i_target), l_type, l_gen);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - RDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_RDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting rdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - LRDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_LRDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting lrdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - start the dispatcher
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
return perform_rcd_load_dispatch<FORCE_DISPATCH>(dimm_kind( l_type, l_gen ), i_target, i_inst);
fapi_try_exit:
FAPI_ERR("couldn't get dimm type, dram gen: %s", mss::c_str(i_target));
return fapi2::current_err;
}
} // namespace
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file rcd_load.C
/// @brief Run and manage the RCD_LOAD engine
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/rcd_load.H>
#include <lib/dimm/rcd_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCBIST specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCBIST>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
// A vector of CCS instructions. We'll ask the targets to fill it, and then we'll execute it
ccs::program<TARGET_TYPE_MCBIST> l_program;
// Clear the initial delays. This will force the CCS engine to recompute the delay based on the
// instructions in the CCS instruction vector
l_program.iv_poll.iv_initial_delay = 0;
l_program.iv_poll.iv_initial_sim_delay = 0;
for (auto c : i_target.getChildren<TARGET_TYPE_MCS>())
{
for (auto p : c.getChildren<TARGET_TYPE_MCA>())
{
for (auto d : p.getChildren<TARGET_TYPE_DIMM>())
{
FAPI_DBG("rcd load for %s", mss::c_str(d));
FAPI_TRY( perform_rcd_load(d, l_program.iv_instructions) );
}
// We have to configure the CCS engine to let it know which port these instructions are
// going out (or whether it's broadcast ...) so lets execute the instructions we presently
// have so that we kind of do this by port
FAPI_TRY( ccs::execute(i_target, l_program, p) );
}
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - unknown DIMM case
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to (unused)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
// If we're here, we have a problem. The DIMM kind (type and/or generation) wasn't know
// to our dispatcher. We have a DIMM plugged in we don't know how to deal with.
FAPI_ASSERT(false,
fapi2::MSS_UNKNOWN_DIMM()
.set_DIMM_TYPE(l_type)
.set_DRAM_GEN(l_gen)
.set_DIMM_IN_ERROR(i_target),
"Unable to perform rcd load on %s: unknown type (%d) or generation (%d)",
mss::c_str(i_target), l_type, l_gen);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - RDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_RDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting rdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - LRDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_LRDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting lrdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - start the dispatcher
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
return perform_rcd_load_dispatch<FORCE_DISPATCH>(dimm_kind( l_type, l_gen ), i_target, i_inst);
fapi_try_exit:
FAPI_ERR("couldn't get dimm type, dram gen: %s", mss::c_str(i_target));
return fapi2::current_err;
}
} // namespace
|
Change RCD, MRS polling delays; calculated no longer static
|
Change RCD, MRS polling delays; calculated no longer static
Change-Id: I93a9b1531fac3c767cc06a28cd4789239b49633b
Original-Change-Id: I93eea0b81944402c7070a6a4beec415426461b37
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/29388
Tested-by: Jenkins Server <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: ANDRE A. MARIN <[email protected]>
Reviewed-by: Joseph J. McGill <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
abb8067181c494f3188a7ca97d654edcf6c36fdf
|
include/reflection_experiments/comparisons.hpp
|
include/reflection_experiments/comparisons.hpp
|
#pragma once
#include "meta_utilities.hpp"
#include "refl_utilities.hpp"
namespace reflcompare {
namespace refl = jk::refl_utilities;
namespace metap = jk::metaprogramming;
#if USING_REFLEXPR
namespace meta = std::meta;
#elif USING_CPP3K
namespace meta = cpp3k::meta;
#endif
template<typename T>
bool equal(const T& a, const T& b) {
if constexpr (metap::is_detected<metap::equality_comparable, T>{}) {
return a == b;
} else if constexpr (metap::is_detected<metap::iterable, T>{}) {
bool equals = true;
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); ++i) {
equals &= equal(a[i], b[i]);
}
return equals;
} else {
#if USING_REFLEXPR
using MetaT = reflexpr(T);
static_assert(meta::Record<MetaT>,
"Type contained a member which has no comparison operator defined.");
bool result = true;
meta::for_each<meta::get_data_members_m<MetaT>>(
[&a, &b, &result](auto&& member) {
using MetaMember = typename std::decay_t<decltype(member)>;
constexpr auto p = meta::get_pointer<MetaMember>::value;
result &= equal(a.*p, b.*p);
}
);
return result;
#elif USING_CPP3K
bool result = true;
meta::for_each($T.member_variables(),
[&a, &b, &result](auto&& member){
result &= equal(a.*member.pointer(), b.*member.pointer());
}
);
return result;
#endif
}
}
} // namespace reflcompare
|
#pragma once
#include "meta_utilities.hpp"
#include "refl_utilities.hpp"
namespace reflcompare {
namespace refl = jk::refl_utilities;
namespace metap = jk::metaprogramming;
#if USING_REFLEXPR
namespace meta = std::meta;
#elif USING_CPP3K
namespace meta = cpp3k::meta;
#endif
template<typename T>
bool equal(const T& a, const T& b) {
if constexpr (metap::is_detected<metap::equality_comparable, T>{}) {
return a == b;
} else if constexpr (metap::is_detected<metap::iterable, T>{}) {
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); ++i) {
if (!equal(a[i], b[i])) {
return false;
}
}
return true;
} else {
#if USING_REFLEXPR
using MetaT = reflexpr(T);
static_assert(meta::Record<MetaT>,
"Type contained a member which has no comparison operator defined.");
bool result = true;
meta::for_each<meta::get_data_members_m<MetaT>>(
[&a, &b, &result](auto&& member) {
using MetaMember = typename std::decay_t<decltype(member)>;
constexpr auto p = meta::get_pointer<MetaMember>::value;
result = result && equal(a.*p, b.*p)
}
);
return result;
#elif USING_CPP3K
bool result = true;
meta::for_each($T.member_variables(),
[&a, &b, &result](auto&& member){
result = result && equal(a.*member.pointer(), b.*member.pointer());
}
);
return result;
#endif
}
}
} // namespace reflcompare
|
use && in example because it's safer
|
use && in example because it's safer
|
C++
|
mit
|
jacquelinekay/reflection_experiments
|
77ffa52524ee558cea10578441f579ff9138d0ac
|
include/tao/pegtl/contrib/raise_controller.hpp
|
include/tao/pegtl/contrib/raise_controller.hpp
|
// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_RAISE_CONTROLLER_HPP
#define TAO_PEGTL_CONTRIB_RAISE_CONTROLLER_HPP
#include <type_traits>
#include "../config.hpp"
#include "../normal.hpp"
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Dummy, typename T, typename Rule, typename = void >
struct raise_on_failure
: std::bool_constant< T::template message< Rule > != nullptr >
{};
template< typename Dummy, typename T, typename Rule >
struct raise_on_failure< Dummy, T, Rule, decltype( T::template raise_on_failure< Rule >, void() ) >
: std::bool_constant< T::template raise_on_failure< Rule > >
{};
} // namespace internal
template< typename T, bool RequireMessage = true, template< typename... > class Base = normal >
struct raise_controller
{
template< typename Rule >
struct control
: Base< Rule >
{
template< typename Input, typename... States >
static void failure( const Input& in, States&&... st ) noexcept( !internal::raise_on_failure< Input, T, Rule >::value && noexcept( Base< Rule >::failure( in, st... ) ) )
{
if constexpr( internal::raise_on_failure< Input, T, Rule >::value ) {
raise( in, st... );
}
else {
Base< Rule >::failure( in, st... );
}
}
template< typename Input, typename... States >
static void raise( const Input& in, States&&... st )
{
if constexpr( RequireMessage ) {
static_assert( T::template message< Rule > != nullptr );
}
if constexpr( T::template message< Rule > != nullptr ) {
throw parse_error( T::template message< Rule >, in );
}
else {
Base< Rule >::raise( in, st... );
}
}
};
};
} // namespace TAO_PEGTL_NAMESPACE
#endif
|
// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_RAISE_CONTROLLER_HPP
#define TAO_PEGTL_CONTRIB_RAISE_CONTROLLER_HPP
#include <type_traits>
#include "../config.hpp"
#include "../normal.hpp"
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Dummy, typename T, typename Rule, typename = void >
struct raise_on_failure
: std::bool_constant< T::template message< Rule > != nullptr >
{};
template< typename Dummy, typename T, typename Rule >
struct raise_on_failure< Dummy, T, Rule, decltype( T::template raise_on_failure< Rule >, void() ) >
: std::bool_constant< T::template raise_on_failure< Rule > >
{};
} // namespace internal
template< typename T, bool RequireMessage = true, template< typename... > class Base = normal >
struct raise_controller
{
template< typename Rule >
struct control
: Base< Rule >
{
template< typename Input, typename... States >
static void failure( const Input& in, States&&... st ) noexcept( !internal::raise_on_failure< Input, T, Rule >::value && noexcept( Base< Rule >::failure( in, st... ) ) )
{
if constexpr( internal::raise_on_failure< Input, T, Rule >::value ) {
raise( in, st... );
}
else {
Base< Rule >::failure( in, st... );
}
}
template< typename Input, typename... States >
static void raise( const Input& in, States&&... st )
{
if constexpr( RequireMessage ) {
static_assert( T::template message< Rule > != nullptr );
}
if constexpr( T::template message< Rule > != nullptr ) {
throw parse_error( T::template message< Rule >, in );
#if defined( _MSC_VER )
(void)( (void)st, ... );
#endif
}
else {
Base< Rule >::raise( in, st... );
}
}
};
};
} // namespace TAO_PEGTL_NAMESPACE
#endif
|
Fix MSVC
|
Fix MSVC
|
C++
|
mit
|
ColinH/PEGTL,ColinH/PEGTL
|
308ac876fa92e38b93736386cc23280a3269d565
|
Tutorial/Tutorial4ActorPlugin/Tutorial4ActorModule.cpp
|
Tutorial/Tutorial4ActorPlugin/Tutorial4ActorModule.cpp
|
#include "Tutorial4ActorModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include <thread>
bool HelloWorld4ActorModule::Init()
{
//ʼ
std::cout << "Hello, world4, Init ThreadID: " << std::this_thread::get_id() << std::endl;
return true;
}
int HelloWorld4ActorModule::OnASyncEvent(const NFIDENTID& self, const int event, std::string& arg)
{
//¼ص
std::cout << "Begin OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << std::this_thread::get_id() << std::endl;
arg += " event test ok";
return 0;
}
int HelloWorld4ActorModule::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)
{
//¼ص
std::cout << "End OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << std::this_thread::get_id() << std::endl;
return 0;
}
bool HelloWorld4ActorModule::AfterInit()
{
//ʼ
std::cout << "Hello, world4, AfterInit, ThreadID: " << GetCurrentThreadId() << std::endl;
m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));
//////////////////////////////////////ͬ/////////////////////////////////////////////////////////////////////
m_pEventProcessModule->AddAsyncEventCallBack(NFIDENTID(), 2222, this, &HelloWorld4ActorModule::OnASyncEvent, &HelloWorld4ActorModule::OnSyncEvent);
for (int i = 0; i < 20; ++i)
{
m_pEventProcessModule->DoEvent(NFIDENTID(), 2222, NFCDataList() << boost::lexical_cast<std::string>(i), false);
}
std::cout << "End Test Actor, ThreadID: " << std::this_thread::get_id() << std::endl;
///////////////////////////////////////////////////////////////////////////////////////////////////////////
return true;
}
bool HelloWorld4ActorModule::Execute( const float fLasFrametime, const float fStartedTime )
{
//ÿִ֡
//std::cout << "Hello, world3, Execute" << std::endl;
return true;
}
bool HelloWorld4ActorModule::BeforeShut()
{
//ʼ֮ǰ
std::cout << "Hello, world4, BeforeShut" << std::endl;
m_pKernelModule->DestroyAll();
return true;
}
bool HelloWorld4ActorModule::Shut()
{
//ʼ
std::cout << "Hello, world4, Shut" << std::endl;
return true;
}
|
#include "Tutorial4ActorModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include <thread>
bool HelloWorld4ActorModule::Init()
{
//ʼ
std::cout << "Hello, world4, Init ThreadID: " << std::this_thread::get_id() << std::endl;
return true;
}
int HelloWorld4ActorModule::OnASyncEvent(const NFIDENTID& self, const int event, std::string& arg)
{
//¼ص
std::cout << "Begin OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << std::this_thread::get_id() << std::endl;
arg += " event test ok";
return 0;
}
int HelloWorld4ActorModule::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)
{
//¼ص
std::cout << "End OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << std::this_thread::get_id() << std::endl;
return 0;
}
bool HelloWorld4ActorModule::AfterInit()
{
//ʼ
std::cout << "Hello, world4, AfterInit, ThreadID: " << std::this_thread::get_id() << std::endl;
m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));
//////////////////////////////////////ͬ/////////////////////////////////////////////////////////////////////
m_pEventProcessModule->AddAsyncEventCallBack(NFIDENTID(), 2222, this, &HelloWorld4ActorModule::OnASyncEvent, &HelloWorld4ActorModule::OnSyncEvent);
for (int i = 0; i < 20; ++i)
{
m_pEventProcessModule->DoEvent(NFIDENTID(), 2222, NFCDataList() << boost::lexical_cast<std::string>(i), false);
}
std::cout << "End Test Actor, ThreadID: " << std::this_thread::get_id() << std::endl;
///////////////////////////////////////////////////////////////////////////////////////////////////////////
return true;
}
bool HelloWorld4ActorModule::Execute( const float fLasFrametime, const float fStartedTime )
{
//ÿִ֡
//std::cout << "Hello, world3, Execute" << std::endl;
return true;
}
bool HelloWorld4ActorModule::BeforeShut()
{
//ʼ֮ǰ
std::cout << "Hello, world4, BeforeShut" << std::endl;
m_pKernelModule->DestroyAll();
return true;
}
bool HelloWorld4ActorModule::Shut()
{
//ʼ
std::cout << "Hello, world4, Shut" << std::endl;
return true;
}
|
modify GetCurrentThreadID() as std::this_thread::get_id()
|
modify GetCurrentThreadID() as std::this_thread::get_id()
|
C++
|
apache-2.0
|
zh423328/NFServer,zh423328/NFServer,xinst/NoahGameFrame,xinst/NoahGameFrame,zh423328/NFServer,xinst/NoahGameFrame,zh423328/NFServer,xinst/NoahGameFrame,zh423328/NFServer,xinst/NoahGameFrame,xinst/NoahGameFrame,zh423328/NFServer,xinst/NoahGameFrame,xinst/NoahGameFrame,zh423328/NFServer,zh423328/NFServer,xinst/NoahGameFrame
|
cdd0b4e13133a34690aa0483cf97859078b2d85b
|
test/test_file_storage.cpp
|
test/test_file_storage.cpp
|
/*
Copyright (c) 2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/file_storage.hpp"
using namespace libtorrent;
void setup_test_storage(file_storage& st)
{
st.add_file("test/a", 10000);
st.add_file("test/b", 20000);
st.add_file("test/c/a", 30000);
st.add_file("test/c/b", 40000);
st.set_piece_length(0x4000);
st.set_num_pieces((st.total_size() + st.piece_length() - 1) / 0x4000);
TEST_EQUAL(st.file_name(0), "a");
TEST_EQUAL(st.file_name(1), "b");
TEST_EQUAL(st.file_name(2), "a");
TEST_EQUAL(st.file_name(3), "b");
TEST_EQUAL(st.name(), "test");
TEST_EQUAL(st.file_path(0), "test/a");
TEST_EQUAL(st.file_path(1), "test/b");
TEST_EQUAL(st.file_path(2), "test/c/a");
TEST_EQUAL(st.file_path(3), "test/c/b");
TEST_EQUAL(st.file_size(0), 10000);
TEST_EQUAL(st.file_size(1), 20000);
TEST_EQUAL(st.file_size(2), 30000);
TEST_EQUAL(st.file_size(3), 40000);
TEST_EQUAL(st.file_offset(0), 0);
TEST_EQUAL(st.file_offset(1), 10000);
TEST_EQUAL(st.file_offset(2), 30000);
TEST_EQUAL(st.file_offset(3), 60000);
TEST_EQUAL(st.total_size(), 100000);
TEST_EQUAL(st.piece_length(), 0x4000);
printf("%d\n", st.num_pieces());
TEST_EQUAL(st.num_pieces(), (100000 + 0x3fff) / 0x4000);
}
int test_main()
{
{
file_storage st;
setup_test_storage(st);
st.rename_file(0, "test/c/d");
TEST_EQUAL(st.file_path(0, "./"), "./test/c/d");
#ifdef TORRENT_WINDOWS
st.rename_file(0, "c:\\tmp\\a");
TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
st.rename_file(0, "/tmp/a");
TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
}
{
file_storage st;
st.add_file("a", 10000);
st.rename_file(0, "test/c/d");
TEST_EQUAL(st.file_path(0, "./"), "./test/c/d");
#ifdef TORRENT_WINDOWS
st.rename_file(0, "c:\\tmp\\a");
TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
st.rename_file(0, "/tmp/a");
TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
}
{
file_storage fs;
fs.set_piece_length(512);
fs.add_file(combine_path("temp_storage", "test1.tmp"), 17);
fs.add_file(combine_path("temp_storage", "test2.tmp"), 612);
fs.add_file(combine_path("temp_storage", "test3.tmp"), 0);
fs.add_file(combine_path("temp_storage", "test4.tmp"), 0);
fs.add_file(combine_path("temp_storage", "test5.tmp"), 3253);
// size: 3882
fs.add_file(combine_path("temp_storage", "test6.tmp"), 841);
// size: 4723
peer_request rq = fs.map_file(0, 0, 10);
TEST_EQUAL(rq.piece, 0);
TEST_EQUAL(rq.start, 0);
TEST_EQUAL(rq.length, 10);
rq = fs.map_file(5, 0, 10);
TEST_EQUAL(rq.piece, 7);
TEST_EQUAL(rq.start, 298);
TEST_EQUAL(rq.length, 10);
rq = fs.map_file(5, 0, 1000);
TEST_EQUAL(rq.piece, 7);
TEST_EQUAL(rq.start, 298);
TEST_EQUAL(rq.length, 841);
}
return 0;
}
|
/*
Copyright (c) 2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/file_storage.hpp"
using namespace libtorrent;
void setup_test_storage(file_storage& st)
{
st.add_file("test/a", 10000);
st.add_file("test/b", 20000);
st.add_file("test/c/a", 30000);
st.add_file("test/c/b", 40000);
st.set_piece_length(0x4000);
st.set_num_pieces((st.total_size() + st.piece_length() - 1) / 0x4000);
TEST_EQUAL(st.file_name(0), "a");
TEST_EQUAL(st.file_name(1), "b");
TEST_EQUAL(st.file_name(2), "a");
TEST_EQUAL(st.file_name(3), "b");
TEST_EQUAL(st.name(), "test");
TEST_EQUAL(st.file_path(0), combine_path("test", "a"));
TEST_EQUAL(st.file_path(1), combine_path("test", "b"));
TEST_EQUAL(st.file_path(2), combine_path("test", combine_path("c", "a")));
TEST_EQUAL(st.file_path(3), combine_path("test", combine_path("c", "b")));
TEST_EQUAL(st.file_size(0), 10000);
TEST_EQUAL(st.file_size(1), 20000);
TEST_EQUAL(st.file_size(2), 30000);
TEST_EQUAL(st.file_size(3), 40000);
TEST_EQUAL(st.file_offset(0), 0);
TEST_EQUAL(st.file_offset(1), 10000);
TEST_EQUAL(st.file_offset(2), 30000);
TEST_EQUAL(st.file_offset(3), 60000);
TEST_EQUAL(st.total_size(), 100000);
TEST_EQUAL(st.piece_length(), 0x4000);
printf("%d\n", st.num_pieces());
TEST_EQUAL(st.num_pieces(), (100000 + 0x3fff) / 0x4000);
}
int test_main()
{
{
file_storage st;
setup_test_storage(st);
st.rename_file(0, combine_path("test", combine_path("c", "d")));
TEST_EQUAL(st.file_path(0, "."), combine_path(".", combine_path("test", combine_path("c", "d"))));
#ifdef TORRENT_WINDOWS
st.rename_file(0, "c:\\tmp\\a");
TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
st.rename_file(0, "/tmp/a");
TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
}
{
file_storage st;
st.add_file("a", 10000);
st.rename_file(0, combine_path("test", combine_path("c", "d")));
TEST_EQUAL(st.file_path(0, "."), combine_path(".", combine_path("test", combine_path("c", "d"))));
#ifdef TORRENT_WINDOWS
st.rename_file(0, "c:\\tmp\\a");
TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
st.rename_file(0, "/tmp/a");
TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
}
{
file_storage fs;
fs.set_piece_length(512);
fs.add_file(combine_path("temp_storage", "test1.tmp"), 17);
fs.add_file(combine_path("temp_storage", "test2.tmp"), 612);
fs.add_file(combine_path("temp_storage", "test3.tmp"), 0);
fs.add_file(combine_path("temp_storage", "test4.tmp"), 0);
fs.add_file(combine_path("temp_storage", "test5.tmp"), 3253);
// size: 3882
fs.add_file(combine_path("temp_storage", "test6.tmp"), 841);
// size: 4723
peer_request rq = fs.map_file(0, 0, 10);
TEST_EQUAL(rq.piece, 0);
TEST_EQUAL(rq.start, 0);
TEST_EQUAL(rq.length, 10);
rq = fs.map_file(5, 0, 10);
TEST_EQUAL(rq.piece, 7);
TEST_EQUAL(rq.start, 298);
TEST_EQUAL(rq.length, 10);
rq = fs.map_file(5, 0, 1000);
TEST_EQUAL(rq.piece, 7);
TEST_EQUAL(rq.start, 298);
TEST_EQUAL(rq.length, 841);
}
return 0;
}
|
fix windows build of test_file_storage
|
fix windows build of test_file_storage
git-svn-id: 4f0141143c3c635d33f1b9f02fcb2b6c73e45c89@8667 a83610d8-ad2a-0410-a6ab-fc0612d85776
|
C++
|
bsd-3-clause
|
svn2github/libtorrent-rasterbar-trunk,dpolishuk/libtorrent,svn2github/libtorrent-rasterbar-trunk,dpolishuk/libtorrent,dpolishuk/libtorrent,dpolishuk/libtorrent,dpolishuk/libtorrent,dpolishuk/libtorrent,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk
|
4d5d4b7e7182d01fe5870db5af4c32c8bf31a3aa
|
test/unit/test_mrn_sys.cpp
|
test/unit/test_mrn_sys.cpp
|
/* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2010 Tetsuro IKEDA
Copyright(C) 2011-2012 Kouhei Sutou <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <string.h>
#include <cppcutter.h>
#include <mrn_sys.h>
static grn_ctx *ctx;
static grn_obj *db;
static grn_hash *hash;
static grn_obj buffer;
namespace test_mrn_sys
{
void cut_startup()
{
ctx = (grn_ctx *)malloc(sizeof(grn_ctx));
grn_init();
grn_ctx_init(ctx, 0);
db = grn_db_create(ctx, NULL, NULL);
grn_ctx_use(ctx, db);
}
void cut_shutdown()
{
grn_obj_unlink(ctx, db);
grn_ctx_fin(ctx);
grn_fin();
free(ctx);
}
void cut_setup()
{
hash = grn_hash_create(ctx, NULL, 1024, sizeof(grn_obj *),
GRN_OBJ_KEY_VAR_SIZE);
GRN_TEXT_INIT(&buffer, 0);
}
void cut_teardown()
{
grn_hash_close(ctx, hash);
grn_obj_unlink(ctx, &buffer);
}
void test_mrn_hash_put()
{
const char *key = "mroonga";
cut_assert_equal_int(0, mrn_hash_put(ctx, hash, key, &buffer));
cut_assert_equal_int(-1, mrn_hash_put(ctx, hash, key, &buffer));
}
void test_mrn_hash_get()
{
const char *key = "mroonga";
const char *value = "A storage engine based on groonga.";
grn_obj *result;
GRN_TEXT_SETS(ctx, &buffer, value);
GRN_TEXT_PUT(ctx, &buffer, "\0", 1);
mrn_hash_put(ctx, hash, key, &buffer);
cut_assert_equal_int(0, mrn_hash_get(ctx, hash, key, &result));
cut_assert_equal_string(value, GRN_TEXT_VALUE(&buffer));
}
void test_mrn_hash_remove()
{
const char *key = "mroonga";
mrn_hash_put(ctx, hash, key, &buffer);
cut_assert_equal_int(-1, mrn_hash_remove(ctx, hash, "nonexistent"));
cut_assert_equal_int(0, mrn_hash_remove(ctx, hash, key));
cut_assert_equal_int(-1, mrn_hash_remove(ctx, hash, key));
}
void test_mrn_table_name_gen()
{
char buf[64];
const char *arg1 = "./hoge/fuga";
const char *arg2 = "./foobar/mysql";
const char *arg3 = "./d/b";
const char *arg4 = "./d/_b";
cut_assert_equal_string("fuga", mrn_table_name_gen(arg1, buf));
cut_assert_equal_string("mysql", mrn_table_name_gen(arg2, buf));
cut_assert_equal_string("b", mrn_table_name_gen(arg3, buf));
cut_assert_equal_string("@005fb", mrn_table_name_gen(arg4, buf));
}
void test_mrn_index_table_name_gen()
{
char buf[64], buf2[64];
const char *arg = "./db/users";
mrn_table_name_gen(arg, buf);
cut_assert_equal_string("users-name",
mrn_index_table_name_gen(buf, "name", buf2));
}
}
|
/* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2010 Tetsuro IKEDA
Copyright(C) 2011-2012 Kouhei Sutou <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <string.h>
#include <cppcutter.h>
#include <mrn_sys.h>
static grn_ctx *ctx;
static grn_obj *db;
static grn_hash *hash;
static grn_obj buffer;
namespace test_mrn_sys
{
void cut_startup()
{
ctx = (grn_ctx *)malloc(sizeof(grn_ctx));
grn_init();
grn_ctx_init(ctx, 0);
db = grn_db_create(ctx, NULL, NULL);
grn_ctx_use(ctx, db);
}
void cut_shutdown()
{
grn_obj_unlink(ctx, db);
grn_ctx_fin(ctx);
grn_fin();
free(ctx);
}
void cut_setup()
{
hash = grn_hash_create(ctx, NULL, 1024, sizeof(grn_obj *),
GRN_OBJ_KEY_VAR_SIZE);
GRN_TEXT_INIT(&buffer, 0);
}
void cut_teardown()
{
grn_hash_close(ctx, hash);
grn_obj_unlink(ctx, &buffer);
}
void test_mrn_hash_put()
{
const char *key = "mroonga";
cut_assert_equal_int(0, mrn_hash_put(ctx, hash, key, &buffer));
cut_assert_equal_int(-1, mrn_hash_put(ctx, hash, key, &buffer));
}
void test_mrn_hash_get()
{
const char *key = "mroonga";
const char *value = "A storage engine based on groonga.";
grn_obj *result;
GRN_TEXT_SETS(ctx, &buffer, value);
GRN_TEXT_PUT(ctx, &buffer, "\0", 1);
mrn_hash_put(ctx, hash, key, &buffer);
cut_assert_equal_int(0, mrn_hash_get(ctx, hash, key, &result));
cut_assert_equal_string(value, GRN_TEXT_VALUE(&buffer));
}
void test_mrn_hash_remove()
{
const char *key = "mroonga";
mrn_hash_put(ctx, hash, key, &buffer);
cut_assert_equal_int(-1, mrn_hash_remove(ctx, hash, "nonexistent"));
cut_assert_equal_int(0, mrn_hash_remove(ctx, hash, key));
cut_assert_equal_int(-1, mrn_hash_remove(ctx, hash, key));
}
void test_mrn_table_name_gen()
{
char buf[64];
const char *arg1 = "./hoge/fuga";
const char *arg2 = "./foobar/mysql";
const char *arg3 = "./d/b";
const char *arg4 = "./d/_b";
cut_assert_equal_string("fuga", mrn_table_name_gen(arg1, buf));
cut_assert_equal_string("mysql", mrn_table_name_gen(arg2, buf));
cut_assert_equal_string("b", mrn_table_name_gen(arg3, buf));
cut_assert_equal_string("@005fb", mrn_table_name_gen(arg4, buf));
}
void test_mrn_table_name_gen_for_mysql()
{
char buf[64];
const char *arg1 = "./hoge/fuga";
const char *arg2 = "./foobar/mysql";
const char *arg3 = "./d/b";
const char *arg4 = "./d/_b";
cut_assert_equal_string("fuga", mrn_table_name_gen_for_mysql(arg1, buf));
cut_assert_equal_string("mysql", mrn_table_name_gen_for_mysql(arg2, buf));
cut_assert_equal_string("b", mrn_table_name_gen_for_mysql(arg3, buf));
cut_assert_equal_string("_b", mrn_table_name_gen_for_mysql(arg4, buf));
}
void test_mrn_index_table_name_gen()
{
char buf[64], buf2[64];
const char *arg = "./db/users";
mrn_table_name_gen(arg, buf);
cut_assert_equal_string("users-name",
mrn_index_table_name_gen(buf, "name", buf2));
}
}
|
add a test for table name starts with '_' case
|
test: add a test for table name starts with '_' case
For MySQL table name version.
|
C++
|
lgpl-2.1
|
naoa/mroonga,yoku0825/mroonga,mroonga/mroonga,mroonga/mroonga,mroonga/mroonga,yoku0825/mroonga,yoku0825/mroonga,yoku0825/mroonga,naoa/mroonga,naoa/mroonga,yoku0825/mroonga,yoku0825/mroonga,naoa/mroonga,naoa/mroonga,mroonga/mroonga,naoa/mroonga
|
15666e6a0a85f1aeb84a2ada0151c8bd5829753a
|
folly/experimental/observer/detail/ObserverManager.cpp
|
folly/experimental/observer/detail/ObserverManager.cpp
|
/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/experimental/observer/detail/ObserverManager.h>
#include <future>
#include <folly/ExceptionString.h>
#include <folly/Format.h>
#include <folly/MPMCQueue.h>
#include <folly/Range.h>
#include <folly/Singleton.h>
#include <folly/portability/GFlags.h>
#include <folly/system/ThreadName.h>
namespace folly {
namespace observer_detail {
FOLLY_TLS bool ObserverManager::inManagerThread_{false};
FOLLY_TLS ObserverManager::DependencyRecorder::Dependencies*
ObserverManager::DependencyRecorder::currentDependencies_{nullptr};
DEFINE_int32(
observer_manager_pool_size,
4,
"How many internal threads ObserverManager should use");
static constexpr StringPiece kObserverManagerThreadNamePrefix{"ObserverMngr"};
namespace {
constexpr size_t kCurrentQueueSize{10 * 1024};
constexpr size_t kNextQueueSize{10 * 1024};
} // namespace
class ObserverManager::CurrentQueue {
public:
CurrentQueue() : queue_(kCurrentQueueSize) {
if (FLAGS_observer_manager_pool_size < 1) {
LOG(ERROR) << "--observer_manager_pool_size should be >= 1";
FLAGS_observer_manager_pool_size = 1;
}
for (int32_t i = 0; i < FLAGS_observer_manager_pool_size; ++i) {
threads_.emplace_back([this, i]() {
folly::setThreadName(
folly::sformat("{}{}", kObserverManagerThreadNamePrefix, i));
ObserverManager::inManagerThread_ = true;
while (true) {
Function<void()> task;
queue_.blockingRead(task);
if (!task) {
return;
}
try {
task();
} catch (...) {
LOG(ERROR) << "Exception while running CurrentQueue task: "
<< exceptionStr(std::current_exception());
}
}
});
}
}
~CurrentQueue() {
for (size_t i = 0; i < threads_.size(); ++i) {
queue_.blockingWrite(nullptr);
}
for (auto& thread : threads_) {
thread.join();
}
CHECK(queue_.isEmpty());
}
void add(Function<void()> task) {
if (ObserverManager::inManagerThread()) {
if (!queue_.write(std::move(task))) {
throw std::runtime_error("Too many Observers scheduled for update.");
}
} else {
queue_.blockingWrite(std::move(task));
}
}
private:
MPMCQueue<Function<void()>> queue_;
std::vector<std::thread> threads_;
};
class ObserverManager::NextQueue {
public:
explicit NextQueue(ObserverManager& manager)
: manager_(manager), queue_(kNextQueueSize) {
thread_ = std::thread([&]() {
Core::WeakPtr queueCoreWeak;
while (true) {
queue_.blockingRead(queueCoreWeak);
if (stop_) {
return;
}
std::vector<Core::Ptr> cores;
{
if (auto queueCore = queueCoreWeak.lock()) {
cores.emplace_back(std::move(queueCore));
}
}
{
SharedMutexReadPriority::WriteHolder wh(manager_.versionMutex_);
// We can't pick more tasks from the queue after we bumped the
// version, so we have to do this while holding the lock.
while (cores.size() < kNextQueueSize && queue_.read(queueCoreWeak)) {
if (stop_) {
return;
}
if (auto queueCore = queueCoreWeak.lock()) {
cores.emplace_back(std::move(queueCore));
}
}
for (auto& corePtr : cores) {
corePtr->setForceRefresh();
}
++manager_.version_;
}
for (auto& core : cores) {
manager_.scheduleRefresh(std::move(core), manager_.version_);
}
{
auto wEmptyWaiters = emptyWaiters_.wlock();
// We don't want any new waiters to be added while we are checking the
// queue.
if (queue_.isEmpty()) {
for (auto& promise : *wEmptyWaiters) {
promise.set_value();
}
wEmptyWaiters->clear();
}
}
}
});
}
void add(Core::WeakPtr core) {
queue_.blockingWrite(std::move(core));
}
~NextQueue() {
stop_ = true;
// Write to the queue to notify the thread.
queue_.blockingWrite(Core::WeakPtr());
thread_.join();
}
void waitForEmpty() {
std::promise<void> promise;
auto future = promise.get_future();
emptyWaiters_.wlock()->push_back(std::move(promise));
// Write to the queue to notify the thread.
queue_.blockingWrite(Core::WeakPtr());
future.get();
}
private:
ObserverManager& manager_;
MPMCQueue<Core::WeakPtr> queue_;
std::thread thread_;
std::atomic<bool> stop_{false};
folly::Synchronized<std::vector<std::promise<void>>> emptyWaiters_;
};
ObserverManager::ObserverManager() {
currentQueue_ = std::make_unique<CurrentQueue>();
nextQueue_ = std::make_unique<NextQueue>(*this);
}
ObserverManager::~ObserverManager() {
// Destroy NextQueue, before the rest of this object, since it expects
// ObserverManager to be alive.
nextQueue_.reset();
currentQueue_.reset();
}
void ObserverManager::scheduleCurrent(Function<void()> task) {
currentQueue_->add(std::move(task));
}
void ObserverManager::scheduleNext(Core::WeakPtr core) {
nextQueue_->add(std::move(core));
}
void ObserverManager::waitForAllUpdates() {
auto instance = getInstance();
if (!instance) {
return;
}
instance->nextQueue_->waitForEmpty();
// Wait for all readers to release the lock.
SharedMutexReadPriority::WriteHolder wh(instance->versionMutex_);
}
struct ObserverManager::Singleton {
static folly::Singleton<ObserverManager> instance;
// MSVC 2015 doesn't let us access ObserverManager's constructor if we
// try to use a lambda to initialize instance, so we have to create
// an actual function instead.
static ObserverManager* createManager() {
return new ObserverManager();
}
};
folly::Singleton<ObserverManager> ObserverManager::Singleton::instance(
createManager);
std::shared_ptr<ObserverManager> ObserverManager::getInstance() {
return Singleton::instance.try_get();
}
} // namespace observer_detail
} // namespace folly
|
/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/experimental/observer/detail/ObserverManager.h>
#include <future>
#include <folly/ExceptionString.h>
#include <folly/Format.h>
#include <folly/Range.h>
#include <folly/Singleton.h>
#include <folly/concurrency/UnboundedQueue.h>
#include <folly/portability/GFlags.h>
#include <folly/system/ThreadName.h>
namespace folly {
namespace observer_detail {
FOLLY_TLS bool ObserverManager::inManagerThread_{false};
FOLLY_TLS ObserverManager::DependencyRecorder::Dependencies*
ObserverManager::DependencyRecorder::currentDependencies_{nullptr};
DEFINE_int32(
observer_manager_pool_size,
4,
"How many internal threads ObserverManager should use");
namespace {
constexpr StringPiece kObserverManagerThreadNamePrefix{"ObserverMngr"};
constexpr size_t kNextBatchSize{1024};
} // namespace
class ObserverManager::CurrentQueue {
public:
CurrentQueue() {
if (FLAGS_observer_manager_pool_size < 1) {
LOG(ERROR) << "--observer_manager_pool_size should be >= 1";
FLAGS_observer_manager_pool_size = 1;
}
for (int32_t i = 0; i < FLAGS_observer_manager_pool_size; ++i) {
threads_.emplace_back([this, i]() {
folly::setThreadName(
folly::sformat("{}{}", kObserverManagerThreadNamePrefix, i));
ObserverManager::inManagerThread_ = true;
while (true) {
Function<void()> task;
queue_.dequeue(task);
if (!task) {
return;
}
try {
task();
} catch (...) {
LOG(ERROR) << "Exception while running CurrentQueue task: "
<< exceptionStr(std::current_exception());
}
}
});
}
}
~CurrentQueue() {
for (size_t i = 0; i < threads_.size(); ++i) {
queue_.enqueue(nullptr);
}
for (auto& thread : threads_) {
thread.join();
}
CHECK(queue_.empty());
}
void add(Function<void()> task) {
queue_.enqueue(std::move(task));
}
private:
UMPMCQueue<Function<void()>, true> queue_;
std::vector<std::thread> threads_;
};
class ObserverManager::NextQueue {
public:
explicit NextQueue(ObserverManager& manager) : manager_(manager) {
thread_ = std::thread([&]() {
Core::WeakPtr queueCoreWeak;
while (true) {
queue_.dequeue(queueCoreWeak);
if (stop_) {
return;
}
std::vector<Core::Ptr> cores;
{
if (auto queueCore = queueCoreWeak.lock()) {
cores.emplace_back(std::move(queueCore));
}
}
{
SharedMutexReadPriority::WriteHolder wh(manager_.versionMutex_);
// We can't pick more tasks from the queue after we bumped the
// version, so we have to do this while holding the lock.
while (cores.size() < kNextBatchSize &&
queue_.try_dequeue(queueCoreWeak)) {
if (stop_) {
return;
}
if (auto queueCore = queueCoreWeak.lock()) {
cores.emplace_back(std::move(queueCore));
}
}
for (auto& corePtr : cores) {
corePtr->setForceRefresh();
}
++manager_.version_;
}
for (auto& core : cores) {
manager_.scheduleRefresh(std::move(core), manager_.version_);
}
{
auto wEmptyWaiters = emptyWaiters_.wlock();
// We don't want any new waiters to be added while we are checking the
// queue.
if (queue_.empty()) {
for (auto& promise : *wEmptyWaiters) {
promise.set_value();
}
wEmptyWaiters->clear();
}
}
}
});
}
void add(Core::WeakPtr core) {
queue_.enqueue(std::move(core));
}
~NextQueue() {
stop_ = true;
// Write to the queue to notify the thread.
queue_.enqueue(Core::WeakPtr());
thread_.join();
}
void waitForEmpty() {
std::promise<void> promise;
auto future = promise.get_future();
emptyWaiters_.wlock()->push_back(std::move(promise));
// Write to the queue to notify the thread.
queue_.enqueue(Core::WeakPtr());
future.get();
}
private:
ObserverManager& manager_;
UMPSCQueue<Core::WeakPtr, true> queue_;
std::thread thread_;
std::atomic<bool> stop_{false};
folly::Synchronized<std::vector<std::promise<void>>> emptyWaiters_;
};
ObserverManager::ObserverManager() {
currentQueue_ = std::make_unique<CurrentQueue>();
nextQueue_ = std::make_unique<NextQueue>(*this);
}
ObserverManager::~ObserverManager() {
// Destroy NextQueue, before the rest of this object, since it expects
// ObserverManager to be alive.
nextQueue_.reset();
currentQueue_.reset();
}
void ObserverManager::scheduleCurrent(Function<void()> task) {
currentQueue_->add(std::move(task));
}
void ObserverManager::scheduleNext(Core::WeakPtr core) {
nextQueue_->add(std::move(core));
}
void ObserverManager::waitForAllUpdates() {
auto instance = getInstance();
if (!instance) {
return;
}
instance->nextQueue_->waitForEmpty();
// Wait for all readers to release the lock.
SharedMutexReadPriority::WriteHolder wh(instance->versionMutex_);
}
struct ObserverManager::Singleton {
static folly::Singleton<ObserverManager> instance;
// MSVC 2015 doesn't let us access ObserverManager's constructor if we
// try to use a lambda to initialize instance, so we have to create
// an actual function instead.
static ObserverManager* createManager() {
return new ObserverManager();
}
};
folly::Singleton<ObserverManager> ObserverManager::Singleton::instance(
createManager);
std::shared_ptr<ObserverManager> ObserverManager::getInstance() {
return Singleton::instance.try_get();
}
} // namespace observer_detail
} // namespace folly
|
Use unbounded queues
|
Use unbounded queues
Summary: There's no way we can size such queues appropriately.
Reviewed By: yfeldblum
Differential Revision: D15271382
fbshipit-source-id: 7d8c5b0a3faffac3e86cb87fa18d0597facc3189
|
C++
|
apache-2.0
|
facebook/folly,facebook/folly,facebook/folly,facebook/folly,facebook/folly
|
5929d5d5e57f42ea9d1a4782f97dc1cc6036dd04
|
libcaf_core/caf/expected.hpp
|
libcaf_core/caf/expected.hpp
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_EXPECTED_HPP
#define CAF_EXPECTED_HPP
#include "caf/config.hpp"
#include <new>
#include <memory>
#include <ostream>
#include <type_traits>
#include "caf/unit.hpp"
#include "caf/error.hpp"
#include "caf/unifyn.hpp"
namespace caf {
/// Represents the result of a computation which can either complete
/// successfully with an instance of type `T` or fail with an `error`.
/// @tparam T The type of the result.
template <typename T>
class expected {
public:
// -- member types -----------------------------------------------------------
using value_type = T;
// -- static member variables ------------------------------------------------
/// Stores whether move construct and move assign never throw.
static constexpr bool nothrow_move
= std::is_nothrow_move_constructible<T>::value
&& std::is_nothrow_move_assignable<T>::value;
/// Stores whether copy construct and copy assign never throw.
static constexpr bool nothrow_copy
= std::is_nothrow_copy_constructible<T>::value
&& std::is_nothrow_copy_assignable<T>::value;
// -- constructors, destructors, and assignment operators --------------------
template <class U>
expected(U x,
typename std::enable_if<std::is_convertible<U, T>::value>::type* = 0)
: engaged_(true) {
new (&value_) T(std::move(x));
}
expected(T&& x) noexcept(nothrow_move) : engaged_(true) {
new (&value_) T(std::move(x));
}
expected(const T& x) noexcept(nothrow_copy) : engaged_(true) {
new (&value_) T(x);
}
expected(caf::error e) noexcept : engaged_(false) {
new (&error_) caf::error{std::move(e)};
}
expected(const expected& other) noexcept(nothrow_copy) {
construct(other);
}
template <class Code, class E = enable_if_has_make_error_t<Code>>
expected(Code code) : engaged_(false) {
new (&error_) caf::error(make_error(code));
}
expected(expected&& other) noexcept(nothrow_move) {
construct(std::move(other));
}
~expected() {
destroy();
}
expected& operator=(const expected& other) noexcept(nothrow_copy) {
if (engaged_ && other.engaged_)
value_ = other.value_;
else if (!engaged_ && !other.engaged_)
error_ = other.error_;
else {
destroy();
construct(other);
}
return *this;
}
expected& operator=(expected&& other) noexcept(nothrow_move) {
if (engaged_ && other.engaged_)
value_ = std::move(other.value_);
else if (!engaged_ && !other.engaged_)
error_ = std::move(other.error_);
else {
destroy();
construct(std::move(other));
}
return *this;
}
expected& operator=(const T& x) noexcept(nothrow_copy) {
if (engaged_) {
value_ = x;
} else {
destroy();
engaged_ = true;
new (&value_) T(x);
}
return *this;
}
expected& operator=(T&& x) noexcept(nothrow_move) {
if (engaged_) {
value_ = std::move(x);
} else {
destroy();
engaged_ = true;
new (&value_) T(std::move(x));
}
return *this;
}
template <class U>
typename std::enable_if<std::is_convertible<U, T>::value, expected&>::type
operator=(U x) {
return *this = T{std::move(x)};
}
expected& operator=(caf::error e) noexcept {
if (!engaged_)
error_ = std::move(e);
else {
destroy();
engaged_ = false;
new (&value_) caf::error(std::move(e));
}
return *this;
}
template <class Code>
enable_if_has_make_error_t<Code, expected&> operator=(Code code) {
return *this = make_error(code);
}
// -- modifiers --------------------------------------------------------------
/// @copydoc cvalue
T& value() noexcept {
CAF_ASSERT(engaged_);
return value_;
}
/// @copydoc cvalue
T& operator*() noexcept {
return value();
}
/// @copydoc cvalue
T* operator->() noexcept {
return &value();
}
/// @copydoc cerror
caf::error& error() noexcept {
CAF_ASSERT(!engaged_);
return error_;
}
// -- observers --------------------------------------------------------------
/// Returns the contained value.
/// @pre `engaged() == true`.
const T& cvalue() const noexcept {
CAF_ASSERT(engaged_);
return value_;
}
/// @copydoc cvalue
const T& value() const noexcept {
CAF_ASSERT(engaged_);
return value_;
}
/// @copydoc cvalue
const T& operator*() const noexcept {
return value();
}
/// @copydoc cvalue
const T* operator->() const noexcept {
return &value();
}
/// @copydoc engaged
explicit operator bool() const noexcept {
return engaged();
}
/// Returns `true` if the object holds a value (is engaged).
bool engaged() const noexcept {
return engaged_;
}
/// Returns the contained error.
/// @pre `engaged() == false`.
const caf::error& cerror() const noexcept {
CAF_ASSERT(!engaged_);
return error_;
}
/// @copydoc cerror
const caf::error& error() const noexcept {
CAF_ASSERT(!engaged_);
return error_;
}
private:
void construct(expected&& other) noexcept(nothrow_move) {
if (other.engaged_)
new (&value_) T(std::move(other.value_));
else
new (&error_) caf::error(std::move(other.error_));
engaged_ = other.engaged_;
}
void construct(const expected& other) noexcept(nothrow_copy) {
if (other.engaged_)
new (&value_) T(other.value_);
else
new (&error_) caf::error(other.error_);
engaged_ = other.engaged_;
}
void destroy() {
if (engaged_)
value_.~T();
else
error_.~error();
}
bool engaged_;
union {
T value_;
caf::error error_;
};
};
/// @relates expected
template <class T>
auto operator==(const expected<T>& x, const expected<T>& y)
-> decltype(*x == *y) {
return x && y ? *x == *y : (!x && !y ? x.error() == y.error() : false);
}
/// @relates expected
template <class T, class U>
auto operator==(const expected<T>& x, const U& y) -> decltype(*x == y) {
return x ? *x == y : false;
}
/// @relates expected
template <class T, class U>
auto operator==(const T& x, const expected<U>& y) -> decltype(x == *y) {
return y == x;
}
/// @relates expected
template <class T>
bool operator==(const expected<T>& x, const error& y) {
return x ? false : x.error() == y;
}
/// @relates expected
template <class T>
bool operator==(const error& x, const expected<T>& y) {
return y == x;
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator==(const expected<T>& x, E y) {
return x == make_error(y);
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator==(E x, const expected<T>& y) {
return y == make_error(x);
}
/// @relates expected
template <class T>
auto operator!=(const expected<T>& x, const expected<T>& y)
-> decltype(*x == *y) {
return !(x == y);
}
/// @relates expected
template <class T, class U>
auto operator!=(const expected<T>& x, const U& y) -> decltype(*x == y) {
return !(x == y);
}
/// @relates expected
template <class T, class U>
auto operator!=(const T& x, const expected<U>& y) -> decltype(x == *y) {
return !(x == y);
}
/// @relates expected
template <class T>
bool operator!=(const expected<T>& x, const error& y) {
return !(x == y);
}
/// @relates expected
template <class T>
bool operator!=(const error& x, const expected<T>& y) {
return !(x == y);
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator!=(const expected<T>& x, E y) {
return !(x == y);
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator!=(E x, const expected<T>& y) {
return !(x == y);
}
/// The pattern `expected<void>` shall be used for functions that may generate
/// an error but would otherwise return `bool`.
template <>
class expected<void> {
public:
expected() = default;
expected(unit_t) noexcept {
// nop
}
expected(caf::error e) noexcept : error_(std::move(e)) {
// nop
}
expected(const expected& other) noexcept : error_(other.error_) {
// nop
}
expected(expected&& other) noexcept : error_(std::move(other.error_)) {
// nop
}
template <class Code, class E = enable_if_has_make_error_t<Code>>
expected(Code code) : error_(make_error(code)) {
// nop
}
expected& operator=(const expected& other) noexcept {
error_ = other.error_;
return *this;
}
expected& operator=(expected&& other) noexcept {
error_ = std::move(other.error_);
return *this;
}
explicit operator bool() const {
return !error_;
}
const caf::error& error() const {
return error_;
}
private:
caf::error error_;
};
template <>
class expected<unit_t> : public expected<void> {
public:
using expected<void>::expected;
};
template <class T>
auto to_string(const expected<T>& x) -> decltype(to_string(*x)) {
if (x)
return to_string(*x);
return "!" + to_string(x.error());
}
/// @cond PRIVATE
/// Assigns the value of `expr` (which must return an `expected`)
/// to a new variable named `var` or throws a `std::runtime_error` on error.
/// @relates expected
/// @experimental
#define CAF_EXP_THROW(var, expr) \
auto CAF_UNIFYN(tmp_var_) = expr; \
if (!CAF_UNIFYN(tmp_var_)) \
CAF_RAISE_ERROR(to_string(CAF_UNIFYN(tmp_var_).error())); \
auto& var = *CAF_UNIFYN(tmp_var_)
/// @endcond
} // namespace caf
namespace std {
template <class T>
auto operator<<(ostream& oss, const caf::expected<T>& x)
-> decltype(oss << *x) {
if (x)
oss << *x;
else
oss << "!" << to_string(x.error());
return oss;
}
} // namespace std
#endif
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_EXPECTED_HPP
#define CAF_EXPECTED_HPP
#include "caf/config.hpp"
#include <new>
#include <memory>
#include <ostream>
#include <type_traits>
#include "caf/unit.hpp"
#include "caf/error.hpp"
#include "caf/unifyn.hpp"
namespace caf {
/// Represents the result of a computation which can either complete
/// successfully with an instance of type `T` or fail with an `error`.
/// @tparam T The type of the result.
template <typename T>
class expected {
public:
// -- member types -----------------------------------------------------------
using value_type = T;
// -- static member variables ------------------------------------------------
/// Stores whether move construct and move assign never throw.
static constexpr bool nothrow_move
= std::is_nothrow_move_constructible<T>::value
&& std::is_nothrow_move_assignable<T>::value;
/// Stores whether copy construct and copy assign never throw.
static constexpr bool nothrow_copy
= std::is_nothrow_copy_constructible<T>::value
&& std::is_nothrow_copy_assignable<T>::value;
// -- constructors, destructors, and assignment operators --------------------
template <class U>
expected(U x,
typename std::enable_if<std::is_convertible<U, T>::value>::type* = 0)
: engaged_(true) {
new (&value_) T(std::move(x));
}
expected(T&& x) noexcept(nothrow_move) : engaged_(true) {
new (&value_) T(std::move(x));
}
expected(const T& x) noexcept(nothrow_copy) : engaged_(true) {
new (&value_) T(x);
}
expected(caf::error e) noexcept : engaged_(false) {
new (&error_) caf::error{std::move(e)};
}
expected(const expected& other) noexcept(nothrow_copy) {
construct(other);
}
template <class Code, class E = enable_if_has_make_error_t<Code>>
expected(Code code) : engaged_(false) {
new (&error_) caf::error(make_error(code));
}
expected(expected&& other) noexcept(nothrow_move) {
construct(std::move(other));
}
~expected() {
destroy();
}
expected& operator=(const expected& other) noexcept(nothrow_copy) {
if (engaged_ && other.engaged_)
value_ = other.value_;
else if (!engaged_ && !other.engaged_)
error_ = other.error_;
else {
destroy();
construct(other);
}
return *this;
}
expected& operator=(expected&& other) noexcept(nothrow_move) {
if (engaged_ && other.engaged_)
value_ = std::move(other.value_);
else if (!engaged_ && !other.engaged_)
error_ = std::move(other.error_);
else {
destroy();
construct(std::move(other));
}
return *this;
}
expected& operator=(const T& x) noexcept(nothrow_copy) {
if (engaged_) {
value_ = x;
} else {
destroy();
engaged_ = true;
new (&value_) T(x);
}
return *this;
}
expected& operator=(T&& x) noexcept(nothrow_move) {
if (engaged_) {
value_ = std::move(x);
} else {
destroy();
engaged_ = true;
new (&value_) T(std::move(x));
}
return *this;
}
template <class U>
typename std::enable_if<std::is_convertible<U, T>::value, expected&>::type
operator=(U x) {
return *this = T{std::move(x)};
}
expected& operator=(caf::error e) noexcept {
if (!engaged_)
error_ = std::move(e);
else {
destroy();
engaged_ = false;
new (&value_) caf::error(std::move(e));
}
return *this;
}
template <class Code>
enable_if_has_make_error_t<Code, expected&> operator=(Code code) {
return *this = make_error(code);
}
// -- modifiers --------------------------------------------------------------
/// @copydoc cvalue
T& value() noexcept {
CAF_ASSERT(engaged_);
return value_;
}
/// @copydoc cvalue
T& operator*() noexcept {
return value();
}
/// @copydoc cvalue
T* operator->() noexcept {
return &value();
}
/// @copydoc cerror
caf::error& error() noexcept {
CAF_ASSERT(!engaged_);
return error_;
}
// -- observers --------------------------------------------------------------
/// Returns the contained value.
/// @pre `engaged() == true`.
const T& cvalue() const noexcept {
CAF_ASSERT(engaged_);
return value_;
}
/// @copydoc cvalue
const T& value() const noexcept {
CAF_ASSERT(engaged_);
return value_;
}
/// @copydoc cvalue
const T& operator*() const noexcept {
return value();
}
/// @copydoc cvalue
const T* operator->() const noexcept {
return &value();
}
/// @copydoc engaged
explicit operator bool() const noexcept {
return engaged();
}
/// Returns `true` if the object holds a value (is engaged).
bool engaged() const noexcept {
return engaged_;
}
/// Returns the contained error.
/// @pre `engaged() == false`.
const caf::error& cerror() const noexcept {
CAF_ASSERT(!engaged_);
return error_;
}
/// @copydoc cerror
const caf::error& error() const noexcept {
CAF_ASSERT(!engaged_);
return error_;
}
private:
void construct(expected&& other) noexcept(nothrow_move) {
if (other.engaged_)
new (&value_) T(std::move(other.value_));
else
new (&error_) caf::error(std::move(other.error_));
engaged_ = other.engaged_;
}
void construct(const expected& other) noexcept(nothrow_copy) {
if (other.engaged_)
new (&value_) T(other.value_);
else
new (&error_) caf::error(other.error_);
engaged_ = other.engaged_;
}
void destroy() {
if (engaged_)
value_.~T();
else
error_.~error();
}
bool engaged_;
union {
T value_;
caf::error error_;
};
};
/// @relates expected
template <class T>
auto operator==(const expected<T>& x, const expected<T>& y)
-> decltype(*x == *y) {
return x && y ? *x == *y : (!x && !y ? x.error() == y.error() : false);
}
/// @relates expected
template <class T, class U>
auto operator==(const expected<T>& x, const U& y) -> decltype(*x == y) {
return x ? *x == y : false;
}
/// @relates expected
template <class T, class U>
auto operator==(const T& x, const expected<U>& y) -> decltype(x == *y) {
return y == x;
}
/// @relates expected
template <class T>
bool operator==(const expected<T>& x, const error& y) {
return x ? false : x.error() == y;
}
/// @relates expected
template <class T>
bool operator==(const error& x, const expected<T>& y) {
return y == x;
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator==(const expected<T>& x, E y) {
return x == make_error(y);
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator==(E x, const expected<T>& y) {
return y == make_error(x);
}
/// @relates expected
template <class T>
auto operator!=(const expected<T>& x, const expected<T>& y)
-> decltype(*x == *y) {
return !(x == y);
}
/// @relates expected
template <class T, class U>
auto operator!=(const expected<T>& x, const U& y) -> decltype(*x == y) {
return !(x == y);
}
/// @relates expected
template <class T, class U>
auto operator!=(const T& x, const expected<U>& y) -> decltype(x == *y) {
return !(x == y);
}
/// @relates expected
template <class T>
bool operator!=(const expected<T>& x, const error& y) {
return !(x == y);
}
/// @relates expected
template <class T>
bool operator!=(const error& x, const expected<T>& y) {
return !(x == y);
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator!=(const expected<T>& x, E y) {
return !(x == y);
}
/// @relates expected
template <class T, class E>
enable_if_has_make_error_t<E, bool> operator!=(E x, const expected<T>& y) {
return !(x == y);
}
/// The pattern `expected<void>` shall be used for functions that may generate
/// an error but would otherwise return `bool`.
template <>
class expected<void> {
public:
expected() = default;
expected(unit_t) noexcept {
// nop
}
expected(caf::error e) noexcept : error_(std::move(e)) {
// nop
}
expected(const expected& other) noexcept : error_(other.error_) {
// nop
}
expected(expected&& other) noexcept : error_(std::move(other.error_)) {
// nop
}
template <class Code, class E = enable_if_has_make_error_t<Code>>
expected(Code code) : error_(make_error(code)) {
// nop
}
expected& operator=(const expected& other) noexcept {
error_ = other.error_;
return *this;
}
expected& operator=(expected&& other) noexcept {
error_ = std::move(other.error_);
return *this;
}
explicit operator bool() const {
return !error_;
}
const caf::error& error() const {
return error_;
}
private:
caf::error error_;
};
/// @relates expected
inline bool operator==(const expected<void>& x, const expected<void>& y) {
return (x && y) || (!x && !y && x.error() == y.error());
}
/// @relates expected
inline bool operator!=(const expected<void>& x, const expected<void>& y) {
return !(x == y);
}
template <>
class expected<unit_t> : public expected<void> {
public:
using expected<void>::expected;
};
template <class T>
auto to_string(const expected<T>& x) -> decltype(to_string(*x)) {
if (x)
return to_string(*x);
return "!" + to_string(x.error());
}
/// @cond PRIVATE
/// Assigns the value of `expr` (which must return an `expected`)
/// to a new variable named `var` or throws a `std::runtime_error` on error.
/// @relates expected
/// @experimental
#define CAF_EXP_THROW(var, expr) \
auto CAF_UNIFYN(tmp_var_) = expr; \
if (!CAF_UNIFYN(tmp_var_)) \
CAF_RAISE_ERROR(to_string(CAF_UNIFYN(tmp_var_).error())); \
auto& var = *CAF_UNIFYN(tmp_var_)
/// @endcond
} // namespace caf
namespace std {
template <class T>
auto operator<<(ostream& oss, const caf::expected<T>& x)
-> decltype(oss << *x) {
if (x)
oss << *x;
else
oss << "!" << to_string(x.error());
return oss;
}
} // namespace std
#endif
|
Make expected<void> equality-comparable
|
Make expected<void> equality-comparable
|
C++
|
bsd-3-clause
|
nq-ebaratte/actor-framework,nq-ebaratte/actor-framework,nq-ebaratte/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,nq-ebaratte/actor-framework
|
9c308e7059b4ff95dc1d90b7f7a6fbf4da55ffde
|
src/publishsubscribe/xqsettingsmanager_symbian/cpublishandsubscribehandler.cpp
|
src/publishsubscribe/xqsettingsmanager_symbian/cpublishandsubscribehandler.cpp
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "cpublishandsubscribehandler.h"
#include <e32property.h>
#include "xqsettingskey.h"
CPublishAndSubscribeHandler* CPublishAndSubscribeHandler::NewL(TUid aUid)
{
CPublishAndSubscribeHandler* self = new (ELeave) CPublishAndSubscribeHandler(aUid);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}
void CPublishAndSubscribeHandler::ConstructL()
{
}
CPublishAndSubscribeHandler::CPublishAndSubscribeHandler(TUid aUid)
: m_uid(aUid)
{
}
CPublishAndSubscribeHandler::~CPublishAndSubscribeHandler()
{
}
void CPublishAndSubscribeHandler::setObserver(MSettingsHandlerObserver* observer)
{
m_observer = observer;
}
TInt CPublishAndSubscribeHandler::getValue(unsigned long key, TInt& value)
{
return RProperty::Get(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::getValue(unsigned long /*key*/, TReal& /*value*/)
{
return KErrArgument;
}
void CPublishAndSubscribeHandler::getValueL(unsigned long key, RBuf8& value)
{
TInt err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxPropertySize);
err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxLargePropertySize);
err = RProperty::Get(m_uid, key, value);
}
}
User::LeaveIfError(err);
}
void CPublishAndSubscribeHandler::getValueL(unsigned long key, RBuf16& value)
{
TInt err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxPropertySize);
err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxLargePropertySize);
err = RProperty::Get(m_uid, key, value);
}
}
User::LeaveIfError(err);
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long key, const TInt& value)
{
return RProperty::Set(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long /*key*/, const TReal& /*value*/)
{
return KErrArgument;
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long key, const TDesC8& value)
{
return RProperty::Set(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long key, const TDesC16& value)
{
return RProperty::Set(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::defineProperty(unsigned long key, XQSettingsManager::Type type)
{
switch (type)
{
case XQSettingsManager::TypeInt:
{
return RProperty::Define(m_uid, key, RProperty::EInt);
}
case XQSettingsManager::TypeString:
{
return RProperty::Define(m_uid, key, RProperty::EText);
}
case XQSettingsManager::TypeByteArray:
{
return RProperty::Define(m_uid, key, RProperty::EByteArray);
}
case XQSettingsManager::TypeDouble:
default:
{
return KErrArgument;
}
}
}
TInt CPublishAndSubscribeHandler::defineProperty(unsigned long key, XQSettingsManager::Type type,
const XQPublishAndSubscribeSecurityPolicy& readPolicy, const XQPublishAndSubscribeSecurityPolicy& writePolicy)
{
switch (type)
{
case XQSettingsManager::TypeInt:
{
return RProperty::Define(m_uid, key, RProperty::EInt, symbianPolicy(readPolicy), symbianPolicy(writePolicy));
}
case XQSettingsManager::TypeString:
{
return RProperty::Define(m_uid, key, RProperty::EText, symbianPolicy(readPolicy), symbianPolicy(writePolicy));
}
case XQSettingsManager::TypeByteArray:
{
return RProperty::Define(m_uid, key, RProperty::EByteArray, symbianPolicy(readPolicy), symbianPolicy(writePolicy));
}
case XQSettingsManager::TypeDouble:
default:
{
return KErrArgument;
}
}
}
TSecurityPolicy CPublishAndSubscribeHandler::symbianPolicy(const XQPublishAndSubscribeSecurityPolicy& policy)
{
//Use constructor for EAlwaysFail or EAlwaysPass
switch (policy.secPolicyType())
{
case XQPublishAndSubscribeSecurityPolicy::SecPolicyAlwaysFail:
{
return TSecurityPolicy(TSecurityPolicy::EAlwaysFail);
}
case XQPublishAndSubscribeSecurityPolicy::SecPolicyAlwaysPass:
{
return TSecurityPolicy(TSecurityPolicy::EAlwaysPass);
}
default:
{
break;
}
}
TCapability capability1 = ECapability_None;
TCapability capability2 = ECapability_None;
TCapability capability3 = ECapability_None;
TCapability capability4 = ECapability_None;
TCapability capability5 = ECapability_None;
TCapability capability6 = ECapability_None;
TCapability capability7 = ECapability_None;
const QList<XQPublishAndSubscribeSecurityPolicy::Capability>& capabilities = policy.capabilities();
if (capabilities.count() > 0) capability1 = symbianCapability(capabilities[0]);
if (capabilities.count() > 1) capability2 = symbianCapability(capabilities[1]);
if (capabilities.count() > 2) capability3 = symbianCapability(capabilities[2]);
if (capabilities.count() > 3) capability4 = symbianCapability(capabilities[3]);
if (capabilities.count() > 4) capability5 = symbianCapability(capabilities[4]);
if (capabilities.count() > 5) capability6 = symbianCapability(capabilities[5]);
if (capabilities.count() > 6) capability7 = symbianCapability(capabilities[6]);
long int secureId = policy.secureId().uid();
if (secureId != -1)
{
//Use constructor for TSecureId + max 3 capabilities
return TSecurityPolicy(TSecureId(secureId), capability1, capability2, capability3);
}
long int vendorId = policy.vendorId().uid();
if (vendorId != -1)
{
//Use constructor for TVendorId + max 3 capabilities
return TSecurityPolicy(TVendorId(vendorId), capability1, capability2, capability3);
}
if (capabilities.count() < 4)
{
//Use constructor for max 3 capabilities
return TSecurityPolicy(capability1, capability2, capability3);
}
else
{
//Use constructor for max 7 capabilities
return TSecurityPolicy(capability1, capability2, capability3, capability4, capability5, capability6, capability7);
}
}
TCapability CPublishAndSubscribeHandler::symbianCapability(const XQPublishAndSubscribeSecurityPolicy::Capability& capability)
{
switch (capability)
{
case XQPublishAndSubscribeSecurityPolicy::CapabilityTCB: return ECapabilityTCB;
case XQPublishAndSubscribeSecurityPolicy::CapabilityCommDD: return ECapabilityCommDD;
case XQPublishAndSubscribeSecurityPolicy::CapabilityPowerMgmt: return ECapabilityPowerMgmt;
case XQPublishAndSubscribeSecurityPolicy::CapabilityMultimediaDD: return ECapabilityMultimediaDD;
case XQPublishAndSubscribeSecurityPolicy::CapabilityReadDeviceData: return ECapabilityReadDeviceData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityWriteDeviceData: return ECapabilityWriteDeviceData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityDRM: return ECapabilityDRM;
case XQPublishAndSubscribeSecurityPolicy::CapabilityTrustedUI: return ECapabilityTrustedUI;
case XQPublishAndSubscribeSecurityPolicy::CapabilityProtServ: return ECapabilityProtServ;
case XQPublishAndSubscribeSecurityPolicy::CapabilityDiskAdmin: return ECapabilityDiskAdmin;
case XQPublishAndSubscribeSecurityPolicy::CapabilityNetworkControl: return ECapabilityNetworkControl;
case XQPublishAndSubscribeSecurityPolicy::CapabilityAllFiles: return ECapabilityAllFiles;
case XQPublishAndSubscribeSecurityPolicy::CapabilitySwEvent: return ECapabilitySwEvent;
case XQPublishAndSubscribeSecurityPolicy::CapabilityNetworkServices: return ECapabilityNetworkServices;
case XQPublishAndSubscribeSecurityPolicy::CapabilityLocalServices: return ECapabilityLocalServices;
case XQPublishAndSubscribeSecurityPolicy::CapabilityReadUserData: return ECapabilityReadUserData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityWriteUserData: return ECapabilityWriteUserData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityLocation: return ECapabilityLocation;
case XQPublishAndSubscribeSecurityPolicy::CapabilitySurroundingsDD: return ECapabilitySurroundingsDD;
case XQPublishAndSubscribeSecurityPolicy::CapabilityUserEnvironment: return ECapabilityUserEnvironment;
default:
{
break;
}
}
return TCapability();
}
TInt CPublishAndSubscribeHandler::deleteProperty(unsigned long key)
{
return RProperty::Delete(m_uid, key);
}
bool CPublishAndSubscribeHandler::handleStartMonitoring(const XQSettingsKey& key, XQSettingsManager::Type type, MSettingsHandlerObserver& observer, TInt& error)
{
if (m_monitors.contains(key.key()))
{
error = KErrAlreadyExists;
return false;
}
CPubSubMonitor* newMonitor = new CPubSubMonitor(key, type, observer);
if (newMonitor)
{
m_monitors[key.key()] = newMonitor;
error = newMonitor->StartMonitoring();
return error == KErrNone;
}
error = KErrNoMemory;
return false;
}
bool CPublishAndSubscribeHandler::handleStopMonitoring(const XQSettingsKey& key, TInt& error)
{
if (!m_monitors.contains(key.key()))
{
error = KErrNotFound;
return false;
}
const long int itemKey = key.key();
CPubSubMonitor* monitor = m_monitors[itemKey];
m_monitors.remove(itemKey);
delete monitor;
return error == KErrNone;
}
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "cpublishandsubscribehandler.h"
#include <e32property.h>
#include "xqsettingskey.h"
CPublishAndSubscribeHandler* CPublishAndSubscribeHandler::NewL(TUid aUid)
{
CPublishAndSubscribeHandler* self = new (ELeave) CPublishAndSubscribeHandler(aUid);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}
void CPublishAndSubscribeHandler::ConstructL()
{
}
CPublishAndSubscribeHandler::CPublishAndSubscribeHandler(TUid aUid)
: m_uid(aUid)
{
}
CPublishAndSubscribeHandler::~CPublishAndSubscribeHandler()
{
qDeleteAll(m_monitors);
}
void CPublishAndSubscribeHandler::setObserver(MSettingsHandlerObserver* observer)
{
m_observer = observer;
}
TInt CPublishAndSubscribeHandler::getValue(unsigned long key, TInt& value)
{
return RProperty::Get(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::getValue(unsigned long /*key*/, TReal& /*value*/)
{
return KErrArgument;
}
void CPublishAndSubscribeHandler::getValueL(unsigned long key, RBuf8& value)
{
TInt err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxPropertySize);
err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxLargePropertySize);
err = RProperty::Get(m_uid, key, value);
}
}
User::LeaveIfError(err);
}
void CPublishAndSubscribeHandler::getValueL(unsigned long key, RBuf16& value)
{
TInt err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxPropertySize);
err = RProperty::Get(m_uid, key, value);
if (err == KErrOverflow)
{
value.ReAllocL(RProperty::KMaxLargePropertySize);
err = RProperty::Get(m_uid, key, value);
}
}
User::LeaveIfError(err);
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long key, const TInt& value)
{
return RProperty::Set(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long /*key*/, const TReal& /*value*/)
{
return KErrArgument;
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long key, const TDesC8& value)
{
return RProperty::Set(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::setValue(unsigned long key, const TDesC16& value)
{
return RProperty::Set(m_uid, key, value);
}
TInt CPublishAndSubscribeHandler::defineProperty(unsigned long key, XQSettingsManager::Type type)
{
switch (type)
{
case XQSettingsManager::TypeInt:
{
return RProperty::Define(m_uid, key, RProperty::EInt);
}
case XQSettingsManager::TypeString:
{
return RProperty::Define(m_uid, key, RProperty::EText);
}
case XQSettingsManager::TypeByteArray:
{
return RProperty::Define(m_uid, key, RProperty::EByteArray);
}
case XQSettingsManager::TypeDouble:
default:
{
return KErrArgument;
}
}
}
TInt CPublishAndSubscribeHandler::defineProperty(unsigned long key, XQSettingsManager::Type type,
const XQPublishAndSubscribeSecurityPolicy& readPolicy, const XQPublishAndSubscribeSecurityPolicy& writePolicy)
{
switch (type)
{
case XQSettingsManager::TypeInt:
{
return RProperty::Define(m_uid, key, RProperty::EInt, symbianPolicy(readPolicy), symbianPolicy(writePolicy));
}
case XQSettingsManager::TypeString:
{
return RProperty::Define(m_uid, key, RProperty::EText, symbianPolicy(readPolicy), symbianPolicy(writePolicy));
}
case XQSettingsManager::TypeByteArray:
{
return RProperty::Define(m_uid, key, RProperty::EByteArray, symbianPolicy(readPolicy), symbianPolicy(writePolicy));
}
case XQSettingsManager::TypeDouble:
default:
{
return KErrArgument;
}
}
}
TSecurityPolicy CPublishAndSubscribeHandler::symbianPolicy(const XQPublishAndSubscribeSecurityPolicy& policy)
{
//Use constructor for EAlwaysFail or EAlwaysPass
switch (policy.secPolicyType())
{
case XQPublishAndSubscribeSecurityPolicy::SecPolicyAlwaysFail:
{
return TSecurityPolicy(TSecurityPolicy::EAlwaysFail);
}
case XQPublishAndSubscribeSecurityPolicy::SecPolicyAlwaysPass:
{
return TSecurityPolicy(TSecurityPolicy::EAlwaysPass);
}
default:
{
break;
}
}
TCapability capability1 = ECapability_None;
TCapability capability2 = ECapability_None;
TCapability capability3 = ECapability_None;
TCapability capability4 = ECapability_None;
TCapability capability5 = ECapability_None;
TCapability capability6 = ECapability_None;
TCapability capability7 = ECapability_None;
const QList<XQPublishAndSubscribeSecurityPolicy::Capability>& capabilities = policy.capabilities();
if (capabilities.count() > 0) capability1 = symbianCapability(capabilities[0]);
if (capabilities.count() > 1) capability2 = symbianCapability(capabilities[1]);
if (capabilities.count() > 2) capability3 = symbianCapability(capabilities[2]);
if (capabilities.count() > 3) capability4 = symbianCapability(capabilities[3]);
if (capabilities.count() > 4) capability5 = symbianCapability(capabilities[4]);
if (capabilities.count() > 5) capability6 = symbianCapability(capabilities[5]);
if (capabilities.count() > 6) capability7 = symbianCapability(capabilities[6]);
long int secureId = policy.secureId().uid();
if (secureId != -1)
{
//Use constructor for TSecureId + max 3 capabilities
return TSecurityPolicy(TSecureId(secureId), capability1, capability2, capability3);
}
long int vendorId = policy.vendorId().uid();
if (vendorId != -1)
{
//Use constructor for TVendorId + max 3 capabilities
return TSecurityPolicy(TVendorId(vendorId), capability1, capability2, capability3);
}
if (capabilities.count() < 4)
{
//Use constructor for max 3 capabilities
return TSecurityPolicy(capability1, capability2, capability3);
}
else
{
//Use constructor for max 7 capabilities
return TSecurityPolicy(capability1, capability2, capability3, capability4, capability5, capability6, capability7);
}
}
TCapability CPublishAndSubscribeHandler::symbianCapability(const XQPublishAndSubscribeSecurityPolicy::Capability& capability)
{
switch (capability)
{
case XQPublishAndSubscribeSecurityPolicy::CapabilityTCB: return ECapabilityTCB;
case XQPublishAndSubscribeSecurityPolicy::CapabilityCommDD: return ECapabilityCommDD;
case XQPublishAndSubscribeSecurityPolicy::CapabilityPowerMgmt: return ECapabilityPowerMgmt;
case XQPublishAndSubscribeSecurityPolicy::CapabilityMultimediaDD: return ECapabilityMultimediaDD;
case XQPublishAndSubscribeSecurityPolicy::CapabilityReadDeviceData: return ECapabilityReadDeviceData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityWriteDeviceData: return ECapabilityWriteDeviceData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityDRM: return ECapabilityDRM;
case XQPublishAndSubscribeSecurityPolicy::CapabilityTrustedUI: return ECapabilityTrustedUI;
case XQPublishAndSubscribeSecurityPolicy::CapabilityProtServ: return ECapabilityProtServ;
case XQPublishAndSubscribeSecurityPolicy::CapabilityDiskAdmin: return ECapabilityDiskAdmin;
case XQPublishAndSubscribeSecurityPolicy::CapabilityNetworkControl: return ECapabilityNetworkControl;
case XQPublishAndSubscribeSecurityPolicy::CapabilityAllFiles: return ECapabilityAllFiles;
case XQPublishAndSubscribeSecurityPolicy::CapabilitySwEvent: return ECapabilitySwEvent;
case XQPublishAndSubscribeSecurityPolicy::CapabilityNetworkServices: return ECapabilityNetworkServices;
case XQPublishAndSubscribeSecurityPolicy::CapabilityLocalServices: return ECapabilityLocalServices;
case XQPublishAndSubscribeSecurityPolicy::CapabilityReadUserData: return ECapabilityReadUserData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityWriteUserData: return ECapabilityWriteUserData;
case XQPublishAndSubscribeSecurityPolicy::CapabilityLocation: return ECapabilityLocation;
case XQPublishAndSubscribeSecurityPolicy::CapabilitySurroundingsDD: return ECapabilitySurroundingsDD;
case XQPublishAndSubscribeSecurityPolicy::CapabilityUserEnvironment: return ECapabilityUserEnvironment;
default:
{
break;
}
}
return TCapability();
}
TInt CPublishAndSubscribeHandler::deleteProperty(unsigned long key)
{
return RProperty::Delete(m_uid, key);
}
bool CPublishAndSubscribeHandler::handleStartMonitoring(const XQSettingsKey& key, XQSettingsManager::Type type, MSettingsHandlerObserver& observer, TInt& error)
{
if (m_monitors.contains(key.key()))
{
error = KErrAlreadyExists;
return false;
}
CPubSubMonitor* newMonitor = new CPubSubMonitor(key, type, observer);
if (newMonitor)
{
m_monitors[key.key()] = newMonitor;
error = newMonitor->StartMonitoring();
return error == KErrNone;
}
error = KErrNoMemory;
return false;
}
bool CPublishAndSubscribeHandler::handleStopMonitoring(const XQSettingsKey& key, TInt& error)
{
if (!m_monitors.contains(key.key()))
{
error = KErrNotFound;
return false;
}
const long int itemKey = key.key();
CPubSubMonitor* monitor = m_monitors[itemKey];
m_monitors.remove(itemKey);
delete monitor;
return error == KErrNone;
}
|
Fix memory leak.
|
Fix memory leak.
Task-number: MOBILITY-1231
|
C++
|
lgpl-2.1
|
kaltsi/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility
|
7f74014b590df6644c03fd00c73107252a8d005a
|
cpp/src/main/models/factor/FactorModel.cpp
|
cpp/src/main/models/factor/FactorModel.cpp
|
#include "FactorModel.h"
void FactorModel::set_parameters(FactorModelParameters* parameters){
FactorsParameters factors_parameters;
factors_parameters.begin_min=begin_min_;
factors_parameters.begin_max=begin_max_;
factors_parameters.dimension=dimension_;
factors_parameters.seed=parameters->seed+1; //subobject seed: own seed+1
user_factors_.set_parameters(factors_parameters);
factors_parameters.seed=parameters->seed+2; //second subobject: own seed+2
item_factors_.set_parameters(factors_parameters);
}
void FactorModel::clear(){
user_factors_.clear();
item_factors_.clear();
if(use_user_bias_){
user_bias_.clear();
}
if(use_user_bias_){
item_bias_.clear();
}
if(initialize_all_){
for(int user=0;user<=max_user_;user++) user_factors_.init(user);
for(int item=0;item<=max_item_;item++) item_factors_.init(item);
if(use_user_bias_){
for(int user=0;user<=max_user_;user++) user_bias_.init(user);
}
if(use_item_bias_){
for(int item=0;item<=max_item_;item++) item_bias_.init(item);
}
}
//TODO recency.clear()?
}
void FactorModel::add(RecDat *rec_dat){
user_factors_.init(rec_dat->user);
item_factors_.init(rec_dat->item);
if (use_user_bias_) user_bias_.init(rec_dat->user);
if (use_item_bias_) item_bias_.init(rec_dat->item);
lemp_container_.schedule_update_item(rec_dat->item);
}
double FactorModel::prediction(RecDat *rec_dat){
double scalar_product = compute_product(rec_dat);
double user_bias_val = compute_user_bias(rec_dat);
double item_bias_val = compute_item_bias(rec_dat);
if(user_recency_!=NULL){
double user_recency_val = user_recency_->get(rec_dat->user,rec_dat->time);
user_bias_val*=user_recency_val;
scalar_product*=user_recency_val;
}
if(item_recency_!=NULL){
double item_recency_val = item_recency_->get(rec_dat->item,rec_dat->time);
item_bias_val*=item_recency_val;
scalar_product+=item_recency_val;
}
double prediction = scalar_product+user_bias_val+item_bias_val;
if(use_sigmoid_){
prediction=Util::sigmoid_function(prediction);
}
return prediction;
}
double FactorModel::similarity(int item1, int item2){
vector<double>* item1_vector = item_factors_.get(item1);
vector<double>* item2_vector = item_factors_.get(item2);
return Util::scalar_product(item1_vector, item2_vector)/(Util::norm(item1_vector)*Util::norm(item2_vector));
}
double FactorModel::compute_user_bias(RecDat *rec_dat){
double user_bias_val = 0;
if (use_user_bias_) user_bias_val = user_bias_.get(rec_dat->user);
return user_bias_val;
}
double FactorModel::compute_item_bias(RecDat *rec_dat){
double item_bias_val = 0;
if (use_item_bias_) item_bias_val = item_bias_.get(rec_dat->item);
return item_bias_val;
}
double FactorModel::compute_product(RecDat *rec_dat){
return Util::scalar_product(user_factors_.get(rec_dat->user),item_factors_.get(rec_dat->item));
}
void FactorModel::write(ostream& file){
user_factors_.write(file);
item_factors_.write(file);
//TODO bias, recency
}
void FactorModel::read(istream& file){
user_factors_.read(file);
item_factors_.read(file);
lemp_container_.reinitialize(&item_factors_);
//TODO bias, recency
}
RankingScoreIterator* FactorModel::get_ranking_score_iterator(int u){
if(use_item_bias_ || use_user_bias_){
return NULL;
} else {
ranking_score_iterator_ = FactorModelRankingScoreIterator(*user_factors_.get(u), &lemp_container_);
return &ranking_score_iterator_;
}
}
//double FactorModel::user_factor_mean() {
// double avg=0;
// vector<int> user_indices = user_factors_.get_nonnull_indices();
// for(std::vector<int>::iterator it = user_indices.begin() ; it != user_indices.end(); ++it)
// avg+=Util::scalar_product(user_factors_.get(*it),user_factors_.get(*it));
// if(user_indices.size()>0) avg=avg/double(user_indices.size());
// return avg;
//}
//
//
//double FactorModel::item_factor_mean() {
// double avg=0;
// vector<int> item_indices = item_factors_.get_nonnull_indices();
// for(std::vector<int>::iterator it = item_indices.begin() ; it != item_indices.end(); ++it)
// avg+=Util::scalar_product(item_factors_.get(*it),item_factors_.get(*it));
// if(item_indices.size()>0) avg=avg/double(item_indices.size());
// return avg;
//}
|
#include "FactorModel.h"
void FactorModel::set_parameters(FactorModelParameters* parameters){
FactorsParameters factors_parameters;
factors_parameters.begin_min=begin_min_;
factors_parameters.begin_max=begin_max_;
factors_parameters.dimension=dimension_;
factors_parameters.seed=parameters->seed+1; //subobject seed: own seed+1
user_factors_.set_parameters(factors_parameters);
factors_parameters.seed=parameters->seed+2; //second subobject: own seed+2
item_factors_.set_parameters(factors_parameters);
}
void FactorModel::clear(){
user_factors_.clear();
item_factors_.clear();
if(use_user_bias_){
user_bias_.clear();
}
if(use_user_bias_){
item_bias_.clear();
}
if(initialize_all_){
for(int user=0;user<=max_user_;user++) user_factors_.init(user);
for(int item=0;item<=max_item_;item++) item_factors_.init(item);
if(use_user_bias_){
for(int user=0;user<=max_user_;user++) user_bias_.init(user);
}
if(use_item_bias_){
for(int item=0;item<=max_item_;item++) item_bias_.init(item);
}
}
//TODO recency.clear()?
}
void FactorModel::add(RecDat *rec_dat){
user_factors_.init(rec_dat->user);
item_factors_.init(rec_dat->item);
if (use_user_bias_) user_bias_.init(rec_dat->user);
if (use_item_bias_) item_bias_.init(rec_dat->item);
lemp_container_.schedule_update_item(rec_dat->item);
}
double FactorModel::prediction(RecDat *rec_dat){
double scalar_product = compute_product(rec_dat);
double user_bias_val = compute_user_bias(rec_dat);
double item_bias_val = compute_item_bias(rec_dat);
if(user_recency_!=NULL){
double user_recency_val = user_recency_->get(rec_dat->user,rec_dat->time);
user_bias_val*=user_recency_val;
scalar_product*=user_recency_val;
}
if(item_recency_!=NULL){
double item_recency_val = item_recency_->get(rec_dat->item,rec_dat->time);
item_bias_val*=item_recency_val;
scalar_product*=item_recency_val;
}
double prediction = scalar_product+user_bias_val+item_bias_val;
if(use_sigmoid_){
prediction=Util::sigmoid_function(prediction);
}
return prediction;
}
double FactorModel::similarity(int item1, int item2){
vector<double>* item1_vector = item_factors_.get(item1);
vector<double>* item2_vector = item_factors_.get(item2);
return Util::scalar_product(item1_vector, item2_vector)/(Util::norm(item1_vector)*Util::norm(item2_vector));
}
double FactorModel::compute_user_bias(RecDat *rec_dat){
double user_bias_val = 0;
if (use_user_bias_) user_bias_val = user_bias_.get(rec_dat->user);
return user_bias_val;
}
double FactorModel::compute_item_bias(RecDat *rec_dat){
double item_bias_val = 0;
if (use_item_bias_) item_bias_val = item_bias_.get(rec_dat->item);
return item_bias_val;
}
double FactorModel::compute_product(RecDat *rec_dat){
return Util::scalar_product(user_factors_.get(rec_dat->user),item_factors_.get(rec_dat->item));
}
void FactorModel::write(ostream& file){
user_factors_.write(file);
item_factors_.write(file);
//TODO bias, recency
}
void FactorModel::read(istream& file){
user_factors_.read(file);
item_factors_.read(file);
lemp_container_.reinitialize(&item_factors_);
//TODO bias, recency
}
RankingScoreIterator* FactorModel::get_ranking_score_iterator(int u){
if(use_item_bias_ || use_user_bias_){
return NULL;
} else {
ranking_score_iterator_ = FactorModelRankingScoreIterator(*user_factors_.get(u), &lemp_container_);
return &ranking_score_iterator_;
}
}
//double FactorModel::user_factor_mean() {
// double avg=0;
// vector<int> user_indices = user_factors_.get_nonnull_indices();
// for(std::vector<int>::iterator it = user_indices.begin() ; it != user_indices.end(); ++it)
// avg+=Util::scalar_product(user_factors_.get(*it),user_factors_.get(*it));
// if(user_indices.size()>0) avg=avg/double(user_indices.size());
// return avg;
//}
//
//
//double FactorModel::item_factor_mean() {
// double avg=0;
// vector<int> item_indices = item_factors_.get_nonnull_indices();
// for(std::vector<int>::iterator it = item_indices.begin() ; it != item_indices.end(); ++it)
// avg+=Util::scalar_product(item_factors_.get(*it),item_factors_.get(*it));
// if(item_indices.size()>0) avg=avg/double(item_indices.size());
// return avg;
//}
|
fix bug in recency mode prediction calculation
|
fix bug in recency mode prediction calculation
|
C++
|
apache-2.0
|
rpalovics/Alpenglow,rpalovics/Alpenglow,rpalovics/Alpenglow,proto-n/Alpenglow,proto-n/Alpenglow,proto-n/Alpenglow
|
9d8c445840004d9af7c174e319f5c5e0d16ce6ee
|
chrome/renderer/blocked_plugin.cc
|
chrome/renderer/blocked_plugin.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/blocked_plugin.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMenuItemInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRegularExpression.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCaseSensitivity.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/webview_plugin.h"
using WebKit::WebContextMenuData;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebMenuItemInfo;
using WebKit::WebNode;
using WebKit::WebPlugin;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRegularExpression;
using WebKit::WebString;
using WebKit::WebVector;
static const char* const kBlockedPluginDataURL = "chrome://blockedplugindata/";
// TODO(cevans) - move these to a shared header file so that there are no
// collisions in the longer term. Currently, blocked_plugin.cc is the only
// user of custom menu commands (extension menu items have their own range).
static const unsigned kMenuActionLoad = 1;
static const unsigned kMenuActionRemove = 2;
static const BlockedPlugin* gLastActiveMenu;
BlockedPlugin::BlockedPlugin(RenderView* render_view,
WebFrame* frame,
const webkit::npapi::PluginGroup& info,
const WebPluginParams& params,
const WebPreferences& preferences,
int template_id,
const string16& message,
bool is_blocked_for_prerendering)
: RenderViewObserver(render_view),
frame_(frame),
plugin_params_(params),
is_blocked_for_prerendering_(is_blocked_for_prerendering),
hidden_(false) {
const base::StringPiece template_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));
DCHECK(!template_html.empty()) << "unable to load template. ID: "
<< template_id;
DictionaryValue values;
values.SetString("message", message);
name_ = info.GetGroupName();
values.SetString("name", name_);
values.SetString("hide", l10n_util::GetStringUTF8(IDS_PLUGIN_HIDE));
// "t" is the id of the templates root node.
std::string html_data = jstemplate_builder::GetTemplatesHtml(
template_html, &values, "t");
plugin_ = webkit::npapi::WebViewPlugin::Create(this,
preferences,
html_data,
GURL(kBlockedPluginDataURL));
}
BlockedPlugin::~BlockedPlugin() {
}
void BlockedPlugin::BindWebFrame(WebFrame* frame) {
BindToJavascript(frame, "plugin");
BindMethod("load", &BlockedPlugin::Load);
BindMethod("hide", &BlockedPlugin::Hide);
}
void BlockedPlugin::WillDestroyPlugin() {
delete this;
}
void BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {
WebContextMenuData menu_data;
WebVector<WebMenuItemInfo> custom_items(static_cast<size_t>(4));
WebMenuItemInfo name_item;
name_item.label = name_;
custom_items[0] = name_item;
WebMenuItemInfo separator_item;
separator_item.type = WebMenuItemInfo::Separator;
custom_items[1] = separator_item;
WebMenuItemInfo run_item;
run_item.action = kMenuActionLoad;
run_item.enabled = true;
run_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());
custom_items[2] = run_item;
WebMenuItemInfo hide_item;
hide_item.action = kMenuActionRemove;
hide_item.enabled = true;
hide_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());
custom_items[3] = hide_item;
menu_data.customItems.swap(custom_items);
menu_data.mousePosition = WebPoint(event.windowX, event.windowY);
render_view()->showContextMenu(NULL, menu_data);
gLastActiveMenu = this;
}
bool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {
// We don't swallow ViewMsg_CustomContextMenuAction because we listen for all
// custom menu IDs, and not just our own. We don't swallow
// ViewMsg_LoadBlockedPlugins because multiple blocked plugins have an
// interest in it.
if (message.type() == ViewMsg_CustomContextMenuAction::ID &&
gLastActiveMenu == this) {
ViewMsg_CustomContextMenuAction::Dispatch(
&message, this, this, &BlockedPlugin::OnMenuItemSelected);
} else if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {
LoadPlugin();
} else if (message.type() == ViewMsg_DisplayPrerenderedPage::ID) {
if (is_blocked_for_prerendering_)
LoadPlugin();
}
return false;
}
void BlockedPlugin::OnMenuItemSelected(
const webkit_glue::CustomContextMenuContext& /* ignored */,
unsigned id) {
if (id == kMenuActionLoad) {
LoadPlugin();
} else if (id == kMenuActionRemove) {
HidePlugin();
}
}
void BlockedPlugin::LoadPlugin() {
CHECK(plugin_);
// This is not strictly necessary but is an important defense in case the
// event propagation changes between "close" vs. "click-to-play".
if (hidden_)
return;
WebPluginContainer* container = plugin_->container();
WebPlugin* new_plugin =
render_view()->CreatePluginNoCheck(frame_, plugin_params_);
if (new_plugin && new_plugin->initialize(container)) {
plugin_->RestoreTitleText();
container->setPlugin(new_plugin);
container->invalidate();
container->reportGeometry();
plugin_->ReplayReceivedData(new_plugin);
plugin_->destroy();
}
}
void BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {
LoadPlugin();
}
void BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {
HidePlugin();
}
void BlockedPlugin::HidePlugin() {
CHECK(plugin_);
hidden_ = true;
WebPluginContainer* container = plugin_->container();
WebElement element = container->element();
element.setAttribute("style", "display: none;");
// If we have a width and height, search for a parent (often <div>) with the
// same dimensions. If we find such a parent, hide that as well.
// This makes much more uncovered page content usable (including clickable)
// as opposed to merely visible.
// TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for
// now for these reasons:
// 1) Makes the user experience better.
// 2) Foulness is encapsulated within this single function.
// 3) Confidence in no fasle positives.
// 4) Seems to have a good / low false negative rate at this time.
if (element.hasAttribute("width") && element.hasAttribute("height")) {
std::string width_str("width:[\\s]*");
width_str += element.getAttribute("width").utf8().data();
if (EndsWith(width_str, "px", false)) {
width_str = width_str.substr(0, width_str.length() - 2);
}
TrimWhitespace(width_str, TRIM_TRAILING, &width_str);
width_str += "[\\s]*px";
WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),
WebKit::WebTextCaseSensitive);
std::string height_str("height:[\\s]*");
height_str += element.getAttribute("height").utf8().data();
if (EndsWith(height_str, "px", false)) {
height_str = height_str.substr(0, height_str.length() - 2);
}
TrimWhitespace(height_str, TRIM_TRAILING, &height_str);
height_str += "[\\s]*px";
WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),
WebKit::WebTextCaseSensitive);
WebNode parent = element;
while (!parent.parentNode().isNull()) {
parent = parent.parentNode();
if (!parent.isElementNode())
continue;
element = parent.toConst<WebElement>();
if (element.hasAttribute("style")) {
WebString style_str = element.getAttribute("style");
if (width_regex.match(style_str) >= 0 &&
height_regex.match(style_str) >= 0)
element.setAttribute("style", "display: none;");
}
}
}
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/blocked_plugin.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMenuItemInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRegularExpression.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCaseSensitivity.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/webview_plugin.h"
using WebKit::WebContextMenuData;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebMenuItemInfo;
using WebKit::WebNode;
using WebKit::WebPlugin;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRegularExpression;
using WebKit::WebString;
using WebKit::WebVector;
static const char* const kBlockedPluginDataURL = "chrome://blockedplugindata/";
// TODO(cevans) - move these to a shared header file so that there are no
// collisions in the longer term. Currently, blocked_plugin.cc is the only
// user of custom menu commands (extension menu items have their own range).
static const unsigned kMenuActionLoad = 1;
static const unsigned kMenuActionRemove = 2;
static const BlockedPlugin* gLastActiveMenu;
BlockedPlugin::BlockedPlugin(RenderView* render_view,
WebFrame* frame,
const webkit::npapi::PluginGroup& info,
const WebPluginParams& params,
const WebPreferences& preferences,
int template_id,
const string16& message,
bool is_blocked_for_prerendering)
: RenderViewObserver(render_view),
frame_(frame),
plugin_params_(params),
is_blocked_for_prerendering_(is_blocked_for_prerendering),
hidden_(false) {
const base::StringPiece template_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));
DCHECK(!template_html.empty()) << "unable to load template. ID: "
<< template_id;
DictionaryValue values;
values.SetString("message", message);
name_ = info.GetGroupName();
values.SetString("name", name_);
values.SetString("hide", l10n_util::GetStringUTF8(IDS_PLUGIN_HIDE));
// "t" is the id of the templates root node.
std::string html_data = jstemplate_builder::GetTemplatesHtml(
template_html, &values, "t");
plugin_ = webkit::npapi::WebViewPlugin::Create(this,
preferences,
html_data,
GURL(kBlockedPluginDataURL));
}
BlockedPlugin::~BlockedPlugin() {
}
void BlockedPlugin::BindWebFrame(WebFrame* frame) {
BindToJavascript(frame, "plugin");
BindMethod("load", &BlockedPlugin::Load);
BindMethod("hide", &BlockedPlugin::Hide);
}
void BlockedPlugin::WillDestroyPlugin() {
delete this;
}
void BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {
WebContextMenuData menu_data;
WebVector<WebMenuItemInfo> custom_items(static_cast<size_t>(4));
WebMenuItemInfo name_item;
name_item.label = name_;
name_item.hasTextDirectionOverride = false;
name_item.textDirection = WebKit::WebTextDirectionDefault;
custom_items[0] = name_item;
WebMenuItemInfo separator_item;
separator_item.type = WebMenuItemInfo::Separator;
custom_items[1] = separator_item;
WebMenuItemInfo run_item;
run_item.action = kMenuActionLoad;
run_item.enabled = true;
run_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());
run_item.hasTextDirectionOverride = false;
run_item.textDirection = WebKit::WebTextDirectionDefault;
custom_items[2] = run_item;
WebMenuItemInfo hide_item;
hide_item.action = kMenuActionRemove;
hide_item.enabled = true;
hide_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());
hide_item.hasTextDirectionOverride = false;
hide_item.textDirection = WebKit::WebTextDirectionDefault;
custom_items[3] = hide_item;
menu_data.customItems.swap(custom_items);
menu_data.mousePosition = WebPoint(event.windowX, event.windowY);
render_view()->showContextMenu(NULL, menu_data);
gLastActiveMenu = this;
}
bool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {
// We don't swallow ViewMsg_CustomContextMenuAction because we listen for all
// custom menu IDs, and not just our own. We don't swallow
// ViewMsg_LoadBlockedPlugins because multiple blocked plugins have an
// interest in it.
if (message.type() == ViewMsg_CustomContextMenuAction::ID &&
gLastActiveMenu == this) {
ViewMsg_CustomContextMenuAction::Dispatch(
&message, this, this, &BlockedPlugin::OnMenuItemSelected);
} else if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {
LoadPlugin();
} else if (message.type() == ViewMsg_DisplayPrerenderedPage::ID) {
if (is_blocked_for_prerendering_)
LoadPlugin();
}
return false;
}
void BlockedPlugin::OnMenuItemSelected(
const webkit_glue::CustomContextMenuContext& /* ignored */,
unsigned id) {
if (id == kMenuActionLoad) {
LoadPlugin();
} else if (id == kMenuActionRemove) {
HidePlugin();
}
}
void BlockedPlugin::LoadPlugin() {
CHECK(plugin_);
// This is not strictly necessary but is an important defense in case the
// event propagation changes between "close" vs. "click-to-play".
if (hidden_)
return;
WebPluginContainer* container = plugin_->container();
WebPlugin* new_plugin =
render_view()->CreatePluginNoCheck(frame_, plugin_params_);
if (new_plugin && new_plugin->initialize(container)) {
plugin_->RestoreTitleText();
container->setPlugin(new_plugin);
container->invalidate();
container->reportGeometry();
plugin_->ReplayReceivedData(new_plugin);
plugin_->destroy();
}
}
void BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {
LoadPlugin();
}
void BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {
HidePlugin();
}
void BlockedPlugin::HidePlugin() {
CHECK(plugin_);
hidden_ = true;
WebPluginContainer* container = plugin_->container();
WebElement element = container->element();
element.setAttribute("style", "display: none;");
// If we have a width and height, search for a parent (often <div>) with the
// same dimensions. If we find such a parent, hide that as well.
// This makes much more uncovered page content usable (including clickable)
// as opposed to merely visible.
// TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for
// now for these reasons:
// 1) Makes the user experience better.
// 2) Foulness is encapsulated within this single function.
// 3) Confidence in no fasle positives.
// 4) Seems to have a good / low false negative rate at this time.
if (element.hasAttribute("width") && element.hasAttribute("height")) {
std::string width_str("width:[\\s]*");
width_str += element.getAttribute("width").utf8().data();
if (EndsWith(width_str, "px", false)) {
width_str = width_str.substr(0, width_str.length() - 2);
}
TrimWhitespace(width_str, TRIM_TRAILING, &width_str);
width_str += "[\\s]*px";
WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),
WebKit::WebTextCaseSensitive);
std::string height_str("height:[\\s]*");
height_str += element.getAttribute("height").utf8().data();
if (EndsWith(height_str, "px", false)) {
height_str = height_str.substr(0, height_str.length() - 2);
}
TrimWhitespace(height_str, TRIM_TRAILING, &height_str);
height_str += "[\\s]*px";
WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),
WebKit::WebTextCaseSensitive);
WebNode parent = element;
while (!parent.parentNode().isNull()) {
parent = parent.parentNode();
if (!parent.isElementNode())
continue;
element = parent.toConst<WebElement>();
if (element.hasAttribute("style")) {
WebString style_str = element.getAttribute("style");
if (width_regex.match(style_str) >= 0 &&
height_regex.match(style_str) >= 0)
element.setAttribute("style", "display: none;");
}
}
}
}
|
Fix some uninitialized struct members.
|
Coverity: Fix some uninitialized struct members.
CID=14884,14885,14886
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/6665017
git-svn-id: http://src.chromium.org/svn/trunk/src@77761 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: f7366216cc9753e950449579a301d93d710d572e
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
38985a0046065cdca5bd4c36528a79d1f2526644
|
chrome/renderer/devtools_agent.cc
|
chrome/renderer/devtools_agent.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/devtools_agent.h"
#include <map>
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent_filter.h"
#include "chrome/renderer/render_view.h"
#include "grit/webkit_chromium_resources.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsAgentClient;
using WebKit::WebPoint;
using WebKit::WebString;
using WebKit::WebCString;
using WebKit::WebVector;
using WebKit::WebView;
namespace {
class WebKitClientMessageLoopImpl
: public WebDevToolsAgentClient::WebKitClientMessageLoop {
public:
WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { }
virtual ~WebKitClientMessageLoopImpl() {
message_loop_ = NULL;
}
virtual void run() {
bool old_state = message_loop_->NestableTasksAllowed();
message_loop_->SetNestableTasksAllowed(true);
message_loop_->Run();
message_loop_->SetNestableTasksAllowed(old_state);
}
virtual void quitNow() {
message_loop_->QuitNow();
}
private:
MessageLoop* message_loop_;
};
} // namespace
// static
std::map<int, DevToolsAgent*> DevToolsAgent::agent_for_routing_id_;
DevToolsAgent::DevToolsAgent(int routing_id, RenderView* render_view)
: routing_id_(routing_id),
render_view_(render_view) {
agent_for_routing_id_[routing_id] = this;
CommandLine* cmd = CommandLine::ForCurrentProcess();
expose_v8_debugger_protocol_ =cmd->HasSwitch(switches::kRemoteShellPort);
}
DevToolsAgent::~DevToolsAgent() {
agent_for_routing_id_.erase(routing_id_);
}
void DevToolsAgent::OnNavigate() {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent) {
web_agent->didNavigate();
}
}
// Called on the Renderer thread.
bool DevToolsAgent::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(DevToolsAgent, message)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnAttach)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_FrontendLoaded, OnFrontendLoaded)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend,
OnDispatchOnInspectorBackend)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_InspectElement, OnInspectElement)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_SetApuAgentEnabled,
OnSetApuAgentEnabled)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void DevToolsAgent::sendMessageToInspectorFrontend(
const WebKit::WebString& message) {
IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
routing_id_,
DevToolsClientMsg_DispatchOnInspectorFrontend(message.utf8()));
render_view_->Send(m);
}
void DevToolsAgent::sendDebuggerOutput(const WebKit::WebString& data) {
IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
routing_id_,
DevToolsClientMsg_DebuggerOutput(data.utf8()));
render_view_->Send(m);
}
void DevToolsAgent::sendDispatchToAPU(const WebKit::WebString& data) {
IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
routing_id_,
DevToolsClientMsg_DispatchToAPU(data.utf8()));
render_view_->Send(m);
}
int DevToolsAgent::hostIdentifier() {
return routing_id_;
}
void DevToolsAgent::forceRepaint() {
render_view_->GenerateFullRepaint();
}
void DevToolsAgent::runtimeFeatureStateChanged(
const WebKit::WebString& feature,
bool enabled) {
render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
routing_id_,
feature.utf8(),
enabled ? "true" : "false"));
}
void DevToolsAgent::runtimePropertyChanged(
const WebKit::WebString& name,
const WebKit::WebString& value) {
render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
routing_id_,
name.utf8(),
value.utf8()));
}
WebCString DevToolsAgent::injectedScriptSource() {
base::StringPiece injectjsWebkit =
webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
return WebCString(injectjsWebkit.data(), injectjsWebkit.length());
}
WebCString DevToolsAgent::debuggerScriptSource() {
base::StringPiece debuggerScriptjs =
webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS);
return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length());
}
WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop*
DevToolsAgent::createClientMessageLoop() {
return new WebKitClientMessageLoopImpl();
}
bool DevToolsAgent::exposeV8DebuggerProtocol() {
return expose_v8_debugger_protocol_;
}
// static
DevToolsAgent* DevToolsAgent::FromHostId(int host_id) {
std::map<int, DevToolsAgent*>::iterator it =
agent_for_routing_id_.find(host_id);
if (it != agent_for_routing_id_.end()) {
return it->second;
}
return NULL;
}
void DevToolsAgent::OnAttach(
const DevToolsRuntimeProperties& runtime_properties) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent) {
web_agent->attach();
for (DevToolsRuntimeProperties::const_iterator it =
runtime_properties.begin();
it != runtime_properties.end(); ++it) {
web_agent->setRuntimeFeatureEnabled(WebString::fromUTF8(it->first),
it->second == "true");
}
}
}
void DevToolsAgent::OnDetach() {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->detach();
}
void DevToolsAgent::OnFrontendLoaded() {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->frontendLoaded();
}
void DevToolsAgent::OnDispatchOnInspectorBackend(const std::string& message) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->dispatchOnInspectorBackend(WebString::fromUTF8(message));
}
void DevToolsAgent::OnInspectElement(int x, int y) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent) {
web_agent->attach();
web_agent->inspectElementAt(WebPoint(x, y));
}
}
void DevToolsAgent::OnSetApuAgentEnabled(bool enabled) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->setRuntimeFeatureEnabled("apu-agent", enabled);
}
WebDevToolsAgent* DevToolsAgent::GetWebAgent() {
WebView* web_view = render_view_->webview();
if (!web_view)
return NULL;
return web_view->devToolsAgent();
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/devtools_agent.h"
#include <map>
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent_filter.h"
#include "chrome/renderer/render_view.h"
#include "grit/webkit_chromium_resources.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsAgentClient;
using WebKit::WebPoint;
using WebKit::WebString;
using WebKit::WebCString;
using WebKit::WebVector;
using WebKit::WebView;
namespace {
class WebKitClientMessageLoopImpl
: public WebDevToolsAgentClient::WebKitClientMessageLoop {
public:
WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { }
virtual ~WebKitClientMessageLoopImpl() {
message_loop_ = NULL;
}
virtual void run() {
bool old_state = message_loop_->NestableTasksAllowed();
message_loop_->SetNestableTasksAllowed(true);
message_loop_->Run();
message_loop_->SetNestableTasksAllowed(old_state);
}
virtual void quitNow() {
message_loop_->QuitNow();
}
private:
MessageLoop* message_loop_;
};
} // namespace
// static
std::map<int, DevToolsAgent*> DevToolsAgent::agent_for_routing_id_;
DevToolsAgent::DevToolsAgent(int routing_id, RenderView* render_view)
: routing_id_(routing_id),
render_view_(render_view) {
agent_for_routing_id_[routing_id] = this;
CommandLine* cmd = CommandLine::ForCurrentProcess();
expose_v8_debugger_protocol_ =cmd->HasSwitch(switches::kRemoteShellPort);
}
DevToolsAgent::~DevToolsAgent() {
agent_for_routing_id_.erase(routing_id_);
}
void DevToolsAgent::OnNavigate() {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent) {
web_agent->didNavigate();
}
}
// Called on the Renderer thread.
bool DevToolsAgent::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(DevToolsAgent, message)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnAttach)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_FrontendLoaded, OnFrontendLoaded)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend,
OnDispatchOnInspectorBackend)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_InspectElement, OnInspectElement)
IPC_MESSAGE_HANDLER(DevToolsAgentMsg_SetApuAgentEnabled,
OnSetApuAgentEnabled)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void DevToolsAgent::sendMessageToInspectorFrontend(
const WebKit::WebString& message) {
IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
routing_id_,
DevToolsClientMsg_DispatchOnInspectorFrontend(message.utf8()));
render_view_->Send(m);
}
void DevToolsAgent::sendDebuggerOutput(const WebKit::WebString& data) {
IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
routing_id_,
DevToolsClientMsg_DebuggerOutput(data.utf8()));
render_view_->Send(m);
}
void DevToolsAgent::sendDispatchToAPU(const WebKit::WebString& data) {
IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
routing_id_,
DevToolsClientMsg_DispatchToAPU(data.utf8()));
render_view_->Send(m);
}
int DevToolsAgent::hostIdentifier() {
return routing_id_;
}
void DevToolsAgent::forceRepaint() {
render_view_->GenerateFullRepaint();
}
void DevToolsAgent::runtimeFeatureStateChanged(
const WebKit::WebString& feature,
bool enabled) {
render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
routing_id_,
feature.utf8(),
enabled ? "true" : "false"));
}
void DevToolsAgent::runtimePropertyChanged(
const WebKit::WebString& name,
const WebKit::WebString& value) {
render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
routing_id_,
name.utf8(),
value.utf8()));
}
WebCString DevToolsAgent::injectedScriptSource() {
base::StringPiece injectjsWebkit =
webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
return WebCString(injectjsWebkit.data(), injectjsWebkit.length());
}
WebCString DevToolsAgent::debuggerScriptSource() {
base::StringPiece debuggerScriptjs =
webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS);
return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length());
}
WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop*
DevToolsAgent::createClientMessageLoop() {
return new WebKitClientMessageLoopImpl();
}
bool DevToolsAgent::exposeV8DebuggerProtocol() {
return expose_v8_debugger_protocol_;
}
// static
DevToolsAgent* DevToolsAgent::FromHostId(int host_id) {
std::map<int, DevToolsAgent*>::iterator it =
agent_for_routing_id_.find(host_id);
if (it != agent_for_routing_id_.end()) {
return it->second;
}
return NULL;
}
void DevToolsAgent::OnAttach(
const DevToolsRuntimeProperties& runtime_properties) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent) {
web_agent->attach();
for (DevToolsRuntimeProperties::const_iterator it =
runtime_properties.begin();
it != runtime_properties.end(); ++it) {
web_agent->setRuntimeProperty(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
}
}
}
void DevToolsAgent::OnDetach() {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->detach();
}
void DevToolsAgent::OnFrontendLoaded() {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->frontendLoaded();
}
void DevToolsAgent::OnDispatchOnInspectorBackend(const std::string& message) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->dispatchOnInspectorBackend(WebString::fromUTF8(message));
}
void DevToolsAgent::OnInspectElement(int x, int y) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent) {
web_agent->attach();
web_agent->inspectElementAt(WebPoint(x, y));
}
}
void DevToolsAgent::OnSetApuAgentEnabled(bool enabled) {
WebDevToolsAgent* web_agent = GetWebAgent();
if (web_agent)
web_agent->setRuntimeProperty("apu-agent", enabled ?
WebString::fromUTF8("true") : WebString::fromUTF8("false"));
}
WebDevToolsAgent* DevToolsAgent::GetWebAgent() {
WebView* web_view = render_view_->webview();
if (!web_view)
return NULL;
return web_view->devToolsAgent();
}
|
complete migration to runtime properties started upstream.
|
DevTools: complete migration to runtime properties started upstream.
Review URL: http://codereview.chromium.org/3132025
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@56663 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
248e1623b3943775a94ca3cee125f02788549e3e
|
chrome/renderer/pepper_devices.cc
|
chrome/renderer/pepper_devices.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/pepper_devices.h"
#include "chrome/renderer/webplugin_delegate_pepper.h"
#include "skia/ext/platform_canvas.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/webplugin.h"
namespace {
const uint32 kBytesPerPixel = 4; // Only 8888 RGBA for now.
} // namespace
int Graphics2DDeviceContext::next_buffer_id_ = 0;
Graphics2DDeviceContext::Graphics2DDeviceContext(
WebPluginDelegatePepper* plugin_delegate)
: plugin_delegate_(plugin_delegate) {
}
NPError Graphics2DDeviceContext::Initialize(
gfx::Rect window_rect, const NPDeviceContext2DConfig* config,
NPDeviceContext2D* context) {
int width = window_rect.width();
int height = window_rect.height();
uint32 buffer_size = width * height * kBytesPerPixel;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
transport_dib_.reset(TransportDIB::Create(buffer_size, ++next_buffer_id_));
if (!transport_dib_.get())
return NPERR_OUT_OF_MEMORY_ERROR;
canvas_.reset(transport_dib_->GetPlatformCanvas(width, height));
if (!canvas_.get())
return NPERR_OUT_OF_MEMORY_ERROR;
// Note that we need to get the address out of the bitmap rather than
// using plugin_buffer_->memory(). The memory() is when the bitmap data
// has had "Map" called on it. For Windows, this is separate than making a
// bitmap using the shared section.
const SkBitmap& plugin_bitmap =
canvas_->getTopPlatformDevice().accessBitmap(true);
SkAutoLockPixels locker(plugin_bitmap);
// TODO(brettw) this theoretically shouldn't be necessary. But the
// platform device on Windows will fill itself with green to help you
// catch areas you didn't paint.
plugin_bitmap.eraseARGB(0, 0, 0, 0);
// Save the canvas to the output context structure and save the
// OpenPaintContext for future reference.
context->region = plugin_bitmap.getAddr32(0, 0);
context->stride = width * kBytesPerPixel;
context->dirty.left = 0;
context->dirty.top = 0;
context->dirty.right = width;
context->dirty.bottom = height;
return NPERR_NO_ERROR;
}
NPError Graphics2DDeviceContext::Flush(SkBitmap* committed_bitmap,
NPDeviceContext2D* context,
NPDeviceFlushContextCallbackPtr callback,
NPP id, void* user_data) {
// Draw the bitmap to the backing store.
//
// TODO(brettw) we can optimize this in the case where the entire canvas is
// updated by actually taking ownership of the buffer and not telling the
// plugin we're done using it. This wat we can avoid the copy when the entire
// canvas has been updated.
SkIRect src_rect = { context->dirty.left,
context->dirty.top,
context->dirty.right,
context->dirty.bottom };
SkRect dest_rect = { SkIntToScalar(context->dirty.left),
SkIntToScalar(context->dirty.top),
SkIntToScalar(context->dirty.right),
SkIntToScalar(context->dirty.bottom) };
SkCanvas committed_canvas(*committed_bitmap);
// We want to replace the contents of the bitmap rather than blend.
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
committed_canvas.drawBitmapRect(
canvas_->getTopPlatformDevice().accessBitmap(false),
&src_rect, dest_rect, &paint);
committed_bitmap->setIsOpaque(false);
// Cause the updated part of the screen to be repainted. This will happen
// asynchronously.
// TODO(brettw) is this the coorect coordinate system?
gfx::Rect dest_gfx_rect(context->dirty.left, context->dirty.top,
context->dirty.right - context->dirty.left,
context->dirty.bottom - context->dirty.top);
plugin_delegate_->instance()->webplugin()->InvalidateRect(dest_gfx_rect);
// Save the callback to execute later. See |unpainted_flush_callbacks_| in
// the header file.
if (callback) {
unpainted_flush_callbacks_.push_back(
FlushCallbackData(callback, id, context, user_data));
}
return NPERR_NO_ERROR;
}
void Graphics2DDeviceContext::RenderViewInitiatedPaint() {
// Move all "unpainted" callbacks to the painted state. See
// |unpainted_flush_callbacks_| in the header for more.
std::copy(unpainted_flush_callbacks_.begin(),
unpainted_flush_callbacks_.end(),
std::back_inserter(painted_flush_callbacks_));
unpainted_flush_callbacks_.clear();
}
void Graphics2DDeviceContext::RenderViewFlushedPaint() {
// Notify all "painted" callbacks. See |unpainted_flush_callbacks_| in the
// header for more.
for (size_t i = 0; i < painted_flush_callbacks_.size(); i++) {
const FlushCallbackData& data = painted_flush_callbacks_[i];
data.function(data.npp, data.context, NPERR_NO_ERROR, data.user_data);
}
painted_flush_callbacks_.clear();
}
AudioDeviceContext::~AudioDeviceContext() {
if (stream_id_) {
OnDestroy();
}
}
NPError AudioDeviceContext::Initialize(AudioMessageFilter* filter,
const NPDeviceContextAudioConfig* config,
NPDeviceContextAudio* context) {
DCHECK(filter);
// Make sure we don't call init more than once.
DCHECK_EQ(0, stream_id_);
if (!config || !context) {
return NPERR_INVALID_PARAM;
}
filter_ = filter;
context_= context;
ViewHostMsg_Audio_CreateStream_Params params;
params.format = AudioManager::AUDIO_PCM_LINEAR;
params.channels = config->outputChannelMap;
params.sample_rate = config->sampleRate;
switch (config->sampleType) {
case NPAudioSampleTypeInt16:
params.bits_per_sample = 16;
break;
case NPAudioSampleTypeFloat32:
params.bits_per_sample = 32;
break;
default:
return NPERR_INVALID_PARAM;
}
context->config = *config;
params.packet_size = config->sampleFrameCount * config->outputChannelMap
* (params.bits_per_sample >> 3);
// TODO(neb): figure out if this number is grounded in reality
params.buffer_capacity = params.packet_size * 3;
stream_id_ = filter_->AddDelegate(this);
filter->Send(new ViewHostMsg_CreateAudioStream(0, stream_id_, params, true));
return NPERR_NO_ERROR;
}
void AudioDeviceContext::OnDestroy() {
// Make sure we don't call destroy more than once.
DCHECK_NE(0, stream_id_);
filter_->RemoveDelegate(stream_id_);
filter_->Send(new ViewHostMsg_CloseAudioStream(0, stream_id_));
stream_id_ = 0;
if (audio_thread_.get()) {
socket_->Close();
audio_thread_->Join();
}
}
void AudioDeviceContext::OnRequestPacket(
uint32 bytes_in_buffer, const base::Time& message_timestamp) {
FireAudioCallback();
filter_->Send(new ViewHostMsg_NotifyAudioPacketReady(0, stream_id_,
shared_memory_size_));
}
void AudioDeviceContext::OnStateChanged(
const ViewMsg_AudioStreamState_Params& state) {
}
void AudioDeviceContext::OnCreated(
base::SharedMemoryHandle handle, uint32 length) {
#if defined(OS_WIN)
DCHECK(handle);
#else
DCHECK_NE(-1, handle.fd);
#endif
DCHECK(length);
DCHECK(context_);
shared_memory_.reset(new base::SharedMemory(handle, false));
shared_memory_->Map(length);
shared_memory_size_ = length;
context_->outBuffer = shared_memory_->memory();
FireAudioCallback();
filter_->Send(new ViewHostMsg_PlayAudioStream(0, stream_id_));
}
void AudioDeviceContext::OnLowLatencyCreated(
base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle,
uint32 length) {
#if defined(OS_WIN)
DCHECK(handle);
DCHECK(socket_handle);
#else
DCHECK_NE(-1, handle.fd);
DCHECK_NE(-1, socket_handle);
#endif
DCHECK(length);
DCHECK(context_);
DCHECK(!audio_thread_.get());
shared_memory_.reset(new base::SharedMemory(handle, false));
shared_memory_->Map(length);
shared_memory_size_ = length;
context_->outBuffer = shared_memory_->memory();
socket_.reset(new base::SyncSocket(socket_handle));
// Allow the client to pre-populate the buffer.
FireAudioCallback();
if (context_->config.startThread) {
audio_thread_.reset(
new base::DelegateSimpleThread(this, "plugin_audio_thread"));
audio_thread_->Start();
}
filter_->Send(new ViewHostMsg_PlayAudioStream(0, stream_id_));
}
void AudioDeviceContext::OnVolume(double volume) {
}
void AudioDeviceContext::Run() {
int pending_data;
while (sizeof(pending_data) == socket_->Receive(&pending_data,
sizeof(pending_data)) &&
pending_data >= 0) {
FireAudioCallback();
}
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/pepper_devices.h"
#include "chrome/renderer/webplugin_delegate_pepper.h"
#include "skia/ext/platform_canvas.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/webplugin.h"
namespace {
const uint32 kBytesPerPixel = 4; // Only 8888 RGBA for now.
} // namespace
int Graphics2DDeviceContext::next_buffer_id_ = 0;
Graphics2DDeviceContext::Graphics2DDeviceContext(
WebPluginDelegatePepper* plugin_delegate)
: plugin_delegate_(plugin_delegate) {
}
NPError Graphics2DDeviceContext::Initialize(
gfx::Rect window_rect, const NPDeviceContext2DConfig* config,
NPDeviceContext2D* context) {
int width = window_rect.width();
int height = window_rect.height();
uint32 buffer_size = width * height * kBytesPerPixel;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
// On the Mac, there is no clean way to create a TransportDIB::Handle and
// then Map() it. Using TransportDIB::Create() followed by
// TransportDIB::Map() will leak a TransportDIB object (you can't Create()
// then Map(), then delete because the file descriptor used by the underlying
// shared memory object gets closed.) Work around this issue by creating
// a SharedMemory object then pass that into TransportDIB::Map().
scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory());
if (!shared_memory->Create(L"", false /* read write */,
false /* do not open existing */, buffer_size)) {
return NPERR_OUT_OF_MEMORY_ERROR;
}
TransportDIB::Handle dib_handle;
shared_memory->GiveToProcess(0 /* pid, not needed */, &dib_handle);
transport_dib_.reset(TransportDIB::Map(dib_handle));
#else
transport_dib_.reset(TransportDIB::Create(buffer_size, ++next_buffer_id_));
if (!transport_dib_.get())
return NPERR_OUT_OF_MEMORY_ERROR;
#endif // defined(OS_MACOSX)
canvas_.reset(transport_dib_->GetPlatformCanvas(width, height));
if (!canvas_.get())
return NPERR_OUT_OF_MEMORY_ERROR;
// Note that we need to get the address out of the bitmap rather than
// using plugin_buffer_->memory(). The memory() is when the bitmap data
// has had "Map" called on it. For Windows, this is separate than making a
// bitmap using the shared section.
const SkBitmap& plugin_bitmap =
canvas_->getTopPlatformDevice().accessBitmap(true);
SkAutoLockPixels locker(plugin_bitmap);
// TODO(brettw) this theoretically shouldn't be necessary. But the
// platform device on Windows will fill itself with green to help you
// catch areas you didn't paint.
plugin_bitmap.eraseARGB(0, 0, 0, 0);
// Save the canvas to the output context structure and save the
// OpenPaintContext for future reference.
context->region = plugin_bitmap.getAddr32(0, 0);
context->stride = width * kBytesPerPixel;
context->dirty.left = 0;
context->dirty.top = 0;
context->dirty.right = width;
context->dirty.bottom = height;
return NPERR_NO_ERROR;
}
NPError Graphics2DDeviceContext::Flush(SkBitmap* committed_bitmap,
NPDeviceContext2D* context,
NPDeviceFlushContextCallbackPtr callback,
NPP id, void* user_data) {
// Draw the bitmap to the backing store.
//
// TODO(brettw) we can optimize this in the case where the entire canvas is
// updated by actually taking ownership of the buffer and not telling the
// plugin we're done using it. This wat we can avoid the copy when the entire
// canvas has been updated.
SkIRect src_rect = { context->dirty.left,
context->dirty.top,
context->dirty.right,
context->dirty.bottom };
SkRect dest_rect = { SkIntToScalar(context->dirty.left),
SkIntToScalar(context->dirty.top),
SkIntToScalar(context->dirty.right),
SkIntToScalar(context->dirty.bottom) };
SkCanvas committed_canvas(*committed_bitmap);
// We want to replace the contents of the bitmap rather than blend.
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
committed_canvas.drawBitmapRect(
canvas_->getTopPlatformDevice().accessBitmap(false),
&src_rect, dest_rect, &paint);
committed_bitmap->setIsOpaque(false);
// Cause the updated part of the screen to be repainted. This will happen
// asynchronously.
// TODO(brettw) is this the coorect coordinate system?
gfx::Rect dest_gfx_rect(context->dirty.left, context->dirty.top,
context->dirty.right - context->dirty.left,
context->dirty.bottom - context->dirty.top);
plugin_delegate_->instance()->webplugin()->InvalidateRect(dest_gfx_rect);
// Save the callback to execute later. See |unpainted_flush_callbacks_| in
// the header file.
if (callback) {
unpainted_flush_callbacks_.push_back(
FlushCallbackData(callback, id, context, user_data));
}
return NPERR_NO_ERROR;
}
void Graphics2DDeviceContext::RenderViewInitiatedPaint() {
// Move all "unpainted" callbacks to the painted state. See
// |unpainted_flush_callbacks_| in the header for more.
std::copy(unpainted_flush_callbacks_.begin(),
unpainted_flush_callbacks_.end(),
std::back_inserter(painted_flush_callbacks_));
unpainted_flush_callbacks_.clear();
}
void Graphics2DDeviceContext::RenderViewFlushedPaint() {
// Notify all "painted" callbacks. See |unpainted_flush_callbacks_| in the
// header for more.
for (size_t i = 0; i < painted_flush_callbacks_.size(); i++) {
const FlushCallbackData& data = painted_flush_callbacks_[i];
data.function(data.npp, data.context, NPERR_NO_ERROR, data.user_data);
}
painted_flush_callbacks_.clear();
}
AudioDeviceContext::~AudioDeviceContext() {
if (stream_id_) {
OnDestroy();
}
}
NPError AudioDeviceContext::Initialize(AudioMessageFilter* filter,
const NPDeviceContextAudioConfig* config,
NPDeviceContextAudio* context) {
DCHECK(filter);
// Make sure we don't call init more than once.
DCHECK_EQ(0, stream_id_);
if (!config || !context) {
return NPERR_INVALID_PARAM;
}
filter_ = filter;
context_= context;
ViewHostMsg_Audio_CreateStream_Params params;
params.format = AudioManager::AUDIO_PCM_LINEAR;
params.channels = config->outputChannelMap;
params.sample_rate = config->sampleRate;
switch (config->sampleType) {
case NPAudioSampleTypeInt16:
params.bits_per_sample = 16;
break;
case NPAudioSampleTypeFloat32:
params.bits_per_sample = 32;
break;
default:
return NPERR_INVALID_PARAM;
}
context->config = *config;
params.packet_size = config->sampleFrameCount * config->outputChannelMap
* (params.bits_per_sample >> 3);
// TODO(neb): figure out if this number is grounded in reality
params.buffer_capacity = params.packet_size * 3;
stream_id_ = filter_->AddDelegate(this);
filter->Send(new ViewHostMsg_CreateAudioStream(0, stream_id_, params, true));
return NPERR_NO_ERROR;
}
void AudioDeviceContext::OnDestroy() {
// Make sure we don't call destroy more than once.
DCHECK_NE(0, stream_id_);
filter_->RemoveDelegate(stream_id_);
filter_->Send(new ViewHostMsg_CloseAudioStream(0, stream_id_));
stream_id_ = 0;
if (audio_thread_.get()) {
socket_->Close();
audio_thread_->Join();
}
}
void AudioDeviceContext::OnRequestPacket(
uint32 bytes_in_buffer, const base::Time& message_timestamp) {
FireAudioCallback();
filter_->Send(new ViewHostMsg_NotifyAudioPacketReady(0, stream_id_,
shared_memory_size_));
}
void AudioDeviceContext::OnStateChanged(
const ViewMsg_AudioStreamState_Params& state) {
}
void AudioDeviceContext::OnCreated(
base::SharedMemoryHandle handle, uint32 length) {
#if defined(OS_WIN)
DCHECK(handle);
#else
DCHECK_NE(-1, handle.fd);
#endif
DCHECK(length);
DCHECK(context_);
shared_memory_.reset(new base::SharedMemory(handle, false));
shared_memory_->Map(length);
shared_memory_size_ = length;
context_->outBuffer = shared_memory_->memory();
FireAudioCallback();
filter_->Send(new ViewHostMsg_PlayAudioStream(0, stream_id_));
}
void AudioDeviceContext::OnLowLatencyCreated(
base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle,
uint32 length) {
#if defined(OS_WIN)
DCHECK(handle);
DCHECK(socket_handle);
#else
DCHECK_NE(-1, handle.fd);
DCHECK_NE(-1, socket_handle);
#endif
DCHECK(length);
DCHECK(context_);
DCHECK(!audio_thread_.get());
shared_memory_.reset(new base::SharedMemory(handle, false));
shared_memory_->Map(length);
shared_memory_size_ = length;
context_->outBuffer = shared_memory_->memory();
socket_.reset(new base::SyncSocket(socket_handle));
// Allow the client to pre-populate the buffer.
FireAudioCallback();
if (context_->config.startThread) {
audio_thread_.reset(
new base::DelegateSimpleThread(this, "plugin_audio_thread"));
audio_thread_->Start();
}
filter_->Send(new ViewHostMsg_PlayAudioStream(0, stream_id_));
}
void AudioDeviceContext::OnVolume(double volume) {
}
void AudioDeviceContext::Run() {
int pending_data;
while (sizeof(pending_data) == socket_->Receive(&pending_data,
sizeof(pending_data)) &&
pending_data >= 0) {
FireAudioCallback();
}
}
|
Fix Pepper 2D device init on Mac, so that it work with NaCl modules as well as with trusted Pepper plugins. The shared memory was not being used to create the skia bitmap due to a missing mmap() call. Adding this call (via TransportDIB::Map()) generates the right shared mem region.
|
Fix Pepper 2D device init on Mac, so that it work with NaCl modules as well as
with trusted Pepper plugins. The shared memory was not being used to create
the skia bitmap due to a missing mmap() call. Adding this call (via
TransportDIB::Map()) generates the right shared mem region.
Note: this is an interim fix. Really, the browser should make the TransportDIB
as it does onthe Mac for the GPU plugin.
BUG=40701
TEST=Run any Pepper 2D application as a .nexe
Review URL: http://codereview.chromium.org/1542016
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@43873 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,robclark/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,zcbenz/cefode-chromium,dednal/chromium.src,ltilve/chromium,markYoungH/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,patrickm/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,rogerwang/chromium,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,rogerwang/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,anirudhSK/chromium,dushu1203/chromium.src,robclark/chromium,jaruba/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,keishi/chromium,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,robclark/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,rogerwang/chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,robclark/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,robclark/chromium,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,rogerwang/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,keishi/chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,dednal/chromium.src,keishi/chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,robclark/chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,keishi/chromium,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,anirudhSK/chromium,littlstar/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,robclark/chromium,mohamed--abdel-maksoud/chromium.src,keishi/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,keishi/chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,robclark/chromium,ltilve/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,rogerwang/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,patrickm/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,rogerwang/chromium,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,patrickm/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,Jonekee/chromium.src,M4sse/chromium.src,keishi/chromium,ltilve/chromium,Chilledheart/chromium,keishi/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,rogerwang/chromium,dednal/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,robclark/chromium,Chilledheart/chromium
|
68d3c92160825cadaf2d982777a19b4bcf3f5167
|
cintex/src/CINTTypedefBuilder.cxx
|
cintex/src/CINTTypedefBuilder.cxx
|
// @(#)root/cintex:$Name: $:$Id: CINTTypedefBuilder.cxx,v 1.9 2006/06/13 08:19:01 brun Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT {
namespace Cintex {
int CINTTypedefBuilder::Setup(const Type& t) {
if ( t.IsTypedef() ) {
std::string nam = CintName(t.Name(SCOPED));
Type rt(t);
Scope scope = rt.DeclaringScope();
CINTScopeBuilder::Setup( scope );
while ( rt.IsTypedef() ) rt = rt.ToType();
Indirection indir = IndirectionGet(rt);
Scope rscope = indir.second.DeclaringScope();
if ( scope != rscope ) {
if ( rscope ) CINTScopeBuilder::Setup(rscope);
else {
rscope = Scope::ByName(Tools::GetScopeName(indir.second.Name(SCOPED)));
CINTScopeBuilder::Setup(rscope);
}
}
if( -1 != G__defined_typename(nam.c_str()) ) return -1;
if ( Cintex::Debug() ) {
std::cout << "Building typedef " << nam << std::endl;
}
int rtypenum;
int rtagnum;
CintType(rt, rtypenum, rtagnum );
int stagnum = -1;
if ( !scope.IsTopScope() ) stagnum = ::G__defined_tagname(scope.Name(SCOPED).c_str(), 1);
int r = ::G__search_typename2( t.Name().c_str(), rtypenum, rtagnum, 0, stagnum);
::G__setnewtype(-1,NULL,0);
return r;
}
return -1;
}
}
}
|
// @(#)root/cintex:$Name: $:$Id: CINTTypedefBuilder.cxx,v 1.10 2006/06/15 12:07:18 brun Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT {
namespace Cintex {
int CINTTypedefBuilder::Setup(const Type& t) {
if ( t.IsTypedef() ) {
std::string nam = CintName(t.Name(SCOPED));
Type rt(t);
Scope scope = rt.DeclaringScope();
CINTScopeBuilder::Setup( scope );
while ( rt.IsTypedef() ) rt = rt.ToType();
Indirection indir = IndirectionGet(rt);
Scope rscope = indir.second.DeclaringScope();
if ( scope != rscope ) {
if ( rscope ) CINTScopeBuilder::Setup(rscope);
else {
rscope = Scope::ByName(Tools::GetScopeName(indir.second.Name(SCOPED)));
CINTScopeBuilder::Setup(rscope);
}
}
if( -1 != G__defined_typename(nam.c_str()) ) return -1;
if ( Cintex::Debug() ) {
std::cout << "Building typedef " << nam << std::endl;
}
int rtypenum;
int rtagnum;
CintType(rt, rtypenum, rtagnum );
int stagnum = -1;
if ( !scope.IsTopScope() ) stagnum = ::G__defined_tagname(CintName(scope.Name(SCOPED)).c_str(), 1);
int r = ::G__search_typename2( t.Name().c_str(), rtypenum, rtagnum, 0, stagnum);
::G__setnewtype(-1,NULL,0);
return r;
}
return -1;
}
}
}
|
convert declaring scope of a typedef to the Cint conventions
|
convert declaring scope of a typedef to the Cint conventions
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@15587 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
sbinet/cxx-root,lgiommi/root,mattkretz/root,kirbyherm/root-r-tools,strykejern/TTreeReader,tc3t/qoot,esakellari/root,mhuwiler/rootauto,esakellari/my_root_for_test,mhuwiler/rootauto,0x0all/ROOT,Dr15Jones/root,dfunke/root,ffurano/root5,lgiommi/root,sawenzel/root,dfunke/root,cxx-hep/root-cern,gganis/root,gbitzes/root,mkret2/root,evgeny-boger/root,esakellari/root,pspe/root,veprbl/root,zzxuanyuan/root,mattkretz/root,dfunke/root,davidlt/root,thomaskeck/root,zzxuanyuan/root,olifre/root,buuck/root,satyarth934/root,Dr15Jones/root,simonpf/root,kirbyherm/root-r-tools,georgtroska/root,vukasinmilosevic/root,BerserkerTroll/root,dfunke/root,vukasinmilosevic/root,bbockelm/root,Dr15Jones/root,satyarth934/root,sirinath/root,dfunke/root,sawenzel/root,BerserkerTroll/root,veprbl/root,veprbl/root,smarinac/root,olifre/root,sirinath/root,jrtomps/root,krafczyk/root,sirinath/root,BerserkerTroll/root,krafczyk/root,mhuwiler/rootauto,esakellari/root,dfunke/root,perovic/root,mhuwiler/rootauto,satyarth934/root,gbitzes/root,satyarth934/root,krafczyk/root,strykejern/TTreeReader,nilqed/root,omazapa/root-old,0x0all/ROOT,kirbyherm/root-r-tools,Dr15Jones/root,zzxuanyuan/root-compressor-dummy,omazapa/root,esakellari/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,tc3t/qoot,perovic/root,perovic/root,vukasinmilosevic/root,thomaskeck/root,davidlt/root,0x0all/ROOT,tc3t/qoot,root-mirror/root,olifre/root,Y--/root,agarciamontoro/root,arch1tect0r/root,buuck/root,gganis/root,CristinaCristescu/root,mhuwiler/rootauto,nilqed/root,omazapa/root,arch1tect0r/root,buuck/root,esakellari/my_root_for_test,jrtomps/root,beniz/root,Duraznos/root,nilqed/root,veprbl/root,omazapa/root,vukasinmilosevic/root,arch1tect0r/root,beniz/root,davidlt/root,agarciamontoro/root,jrtomps/root,Y--/root,thomaskeck/root,davidlt/root,BerserkerTroll/root,Duraznos/root,omazapa/root-old,omazapa/root,pspe/root,mhuwiler/rootauto,cxx-hep/root-cern,sbinet/cxx-root,omazapa/root-old,simonpf/root,satyarth934/root,root-mirror/root,smarinac/root,sawenzel/root,pspe/root,abhinavmoudgil95/root,olifre/root,agarciamontoro/root,beniz/root,esakellari/root,alexschlueter/cern-root,ffurano/root5,Y--/root,BerserkerTroll/root,krafczyk/root,dfunke/root,mattkretz/root,Duraznos/root,buuck/root,esakellari/my_root_for_test,arch1tect0r/root,georgtroska/root,sawenzel/root,evgeny-boger/root,Dr15Jones/root,abhinavmoudgil95/root,cxx-hep/root-cern,gganis/root,kirbyherm/root-r-tools,nilqed/root,simonpf/root,sirinath/root,abhinavmoudgil95/root,jrtomps/root,krafczyk/root,omazapa/root,dfunke/root,thomaskeck/root,Dr15Jones/root,esakellari/root,gbitzes/root,sirinath/root,beniz/root,omazapa/root-old,BerserkerTroll/root,pspe/root,Y--/root,lgiommi/root,gbitzes/root,ffurano/root5,veprbl/root,sirinath/root,bbockelm/root,davidlt/root,cxx-hep/root-cern,zzxuanyuan/root,evgeny-boger/root,strykejern/TTreeReader,satyarth934/root,davidlt/root,zzxuanyuan/root-compressor-dummy,esakellari/root,mhuwiler/rootauto,nilqed/root,lgiommi/root,krafczyk/root,Y--/root,esakellari/root,satyarth934/root,sawenzel/root,zzxuanyuan/root,tc3t/qoot,root-mirror/root,jrtomps/root,esakellari/my_root_for_test,thomaskeck/root,mkret2/root,mkret2/root,olifre/root,gganis/root,tc3t/qoot,karies/root,satyarth934/root,Y--/root,abhinavmoudgil95/root,buuck/root,omazapa/root-old,0x0all/ROOT,veprbl/root,abhinavmoudgil95/root,Duraznos/root,beniz/root,sirinath/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,bbockelm/root,georgtroska/root,tc3t/qoot,mkret2/root,jrtomps/root,thomaskeck/root,vukasinmilosevic/root,cxx-hep/root-cern,tc3t/qoot,gbitzes/root,vukasinmilosevic/root,cxx-hep/root-cern,veprbl/root,olifre/root,omazapa/root-old,mkret2/root,sbinet/cxx-root,Duraznos/root,georgtroska/root,strykejern/TTreeReader,pspe/root,arch1tect0r/root,beniz/root,agarciamontoro/root,abhinavmoudgil95/root,perovic/root,krafczyk/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,zzxuanyuan/root,alexschlueter/cern-root,pspe/root,buuck/root,satyarth934/root,Y--/root,root-mirror/root,mattkretz/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,smarinac/root,sbinet/cxx-root,sirinath/root,evgeny-boger/root,arch1tect0r/root,cxx-hep/root-cern,gganis/root,arch1tect0r/root,karies/root,olifre/root,esakellari/my_root_for_test,georgtroska/root,sbinet/cxx-root,mkret2/root,mkret2/root,gbitzes/root,vukasinmilosevic/root,omazapa/root,zzxuanyuan/root,omazapa/root,smarinac/root,perovic/root,davidlt/root,esakellari/my_root_for_test,mhuwiler/rootauto,0x0all/ROOT,olifre/root,buuck/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,sirinath/root,davidlt/root,beniz/root,jrtomps/root,smarinac/root,omazapa/root,BerserkerTroll/root,CristinaCristescu/root,karies/root,simonpf/root,CristinaCristescu/root,olifre/root,nilqed/root,mkret2/root,alexschlueter/cern-root,sirinath/root,0x0all/ROOT,dfunke/root,CristinaCristescu/root,satyarth934/root,esakellari/my_root_for_test,Duraznos/root,mattkretz/root,alexschlueter/cern-root,tc3t/qoot,thomaskeck/root,mattkretz/root,veprbl/root,CristinaCristescu/root,evgeny-boger/root,CristinaCristescu/root,gbitzes/root,root-mirror/root,bbockelm/root,krafczyk/root,CristinaCristescu/root,olifre/root,zzxuanyuan/root,buuck/root,sawenzel/root,alexschlueter/cern-root,vukasinmilosevic/root,nilqed/root,Y--/root,arch1tect0r/root,jrtomps/root,omazapa/root-old,georgtroska/root,mkret2/root,nilqed/root,root-mirror/root,vukasinmilosevic/root,esakellari/root,davidlt/root,Duraznos/root,beniz/root,karies/root,davidlt/root,zzxuanyuan/root,veprbl/root,Y--/root,omazapa/root,Duraznos/root,perovic/root,omazapa/root,gganis/root,tc3t/qoot,beniz/root,strykejern/TTreeReader,thomaskeck/root,abhinavmoudgil95/root,Y--/root,simonpf/root,CristinaCristescu/root,veprbl/root,bbockelm/root,georgtroska/root,omazapa/root,bbockelm/root,mattkretz/root,agarciamontoro/root,gganis/root,olifre/root,gbitzes/root,jrtomps/root,beniz/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,root-mirror/root,lgiommi/root,gbitzes/root,0x0all/ROOT,georgtroska/root,esakellari/root,beniz/root,lgiommi/root,mhuwiler/rootauto,evgeny-boger/root,strykejern/TTreeReader,nilqed/root,simonpf/root,smarinac/root,georgtroska/root,Y--/root,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,krafczyk/root,Duraznos/root,CristinaCristescu/root,CristinaCristescu/root,0x0all/ROOT,satyarth934/root,lgiommi/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,pspe/root,kirbyherm/root-r-tools,simonpf/root,karies/root,smarinac/root,agarciamontoro/root,buuck/root,pspe/root,buuck/root,kirbyherm/root-r-tools,abhinavmoudgil95/root,omazapa/root-old,pspe/root,smarinac/root,georgtroska/root,krafczyk/root,Duraznos/root,BerserkerTroll/root,root-mirror/root,ffurano/root5,perovic/root,veprbl/root,mattkretz/root,thomaskeck/root,root-mirror/root,Duraznos/root,simonpf/root,abhinavmoudgil95/root,sbinet/cxx-root,agarciamontoro/root,lgiommi/root,vukasinmilosevic/root,root-mirror/root,sawenzel/root,ffurano/root5,simonpf/root,strykejern/TTreeReader,sbinet/cxx-root,evgeny-boger/root,CristinaCristescu/root,perovic/root,gbitzes/root,abhinavmoudgil95/root,mhuwiler/rootauto,bbockelm/root,simonpf/root,sawenzel/root,omazapa/root-old,gganis/root,evgeny-boger/root,perovic/root,BerserkerTroll/root,mkret2/root,jrtomps/root,ffurano/root5,agarciamontoro/root,dfunke/root,zzxuanyuan/root,sbinet/cxx-root,pspe/root,BerserkerTroll/root,arch1tect0r/root,smarinac/root,alexschlueter/cern-root,Dr15Jones/root,karies/root,sawenzel/root,root-mirror/root,karies/root,karies/root,esakellari/my_root_for_test,abhinavmoudgil95/root,sbinet/cxx-root,dfunke/root,karies/root,bbockelm/root,bbockelm/root,sbinet/cxx-root,mattkretz/root,bbockelm/root,smarinac/root,agarciamontoro/root,mkret2/root,nilqed/root,karies/root,jrtomps/root,lgiommi/root,bbockelm/root,sirinath/root,georgtroska/root,sbinet/cxx-root,omazapa/root-old,zzxuanyuan/root,evgeny-boger/root,gbitzes/root,zzxuanyuan/root,BerserkerTroll/root,evgeny-boger/root,gganis/root,perovic/root,esakellari/my_root_for_test,alexschlueter/cern-root,arch1tect0r/root,lgiommi/root,tc3t/qoot,esakellari/my_root_for_test,gganis/root,arch1tect0r/root,esakellari/root,simonpf/root,gganis/root,agarciamontoro/root,nilqed/root,zzxuanyuan/root,buuck/root,ffurano/root5,kirbyherm/root-r-tools,sawenzel/root,mattkretz/root,mattkretz/root,karies/root,pspe/root,lgiommi/root,davidlt/root,perovic/root,cxx-hep/root-cern
|
e9f090e8b2ca2eda3e9a1b1c3ba4acce843720ba
|
src/glsl/lower_output_reads.cpp
|
src/glsl/lower_output_reads.cpp
|
/*
* Copyright © 2012 Vincent Lejeune
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ir.h"
#include "program/hash_table.h"
/**
* \file lower_output_reads.cpp
*
* In GLSL, shader output variables (such as varyings) can be both read and
* written. However, on some hardware, reading an output register causes
* trouble.
*
* This pass creates temporary shadow copies of every (used) shader output,
* and replaces all accesses to use those instead. It also adds code to the
* main() function to copy the final values to the actual shader outputs.
*/
class output_read_remover : public ir_hierarchical_visitor {
protected:
/**
* A hash table mapping from the original ir_variable shader outputs
* (ir_var_out mode) to the new temporaries to be used instead.
*/
hash_table *replacements;
void *mem_ctx;
public:
output_read_remover();
~output_read_remover();
virtual ir_visitor_status visit(class ir_dereference_variable *);
virtual ir_visitor_status visit_leave(class ir_return *);
virtual ir_visitor_status visit_leave(class ir_function_signature *);
};
/**
* Hash function for the output variables - computes the hash of the name.
* NOTE: We're using the name string to ensure that the hash doesn't depend
* on any random factors, otherwise the output_read_remover could produce
* the random order of the assignments.
*
* NOTE: If you want to reuse this function please take into account that
* generally the names of the variables are non-unique.
*/
static unsigned
hash_table_var_hash(const void *key)
{
const ir_variable * var = static_cast<const ir_variable *>(key);
return hash_table_string_hash(var->name);
}
output_read_remover::output_read_remover()
{
mem_ctx = ralloc_context(NULL);
replacements =
hash_table_ctor(0, hash_table_var_hash, hash_table_pointer_compare);
}
output_read_remover::~output_read_remover()
{
hash_table_dtor(replacements);
ralloc_free(mem_ctx);
}
ir_visitor_status
output_read_remover::visit(ir_dereference_variable *ir)
{
if (ir->var->mode != ir_var_out)
return visit_continue;
ir_variable *temp = (ir_variable *) hash_table_find(replacements, ir->var);
/* If we don't have an existing temporary, create one. */
if (temp == NULL) {
void *var_ctx = ralloc_parent(ir->var);
temp = new(var_ctx) ir_variable(ir->var->type, ir->var->name,
ir_var_temporary);
hash_table_insert(replacements, temp, ir->var);
}
/* Update the dereference to use the temporary */
ir->var = temp;
return visit_continue;
}
/**
* Create an assignment to copy a temporary value back to the actual output.
*/
static ir_assignment *
copy(void *ctx, ir_variable *output, ir_variable *temp)
{
ir_dereference_variable *lhs = new(ctx) ir_dereference_variable(output);
ir_dereference_variable *rhs = new(ctx) ir_dereference_variable(temp);
return new(ctx) ir_assignment(lhs, rhs);
}
/** Insert a copy-back assignment before a "return" statement */
static void
emit_return_copy(const void *key, void *data, void *closure)
{
ir_return *ir = (ir_return *) closure;
ir->insert_before(copy(ir, (ir_variable *) key, (ir_variable *) data));
}
/** Insert a copy-back assignment at the end of the main() function */
static void
emit_main_copy(const void *key, void *data, void *closure)
{
ir_function_signature *sig = (ir_function_signature *) closure;
sig->body.push_tail(copy(sig, (ir_variable *) key, (ir_variable *) data));
}
ir_visitor_status
output_read_remover::visit_leave(ir_return *ir)
{
hash_table_call_foreach(replacements, emit_return_copy, ir);
return visit_continue;
}
ir_visitor_status
output_read_remover::visit_leave(ir_function_signature *sig)
{
if (strcmp(sig->function_name(), "main") != 0)
return visit_continue;
hash_table_call_foreach(replacements, emit_main_copy, sig);
return visit_continue;
}
void
lower_output_reads(exec_list *instructions)
{
output_read_remover v;
visit_list_elements(&v, instructions);
}
|
/*
* Copyright © 2012 Vincent Lejeune
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ir.h"
#include "program/hash_table.h"
/**
* \file lower_output_reads.cpp
*
* In GLSL, shader output variables (such as varyings) can be both read and
* written. However, on some hardware, reading an output register causes
* trouble.
*
* This pass creates temporary shadow copies of every (used) shader output,
* and replaces all accesses to use those instead. It also adds code to the
* main() function to copy the final values to the actual shader outputs.
*/
class output_read_remover : public ir_hierarchical_visitor {
protected:
/**
* A hash table mapping from the original ir_variable shader outputs
* (ir_var_out mode) to the new temporaries to be used instead.
*/
hash_table *replacements;
void *mem_ctx;
public:
output_read_remover();
~output_read_remover();
virtual ir_visitor_status visit(class ir_dereference_variable *);
virtual ir_visitor_status visit_leave(class ir_return *);
virtual ir_visitor_status visit_leave(class ir_function_signature *);
};
/**
* Hash function for the output variables - computes the hash of the name.
* NOTE: We're using the name string to ensure that the hash doesn't depend
* on any random factors, otherwise the output_read_remover could produce
* the random order of the assignments.
*
* NOTE: If you want to reuse this function please take into account that
* generally the names of the variables are non-unique.
*/
static unsigned
hash_table_var_hash(const void *key)
{
const ir_variable * var = static_cast<const ir_variable *>(key);
return hash_table_string_hash(var->name);
}
output_read_remover::output_read_remover()
{
mem_ctx = ralloc_context(NULL);
replacements =
hash_table_ctor(0, hash_table_var_hash, hash_table_pointer_compare);
}
output_read_remover::~output_read_remover()
{
hash_table_dtor(replacements);
ralloc_free(mem_ctx);
}
ir_visitor_status
output_read_remover::visit(ir_dereference_variable *ir)
{
if (ir->var->mode != ir_var_out)
return visit_continue;
ir_variable *temp = (ir_variable *) hash_table_find(replacements, ir->var);
/* If we don't have an existing temporary, create one. */
if (temp == NULL) {
void *var_ctx = ralloc_parent(ir->var);
temp = new(var_ctx) ir_variable(ir->var->type, ir->var->name,
ir_var_temporary);
hash_table_insert(replacements, temp, ir->var);
ir->var->insert_after(temp);
}
/* Update the dereference to use the temporary */
ir->var = temp;
return visit_continue;
}
/**
* Create an assignment to copy a temporary value back to the actual output.
*/
static ir_assignment *
copy(void *ctx, ir_variable *output, ir_variable *temp)
{
ir_dereference_variable *lhs = new(ctx) ir_dereference_variable(output);
ir_dereference_variable *rhs = new(ctx) ir_dereference_variable(temp);
return new(ctx) ir_assignment(lhs, rhs);
}
/** Insert a copy-back assignment before a "return" statement */
static void
emit_return_copy(const void *key, void *data, void *closure)
{
ir_return *ir = (ir_return *) closure;
ir->insert_before(copy(ir, (ir_variable *) key, (ir_variable *) data));
}
/** Insert a copy-back assignment at the end of the main() function */
static void
emit_main_copy(const void *key, void *data, void *closure)
{
ir_function_signature *sig = (ir_function_signature *) closure;
sig->body.push_tail(copy(sig, (ir_variable *) key, (ir_variable *) data));
}
ir_visitor_status
output_read_remover::visit_leave(ir_return *ir)
{
hash_table_call_foreach(replacements, emit_return_copy, ir);
return visit_continue;
}
ir_visitor_status
output_read_remover::visit_leave(ir_function_signature *sig)
{
if (strcmp(sig->function_name(), "main") != 0)
return visit_continue;
hash_table_call_foreach(replacements, emit_main_copy, sig);
return visit_continue;
}
void
lower_output_reads(exec_list *instructions)
{
output_read_remover v;
visit_list_elements(&v, instructions);
}
|
add new variable declaration in function body in lower_output_read
|
glsl: add new variable declaration in function body in lower_output_read
Reviewed-by: Kenneth Graunke <kenneth at whitecape.org>
|
C++
|
mit
|
zz85/glsl-optimizer,mapbox/glsl-optimizer,zeux/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,tokyovigilante/glsl-optimizer,zz85/glsl-optimizer,bkaradzic/glsl-optimizer,metora/MesaGLSLCompiler,mcanthony/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,jbarczak/glsl-optimizer,mapbox/glsl-optimizer,wolf96/glsl-optimizer,mcanthony/glsl-optimizer,zeux/glsl-optimizer,benaadams/glsl-optimizer,tokyovigilante/glsl-optimizer,mapbox/glsl-optimizer,jbarczak/glsl-optimizer,djreep81/glsl-optimizer,mcanthony/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,bkaradzic/glsl-optimizer,mcanthony/glsl-optimizer,djreep81/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,metora/MesaGLSLCompiler,bkaradzic/glsl-optimizer,zz85/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,bkaradzic/glsl-optimizer,wolf96/glsl-optimizer,tokyovigilante/glsl-optimizer,djreep81/glsl-optimizer,benaadams/glsl-optimizer,bkaradzic/glsl-optimizer,zz85/glsl-optimizer,dellis1972/glsl-optimizer,zeux/glsl-optimizer,tokyovigilante/glsl-optimizer,dellis1972/glsl-optimizer,wolf96/glsl-optimizer,mapbox/glsl-optimizer,wolf96/glsl-optimizer,tokyovigilante/glsl-optimizer,zz85/glsl-optimizer,zeux/glsl-optimizer,mapbox/glsl-optimizer,dellis1972/glsl-optimizer,zz85/glsl-optimizer,metora/MesaGLSLCompiler,zeux/glsl-optimizer,mcanthony/glsl-optimizer,benaadams/glsl-optimizer,benaadams/glsl-optimizer
|
b3a922a9ad6d370e7021981550118f83f11b071c
|
src/lib/operators/inclusion.cpp
|
src/lib/operators/inclusion.cpp
|
#include <annis/operators/inclusion.h>
#include <annis/wrapper.h>
using namespace annis;
Inclusion::Inclusion(const DB &db)
: db(db),
anyNodeAnno(Init::initAnnotation(db.getNodeNameStringID(), 0, db.getNamespaceStringID())),
tokHelper(db)
{
gsOrder = db.getGraphStorage(ComponentType::ORDERING, annis_ns, "");
gsLeftToken = db.getGraphStorage(ComponentType::LEFT_TOKEN, annis_ns, "");
gsRightToken = db.getGraphStorage(ComponentType::RIGHT_TOKEN, annis_ns, "");
}
bool Inclusion::filter(const Match &lhs, const Match &rhs)
{
nodeid_t lhsLeftToken = tokHelper.leftTokenForNode(lhs.node);
nodeid_t lhsRightToken = tokHelper.rightTokenForNode(lhs.node);
int spanLength = spanLength = gsOrder->distance(Init::initEdge(lhsLeftToken, lhsRightToken));
nodeid_t rhsLeftToken = tokHelper.leftTokenForNode(rhs.node);
nodeid_t rhsRightToken = tokHelper.rightTokenForNode(rhs.node);
if(gsOrder->isConnected(Init::initEdge(lhsLeftToken, rhsLeftToken), 0, spanLength)
&& gsOrder->isConnected(Init::initEdge(rhsRightToken, lhsRightToken), 0, spanLength)
)
{
return true;
}
return false;
}
std::unique_ptr<AnnoIt> Inclusion::retrieveMatches(const annis::Match &lhs)
{
std::unique_ptr<ListWrapper> w = std::make_unique<ListWrapper>();
nodeid_t leftToken;
nodeid_t rightToken;
int spanLength = 0;
if(db.nodeAnnos.getNodeAnnotation(lhs.node, annis_ns, annis_tok).first)
{
// is token
leftToken = lhs.node;
rightToken = lhs.node;
}
else
{
leftToken = gsLeftToken->getOutgoingEdges(lhs.node)[0];
rightToken = gsRightToken->getOutgoingEdges(lhs.node)[0];
spanLength = gsOrder->distance(Init::initEdge(leftToken, rightToken));
}
// find each token which is between the left and right border
std::unique_ptr<EdgeIterator> itIncludedStart = gsOrder->findConnected(leftToken, 0, spanLength);
for(std::pair<bool, nodeid_t> includedStart = itIncludedStart->next();
includedStart.first;
includedStart = itIncludedStart->next())
{
const nodeid_t& includedTok = includedStart.second;
// add the token itself
w->addMatch(Init::initMatch(anyNodeAnno, includedTok));
// add aligned nodes
for(const auto& leftAlignedNode : gsLeftToken->getOutgoingEdges(includedTok))
{
nodeid_t includedEndCandiate = gsRightToken->getOutgoingEdges(leftAlignedNode)[0];
if(gsOrder->isConnected(Init::initEdge(includedEndCandiate, rightToken), 0, spanLength))
{
w->addMatch(Init::initMatch(anyNodeAnno, leftAlignedNode));
}
}
}
return w;
}
Inclusion::~Inclusion()
{
}
|
#include <annis/operators/inclusion.h>
#include <annis/wrapper.h>
using namespace annis;
Inclusion::Inclusion(const DB &db)
: db(db),
anyNodeAnno(Init::initAnnotation(db.getNodeNameStringID(), 0, db.getNamespaceStringID())),
tokHelper(db)
{
gsOrder = db.getGraphStorage(ComponentType::ORDERING, annis_ns, "");
gsLeftToken = db.getGraphStorage(ComponentType::LEFT_TOKEN, annis_ns, "");
gsRightToken = db.getGraphStorage(ComponentType::RIGHT_TOKEN, annis_ns, "");
}
bool Inclusion::filter(const Match &lhs, const Match &rhs)
{
nodeid_t lhsLeftToken = tokHelper.leftTokenForNode(lhs.node);
nodeid_t lhsRightToken = tokHelper.rightTokenForNode(lhs.node);
int spanLength = spanLength = gsOrder->distance(Init::initEdge(lhsLeftToken, lhsRightToken));
nodeid_t rhsLeftToken = tokHelper.leftTokenForNode(rhs.node);
nodeid_t rhsRightToken = tokHelper.rightTokenForNode(rhs.node);
if(gsOrder->isConnected(Init::initEdge(lhsLeftToken, rhsLeftToken), 0, spanLength)
&& gsOrder->isConnected(Init::initEdge(rhsRightToken, lhsRightToken), 0, spanLength)
)
{
return true;
}
return false;
}
std::unique_ptr<AnnoIt> Inclusion::retrieveMatches(const annis::Match &lhs)
{
std::unique_ptr<ListWrapper> w = std::make_unique<ListWrapper>();
nodeid_t leftToken;
nodeid_t rightToken;
int spanLength = 0;
if(db.nodeAnnos.getNodeAnnotation(lhs.node, annis_ns, annis_tok).first)
{
// is token
leftToken = lhs.node;
rightToken = lhs.node;
}
else
{
leftToken = gsLeftToken->getOutgoingEdges(lhs.node)[0];
rightToken = gsRightToken->getOutgoingEdges(lhs.node)[0];
spanLength = gsOrder->distance(Init::initEdge(leftToken, rightToken));
}
// find each token which is between the left and right border
std::unique_ptr<EdgeIterator> itIncludedStart = gsOrder->findConnected(leftToken, 0, spanLength);
for(std::pair<bool, nodeid_t> includedStart = itIncludedStart->next();
includedStart.first;
includedStart = itIncludedStart->next())
{
const nodeid_t& includedTok = includedStart.second;
// add the token itself
w->addMatch(Init::initMatch(anyNodeAnno, includedTok));
// add aligned nodes
for(const auto& leftAlignedNode : gsLeftToken->getOutgoingEdges(includedTok))
{
const nodeid_t& includedEndCandiate = gsRightToken->getOutgoingEdges(leftAlignedNode)[0];
if(gsOrder->isConnected({includedEndCandiate, rightToken}, 0, spanLength))
{
w->addMatch(Init::initMatch(anyNodeAnno, leftAlignedNode));
}
}
}
return w;
}
Inclusion::~Inclusion()
{
}
|
use reference instead of copying the node id
|
use reference instead of copying the node id
|
C++
|
apache-2.0
|
thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS
|
9ad250411bd51621d22fab0d406af423e9504847
|
Modules/Bundles/org.mitk.gui.qt.simpleexample/src/internal/QmitkSimpleExampleView.cpp
|
Modules/Bundles/org.mitk.gui.qt.simpleexample/src/internal/QmitkSimpleExampleView.cpp
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision: 17332 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkSimpleExampleView.h"
#include "mitkNodePredicateDataType.h"
#include "QmitkDataStorageComboBox.h"
#include "QmitkStdMultiWidget.h"
#include <QMessageBox>
#include <mitkMovieGenerator.h>
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateNOT.h"
#include "mitkProperties.h"
#include <QmitkStepperAdapter.h>
#include <QFileDialog>
#include <QFileInfo>
#include <QDir>
#include <vtkRenderWindow.h>
#include "vtkImageWriter.h"
#include "vtkPNGWriter.h"
#include "vtkJPEGWriter.h"
#include "vtkRenderLargeImage.h"
const std::string QmitkSimpleExampleView::VIEW_ID = "org.mitk.views.simpleexample";
QmitkSimpleExampleView::QmitkSimpleExampleView()
: QmitkFunctionality(),
m_Controls(NULL),
m_MultiWidget(NULL),
m_NavigatorsInitialized(false)
{
}
QmitkSimpleExampleView::~QmitkSimpleExampleView()
{
}
void QmitkSimpleExampleView::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
// create GUI widgets
m_Controls = new Ui::QmitkSimpleExampleViewControls;
m_Controls->setupUi(parent);
this->CreateConnections();
}
}
void QmitkSimpleExampleView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
m_MultiWidget = &stdMultiWidget;
new QmitkStepperAdapter(m_Controls->sliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample");
new QmitkStepperAdapter(m_Controls->sliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample");
new QmitkStepperAdapter(m_Controls->sliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample");
new QmitkStepperAdapter(m_Controls->sliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample");
new QmitkStepperAdapter(m_Controls->movieNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample");
}
void QmitkSimpleExampleView::StdMultiWidgetNotAvailable()
{
m_MultiWidget = NULL;
}
void QmitkSimpleExampleView::CreateConnections()
{
if ( m_Controls )
{
connect(m_Controls->stereoSelect, SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) );
connect(m_Controls->reInitializeNavigatorsButton, SIGNAL(clicked()), this, SLOT(initNavigators()) );
connect(m_Controls->genMovieButton, SIGNAL(clicked()), this, SLOT(generateMovie()) );
connect(m_Controls->m_RenderWindow1Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow1Clicked()) );
connect(m_Controls->m_RenderWindow2Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow2Clicked()) );
connect(m_Controls->m_RenderWindow3Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow3Clicked()) );
connect(m_Controls->m_RenderWindow4Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow4Clicked()) );
connect(m_Controls->m_TakeScreenshotBtn, SIGNAL(clicked()), this, SLOT(OnTakeScreenshot()) );
connect(m_Controls->m_TakeHighResScreenShotBtn, SIGNAL(clicked()), this, SLOT(OnTakeHighResolutionScreenshot()) );
}
}
void QmitkSimpleExampleView::Activated()
{
QmitkFunctionality::Activated();
}
void QmitkSimpleExampleView::Deactivated()
{
QmitkFunctionality::Deactivated();
}
void QmitkSimpleExampleView::initNavigators()
{
/* get all nodes that have not set "includeInBoundingBox" to false */
mitk::NodePredicateNOT::Pointer pred = mitk::NodePredicateNOT::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
/* calculate bounding geometry of these nodes */
mitk::Geometry3D::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs);
/* initialize the views to the bounding geometry */
m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
//m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(GetDefaultDataStorage());
}
void QmitkSimpleExampleView::generateMovie()
{
QmitkRenderWindow* movieRenderWindow = GetMovieRenderWindow();
//mitk::Stepper::Pointer stepper = multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice();
mitk::Stepper::Pointer stepper = movieRenderWindow->GetSliceNavigationController()->GetSlice();
mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New();
if (movieGenerator.IsNotNull()) {
movieGenerator->SetStepper( stepper );
movieGenerator->SetRenderer( mitk::BaseRenderer::GetInstance(movieRenderWindow->GetRenderWindow()) );
QString movieFileName = QFileDialog::getSaveFileName(0, "Choose a file name", QString(), "Movie (*.avi)");
if (!movieFileName.isEmpty()) {
movieGenerator->SetFileName( movieFileName.toStdString().c_str() );
movieGenerator->WriteMovie();
}
}
}
void QmitkSimpleExampleView::stereoSelectionChanged( int id )
{
/* From vtkRenderWindow.h tells us about stereo rendering:
Set/Get what type of stereo rendering to use. CrystalEyes mode uses frame-sequential capabilities available in OpenGL to drive LCD shutter glasses and stereo projectors. RedBlue mode is a simple type of stereo for use with red-blue glasses. Anaglyph mode is a superset of RedBlue mode, but the color output channels can be configured using the AnaglyphColorMask and the color of the original image can be (somewhat maintained using AnaglyphColorSaturation; the default colors for Anaglyph mode is red-cyan. Interlaced stereo mode produces a composite image where horizontal lines alternate between left and right views. StereoLeft and StereoRight modes choose one or the other stereo view. Dresden mode is yet another stereoscopic interleaving.
*/
vtkRenderWindow * vtkrenderwindow = m_MultiWidget->mitkWidget4->GetRenderWindow();
// note: foreground vtkRenderers (at least the department logo renderer) produce errors in stereoscopic visualization.
// Therefore, we disable the logo visualization during stereo rendering.
switch(id)
{
case 0:
vtkrenderwindow->StereoRenderOff();
break;
case 1:
vtkrenderwindow->SetStereoTypeToRedBlue();
vtkrenderwindow->StereoRenderOn();
m_MultiWidget->DisableDepartmentLogo();
break;
case 2:
vtkrenderwindow->SetStereoTypeToDresden();
vtkrenderwindow->StereoRenderOn();
m_MultiWidget->DisableDepartmentLogo();
break;
}
mitk::BaseRenderer::GetInstance(m_MultiWidget->mitkWidget4->GetRenderWindow())->SetMapperID(2);
m_MultiWidget->RequestUpdate();
}
QmitkRenderWindow* QmitkSimpleExampleView::GetMovieRenderWindow()
{
//check which RenderWindow should be used to generate the movie, e.g. which button is toggled
if(m_Controls->m_RenderWindow1Button->isChecked())
{
return m_MultiWidget->mitkWidget1;
}
else if(m_Controls->m_RenderWindow2Button->isChecked())
{
return m_MultiWidget->mitkWidget2;
}
else if(m_Controls->m_RenderWindow3Button->isChecked())
{
return m_MultiWidget->mitkWidget3;
}
else if(m_Controls->m_RenderWindow4Button->isChecked())
{
return m_MultiWidget->mitkWidget4;
}
else //as default take widget1
{
return m_MultiWidget->mitkWidget1;
}
}
void QmitkSimpleExampleView::OnRenderWindow1Clicked()
{
m_Controls->m_RenderWindow2Button->setChecked(false);
m_Controls->m_RenderWindow3Button->setChecked(false);
m_Controls->m_RenderWindow4Button->setChecked(false);
}
void QmitkSimpleExampleView::OnRenderWindow2Clicked()
{
m_Controls->m_RenderWindow1Button->setChecked(false);
m_Controls->m_RenderWindow3Button->setChecked(false);
m_Controls->m_RenderWindow4Button->setChecked(false);
}
void QmitkSimpleExampleView::OnRenderWindow3Clicked()
{
m_Controls->m_RenderWindow2Button->setChecked(false);
m_Controls->m_RenderWindow1Button->setChecked(false);
m_Controls->m_RenderWindow4Button->setChecked(false);
}
void QmitkSimpleExampleView::OnRenderWindow4Clicked()
{
m_Controls->m_RenderWindow2Button->setChecked(false);
m_Controls->m_RenderWindow3Button->setChecked(false);
m_Controls->m_RenderWindow1Button->setChecked(false);
}
void QmitkSimpleExampleView::OnTakeHighResolutionScreenshot()
{
QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)");
QmitkRenderWindow* renWin = m_MultiWidget->GetRenderWindow4(); // high res is always the 3D view
if (renWin == NULL)
return;
vtkRenderer* renderer = renWin->GetRenderer()->GetVtkRenderer();
if (renderer == NULL)
return;
this->TakeScreenshot(renderer, 4, fileName);
}
void QmitkSimpleExampleView::OnTakeScreenshot()
{
QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)");
QmitkRenderWindow* renWin = this->GetMovieRenderWindow();
if (renWin == NULL)
return;
vtkRenderer* renderer = renWin->GetRenderer()->GetVtkRenderer();
if (renderer == NULL)
return;
this->TakeScreenshot(renderer, 1, fileName);
}
void QmitkSimpleExampleView::TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName)
{
if ((renderer == NULL) ||(magnificationFactor < 1) || fileName.isEmpty())
return;
vtkImageWriter* fileWriter;
QFileInfo fi(fileName);
QString suffix = fi.suffix();
if (suffix.compare("png", Qt::CaseInsensitive) == 0)
{
fileWriter = vtkPNGWriter::New();
}
else // default is jpeg
{
vtkJPEGWriter* w = vtkJPEGWriter::New();
w->SetQuality(100);
w->ProgressiveOff();
fileWriter = w;
}
vtkRenderLargeImage* magnifier = vtkRenderLargeImage::New();
magnifier->SetInput(renderer);
magnifier->SetMagnification(magnificationFactor);
fileWriter->SetInput(magnifier->GetOutput());
fileWriter->SetFileName(fileName.toLatin1());
// vtkRenderLargeImage has problems with different layers, therefore we have to
// temporarily deactivate all other layers.
// we set the background to white, because it is nicer than black...
double oldBackground[3];
renderer->GetBackground(oldBackground);
double white[] = {1.0, 1.0, 1.0};
renderer->SetBackground(white);
m_MultiWidget->DisableColoredRectangles();
m_MultiWidget->DisableDepartmentLogo();
m_MultiWidget->DisableGradientBackground();
fileWriter->Write();
m_MultiWidget->EnableColoredRectangles();
m_MultiWidget->EnableDepartmentLogo();
m_MultiWidget->EnableGradientBackground();
renderer->SetBackground(oldBackground);
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision: 17332 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkSimpleExampleView.h"
#include "mitkNodePredicateDataType.h"
#include "QmitkDataStorageComboBox.h"
#include "QmitkStdMultiWidget.h"
#include <QMessageBox>
#include <mitkMovieGenerator.h>
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateNOT.h"
#include "mitkProperties.h"
#include <QmitkStepperAdapter.h>
#include <QFileDialog>
#include <QFileInfo>
#include <QDir>
#include <vtkRenderWindow.h>
#include "vtkImageWriter.h"
#include "vtkPNGWriter.h"
#include "vtkJPEGWriter.h"
#include "vtkRenderLargeImage.h"
const std::string QmitkSimpleExampleView::VIEW_ID = "org.mitk.views.simpleexample";
QmitkSimpleExampleView::QmitkSimpleExampleView()
: QmitkFunctionality(),
m_Controls(NULL),
m_MultiWidget(NULL),
m_NavigatorsInitialized(false)
{
}
QmitkSimpleExampleView::~QmitkSimpleExampleView()
{
}
void QmitkSimpleExampleView::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
// create GUI widgets
m_Controls = new Ui::QmitkSimpleExampleViewControls;
m_Controls->setupUi(parent);
this->CreateConnections();
}
}
void QmitkSimpleExampleView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
m_MultiWidget = &stdMultiWidget;
new QmitkStepperAdapter(m_Controls->sliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample");
new QmitkStepperAdapter(m_Controls->sliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample");
new QmitkStepperAdapter(m_Controls->sliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample");
new QmitkStepperAdapter(m_Controls->sliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample");
new QmitkStepperAdapter(m_Controls->movieNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample");
}
void QmitkSimpleExampleView::StdMultiWidgetNotAvailable()
{
m_MultiWidget = NULL;
}
void QmitkSimpleExampleView::CreateConnections()
{
if ( m_Controls )
{
connect(m_Controls->stereoSelect, SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) );
connect(m_Controls->reInitializeNavigatorsButton, SIGNAL(clicked()), this, SLOT(initNavigators()) );
connect(m_Controls->genMovieButton, SIGNAL(clicked()), this, SLOT(generateMovie()) );
connect(m_Controls->m_RenderWindow1Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow1Clicked()) );
connect(m_Controls->m_RenderWindow2Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow2Clicked()) );
connect(m_Controls->m_RenderWindow3Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow3Clicked()) );
connect(m_Controls->m_RenderWindow4Button, SIGNAL(clicked()), this, SLOT(OnRenderWindow4Clicked()) );
connect(m_Controls->m_TakeScreenshotBtn, SIGNAL(clicked()), this, SLOT(OnTakeScreenshot()) );
connect(m_Controls->m_TakeHighResScreenShotBtn, SIGNAL(clicked()), this, SLOT(OnTakeHighResolutionScreenshot()) );
}
}
void QmitkSimpleExampleView::Activated()
{
QmitkFunctionality::Activated();
}
void QmitkSimpleExampleView::Deactivated()
{
QmitkFunctionality::Deactivated();
}
void QmitkSimpleExampleView::initNavigators()
{
/* get all nodes that have not set "includeInBoundingBox" to false */
mitk::NodePredicateNOT::Pointer pred = mitk::NodePredicateNOT::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
/* calculate bounding geometry of these nodes */
mitk::Geometry3D::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs);
/* initialize the views to the bounding geometry */
m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
//m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(GetDefaultDataStorage());
}
void QmitkSimpleExampleView::generateMovie()
{
QmitkRenderWindow* movieRenderWindow = GetMovieRenderWindow();
//mitk::Stepper::Pointer stepper = multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice();
mitk::Stepper::Pointer stepper = movieRenderWindow->GetSliceNavigationController()->GetSlice();
mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New();
if (movieGenerator.IsNotNull()) {
movieGenerator->SetStepper( stepper );
movieGenerator->SetRenderer( mitk::BaseRenderer::GetInstance(movieRenderWindow->GetRenderWindow()) );
QString movieFileName = QFileDialog::getSaveFileName(0, "Choose a file name", QString(), "Movie (*.avi)");
if (!movieFileName.isEmpty()) {
movieGenerator->SetFileName( movieFileName.toStdString().c_str() );
movieGenerator->WriteMovie();
}
}
}
void QmitkSimpleExampleView::stereoSelectionChanged( int id )
{
/* From vtkRenderWindow.h tells us about stereo rendering:
Set/Get what type of stereo rendering to use. CrystalEyes mode uses frame-sequential capabilities available in OpenGL to drive LCD shutter glasses and stereo projectors. RedBlue mode is a simple type of stereo for use with red-blue glasses. Anaglyph mode is a superset of RedBlue mode, but the color output channels can be configured using the AnaglyphColorMask and the color of the original image can be (somewhat maintained using AnaglyphColorSaturation; the default colors for Anaglyph mode is red-cyan. Interlaced stereo mode produces a composite image where horizontal lines alternate between left and right views. StereoLeft and StereoRight modes choose one or the other stereo view. Dresden mode is yet another stereoscopic interleaving.
*/
vtkRenderWindow * vtkrenderwindow = m_MultiWidget->mitkWidget4->GetRenderWindow();
// note: foreground vtkRenderers (at least the department logo renderer) produce errors in stereoscopic visualization.
// Therefore, we disable the logo visualization during stereo rendering.
switch(id)
{
case 0:
vtkrenderwindow->StereoRenderOff();
break;
case 1:
vtkrenderwindow->SetStereoTypeToRedBlue();
vtkrenderwindow->StereoRenderOn();
m_MultiWidget->DisableDepartmentLogo();
break;
case 2:
vtkrenderwindow->SetStereoTypeToDresden();
vtkrenderwindow->StereoRenderOn();
m_MultiWidget->DisableDepartmentLogo();
break;
}
mitk::BaseRenderer::GetInstance(m_MultiWidget->mitkWidget4->GetRenderWindow())->SetMapperID(2);
m_MultiWidget->RequestUpdate();
}
QmitkRenderWindow* QmitkSimpleExampleView::GetMovieRenderWindow()
{
//check which RenderWindow should be used to generate the movie, e.g. which button is toggled
if(m_Controls->m_RenderWindow1Button->isChecked())
{
return m_MultiWidget->mitkWidget1;
}
else if(m_Controls->m_RenderWindow2Button->isChecked())
{
return m_MultiWidget->mitkWidget2;
}
else if(m_Controls->m_RenderWindow3Button->isChecked())
{
return m_MultiWidget->mitkWidget3;
}
else if(m_Controls->m_RenderWindow4Button->isChecked())
{
return m_MultiWidget->mitkWidget4;
}
else //as default take widget1
{
return m_MultiWidget->mitkWidget1;
}
}
void QmitkSimpleExampleView::OnRenderWindow1Clicked()
{
m_Controls->m_RenderWindow2Button->setChecked(false);
m_Controls->m_RenderWindow3Button->setChecked(false);
m_Controls->m_RenderWindow4Button->setChecked(false);
}
void QmitkSimpleExampleView::OnRenderWindow2Clicked()
{
m_Controls->m_RenderWindow1Button->setChecked(false);
m_Controls->m_RenderWindow3Button->setChecked(false);
m_Controls->m_RenderWindow4Button->setChecked(false);
}
void QmitkSimpleExampleView::OnRenderWindow3Clicked()
{
m_Controls->m_RenderWindow2Button->setChecked(false);
m_Controls->m_RenderWindow1Button->setChecked(false);
m_Controls->m_RenderWindow4Button->setChecked(false);
}
void QmitkSimpleExampleView::OnRenderWindow4Clicked()
{
m_Controls->m_RenderWindow2Button->setChecked(false);
m_Controls->m_RenderWindow3Button->setChecked(false);
m_Controls->m_RenderWindow1Button->setChecked(false);
}
void QmitkSimpleExampleView::OnTakeHighResolutionScreenshot()
{
QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)");
QmitkRenderWindow* renWin = this->GetMovieRenderWindow();
if (renWin == NULL)
return;
vtkRenderer* renderer = renWin->GetRenderer()->GetVtkRenderer();
if (renderer == NULL)
return;
this->TakeScreenshot(renderer, 4, fileName);
}
void QmitkSimpleExampleView::OnTakeScreenshot()
{
QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", QDir::currentPath(), "JPEG file (*.jpg);;PNG file (*.png)");
QmitkRenderWindow* renWin = this->GetMovieRenderWindow();
if (renWin == NULL)
return;
vtkRenderer* renderer = renWin->GetRenderer()->GetVtkRenderer();
if (renderer == NULL)
return;
this->TakeScreenshot(renderer, 1, fileName);
}
void QmitkSimpleExampleView::TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName)
{
if ((renderer == NULL) ||(magnificationFactor < 1) || fileName.isEmpty())
return;
bool doubleBuffering( renderer->GetRenderWindow()->GetDoubleBuffer() );
renderer->GetRenderWindow()->DoubleBufferOff();
vtkImageWriter* fileWriter;
QFileInfo fi(fileName);
QString suffix = fi.suffix();
if (suffix.compare("png", Qt::CaseInsensitive) == 0)
{
fileWriter = vtkPNGWriter::New();
}
else // default is jpeg
{
vtkJPEGWriter* w = vtkJPEGWriter::New();
w->SetQuality(100);
w->ProgressiveOff();
fileWriter = w;
}
vtkRenderLargeImage* magnifier = vtkRenderLargeImage::New();
magnifier->SetInput(renderer);
magnifier->SetMagnification(magnificationFactor);
//magnifier->Update();
fileWriter->SetInput(magnifier->GetOutput());
fileWriter->SetFileName(fileName.toLatin1());
// vtkRenderLargeImage has problems with different layers, therefore we have to
// temporarily deactivate all other layers.
// we set the background to white, because it is nicer than black...
double oldBackground[3];
renderer->GetBackground(oldBackground);
double white[] = {1.0, 1.0, 1.0};
renderer->SetBackground(white);
m_MultiWidget->DisableColoredRectangles();
m_MultiWidget->DisableDepartmentLogo();
m_MultiWidget->DisableGradientBackground();
fileWriter->Write();
fileWriter->Delete();
m_MultiWidget->EnableColoredRectangles();
m_MultiWidget->EnableDepartmentLogo();
m_MultiWidget->EnableGradientBackground();
renderer->SetBackground(oldBackground);
renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering);
}
|
FIX (#2348): some Linux adaptions to make high resolution screenshots work
|
FIX (#2348): some Linux adaptions to make high resolution screenshots work
|
C++
|
bsd-3-clause
|
iwegner/MITK,NifTK/MITK,fmilano/mitk,nocnokneo/MITK,danielknorr/MITK,rfloca/MITK,RabadanLab/MITKats,nocnokneo/MITK,danielknorr/MITK,RabadanLab/MITKats,NifTK/MITK,iwegner/MITK,danielknorr/MITK,MITK/MITK,iwegner/MITK,fmilano/mitk,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,rfloca/MITK,NifTK/MITK,danielknorr/MITK,rfloca/MITK,iwegner/MITK,fmilano/mitk,MITK/MITK,rfloca/MITK,fmilano/mitk,nocnokneo/MITK,RabadanLab/MITKats,danielknorr/MITK,danielknorr/MITK,NifTK/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,rfloca/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,fmilano/mitk,MITK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,NifTK/MITK,rfloca/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,RabadanLab/MITKats,iwegner/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,iwegner/MITK,RabadanLab/MITKats,MITK/MITK,fmilano/mitk,rfloca/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK
|
79867ec5da6dcf6bccc481a17f0a123630485921
|
Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.cpp
|
Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// semantic relations plugin
#include "QmitkSemanticRelationsView.h"
#include "QmitkSemanticRelationsNodeSelectionDialog.h"
#include "QmitkDataNodeAddToSemanticRelationsAction.h"
#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
// semantic relations module
#include <mitkNodePredicates.h>
#include <mitkSemanticRelationException.h>
// mitk qt widgets module
#include <QmitkDnDDataNodeWidget.h>
#include <QmitkRenderWindow.h>
// mitk multi label module
#include <mitkLabelSetImage.h>
// berry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// qt
#include <QMenu>
#include <QTreeView>
const std::string QmitkSemanticRelationsView::VIEW_ID = "org.mitk.views.semanticrelations";
void QmitkSemanticRelationsView::SetFocus()
{
// nothing here
}
void QmitkSemanticRelationsView::CreateQtPartControl(QWidget* parent)
{
// create GUI widgets
m_Controls.setupUi(parent);
// initialize the semantic relations
m_SemanticRelations = std::make_unique<mitk::SemanticRelations>(GetDataStorage());
m_LesionInfoWidget = new QmitkLesionInfoWidget(GetDataStorage(), parent);
m_Controls.gridLayout->addWidget(m_LesionInfoWidget);
m_PatientTableInspector = new QmitkPatientTableInspector(parent);
m_PatientTableInspector->SetDataStorage(GetDataStorage());
m_Controls.gridLayout->addWidget(m_PatientTableInspector);
QGridLayout* dndDataNodeWidgetLayout = new QGridLayout;
dndDataNodeWidgetLayout->addWidget(m_PatientTableInspector, 0, 0);
dndDataNodeWidgetLayout->setContentsMargins(0, 0, 0, 0);
m_DnDDataNodeWidget = new QmitkDnDDataNodeWidget(parent);
m_DnDDataNodeWidget->setLayout(dndDataNodeWidgetLayout);
m_Controls.gridLayout->addWidget(m_DnDDataNodeWidget);
m_ContextMenu = new QmitkSemanticRelationsContextMenu(GetSite(), m_PatientTableInspector);
m_ContextMenu->SetDataStorage(GetDataStorage());
mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart();
if (nullptr != renderWindowPart)
{
RenderWindowPartActivated(renderWindowPart);
}
SetUpConnections();
}
void QmitkSemanticRelationsView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
// connect QmitkRenderWindows - underlying vtkRenderWindow is the same as "mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows()"
QHash<QString, QmitkRenderWindow*> windowMap = renderWindowPart->GetQmitkRenderWindows();
QHash<QString, QmitkRenderWindow*>::Iterator it;
mitk::BaseRenderer* baseRenderer = nullptr;
RenderWindowLayerUtilities::RendererVector controlledRenderer;
for (it = windowMap.begin(); it != windowMap.end(); ++it)
{
baseRenderer = mitk::BaseRenderer::GetInstance(it.value()->GetVtkRenderWindow());
if (nullptr != baseRenderer)
{
controlledRenderer.push_back(baseRenderer);
}
}
m_ContextMenu->SetControlledRenderer(controlledRenderer);
}
void QmitkSemanticRelationsView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)
{
// nothing here
}
void QmitkSemanticRelationsView::SetUpConnections()
{
connect(m_Controls.caseIDComboBox, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentIndexChanged), this, &QmitkSemanticRelationsView::OnCaseIDSelectionChanged);
connect(m_LesionInfoWidget, &QmitkLesionInfoWidget::LesionSelectionChanged, this, &QmitkSemanticRelationsView::OnLesionSelectionChanged);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::CurrentSelectionChanged, this, &QmitkSemanticRelationsView::OnDataNodeSelectionChanged);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::DataNodeDoubleClicked, this, &QmitkSemanticRelationsView::OnDataNodeDoubleClicked);
connect(m_DnDDataNodeWidget, &QmitkDnDDataNodeWidget::NodesDropped, this, &QmitkSemanticRelationsView::OnNodesAdded);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::OnContextMenuRequested, m_ContextMenu, &QmitkSemanticRelationsContextMenu::OnContextMenuRequested);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::OnNodeRemoved, this, &QmitkSemanticRelationsView::NodeRemoved);
}
QItemSelectionModel* QmitkSemanticRelationsView::GetDataNodeSelectionModel() const
{
return m_PatientTableInspector->GetSelectionModel();
}
void QmitkSemanticRelationsView::NodeRemoved(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
return;
}
if (m_SemanticRelations->InstanceExists(dataNode))
{
RemoveFromSemanticRelationsAction::Run(m_SemanticRelations.get(), dataNode);
mitk::SemanticTypes::CaseID caseID = mitk::GetCaseIDFromDataNode(dataNode);
RemoveFromComboBox(caseID);
}
}
void QmitkSemanticRelationsView::OnLesionSelectionChanged(const mitk::SemanticTypes::Lesion& lesion)
{
m_PatientTableInspector->SetLesion(lesion);
}
void QmitkSemanticRelationsView::OnDataNodeSelectionChanged(const QList<mitk::DataNode::Pointer>& dataNodeSelection)
{
m_LesionInfoWidget->SetDataNodeSelection(dataNodeSelection);
}
void QmitkSemanticRelationsView::OnDataNodeDoubleClicked(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
return;
}
if (mitk::NodePredicates::GetImagePredicate()->CheckNode(dataNode))
{
OpenInEditor(dataNode);
}
else if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
{
JumpToPosition(dataNode);
}
}
void QmitkSemanticRelationsView::OnCaseIDSelectionChanged(const QString& caseID)
{
m_LesionInfoWidget->SetCaseID(caseID.toStdString());
m_PatientTableInspector->SetCaseID(caseID.toStdString());
}
void QmitkSemanticRelationsView::OnNodesAdded(QmitkDnDDataNodeWidget* dnDDataNodeWidget, std::vector<mitk::DataNode*> nodes)
{
mitk::SemanticTypes::CaseID caseID = "";
for (mitk::DataNode* dataNode : nodes)
{
AddToSemanticRelationsAction::Run(m_SemanticRelations.get(), GetDataStorage(), dataNode);
caseID = mitk::GetCaseIDFromDataNode(dataNode);
AddToComboBox(caseID);
}
}
void QmitkSemanticRelationsView::OnNodeRemoved(const mitk::DataNode* dataNode)
{
NodeRemoved(dataNode);
}
void QmitkSemanticRelationsView::AddToComboBox(const mitk::SemanticTypes::CaseID& caseID)
{
int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
if (-1 == foundIndex)
{
// add the caseID to the combo box, as it is not already contained
m_Controls.caseIDComboBox->addItem(QString::fromStdString(caseID));
}
}
void QmitkSemanticRelationsView::RemoveFromComboBox(const mitk::SemanticTypes::CaseID& caseID)
{
std::vector<mitk::SemanticTypes::ControlPoint> allControlPoints = m_SemanticRelations->GetAllControlPointsOfCase(caseID);
int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
if (allControlPoints.empty() && -1 != foundIndex)
{
// TODO: find new way to check for empty case id
// caseID does not contain any control points and therefore no data
// remove the caseID, if it is still contained
m_Controls.caseIDComboBox->removeItem(foundIndex);
}
}
void QmitkSemanticRelationsView::OpenInEditor(const mitk::DataNode* dataNode)
{
auto renderWindowPart = GetRenderWindowPart();
if (nullptr == renderWindowPart)
{
renderWindowPart = GetRenderWindowPart(QmitkAbstractView::BRING_TO_FRONT | QmitkAbstractView::OPEN);
if (nullptr == renderWindowPart)
{
// no render window available
return;
}
}
auto image = dynamic_cast<mitk::Image*>(dataNode->GetData());
if (nullptr != image)
{
mitk::RenderingManager::GetInstance()->InitializeViews(image->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true);
}
}
void QmitkSemanticRelationsView::JumpToPosition(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
return;
}
mitk::LabelSetImage* labelSetImage = dynamic_cast<mitk::LabelSetImage*>(dataNode->GetData());
if (nullptr == labelSetImage)
{
return;
}
int activeLayer = labelSetImage->GetActiveLayer();
mitk::Label* activeLabel = labelSetImage->GetActiveLabel(activeLayer);
labelSetImage->UpdateCenterOfMass(activeLabel->GetValue(), activeLayer);
const mitk::Point3D& centerPosition = activeLabel->GetCenterOfMassCoordinates();
if (centerPosition.GetVnlVector().max_value() > 0.0)
{
auto renderWindowPart = GetRenderWindowPart();
if (nullptr == renderWindowPart)
{
renderWindowPart = GetRenderWindowPart(QmitkAbstractView::BRING_TO_FRONT | QmitkAbstractView::OPEN);
if (nullptr == renderWindowPart)
{
// no render window available
return;
}
}
auto segmentation = dynamic_cast<mitk::LabelSetImage*>(dataNode->GetData());
if (nullptr != segmentation)
{
renderWindowPart->SetSelectedPosition(centerPosition);
mitk::RenderingManager::GetInstance()->InitializeViews(segmentation->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true);
}
}
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// semantic relations plugin
#include "QmitkSemanticRelationsView.h"
#include "QmitkSemanticRelationsNodeSelectionDialog.h"
#include "QmitkDataNodeAddToSemanticRelationsAction.h"
#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
// semantic relations module
#include <mitkNodePredicates.h>
#include <mitkSemanticRelationException.h>
// mitk qt widgets module
#include <QmitkDnDDataNodeWidget.h>
#include <QmitkRenderWindow.h>
// mitk multi label module
#include <mitkLabelSetImage.h>
// berry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// qt
#include <QMenu>
#include <QTreeView>
const std::string QmitkSemanticRelationsView::VIEW_ID = "org.mitk.views.semanticrelations";
void QmitkSemanticRelationsView::SetFocus()
{
// nothing here
}
void QmitkSemanticRelationsView::CreateQtPartControl(QWidget* parent)
{
// create GUI widgets
m_Controls.setupUi(parent);
// initialize the semantic relations
m_SemanticRelations = std::make_unique<mitk::SemanticRelations>(GetDataStorage());
m_LesionInfoWidget = new QmitkLesionInfoWidget(GetDataStorage(), parent);
m_Controls.gridLayout->addWidget(m_LesionInfoWidget);
m_PatientTableInspector = new QmitkPatientTableInspector(parent);
m_PatientTableInspector->SetDataStorage(GetDataStorage());
m_Controls.gridLayout->addWidget(m_PatientTableInspector);
QGridLayout* dndDataNodeWidgetLayout = new QGridLayout;
dndDataNodeWidgetLayout->addWidget(m_PatientTableInspector, 0, 0);
dndDataNodeWidgetLayout->setContentsMargins(0, 0, 0, 0);
m_DnDDataNodeWidget = new QmitkDnDDataNodeWidget(parent);
m_DnDDataNodeWidget->setLayout(dndDataNodeWidgetLayout);
m_Controls.gridLayout->addWidget(m_DnDDataNodeWidget);
m_ContextMenu = new QmitkSemanticRelationsContextMenu(GetSite(), m_PatientTableInspector);
m_ContextMenu->SetDataStorage(GetDataStorage());
mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart();
if (nullptr != renderWindowPart)
{
RenderWindowPartActivated(renderWindowPart);
}
SetUpConnections();
const auto& allCaseIDs = m_SemanticRelations->GetAllCaseIDs();
for (const auto& caseID : allCaseIDs)
{
AddToComboBox(caseID);
}
}
void QmitkSemanticRelationsView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
// connect QmitkRenderWindows - underlying vtkRenderWindow is the same as "mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows()"
QHash<QString, QmitkRenderWindow*> windowMap = renderWindowPart->GetQmitkRenderWindows();
QHash<QString, QmitkRenderWindow*>::Iterator it;
mitk::BaseRenderer* baseRenderer = nullptr;
RenderWindowLayerUtilities::RendererVector controlledRenderer;
for (it = windowMap.begin(); it != windowMap.end(); ++it)
{
baseRenderer = mitk::BaseRenderer::GetInstance(it.value()->GetVtkRenderWindow());
if (nullptr != baseRenderer)
{
controlledRenderer.push_back(baseRenderer);
}
}
m_ContextMenu->SetControlledRenderer(controlledRenderer);
}
void QmitkSemanticRelationsView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)
{
// nothing here
}
void QmitkSemanticRelationsView::SetUpConnections()
{
connect(m_Controls.caseIDComboBox, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentIndexChanged), this, &QmitkSemanticRelationsView::OnCaseIDSelectionChanged);
connect(m_LesionInfoWidget, &QmitkLesionInfoWidget::LesionSelectionChanged, this, &QmitkSemanticRelationsView::OnLesionSelectionChanged);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::CurrentSelectionChanged, this, &QmitkSemanticRelationsView::OnDataNodeSelectionChanged);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::DataNodeDoubleClicked, this, &QmitkSemanticRelationsView::OnDataNodeDoubleClicked);
connect(m_DnDDataNodeWidget, &QmitkDnDDataNodeWidget::NodesDropped, this, &QmitkSemanticRelationsView::OnNodesAdded);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::OnContextMenuRequested, m_ContextMenu, &QmitkSemanticRelationsContextMenu::OnContextMenuRequested);
connect(m_PatientTableInspector, &QmitkPatientTableInspector::OnNodeRemoved, this, &QmitkSemanticRelationsView::NodeRemoved);
}
QItemSelectionModel* QmitkSemanticRelationsView::GetDataNodeSelectionModel() const
{
return m_PatientTableInspector->GetSelectionModel();
}
void QmitkSemanticRelationsView::NodeRemoved(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
return;
}
if (m_SemanticRelations->InstanceExists(dataNode))
{
RemoveFromSemanticRelationsAction::Run(m_SemanticRelations.get(), dataNode);
mitk::SemanticTypes::CaseID caseID = mitk::GetCaseIDFromDataNode(dataNode);
RemoveFromComboBox(caseID);
}
}
void QmitkSemanticRelationsView::OnLesionSelectionChanged(const mitk::SemanticTypes::Lesion& lesion)
{
m_PatientTableInspector->SetLesion(lesion);
}
void QmitkSemanticRelationsView::OnDataNodeSelectionChanged(const QList<mitk::DataNode::Pointer>& dataNodeSelection)
{
m_LesionInfoWidget->SetDataNodeSelection(dataNodeSelection);
}
void QmitkSemanticRelationsView::OnDataNodeDoubleClicked(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
return;
}
if (mitk::NodePredicates::GetImagePredicate()->CheckNode(dataNode))
{
OpenInEditor(dataNode);
}
else if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
{
JumpToPosition(dataNode);
}
}
void QmitkSemanticRelationsView::OnCaseIDSelectionChanged(const QString& caseID)
{
m_LesionInfoWidget->SetCaseID(caseID.toStdString());
m_PatientTableInspector->SetCaseID(caseID.toStdString());
}
void QmitkSemanticRelationsView::OnNodesAdded(QmitkDnDDataNodeWidget* dnDDataNodeWidget, std::vector<mitk::DataNode*> nodes)
{
mitk::SemanticTypes::CaseID caseID = "";
for (mitk::DataNode* dataNode : nodes)
{
AddToSemanticRelationsAction::Run(m_SemanticRelations.get(), GetDataStorage(), dataNode);
caseID = mitk::GetCaseIDFromDataNode(dataNode);
AddToComboBox(caseID);
}
}
void QmitkSemanticRelationsView::OnNodeRemoved(const mitk::DataNode* dataNode)
{
NodeRemoved(dataNode);
}
void QmitkSemanticRelationsView::AddToComboBox(const mitk::SemanticTypes::CaseID& caseID)
{
int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
if (-1 == foundIndex)
{
// add the caseID to the combo box, as it is not already contained
m_Controls.caseIDComboBox->addItem(QString::fromStdString(caseID));
}
}
void QmitkSemanticRelationsView::RemoveFromComboBox(const mitk::SemanticTypes::CaseID& caseID)
{
std::vector<mitk::SemanticTypes::ControlPoint> allControlPoints = m_SemanticRelations->GetAllControlPointsOfCase(caseID);
int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
if (allControlPoints.empty() && -1 != foundIndex)
{
// TODO: find new way to check for empty case id
// caseID does not contain any control points and therefore no data
// remove the caseID, if it is still contained
m_Controls.caseIDComboBox->removeItem(foundIndex);
}
}
void QmitkSemanticRelationsView::OpenInEditor(const mitk::DataNode* dataNode)
{
auto renderWindowPart = GetRenderWindowPart();
if (nullptr == renderWindowPart)
{
renderWindowPart = GetRenderWindowPart(QmitkAbstractView::BRING_TO_FRONT | QmitkAbstractView::OPEN);
if (nullptr == renderWindowPart)
{
// no render window available
return;
}
}
auto image = dynamic_cast<mitk::Image*>(dataNode->GetData());
if (nullptr != image)
{
mitk::RenderingManager::GetInstance()->InitializeViews(image->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true);
}
}
void QmitkSemanticRelationsView::JumpToPosition(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
return;
}
mitk::LabelSetImage* labelSetImage = dynamic_cast<mitk::LabelSetImage*>(dataNode->GetData());
if (nullptr == labelSetImage)
{
return;
}
int activeLayer = labelSetImage->GetActiveLayer();
mitk::Label* activeLabel = labelSetImage->GetActiveLabel(activeLayer);
labelSetImage->UpdateCenterOfMass(activeLabel->GetValue(), activeLayer);
const mitk::Point3D& centerPosition = activeLabel->GetCenterOfMassCoordinates();
if (centerPosition.GetVnlVector().max_value() > 0.0)
{
auto renderWindowPart = GetRenderWindowPart();
if (nullptr == renderWindowPart)
{
renderWindowPart = GetRenderWindowPart(QmitkAbstractView::BRING_TO_FRONT | QmitkAbstractView::OPEN);
if (nullptr == renderWindowPart)
{
// no render window available
return;
}
}
auto segmentation = dynamic_cast<mitk::LabelSetImage*>(dataNode->GetData());
if (nullptr != segmentation)
{
renderWindowPart->SetSelectedPosition(centerPosition);
mitk::RenderingManager::GetInstance()->InitializeViews(segmentation->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true);
}
}
}
|
Initialize semantic relations view on activation, if data exists
|
Initialize semantic relations view on activation, if data exists
|
C++
|
bsd-3-clause
|
fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK
|
09d2c5dd37453581f30785e1585af10b5ccf22ad
|
core/mapi/version.cpp
|
core/mapi/version.cpp
|
#include <core/stdafx.h>
#include <core/mapi/version.h>
#include <core/utility/import.h>
#include <core/mapi/stubutils.h>
#include <core/utility/strings.h>
#include <core/utility/output.h>
#include <core/utility/error.h>
#include <appmodel.h>
#include <AppxPackaging.h>
namespace version
{
std::wstring GetMSIVersion()
{
if (!import::pfnMsiProvideQualifiedComponent || !import::pfnMsiGetFileVersion) return strings::emptystring;
std::wstring szOut;
for (auto i = oqcOfficeBegin; i < oqcOfficeEnd; i++)
{
auto b64 = false;
auto lpszTempPath = mapistub::GetOutlookPath(mapistub::g_pszOutlookQualifiedComponents[i], &b64);
if (!lpszTempPath.empty())
{
const auto lpszTempVer = new (std::nothrow) WCHAR[MAX_PATH];
const auto lpszTempLang = new (std::nothrow) WCHAR[MAX_PATH];
if (lpszTempVer && lpszTempLang)
{
DWORD dwValueBuf = MAX_PATH;
const auto hRes = WC_W32(import::pfnMsiGetFileVersion(
lpszTempPath.c_str(), lpszTempVer, &dwValueBuf, lpszTempLang, &dwValueBuf));
if (SUCCEEDED(hRes))
{
szOut = strings::formatmessage(
IDS_OUTLOOKVERSIONSTRING, lpszTempPath.c_str(), lpszTempVer, lpszTempLang);
szOut += strings::formatmessage(b64 ? IDS_TRUE : IDS_FALSE);
szOut += L"\n"; // STRING_OK
}
delete[] lpszTempLang;
delete[] lpszTempVer;
}
}
}
return szOut;
}
LPCWSTR AppArchitectureToString(const APPX_PACKAGE_ARCHITECTURE a)
{
switch (a)
{
case APPX_PACKAGE_ARCHITECTURE_X86:
return L"x86";
case APPX_PACKAGE_ARCHITECTURE_ARM:
return L"arm";
case APPX_PACKAGE_ARCHITECTURE_X64:
return L"x64";
case APPX_PACKAGE_ARCHITECTURE_NEUTRAL:
return L"neutral";
default:
return L"?";
}
}
// Most of this function is from https://msdn.microsoft.com/en-us/library/windows/desktop/dn270601(v=vs.85).aspx
// Return empty strings so the logic that calls this Lookup function can be handled accordingly
// Only if the API call works do we want to return anything other than an empty string
std::wstring GetFullName(_In_ LPCWSTR familyName, _In_ const UINT32 filter)
{
if (!import::pfnFindPackagesByPackageFamily)
{
output::DebugPrint(output::DBGGeneric, L"LookupFamilyName: FindPackagesByPackageFamily not found\n");
return L"";
}
UINT32 count = 0;
UINT32 length = 0;
auto rc =
import::pfnFindPackagesByPackageFamily(familyName, filter, &count, nullptr, &length, nullptr, nullptr);
if (rc == ERROR_SUCCESS)
{
output::DebugPrint(output::DBGGeneric, L"LookupFamilyName: No packages found\n");
return L"";
}
if (rc != ERROR_INSUFFICIENT_BUFFER)
{
output::DebugPrint(output::DBGGeneric, L"LookupFamilyName: Error %ld in FindPackagesByPackageFamily\n", rc);
return L"";
}
const auto fullNames = static_cast<LPWSTR*>(malloc(count * sizeof(LPWSTR)));
const auto buffer = static_cast<PWSTR>(malloc(length * sizeof(WCHAR)));
if (fullNames && buffer)
{
rc =
import::pfnFindPackagesByPackageFamily(familyName, filter, &count, fullNames, &length, buffer, nullptr);
if (rc != ERROR_SUCCESS)
{
output::DebugPrint(
output::DBGGeneric, L"LookupFamilyName: Error %d looking up Full Names from Family Names\n", rc);
}
}
std::wstring builds;
if (count && fullNames)
{
// We just take the first one.
builds = fullNames[0];
}
free(buffer);
free(fullNames);
return builds;
}
std::wstring GetPackageVersion(LPCWSTR fullname)
{
if (!import::pfnPackageIdFromFullName) return strings::emptystring;
UINT32 length = 0;
auto rc = import::pfnPackageIdFromFullName(fullname, 0, &length, nullptr);
if (rc == ERROR_SUCCESS)
{
output::DebugPrint(output::DBGGeneric, L"GetPackageId: Package not found\n");
return strings::emptystring;
}
if (rc != ERROR_INSUFFICIENT_BUFFER)
{
output::DebugPrint(output::DBGGeneric, L"GetPackageId: Error %ld in PackageIdFromFullName\n", rc);
return strings::emptystring;
}
std::wstring build;
const auto package_id = static_cast<PACKAGE_ID*>(malloc(length));
if (package_id)
{
rc = import::pfnPackageIdFromFullName(fullname, 0, &length, reinterpret_cast<BYTE*>(package_id));
if (rc != ERROR_SUCCESS)
{
output::DebugPrint(
output::DBGGeneric, L"PackageIdFromFullName: Error %d looking up ID from full name\n", rc);
}
else
{
build = strings::format(
L"%d.%d.%d.%d %ws",
package_id->version.Major,
package_id->version.Minor,
package_id->version.Build,
package_id->version.Revision,
AppArchitectureToString(static_cast<APPX_PACKAGE_ARCHITECTURE>(package_id->processorArchitecture)));
}
}
free(package_id);
return build;
}
std::wstring GetCentennialVersion()
{
// Check for Centennial Office
const auto familyName = L"Microsoft.Office.Desktop_8wekyb3d8bbwe";
const UINT32 filter =
PACKAGE_FILTER_BUNDLE | PACKAGE_FILTER_HEAD | PACKAGE_PROPERTY_BUNDLE | PACKAGE_PROPERTY_RESOURCE;
auto fullName = GetFullName(familyName, filter);
if (!fullName.empty())
{
return L"Microsoft Store Version: " + GetPackageVersion(fullName.c_str());
}
return strings::emptystring;
}
std::wstring GetOutlookVersionString()
{
auto szVersionString = GetMSIVersion();
if (szVersionString.empty())
{
szVersionString = GetCentennialVersion();
}
if (szVersionString.empty())
{
szVersionString = strings::loadstring(IDS_NOOUTLOOK);
}
return szVersionString;
}
} // namespace version
|
#include <core/stdafx.h>
#include <core/mapi/version.h>
#include <core/utility/import.h>
#include <core/mapi/stubutils.h>
#include <core/utility/strings.h>
#include <core/utility/output.h>
#include <core/utility/error.h>
#include <appmodel.h>
#include <AppxPackaging.h>
namespace version
{
std::wstring GetMSIVersion()
{
if (!import::pfnMsiProvideQualifiedComponent || !import::pfnMsiGetFileVersion) return strings::emptystring;
std::wstring szOut;
for (auto i = oqcOfficeBegin; i < oqcOfficeEnd; i++)
{
auto b64 = false;
auto lpszTempPath = mapistub::GetOutlookPath(mapistub::g_pszOutlookQualifiedComponents[i], &b64);
if (!lpszTempPath.empty())
{
const auto lpszTempVer = std::wstring(MAX_PATH, '\0');
const auto lpszTempLang = std::wstring(MAX_PATH, '\0');
DWORD dwValueBuf = MAX_PATH;
const auto hRes = WC_W32(import::pfnMsiGetFileVersion(
lpszTempPath.c_str(),
const_cast<wchar_t*>(lpszTempVer.c_str()),
&dwValueBuf,
const_cast<wchar_t*>(lpszTempLang.c_str()),
&dwValueBuf));
if (SUCCEEDED(hRes))
{
szOut = strings::formatmessage(
IDS_OUTLOOKVERSIONSTRING, lpszTempPath.c_str(), lpszTempVer.c_str(), lpszTempLang.c_str());
szOut += strings::formatmessage(b64 ? IDS_TRUE : IDS_FALSE);
szOut += L"\n"; // STRING_OK
}
}
}
return szOut;
}
LPCWSTR AppArchitectureToString(const APPX_PACKAGE_ARCHITECTURE a)
{
switch (a)
{
case APPX_PACKAGE_ARCHITECTURE_X86:
return L"x86";
case APPX_PACKAGE_ARCHITECTURE_ARM:
return L"arm";
case APPX_PACKAGE_ARCHITECTURE_X64:
return L"x64";
case APPX_PACKAGE_ARCHITECTURE_NEUTRAL:
return L"neutral";
default:
return L"?";
}
}
// Most of this function is from https://msdn.microsoft.com/en-us/library/windows/desktop/dn270601(v=vs.85).aspx
// Return empty strings so the logic that calls this Lookup function can be handled accordingly
// Only if the API call works do we want to return anything other than an empty string
std::wstring GetFullName(_In_ LPCWSTR familyName, _In_ const UINT32 filter)
{
if (!import::pfnFindPackagesByPackageFamily)
{
output::DebugPrint(output::DBGGeneric, L"LookupFamilyName: FindPackagesByPackageFamily not found\n");
return L"";
}
UINT32 count = 0;
UINT32 length = 0;
auto rc =
import::pfnFindPackagesByPackageFamily(familyName, filter, &count, nullptr, &length, nullptr, nullptr);
if (rc == ERROR_SUCCESS)
{
output::DebugPrint(output::DBGGeneric, L"LookupFamilyName: No packages found\n");
return L"";
}
if (rc != ERROR_INSUFFICIENT_BUFFER)
{
output::DebugPrint(output::DBGGeneric, L"LookupFamilyName: Error %ld in FindPackagesByPackageFamily\n", rc);
return L"";
}
const auto fullNames = static_cast<LPWSTR*>(malloc(count * sizeof(LPWSTR)));
const auto buffer = static_cast<PWSTR>(malloc(length * sizeof(WCHAR)));
if (fullNames && buffer)
{
rc =
import::pfnFindPackagesByPackageFamily(familyName, filter, &count, fullNames, &length, buffer, nullptr);
if (rc != ERROR_SUCCESS)
{
output::DebugPrint(
output::DBGGeneric, L"LookupFamilyName: Error %d looking up Full Names from Family Names\n", rc);
}
}
std::wstring builds;
if (count && fullNames)
{
// We just take the first one.
builds = fullNames[0];
}
free(buffer);
free(fullNames);
return builds;
}
std::wstring GetPackageVersion(LPCWSTR fullname)
{
if (!import::pfnPackageIdFromFullName) return strings::emptystring;
UINT32 length = 0;
auto rc = import::pfnPackageIdFromFullName(fullname, 0, &length, nullptr);
if (rc == ERROR_SUCCESS)
{
output::DebugPrint(output::DBGGeneric, L"GetPackageId: Package not found\n");
return strings::emptystring;
}
if (rc != ERROR_INSUFFICIENT_BUFFER)
{
output::DebugPrint(output::DBGGeneric, L"GetPackageId: Error %ld in PackageIdFromFullName\n", rc);
return strings::emptystring;
}
std::wstring build;
const auto package_id = static_cast<PACKAGE_ID*>(malloc(length));
if (package_id)
{
rc = import::pfnPackageIdFromFullName(fullname, 0, &length, reinterpret_cast<BYTE*>(package_id));
if (rc != ERROR_SUCCESS)
{
output::DebugPrint(
output::DBGGeneric, L"PackageIdFromFullName: Error %d looking up ID from full name\n", rc);
}
else
{
build = strings::format(
L"%d.%d.%d.%d %ws",
package_id->version.Major,
package_id->version.Minor,
package_id->version.Build,
package_id->version.Revision,
AppArchitectureToString(static_cast<APPX_PACKAGE_ARCHITECTURE>(package_id->processorArchitecture)));
}
}
free(package_id);
return build;
}
std::wstring GetCentennialVersion()
{
// Check for Centennial Office
const auto familyName = L"Microsoft.Office.Desktop_8wekyb3d8bbwe";
const UINT32 filter =
PACKAGE_FILTER_BUNDLE | PACKAGE_FILTER_HEAD | PACKAGE_PROPERTY_BUNDLE | PACKAGE_PROPERTY_RESOURCE;
auto fullName = GetFullName(familyName, filter);
if (!fullName.empty())
{
return L"Microsoft Store Version: " + GetPackageVersion(fullName.c_str());
}
return strings::emptystring;
}
std::wstring GetOutlookVersionString()
{
auto szVersionString = GetMSIVersion();
if (szVersionString.empty())
{
szVersionString = GetCentennialVersion();
}
if (szVersionString.empty())
{
szVersionString = strings::loadstring(IDS_NOOUTLOOK);
}
return szVersionString;
}
} // namespace version
|
remove some new
|
remove some new
|
C++
|
mit
|
stephenegriffin/mfcmapi,stephenegriffin/mfcmapi,stephenegriffin/mfcmapi
|
1de4609b77966411af14f336974d310f3c35ddcd
|
core/src/cell/cell.cc
|
core/src/cell/cell.cc
|
/**
* @file cell.cc
* @author Stavros Papadopoulos <[email protected]>
*
* @section LICENSE
*
* The MIT License
*
* Copyright (c) 2014 Stavros Papadopoulos <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* This file implements the class Cell.
*/
#include "cell.h"
#include "utils.h"
#include <iostream>
#include <string.h>
#include <assert.h>
/******************************************************
************* CONSTRUCTORS & DESTRUCTORS **************
******************************************************/
Cell::Cell(
const ArraySchema* array_schema,
int id_num,
bool random_access)
: array_schema_(array_schema),
random_access_(random_access),
id_num_(id_num) {
assert(id_num >= 0);
// Set attribute_ids_
attribute_ids_= array_schema_->attribute_ids();
// Set cell_size_ and var_size_
cell_size_ = array_schema_->cell_size() + id_num * sizeof(int64_t);
var_size_ = array_schema_->var_size();
}
Cell::Cell(
const void* cell,
const ArraySchema* array_schema,
int id_num,
bool random_access)
: array_schema_(array_schema),
id_num_(id_num),
random_access_(random_access) {
assert(id_num >= 0);
// Set attribute_ids_
attribute_ids_= array_schema_->attribute_ids();
// Set cell
set_cell(cell);
// Set cell_size_ and var_size_
cell_size_ = array_schema_->cell_size() + id_num * sizeof(int64_t);
var_size_ = array_schema_->var_size();
}
Cell::Cell(
const ArraySchema* array_schema,
const std::vector<int>& attribute_ids,
int id_num,
bool random_access)
: array_schema_(array_schema),
id_num_(id_num),
random_access_(random_access) {
assert(id_num >= 0);
// For easy reference
int attribute_num = array_schema->attribute_num();
// Checks
assert(attribute_ids.size() != 0);
assert(no_duplicates(attribute_ids));
assert(attribute_ids.back() == attribute_num);
// Set attribute_ids_
attribute_ids_= attribute_ids;
// Set cell_size_ and var_size_
cell_size_ = array_schema_->cell_size(attribute_ids_) +
id_num * sizeof(int64_t);
var_size_ = array_schema_->var_size();
}
Cell::~Cell() {
}
/******************************************************
********************* ACCESSORS ***********************
******************************************************/
const ArraySchema* Cell::array_schema() const {
return array_schema_;
}
int Cell::attribute_id(int i) const {
return attribute_ids_[i];
}
int Cell::attribute_num() const {
return attribute_ids_.size();
}
CellConstAttrIterator Cell::begin() const {
return CellConstAttrIterator(this, 0);
}
const void* Cell::cell() const {
return cell_;
}
ssize_t Cell::cell_size() const {
if(cell_ == NULL)
return 0;
if(!var_size_) {
return cell_size_;
} else {
size_t cell_size;
memcpy(&cell_size,
id_num_ * sizeof(int64_t) + array_schema_->coords_size() +
static_cast<const char*>(cell_),
sizeof(size_t));
return cell_size + id_num_ * sizeof(int64_t);
}
}
template<class T>
CSVLine Cell::csv_line(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const {
// For easy reference
int dim_num = array_schema_->dim_num();
int attribute_num = array_schema_->attribute_num();
// Initialization
CSVLine csv_line;
// Append ids
for(int i=0; i<id_num_; ++i)
csv_line << id(i);
// Append coordinates
const T* coords = (*this)[attribute_num];
for(int i=0; i<dim_ids.size(); ++i) {
assert(dim_ids[i] >= 0 && dim_ids[i] < array_schema_->dim_num());
csv_line << coords[dim_ids[i]];
}
// Append attribute values
for(int i=0; i<attribute_ids.size(); ++i) {
assert(attribute_ids[i] >= 0 && attribute_ids[i] < attribute_num);
const std::type_info* attr_type = array_schema_->type(attribute_ids[i]);
if(attr_type == &typeid(char)) {
if(var_size(attribute_ids[i])) // Special case for strings
append_string(attribute_ids[i], csv_line);
else
append_attribute<char>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(int)) {
append_attribute<int>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(int64_t)) {
append_attribute<int64_t>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(float)) {
append_attribute<float>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(double)) {
append_attribute<double>(attribute_ids[i], csv_line);
}
}
return csv_line;
}
int64_t Cell::id(int i) const {
assert(i >= 0 && i < id_num_);
int64_t id_r;
memcpy(&id_r,
static_cast<const char*>(cell_) + i * sizeof(int64_t),
sizeof(int64_t));
return id_r;
}
size_t Cell::ids_size() const {
return id_num_ * sizeof(int64_t);
}
int Cell::val_num(int attribute_id) const {
int val_num = array_schema_->val_num(attribute_id);
// Variable-lengthed attribute
if(val_num == VAR_SIZE) {
std::map<int, int>::const_iterator it = val_num_.find(attribute_id);
assert(it != val_num_.end());
val_num = it->second;
}
return val_num;
}
bool Cell::var_size() const {
return var_size_;
}
bool Cell::var_size(int attribute_id) const {
return array_schema_->cell_size(attribute_id) == VAR_SIZE;
}
/******************************************************
********************* MUTATORS ************************
******************************************************/
void Cell::set_cell(const void* cell) {
cell_ = cell;
// Initialization
if(cell_ != NULL && random_access_) {
init_val_num();
init_attribute_offsets();
}
}
/******************************************************
********************* OPERATORS ***********************
******************************************************/
TypeConverter Cell::operator[](int attribute_id) const {
// Soundness check
std::map<int, size_t>::const_iterator it =
attribute_offsets_.find(attribute_id);
assert(it != attribute_offsets_.end());
// Return the start of the attribute value
return TypeConverter(static_cast<const char*>(cell_) + it->second);
}
/******************************************************
***************** PRIVATE METHODS *********************
******************************************************/
template<class T>
void Cell::append_attribute(int attribute_id, CSVLine& csv_line) const {
int val_num = this->val_num(attribute_id);
bool var_size = this->var_size(attribute_id);
// Number of values for the case of variable-sized attribute
if(typeid(T) != typeid(char) && var_size)
csv_line << val_num;
// Append attribute values
const T* v;
if(!var_size) {
v = (*this)[attribute_id];
} else { // Skip the val_num
const void* temp =
static_cast<const char*>((*this)[attribute_id]) + sizeof(int);
v = static_cast<const T*>(temp);
}
for(int i=0; i<val_num; ++i) {
if(is_null(v[i]))
csv_line << NULL_VALUE;
else if(is_del(v[i]))
csv_line << DEL_VALUE;
else
csv_line << v[i];
}
}
void Cell::append_string(int attribute_id, CSVLine& csv_line) const {
int val_num = this->val_num(attribute_id);
std::string v;
v.resize(val_num);
const char* s = static_cast<const char*>((*this)[attribute_id]) + sizeof(int);
v.assign(s, val_num);
if(is_null(v[0])) {
csv_line << NULL_VALUE;
} else if(is_del(v[0]))
csv_line << DEL_VALUE;
else
csv_line << v;
}
void Cell::init_attribute_offsets() {
attribute_offsets_.clear();
// Coordinates
attribute_offsets_[array_schema_->attribute_num()] =
id_num_ * sizeof(int64_t);
// Attributes
CellConstAttrIterator attr_it = begin();
for(; !attr_it.end(); ++attr_it)
attribute_offsets_[attr_it.attribute_id()] = attr_it.offset();
}
void Cell::init_val_num() {
val_num_.clear();
// For easy reference
int attribute_num = array_schema_->attribute_num();
if(var_size_) {
size_t offset = id_num_ * sizeof(int64_t) + sizeof(size_t) +
array_schema_->cell_size(attribute_num);
// For all attributes (excluding coordinates)
int val_num;
for(int i=0; i<attribute_ids_.size()-1; ++i) {
val_num = array_schema_->val_num(attribute_ids_[i]);
if(val_num == VAR_SIZE) {
memcpy(&val_num, static_cast<const char*>(cell_) + offset, sizeof(int));
offset += sizeof(int);
}
offset += val_num * array_schema_->type_size(attribute_ids_[i]);
val_num_[attribute_ids_[i]] = val_num;
}
}
}
// Explicit template instantiations
template CSVLine Cell::csv_line<int>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
template CSVLine Cell::csv_line<int64_t>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
template CSVLine Cell::csv_line<float>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
template CSVLine Cell::csv_line<double>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
|
/**
* @file cell.cc
* @author Stavros Papadopoulos <[email protected]>
*
* @section LICENSE
*
* The MIT License
*
* Copyright (c) 2014 Stavros Papadopoulos <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* This file implements the class Cell.
*/
#include "cell.h"
#include "utils.h"
#include <iostream>
#include <string.h>
#include <assert.h>
/******************************************************
************* CONSTRUCTORS & DESTRUCTORS **************
******************************************************/
Cell::Cell(
const ArraySchema* array_schema,
int id_num,
bool random_access)
: array_schema_(array_schema),
random_access_(random_access),
id_num_(id_num) {
assert(id_num >= 0);
// Set attribute_ids_
attribute_ids_= array_schema_->attribute_ids();
// Set cell_size_ and var_size_
cell_size_ = array_schema_->cell_size() + id_num * sizeof(int64_t);
var_size_ = array_schema_->var_size();
}
Cell::Cell(
const void* cell,
const ArraySchema* array_schema,
int id_num,
bool random_access)
: array_schema_(array_schema),
id_num_(id_num),
random_access_(random_access) {
assert(id_num >= 0);
// Set attribute_ids_
attribute_ids_= array_schema_->attribute_ids();
// Set cell
set_cell(cell);
// Set cell_size_ and var_size_
cell_size_ = array_schema_->cell_size() + id_num * sizeof(int64_t);
var_size_ = array_schema_->var_size();
}
Cell::Cell(
const ArraySchema* array_schema,
const std::vector<int>& attribute_ids,
int id_num,
bool random_access)
: array_schema_(array_schema),
id_num_(id_num),
random_access_(random_access) {
assert(id_num >= 0);
// For easy reference
int attribute_num = array_schema->attribute_num();
// Checks
assert(attribute_ids.size() != 0);
assert(no_duplicates(attribute_ids));
assert(attribute_ids.back() == attribute_num);
// Set attribute_ids_
attribute_ids_= attribute_ids;
// Set cell_size_ and var_size_
cell_size_ = array_schema->cell_size(attribute_ids_);
var_size_ = (cell_size_ == VAR_SIZE);
if(!var_size_)
cell_size_ = array_schema_->cell_size(attribute_ids_) +
id_num * sizeof(int64_t);
}
Cell::~Cell() {
}
/******************************************************
********************* ACCESSORS ***********************
******************************************************/
const ArraySchema* Cell::array_schema() const {
return array_schema_;
}
int Cell::attribute_id(int i) const {
return attribute_ids_[i];
}
int Cell::attribute_num() const {
return attribute_ids_.size();
}
CellConstAttrIterator Cell::begin() const {
return CellConstAttrIterator(this, 0);
}
const void* Cell::cell() const {
return cell_;
}
ssize_t Cell::cell_size() const {
if(cell_ == NULL)
return 0;
if(!var_size_) {
return cell_size_;
} else {
size_t cell_size;
memcpy(&cell_size,
id_num_ * sizeof(int64_t) + array_schema_->coords_size() +
static_cast<const char*>(cell_),
sizeof(size_t));
return cell_size + id_num_ * sizeof(int64_t);
}
}
template<class T>
CSVLine Cell::csv_line(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const {
// For easy reference
int dim_num = array_schema_->dim_num();
int attribute_num = array_schema_->attribute_num();
// Initialization
CSVLine csv_line;
// Append ids
for(int i=0; i<id_num_; ++i)
csv_line << id(i);
// Append coordinates
const T* coords = (*this)[attribute_num];
for(int i=0; i<dim_ids.size(); ++i) {
assert(dim_ids[i] >= 0 && dim_ids[i] < array_schema_->dim_num());
csv_line << coords[dim_ids[i]];
}
// Append attribute values
for(int i=0; i<attribute_ids.size(); ++i) {
assert(attribute_ids[i] >= 0 && attribute_ids[i] < attribute_num);
const std::type_info* attr_type = array_schema_->type(attribute_ids[i]);
if(attr_type == &typeid(char)) {
if(var_size(attribute_ids[i])) // Special case for strings
append_string(attribute_ids[i], csv_line);
else
append_attribute<char>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(int)) {
append_attribute<int>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(int64_t)) {
append_attribute<int64_t>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(float)) {
append_attribute<float>(attribute_ids[i], csv_line);
} else if(attr_type == &typeid(double)) {
append_attribute<double>(attribute_ids[i], csv_line);
}
}
return csv_line;
}
int64_t Cell::id(int i) const {
assert(i >= 0 && i < id_num_);
int64_t id_r;
memcpy(&id_r,
static_cast<const char*>(cell_) + i * sizeof(int64_t),
sizeof(int64_t));
return id_r;
}
size_t Cell::ids_size() const {
return id_num_ * sizeof(int64_t);
}
int Cell::val_num(int attribute_id) const {
int val_num = array_schema_->val_num(attribute_id);
// Variable-lengthed attribute
if(val_num == VAR_SIZE) {
std::map<int, int>::const_iterator it = val_num_.find(attribute_id);
assert(it != val_num_.end());
val_num = it->second;
}
return val_num;
}
bool Cell::var_size() const {
return var_size_;
}
bool Cell::var_size(int attribute_id) const {
return array_schema_->cell_size(attribute_id) == VAR_SIZE;
}
/******************************************************
********************* MUTATORS ************************
******************************************************/
void Cell::set_cell(const void* cell) {
cell_ = cell;
// Initialization
if(cell_ != NULL && random_access_) {
init_val_num();
init_attribute_offsets();
}
}
/******************************************************
********************* OPERATORS ***********************
******************************************************/
TypeConverter Cell::operator[](int attribute_id) const {
// Soundness check
std::map<int, size_t>::const_iterator it =
attribute_offsets_.find(attribute_id);
assert(it != attribute_offsets_.end());
// Return the start of the attribute value
return TypeConverter(static_cast<const char*>(cell_) + it->second);
}
/******************************************************
***************** PRIVATE METHODS *********************
******************************************************/
template<class T>
void Cell::append_attribute(int attribute_id, CSVLine& csv_line) const {
int val_num = this->val_num(attribute_id);
bool var_size = this->var_size(attribute_id);
// Number of values for the case of variable-sized attribute
if(typeid(T) != typeid(char) && var_size)
csv_line << val_num;
// Append attribute values
const T* v;
if(!var_size) {
v = (*this)[attribute_id];
} else { // Skip the val_num
const void* temp =
static_cast<const char*>((*this)[attribute_id]) + sizeof(int);
v = static_cast<const T*>(temp);
}
for(int i=0; i<val_num; ++i) {
if(is_null(v[i]))
csv_line << NULL_VALUE;
else if(is_del(v[i]))
csv_line << DEL_VALUE;
else
csv_line << v[i];
}
}
void Cell::append_string(int attribute_id, CSVLine& csv_line) const {
int val_num = this->val_num(attribute_id);
std::string v;
v.resize(val_num);
const char* s = static_cast<const char*>((*this)[attribute_id]) + sizeof(int);
v.assign(s, val_num);
if(is_null(v[0])) {
csv_line << NULL_VALUE;
} else if(is_del(v[0]))
csv_line << DEL_VALUE;
else
csv_line << v;
}
void Cell::init_attribute_offsets() {
attribute_offsets_.clear();
// Coordinates
attribute_offsets_[array_schema_->attribute_num()] =
id_num_ * sizeof(int64_t);
// Attributes
CellConstAttrIterator attr_it = begin();
for(; !attr_it.end(); ++attr_it)
attribute_offsets_[attr_it.attribute_id()] = attr_it.offset();
}
void Cell::init_val_num() {
val_num_.clear();
// For easy reference
int attribute_num = array_schema_->attribute_num();
if(var_size_) {
size_t offset = id_num_ * sizeof(int64_t) + sizeof(size_t) +
array_schema_->cell_size(attribute_num);
// For all attributes (excluding coordinates)
int val_num;
for(int i=0; i<attribute_ids_.size()-1; ++i) {
val_num = array_schema_->val_num(attribute_ids_[i]);
if(val_num == VAR_SIZE) {
memcpy(&val_num, static_cast<const char*>(cell_) + offset, sizeof(int));
offset += sizeof(int);
}
offset += val_num * array_schema_->type_size(attribute_ids_[i]);
val_num_[attribute_ids_[i]] = val_num;
}
}
}
// Explicit template instantiations
template CSVLine Cell::csv_line<int>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
template CSVLine Cell::csv_line<int64_t>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
template CSVLine Cell::csv_line<float>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
template CSVLine Cell::csv_line<double>(
const std::vector<int>& dim_ids,
const std::vector<int>& attribute_ids) const;
|
Check for var_size if only a subset of attributes are requested while constructing a Cell object. The logic should be the same as that used in array_cell_iterator.
|
Check for var_size if only a subset of attributes are requested while
constructing a Cell object. The logic should be the same as that used in
array_cell_iterator.
|
C++
|
mit
|
TileDB-Inc/TileDB,TileDB-Inc/TileDB,TileDB-Inc/TileDB,npapa/TileDB,kavskalyan/TileDB,kavskalyan/TileDB,Intel-HLS/TileDB,Intel-HLS/TileDB,TileDB-Inc/TileDB,npapa/TileDB
|
c53caa565439d2258cac68d6ad087fdd2c5cfce6
|
src/mocc-core/pin_mesh_rect.cpp
|
src/mocc-core/pin_mesh_rect.cpp
|
#include "pin_mesh_rect.hpp"
#include <algorithm>
#include <cassert>
#include "error.hpp"
namespace mocc {
PinMesh_Rect::PinMesh_Rect( const pugi::xml_node &input ):
PinMesh( input )
{
// Parse the number of x and y divisions
int ndiv_x = input.child("sub_x").text().as_int(0);
if (ndiv_x < 1) {
Error("Failed to read valid number of X divisions in rect pin mesh.");
}
int ndiv_y = input.child("sub_y").text().as_int(0);
if (ndiv_y < 1) {
Error("Failed to read valid number of Y divisions in rect pin mesh.");
}
n_xsreg_ = ndiv_x * ndiv_y;
n_reg_ = ndiv_x * ndiv_y;
float dx = pitch_x_/ndiv_x;
float dy = pitch_y_/ndiv_y;
float h_pitch_x = 0.5*pitch_x_;
float h_pitch_y = 0.5*pitch_y_;
for (int i=1; i<ndiv_x; i++) {
hx_.push_back( i*dx-h_pitch_x );
}
for (int i=1; i<ndiv_y; i++) {
hy_.push_back( i*dy-h_pitch_y );
}
// Form lines representing the mesh boundaries
for ( auto &xi: hx_ ) {
lines_.push_back( Line( Point2(xi, -h_pitch_y),
Point2(xi, h_pitch_y) ) );
}
for ( auto &yi: hy_ ) {
lines_.push_back( Line( Point2(-h_pitch_x, yi),
Point2( h_pitch_x, yi) ) );
}
// Determine FSR volumes
vol_ = VecF(n_reg_, dx*dy);
return;
}
int PinMesh_Rect::trace( Point2 p1, Point2 p2, int first_reg, VecF &s,
VecI ® ) const {
// Make a vector to store the collision points and add the start and end
// points to it
std::vector<Point2> ps;
ps.push_back(p1);
ps.push_back(p2);
// Create a line object for the input points to test for collisions with
Line l(p1, p2);
// Test for collisions with all of the lines in the mesh
for (auto &li: lines_) {
Point2 p;
int ret = Intersect( li, l, p );
if( ret == 1 ) {
ps.push_back(p);
}
}
// Sort the points
std::sort( ps.begin(), ps.end() );
ps.erase( std::unique(ps.begin(), ps.end()), ps.end() );
// Determine segment lengths and region indices
for( unsigned int ip=1; ip<ps.size(); ip++ ) {
s.push_back( ps[ip].distance(ps[ip-1]) );
reg.push_back( this->find_reg( Midpoint(ps[ip], ps[ip-1]) )
+ first_reg );
}
return ps.size()-1;
}
// Return an integer containing the pin-local FSR index in which the passed
// Point resides.
//
// In the rectangular mesh, the indices are ordered naturally. The first
// region is in the lower left, the last in the upper right, proceeding
// first in the x direction, then in the y. nothing too fancy.
int PinMesh_Rect::find_reg( Point2 p ) const {
// Make sure the point is inside the pin
if( fabs(p.x) > 0.5*pitch_x_ ) {
return -1;
}
if( fabs(p.y) > 0.5*pitch_y_ ) {
return -1;
}
unsigned int ix;
for( ix=0; ix<hx_.size(); ix++ ) {
if( hx_[ix] > p.x ) {
break;
}
}
unsigned int iy;
for( iy=0; iy<hy_.size(); iy++ ) {
if( hy_[iy] > p.y ) {
break;
}
}
unsigned int ireg = (hx_.size()+1)*iy + ix;
assert(ireg < n_reg_);
return ireg;
}
}
|
#include "pin_mesh_rect.hpp"
#include <algorithm>
#include <cassert>
#include "error.hpp"
namespace mocc {
PinMesh_Rect::PinMesh_Rect( const pugi::xml_node &input ):
PinMesh( input )
{
// Parse the number of x and y divisions
int ndiv_x = input.child("sub_x").text().as_int(0);
if (ndiv_x < 1) {
Error("Failed to read valid number of X divisions in rect pin mesh.");
}
int ndiv_y = input.child("sub_y").text().as_int(0);
if (ndiv_y < 1) {
Error("Failed to read valid number of Y divisions in rect pin mesh.");
}
n_xsreg_ = ndiv_x * ndiv_y;
n_reg_ = ndiv_x * ndiv_y;
real_t dx = pitch_x_/ndiv_x;
real_t dy = pitch_y_/ndiv_y;
real_t h_pitch_x = 0.5*pitch_x_;
real_t h_pitch_y = 0.5*pitch_y_;
for (int i=1; i<ndiv_x; i++) {
hx_.push_back( i*dx-h_pitch_x );
}
for (int i=1; i<ndiv_y; i++) {
hy_.push_back( i*dy-h_pitch_y );
}
// Form lines representing the mesh boundaries
for ( auto &xi: hx_ ) {
lines_.push_back( Line( Point2(xi, -h_pitch_y),
Point2(xi, h_pitch_y) ) );
}
for ( auto &yi: hy_ ) {
lines_.push_back( Line( Point2(-h_pitch_x, yi),
Point2( h_pitch_x, yi) ) );
}
// Determine FSR volumes
vol_ = VecF(n_reg_, dx*dy);
return;
}
int PinMesh_Rect::trace( Point2 p1, Point2 p2, int first_reg, VecF &s,
VecI ® ) const {
// Make a vector to store the collision points and add the start and end
// points to it
std::vector<Point2> ps;
ps.push_back(p1);
ps.push_back(p2);
// Create a line object for the input points to test for collisions with
Line l(p1, p2);
// Test for collisions with all of the lines in the mesh
for (auto &li: lines_) {
Point2 p;
int ret = Intersect( li, l, p );
if( ret == 1 ) {
ps.push_back(p);
}
}
// Sort the points
std::sort( ps.begin(), ps.end() );
ps.erase( std::unique(ps.begin(), ps.end()), ps.end() );
// Determine segment lengths and region indices
for( unsigned int ip=1; ip<ps.size(); ip++ ) {
s.push_back( ps[ip].distance(ps[ip-1]) );
reg.push_back( this->find_reg( Midpoint(ps[ip], ps[ip-1]) )
+ first_reg );
}
return ps.size()-1;
}
// Return an integer containing the pin-local FSR index in which the passed
// Point resides.
//
// In the rectangular mesh, the indices are ordered naturally. The first
// region is in the lower left, the last in the upper right, proceeding
// first in the x direction, then in the y. nothing too fancy.
int PinMesh_Rect::find_reg( Point2 p ) const {
// Make sure the point is inside the pin
if( fabs(p.x) > 0.5*pitch_x_ ) {
return -1;
}
if( fabs(p.y) > 0.5*pitch_y_ ) {
return -1;
}
unsigned int ix;
for( ix=0; ix<hx_.size(); ix++ ) {
if( hx_[ix] > p.x ) {
break;
}
}
unsigned int iy;
for( iy=0; iy<hy_.size(); iy++ ) {
if( hy_[iy] > p.y ) {
break;
}
}
unsigned int ireg = (hx_.size()+1)*iy + ix;
assert(ireg < n_reg_);
return ireg;
}
}
|
Replace 'float' with 'real_t' in rect pin mesh
|
Replace 'float' with 'real_t' in rect pin mesh
There were some convergence issues in 2d3d from pricision of the mesh
representation. The single-precision in the mesh was leading to poor homogenized
values.
|
C++
|
apache-2.0
|
youngmit/mocc,youngmit/mocc,youngmit/mocc,youngmit/mocc
|
73a3182ccd2580f116f058a0e088bfc9e30e3af1
|
tests/test-progs/dtu/random/main.cpp
|
tests/test-progs/dtu/random/main.cpp
|
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include "../dtu.h"
#ifndef PE_ID
#define PE_ID (-1)
#endif
void pe_printf(const char *format, ...)
{
va_list args;
printf("PE%d: ", PE_ID);
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
}
void printMessage(uint8_t* message, unsigned ep)
{
MessageHeader* header = reinterpret_cast<MessageHeader*>(message);
message = message + sizeof(MessageHeader);
int start = message[0];
bool valid = true;
for (int i = 0; i < header->length; i++)
{
if (message[i] != (start + i) % 256)
{
valid = false;
break;
}
}
pe_printf("ep%u, Received %s of %d bytes from PE%d (ep %d): %s",
ep,
header->flags & 1 ? "reply" : "message",
header->length,
header->senderCoreId,
header->senderEpId,
valid ? "valid" : "invalid");
if (!valid)
{
printf("PE%u: ep%u, invalid message:", PE_ID, ep);
for (int i = 0; i < header->length; i++)
printf( " %2.2x", message[i]);
printf("\n");
}
}
int main()
{
pe_printf("Hello World!");
srand(PE_ID);
pe_printf("setup endpoints");
uint8_t* messageBuffer = (uint8_t*) malloc(58);
// ringbuffers
uint8_t* ep2_buffer = (uint8_t*) malloc(1024);
uint8_t* ep3_buffer = (uint8_t*) malloc(1024);
uint8_t* ep4_buffer = (uint8_t*) malloc(1024);
uint8_t* ep5_buffer = (uint8_t*) malloc(1024);
// endpoints 0 and 1 send messages
dtuEndpoints[0].mode = 1;
dtuEndpoints[0].maxMessageSize = 64;
dtuEndpoints[0].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[0].credits = 64;
dtuEndpoints[0].label = 0xDEADBEEFC0DEFEED;
dtuEndpoints[0].replyLabel = 0xFEDCBA0987654321;
dtuEndpoints[1].mode = 1;
dtuEndpoints[1].maxMessageSize = 64;
dtuEndpoints[1].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[1].credits = 64;
dtuEndpoints[1].label = 0xDEADBEEFC0DEFEED;
dtuEndpoints[1].replyLabel = 0xFEDCBA0987654321;
// endpoints 2 and 3 receive messages
dtuEndpoints[2].mode = 0;
dtuEndpoints[2].maxMessageSize = 64;
dtuEndpoints[2].bufferSize = 16;
dtuEndpoints[2].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[2].bufferAddr = reinterpret_cast<uint64_t>(ep2_buffer);
dtuEndpoints[2].bufferReadPtr = reinterpret_cast<uint64_t>(ep2_buffer);
dtuEndpoints[2].bufferWritePtr = reinterpret_cast<uint64_t>(ep2_buffer);
dtuEndpoints[3].mode = 0;
dtuEndpoints[3].maxMessageSize = 64;
dtuEndpoints[3].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[3].bufferSize = 16;
dtuEndpoints[3].bufferAddr = reinterpret_cast<uint64_t>(ep3_buffer);
dtuEndpoints[3].bufferReadPtr = reinterpret_cast<uint64_t>(ep3_buffer);
dtuEndpoints[3].bufferWritePtr = reinterpret_cast<uint64_t>(ep3_buffer);
// endpoints 4 and 5 receive replies
dtuEndpoints[4].mode = 0;
dtuEndpoints[4].maxMessageSize = 64;
dtuEndpoints[4].bufferSize = 16;
dtuEndpoints[4].bufferAddr = reinterpret_cast<uint64_t>(ep4_buffer);
dtuEndpoints[4].bufferReadPtr = reinterpret_cast<uint64_t>(ep4_buffer);
dtuEndpoints[4].bufferWritePtr = reinterpret_cast<uint64_t>(ep4_buffer);
dtuEndpoints[5].mode = 0;
dtuEndpoints[5].maxMessageSize = 64;
dtuEndpoints[5].bufferSize = 16;
dtuEndpoints[5].bufferAddr = reinterpret_cast<uint64_t>(ep5_buffer);
dtuEndpoints[5].bufferReadPtr = reinterpret_cast<uint64_t>(ep5_buffer);
dtuEndpoints[5].bufferWritePtr = reinterpret_cast<uint64_t>(ep5_buffer);
while(true)
{
for (int ep = 2; ep <= 5; ep++)
{
if(dtuEndpoints[ep].bufferMessageCount > 0)
{
uint8_t* message =
reinterpret_cast<uint8_t*>(dtuEndpoints[ep].bufferReadPtr);
printMessage(message, ep);
if (ep < 4) // send reply only if we received a message
{
// choose parameters randomly
dtuEndpoints[ep].messageSize = rand() % 42 + 1; // 1 to 42 (+22 for header)
// fill message buffer with data
uint8_t start = rand();
for (unsigned i = 0; i < dtuEndpoints[ep].messageSize; i++)
messageBuffer[i] = start + i;
pe_printf("ep %u: Send reply of %u bytes",
ep,
dtuEndpoints[ep].messageSize);
*dtuCommandPtr = 0x1 | (ep << 2);
// wait until operation finished
while (*dtuStatusPtr);
}
// increment read pointer
*dtuCommandPtr = 0x2 | (ep << 2);
}
}
if(rand() % 8 == 0)
{
unsigned ep = rand() % 2; // 0 or 1
if (dtuEndpoints[ep].credits >= 64)
{
// choose parameters randomly
dtuEndpoints[ep].messageSize = rand() % 42 + 1; // 1 to 42 (+22 for header)
dtuEndpoints[ep].targetCoreId = rand() % 8; // 0 to 7
dtuEndpoints[ep].targetEpId = rand() % 2 + 2; // 2 or 3
dtuEndpoints[ep].replyEpId = rand() % 2 + 4; // 4 or 5
// fill message buffer with data
uint8_t start = rand();
for (unsigned i = 0; i < dtuEndpoints[ep].messageSize; i++)
messageBuffer[i] = start + i;
pe_printf("ep %d: Send message of %u bytes to PE%u (ep %u, reply %d)",
ep,
dtuEndpoints[ep].messageSize,
dtuEndpoints[ep].targetCoreId,
dtuEndpoints[ep].targetEpId,
dtuEndpoints[ep].replyEpId);
*dtuCommandPtr = 0x1 | (ep << 2);
// wait until operation finished
while (*dtuStatusPtr);
}
}
}
}
|
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include "../dtu.h"
#ifndef PE_ID
#define PE_ID (-1)
#endif
void pe_printf(const char *format, ...)
{
va_list args;
printf("PE%d: ", PE_ID);
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
}
void printMessage(uint8_t* message, unsigned ep)
{
MessageHeader* header = reinterpret_cast<MessageHeader*>(message);
message = message + sizeof(MessageHeader);
int start = message[0];
bool valid = true;
for (int i = 0; i < header->length; i++)
{
if (message[i] != (start + i) % 256)
{
valid = false;
break;
}
}
pe_printf("ep%u, Received %s of %d bytes @ %p from PE%d (ep %d): %s",
ep,
header->flags & 1 ? "reply" : "message",
header->length,
header,
header->senderCoreId,
header->senderEpId,
valid ? "valid" : "invalid");
if (!valid)
{
printf("PE%u: ep%u, invalid message:", PE_ID, ep);
for (int i = 0; i < header->length; i++)
printf( " %2.2x", message[i]);
printf("\n");
}
}
int main()
{
pe_printf("Hello World!");
srand(PE_ID);
pe_printf("setup endpoints");
uint8_t* messageBuffer = (uint8_t*) malloc(58);
// ringbuffers
uint8_t* ep2_buffer = (uint8_t*) malloc(1024);
uint8_t* ep3_buffer = (uint8_t*) malloc(1024);
uint8_t* ep4_buffer = (uint8_t*) malloc(1024);
uint8_t* ep5_buffer = (uint8_t*) malloc(1024);
// endpoints 0 and 1 send messages
dtuEndpoints[0].mode = 1;
dtuEndpoints[0].maxMessageSize = 64;
dtuEndpoints[0].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[0].credits = 64;
dtuEndpoints[0].label = 0xDEADBEEFC0DEFEED;
dtuEndpoints[0].replyLabel = 0xFEDCBA0987654321;
dtuEndpoints[1].mode = 1;
dtuEndpoints[1].maxMessageSize = 64;
dtuEndpoints[1].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[1].credits = 64;
dtuEndpoints[1].label = 0xDEADBEEFC0DEFEED;
dtuEndpoints[1].replyLabel = 0xFEDCBA0987654321;
// endpoints 2 and 3 receive messages
dtuEndpoints[2].mode = 0;
dtuEndpoints[2].maxMessageSize = 64;
dtuEndpoints[2].bufferSize = 16;
dtuEndpoints[2].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[2].bufferAddr = reinterpret_cast<uint64_t>(ep2_buffer);
dtuEndpoints[2].bufferReadPtr = reinterpret_cast<uint64_t>(ep2_buffer);
dtuEndpoints[2].bufferWritePtr = reinterpret_cast<uint64_t>(ep2_buffer);
dtuEndpoints[3].mode = 0;
dtuEndpoints[3].maxMessageSize = 64;
dtuEndpoints[3].messageAddr = reinterpret_cast<uint64_t>(messageBuffer);
dtuEndpoints[3].bufferSize = 16;
dtuEndpoints[3].bufferAddr = reinterpret_cast<uint64_t>(ep3_buffer);
dtuEndpoints[3].bufferReadPtr = reinterpret_cast<uint64_t>(ep3_buffer);
dtuEndpoints[3].bufferWritePtr = reinterpret_cast<uint64_t>(ep3_buffer);
// endpoints 4 and 5 receive replies
dtuEndpoints[4].mode = 0;
dtuEndpoints[4].maxMessageSize = 64;
dtuEndpoints[4].bufferSize = 16;
dtuEndpoints[4].bufferAddr = reinterpret_cast<uint64_t>(ep4_buffer);
dtuEndpoints[4].bufferReadPtr = reinterpret_cast<uint64_t>(ep4_buffer);
dtuEndpoints[4].bufferWritePtr = reinterpret_cast<uint64_t>(ep4_buffer);
dtuEndpoints[5].mode = 0;
dtuEndpoints[5].maxMessageSize = 64;
dtuEndpoints[5].bufferSize = 16;
dtuEndpoints[5].bufferAddr = reinterpret_cast<uint64_t>(ep5_buffer);
dtuEndpoints[5].bufferReadPtr = reinterpret_cast<uint64_t>(ep5_buffer);
dtuEndpoints[5].bufferWritePtr = reinterpret_cast<uint64_t>(ep5_buffer);
while(true)
{
for (int ep = 2; ep <= 5; ep++)
{
if(dtuEndpoints[ep].bufferMessageCount > 0)
{
uint8_t* message =
reinterpret_cast<uint8_t*>(dtuEndpoints[ep].bufferReadPtr);
printMessage(message, ep);
if (ep < 4) // send reply only if we received a message
{
// choose parameters randomly
dtuEndpoints[ep].messageSize = rand() % 42 + 1; // 1 to 42 (+22 for header)
// fill message buffer with data
uint8_t start = rand();
for (unsigned i = 0; i < dtuEndpoints[ep].messageSize; i++)
messageBuffer[i] = start + i;
pe_printf("ep %u: Send reply of %u bytes",
ep,
dtuEndpoints[ep].messageSize);
*dtuCommandPtr = 0x1 | (ep << 2);
// wait until operation finished
while (*dtuStatusPtr);
}
// increment read pointer
*dtuCommandPtr = 0x2 | (ep << 2);
}
}
if(rand() % 8 == 0)
{
unsigned ep = rand() % 2; // 0 or 1
if (dtuEndpoints[ep].credits >= 64)
{
// choose parameters randomly
dtuEndpoints[ep].messageSize = rand() % 42 + 1; // 1 to 42 (+22 for header)
dtuEndpoints[ep].targetCoreId = rand() % 8; // 0 to 7
dtuEndpoints[ep].targetEpId = rand() % 2 + 2; // 2 or 3
dtuEndpoints[ep].replyEpId = rand() % 2 + 4; // 4 or 5
// fill message buffer with data
uint8_t start = rand();
for (unsigned i = 0; i < dtuEndpoints[ep].messageSize; i++)
messageBuffer[i] = start + i;
pe_printf("ep %d: Send message of %u bytes to PE%u (ep %u, reply %d)",
ep,
dtuEndpoints[ep].messageSize,
dtuEndpoints[ep].targetCoreId,
dtuEndpoints[ep].targetEpId,
dtuEndpoints[ep].replyEpId);
*dtuCommandPtr = 0x1 | (ep << 2);
// wait until operation finished
while (*dtuStatusPtr);
}
}
}
}
|
print address of message.
|
dtu-test-progs: print address of message.
|
C++
|
bsd-3-clause
|
TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu
|
22a9e06e326c18152b7c804d60a589c2bf81c062
|
src/parser/lomse_xml_parser.cpp
|
src/parser/lomse_xml_parser.cpp
|
//---------------------------------------------------------------------------------------
// This file is part of the Lomse library.
// Lomse is copyrighted work (c) 2010-2016. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// For any comment, suggestion or feature request, please contact the manager of
// the project at [email protected]
//---------------------------------------------------------------------------------------
#include "lomse_xml_parser.h"
#include <iostream>
#include <ostream>
#include <sstream>
#include <vector>
using namespace std;
//---------------------------------------------------------------------------------------
//AWARE: Microsoft deprecated fopen() but the "security enhanced" new function
//fopen_s() is only defined by Microsoft which "coincidentally" makes your code
//non-portable.
//
//The addressed security issue is, basically, for files opened for writing.
//Microsoft improves security by opening the file with exclusive access.
//
//This is not needed in this source code, as the file is opened for read, but there
//is a need to suppress the annoying Microsoft warnings, which is not easy.
//Thanks Microsoft!
//
//See:
// https://stackoverflow.com/questions/906599/why-cant-i-use-fopen
// https://stackoverflow.com/questions/858252/alternatives-to-ms-strncpy-s
//
#if (defined(_MSC_VER) && (_MSC_VER >= 1400) )
#include <cstdio>
inline extern FILE* my_fopen_s(char *fname, char *mode)
{
FILE *fptr;
fopen_s(&fptr, fname, mode);
return fptr;
}
#define fopen(fname, mode) my_fopen_s((fname), mode))
#else
#define fopen_s(fp, fmt, mode) *(fp)=fopen( (fmt), (mode))
#endif
//---------------------------------------------------------------------------------------
namespace lomse
{
//=======================================================================================
// XmlNode implementation
//=======================================================================================
int XmlNode::type()
{
switch( m_node.type() )
{
case pugi::node_null: return XmlNode::k_node_null;
case pugi::node_document: return XmlNode::k_node_document;
case pugi::node_element: return XmlNode::k_node_element;
case pugi::node_pcdata: return XmlNode::k_node_pcdata;
case pugi::node_cdata: return XmlNode::k_node_cdata;
case pugi::node_comment: return XmlNode::k_node_comment;
case pugi::node_pi: return XmlNode::k_node_pi;
case pugi::node_declaration: return XmlNode::k_node_declaration;
case pugi::node_doctype: return XmlNode::k_node_doctype;
default: return XmlNode::k_node_unknown;
}
}
//---------------------------------------------------------------------------------------
string XmlNode::value()
{
//Depending on node type,
//name or value may be absent. node_document nodes do not have a name or value,
//node_element and node_declaration nodes always have a name but never have a value,
//node_pcdata, node_cdata, node_comment and node_doctype nodes never have a
//name but always have a value (it may be empty though), node_pi nodes always
//have a name and a value (again, value may be empty).
if (m_node.type() == pugi::node_pcdata)
return string(m_node.value());
if (m_node.type() == pugi::node_element)
{
pugi::xml_node child = m_node.first_child();
return string(child.value());
}
return "";
}
//---------------------------------------------------------------------------------------
ptrdiff_t XmlNode::offset()
{
return m_node.offset_debug();
}
//=======================================================================================
// XmlParser implementation
//=======================================================================================
XmlParser::XmlParser(ostream& reporter)
: Parser(reporter)
, m_root()
, m_errorOffset(0)
, m_fOffsetDataReady(false)
{
}
//---------------------------------------------------------------------------------------
XmlParser::~XmlParser()
{
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_text(const std::string& sourceText)
{
parse_char_string( const_cast<char*>(sourceText.c_str()) );
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_cstring(char* sourceText)
{
parse_char_string(sourceText);
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_file(const std::string& filename, bool UNUSED(fErrorMsg))
{
m_fOffsetDataReady = false;
m_filename = filename;
pugi::xml_parse_result result = m_doc.load_file(filename.c_str(),
(pugi::parse_default |
//pugi::parse_trim_pcdata |
//pugi::parse_wnorm_attribute |
pugi::parse_declaration)
);
if (!result)
{
m_errorMsg = string(result.description());
m_errorOffset = result.offset;
}
find_root();
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_char_string(char* str)
{
m_fOffsetDataReady = false;
m_filename.clear();
pugi::xml_parse_result result = m_doc.load_string(str, (pugi::parse_default |
//pugi::parse_trim_pcdata |
//pugi::parse_wnorm_attribute |
pugi::parse_declaration)
);
if (!result)
{
m_errorMsg = string(result.description());
m_errorOffset = result.offset;
}
find_root();
}
//---------------------------------------------------------------------------------------
void XmlParser::find_root()
{
pugi::xml_node root = m_doc.first_child();
m_encoding = "unknown";
if (root.type() == pugi::node_declaration)
{
if (root.attribute("encoding") != nullptr)
m_encoding = root.attribute("encoding").value();
}
while (root && root.type() != pugi::node_element)
root = root.next_sibling();
m_root = XmlNode(root);
}
//---------------------------------------------------------------------------------------
bool XmlParser::build_offset_data(const char* filename)
{
//AWARE:
// * Windows and DOS use a pair of CR (\r) and LF (\n) chars to end lines
// * UNIX (including Linux and FreeBSD) uses only an LF char
// * OS X also uses a single LF character
// * The old classic Mac operating system used a single CR char
//This code does not handle old Mac-style line breaks but it is not expected
//to run in these old machines.
//Also, this code does not handle tabs, that are counted as 1 char
m_offsetData.clear();
FILE* f = fopen(filename, "rb");
if (!f)
return false;
ptrdiff_t offset = 0;
char buffer[1024];
size_t size;
while ((size = fread(buffer, 1, sizeof(buffer), f)) > 0)
{
for (size_t i = 0; i < size; ++i)
if (buffer[i] == '\n')
m_offsetData.push_back(offset + i);
offset += size;
}
fclose(f);
return true;
}
//---------------------------------------------------------------------------------------
std::pair<int, int> XmlParser::get_location(ptrdiff_t offset)
{
vector<ptrdiff_t>::const_iterator it =
std::lower_bound(m_offsetData.begin(), m_offsetData.end(), offset);
size_t index = it - m_offsetData.begin();
return std::make_pair(1 + index, index == 0 ? offset + 1
: offset - m_offsetData[index - 1]);
}
//---------------------------------------------------------------------------------------
int XmlParser::get_line_number(XmlNode* node)
{
ptrdiff_t offset = node->offset();
if (!m_fOffsetDataReady && !m_filename.empty())
m_fOffsetDataReady = build_offset_data(m_filename.c_str());
if ( m_fOffsetDataReady)
{
std::pair<int, int> pos = get_location(offset);
return pos.first;
}
else
return 0;
}
} //namespace lomse
|
//---------------------------------------------------------------------------------------
// This file is part of the Lomse library.
// Lomse is copyrighted work (c) 2010-2016. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// For any comment, suggestion or feature request, please contact the manager of
// the project at [email protected]
//---------------------------------------------------------------------------------------
#include "lomse_xml_parser.h"
#include <iostream>
#include <ostream>
#include <sstream>
#include <vector>
using namespace std;
//---------------------------------------------------------------------------------------
//AWARE: Microsoft deprecated fopen() but the "security enhanced" new function
//fopen_s() is only defined by Microsoft which "coincidentally" makes your code
//non-portable.
//
//The addressed security issue is, basically, for files opened for writing.
//Microsoft improves security by opening the file with exclusive access.
//
//This is not needed in this source code, as the file is opened for read, but there
//is a need to suppress the annoying Microsoft warnings, which is not easy.
//Thanks Microsoft!
//
//See:
// https://stackoverflow.com/questions/906599/why-cant-i-use-fopen
// https://stackoverflow.com/questions/858252/alternatives-to-ms-strncpy-s
//
#if (defined(_MSC_VER) && (_MSC_VER >= 1400) )
#include <cstdio>
inline extern FILE* my_fopen_s(const char *fname, char *mode)
{
FILE *fptr;
fopen_s(&fptr, fname, mode);
return fptr;
}
#define fopen(fname, mode) my_fopen_s((fname), (mode))
#else
#define fopen_s(fp, fmt, mode) *(fp)=fopen((fmt), (mode))
#endif
//---------------------------------------------------------------------------------------
namespace lomse
{
//=======================================================================================
// XmlNode implementation
//=======================================================================================
int XmlNode::type()
{
switch( m_node.type() )
{
case pugi::node_null: return XmlNode::k_node_null;
case pugi::node_document: return XmlNode::k_node_document;
case pugi::node_element: return XmlNode::k_node_element;
case pugi::node_pcdata: return XmlNode::k_node_pcdata;
case pugi::node_cdata: return XmlNode::k_node_cdata;
case pugi::node_comment: return XmlNode::k_node_comment;
case pugi::node_pi: return XmlNode::k_node_pi;
case pugi::node_declaration: return XmlNode::k_node_declaration;
case pugi::node_doctype: return XmlNode::k_node_doctype;
default: return XmlNode::k_node_unknown;
}
}
//---------------------------------------------------------------------------------------
string XmlNode::value()
{
//Depending on node type,
//name or value may be absent. node_document nodes do not have a name or value,
//node_element and node_declaration nodes always have a name but never have a value,
//node_pcdata, node_cdata, node_comment and node_doctype nodes never have a
//name but always have a value (it may be empty though), node_pi nodes always
//have a name and a value (again, value may be empty).
if (m_node.type() == pugi::node_pcdata)
return string(m_node.value());
if (m_node.type() == pugi::node_element)
{
pugi::xml_node child = m_node.first_child();
return string(child.value());
}
return "";
}
//---------------------------------------------------------------------------------------
ptrdiff_t XmlNode::offset()
{
return m_node.offset_debug();
}
//=======================================================================================
// XmlParser implementation
//=======================================================================================
XmlParser::XmlParser(ostream& reporter)
: Parser(reporter)
, m_root()
, m_errorOffset(0)
, m_fOffsetDataReady(false)
{
}
//---------------------------------------------------------------------------------------
XmlParser::~XmlParser()
{
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_text(const std::string& sourceText)
{
parse_char_string( const_cast<char*>(sourceText.c_str()) );
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_cstring(char* sourceText)
{
parse_char_string(sourceText);
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_file(const std::string& filename, bool UNUSED(fErrorMsg))
{
m_fOffsetDataReady = false;
m_filename = filename;
pugi::xml_parse_result result = m_doc.load_file(filename.c_str(),
(pugi::parse_default |
//pugi::parse_trim_pcdata |
//pugi::parse_wnorm_attribute |
pugi::parse_declaration)
);
if (!result)
{
m_errorMsg = string(result.description());
m_errorOffset = result.offset;
}
find_root();
}
//---------------------------------------------------------------------------------------
void XmlParser::parse_char_string(char* str)
{
m_fOffsetDataReady = false;
m_filename.clear();
pugi::xml_parse_result result = m_doc.load_string(str, (pugi::parse_default |
//pugi::parse_trim_pcdata |
//pugi::parse_wnorm_attribute |
pugi::parse_declaration)
);
if (!result)
{
m_errorMsg = string(result.description());
m_errorOffset = result.offset;
}
find_root();
}
//---------------------------------------------------------------------------------------
void XmlParser::find_root()
{
pugi::xml_node root = m_doc.first_child();
m_encoding = "unknown";
if (root.type() == pugi::node_declaration)
{
if (root.attribute("encoding") != nullptr)
m_encoding = root.attribute("encoding").value();
}
while (root && root.type() != pugi::node_element)
root = root.next_sibling();
m_root = XmlNode(root);
}
//---------------------------------------------------------------------------------------
bool XmlParser::build_offset_data(const char* filename)
{
//AWARE:
// * Windows and DOS use a pair of CR (\r) and LF (\n) chars to end lines
// * UNIX (including Linux and FreeBSD) uses only an LF char
// * OS X also uses a single LF character
// * The old classic Mac operating system used a single CR char
//This code does not handle old Mac-style line breaks but it is not expected
//to run in these old machines.
//Also, this code does not handle tabs, that are counted as 1 char
m_offsetData.clear();
FILE* f = fopen(filename, "rb");
if (!f)
return false;
ptrdiff_t offset = 0;
char buffer[1024];
size_t size;
while ((size = fread(buffer, 1, sizeof(buffer), f)) > 0)
{
for (size_t i = 0; i < size; ++i)
if (buffer[i] == '\n')
m_offsetData.push_back(offset + i);
offset += size;
}
fclose(f);
return true;
}
//---------------------------------------------------------------------------------------
std::pair<int, int> XmlParser::get_location(ptrdiff_t offset)
{
vector<ptrdiff_t>::const_iterator it =
std::lower_bound(m_offsetData.begin(), m_offsetData.end(), offset);
size_t index = it - m_offsetData.begin();
return std::make_pair(1 + index, index == 0 ? offset + 1
: offset - m_offsetData[index - 1]);
}
//---------------------------------------------------------------------------------------
int XmlParser::get_line_number(XmlNode* node)
{
ptrdiff_t offset = node->offset();
if (!m_fOffsetDataReady && !m_filename.empty())
m_fOffsetDataReady = build_offset_data(m_filename.c_str());
if ( m_fOffsetDataReady)
{
std::pair<int, int> pos = get_location(offset);
return pos.first;
}
else
return 0;
}
} //namespace lomse
|
Fix error in macro
|
Fix error in macro
|
C++
|
mit
|
lenmus/lomse,lenmus/lomse,lenmus/lomse
|
1e332f38acc54f51509ed12a3ce220b736263155
|
cvmfs/upload_local.cc
|
cvmfs/upload_local.cc
|
/**
* This file is part of the CernVM File System.
*/
#include "upload_local.h"
#include <errno.h>
#include "logging.h"
#include "compression.h"
#include "util.h"
#include "file_processing/char_buffer.h"
using namespace upload;
LocalUploader::LocalUploader(const SpoolerDefinition &spooler_definition) :
AbstractUploader(spooler_definition),
backend_file_mode_(default_backend_file_mode_ ^ GetUmask()),
upstream_path_(spooler_definition.spooler_configuration),
temporary_path_(spooler_definition.temporary_path)
{
assert (spooler_definition.IsValid() &&
spooler_definition.driver_type == SpoolerDefinition::Local);
atomic_init32(©_errors_);
}
bool LocalUploader::WillHandle(const SpoolerDefinition &spooler_definition) {
return spooler_definition.driver_type == SpoolerDefinition::Local;
}
unsigned int LocalUploader::GetNumberOfErrors() const {
return atomic_read32(©_errors_);
}
void LocalUploader::WorkerThread() {
bool running = true;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "Local WorkerThread started.");
while (running) {
UploadJob job = AcquireNewJob();
switch (job.type) {
case UploadJob::Upload:
Upload(job.stream_handle,
job.buffer,
job.callback);
break;
case UploadJob::Commit:
FinalizeStreamedUpload(job.stream_handle,
job.content_hash,
job.hash_suffix);
break;
case UploadJob::Terminate:
running = false;
break;
default:
const bool unknown_job_type = false;
assert (unknown_job_type);
break;
}
}
LogCvmfs(kLogSpooler, kLogVerboseMsg, "Local WorkerThread exited.");
}
void LocalUploader::FileUpload(const std::string &local_path,
const std::string &remote_path,
const callback_t *callback) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "FileUpload call started.");
// create destination in backend storage temporary directory
std::string tmp_path = CreateTempPath(temporary_path_ + "/upload", 0666);
if (tmp_path.empty()) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to create temp path for "
"upload of file '%s' (errno: %d)",
local_path.c_str(), errno);
atomic_inc32(©_errors_);
Respond(callback, UploaderResults(1, local_path));
return;
}
// copy file into controlled temporary directory location
int retval = CopyPath2Path(local_path, tmp_path);
int retcode = retval ? 0 : 100;
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to copy file '%s' to staging "
"area: '%s'",
local_path.c_str(), tmp_path.c_str());
atomic_inc32(©_errors_);
Respond(callback, UploaderResults(retcode, local_path));
return;
}
// move the file in place (atomic operation)
retcode = Move(tmp_path, remote_path);
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to move file '%s' from the "
"staging area to the final location: "
"'%s'",
tmp_path.c_str(), remote_path.c_str());
atomic_inc32(©_errors_);
}
Respond(callback, UploaderResults(retcode, local_path));
}
int LocalUploader::CreateAndOpenTemporaryChunkFile(std::string *path) const {
const std::string tmp_path = CreateTempPath(temporary_path_ + "/" + "chunk",
0644);
if (tmp_path.empty()) {
LogCvmfs(kLogSpooler, kLogStderr, "Failed to create temp file for upload of "
"file chunk (errno: %d).", errno);
atomic_inc32(©_errors_);
return -1;
}
const int tmp_fd = open(tmp_path.c_str(), O_WRONLY);
if (tmp_fd < 0) {
LogCvmfs(kLogSpooler, kLogStderr, "Failed to open temp file '%s' for upload "
"of file chunk (errno: %d)",
tmp_path.c_str(), errno);
unlink(tmp_path.c_str());
atomic_inc32(©_errors_);
return tmp_fd;
}
*path = tmp_path;
return tmp_fd;
}
UploadStreamHandle* LocalUploader::InitStreamedUpload(
const callback_t *callback) {
std::string tmp_path;
const int tmp_fd = CreateAndOpenTemporaryChunkFile(&tmp_path);
if (tmp_fd < 0) {
return NULL;
}
return new LocalStreamHandle(callback, tmp_fd, tmp_path);
}
void LocalUploader::Upload(UploadStreamHandle *handle,
CharBuffer *buffer,
const callback_t *callback) {
assert (buffer->IsInitialized());
LocalStreamHandle *local_handle = static_cast<LocalStreamHandle*>(handle);
const size_t bytes_written = write(local_handle->file_descriptor,
buffer->ptr(),
buffer->used_bytes());
if (bytes_written != buffer->used_bytes()) {
const int cpy_errno = errno;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to write %d bytes to '%s' "
"(errno: %d)",
buffer->used_bytes(),
local_handle->temporary_path.c_str(),
cpy_errno);
atomic_inc32(©_errors_);
Respond(callback, UploaderResults(cpy_errno, buffer));
return;
}
Respond(callback, UploaderResults(0, buffer));
}
void LocalUploader::FinalizeStreamedUpload(UploadStreamHandle *handle,
const shash::Any content_hash,
const std::string hash_suffix) {
int retval = 0;
LocalStreamHandle *local_handle = static_cast<LocalStreamHandle*>(handle);
retval = close(local_handle->file_descriptor);
if (retval != 0) {
const int cpy_errno = errno;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to close temp file '%s' "
"(errno: %d)",
local_handle->temporary_path.c_str(), cpy_errno);
atomic_inc32(©_errors_);
Respond(handle->commit_callback, UploaderResults(cpy_errno));
return;
}
const std::string final_path = upstream_path_ + "/data" +
content_hash.MakePath(1, 2) +
hash_suffix;
retval = rename(local_handle->temporary_path.c_str(), final_path.c_str());
if (retval != 0) {
const int cpy_errno = errno;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to move temp file '%s' to "
"final location '%s' (errno: %d)",
local_handle->temporary_path.c_str(),
final_path.c_str(),
cpy_errno);
atomic_inc32(©_errors_);
Respond(handle->commit_callback, UploaderResults(cpy_errno));
return;
}
const callback_t *callback = handle->commit_callback;
delete local_handle;
Respond(callback, UploaderResults(0));
}
bool LocalUploader::Remove(const std::string& file_to_delete) {
const int retval = unlink((upstream_path_ + "/" + file_to_delete).c_str());
return retval == 0 || errno == ENOENT;
}
bool LocalUploader::Peek(const std::string& path) const {
return FileExists(upstream_path_ + "/" + path);
}
int LocalUploader::Move(const std::string &local_path,
const std::string &remote_path) const {
const std::string destination_path = upstream_path_ + "/" + remote_path;
// make sure the file has the right permissions
int retval = chmod(local_path.c_str(), backend_file_mode_);
int retcode = (retval == 0) ? 0 : 101;
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to set file permission '%s' "
"errno: %d",
local_path.c_str(), errno);
return retcode;
}
// move the file in place
retval = rename(local_path.c_str(), destination_path.c_str());
retcode = (retval == 0) ? 0 : errno;
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to move file '%s' to '%s' "
"errno: %d",
local_path.c_str(), remote_path.c_str(), errno);
}
return retcode;
}
|
/**
* This file is part of the CernVM File System.
*/
#include "upload_local.h"
#include <errno.h>
#include "logging.h"
#include "compression.h"
#include "util.h"
#include "file_processing/char_buffer.h"
using namespace upload;
LocalUploader::LocalUploader(const SpoolerDefinition &spooler_definition) :
AbstractUploader(spooler_definition),
backend_file_mode_(default_backend_file_mode_ ^ GetUmask()),
upstream_path_(spooler_definition.spooler_configuration),
temporary_path_(spooler_definition.temporary_path)
{
assert (spooler_definition.IsValid() &&
spooler_definition.driver_type == SpoolerDefinition::Local);
atomic_init32(©_errors_);
}
bool LocalUploader::WillHandle(const SpoolerDefinition &spooler_definition) {
return spooler_definition.driver_type == SpoolerDefinition::Local;
}
unsigned int LocalUploader::GetNumberOfErrors() const {
return atomic_read32(©_errors_);
}
void LocalUploader::WorkerThread() {
bool running = true;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "Local WorkerThread started.");
while (running) {
UploadJob job = AcquireNewJob();
switch (job.type) {
case UploadJob::Upload:
Upload(job.stream_handle,
job.buffer,
job.callback);
break;
case UploadJob::Commit:
FinalizeStreamedUpload(job.stream_handle,
job.content_hash,
job.hash_suffix);
break;
case UploadJob::Terminate:
running = false;
break;
default:
const bool unknown_job_type = false;
assert (unknown_job_type);
break;
}
}
LogCvmfs(kLogSpooler, kLogVerboseMsg, "Local WorkerThread exited.");
}
void LocalUploader::FileUpload(const std::string &local_path,
const std::string &remote_path,
const callback_t *callback) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "FileUpload call started.");
// create destination in backend storage temporary directory
std::string tmp_path = CreateTempPath(temporary_path_ + "/upload", 0666);
if (tmp_path.empty()) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to create temp path for "
"upload of file '%s' (errno: %d)",
local_path.c_str(), errno);
atomic_inc32(©_errors_);
Respond(callback, UploaderResults(1, local_path));
return;
}
// copy file into controlled temporary directory location
int retval = CopyPath2Path(local_path, tmp_path);
int retcode = retval ? 0 : 100;
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to copy file '%s' to staging "
"area: '%s'",
local_path.c_str(), tmp_path.c_str());
atomic_inc32(©_errors_);
Respond(callback, UploaderResults(retcode, local_path));
return;
}
// move the file in place (atomic operation)
retcode = Move(tmp_path, remote_path);
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to move file '%s' from the "
"staging area to the final location: "
"'%s'",
tmp_path.c_str(), remote_path.c_str());
atomic_inc32(©_errors_);
}
Respond(callback, UploaderResults(retcode, local_path));
}
int LocalUploader::CreateAndOpenTemporaryChunkFile(std::string *path) const {
const std::string tmp_path = CreateTempPath(temporary_path_ + "/" + "chunk",
0644);
if (tmp_path.empty()) {
LogCvmfs(kLogSpooler, kLogStderr, "Failed to create temp file for upload of "
"file chunk (errno: %d).", errno);
atomic_inc32(©_errors_);
return -1;
}
const int tmp_fd = open(tmp_path.c_str(), O_WRONLY);
if (tmp_fd < 0) {
LogCvmfs(kLogSpooler, kLogStderr, "Failed to open temp file '%s' for upload "
"of file chunk (errno: %d)",
tmp_path.c_str(), errno);
unlink(tmp_path.c_str());
atomic_inc32(©_errors_);
return tmp_fd;
}
*path = tmp_path;
return tmp_fd;
}
UploadStreamHandle* LocalUploader::InitStreamedUpload(
const callback_t *callback) {
std::string tmp_path;
const int tmp_fd = CreateAndOpenTemporaryChunkFile(&tmp_path);
if (tmp_fd < 0) {
return NULL;
}
return new LocalStreamHandle(callback, tmp_fd, tmp_path);
}
void LocalUploader::Upload(UploadStreamHandle *handle,
CharBuffer *buffer,
const callback_t *callback) {
assert (buffer->IsInitialized());
LocalStreamHandle *local_handle = static_cast<LocalStreamHandle*>(handle);
const size_t bytes_written = write(local_handle->file_descriptor,
buffer->ptr(),
buffer->used_bytes());
if (bytes_written != buffer->used_bytes()) {
const int cpy_errno = errno;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to write %d bytes to '%s' "
"(errno: %d)",
buffer->used_bytes(),
local_handle->temporary_path.c_str(),
cpy_errno);
atomic_inc32(©_errors_);
Respond(callback, UploaderResults(cpy_errno, buffer));
return;
}
Respond(callback, UploaderResults(0, buffer));
}
void LocalUploader::FinalizeStreamedUpload(UploadStreamHandle *handle,
const shash::Any content_hash,
const std::string hash_suffix) {
int retval = 0;
LocalStreamHandle *local_handle = static_cast<LocalStreamHandle*>(handle);
retval = close(local_handle->file_descriptor);
if (retval != 0) {
const int cpy_errno = errno;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to close temp file '%s' "
"(errno: %d)",
local_handle->temporary_path.c_str(), cpy_errno);
atomic_inc32(©_errors_);
Respond(handle->commit_callback, UploaderResults(cpy_errno));
return;
}
const std::string final_path = "data" +
content_hash.MakePath(1, 2) +
hash_suffix;
retval = Move(local_handle->temporary_path.c_str(), final_path.c_str());
if (retval != 0) {
const int cpy_errno = errno;
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to move temp file '%s' to "
"final location '%s' (errno: %d)",
local_handle->temporary_path.c_str(),
final_path.c_str(),
cpy_errno);
atomic_inc32(©_errors_);
Respond(handle->commit_callback, UploaderResults(cpy_errno));
return;
}
const callback_t *callback = handle->commit_callback;
delete local_handle;
Respond(callback, UploaderResults(0));
}
bool LocalUploader::Remove(const std::string& file_to_delete) {
const int retval = unlink((upstream_path_ + "/" + file_to_delete).c_str());
return retval == 0 || errno == ENOENT;
}
bool LocalUploader::Peek(const std::string& path) const {
return FileExists(upstream_path_ + "/" + path);
}
int LocalUploader::Move(const std::string &local_path,
const std::string &remote_path) const {
const std::string destination_path = upstream_path_ + "/" + remote_path;
// make sure the file has the right permissions
int retval = chmod(local_path.c_str(), backend_file_mode_);
int retcode = (retval == 0) ? 0 : 101;
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to set file permission '%s' "
"errno: %d",
local_path.c_str(), errno);
return retcode;
}
// move the file in place
retval = rename(local_path.c_str(), destination_path.c_str());
retcode = (retval == 0) ? 0 : errno;
if (retcode != 0) {
LogCvmfs(kLogSpooler, kLogVerboseMsg, "failed to move file '%s' to '%s' "
"errno: %d",
local_path.c_str(), remote_path.c_str(), errno);
}
return retcode;
}
|
use internal `Move()` method in LocalUploader
|
FIX: use internal `Move()` method in LocalUploader
|
C++
|
bsd-3-clause
|
DrDaveD/cvmfs,Moliholy/cvmfs,cvmfs-testing/cvmfs,reneme/cvmfs,cvmfs/cvmfs,Moliholy/cvmfs,Gangbiao/cvmfs,reneme/cvmfs,alhowaidi/cvmfsNDN,MicBrain/cvmfs,djw8605/cvmfs,MicBrain/cvmfs,trshaffer/cvmfs,MicBrain/cvmfs,Gangbiao/cvmfs,Moliholy/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,djw8605/cvmfs,alhowaidi/cvmfsNDN,djw8605/cvmfs,cvmfs/cvmfs,cvmfs-testing/cvmfs,Gangbiao/cvmfs,alhowaidi/cvmfsNDN,cvmfs/cvmfs,alhowaidi/cvmfsNDN,Moliholy/cvmfs,reneme/cvmfs,cvmfs/cvmfs,trshaffer/cvmfs,trshaffer/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,reneme/cvmfs,DrDaveD/cvmfs,cvmfs-testing/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,djw8605/cvmfs,Moliholy/cvmfs,MicBrain/cvmfs,trshaffer/cvmfs,cvmfs/cvmfs,trshaffer/cvmfs,MicBrain/cvmfs,cvmfs-testing/cvmfs,alhowaidi/cvmfsNDN,djw8605/cvmfs,Gangbiao/cvmfs,DrDaveD/cvmfs,cvmfs-testing/cvmfs,reneme/cvmfs,Gangbiao/cvmfs
|
26c4f64a7f7f72e40a3ff1e76eb95a538d1c56db
|
vcl/unx/gtk/fpicker/SalGtkPicker.cxx
|
vcl/unx/gtk/fpicker/SalGtkPicker.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifdef AIX
#define _LINUX_SOURCE_COMPAT
#include <sys/timer.h>
#undef _LINUX_SOURCE_COMPAT
#endif
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
#include <comphelper/processfactory.hxx>
#include <rtl/process.h>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <vcl/svapp.hxx>
#include <tools/urlobj.hxx>
#include <stdio.h>
#include "vcl/window.hxx"
#include "unx/gtk/gtkframe.hxx"
#include "gtk/fpicker/SalGtkPicker.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
OUString SalGtkPicker::uritounicode(const gchar* pIn)
{
if (!pIn)
return OUString();
OUString sURL( const_cast<const sal_Char *>(pIn), strlen(pIn),
RTL_TEXTENCODING_UTF8 );
INetURLObject aURL(sURL);
if (INET_PROT_FILE == aURL.GetProtocol())
{
// all the URLs are handled by office in UTF-8
// so the Gnome FP related URLs should be converted accordingly
gchar *pEncodedFileName = g_filename_from_uri(pIn, NULL, NULL);
if ( pEncodedFileName )
{
OUString sEncoded(pEncodedFileName, strlen(pEncodedFileName),
osl_getThreadTextEncoding());
INetURLObject aCurrentURL(sEncoded, INetURLObject::FSYS_UNX);
aCurrentURL.SetHost(aURL.GetHost());
sURL = aCurrentURL.getExternalURL();
}
else
{
OUString aNewURL = uri::ExternalUriReferenceTranslator::create( m_xContext )->translateToInternal(sURL);
if( !aNewURL.isEmpty() )
sURL = aNewURL;
}
}
return sURL;
}
OString SalGtkPicker::unicodetouri(const OUString &rURL)
{
// all the URLs are handled by office in UTF-8 ( and encoded with "%xx" codes based on UTF-8 )
// so the Gnome FP related URLs should be converted accordingly
OString sURL = OUStringToOString(rURL, RTL_TEXTENCODING_UTF8);
INetURLObject aURL(rURL);
if (INET_PROT_FILE == aURL.GetProtocol())
{
OUString aNewURL = uri::ExternalUriReferenceTranslator::create( m_xContext )->translateToInternal(rURL);
if( !aNewURL.isEmpty() )
{
// At this point the URL should contain ascii characters only actually
sURL = OUStringToOString( aNewURL, osl_getThreadTextEncoding() );
}
}
return sURL;
}
extern "C"
{
static gboolean canceldialog(RunDialog *pDialog)
{
GdkThreadLock lock;
pDialog->cancel();
return false;
}
}
RunDialog::RunDialog( GtkWidget *pDialog, uno::Reference< awt::XExtendedToolkit >& rToolkit,
uno::Reference< frame::XDesktop >& rDesktop ) :
cppu::WeakComponentImplHelper2< awt::XTopWindowListener, frame::XTerminateListener >( maLock ),
mpDialog(pDialog), mxToolkit(rToolkit), mxDesktop(rDesktop)
{
GtkWindow *pParent = NULL;
::Window * pWindow = ::Application::GetActiveTopWindow();
if( pWindow )
{
GtkSalFrame *pFrame = dynamic_cast<GtkSalFrame *>( pWindow->ImplGetFrame() );
if( pFrame )
pParent = GTK_WINDOW( pFrame->getWindow() );
}
if (pParent)
gtk_window_set_transient_for( GTK_WINDOW( mpDialog ), pParent );
}
RunDialog::~RunDialog()
{
SolarMutexGuard g;
g_source_remove_by_user_data (this);
}
void SAL_CALL RunDialog::windowOpened( const ::com::sun::star::lang::EventObject& )
throw (::com::sun::star::uno::RuntimeException)
{
SolarMutexGuard g;
g_timeout_add_full(G_PRIORITY_HIGH_IDLE, 0, (GSourceFunc)canceldialog, this, NULL);
}
void SAL_CALL RunDialog::queryTermination( const ::com::sun::star::lang::EventObject& )
throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException)
{
}
void SAL_CALL RunDialog::notifyTermination( const ::com::sun::star::lang::EventObject& )
throw(::com::sun::star::uno::RuntimeException)
{
SolarMutexGuard g;
g_timeout_add_full(G_PRIORITY_HIGH_IDLE, 0, (GSourceFunc)canceldialog, this, NULL);
}
void RunDialog::cancel()
{
gtk_dialog_response( GTK_DIALOG( mpDialog ), GTK_RESPONSE_CANCEL );
gtk_widget_hide( mpDialog );
}
gint RunDialog::run()
{
if (mxToolkit.is())
mxToolkit->addTopWindowListener(this);
gint nStatus = gtk_dialog_run( GTK_DIALOG( mpDialog ) );
if (mxToolkit.is())
mxToolkit->removeTopWindowListener(this);
if (nStatus != 1) //PLAY
gtk_widget_hide( mpDialog );
return nStatus;
}
// FIXME: this is pretty nasty ... we try to tell gtk+'s
// gettext the locale it should use via the environment
void SalGtkPicker::setGtkLanguage()
{
static bool bSet = false;
if (bSet)
return;
OUString aLocaleString( Application::GetSettings().GetUILanguageTag().getGlibcLocaleString( ".UTF-8"));
if (!aLocaleString.isEmpty())
{
OUString envVar( "LANGUAGE" );
osl_setEnvironment( envVar.pData, aLocaleString.pData );
}
bSet = true;
}
SalGtkPicker::SalGtkPicker( const uno::Reference<uno::XComponentContext>& xContext )
: m_pDialog( 0 ), m_xContext( xContext )
{
setGtkLanguage();
}
SalGtkPicker::~SalGtkPicker()
{
SolarMutexGuard g;
if (m_pDialog)
{
gtk_widget_destroy(m_pDialog);
}
}
void SAL_CALL SalGtkPicker::implsetDisplayDirectory( const OUString& aDirectory )
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
OSL_ASSERT( m_pDialog != NULL );
OString aTxt = unicodetouri(aDirectory);
if( aTxt.isEmpty() ){
aTxt = unicodetouri(OUString("file:///."));
}
if( aTxt.lastIndexOf('/') == aTxt.getLength() - 1 )
aTxt = aTxt.copy( 0, aTxt.getLength() - 1 );
OSL_TRACE( "setting path to %s", aTxt.getStr() );
gtk_file_chooser_set_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ),
aTxt.getStr() );
}
OUString SAL_CALL SalGtkPicker::implgetDisplayDirectory() throw( uno::RuntimeException )
{
OSL_ASSERT( m_pDialog != NULL );
gchar* pCurrentFolder =
gtk_file_chooser_get_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ) );
OUString aCurrentFolderName = uritounicode(pCurrentFolder);
g_free( pCurrentFolder );
return aCurrentFolderName;
}
void SAL_CALL SalGtkPicker::implsetTitle( const OUString& aTitle ) throw( uno::RuntimeException )
{
OSL_ASSERT( m_pDialog != NULL );
OString aWindowTitle = OUStringToOString( aTitle, RTL_TEXTENCODING_UTF8 );
gtk_window_set_title( GTK_WINDOW( m_pDialog ), aWindowTitle.getStr() );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifdef AIX
#define _LINUX_SOURCE_COMPAT
#include <sys/timer.h>
#undef _LINUX_SOURCE_COMPAT
#endif
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
#include <comphelper/processfactory.hxx>
#include <rtl/process.h>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <vcl/svapp.hxx>
#include <tools/urlobj.hxx>
#include <stdio.h>
#include "vcl/window.hxx"
#include "unx/gtk/gtkframe.hxx"
#include "gtk/fpicker/SalGtkPicker.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
OUString SalGtkPicker::uritounicode(const gchar* pIn)
{
if (!pIn)
return OUString();
OUString sURL( const_cast<const sal_Char *>(pIn), strlen(pIn),
RTL_TEXTENCODING_UTF8 );
INetURLObject aURL(sURL);
if (INET_PROT_FILE == aURL.GetProtocol())
{
// all the URLs are handled by office in UTF-8
// so the Gnome FP related URLs should be converted accordingly
gchar *pEncodedFileName = g_filename_from_uri(pIn, NULL, NULL);
if ( pEncodedFileName )
{
OUString sEncoded(pEncodedFileName, strlen(pEncodedFileName),
osl_getThreadTextEncoding());
g_free (pEncodedFileName);
INetURLObject aCurrentURL(sEncoded, INetURLObject::FSYS_UNX);
aCurrentURL.SetHost(aURL.GetHost());
sURL = aCurrentURL.getExternalURL();
}
else
{
OUString aNewURL = uri::ExternalUriReferenceTranslator::create( m_xContext )->translateToInternal(sURL);
if( !aNewURL.isEmpty() )
sURL = aNewURL;
}
}
return sURL;
}
OString SalGtkPicker::unicodetouri(const OUString &rURL)
{
// all the URLs are handled by office in UTF-8 ( and encoded with "%xx" codes based on UTF-8 )
// so the Gnome FP related URLs should be converted accordingly
OString sURL = OUStringToOString(rURL, RTL_TEXTENCODING_UTF8);
INetURLObject aURL(rURL);
if (INET_PROT_FILE == aURL.GetProtocol())
{
OUString aNewURL = uri::ExternalUriReferenceTranslator::create( m_xContext )->translateToInternal(rURL);
if( !aNewURL.isEmpty() )
{
// At this point the URL should contain ascii characters only actually
sURL = OUStringToOString( aNewURL, osl_getThreadTextEncoding() );
}
}
return sURL;
}
extern "C"
{
static gboolean canceldialog(RunDialog *pDialog)
{
GdkThreadLock lock;
pDialog->cancel();
return false;
}
}
RunDialog::RunDialog( GtkWidget *pDialog, uno::Reference< awt::XExtendedToolkit >& rToolkit,
uno::Reference< frame::XDesktop >& rDesktop ) :
cppu::WeakComponentImplHelper2< awt::XTopWindowListener, frame::XTerminateListener >( maLock ),
mpDialog(pDialog), mxToolkit(rToolkit), mxDesktop(rDesktop)
{
GtkWindow *pParent = NULL;
::Window * pWindow = ::Application::GetActiveTopWindow();
if( pWindow )
{
GtkSalFrame *pFrame = dynamic_cast<GtkSalFrame *>( pWindow->ImplGetFrame() );
if( pFrame )
pParent = GTK_WINDOW( pFrame->getWindow() );
}
if (pParent)
gtk_window_set_transient_for( GTK_WINDOW( mpDialog ), pParent );
}
RunDialog::~RunDialog()
{
SolarMutexGuard g;
g_source_remove_by_user_data (this);
}
void SAL_CALL RunDialog::windowOpened( const ::com::sun::star::lang::EventObject& )
throw (::com::sun::star::uno::RuntimeException)
{
SolarMutexGuard g;
g_timeout_add_full(G_PRIORITY_HIGH_IDLE, 0, (GSourceFunc)canceldialog, this, NULL);
}
void SAL_CALL RunDialog::queryTermination( const ::com::sun::star::lang::EventObject& )
throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException)
{
}
void SAL_CALL RunDialog::notifyTermination( const ::com::sun::star::lang::EventObject& )
throw(::com::sun::star::uno::RuntimeException)
{
SolarMutexGuard g;
g_timeout_add_full(G_PRIORITY_HIGH_IDLE, 0, (GSourceFunc)canceldialog, this, NULL);
}
void RunDialog::cancel()
{
gtk_dialog_response( GTK_DIALOG( mpDialog ), GTK_RESPONSE_CANCEL );
gtk_widget_hide( mpDialog );
}
gint RunDialog::run()
{
if (mxToolkit.is())
mxToolkit->addTopWindowListener(this);
gint nStatus = gtk_dialog_run( GTK_DIALOG( mpDialog ) );
if (mxToolkit.is())
mxToolkit->removeTopWindowListener(this);
if (nStatus != 1) //PLAY
gtk_widget_hide( mpDialog );
return nStatus;
}
// FIXME: this is pretty nasty ... we try to tell gtk+'s
// gettext the locale it should use via the environment
void SalGtkPicker::setGtkLanguage()
{
static bool bSet = false;
if (bSet)
return;
OUString aLocaleString( Application::GetSettings().GetUILanguageTag().getGlibcLocaleString( ".UTF-8"));
if (!aLocaleString.isEmpty())
{
OUString envVar( "LANGUAGE" );
osl_setEnvironment( envVar.pData, aLocaleString.pData );
}
bSet = true;
}
SalGtkPicker::SalGtkPicker( const uno::Reference<uno::XComponentContext>& xContext )
: m_pDialog( 0 ), m_xContext( xContext )
{
setGtkLanguage();
}
SalGtkPicker::~SalGtkPicker()
{
SolarMutexGuard g;
if (m_pDialog)
{
gtk_widget_destroy(m_pDialog);
}
}
void SAL_CALL SalGtkPicker::implsetDisplayDirectory( const OUString& aDirectory )
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
OSL_ASSERT( m_pDialog != NULL );
OString aTxt = unicodetouri(aDirectory);
if( aTxt.isEmpty() ){
aTxt = unicodetouri(OUString("file:///."));
}
if( aTxt.lastIndexOf('/') == aTxt.getLength() - 1 )
aTxt = aTxt.copy( 0, aTxt.getLength() - 1 );
OSL_TRACE( "setting path to %s", aTxt.getStr() );
gtk_file_chooser_set_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ),
aTxt.getStr() );
}
OUString SAL_CALL SalGtkPicker::implgetDisplayDirectory() throw( uno::RuntimeException )
{
OSL_ASSERT( m_pDialog != NULL );
gchar* pCurrentFolder =
gtk_file_chooser_get_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ) );
OUString aCurrentFolderName = uritounicode(pCurrentFolder);
g_free( pCurrentFolder );
return aCurrentFolderName;
}
void SAL_CALL SalGtkPicker::implsetTitle( const OUString& aTitle ) throw( uno::RuntimeException )
{
OSL_ASSERT( m_pDialog != NULL );
OString aWindowTitle = OUStringToOString( aTitle, RTL_TEXTENCODING_UTF8 );
gtk_window_set_title( GTK_WINDOW( m_pDialog ), aWindowTitle.getStr() );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Fix memory leak in SalGtkPicker::uritounicode.
|
Fix memory leak in SalGtkPicker::uritounicode.
The gchars array returned by g_filename_from_uri will be copied into
the OUString sEncoded and should be freed.
Change-Id: Ib610cce5848607826632c0f5e32020708dac7645
Reviewed-on: https://gerrit.libreoffice.org/4156
Reviewed-by: Noel Power <[email protected]>
Tested-by: Noel Power <[email protected]>
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
362bb521087649c1a473ec97d6ec03c6eab9e662
|
lib/Transforms/Scalar/DeadStoreElimination.cpp
|
lib/Transforms/Scalar/DeadStoreElimination.cpp
|
//===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a trivial dead store elimination that only considers
// basic-block local redundant stores.
//
// FIXME: This should eventually be extended to be a post-dominator tree
// traversal. Doing so would be pretty trivial.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "dse"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
STATISTIC(NumFastStores, "Number of stores deleted");
STATISTIC(NumFastOther , "Number of other instrs removed");
namespace {
struct VISIBILITY_HIDDEN DSE : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
DSE() : FunctionPass((intptr_t)&ID) {}
virtual bool runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Changed |= runOnBasicBlock(*I);
return Changed;
}
bool runOnBasicBlock(BasicBlock &BB);
bool handleFreeWithNonTrivialDependency(FreeInst* F,
Instruction* dependency,
SetVector<Instruction*>& possiblyDead);
bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
bool RemoveUndeadPointers(Value* pointer,
BasicBlock::iterator& BBI,
SmallPtrSet<AllocaInst*, 64>& deadPointers,
SetVector<Instruction*>& possiblyDead);
void DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts);
/// Find the base pointer that a pointer came from
/// Because this is used to find pointers that originate
/// from allocas, it is safe to ignore GEP indices, since
/// either the store will be in the alloca, and thus dead,
/// or beyond the end of the alloca, and thus undefined.
void TranslatePointerBitCasts(Value*& v) {
assert(isa<PointerType>(v->getType()) &&
"Translating a non-pointer type?");
while (true) {
if (BitCastInst* C = dyn_cast<BitCastInst>(v))
v = C->getOperand(0);
else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
v = G->getOperand(0);
else
break;
}
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<TargetData>();
AU.addRequired<AliasAnalysis>();
AU.addRequired<MemoryDependenceAnalysis>();
AU.addPreserved<AliasAnalysis>();
AU.addPreserved<MemoryDependenceAnalysis>();
}
};
char DSE::ID = 0;
RegisterPass<DSE> X("dse", "Dead Store Elimination");
}
FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
bool DSE::runOnBasicBlock(BasicBlock &BB) {
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
// Record the last-seen store to this pointer
DenseMap<Value*, StoreInst*> lastStore;
// Record instructions possibly made dead by deleting a store
SetVector<Instruction*> possiblyDead;
bool MadeChange = false;
// Do a top-down walk on the BB
for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
BBI != BBE; ++BBI) {
// If we find a store or a free...
if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
continue;
Value* pointer = 0;
if (StoreInst* S = dyn_cast<StoreInst>(BBI))
pointer = S->getPointerOperand();
else
pointer = cast<FreeInst>(BBI)->getPointerOperand();
StoreInst*& last = lastStore[pointer];
bool deletedStore = false;
// ... to a pointer that has been stored to before...
if (last) {
Instruction* dep = MD.getDependency(BBI);
// ... and no other memory dependencies are between them....
while (dep != MemoryDependenceAnalysis::None &&
dep != MemoryDependenceAnalysis::NonLocal &&
isa<StoreInst>(dep)) {
if (dep != last) {
dep = MD.getDependency(BBI, dep);
continue;
}
// Remove it!
MD.removeInstruction(last);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
possiblyDead.insert(D);
last->eraseFromParent();
NumFastStores++;
deletedStore = true;
MadeChange = true;
break;
}
}
// Handle frees whose dependencies are non-trivial.
if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
if (!deletedStore)
MadeChange |= handleFreeWithNonTrivialDependency(F,
MD.getDependency(F),
possiblyDead);
// No known stores after the free
last = 0;
} else {
// Update our most-recent-store map.
last = cast<StoreInst>(BBI);
}
}
// If this block ends in a return, unwind, unreachable, and eventually
// tailcall, then all allocas are dead at its end.
if (BB.getTerminator()->getNumSuccessors() == 0)
MadeChange |= handleEndBlock(BB, possiblyDead);
// Do a trivial DCE
while (!possiblyDead.empty()) {
Instruction *I = possiblyDead.back();
possiblyDead.pop_back();
DeleteDeadInstructionChains(I, possiblyDead);
}
return MadeChange;
}
/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
/// dependency is a store to a field of that structure
bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
if (dep == MemoryDependenceAnalysis::None ||
dep == MemoryDependenceAnalysis::NonLocal)
return false;
StoreInst* dependency = dyn_cast<StoreInst>(dep);
if (!dependency)
return false;
Value* depPointer = dependency->getPointerOperand();
const Type* depType = dependency->getOperand(0)->getType();
unsigned depPointerSize = TD.getTypeSize(depType);
// Check for aliasing
AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
depPointer, depPointerSize);
if (A == AliasAnalysis::MustAlias) {
// Remove it!
MD.removeInstruction(dependency);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
possiblyDead.insert(D);
dependency->eraseFromParent();
NumFastStores++;
return true;
}
return false;
}
/// handleEndBlock - Remove dead stores to stack-allocated locations in the
/// function end block. Ex:
/// %A = alloca i32
/// ...
/// store i32 1, i32* %A
/// ret void
bool DSE::handleEndBlock(BasicBlock& BB,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
bool MadeChange = false;
// Pointers alloca'd in this function are dead in the end block
SmallPtrSet<AllocaInst*, 64> deadPointers;
// Find all of the alloca'd pointers in the entry block
BasicBlock *Entry = BB.getParent()->begin();
for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
deadPointers.insert(AI);
// Scan the basic block backwards
for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
--BBI;
if (deadPointers.empty())
break;
// If we find a store whose pointer is dead...
if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
Value* pointerOperand = S->getPointerOperand();
// See through pointer-to-pointer bitcasts
TranslatePointerBitCasts(pointerOperand);
if (deadPointers.count(pointerOperand)){
// Remove it!
MD.removeInstruction(S);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
possiblyDead.insert(D);
BBI++;
S->eraseFromParent();
NumFastStores++;
MadeChange = true;
}
continue;
}
Value* killPointer = 0;
// If we encounter a use of the pointer, it is no longer considered dead
if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
killPointer = L->getPointerOperand();
} else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
killPointer = V->getOperand(0);
} else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
deadPointers.erase(A);
continue;
} else if (CallSite::get(BBI).getInstruction() != 0) {
// If this call does not access memory, it can't
// be undeadifying any of our pointers.
CallSite CS = CallSite::get(BBI);
if (CS.getCalledFunction() &&
AA.doesNotAccessMemory(CS.getCalledFunction()))
continue;
// Remove any pointers made undead by the call from the dead set
std::vector<Instruction*> dead;
for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
E = deadPointers.end(); I != E; ++I) {
// Get size information for the alloca
unsigned pointerSize = ~0UL;
if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
pointerSize = C->getZExtValue() * \
TD.getTypeSize((*I)->getAllocatedType());
// See if the call site touches it
AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
dead.push_back(*I);
}
for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
I != E; ++I)
deadPointers.erase(*I);
continue;
}
if (!killPointer)
continue;
// Deal with undead pointers
MadeChange |= RemoveUndeadPointers(killPointer, BBI,
deadPointers, possiblyDead);
}
return MadeChange;
}
/// RemoveUndeadPointers - takes an instruction and a setvector of
/// dead instructions. If I is dead, it is erased, and its operands are
/// checked for deadness. If they are dead, they are added to the dead
/// setvector.
bool DSE::RemoveUndeadPointers(Value* killPointer,
BasicBlock::iterator& BBI,
SmallPtrSet<AllocaInst*, 64>& deadPointers,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
bool MadeChange = false;
std::vector<Instruction*> undead;
for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
E = deadPointers.end(); I != E; ++I) {
// Get size information for the alloca
unsigned pointerSize = ~0UL;
if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
pointerSize = C->getZExtValue() * \
TD.getTypeSize((*I)->getAllocatedType());
// See if this pointer could alias it
AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
killPointer, ~0UL);
// If it must-alias and a store, we can delete it
if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
StoreInst* S = cast<StoreInst>(BBI);
// Remove it!
MD.removeInstruction(S);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
possiblyDead.insert(D);
BBI++;
S->eraseFromParent();
NumFastStores++;
MadeChange = true;
continue;
// Otherwise, it is undead
} else if (A != AliasAnalysis::NoAlias)
undead.push_back(*I);
}
for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
I != E; ++I)
deadPointers.erase(*I);
return MadeChange;
}
/// DeleteDeadInstructionChains - takes an instruction and a setvector of
/// dead instructions. If I is dead, it is erased, and its operands are
/// checked for deadness. If they are dead, they are added to the dead
/// setvector.
void DSE::DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts) {
// Instruction must be dead.
if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
// Let the memory dependence know
getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
// See if this made any operands dead. We do it this way in case the
// instruction uses the same operand twice. We don't want to delete a
// value then reference it.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
if (I->getOperand(i)->hasOneUse())
if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
DeadInsts.insert(Op); // Attempt to nuke it later.
I->setOperand(i, 0); // Drop from the operand list.
}
I->eraseFromParent();
++NumFastOther;
}
|
//===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a trivial dead store elimination that only considers
// basic-block local redundant stores.
//
// FIXME: This should eventually be extended to be a post-dominator tree
// traversal. Doing so would be pretty trivial.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "dse"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
STATISTIC(NumFastStores, "Number of stores deleted");
STATISTIC(NumFastOther , "Number of other instrs removed");
namespace {
struct VISIBILITY_HIDDEN DSE : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
DSE() : FunctionPass((intptr_t)&ID) {}
virtual bool runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Changed |= runOnBasicBlock(*I);
return Changed;
}
bool runOnBasicBlock(BasicBlock &BB);
bool handleFreeWithNonTrivialDependency(FreeInst* F,
Instruction* dependency,
SetVector<Instruction*>& possiblyDead);
bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
bool RemoveUndeadPointers(Value* pointer,
BasicBlock::iterator& BBI,
SmallPtrSet<AllocaInst*, 64>& deadPointers,
SetVector<Instruction*>& possiblyDead);
void DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts);
/// Find the base pointer that a pointer came from
/// Because this is used to find pointers that originate
/// from allocas, it is safe to ignore GEP indices, since
/// either the store will be in the alloca, and thus dead,
/// or beyond the end of the alloca, and thus undefined.
void TranslatePointerBitCasts(Value*& v) {
assert(isa<PointerType>(v->getType()) &&
"Translating a non-pointer type?");
while (true) {
if (BitCastInst* C = dyn_cast<BitCastInst>(v))
v = C->getOperand(0);
else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
v = G->getOperand(0);
else
break;
}
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<TargetData>();
AU.addRequired<AliasAnalysis>();
AU.addRequired<MemoryDependenceAnalysis>();
AU.addPreserved<AliasAnalysis>();
AU.addPreserved<MemoryDependenceAnalysis>();
}
};
char DSE::ID = 0;
RegisterPass<DSE> X("dse", "Dead Store Elimination");
}
FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
bool DSE::runOnBasicBlock(BasicBlock &BB) {
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
// Record the last-seen store to this pointer
DenseMap<Value*, StoreInst*> lastStore;
// Record instructions possibly made dead by deleting a store
SetVector<Instruction*> possiblyDead;
bool MadeChange = false;
// Do a top-down walk on the BB
for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
BBI != BBE; ++BBI) {
// If we find a store or a free...
if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
continue;
Value* pointer = 0;
if (StoreInst* S = dyn_cast<StoreInst>(BBI))
pointer = S->getPointerOperand();
else
pointer = cast<FreeInst>(BBI)->getPointerOperand();
StoreInst*& last = lastStore[pointer];
bool deletedStore = false;
// ... to a pointer that has been stored to before...
if (last) {
Instruction* dep = MD.getDependency(BBI);
// ... and no other memory dependencies are between them....
while (dep != MemoryDependenceAnalysis::None &&
dep != MemoryDependenceAnalysis::NonLocal &&
isa<StoreInst>(dep)) {
if (dep != last) {
dep = MD.getDependency(BBI, dep);
continue;
}
// Remove it!
MD.removeInstruction(last);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
possiblyDead.insert(D);
last->eraseFromParent();
NumFastStores++;
deletedStore = true;
MadeChange = true;
break;
}
}
// Handle frees whose dependencies are non-trivial.
if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
if (!deletedStore)
MadeChange |= handleFreeWithNonTrivialDependency(F,
MD.getDependency(F),
possiblyDead);
// No known stores after the free
last = 0;
} else {
// Update our most-recent-store map.
last = cast<StoreInst>(BBI);
}
}
// If this block ends in a return, unwind, unreachable, and eventually
// tailcall, then all allocas are dead at its end.
if (BB.getTerminator()->getNumSuccessors() == 0)
MadeChange |= handleEndBlock(BB, possiblyDead);
// Do a trivial DCE
while (!possiblyDead.empty()) {
Instruction *I = possiblyDead.back();
possiblyDead.pop_back();
DeleteDeadInstructionChains(I, possiblyDead);
}
return MadeChange;
}
/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
/// dependency is a store to a field of that structure
bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
if (dep == MemoryDependenceAnalysis::None ||
dep == MemoryDependenceAnalysis::NonLocal)
return false;
StoreInst* dependency = dyn_cast<StoreInst>(dep);
if (!dependency)
return false;
Value* depPointer = dependency->getPointerOperand();
const Type* depType = dependency->getOperand(0)->getType();
unsigned depPointerSize = TD.getTypeSize(depType);
// Check for aliasing
AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
depPointer, depPointerSize);
if (A == AliasAnalysis::MustAlias) {
// Remove it!
MD.removeInstruction(dependency);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
possiblyDead.insert(D);
dependency->eraseFromParent();
NumFastStores++;
return true;
}
return false;
}
/// handleEndBlock - Remove dead stores to stack-allocated locations in the
/// function end block. Ex:
/// %A = alloca i32
/// ...
/// store i32 1, i32* %A
/// ret void
bool DSE::handleEndBlock(BasicBlock& BB,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
bool MadeChange = false;
// Pointers alloca'd in this function are dead in the end block
SmallPtrSet<AllocaInst*, 64> deadPointers;
// Find all of the alloca'd pointers in the entry block
BasicBlock *Entry = BB.getParent()->begin();
for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
deadPointers.insert(AI);
// Scan the basic block backwards
for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
--BBI;
if (deadPointers.empty())
break;
// If we find a store whose pointer is dead...
if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
Value* pointerOperand = S->getPointerOperand();
// See through pointer-to-pointer bitcasts
TranslatePointerBitCasts(pointerOperand);
if (deadPointers.count(pointerOperand)){
// Remove it!
MD.removeInstruction(S);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
possiblyDead.insert(D);
BBI++;
S->eraseFromParent();
NumFastStores++;
MadeChange = true;
}
continue;
}
Value* killPointer = 0;
// If we encounter a use of the pointer, it is no longer considered dead
if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
killPointer = L->getPointerOperand();
} else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
killPointer = V->getOperand(0);
} else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
deadPointers.erase(A);
continue;
} else if (CallSite::get(BBI).getInstruction() != 0) {
// If this call does not access memory, it can't
// be undeadifying any of our pointers.
CallSite CS = CallSite::get(BBI);
if (CS.getCalledFunction() &&
AA.doesNotAccessMemory(CS.getCalledFunction()))
continue;
unsigned modRef = 0;
unsigned other = 0;
// Remove any pointers made undead by the call from the dead set
std::vector<Instruction*> dead;
for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
E = deadPointers.end(); I != E; ++I) {
// HACK: if we detect that our AA is imprecise, it's not
// worth it to scan the rest of the deadPointers set. Just
// assume that the AA will return ModRef for everything, and
// go ahead and bail.
if (modRef >= 16 && other == 0) {
deadPointers.clear();
return MadeChange;
}
// Get size information for the alloca
unsigned pointerSize = ~0UL;
if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
pointerSize = C->getZExtValue() * \
TD.getTypeSize((*I)->getAllocatedType());
// See if the call site touches it
AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
if (A == AliasAnalysis::ModRef)
modRef++;
else
other++;
if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
dead.push_back(*I);
}
for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
I != E; ++I)
deadPointers.erase(*I);
continue;
}
if (!killPointer)
continue;
TranslatePointerBitCasts(killPointer);
// Deal with undead pointers
MadeChange |= RemoveUndeadPointers(killPointer, BBI,
deadPointers, possiblyDead);
}
return MadeChange;
}
/// RemoveUndeadPointers - check for uses of a pointer that make it
/// undead when scanning for dead stores to alloca's.
bool DSE::RemoveUndeadPointers(Value* killPointer,
BasicBlock::iterator& BBI,
SmallPtrSet<AllocaInst*, 64>& deadPointers,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
// If the kill pointer can be easily reduced to an alloca,
// don't bother doing extraneous AA queries
if (AllocaInst* A = dyn_cast<AllocaInst>(killPointer)) {
if (deadPointers.count(A))
deadPointers.erase(A);
return false;
}
bool MadeChange = false;
std::vector<Instruction*> undead;
for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
E = deadPointers.end(); I != E; ++I) {
// Get size information for the alloca
unsigned pointerSize = ~0UL;
if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
pointerSize = C->getZExtValue() * \
TD.getTypeSize((*I)->getAllocatedType());
// See if this pointer could alias it
AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
killPointer, ~0UL);
// If it must-alias and a store, we can delete it
if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
StoreInst* S = cast<StoreInst>(BBI);
// Remove it!
MD.removeInstruction(S);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
possiblyDead.insert(D);
if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
possiblyDead.insert(D);
BBI++;
S->eraseFromParent();
NumFastStores++;
MadeChange = true;
continue;
// Otherwise, it is undead
} else if (A != AliasAnalysis::NoAlias)
undead.push_back(*I);
}
for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
I != E; ++I)
deadPointers.erase(*I);
return MadeChange;
}
/// DeleteDeadInstructionChains - takes an instruction and a setvector of
/// dead instructions. If I is dead, it is erased, and its operands are
/// checked for deadness. If they are dead, they are added to the dead
/// setvector.
void DSE::DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts) {
// Instruction must be dead.
if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
// Let the memory dependence know
getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
// See if this made any operands dead. We do it this way in case the
// instruction uses the same operand twice. We don't want to delete a
// value then reference it.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
if (I->getOperand(i)->hasOneUse())
if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
DeadInsts.insert(Op); // Attempt to nuke it later.
I->setOperand(i, 0); // Drop from the operand list.
}
I->eraseFromParent();
++NumFastOther;
}
|
Make handleEndBlock significantly faster with one trivial improvement, and one hack to avoid hitting a bad case when the alias analysis is imprecise.
|
Make handleEndBlock significantly faster with one trivial improvement,
and one hack to avoid hitting a bad case when the alias analysis is imprecise.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@40935 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
|
4fcffe2e52502656b7d6d77260ebb8372fbdc95f
|
libs/opmapcontrol/src/internals/tilematrix.cpp
|
libs/opmapcontrol/src/internals/tilematrix.cpp
|
/**
******************************************************************************
*
* @file tilematrix.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup OPMapWidget
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "tilematrix.h"
namespace internals {
TileMatrix::TileMatrix()
{
}
void TileMatrix::Clear()
{
mutex.lock();
foreach(Tile* t,matrix.values())
{
delete t;
t=0;
}
matrix.clear();
mutex.unlock();
}
//void TileMatrix::RebuildToUpperZoom()
//{
// mutex.lock();
// QList<Tile*> newtiles;
// foreach(Tile* t,matrix.values())
// {
// Point point=Point(t->GetPos().X()*2,t->GetPos().Y()*2);
// Tile* tile1=new Tile(t->GetZoom()+1,point);
// Tile* tile2=new Tile(t->GetZoom()+1,Point(point.X()+1,point.Y()+0));
// Tile* tile3=new Tile(t->GetZoom()+1,Point(point.X()+0,point.Y()+1));
// Tile* tile4=new Tile(t->GetZoom()+1,Point(point.X()+1,point.Y()+1));
//
// foreach(QByteArray arr, t->Overlays)
// {
// QImage ima=QImage::fromData(arr);
// QImage ima1=ima.copy(0,0,ima.width()/2,ima.height()/2);
// QImage ima2=ima.copy(ima.width()/2,0,ima.width()/2,ima.height()/2);
// QImage ima3=ima.copy(0,ima.height()/2,ima.width()/2,ima.height()/2);
// QImage ima4=ima.copy(ima.width()/2,ima.height()/2,ima.width()/2,ima.height()/2);
// QByteArray ba;
// QBuffer buf(&ba);
// ima1.scaled(QSize(ima.width(),ima.height())).save(&buf,"PNG");
// tile1->Overlays.append(ba);
// QByteArray ba1;
// QBuffer buf1(&ba1);
// ima2.scaled(QSize(ima.width(),ima.height())).save(&buf1,"PNG");
// tile2->Overlays.append(ba1);
// QByteArray ba2;
// QBuffer buf2(&ba2);
// ima3.scaled(QSize(ima.width(),ima.height())).save(&buf2,"PNG");
// tile3->Overlays.append(ba2);
// QByteArray ba3;
// QBuffer buf3(&ba3);
// ima4.scaled(QSize(ima.width(),ima.height())).save(&buf3,"PNG");
// tile4->Overlays.append(ba3);
// newtiles.append(tile1);
// newtiles.append(tile2);
// newtiles.append(tile3);
// newtiles.append(tile4);
// }
// }
// foreach(Tile* t,matrix.values())
// {
// delete t;
// t=0;
// }
// matrix.clear();
// foreach(Tile* t,newtiles)
// {
// matrix.insert(t->GetPos(),t);
// }
//
// mutex.unlock();
//}
void TileMatrix::ClearPointsNotIn(QList<Point>list)
{
removals.clear();
QMutexLocker lock(&mutex);
foreach(Point p, matrix.keys())
{
if(!list.contains(p))
{
removals.append(p);
}
}
mutex.unlock();
foreach(Point p,removals)
{
Tile* t=matrix.value(p, 0);
if(t!=0)
{
delete t;
t=0;
matrix.remove(p);
}
}
removals.clear();
}
Tile* TileMatrix::TileAt(const Point &p)
{
#ifdef DEBUG_TILEMATRIX
qDebug()<<"TileMatrix:TileAt:"<<p.ToString();
#endif //DEBUG_TILEMATRIX
Tile* ret;
mutex.lock();
ret=matrix.value(p,0);
mutex.unlock();
return ret;
}
void TileMatrix::SetTileAt(const Point &p, Tile* tile)
{
mutex.lock();
Tile* t=matrix.value(p,0);
if(t!=0)
delete t;
matrix.insert(p,tile);
mutex.unlock();
}
}
|
/**
******************************************************************************
*
* @file tilematrix.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup OPMapWidget
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "tilematrix.h"
namespace internals {
TileMatrix::TileMatrix()
{
}
void TileMatrix::Clear()
{
mutex.lock();
foreach(Tile* t,matrix.values())
{
delete t;
t=0;
}
matrix.clear();
mutex.unlock();
}
//void TileMatrix::RebuildToUpperZoom()
//{
// mutex.lock();
// QList<Tile*> newtiles;
// foreach(Tile* t,matrix.values())
// {
// Point point=Point(t->GetPos().X()*2,t->GetPos().Y()*2);
// Tile* tile1=new Tile(t->GetZoom()+1,point);
// Tile* tile2=new Tile(t->GetZoom()+1,Point(point.X()+1,point.Y()+0));
// Tile* tile3=new Tile(t->GetZoom()+1,Point(point.X()+0,point.Y()+1));
// Tile* tile4=new Tile(t->GetZoom()+1,Point(point.X()+1,point.Y()+1));
//
// foreach(QByteArray arr, t->Overlays)
// {
// QImage ima=QImage::fromData(arr);
// QImage ima1=ima.copy(0,0,ima.width()/2,ima.height()/2);
// QImage ima2=ima.copy(ima.width()/2,0,ima.width()/2,ima.height()/2);
// QImage ima3=ima.copy(0,ima.height()/2,ima.width()/2,ima.height()/2);
// QImage ima4=ima.copy(ima.width()/2,ima.height()/2,ima.width()/2,ima.height()/2);
// QByteArray ba;
// QBuffer buf(&ba);
// ima1.scaled(QSize(ima.width(),ima.height())).save(&buf,"PNG");
// tile1->Overlays.append(ba);
// QByteArray ba1;
// QBuffer buf1(&ba1);
// ima2.scaled(QSize(ima.width(),ima.height())).save(&buf1,"PNG");
// tile2->Overlays.append(ba1);
// QByteArray ba2;
// QBuffer buf2(&ba2);
// ima3.scaled(QSize(ima.width(),ima.height())).save(&buf2,"PNG");
// tile3->Overlays.append(ba2);
// QByteArray ba3;
// QBuffer buf3(&ba3);
// ima4.scaled(QSize(ima.width(),ima.height())).save(&buf3,"PNG");
// tile4->Overlays.append(ba3);
// newtiles.append(tile1);
// newtiles.append(tile2);
// newtiles.append(tile3);
// newtiles.append(tile4);
// }
// }
// foreach(Tile* t,matrix.values())
// {
// delete t;
// t=0;
// }
// matrix.clear();
// foreach(Tile* t,newtiles)
// {
// matrix.insert(t->GetPos(),t);
// }
//
// mutex.unlock();
//}
void TileMatrix::ClearPointsNotIn(QList<Point>list)
{
removals.clear();
QMutexLocker lock(&mutex);
foreach(Point p, matrix.keys())
{
if(!list.contains(p))
{
removals.append(p);
}
}
foreach(Point p,removals)
{
Tile* t=matrix.value(p, 0);
if(t!=0)
{
delete t;
t=0;
matrix.remove(p);
}
}
removals.clear();
}
Tile* TileMatrix::TileAt(const Point &p)
{
#ifdef DEBUG_TILEMATRIX
qDebug()<<"TileMatrix:TileAt:"<<p.ToString();
#endif //DEBUG_TILEMATRIX
Tile* ret;
mutex.lock();
ret=matrix.value(p,0);
mutex.unlock();
return ret;
}
void TileMatrix::SetTileAt(const Point &p, Tile* tile)
{
mutex.lock();
Tile* t=matrix.value(p,0);
if(t!=0)
delete t;
matrix.insert(p,tile);
mutex.unlock();
}
}
|
Remove unwanted mutex unlocker
|
Remove unwanted mutex unlocker
|
C++
|
agpl-3.0
|
greenoaktree/qgroundcontrol,remspoor/qgroundcontrol,scott-eddy/qgroundcontrol,Hunter522/qgroundcontrol,jy723/qgroundcontrol,devbharat/qgroundcontrol,remspoor/qgroundcontrol,caoxiongkun/qgroundcontrol,remspoor/qgroundcontrol,greenoaktree/qgroundcontrol,lis-epfl/qgroundcontrol,scott-eddy/qgroundcontrol,jy723/qgroundcontrol,Hunter522/qgroundcontrol,kd0aij/qgroundcontrol,UAVenture/qgroundcontrol,Hunter522/qgroundcontrol,catch-twenty-two/qgroundcontrol,fizzaly/qgroundcontrol,mihadyuk/qgroundcontrol,jy723/qgroundcontrol,iidioter/qgroundcontrol,devbharat/qgroundcontrol,CornerOfSkyline/qgroundcontrol,Hunter522/qgroundcontrol,remspoor/qgroundcontrol,iidioter/qgroundcontrol,nado1688/qgroundcontrol,nado1688/qgroundcontrol,mihadyuk/qgroundcontrol,hejunbok/qgroundcontrol,lis-epfl/qgroundcontrol,catch-twenty-two/qgroundcontrol,ethz-asl/qgc_asl,caoxiongkun/qgroundcontrol,caoxiongkun/qgroundcontrol,BMP-TECH/qgroundcontrol,hejunbok/qgroundcontrol,BMP-TECH/qgroundcontrol,devbharat/qgroundcontrol,fizzaly/qgroundcontrol,Hunter522/qgroundcontrol,caoxiongkun/qgroundcontrol,lis-epfl/qgroundcontrol,cfelipesouza/qgroundcontrol,greenoaktree/qgroundcontrol,cfelipesouza/qgroundcontrol,jy723/qgroundcontrol,fizzaly/qgroundcontrol,kd0aij/qgroundcontrol,dagoodma/qgroundcontrol,Hunter522/qgroundcontrol,dagoodma/qgroundcontrol,hejunbok/qgroundcontrol,scott-eddy/qgroundcontrol,TheIronBorn/qgroundcontrol,mihadyuk/qgroundcontrol,ethz-asl/qgc_asl,mihadyuk/qgroundcontrol,lis-epfl/qgroundcontrol,LIKAIMO/qgroundcontrol,dagoodma/qgroundcontrol,jy723/qgroundcontrol,jy723/qgroundcontrol,nado1688/qgroundcontrol,LIKAIMO/qgroundcontrol,ethz-asl/qgc_asl,BMP-TECH/qgroundcontrol,devbharat/qgroundcontrol,greenoaktree/qgroundcontrol,mihadyuk/qgroundcontrol,TheIronBorn/qgroundcontrol,lis-epfl/qgroundcontrol,LIKAIMO/qgroundcontrol,iidioter/qgroundcontrol,remspoor/qgroundcontrol,cfelipesouza/qgroundcontrol,nado1688/qgroundcontrol,ethz-asl/qgc_asl,RedoXyde/PX4_qGCS,caoxiongkun/qgroundcontrol,cfelipesouza/qgroundcontrol,devbharat/qgroundcontrol,LIKAIMO/qgroundcontrol,TheIronBorn/qgroundcontrol,hejunbok/qgroundcontrol,TheIronBorn/qgroundcontrol,nado1688/qgroundcontrol,dagoodma/qgroundcontrol,kd0aij/qgroundcontrol,catch-twenty-two/qgroundcontrol,cfelipesouza/qgroundcontrol,UAVenture/qgroundcontrol,devbharat/qgroundcontrol,greenoaktree/qgroundcontrol,CornerOfSkyline/qgroundcontrol,scott-eddy/qgroundcontrol,dagoodma/qgroundcontrol,kd0aij/qgroundcontrol,BMP-TECH/qgroundcontrol,hejunbok/qgroundcontrol,catch-twenty-two/qgroundcontrol,caoxiongkun/qgroundcontrol,kd0aij/qgroundcontrol,scott-eddy/qgroundcontrol,catch-twenty-two/qgroundcontrol,dagoodma/qgroundcontrol,iidioter/qgroundcontrol,TheIronBorn/qgroundcontrol,UAVenture/qgroundcontrol,CornerOfSkyline/qgroundcontrol,RedoXyde/PX4_qGCS,kd0aij/qgroundcontrol,fizzaly/qgroundcontrol,ethz-asl/qgc_asl,catch-twenty-two/qgroundcontrol,hejunbok/qgroundcontrol,mihadyuk/qgroundcontrol,scott-eddy/qgroundcontrol,UAVenture/qgroundcontrol,RedoXyde/PX4_qGCS,remspoor/qgroundcontrol,cfelipesouza/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,BMP-TECH/qgroundcontrol,iidioter/qgroundcontrol,RedoXyde/PX4_qGCS,fizzaly/qgroundcontrol,CornerOfSkyline/qgroundcontrol,LIKAIMO/qgroundcontrol,CornerOfSkyline/qgroundcontrol,greenoaktree/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,TheIronBorn/qgroundcontrol,iidioter/qgroundcontrol,fizzaly/qgroundcontrol,nado1688/qgroundcontrol,LIKAIMO/qgroundcontrol,BMP-TECH/qgroundcontrol,CornerOfSkyline/qgroundcontrol
|
c0cb14a5c2a26833f3ce385b9b5e8be7d4a9468e
|
machine/instructions/send_stack_with_splat.hpp
|
machine/instructions/send_stack_with_splat.hpp
|
#include "interpreter/instructions.hpp"
#include "class/call_site.hpp"
namespace rubinius {
namespace instructions {
inline bool send_stack_with_splat(STATE, CallFrame* call_frame, intptr_t literal, intptr_t count) {
Object* block = stack_pop();
Object* ary = stack_pop();
Object* recv = stack_back(count);
CallSite* call_site = reinterpret_cast<CallSite*>(literal);
Arguments args(call_site->name(), recv, block, count,
stack_back_position(count));
if(!ary->nil_p()) {
if(CALL_FLAGS() & CALL_FLAG_CONCAT) {
args.prepend(state, as<Array>(ary));
} else {
args.append(state, as<Array>(ary));
}
}
// TODO: instructions
// SET_CALL_FLAGS(0);
Object* ret = call_site->execute(state, args);
stack_clear(count + 1);
state->vm()->checkpoint(state);
CHECK_AND_PUSH(ret);
}
}
}
|
#include "interpreter/instructions.hpp"
#include "class/call_site.hpp"
namespace rubinius {
namespace instructions {
inline bool send_stack_with_splat(STATE, CallFrame* call_frame, intptr_t literal, intptr_t count) {
Object* block = stack_pop();
Object* ary = stack_pop();
Object* recv = stack_back(count);
CallSite* call_site = reinterpret_cast<CallSite*>(literal);
Arguments args(call_site->name(), recv, block, count,
stack_back_position(count));
if(!ary->nil_p()) {
if(CALL_FLAGS() & CALL_FLAG_CONCAT) {
args.prepend(state, as<Array>(ary));
} else {
args.append(state, as<Array>(ary));
}
}
// TODO: instructions
// SET_CALL_FLAGS(0);
stack_clear(count + 1);
Object* ret = call_site->execute(state, args);
state->vm()->checkpoint(state);
CHECK_AND_PUSH(ret);
}
}
}
|
clean up stack before executing method
|
clean up stack before executing method
|
C++
|
mpl-2.0
|
kachick/rubinius,kachick/rubinius,kachick/rubinius,kachick/rubinius,kachick/rubinius,kachick/rubinius,kachick/rubinius,kachick/rubinius
|
64cda54ff1e552fc29ebb27eac7778eac5c6f9e1
|
mjolnir/input/read_random_number_generator.hpp
|
mjolnir/input/read_random_number_generator.hpp
|
#ifndef MJOLNIR_INPUT_READ_RANDOM_NUMBER_GENERATOR_HPP
#define MJOLNIR_INPUT_READ_RANDOM_NUMBER_GENERATOR_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/core/MsgPackLoader.hpp>
namespace mjolnir
{
template<typename traitsT>
RandomNumberGenerator<traitsT> read_rng(const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
std::uint32_t seed = 0;
if(simulator.as_table().count("integrator") != 0)
{
const auto& integrator = toml::find(simulator, "integrator");
if(integrator.as_table().count("seed") != 0)
{
MJOLNIR_LOG_WARN("deprecated: put `seed` under [simulator] table.");
MJOLNIR_LOG_WARN("deprecated: ```toml");
MJOLNIR_LOG_WARN("deprecated: [simulator]");
MJOLNIR_LOG_WARN("deprecated: seed = 12345");
MJOLNIR_LOG_WARN("deprecated: ```");
seed = toml::find<std::uint32_t>(integrator, "seed");
}
else
{
seed = toml::find<std::uint32_t>(simulator, "seed");
}
}
else
{
if(simulator.at("seed").is_integer())
{
seed = toml::find<std::uint32_t>(simulator, "seed");
}
else // load from saved checkpoint file
{
const std::string fname = toml::find<std::string>(simulator, "seed");
MsgPackLoader<traitsT> loader;
MJOLNIR_LOG_NOTICE("RNG is loaded from ", fname);
return loader.load_rng(fname);
}
}
MJOLNIR_LOG_NOTICE("seed is ", seed);
return RandomNumberGenerator<traitsT>(seed);
}
} // mjolnir
#ifdef MJOLNIR_SEPARATE_BUILD
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
namespace mjolnir
{
extern template RandomNumberGenerator<SimulatorTraits<double, UnlimitedBoundary> > read_rng(const toml::value&);
extern template RandomNumberGenerator<SimulatorTraits<float, UnlimitedBoundary> > read_rng(const toml::value&);
extern template RandomNumberGenerator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_rng(const toml::value&);
extern template RandomNumberGenerator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_rng(const toml::value&);
}
#endif // MJOLNIR_SEPARATE_BUILD
#endif// MJOLNIR_INPUT_READ_RANDOM_NUMBER_GENERATOR_HPP
|
#ifndef MJOLNIR_INPUT_READ_RANDOM_NUMBER_GENERATOR_HPP
#define MJOLNIR_INPUT_READ_RANDOM_NUMBER_GENERATOR_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/core/MsgPackLoader.hpp>
namespace mjolnir
{
template<typename traitsT>
RandomNumberGenerator<traitsT> read_rng(const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
std::uint32_t seed = 0;
if(simulator.contains("integrator") && simulator.at("integrator").contains("seed"))
{
MJOLNIR_LOG_WARN("deprecated: put `seed` under [simulator] table.");
MJOLNIR_LOG_WARN("deprecated: ```toml");
MJOLNIR_LOG_WARN("deprecated: [simulator]");
MJOLNIR_LOG_WARN("deprecated: seed = 12345");
MJOLNIR_LOG_WARN("deprecated: ```");
seed = toml::find<std::uint32_t>(simulator, "integrator", "seed");
}
else
{
if(simulator.at("seed").is_integer())
{
seed = toml::find<std::uint32_t>(simulator, "seed");
}
else // load from saved checkpoint file
{
const std::string fname = toml::find<std::string>(simulator, "seed");
MsgPackLoader<traitsT> loader;
MJOLNIR_LOG_NOTICE("RNG is loaded from ", fname);
return loader.load_rng(fname);
}
}
MJOLNIR_LOG_NOTICE("seed is ", seed);
return RandomNumberGenerator<traitsT>(seed);
}
} // mjolnir
#ifdef MJOLNIR_SEPARATE_BUILD
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
namespace mjolnir
{
extern template RandomNumberGenerator<SimulatorTraits<double, UnlimitedBoundary> > read_rng(const toml::value&);
extern template RandomNumberGenerator<SimulatorTraits<float, UnlimitedBoundary> > read_rng(const toml::value&);
extern template RandomNumberGenerator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_rng(const toml::value&);
extern template RandomNumberGenerator<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_rng(const toml::value&);
}
#endif // MJOLNIR_SEPARATE_BUILD
#endif// MJOLNIR_INPUT_READ_RANDOM_NUMBER_GENERATOR_HPP
|
check key existance earlier
|
fix: check key existance earlier
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
ea10f7247e7f27aa8f0b51241b5c5835e093d3a8
|
modules/control/controller/controller_agent.cc
|
modules/control/controller/controller_agent.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/controller/controller_agent.h"
#include <utility>
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/control/common/control_gflags.h"
#include "modules/control/controller/lat_controller.h"
#include "modules/control/controller/lon_controller.h"
#include "modules/control/controller/mpc_controller.h"
namespace apollo {
namespace control {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::time::Clock;
void ControllerAgent::RegisterControllers(const ControlConf *control_conf) {
AINFO << "Only support MPC controller or Lat + Lon controllers as of now";
if (control_conf->active_controllers().size() == 1 &&
control_conf->active_controllers(0) == ControlConf::MPC_CONTROLLER) {
controller_factory_.Register(
ControlConf::MPC_CONTROLLER,
[]() -> Controller * { return new MPCController(); });
} else {
controller_factory_.Register(
ControlConf::LAT_CONTROLLER,
[]() -> Controller * { return new LatController(); });
controller_factory_.Register(
ControlConf::LON_CONTROLLER,
[]() -> Controller * { return new LonController(); });
}
}
Status ControllerAgent::InitializeConf(const ControlConf *control_conf) {
if (!control_conf) {
AERROR << "control_conf is null";
return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to load config");
}
control_conf_ = control_conf;
for (auto controller_type : control_conf_->active_controllers()) {
auto controller = controller_factory_.CreateObject(
static_cast<ControlConf::ControllerType>(controller_type));
if (controller) {
controller_list_.emplace_back(std::move(controller));
} else {
AERROR << "Controller: " << controller_type << "is not supported";
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Invalid controller type:" + controller_type);
}
}
return Status::OK();
}
Status ControllerAgent::Init(const ControlConf *control_conf) {
RegisterControllers(control_conf);
CHECK(InitializeConf(control_conf).ok()) << "Fail to initialize config.";
for (auto &controller : controller_list_) {
if (controller == NULL || !controller->Init(control_conf_).ok()) {
if (controller != NULL) {
AERROR << "Controller <" << controller->Name() << "> init failed!";
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Failed to init Controller:" + controller->Name());
} else {
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Failed to init Controller");
}
}
AINFO << "Controller <" << controller->Name() << "> init done!";
}
return Status::OK();
}
Status ControllerAgent::ComputeControlCommand(
const localization::LocalizationEstimate *localization,
const canbus::Chassis *chassis, const planning::ADCTrajectory *trajectory,
control::ControlCommand *cmd) {
for (auto &controller : controller_list_) {
ADEBUG << "controller:" << controller->Name() << " processing ...";
double start_timestamp = Clock::NowInSeconds();
controller->ComputeControlCommand(localization, chassis, trajectory, cmd);
double end_timestamp = Clock::NowInSeconds();
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
ADEBUG << "controller: " << controller->Name()
<< " calculation time is: " << time_diff_ms << " ms.";
cmd->mutable_latency_stats()->add_controller_time_ms(time_diff_ms);
}
return Status::OK();
}
Status ControllerAgent::Reset() {
for (auto &controller : controller_list_) {
ADEBUG << "controller:" << controller->Name() << " reset...";
controller->Reset();
}
return Status::OK();
}
} // namespace control
} // namespace apollo
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/controller/controller_agent.h"
#include <utility>
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/control/common/control_gflags.h"
#include "modules/control/controller/lat_controller.h"
#include "modules/control/controller/lon_controller.h"
#include "modules/control/controller/mpc_controller.h"
namespace apollo {
namespace control {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::time::Clock;
void ControllerAgent::RegisterControllers(const ControlConf *control_conf) {
AINFO << "Only support MPC controller or Lat + Lon controllers as of now";
for (auto active_controller : control_conf->active_controllers()) {
switch (active_controller) {
case ControlConf::MPC_CONTROLLER:
controller_factory_.Register(
ControlConf::MPC_CONTROLLER,
[]() -> Controller * { return new MPCController(); });
break;
case ControlConf::LAT_CONTROLLER:
controller_factory_.Register(
ControlConf::LAT_CONTROLLER,
[]() -> Controller * { return new LatController(); });
break;
case ControlConf::LON_CONTROLLER:
controller_factory_.Register(
ControlConf::LON_CONTROLLER,
[]() -> Controller * { return new LonController(); });
break;
default:
AERROR << "Unknown active controller type:" << active_controller;
}
}
}
Status ControllerAgent::InitializeConf(const ControlConf *control_conf) {
if (!control_conf) {
AERROR << "control_conf is null";
return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to load config");
}
control_conf_ = control_conf;
for (auto controller_type : control_conf_->active_controllers()) {
auto controller = controller_factory_.CreateObject(
static_cast<ControlConf::ControllerType>(controller_type));
if (controller) {
controller_list_.emplace_back(std::move(controller));
} else {
AERROR << "Controller: " << controller_type << "is not supported";
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Invalid controller type:" + controller_type);
}
}
return Status::OK();
}
Status ControllerAgent::Init(const ControlConf *control_conf) {
RegisterControllers(control_conf);
CHECK(InitializeConf(control_conf).ok()) << "Fail to initialize config.";
for (auto &controller : controller_list_) {
if (controller == NULL || !controller->Init(control_conf_).ok()) {
if (controller != NULL) {
AERROR << "Controller <" << controller->Name() << "> init failed!";
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Failed to init Controller:" + controller->Name());
} else {
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Failed to init Controller");
}
}
AINFO << "Controller <" << controller->Name() << "> init done!";
}
return Status::OK();
}
Status ControllerAgent::ComputeControlCommand(
const localization::LocalizationEstimate *localization,
const canbus::Chassis *chassis, const planning::ADCTrajectory *trajectory,
control::ControlCommand *cmd) {
for (auto &controller : controller_list_) {
ADEBUG << "controller:" << controller->Name() << " processing ...";
double start_timestamp = Clock::NowInSeconds();
controller->ComputeControlCommand(localization, chassis, trajectory, cmd);
double end_timestamp = Clock::NowInSeconds();
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
ADEBUG << "controller: " << controller->Name()
<< " calculation time is: " << time_diff_ms << " ms.";
cmd->mutable_latency_stats()->add_controller_time_ms(time_diff_ms);
}
return Status::OK();
}
Status ControllerAgent::Reset() {
for (auto &controller : controller_list_) {
ADEBUG << "controller:" << controller->Name() << " reset...";
controller->Reset();
}
return Status::OK();
}
} // namespace control
} // namespace apollo
|
refactor controller creation process.
|
control: refactor controller creation process.
|
C++
|
apache-2.0
|
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
|
aac9f2d80a1328cc321bd119743ebc693a6907c1
|
modules/danlin_fontawesome/src/FontAwesome.cpp
|
modules/danlin_fontawesome/src/FontAwesome.cpp
|
/*
==============================================================================
FontAwesome.cpp
Created: 13 Jul 2014 12:45:27pm
Author: Daniel Lindenfelser
==============================================================================
*/
#include "FontAwesome.h"
juce_ImplementSingleton(FontAwesome)
RenderedIcon FontAwesome::getIcon(Icon icon, float size, juce::Colour colour, float scaleFactor) {
int scaledSize = int(size * scaleFactor);
String identifier = juce::String(icon + "@" + String(scaledSize) + "@" + colour.toString());
int64 hash = identifier.hashCode64();
Image canvas = juce::ImageCache::getFromHashCode(hash);
if (canvas.isValid())
return canvas;
Font fontAwesome = getFont(scaledSize);
scaledSize = max(fontAwesome.getStringWidth(icon), scaledSize);
canvas = Image(Image::PixelFormat::ARGB, scaledSize, scaledSize, true);
Graphics g(canvas);
g.setColour(colour);
g.setFont(fontAwesome);
g.drawText(icon, 0, 0, scaledSize, scaledSize, Justification::centred, true);
juce::ImageCache::addImageToCache(canvas, hash);
return canvas;
}
RenderedIcon FontAwesome::getRotatedIcon(Icon icon, float size, juce::Colour colour, float iconRotation, float scaleFactor) {
int scaledSize = int(size * scaleFactor);
String identifier = String(icon + "@" + String(scaledSize) + "@" + colour.toString() + "@" + String(iconRotation) + "@");
int64 hash = identifier.hashCode64();
Image canvas = juce::ImageCache::getFromHashCode(hash);
if (canvas.isValid())
return canvas;
RenderedIcon renderdIcon = getIcon(icon, size, colour, scaleFactor);
canvas = Image(Image::PixelFormat::ARGB, renderdIcon.getWidth(), renderdIcon.getHeight(), true);
Graphics g(canvas);
g.drawImageTransformed(renderdIcon, AffineTransform::rotation(-(float_Pi * iconRotation), renderdIcon.getWidth() * 0.5f, renderdIcon.getHeight() * 0.5f));
juce::ImageCache::addImageToCache(canvas, hash);
return canvas;
}
void FontAwesome::drawAt(juce::Graphics &g, RenderedIcon icon, int x, int y, float scaleFactor) {
int w = icon.getWidth();
int h = icon.getHeight();
g.drawImage(icon,
x, y,
w/scaleFactor, h/scaleFactor,
0, 0,
w, h,
false);
}
void FontAwesome::drawCenterdAt(juce::Graphics &g, RenderedIcon icon, Rectangle<int> r, float scaleFactor) {
float iconWidth = icon.getWidth() / scaleFactor;
float iconHeight = icon.getHeight() / scaleFactor;
int x = r.getX() + ((r.getWidth() * 0.5f) - (iconWidth * 0.5f));
int y = r.getY() + ((r.getHeight() * 0.5f) - (iconHeight * 0.5f));
g.drawImage(icon, x, y, iconWidth, iconHeight, 0, 0, icon.getWidth(), icon.getWidth());
}
juce::Font FontAwesome::getFont() {
static Font fontAwesomeFont(FontAwesome_ptr);
return fontAwesomeFont;
}
juce::Font FontAwesome::getFont(float size) {
juce::Font font = getFont();
font.setHeight(size);
return font;
}
void FontAwesome::drawAt(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y, float scaleFactor) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, scaleFactor), x, y, scaleFactor);
}
void FontAwesome::drawAt(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, g.getInternalContext().getPhysicalPixelScaleFactor()), x, y, g.getInternalContext().getPhysicalPixelScaleFactor());
}
void FontAwesome::drawCenterd(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r, float scaleFactor) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, scaleFactor), r, scaleFactor);
}
void FontAwesome::drawCenterd(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, g.getInternalContext().getPhysicalPixelScaleFactor()), r, g.getInternalContext().getPhysicalPixelScaleFactor());
}
void FontAwesome::drawAtRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y, float rotation, float scaleFactor) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, scaleFactor), x, y, scaleFactor);
}
void FontAwesome::drawAtRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y, float rotation) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, g.getInternalContext().getPhysicalPixelScaleFactor()), x, y, g.getInternalContext().getPhysicalPixelScaleFactor());
}
void FontAwesome::drawCenterdRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r, float rotation, float scaleFactor) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, scaleFactor), r, scaleFactor);
}
void FontAwesome::drawCenterdRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r, float rotation) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, g.getInternalContext().getPhysicalPixelScaleFactor()), r, g.getInternalContext().getPhysicalPixelScaleFactor());
}
|
/*
==============================================================================
FontAwesome.cpp
Created: 13 Jul 2014 12:45:27pm
Author: Daniel Lindenfelser
==============================================================================
*/
#include "FontAwesome.h"
juce_ImplementSingleton(FontAwesome)
RenderedIcon FontAwesome::getIcon(Icon icon, float size, juce::Colour colour, float scaleFactor) {
int scaledSize = int(size * scaleFactor);
String identifier = juce::String(icon + "@" + String(scaledSize) + "@" + colour.toString());
int64 hash = identifier.hashCode64();
Image canvas = juce::ImageCache::getFromHashCode(hash);
if (canvas.isValid())
return canvas;
Font fontAwesome = getFont(scaledSize);
scaledSize = std::max(fontAwesome.getStringWidth(icon), scaledSize);
canvas = Image(Image::PixelFormat::ARGB, scaledSize, scaledSize, true);
Graphics g(canvas);
g.setColour(colour);
g.setFont(fontAwesome);
g.drawText(icon, 0, 0, scaledSize, scaledSize, Justification::centred, true);
juce::ImageCache::addImageToCache(canvas, hash);
return canvas;
}
RenderedIcon FontAwesome::getRotatedIcon(Icon icon, float size, juce::Colour colour, float iconRotation, float scaleFactor) {
int scaledSize = int(size * scaleFactor);
String identifier = String(icon + "@" + String(scaledSize) + "@" + colour.toString() + "@" + String(iconRotation) + "@");
int64 hash = identifier.hashCode64();
Image canvas = juce::ImageCache::getFromHashCode(hash);
if (canvas.isValid())
return canvas;
RenderedIcon renderdIcon = getIcon(icon, size, colour, scaleFactor);
canvas = Image(Image::PixelFormat::ARGB, renderdIcon.getWidth(), renderdIcon.getHeight(), true);
Graphics g(canvas);
g.drawImageTransformed(renderdIcon, AffineTransform::rotation(-(float_Pi * iconRotation), renderdIcon.getWidth() * 0.5f, renderdIcon.getHeight() * 0.5f));
juce::ImageCache::addImageToCache(canvas, hash);
return canvas;
}
void FontAwesome::drawAt(juce::Graphics &g, RenderedIcon icon, int x, int y, float scaleFactor) {
int w = icon.getWidth();
int h = icon.getHeight();
g.drawImage(icon,
x, y,
w/scaleFactor, h/scaleFactor,
0, 0,
w, h,
false);
}
void FontAwesome::drawCenterdAt(juce::Graphics &g, RenderedIcon icon, Rectangle<int> r, float scaleFactor) {
float iconWidth = icon.getWidth() / scaleFactor;
float iconHeight = icon.getHeight() / scaleFactor;
int x = r.getX() + ((r.getWidth() * 0.5f) - (iconWidth * 0.5f));
int y = r.getY() + ((r.getHeight() * 0.5f) - (iconHeight * 0.5f));
g.drawImage(icon, x, y, iconWidth, iconHeight, 0, 0, icon.getWidth(), icon.getWidth());
}
juce::Font FontAwesome::getFont() {
static Font fontAwesomeFont(FontAwesome_ptr);
return fontAwesomeFont;
}
juce::Font FontAwesome::getFont(float size) {
juce::Font font = getFont();
font.setHeight(size);
return font;
}
void FontAwesome::drawAt(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y, float scaleFactor) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, scaleFactor), x, y, scaleFactor);
}
void FontAwesome::drawAt(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, g.getInternalContext().getPhysicalPixelScaleFactor()), x, y, g.getInternalContext().getPhysicalPixelScaleFactor());
}
void FontAwesome::drawCenterd(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r, float scaleFactor) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, scaleFactor), r, scaleFactor);
}
void FontAwesome::drawCenterd(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getIcon(icon, size, colour, g.getInternalContext().getPhysicalPixelScaleFactor()), r, g.getInternalContext().getPhysicalPixelScaleFactor());
}
void FontAwesome::drawAtRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y, float rotation, float scaleFactor) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, scaleFactor), x, y, scaleFactor);
}
void FontAwesome::drawAtRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, int x, int y, float rotation) {
FontAwesome::getInstance()->drawAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, g.getInternalContext().getPhysicalPixelScaleFactor()), x, y, g.getInternalContext().getPhysicalPixelScaleFactor());
}
void FontAwesome::drawCenterdRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r, float rotation, float scaleFactor) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, scaleFactor), r, scaleFactor);
}
void FontAwesome::drawCenterdRotated(juce::Graphics &g, Icon icon, float size, juce::Colour colour, juce::Rectangle<int> r, float rotation) {
FontAwesome::getInstance()->drawCenterdAt(g, FontAwesome::getInstance()->getRotatedIcon(icon, size, colour, rotation, g.getInternalContext().getPhysicalPixelScaleFactor()), r, g.getInternalContext().getPhysicalPixelScaleFactor());
}
|
add missing namespace
|
add missing namespace
|
C++
|
mit
|
danlin/danlin_modules,danlin/danlin_modules,danlin/danlin_modules
|
7258d47b9600d53a4225c5783cc9f6cc3b04189e
|
modules/desktop_capture/window_capturer_win.cc
|
modules/desktop_capture/window_capturer_win.cc
|
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/desktop_capture/window_capturer.h"
#include <assert.h>
#include "webrtc/base/win32.h"
#include "webrtc/modules/desktop_capture/desktop_frame_win.h"
#include "webrtc/modules/desktop_capture/win/window_capture_utils.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
namespace webrtc {
namespace {
typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);
BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {
WindowCapturer::WindowList* list =
reinterpret_cast<WindowCapturer::WindowList*>(param);
// Skip windows that are invisible, minimized, have no title, or are owned,
// unless they have the app window style set.
int len = GetWindowTextLength(hwnd);
HWND owner = GetWindow(hwnd, GW_OWNER);
LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||
(owner && !(exstyle & WS_EX_APPWINDOW))) {
return TRUE;
}
// Skip the Program Manager window and the Start button.
const size_t kClassLength = 256;
WCHAR class_name[kClassLength];
GetClassName(hwnd, class_name, kClassLength);
// Skip Program Manager window and the Start button. This is the same logic
// that's used in Win32WindowPicker in libjingle. Consider filtering other
// windows as well (e.g. toolbars).
if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0)
return TRUE;
WindowCapturer::Window window;
window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);
const size_t kTitleLength = 500;
WCHAR window_title[kTitleLength];
// Truncate the title if it's longer than kTitleLength.
GetWindowText(hwnd, window_title, kTitleLength);
window.title = rtc::ToUtf8(window_title);
// Skip windows when we failed to convert the title or it is empty.
if (window.title.empty())
return TRUE;
list->push_back(window);
return TRUE;
}
class WindowCapturerWin : public WindowCapturer {
public:
WindowCapturerWin();
virtual ~WindowCapturerWin();
// WindowCapturer interface.
virtual bool GetWindowList(WindowList* windows) OVERRIDE;
virtual bool SelectWindow(WindowId id) OVERRIDE;
virtual bool BringSelectedWindowToFront() OVERRIDE;
// DesktopCapturer interface.
virtual void Start(Callback* callback) OVERRIDE;
virtual void Capture(const DesktopRegion& region) OVERRIDE;
private:
bool IsAeroEnabled();
Callback* callback_;
// HWND and HDC for the currently selected window or NULL if window is not
// selected.
HWND window_;
// dwmapi.dll is used to determine if desktop compositing is enabled.
HMODULE dwmapi_library_;
DwmIsCompositionEnabledFunc is_composition_enabled_func_;
DesktopSize previous_size_;
DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);
};
WindowCapturerWin::WindowCapturerWin()
: callback_(NULL),
window_(NULL) {
// Try to load dwmapi.dll dynamically since it is not available on XP.
dwmapi_library_ = LoadLibrary(L"dwmapi.dll");
if (dwmapi_library_) {
is_composition_enabled_func_ =
reinterpret_cast<DwmIsCompositionEnabledFunc>(
GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled"));
assert(is_composition_enabled_func_);
} else {
is_composition_enabled_func_ = NULL;
}
}
WindowCapturerWin::~WindowCapturerWin() {
if (dwmapi_library_)
FreeLibrary(dwmapi_library_);
}
bool WindowCapturerWin::IsAeroEnabled() {
BOOL result = FALSE;
if (is_composition_enabled_func_)
is_composition_enabled_func_(&result);
return result != FALSE;
}
bool WindowCapturerWin::GetWindowList(WindowList* windows) {
WindowList result;
LPARAM param = reinterpret_cast<LPARAM>(&result);
if (!EnumWindows(&WindowsEnumerationHandler, param))
return false;
windows->swap(result);
return true;
}
bool WindowCapturerWin::SelectWindow(WindowId id) {
HWND window = reinterpret_cast<HWND>(id);
if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))
return false;
window_ = window;
previous_size_.set(0, 0);
return true;
}
bool WindowCapturerWin::BringSelectedWindowToFront() {
if (!window_)
return false;
if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_))
return false;
return SetForegroundWindow(window_) != 0;
}
void WindowCapturerWin::Start(Callback* callback) {
assert(!callback_);
assert(callback);
callback_ = callback;
}
void WindowCapturerWin::Capture(const DesktopRegion& region) {
if (!window_) {
LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError();
callback_->OnCaptureCompleted(NULL);
return;
}
// Stop capturing if the window has been closed or hidden.
if (!IsWindow(window_) || !IsWindowVisible(window_)) {
callback_->OnCaptureCompleted(NULL);
return;
}
DesktopRect original_rect;
DesktopRect cropped_rect;
if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) {
LOG(LS_WARNING) << "Failed to get window info: " << GetLastError();
callback_->OnCaptureCompleted(NULL);
return;
}
HDC window_dc = GetWindowDC(window_);
if (!window_dc) {
LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError();
callback_->OnCaptureCompleted(NULL);
return;
}
scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(
cropped_rect.size(), NULL, window_dc));
if (!frame.get()) {
ReleaseDC(window_, window_dc);
callback_->OnCaptureCompleted(NULL);
return;
}
HDC mem_dc = CreateCompatibleDC(window_dc);
HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap());
BOOL result = FALSE;
// When desktop composition (Aero) is enabled each window is rendered to a
// private buffer allowing BitBlt() to get the window content even if the
// window is occluded. PrintWindow() is slower but lets rendering the window
// contents to an off-screen device context when Aero is not available.
// PrintWindow() is not supported by some applications.
//
// If Aero is enabled, we prefer BitBlt() because it's faster and avoids
// window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may
// render occluding windows on top of the desired window.
//
// When composition is enabled the DC returned by GetWindowDC() doesn't always
// have window frame rendered correctly. Windows renders it only once and then
// caches the result between captures. We hack it around by calling
// PrintWindow() whenever window size changes, including the first time of
// capturing - it somehow affects what we get from BitBlt() on the subsequent
// captures.
if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) {
result = PrintWindow(window_, mem_dc, 0);
}
// Aero is enabled or PrintWindow() failed, use BitBlt.
if (!result) {
result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),
window_dc,
cropped_rect.left() - original_rect.left(),
cropped_rect.top() - original_rect.top(),
SRCCOPY);
}
SelectObject(mem_dc, previous_object);
DeleteDC(mem_dc);
ReleaseDC(window_, window_dc);
previous_size_ = frame->size();
frame->mutable_updated_region()->SetRect(
DesktopRect::MakeSize(frame->size()));
if (!result) {
LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed.";
frame.reset();
}
callback_->OnCaptureCompleted(frame.release());
}
} // namespace
// static
WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) {
return new WindowCapturerWin();
}
} // namespace webrtc
|
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/desktop_capture/window_capturer.h"
#include <assert.h>
#include "webrtc/base/win32.h"
#include "webrtc/modules/desktop_capture/desktop_frame_win.h"
#include "webrtc/modules/desktop_capture/win/window_capture_utils.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
namespace webrtc {
namespace {
typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);
BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {
WindowCapturer::WindowList* list =
reinterpret_cast<WindowCapturer::WindowList*>(param);
// Skip windows that are invisible, minimized, have no title, or are owned,
// unless they have the app window style set.
int len = GetWindowTextLength(hwnd);
HWND owner = GetWindow(hwnd, GW_OWNER);
LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||
(owner && !(exstyle & WS_EX_APPWINDOW))) {
return TRUE;
}
// Skip the Program Manager window and the Start button.
const size_t kClassLength = 256;
WCHAR class_name[kClassLength];
GetClassName(hwnd, class_name, kClassLength);
// Skip Program Manager window and the Start button. This is the same logic
// that's used in Win32WindowPicker in libjingle. Consider filtering other
// windows as well (e.g. toolbars).
if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0)
return TRUE;
WindowCapturer::Window window;
window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);
const size_t kTitleLength = 500;
WCHAR window_title[kTitleLength];
// Truncate the title if it's longer than kTitleLength.
GetWindowText(hwnd, window_title, kTitleLength);
window.title = rtc::ToUtf8(window_title);
// Skip windows when we failed to convert the title or it is empty.
if (window.title.empty())
return TRUE;
list->push_back(window);
return TRUE;
}
class WindowCapturerWin : public WindowCapturer {
public:
WindowCapturerWin();
virtual ~WindowCapturerWin();
// WindowCapturer interface.
virtual bool GetWindowList(WindowList* windows) OVERRIDE;
virtual bool SelectWindow(WindowId id) OVERRIDE;
virtual bool BringSelectedWindowToFront() OVERRIDE;
// DesktopCapturer interface.
virtual void Start(Callback* callback) OVERRIDE;
virtual void Capture(const DesktopRegion& region) OVERRIDE;
private:
bool IsAeroEnabled();
Callback* callback_;
// HWND and HDC for the currently selected window or NULL if window is not
// selected.
HWND window_;
// dwmapi.dll is used to determine if desktop compositing is enabled.
HMODULE dwmapi_library_;
DwmIsCompositionEnabledFunc is_composition_enabled_func_;
DesktopSize previous_size_;
DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);
};
WindowCapturerWin::WindowCapturerWin()
: callback_(NULL),
window_(NULL) {
// Try to load dwmapi.dll dynamically since it is not available on XP.
dwmapi_library_ = LoadLibrary(L"dwmapi.dll");
if (dwmapi_library_) {
is_composition_enabled_func_ =
reinterpret_cast<DwmIsCompositionEnabledFunc>(
GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled"));
assert(is_composition_enabled_func_);
} else {
is_composition_enabled_func_ = NULL;
}
}
WindowCapturerWin::~WindowCapturerWin() {
if (dwmapi_library_)
FreeLibrary(dwmapi_library_);
}
bool WindowCapturerWin::IsAeroEnabled() {
BOOL result = FALSE;
if (is_composition_enabled_func_)
is_composition_enabled_func_(&result);
return result != FALSE;
}
bool WindowCapturerWin::GetWindowList(WindowList* windows) {
WindowList result;
LPARAM param = reinterpret_cast<LPARAM>(&result);
if (!EnumWindows(&WindowsEnumerationHandler, param))
return false;
windows->swap(result);
return true;
}
bool WindowCapturerWin::SelectWindow(WindowId id) {
HWND window = reinterpret_cast<HWND>(id);
if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))
return false;
window_ = window;
previous_size_.set(0, 0);
return true;
}
bool WindowCapturerWin::BringSelectedWindowToFront() {
if (!window_)
return false;
if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_))
return false;
return SetForegroundWindow(window_) != 0;
}
void WindowCapturerWin::Start(Callback* callback) {
assert(!callback_);
assert(callback);
callback_ = callback;
}
void WindowCapturerWin::Capture(const DesktopRegion& region) {
if (!window_) {
LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError();
callback_->OnCaptureCompleted(NULL);
return;
}
// Stop capturing if the window has been closed or hidden.
if (!IsWindow(window_) || !IsWindowVisible(window_)) {
callback_->OnCaptureCompleted(NULL);
return;
}
// Return a 2x2 black frame if the window is minimized. The size is 2x2 so it
// can be subsampled to I420 downstream.
if (IsIconic(window_)) {
BasicDesktopFrame* frame = new BasicDesktopFrame(DesktopSize(2, 2));
memset(frame->data(), 0, frame->stride() * frame->size().height());
previous_size_ = frame->size();
callback_->OnCaptureCompleted(frame);
return;
}
DesktopRect original_rect;
DesktopRect cropped_rect;
if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) {
LOG(LS_WARNING) << "Failed to get window info: " << GetLastError();
callback_->OnCaptureCompleted(NULL);
return;
}
HDC window_dc = GetWindowDC(window_);
if (!window_dc) {
LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError();
callback_->OnCaptureCompleted(NULL);
return;
}
scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(
cropped_rect.size(), NULL, window_dc));
if (!frame.get()) {
ReleaseDC(window_, window_dc);
callback_->OnCaptureCompleted(NULL);
return;
}
HDC mem_dc = CreateCompatibleDC(window_dc);
HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap());
BOOL result = FALSE;
// When desktop composition (Aero) is enabled each window is rendered to a
// private buffer allowing BitBlt() to get the window content even if the
// window is occluded. PrintWindow() is slower but lets rendering the window
// contents to an off-screen device context when Aero is not available.
// PrintWindow() is not supported by some applications.
//
// If Aero is enabled, we prefer BitBlt() because it's faster and avoids
// window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may
// render occluding windows on top of the desired window.
//
// When composition is enabled the DC returned by GetWindowDC() doesn't always
// have window frame rendered correctly. Windows renders it only once and then
// caches the result between captures. We hack it around by calling
// PrintWindow() whenever window size changes, including the first time of
// capturing - it somehow affects what we get from BitBlt() on the subsequent
// captures.
if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) {
result = PrintWindow(window_, mem_dc, 0);
}
// Aero is enabled or PrintWindow() failed, use BitBlt.
if (!result) {
result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),
window_dc,
cropped_rect.left() - original_rect.left(),
cropped_rect.top() - original_rect.top(),
SRCCOPY);
}
SelectObject(mem_dc, previous_object);
DeleteDC(mem_dc);
ReleaseDC(window_, window_dc);
previous_size_ = frame->size();
frame->mutable_updated_region()->SetRect(
DesktopRect::MakeSize(frame->size()));
if (!result) {
LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed.";
frame.reset();
}
callback_->OnCaptureCompleted(frame.release());
}
} // namespace
// static
WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) {
return new WindowCapturerWin();
}
} // namespace webrtc
|
Fix window capturing on Windows when the window is minimized.
|
Fix window capturing on Windows when the window is minimized.
BUG=crbug/410290
[email protected]
Review URL: https://webrtc-codereview.appspot.com/20319004
git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@7158 4adac7df-926f-26a2-2b94-8c16560cd09d
|
C++
|
bsd-3-clause
|
svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758
|
662dd1a845e239dd1f347403560df6a9124d6c7c
|
modules/python3/bindings/src/pydatareaders.cpp
|
modules/python3/bindings/src/pydatareaders.cpp
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2022 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwopy/pydatareaders.h>
#include <inviwo/core/io/datareader.h>
#include <inviwo/core/io/datareaderfactory.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/volume/volume.h>
namespace inviwo {
// Allow overriding virtual functions from Python
template <typename T>
class DataReaderTypeTrampoline : public DataReaderType<T>,
public pybind11::trampoline_self_life_support {
public:
using DataReaderType<T>::DataReaderType; // Inherit constructors
virtual DataReaderType<T>* clone() const override {
PYBIND11_OVERRIDE_PURE(DataReaderType<T>*, /* Return type */
DataReaderType<T>, /* Parent class */
clone, /* Name of function in C++ (must match Python name) */
);
}
virtual bool setOption(std::string_view key, std::any value) override {
PYBIND11_OVERRIDE(bool, /* Return type */
DataReaderType<T>, /* Parent class */
setOption, /* Name of function in C++ (must match Python name) */
key, value /* Argument(s) */
);
}
virtual std::shared_ptr<T> readData(std::string_view filePath) override {
PYBIND11_OVERRIDE_PURE(std::shared_ptr<T>, /* Return type */
DataReaderType<T>, /* Parent class */
readData, /* Name of function in C++ (must match Python name) */
filePath /* Argument(s) */
);
}
virtual std::shared_ptr<T> readData(std::string_view filePath, MetaDataOwner* owner) override {
PYBIND11_OVERRIDE(std::shared_ptr<T>, /* Return type */
DataReaderType<T>, /* Parent class */
readData, /* Name of function in C++ (must match Python name) */
filePath, owner /* Argument(s) */
);
}
};
template <typename T>
void exposeFactoryReaderType(pybind11::class_<DataReaderFactory>& r, std::string_view type) {
namespace py = pybind11;
r.def(fmt::format("getExtensionsFor{}", type).c_str(),
(std::vector<FileExtension>(DataReaderFactory::*)() const) &
DataReaderFactory::getExtensionsForType<T>)
.def(fmt::format("get{}Reader", type).c_str(),
(std::unique_ptr<DataReaderType<T>>(DataReaderFactory::*)(std::string_view) const) &
DataReaderFactory::getReaderForTypeAndExtension<T>)
.def(
fmt::format("get{}Reader", type).c_str(),
(std::unique_ptr<DataReaderType<T>>(DataReaderFactory::*)(const FileExtension&) const) &
DataReaderFactory::getReaderForTypeAndExtension<T>)
.def(fmt::format("get{}Reader", type).c_str(),
(std::unique_ptr<DataReaderType<T>>(DataReaderFactory::*)(const FileExtension&,
std::string_view) const) &
DataReaderFactory::getReaderForTypeAndExtension<T>)
.def(fmt::format("has{}Reader", type).c_str(),
(bool(DataReaderFactory::*)(std::string_view) const) &
DataReaderFactory::hasReaderForTypeAndExtension<T>);
}
void exposeDataReaders(pybind11::module& m) {
namespace py = pybind11;
py::class_<DataReader>(m, "DataReader")
.def("clone", &DataReader::clone)
.def_property_readonly("extensions", &DataReader::getExtensions,
py::return_value_policy::reference_internal)
.def("addExtension", &DataReader::addExtension)
.def("setOption", &DataReader::setOption)
.def("getOption", &DataReader::getOption);
// https://pybind11.readthedocs.io/en/stable/advanced/classes.html#binding-classes-with-template-parameters
py::class_<DataReaderType<Image>, DataReader, DataReaderTypeTrampoline<Image>>(
m, "ImageDataReader")
.def("readData", py::overload_cast<std::string_view>(&DataReaderType<Image>::readData))
.def("readData",
py::overload_cast<std::string_view, MetaDataOwner*>(&DataReaderType<Image>::readData));
py::class_<DataReaderType<Mesh>, DataReader, DataReaderTypeTrampoline<Mesh>>(m,
"MeshDataReader")
.def("readData", py::overload_cast<std::string_view>(&DataReaderType<Mesh>::readData))
.def("readData",
py::overload_cast<std::string_view, MetaDataOwner*>(&DataReaderType<Mesh>::readData));
py::class_<DataReaderType<Volume>, DataReader, DataReaderTypeTrampoline<Volume>>(
m, "VolumeDataReader")
.def("readData", py::overload_cast<std::string_view>(&DataReaderType<Volume>::readData))
.def("readData", py::overload_cast<std::string_view, MetaDataOwner*>(
&DataReaderType<Volume>::readData));
auto fr =
py::class_<DataReaderFactory>(m, "DataReaderFactory")
.def(py::init<>())
.def("create",
(std::unique_ptr<DataReader>(DataReaderFactory::*)(const FileExtension&) const) &
DataReaderFactory::create)
.def("create",
(std::unique_ptr<DataReader>(DataReaderFactory::*)(std::string_view) const) &
DataReaderFactory::create)
.def("hasKey",
(bool(DataReaderFactory::*)(std::string_view) const) & DataReaderFactory::hasKey)
.def("hasKey", (bool(DataReaderFactory::*)(const FileExtension&) const) &
DataReaderFactory::hasKey);
// No good way of dealing with template return types so we manually define one for each known
// type.
// https://github.com/pybind/pybind11/issues/1667#issuecomment-454348004
// If your module exposes a new reader type it will have to bind getXXXReader.
exposeFactoryReaderType<Image>(fr, "Image");
exposeFactoryReaderType<Mesh>(fr, "Mesh");
exposeFactoryReaderType<Volume>(fr, "Volume");
}
} // namespace inviwo
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2022 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwopy/pydatareaders.h>
#include <inviwo/core/io/datareader.h>
#include <inviwo/core/io/datareaderfactory.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/volume/volume.h>
namespace inviwo {
// Allow overriding virtual functions from Python
template <typename T>
class DataReaderTypeTrampoline : public DataReaderType<T>,
public pybind11::trampoline_self_life_support {
public:
using DataReaderType<T>::DataReaderType; // Inherit constructors
virtual DataReaderType<T>* clone() const override {
PYBIND11_OVERRIDE_PURE(DataReaderType<T>*, /* Return type */
DataReaderType<T>, /* Parent class */
clone, /* Name of function in C++ (must match Python name) */
);
}
virtual bool setOption(std::string_view key, std::any value) override {
PYBIND11_OVERRIDE(bool, /* Return type */
DataReaderType<T>, /* Parent class */
setOption, /* Name of function in C++ (must match Python name) */
key, value /* Argument(s) */
);
}
virtual std::shared_ptr<T> readData(std::string_view filePath) override {
PYBIND11_OVERRIDE_PURE(std::shared_ptr<T>, /* Return type */
DataReaderType<T>, /* Parent class */
readData, /* Name of function in C++ (must match Python name) */
filePath /* Argument(s) */
);
}
virtual std::shared_ptr<T> readData(std::string_view filePath, MetaDataOwner* owner) override {
PYBIND11_OVERRIDE(std::shared_ptr<T>, /* Return type */
DataReaderType<T>, /* Parent class */
readData, /* Name of function in C++ (must match Python name) */
filePath, owner /* Argument(s) */
);
}
};
template <typename T>
void exposeFactoryReaderType(pybind11::class_<DataReaderFactory>& r, std::string_view type) {
namespace py = pybind11;
r.def(fmt::format("getExtensionsFor{}", type).c_str(),
(std::vector<FileExtension>(DataReaderFactory::*)() const) &
DataReaderFactory::getExtensionsForType<T>)
.def(fmt::format("get{}Reader", type).c_str(),
(std::unique_ptr<DataReaderType<T>>(DataReaderFactory::*)(std::string_view) const) &
DataReaderFactory::getReaderForTypeAndExtension<T>)
.def(
fmt::format("get{}Reader", type).c_str(),
(std::unique_ptr<DataReaderType<T>>(DataReaderFactory::*)(const FileExtension&) const) &
DataReaderFactory::getReaderForTypeAndExtension<T>)
.def(fmt::format("get{}Reader", type).c_str(),
(std::unique_ptr<DataReaderType<T>>(DataReaderFactory::*)(const FileExtension&,
std::string_view) const) &
DataReaderFactory::getReaderForTypeAndExtension<T>)
.def(fmt::format("has{}Reader", type).c_str(),
(bool (DataReaderFactory::*)(std::string_view) const) &
DataReaderFactory::hasReaderForTypeAndExtension<T>);
}
void exposeDataReaders(pybind11::module& m) {
namespace py = pybind11;
py::class_<DataReader>(m, "DataReader")
.def("clone", &DataReader::clone)
.def_property_readonly("extensions", &DataReader::getExtensions,
py::return_value_policy::reference_internal)
.def("addExtension", &DataReader::addExtension)
.def("setOption", &DataReader::setOption)
.def("getOption", &DataReader::getOption);
// https://pybind11.readthedocs.io/en/stable/advanced/classes.html#binding-classes-with-template-parameters
py::class_<DataReaderType<Image>, DataReader, DataReaderTypeTrampoline<Image>>(
m, "ImageDataReader")
.def("readData", py::overload_cast<std::string_view>(&DataReaderType<Image>::readData))
.def("readData",
py::overload_cast<std::string_view, MetaDataOwner*>(&DataReaderType<Image>::readData));
py::class_<DataReaderType<Mesh>, DataReader, DataReaderTypeTrampoline<Mesh>>(m,
"MeshDataReader")
.def("readData", py::overload_cast<std::string_view>(&DataReaderType<Mesh>::readData))
.def("readData",
py::overload_cast<std::string_view, MetaDataOwner*>(&DataReaderType<Mesh>::readData));
py::class_<DataReaderType<Volume>, DataReader, DataReaderTypeTrampoline<Volume>>(
m, "VolumeDataReader")
.def("readData", py::overload_cast<std::string_view>(&DataReaderType<Volume>::readData))
.def("readData", py::overload_cast<std::string_view, MetaDataOwner*>(
&DataReaderType<Volume>::readData));
auto fr =
py::class_<DataReaderFactory>(m, "DataReaderFactory")
.def(py::init<>())
.def("create",
(std::unique_ptr<DataReader>(DataReaderFactory::*)(const FileExtension&) const) &
DataReaderFactory::create)
.def("create",
(std::unique_ptr<DataReader>(DataReaderFactory::*)(std::string_view) const) &
DataReaderFactory::create)
.def("hasKey",
(bool (DataReaderFactory::*)(std::string_view) const) & DataReaderFactory::hasKey)
.def("hasKey", (bool (DataReaderFactory::*)(const FileExtension&) const) &
DataReaderFactory::hasKey);
// No good way of dealing with template return types so we manually define one for each known
// type.
// https://github.com/pybind/pybind11/issues/1667#issuecomment-454348004
// If your module exposes a new reader type it will have to bind getXXXReader.
exposeFactoryReaderType<Image>(fr, "Image");
exposeFactoryReaderType<Mesh>(fr, "Mesh");
exposeFactoryReaderType<Volume>(fr, "Volume");
}
} // namespace inviwo
|
Format fixes
|
Jenkins: Format fixes
|
C++
|
bsd-2-clause
|
inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo
|
93b8b2a42a268b8a87593903f59a528bf349ebf4
|
tree/treeplayer/src/TTreeDrawArgsParser.cxx
|
tree/treeplayer/src/TTreeDrawArgsParser.cxx
|
// @(#)root/treeplayer:$Id$
// Author: Marek Biskup 24/01/2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TTreeDrawArgsParser
A class that parses all parameters for TTree::Draw().
See TTree::Draw() for the format description.
*/
#include "TTreeDrawArgsParser.h"
#include "TDirectory.h"
Int_t TTreeDrawArgsParser::fgMaxDimension = 4;
Int_t TTreeDrawArgsParser::fgMaxParameters = 9;
ClassImp(TTreeDrawArgsParser)
////////////////////////////////////////////////////////////////////////////////
/// Constructor - cleans all the class variables.
TTreeDrawArgsParser::TTreeDrawArgsParser()
{
ClearPrevious();
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor.
TTreeDrawArgsParser::~TTreeDrawArgsParser()
{
}
////////////////////////////////////////////////////////////////////////////////
/// return fgMaxDimension (cannot be inline)
Int_t TTreeDrawArgsParser::GetMaxDimension()
{
return fgMaxDimension;
}
////////////////////////////////////////////////////////////////////////////////
/// Resets all the variables of the class.
void TTreeDrawArgsParser::ClearPrevious()
{
fExp = "";
fSelection = "";
fOption = "";
fDimension = -1;
int i;
for (i = 0; i < fgMaxDimension; i++) {
fVarExp[i] = "";
}
fAdd = kFALSE;
fName = "";
fNoParameters = 0;
for (i = 0; i < fgMaxParameters; i++) {
fParameterGiven[i] = kFALSE;
fParameters[i] = 0;
}
fShouldDraw = kTRUE;
fOriginal = 0;
fDrawProfile = kFALSE;
fOptionSame = kFALSE;
fEntryList = kFALSE;
fOutputType = kUNKNOWN;
}
////////////////////////////////////////////////////////////////////////////////
/// Parse expression [var1 [:var2 [:var3] ...]],
/// number of variables cannot be greater than fgMaxDimension.
///
/// A colon which is followed by (or that follows) another semicolon
/// is not regarded as a separator.
///
/// If there are more separating : than fgMaxDimension - 1 then
/// all characters after (fgMaxDimension - 1)th colon is put into
/// the last variable.
///
/// - fDimension := <number of variables>
/// - fVarExp[0] := <first variable string>
/// - fVarExp[1] := <second variable string>
/// ..
/// Returns kFALSE in case of an error.
Bool_t TTreeDrawArgsParser::SplitVariables(TString variables)
{
fDimension = 0;
if (variables.Length() == 0)
return kTRUE;
int prev = 0;
int i;
for (i = 0; i < variables.Length() && fDimension < fgMaxDimension; i++) {
if (variables[i] == ':'
&& !( (i > 0 && variables[i - 1] == ':')
|| (i + 1 < variables.Length() && variables[i + 1] == ':') ) ) {
fVarExp[fDimension] = variables(prev, i - prev);
prev = i+1;
fDimension++;
}
}
if (fDimension < fgMaxDimension && i != prev)
fVarExp[fDimension++] = variables(prev, i - prev);
else
return kFALSE;
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Syntax:
///
/// [' '*][[\+][' '*]name[(num1 [, [num2] ] [, [num3] ] ...)]]
///
/// num's are floating point numbers
/// sets the fileds fNoParameters, fParameterGiven, fParameters, fAdd, fName
/// to apropriate values.
///
/// Returns kFALSE in case of an error.
Bool_t TTreeDrawArgsParser::ParseName(TString name)
{
name.ReplaceAll(" ", "");
if (name.Length() != 0 && name[0] == '+') {
fAdd = kTRUE;
name = name (1, name.Length() - 1);
}
else
fAdd = kFALSE;
Bool_t result = kTRUE;
fNoParameters = 0;
for (int i = 0; i < fgMaxParameters; i++)
fParameterGiven[i] = kFALSE;
if (char *p = (char*)strstr(name.Data(), "(")) {
fName = name(0, p - name.Data());
p++;
char* end = p + strlen(p);
for (int i = 0; i < fgMaxParameters; i++) {
char* q = p;
while (p < end && *p != ',' && *p != ')')
p++;
TString s(q, p - q);
if (sscanf(s.Data(), "%lf", &fParameters[i]) == 1) {
fParameterGiven[i] = kTRUE;
fNoParameters++;
}
if (p == end) {
Error("ParseName", "expected \')\'");
result = kFALSE;
break;
}
else if (*p == ')')
break;
else if (*p == ',')
p++;
else {
Error("ParseName", "impossible value for *q!");
result = kFALSE;
break;
}
}
}
else { // if (char *p = strstr(name.Data(), "("))
fName = name;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Split variables and parse name and parameters in brackets.
Bool_t TTreeDrawArgsParser::ParseVarExp()
{
char* gg = (char*)strstr(fExp.Data(), ">>");
TString variables;
TString name;
if (gg) {
variables = fExp(0, gg - fExp.Data());
name = fExp(gg+2 - fExp.Data(), fExp.Length() - (gg + 2 - fExp.Data()));
}
else {
variables = fExp;
name = "";
}
Bool_t result = SplitVariables(variables) && ParseName(name);
if (!result) {
Error("ParseVarExp", "error parsing variable expression");
return kFALSE;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Check if options contain some data important for choosing the type of the
/// drawn object.
Bool_t TTreeDrawArgsParser::ParseOption()
{
fOption.ToLower();
if (fOption.Contains("goff")) {
fShouldDraw = kFALSE;
}
if (fOption.Contains("prof")) {
fDrawProfile = kTRUE;
}
if (fOption.Contains("same")) {
fOptionSame = kTRUE;
}
if (fOption.Contains("entrylist")){
fEntryList = kTRUE;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Parses parameters from TTree::Draw().
/// varexp - Variable expression; see TTree::Draw()
/// selection - selection expression; see TTree::Draw()
/// option - Drawnig option; see TTree::Draw
Bool_t TTreeDrawArgsParser::Parse(const char *varexp, const char *selection, Option_t *option)
{
ClearPrevious();
// read the data provided and fill class fields
fSelection = selection;
fExp = varexp;
fOption = option;
Bool_t success = ParseVarExp();
success &= ParseOption();
if (!success)
return kFALSE;
// if the name was specified find the existing histogram
if (fName != "") {
fOriginal = gDirectory->Get(fName);
}
else
fOriginal = 0;
DefineType();
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Put the type of the draw result into fOutputType and return it.
TTreeDrawArgsParser::EOutputType TTreeDrawArgsParser::DefineType()
{
if (fDimension == 0){
if (fEntryList)
return fOutputType = kENTRYLIST;
else
return fOutputType = kEVENTLIST;
}
if (fDimension == 2 && fDrawProfile)
return fOutputType = kPROFILE;
if (fDimension == 3 && fDrawProfile)
return fOutputType = kPROFILE2D;
if (fDimension == 2) {
Bool_t graph = kFALSE;
// GG 9Mar2014: fixing ROOT-5337; should understand why it was like this, but we move to TSelectorDraw
// and this will disappear
// Int_t l = fOption.Length();
// if (l == 0 || fOption.Contains("same")) graph = kTRUE;
if (fOption.Contains("same")) graph = kTRUE;
if (fOption.Contains("p") || fOption.Contains("*") || fOption.Contains("l")) graph = kTRUE;
if (fOption.Contains("surf") || fOption.Contains("lego") || fOption.Contains("cont")) graph = kFALSE;
if (fOption.Contains("col") || fOption.Contains("hist") || fOption.Contains("scat")) graph = kFALSE;
if (fOption.Contains("box")) graph = kFALSE;
if (graph)
return fOutputType = kGRAPH;
else
return fOutputType = kHISTOGRAM2D;
}
if (fDimension == 3) {
if (fOption.Contains("col"))
return fOutputType = kLISTOFGRAPHS;
else
return fOutputType = kHISTOGRAM3D;
// GG 9Mar2014: fixing ROOT-5337; should understand why it was like this, but we move to TSelectorDraw
// and this will disappear
// return fOutputType = kPOLYMARKER3D;
}
if (fDimension == 1)
return fOutputType = kHISTOGRAM1D;
if (fDimension == 4)
return fOutputType = kLISTOFPOLYMARKERS3D;
return kUNKNOWN;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns apropriate TSelector class name for proof for the object that is to be drawn
/// assumes that Parse() method has been called before.
TString TTreeDrawArgsParser::GetProofSelectorName() const
{
switch (fOutputType) {
case kUNKNOWN:
return "";
case kEVENTLIST:
return "TProofDrawEventList";
case kENTRYLIST:
return "TProofDrawEntryList";
case kPROFILE:
return "TProofDrawProfile";
case kPROFILE2D:
return "TProofDrawProfile2D";
case kGRAPH:
return "TProofDrawGraph";
case kPOLYMARKER3D:
return "TProofDrawPolyMarker3D";
case kLISTOFGRAPHS:
return "TProofDrawListOfGraphs";
case kHISTOGRAM1D:
case kHISTOGRAM2D:
case kHISTOGRAM3D:
return "TProofDrawHist";
case kLISTOFPOLYMARKERS3D:
return "TProofDrawListOfPolyMarkers3D";
default:
return "";
}
}
////////////////////////////////////////////////////////////////////////////////
/// returns *num*-th parameter from brackets in the expression
/// in case of an error (wrong number) returns 0.0
/// num - number of parameter (counted from 0)
Double_t TTreeDrawArgsParser::GetParameter(Int_t num) const
{
if (num >= 0 && num <= fgMaxParameters && fParameterGiven[num])
return fParameters[num];
else {
Error("GetParameter","wrong arguments");
return 0.0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// - num - parameter number
/// - def - default value of the parameter
/// returns the value of *num*-th parameter from the brackets in the variable expression
/// if the parameter of that number wasn't specified returns *def*.
Double_t TTreeDrawArgsParser::GetIfSpecified(Int_t num, Double_t def) const
{
if (num >= 0 && num <= fgMaxParameters && fParameterGiven[num])
return fParameters[num];
else
return def;
}
////////////////////////////////////////////////////////////////////////////////
/// returns kTRUE if the *num*-th parameter was specified
/// otherwise returns fFALSE
/// in case of an error (wrong num) prints an error message and
/// returns kFALSE.
Bool_t TTreeDrawArgsParser::IsSpecified(int num) const
{
if (num >= 0 && num <= fgMaxParameters)
return fParameterGiven[num];
else
Error("Specified", "wrong parameter %d; fgMaxParameters: %d", num, fgMaxParameters);
return kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the *num*-th variable string
/// in case of an error prints an error message and returns an empty string.
TString TTreeDrawArgsParser::GetVarExp(Int_t num) const
{
if (num >= 0 && num < fDimension)
return fVarExp[num];
else
Error("GetVarExp", "wrong Parameters %d; fDimension = %d", num, fDimension);
return "";
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the variable string, i.e. [var1[:var2[:var2[:var4]]]].
TString TTreeDrawArgsParser::GetVarExp() const
{
if (fDimension <= 0)
return "";
TString exp = fVarExp[0];
for (int i = 1; i < fDimension; i++) {
exp += ":";
exp += fVarExp[i];
}
return exp;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the desired plot title.
TString TTreeDrawArgsParser::GetObjectTitle() const
{
if (fSelection != "")
return Form("%s {%s}", GetVarExp().Data(), fSelection.Data());
else
return GetVarExp();
}
|
// @(#)root/treeplayer:$Id$
// Author: Marek Biskup 24/01/2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TTreeDrawArgsParser
A class that parses all parameters for TTree::Draw().
See TTree::Draw() for the format description.
*/
#include "TTreeDrawArgsParser.h"
#include "TDirectory.h"
Int_t TTreeDrawArgsParser::fgMaxDimension = 4;
Int_t TTreeDrawArgsParser::fgMaxParameters = 9;
ClassImp(TTreeDrawArgsParser)
////////////////////////////////////////////////////////////////////////////////
/// Constructor - cleans all the class variables.
TTreeDrawArgsParser::TTreeDrawArgsParser()
{
ClearPrevious();
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor.
TTreeDrawArgsParser::~TTreeDrawArgsParser()
{
}
////////////////////////////////////////////////////////////////////////////////
/// return fgMaxDimension (cannot be inline)
Int_t TTreeDrawArgsParser::GetMaxDimension()
{
return fgMaxDimension;
}
////////////////////////////////////////////////////////////////////////////////
/// Resets all the variables of the class.
void TTreeDrawArgsParser::ClearPrevious()
{
fExp = "";
fSelection = "";
fOption = "";
fDimension = -1;
int i;
for (i = 0; i < fgMaxDimension; i++) {
fVarExp[i] = "";
}
fAdd = kFALSE;
fName = "";
fNoParameters = 0;
for (i = 0; i < fgMaxParameters; i++) {
fParameterGiven[i] = kFALSE;
fParameters[i] = 0;
}
fShouldDraw = kTRUE;
fOriginal = 0;
fDrawProfile = kFALSE;
fOptionSame = kFALSE;
fEntryList = kFALSE;
fOutputType = kUNKNOWN;
}
////////////////////////////////////////////////////////////////////////////////
/// Parse expression [var1 [:var2 [:var3] ...]],
/// number of variables cannot be greater than fgMaxDimension.
///
/// A colon which is followed by (or that follows) another semicolon
/// is not regarded as a separator.
///
/// If there are more separating : than fgMaxDimension - 1 then
/// all characters after (fgMaxDimension - 1)th colon is put into
/// the last variable.
///
/// - `fDimension := <number of variables>`
/// - `fVarExp[0] := <first variable string>`
/// - `fVarExp[1] := <second variable string>`
/// ..
/// Returns kFALSE in case of an error.
Bool_t TTreeDrawArgsParser::SplitVariables(TString variables)
{
fDimension = 0;
if (variables.Length() == 0)
return kTRUE;
int prev = 0;
int i;
for (i = 0; i < variables.Length() && fDimension < fgMaxDimension; i++) {
if (variables[i] == ':'
&& !( (i > 0 && variables[i - 1] == ':')
|| (i + 1 < variables.Length() && variables[i + 1] == ':') ) ) {
fVarExp[fDimension] = variables(prev, i - prev);
prev = i+1;
fDimension++;
}
}
if (fDimension < fgMaxDimension && i != prev)
fVarExp[fDimension++] = variables(prev, i - prev);
else
return kFALSE;
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Syntax:
///
/// [' '*][[\+][' '*]name[(num1 [, [num2] ] [, [num3] ] ...)]]
///
/// num's are floating point numbers
/// sets the fileds fNoParameters, fParameterGiven, fParameters, fAdd, fName
/// to appropriate values.
///
/// Returns kFALSE in case of an error.
Bool_t TTreeDrawArgsParser::ParseName(TString name)
{
name.ReplaceAll(" ", "");
if (name.Length() != 0 && name[0] == '+') {
fAdd = kTRUE;
name = name (1, name.Length() - 1);
}
else
fAdd = kFALSE;
Bool_t result = kTRUE;
fNoParameters = 0;
for (int i = 0; i < fgMaxParameters; i++)
fParameterGiven[i] = kFALSE;
if (char *p = (char*)strstr(name.Data(), "(")) {
fName = name(0, p - name.Data());
p++;
char* end = p + strlen(p);
for (int i = 0; i < fgMaxParameters; i++) {
char* q = p;
while (p < end && *p != ',' && *p != ')')
p++;
TString s(q, p - q);
if (sscanf(s.Data(), "%lf", &fParameters[i]) == 1) {
fParameterGiven[i] = kTRUE;
fNoParameters++;
}
if (p == end) {
Error("ParseName", "expected \')\'");
result = kFALSE;
break;
}
else if (*p == ')')
break;
else if (*p == ',')
p++;
else {
Error("ParseName", "impossible value for *q!");
result = kFALSE;
break;
}
}
}
else { // if (char *p = strstr(name.Data(), "("))
fName = name;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Split variables and parse name and parameters in brackets.
Bool_t TTreeDrawArgsParser::ParseVarExp()
{
char* gg = (char*)strstr(fExp.Data(), ">>");
TString variables;
TString name;
if (gg) {
variables = fExp(0, gg - fExp.Data());
name = fExp(gg+2 - fExp.Data(), fExp.Length() - (gg + 2 - fExp.Data()));
}
else {
variables = fExp;
name = "";
}
Bool_t result = SplitVariables(variables) && ParseName(name);
if (!result) {
Error("ParseVarExp", "error parsing variable expression");
return kFALSE;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// Check if options contain some data important for choosing the type of the
/// drawn object.
Bool_t TTreeDrawArgsParser::ParseOption()
{
fOption.ToLower();
if (fOption.Contains("goff")) {
fShouldDraw = kFALSE;
}
if (fOption.Contains("prof")) {
fDrawProfile = kTRUE;
}
if (fOption.Contains("same")) {
fOptionSame = kTRUE;
}
if (fOption.Contains("entrylist")){
fEntryList = kTRUE;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Parses parameters from TTree::Draw().
/// - varexp - Variable expression; see TTree::Draw()
/// - selection - selection expression; see TTree::Draw()
/// - option - Drawing option; see TTree::Draw
Bool_t TTreeDrawArgsParser::Parse(const char *varexp, const char *selection, Option_t *option)
{
ClearPrevious();
// read the data provided and fill class fields
fSelection = selection;
fExp = varexp;
fOption = option;
Bool_t success = ParseVarExp();
success &= ParseOption();
if (!success)
return kFALSE;
// if the name was specified find the existing histogram
if (fName != "") {
fOriginal = gDirectory->Get(fName);
}
else
fOriginal = 0;
DefineType();
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Put the type of the draw result into fOutputType and return it.
TTreeDrawArgsParser::EOutputType TTreeDrawArgsParser::DefineType()
{
if (fDimension == 0){
if (fEntryList)
return fOutputType = kENTRYLIST;
else
return fOutputType = kEVENTLIST;
}
if (fDimension == 2 && fDrawProfile)
return fOutputType = kPROFILE;
if (fDimension == 3 && fDrawProfile)
return fOutputType = kPROFILE2D;
if (fDimension == 2) {
Bool_t graph = kFALSE;
// GG 9Mar2014: fixing ROOT-5337; should understand why it was like this, but we move to TSelectorDraw
// and this will disappear
// Int_t l = fOption.Length();
// if (l == 0 || fOption.Contains("same")) graph = kTRUE;
if (fOption.Contains("same")) graph = kTRUE;
if (fOption.Contains("p") || fOption.Contains("*") || fOption.Contains("l")) graph = kTRUE;
if (fOption.Contains("surf") || fOption.Contains("lego") || fOption.Contains("cont")) graph = kFALSE;
if (fOption.Contains("col") || fOption.Contains("hist") || fOption.Contains("scat")) graph = kFALSE;
if (fOption.Contains("box")) graph = kFALSE;
if (graph)
return fOutputType = kGRAPH;
else
return fOutputType = kHISTOGRAM2D;
}
if (fDimension == 3) {
if (fOption.Contains("col"))
return fOutputType = kLISTOFGRAPHS;
else
return fOutputType = kHISTOGRAM3D;
// GG 9Mar2014: fixing ROOT-5337; should understand why it was like this, but we move to TSelectorDraw
// and this will disappear
// return fOutputType = kPOLYMARKER3D;
}
if (fDimension == 1)
return fOutputType = kHISTOGRAM1D;
if (fDimension == 4)
return fOutputType = kLISTOFPOLYMARKERS3D;
return kUNKNOWN;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns appropriate TSelector class name for proof for the object that is to be drawn
/// assumes that Parse() method has been called before.
TString TTreeDrawArgsParser::GetProofSelectorName() const
{
switch (fOutputType) {
case kUNKNOWN:
return "";
case kEVENTLIST:
return "TProofDrawEventList";
case kENTRYLIST:
return "TProofDrawEntryList";
case kPROFILE:
return "TProofDrawProfile";
case kPROFILE2D:
return "TProofDrawProfile2D";
case kGRAPH:
return "TProofDrawGraph";
case kPOLYMARKER3D:
return "TProofDrawPolyMarker3D";
case kLISTOFGRAPHS:
return "TProofDrawListOfGraphs";
case kHISTOGRAM1D:
case kHISTOGRAM2D:
case kHISTOGRAM3D:
return "TProofDrawHist";
case kLISTOFPOLYMARKERS3D:
return "TProofDrawListOfPolyMarkers3D";
default:
return "";
}
}
////////////////////////////////////////////////////////////////////////////////
/// returns *num*-th parameter from brackets in the expression
/// in case of an error (wrong number) returns 0.0
/// num - number of parameter (counted from 0)
Double_t TTreeDrawArgsParser::GetParameter(Int_t num) const
{
if (num >= 0 && num <= fgMaxParameters && fParameterGiven[num])
return fParameters[num];
else {
Error("GetParameter","wrong arguments");
return 0.0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// - num - parameter number
/// - def - default value of the parameter
/// returns the value of *num*-th parameter from the brackets in the variable expression
/// if the parameter of that number wasn't specified returns *def*.
Double_t TTreeDrawArgsParser::GetIfSpecified(Int_t num, Double_t def) const
{
if (num >= 0 && num <= fgMaxParameters && fParameterGiven[num])
return fParameters[num];
else
return def;
}
////////////////////////////////////////////////////////////////////////////////
/// returns kTRUE if the *num*-th parameter was specified
/// otherwise returns fFALSE
/// in case of an error (wrong num) prints an error message and
/// returns kFALSE.
Bool_t TTreeDrawArgsParser::IsSpecified(int num) const
{
if (num >= 0 && num <= fgMaxParameters)
return fParameterGiven[num];
else
Error("Specified", "wrong parameter %d; fgMaxParameters: %d", num, fgMaxParameters);
return kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the *num*-th variable string
/// in case of an error prints an error message and returns an empty string.
TString TTreeDrawArgsParser::GetVarExp(Int_t num) const
{
if (num >= 0 && num < fDimension)
return fVarExp[num];
else
Error("GetVarExp", "wrong Parameters %d; fDimension = %d", num, fDimension);
return "";
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the variable string, i.e. [var1[:var2[:var2[:var4]]]].
TString TTreeDrawArgsParser::GetVarExp() const
{
if (fDimension <= 0)
return "";
TString exp = fVarExp[0];
for (int i = 1; i < fDimension; i++) {
exp += ":";
exp += fVarExp[i];
}
return exp;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the desired plot title.
TString TTreeDrawArgsParser::GetObjectTitle() const
{
if (fSelection != "")
return Form("%s {%s}", GetVarExp().Data(), fSelection.Data());
else
return GetVarExp();
}
|
Fix Doxygen warnings spell check
|
Fix Doxygen warnings
spell check
|
C++
|
lgpl-2.1
|
mhuwiler/rootauto,agarciamontoro/root,beniz/root,BerserkerTroll/root,beniz/root,agarciamontoro/root,buuck/root,buuck/root,bbockelm/root,simonpf/root,gganis/root,karies/root,zzxuanyuan/root,agarciamontoro/root,agarciamontoro/root,zzxuanyuan/root,gganis/root,olifre/root,BerserkerTroll/root,karies/root,karies/root,abhinavmoudgil95/root,davidlt/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,bbockelm/root,abhinavmoudgil95/root,zzxuanyuan/root,BerserkerTroll/root,olifre/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,buuck/root,mhuwiler/rootauto,karies/root,beniz/root,olifre/root,beniz/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,davidlt/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,gganis/root,abhinavmoudgil95/root,olifre/root,root-mirror/root,mhuwiler/rootauto,BerserkerTroll/root,zzxuanyuan/root,karies/root,simonpf/root,gganis/root,satyarth934/root,buuck/root,root-mirror/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,gganis/root,BerserkerTroll/root,abhinavmoudgil95/root,zzxuanyuan/root,mhuwiler/rootauto,beniz/root,agarciamontoro/root,davidlt/root,root-mirror/root,abhinavmoudgil95/root,simonpf/root,davidlt/root,abhinavmoudgil95/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,olifre/root,karies/root,beniz/root,satyarth934/root,gganis/root,zzxuanyuan/root-compressor-dummy,beniz/root,davidlt/root,davidlt/root,satyarth934/root,karies/root,zzxuanyuan/root,bbockelm/root,olifre/root,root-mirror/root,gganis/root,root-mirror/root,abhinavmoudgil95/root,zzxuanyuan/root,olifre/root,root-mirror/root,root-mirror/root,simonpf/root,satyarth934/root,buuck/root,agarciamontoro/root,beniz/root,gganis/root,davidlt/root,satyarth934/root,bbockelm/root,BerserkerTroll/root,karies/root,simonpf/root,zzxuanyuan/root,satyarth934/root,buuck/root,olifre/root,simonpf/root,satyarth934/root,bbockelm/root,root-mirror/root,simonpf/root,satyarth934/root,BerserkerTroll/root,olifre/root,satyarth934/root,karies/root,olifre/root,mhuwiler/rootauto,mhuwiler/rootauto,abhinavmoudgil95/root,satyarth934/root,mhuwiler/rootauto,mhuwiler/rootauto,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,BerserkerTroll/root,zzxuanyuan/root-compressor-dummy,simonpf/root,simonpf/root,davidlt/root,bbockelm/root,root-mirror/root,gganis/root,gganis/root,olifre/root,zzxuanyuan/root,beniz/root,simonpf/root,bbockelm/root,mhuwiler/rootauto,root-mirror/root,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,bbockelm/root,buuck/root,davidlt/root,buuck/root,buuck/root,bbockelm/root,abhinavmoudgil95/root,zzxuanyuan/root,BerserkerTroll/root,bbockelm/root,zzxuanyuan/root,buuck/root,simonpf/root,beniz/root,gganis/root,abhinavmoudgil95/root,davidlt/root,beniz/root,mhuwiler/rootauto,karies/root,davidlt/root,buuck/root,BerserkerTroll/root,zzxuanyuan/root,karies/root,agarciamontoro/root
|
23787b9cead604de24fc58d78adb062bd988cff4
|
xcore/xcam_thread.cpp
|
xcore/xcam_thread.cpp
|
/*
* xcam_thread.cpp - Thread
*
* Copyright (c) 2014 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Wind Yuan <[email protected]>
*/
#include "xcam_thread.h"
#include "xcam_mutex.h"
namespace XCam {
Thread::Thread (const char *name)
: _name (NULL)
, _thread_id (0)
, _started (false)
{
if (name)
_name = strdup (name);
}
Thread::~Thread ()
{
if (_name)
xcam_free (_name);
}
int
Thread::thread_func (void *user_data)
{
Thread *thread = (Thread *)user_data;
bool ret = true;
{
// Make sure running after start
SmartLock locker(thread->_mutex);
pthread_detach (pthread_self());
}
ret = thread->started ();
while (true) {
{
SmartLock locker(thread->_mutex);
if (!thread->_started || ret == false) {
thread->_started = false;
thread->_thread_id = 0;
thread->_exit_cond.signal();
ret = false;
break;
}
}
ret = thread->loop ();
}
thread->stopped ();
return 0;
}
bool
Thread::started ()
{
XCAM_LOG_DEBUG ("Thread(%s) started", XCAM_STR(_name));
return true;
}
void
Thread::stopped ()
{
XCAM_LOG_DEBUG ("Thread(%s) stopped", XCAM_STR(_name));
}
bool Thread::start ()
{
SmartLock locker(_mutex);
if (_started)
return true;
if (pthread_create (&_thread_id, NULL, (void * (*)(void*))thread_func, this) != 0)
return false;
_started = true;
return true;
}
bool Thread::stop ()
{
SmartLock locker(_mutex);
if (_started) {
_started = false;
_exit_cond.wait(_mutex);
}
return true;
}
bool Thread::is_running ()
{
SmartLock locker(_mutex);
return _started;
}
};
|
/*
* xcam_thread.cpp - Thread
*
* Copyright (c) 2014 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Wind Yuan <[email protected]>
*/
#include "xcam_thread.h"
#include "xcam_mutex.h"
#include <errno.h>
namespace XCam {
Thread::Thread (const char *name)
: _name (NULL)
, _thread_id (0)
, _started (false)
{
if (name)
_name = strdup (name);
}
Thread::~Thread ()
{
if (_name)
xcam_free (_name);
}
int
Thread::thread_func (void *user_data)
{
Thread *thread = (Thread *)user_data;
bool ret = true;
{
// Make sure running after start
SmartLock locker(thread->_mutex);
pthread_detach (pthread_self());
}
ret = thread->started ();
while (true) {
{
SmartLock locker(thread->_mutex);
if (!thread->_started || ret == false) {
thread->_started = false;
thread->_thread_id = 0;
thread->_exit_cond.signal();
ret = false;
break;
}
}
ret = thread->loop ();
}
thread->stopped ();
return 0;
}
bool
Thread::started ()
{
XCAM_LOG_DEBUG ("Thread(%s) started", XCAM_STR(_name));
return true;
}
void
Thread::stopped ()
{
XCAM_LOG_DEBUG ("Thread(%s) stopped", XCAM_STR(_name));
}
bool Thread::start ()
{
SmartLock locker(_mutex);
if (_started)
return true;
if (pthread_create (&_thread_id, NULL, (void * (*)(void*))thread_func, this) != 0)
return false;
_started = true;
#ifdef __USE_GNU
char thread_name[16];
xcam_mem_clear (thread_name);
snprintf (thread_name, sizeof (thread_name), "xc:%s", XCAM_STR(_name));
int ret = pthread_setname_np (_thread_id, thread_name);
if (ret != 0) {
XCAM_LOG_WARNING ("Thread(%s) set name to thread_id failed.(%d, %s)", XCAM_STR(_name), ret, strerror(ret));
}
#endif
return true;
}
bool Thread::stop ()
{
SmartLock locker(_mutex);
if (_started) {
_started = false;
_exit_cond.wait(_mutex);
}
return true;
}
bool Thread::is_running ()
{
SmartLock locker(_mutex);
return _started;
}
};
|
set name in each thread
|
thread: set name in each thread
Signed-off-by: Wind Yuan <[email protected]>
|
C++
|
apache-2.0
|
skibey/libxcam,zjamy/libxcam,dspmeng/libxcam,dspmeng/libxcam,dspmeng/libxcam,skibey/libxcam,skibey/libxcam,zjamy/libxcam,zjamy/libxcam
|
6b3647d5795467277fdd6cf3cc1684085f06fd49
|
cint/cint/src/Type.cxx
|
cint/cint/src/Type.cxx
|
/* /% C++ %/ */
/***********************************************************************
* cint (C/C++ interpreter)
************************************************************************
* Source file Type.cxx
************************************************************************
* Description:
* Extended Run Time Type Identification API
************************************************************************
* Author Masaharu Goto
* Copyright(c) 1995~2005 Masaharu Goto
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include "Api.h"
#include "common.h"
#ifndef G__OLDIMPLEMENTATION1586
// This length should match or exceed the length in G__type2string
static char G__buf[G__LONGLINE];
#endif
/*********************************************************************
* class G__TypeInfo
*
*********************************************************************/
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(const char *typenamein):
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{
Init(typenamein);
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo():
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(G__value buf):
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{
Init(buf);
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::~G__TypeInfo() {}
#ifndef __MAKECINT__
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(const Cint::G__TypeInfo& rhs)
: G__ClassInfo(rhs)
{
type = rhs.type;
typenum = rhs.typenum;
reftype = rhs.reftype;
isconst = rhs.isconst;
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo& Cint::G__TypeInfo::operator=(const Cint::G__TypeInfo& rhs)
{
if (this != &rhs) {
type = rhs.type;
typenum = rhs.typenum;
reftype = rhs.reftype;
isconst = rhs.isconst;
}
return *this;
}
#endif // __MAKECINT__
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(G__value& buf) {
type = buf.type;
typenum = buf.typenum;
tagnum = buf.tagnum;
if(type!='d' && type!='f') reftype=buf.obj.reftype.reftype;
else reftype=0;
isconst = buf.isconst;
}
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(struct G__var_array *var,int ig15) {
type = var->type[ig15];
typenum = var->p_typetable[ig15];
tagnum = var->p_tagtable[ig15];
reftype = var->reftype[ig15];
isconst = var->constvar[ig15];
}
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(const char *typenamein)
{
G__value buf;
buf = G__string2type_body(typenamein,2);
type = buf.type;
tagnum = buf.tagnum;
typenum = buf.typenum;
reftype = buf.obj.reftype.reftype;
isconst = buf.obj.i;
class_property = 0;
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::operator==(const G__TypeInfo& a)
{
if(type==a.type && tagnum==a.tagnum && typenum==a.typenum &&
reftype==a.reftype) {
return(1);
}
else {
return(0);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::operator!=(const G__TypeInfo& a)
{
if(type==a.type && tagnum==a.tagnum && typenum==a.typenum &&
reftype==a.reftype) {
return(0);
}
else {
return(1);
}
}
///////////////////////////////////////////////////////////////////////////
const char* Cint::G__TypeInfo::TrueName()
{
#if !defined(G__OLDIMPLEMENTATION1586)
strcpy(G__buf,
G__type2string((int)type,(int)tagnum,-1,(int)reftype,(int)isconst));
return(G__buf);
#elif !defind(G__OLDIMPLEMENTATION401)
return(G__type2string((int)type,(int)tagnum,-1,(int)reftype,(int)isconst));
#else
return(G__type2string((int)type,(int)tagnum,-1,(int)reftype));
#endif
}
///////////////////////////////////////////////////////////////////////////
const char* Cint::G__TypeInfo::Name()
{
#if !defined(G__OLDIMPLEMENTATION1586)
strcpy(G__buf,G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype
,(int)isconst));
return(G__buf);
#elif !defind(G__OLDIMPLEMENTATION401)
return(G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype
,(int)isconst));
#else
return(G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype));
#endif
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Size() const
{
G__value buf;
buf.type=(int)type;
buf.tagnum=(int)tagnum;
buf.typenum=(int)typenum;
buf.ref=reftype;
if(isupper(type)) {
buf.obj.reftype.reftype=reftype;
return(sizeof(void*));
}
return(G__sizeof(&buf));
}
///////////////////////////////////////////////////////////////////////////
long Cint::G__TypeInfo::Property()
{
long property = 0;
if(-1!=typenum) property|=G__BIT_ISTYPEDEF;
if(-1==tagnum) property|=G__BIT_ISFUNDAMENTAL;
else {
if(strcmp(G__struct.name[tagnum],"G__longlong")==0 ||
strcmp(G__struct.name[tagnum],"G__ulonglong")==0 ||
strcmp(G__struct.name[tagnum],"G__longdouble")==0) {
property|=G__BIT_ISFUNDAMENTAL;
if(-1!=typenum &&
(strcmp(G__newtype.name[typenum],"long long")==0 ||
strcmp(G__newtype.name[typenum],"unsigned long long")==0 ||
strcmp(G__newtype.name[typenum],"long double")==0)) {
property &= (~G__BIT_ISTYPEDEF);
}
}
else {
if(G__ClassInfo::IsValid()) property|=G__ClassInfo::Property();
}
}
if(isupper((int)type)) property|=G__BIT_ISPOINTER;
if(reftype==G__PARAREFERENCE||reftype>G__PARAREF)
property|=G__BIT_ISREFERENCE;
if(isconst&G__CONSTVAR) property|=G__BIT_ISCONSTANT;
if(isconst&G__PCONSTVAR) property|=G__BIT_ISPCONSTANT;
return(property);
}
///////////////////////////////////////////////////////////////////////////
void* Cint::G__TypeInfo::New() {
if(G__ClassInfo::IsValid()) {
return(G__ClassInfo::New());
}
else {
size_t size;
void *p;
size = Size();
p = new char[size];
return(p);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::IsValid() {
if(G__ClassInfo::IsValid()) {
return(1);
}
else if(type) {
return(1);
}
else {
return(0);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Typenum() const { return(typenum); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Type() const { return(type); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Reftype() const { return(reftype); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Isconst() const { return(isconst); }
///////////////////////////////////////////////////////////////////////////
G__value Cint::G__TypeInfo::Value() const {
G__value buf;
buf.type=type;
buf.tagnum=tagnum;
buf.typenum=typenum;
buf.isconst=(G__SIGNEDCHAR_T)isconst;
buf.obj.reftype.reftype = reftype;
buf.obj.i = 1;
buf.ref = 0;
return(buf);
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Next()
{
return 0;
}
|
/* /% C++ %/ */
/***********************************************************************
* cint (C/C++ interpreter)
************************************************************************
* Source file Type.cxx
************************************************************************
* Description:
* Extended Run Time Type Identification API
************************************************************************
* Author Masaharu Goto
* Copyright(c) 1995~2005 Masaharu Goto
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include "Api.h"
#include "common.h"
#ifndef G__OLDIMPLEMENTATION1586
// This length should match or exceed the length in G__type2string
static char G__buf[G__LONGLINE];
#endif
/*********************************************************************
* class G__TypeInfo
*
*********************************************************************/
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(const char *typenamein):
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{
Init(typenamein);
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo():
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(G__value buf):
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{
Init(buf);
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::~G__TypeInfo() {}
#ifndef __MAKECINT__
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(const Cint::G__TypeInfo& rhs)
: G__ClassInfo(rhs)
{
type = rhs.type;
typenum = rhs.typenum;
reftype = rhs.reftype;
isconst = rhs.isconst;
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo& Cint::G__TypeInfo::operator=(const Cint::G__TypeInfo& rhs)
{
if (this != &rhs) {
type = rhs.type;
typenum = rhs.typenum;
reftype = rhs.reftype;
isconst = rhs.isconst;
}
return *this;
}
#endif // __MAKECINT__
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(G__value& buf) {
type = buf.type;
typenum = buf.typenum;
tagnum = buf.tagnum;
if(type!='d' && type!='f') reftype=buf.obj.reftype.reftype;
else reftype=0;
isconst = buf.isconst;
}
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(struct G__var_array *var,int ig15) {
type = var->type[ig15];
typenum = var->p_typetable[ig15];
tagnum = var->p_tagtable[ig15];
reftype = var->reftype[ig15];
isconst = var->constvar[ig15];
}
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(const char *typenamein)
{
G__value buf;
buf = G__string2type_body(typenamein,2);
type = buf.type;
tagnum = buf.tagnum;
typenum = buf.typenum;
reftype = buf.obj.reftype.reftype;
isconst = buf.obj.i;
class_property = 0;
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::operator==(const G__TypeInfo& a)
{
if(type==a.type && tagnum==a.tagnum && typenum==a.typenum &&
reftype==a.reftype) {
return(1);
}
else {
return(0);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::operator!=(const G__TypeInfo& a)
{
if(type==a.type && tagnum==a.tagnum && typenum==a.typenum &&
reftype==a.reftype) {
return(0);
}
else {
return(1);
}
}
///////////////////////////////////////////////////////////////////////////
const char* Cint::G__TypeInfo::TrueName()
{
#if !defined(G__OLDIMPLEMENTATION1586)
strcpy(G__buf,
G__type2string((int)type,(int)tagnum,-1,(int)reftype,(int)isconst));
return(G__buf);
#elif !defined(G__OLDIMPLEMENTATION401)
return(G__type2string((int)type,(int)tagnum,-1,(int)reftype,(int)isconst));
#else
return(G__type2string((int)type,(int)tagnum,-1,(int)reftype));
#endif
}
///////////////////////////////////////////////////////////////////////////
const char* Cint::G__TypeInfo::Name()
{
#if !defined(G__OLDIMPLEMENTATION1586)
strcpy(G__buf,G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype
,(int)isconst));
return(G__buf);
#elif !defined(G__OLDIMPLEMENTATION401)
return(G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype
,(int)isconst));
#else
return(G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype));
#endif
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Size() const
{
G__value buf;
buf.type=(int)type;
buf.tagnum=(int)tagnum;
buf.typenum=(int)typenum;
buf.ref=reftype;
if(isupper(type)) {
buf.obj.reftype.reftype=reftype;
return(sizeof(void*));
}
return(G__sizeof(&buf));
}
///////////////////////////////////////////////////////////////////////////
long Cint::G__TypeInfo::Property()
{
long property = 0;
if(-1!=typenum) property|=G__BIT_ISTYPEDEF;
if(-1==tagnum) property|=G__BIT_ISFUNDAMENTAL;
else {
if(strcmp(G__struct.name[tagnum],"G__longlong")==0 ||
strcmp(G__struct.name[tagnum],"G__ulonglong")==0 ||
strcmp(G__struct.name[tagnum],"G__longdouble")==0) {
property|=G__BIT_ISFUNDAMENTAL;
if(-1!=typenum &&
(strcmp(G__newtype.name[typenum],"long long")==0 ||
strcmp(G__newtype.name[typenum],"unsigned long long")==0 ||
strcmp(G__newtype.name[typenum],"long double")==0)) {
property &= (~G__BIT_ISTYPEDEF);
}
}
else {
if(G__ClassInfo::IsValid()) property|=G__ClassInfo::Property();
}
}
if(isupper((int)type)) property|=G__BIT_ISPOINTER;
if(reftype==G__PARAREFERENCE||reftype>G__PARAREF)
property|=G__BIT_ISREFERENCE;
if(isconst&G__CONSTVAR) property|=G__BIT_ISCONSTANT;
if(isconst&G__PCONSTVAR) property|=G__BIT_ISPCONSTANT;
return(property);
}
///////////////////////////////////////////////////////////////////////////
void* Cint::G__TypeInfo::New() {
if(G__ClassInfo::IsValid()) {
return(G__ClassInfo::New());
}
else {
size_t size;
void *p;
size = Size();
p = new char[size];
return(p);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::IsValid() {
if(G__ClassInfo::IsValid()) {
return(1);
}
else if(type) {
return(1);
}
else {
return(0);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Typenum() const { return(typenum); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Type() const { return(type); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Reftype() const { return(reftype); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Isconst() const { return(isconst); }
///////////////////////////////////////////////////////////////////////////
G__value Cint::G__TypeInfo::Value() const {
G__value buf;
buf.type=type;
buf.tagnum=tagnum;
buf.typenum=typenum;
buf.isconst=(G__SIGNEDCHAR_T)isconst;
buf.obj.reftype.reftype = reftype;
buf.obj.i = 1;
buf.ref = 0;
return(buf);
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Next()
{
return 0;
}
|
Fix typo in preprocessor statement noticed by gcc 4.4
|
Fix typo in preprocessor statement noticed by gcc 4.4
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@26109 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,bbannier/ROOT,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,bbannier/ROOT,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,bbannier/ROOT
|
416c7533e0e37033b48213bcda0c9c6fb22e226f
|
fpicker/source/win32/filepicker/getfilenamewrapper.cxx
|
fpicker/source/win32/filepicker/getfilenamewrapper.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <stdio.h>
#include <osl/diagnose.h>
#include "getfilenamewrapper.hxx"
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <objbase.h>
#include <process.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
namespace /* private */
{
//-----------------------------------------------
// This class prevents changing of the working
// directory.
//-----------------------------------------------
class CurDirGuard
{
sal_Bool m_bValid;
wchar_t* m_pBuffer;
DWORD m_nBufLen;
public:
CurDirGuard()
: m_bValid( sal_False )
, m_pBuffer( NULL )
, m_nBufLen( 0 )
{
m_nBufLen = GetCurrentDirectoryW( 0, NULL );
if ( m_nBufLen )
{
m_pBuffer = new wchar_t[m_nBufLen];
m_bValid = ( GetCurrentDirectoryW( m_nBufLen, m_pBuffer ) == ( m_nBufLen - 1 ) );
}
}
~CurDirGuard()
{
bool bDirSet = false;
if ( m_pBuffer )
{
if ( m_bValid )
{
if ( m_nBufLen - 1 > MAX_PATH )
{
if ( (LONG32)GetVersion() < 0 )
{
// this is Win 98/ME branch, such a long path can not be set
// use the system path as fallback later
}
else
{
DWORD nNewLen = m_nBufLen + 8;
wchar_t* pNewBuffer = new wchar_t[nNewLen];
if ( m_nBufLen > 3 && m_pBuffer[0] == (wchar_t)'\\' && m_pBuffer[1] == (wchar_t)'\\' )
{
if ( m_pBuffer[2] == (wchar_t)'?' )
_snwprintf( pNewBuffer, nNewLen, L"%s", m_pBuffer );
else
_snwprintf( pNewBuffer, nNewLen, L"\\\\?\\UNC\\%s", m_pBuffer+2 );
}
else
_snwprintf( pNewBuffer, nNewLen, L"\\\\?\\%s", m_pBuffer );
bDirSet = SetCurrentDirectoryW( pNewBuffer );
delete [] pNewBuffer;
}
}
else
bDirSet = SetCurrentDirectoryW( m_pBuffer );
}
delete [] m_pBuffer;
m_pBuffer = NULL;
}
if ( !bDirSet )
{
// the fallback solution
wchar_t pPath[MAX_PATH+1];
if ( GetWindowsDirectoryW( pPath, MAX_PATH+1 ) <= MAX_PATH )
{
SetCurrentDirectoryW( pPath );
}
else
{
// the system path is also too long?!!
}
}
}
};
//-----------------------------------------------
//
//-----------------------------------------------
struct GetFileNameParam
{
GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) :
m_bOpen(bOpen),
m_lpofn(lpofn),
m_bRet(false),
m_ExtErr(0)
{}
bool m_bOpen;
LPOPENFILENAME m_lpofn;
bool m_bRet;
int m_ExtErr;
};
//-----------------------------------------------
//
//-----------------------------------------------
unsigned __stdcall ThreadProc(void* pParam)
{
CurDirGuard aGuard;
GetFileNameParam* lpgfnp =
reinterpret_cast<GetFileNameParam*>(pParam);
HRESULT hr = OleInitialize( NULL );
if (lpgfnp->m_bOpen)
lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn);
else
lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn);
lpgfnp->m_ExtErr = CommDlgExtendedError();
if ( SUCCEEDED( hr ) )
OleUninitialize();
return 0;
}
//-----------------------------------------------
// exceutes GetOpenFileName/GetSaveFileName in
// a separat thread
//-----------------------------------------------
bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, /*out*/ int& ExtErr)
{
GetFileNameParam gfnp(bOpen,lpofn);
unsigned id;
HANDLE hThread = reinterpret_cast<HANDLE>(
_beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id));
OSL_POSTCOND(hThread, "could not create STA thread");
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
ExtErr = gfnp.m_ExtErr;
return gfnp.m_bRet;
}
//-----------------------------------------------
// This function returns true if the calling
// thread belongs to a Multithreaded Appartment
// (MTA)
//-----------------------------------------------
bool IsMTA()
{
HRESULT hr = CoInitialize(NULL);
if (RPC_E_CHANGED_MODE == hr)
return true;
if(SUCCEEDED(hr))
CoUninitialize();
return false;
}
} // namespace private
//-----------------------------------------------
//
//-----------------------------------------------
CGetFileNameWrapper::CGetFileNameWrapper() :
m_ExtendedDialogError(0)
{
}
//-----------------------------------------------
//
//-----------------------------------------------
bool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn)
{
OSL_PRECOND(lpofn,"invalid parameter");
bool bRet = false;
if (IsMTA())
{
bRet = ThreadExecGetFileName(
lpofn, true, m_ExtendedDialogError);
}
else
{
CurDirGuard aGuard;
HRESULT hr = OleInitialize( NULL );
bRet = GetOpenFileName(lpofn);
m_ExtendedDialogError = CommDlgExtendedError();
if ( SUCCEEDED( hr ) )
OleUninitialize();
}
return bRet;
}
//-----------------------------------------------
//
//-----------------------------------------------
bool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn)
{
OSL_PRECOND(lpofn,"invalid parameter");
bool bRet = false;
if (IsMTA())
{
bRet = ThreadExecGetFileName(
lpofn, false, m_ExtendedDialogError);
}
else
{
CurDirGuard aGuard;
bRet = GetSaveFileName(lpofn);
m_ExtendedDialogError = CommDlgExtendedError();
}
return bRet;
}
//-----------------------------------------------
//
//-----------------------------------------------
int CGetFileNameWrapper::commDlgExtendedError( )
{
return m_ExtendedDialogError;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <stdio.h>
#include <osl/diagnose.h>
#include "getfilenamewrapper.hxx"
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <objbase.h>
#include <process.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
namespace /* private */
{
//-----------------------------------------------
// This class prevents changing of the working
// directory.
//-----------------------------------------------
class CurDirGuard
{
sal_Bool m_bValid;
wchar_t* m_pBuffer;
DWORD m_nBufLen;
public:
CurDirGuard()
: m_bValid( sal_False )
, m_pBuffer( NULL )
, m_nBufLen( 0 )
{
m_nBufLen = GetCurrentDirectoryW( 0, NULL );
if ( m_nBufLen )
{
m_pBuffer = new wchar_t[m_nBufLen];
m_bValid = ( GetCurrentDirectoryW( m_nBufLen, m_pBuffer ) == ( m_nBufLen - 1 ) );
}
}
~CurDirGuard()
{
bool bDirSet = false;
if ( m_pBuffer )
{
if ( m_bValid )
{
if ( m_nBufLen - 1 > MAX_PATH )
{
DWORD nNewLen = m_nBufLen + 8;
wchar_t* pNewBuffer = new wchar_t[nNewLen];
if ( m_nBufLen > 3 && m_pBuffer[0] == (wchar_t)'\\' && m_pBuffer[1] == (wchar_t)'\\' )
{
if ( m_pBuffer[2] == (wchar_t)'?' )
_snwprintf( pNewBuffer, nNewLen, L"%s", m_pBuffer );
else
_snwprintf( pNewBuffer, nNewLen, L"\\\\?\\UNC\\%s", m_pBuffer+2 );
}
else
_snwprintf( pNewBuffer, nNewLen, L"\\\\?\\%s", m_pBuffer );
bDirSet = SetCurrentDirectoryW( pNewBuffer );
delete [] pNewBuffer;
}
else
bDirSet = SetCurrentDirectoryW( m_pBuffer );
}
delete [] m_pBuffer;
m_pBuffer = NULL;
}
if ( !bDirSet )
{
// the fallback solution
wchar_t pPath[MAX_PATH+1];
if ( GetWindowsDirectoryW( pPath, MAX_PATH+1 ) <= MAX_PATH )
{
SetCurrentDirectoryW( pPath );
}
else
{
// the system path is also too long?!!
}
}
}
};
//-----------------------------------------------
//
//-----------------------------------------------
struct GetFileNameParam
{
GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) :
m_bOpen(bOpen),
m_lpofn(lpofn),
m_bRet(false),
m_ExtErr(0)
{}
bool m_bOpen;
LPOPENFILENAME m_lpofn;
bool m_bRet;
int m_ExtErr;
};
//-----------------------------------------------
//
//-----------------------------------------------
unsigned __stdcall ThreadProc(void* pParam)
{
CurDirGuard aGuard;
GetFileNameParam* lpgfnp =
reinterpret_cast<GetFileNameParam*>(pParam);
HRESULT hr = OleInitialize( NULL );
if (lpgfnp->m_bOpen)
lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn);
else
lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn);
lpgfnp->m_ExtErr = CommDlgExtendedError();
if ( SUCCEEDED( hr ) )
OleUninitialize();
return 0;
}
//-----------------------------------------------
// exceutes GetOpenFileName/GetSaveFileName in
// a separat thread
//-----------------------------------------------
bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, /*out*/ int& ExtErr)
{
GetFileNameParam gfnp(bOpen,lpofn);
unsigned id;
HANDLE hThread = reinterpret_cast<HANDLE>(
_beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id));
OSL_POSTCOND(hThread, "could not create STA thread");
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
ExtErr = gfnp.m_ExtErr;
return gfnp.m_bRet;
}
//-----------------------------------------------
// This function returns true if the calling
// thread belongs to a Multithreaded Appartment
// (MTA)
//-----------------------------------------------
bool IsMTA()
{
HRESULT hr = CoInitialize(NULL);
if (RPC_E_CHANGED_MODE == hr)
return true;
if(SUCCEEDED(hr))
CoUninitialize();
return false;
}
} // namespace private
//-----------------------------------------------
//
//-----------------------------------------------
CGetFileNameWrapper::CGetFileNameWrapper() :
m_ExtendedDialogError(0)
{
}
//-----------------------------------------------
//
//-----------------------------------------------
bool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn)
{
OSL_PRECOND(lpofn,"invalid parameter");
bool bRet = false;
if (IsMTA())
{
bRet = ThreadExecGetFileName(
lpofn, true, m_ExtendedDialogError);
}
else
{
CurDirGuard aGuard;
HRESULT hr = OleInitialize( NULL );
bRet = GetOpenFileName(lpofn);
m_ExtendedDialogError = CommDlgExtendedError();
if ( SUCCEEDED( hr ) )
OleUninitialize();
}
return bRet;
}
//-----------------------------------------------
//
//-----------------------------------------------
bool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn)
{
OSL_PRECOND(lpofn,"invalid parameter");
bool bRet = false;
if (IsMTA())
{
bRet = ThreadExecGetFileName(
lpofn, false, m_ExtendedDialogError);
}
else
{
CurDirGuard aGuard;
bRet = GetSaveFileName(lpofn);
m_ExtendedDialogError = CommDlgExtendedError();
}
return bRet;
}
//-----------------------------------------------
//
//-----------------------------------------------
int CGetFileNameWrapper::commDlgExtendedError( )
{
return m_ExtendedDialogError;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Drop Win9x code
|
Drop Win9x code
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
47366dbec4881c7be642b2c9790c81ccea79ca65
|
marketorderswidget.cpp
|
marketorderswidget.cpp
|
#include "marketorderswidget.hpp"
#include "ui_marketorderswidget.h"
#include <QSqlQuery>
#include <QListIterator>
#include <QPushButton>
#include <QTableWidget>
#include <QtXmlPatterns>
#include <QMovie>
#include "network.hpp"
#include "queries.hpp"
#include "settings.hpp"
#include "global.hpp"
MarketOrdersWidget::MarketOrdersWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MarketOrdersWidget)
{
ui->setupUi(this);
for (QListIterator<MarketOrdersTable*> i({ui->sellOrdersTable, ui->buyOrdersTable}); i.hasNext();) {
MarketOrdersTable* table = i.next();
table->setColumnCount(4);
table->setHorizontalHeaderLabels({tr("Station"), tr("Price"), tr("Quantity"), tr("Reported Time")});
table->verticalHeader()->hide();
table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
}
refreshOrStopButton = new QPushButton();
setButtonState(RefreshState);
ui->tabs->setCornerWidget(refreshOrStopButton);
refreshOrStopButton->hide();
typeId = -1;
connect(ui->typePixmapLabel, SIGNAL(typeDropped(int)),
this, SLOT(typeDropped(int)));
connect(refreshOrStopButton, SIGNAL(clicked()),
this, SLOT(refreshOrStop()));
}
MarketOrdersWidget::~MarketOrdersWidget()
{
delete ui;
}
void MarketOrdersWidget::typeDropped(int typeId)
{
this->typeId = typeId;
QSqlQuery* typeNameQuery = Queries::getTypeNameQuery();
typeNameQuery->bindValue(":id", typeId);
typeNameQuery->exec();
typeNameQuery->next();
QString typeName = typeNameQuery->value(0).toString();
ui->typeNameLabel->setText(QString("<h2>%1</h2>").arg(typeName));
ui->infoButton->init(typeId);
reply = Network::getOrders(typeId, Settings::getMarketOrdersTimeLimitSetting());
refreshOrStopButton->show();
setButtonState(StopState);
connect(reply, SIGNAL(finished()),
this, SLOT(replyFinished()));
}
void MarketOrdersWidget::replyFinished()
{
QString xmlString = reply->readAll();
reply->deleteLater();
clearTable(ui->sellOrdersTable);
clearTable(ui->buyOrdersTable);
parseReply(xmlString);
setButtonState(RefreshState);
}
void MarketOrdersWidget::parseReply(const QString& xmlString)
{
parseReplyForTable(xmlString, ui->sellOrdersTable, "sell_orders");
parseReplyForTable(xmlString, ui->buyOrdersTable, "buy_orders");
}
void MarketOrdersWidget::parseReplyForTable(const QString& xmlString, QTableWidget* table, const QString& tagName)
{
QXmlQuery query;
query.setFocus(xmlString);
query.setQuery(QString("for $x in //%1/order \n"
"return fn:concat($x/station/text(), \"/\","
" $x/price/text(), \"/\","
" $x/vol_remain/text(), \"/\","
" $x/reported_time/text())").arg(tagName));
QStringList strlist;
query.evaluateTo(&strlist);
for (int i = 0; i < strlist.size(); i++) {
QStringList splitted = strlist[i].split("/");
addTableRow(table, splitted[0].toInt(), splitted[1].toDouble(),
splitted[2].toInt(), splitted[3]);
}
}
void MarketOrdersWidget::addTableRow(QTableWidget* table, int stationId, double price,
int quantity, QString reportedTime)
{
QLocale locale(QLocale::English);
int rowId = table->rowCount();
table->insertRow(rowId);
QSqlQuery* stationNameQuery = Queries::getStationNameQuery();
stationNameQuery->bindValue(":id", stationId);
stationNameQuery->exec();
stationNameQuery->next();
table->setItem(rowId, 0, new QTableWidgetItem(stationNameQuery->value(0).toString()));
table->setItem(rowId, 1, new QTableWidgetItem(locale.toString(price, 'f', 2)));
table->setItem(rowId, 2, new QTableWidgetItem(locale.toString(quantity)));
table->setItem(rowId, 3, new QTableWidgetItem(reportedTime));
for (QListIterator<int> i(QList<int>({1, 2, 3})); i.hasNext();)
table->item(rowId, i.next())->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
}
void MarketOrdersWidget::clearTable(QTableWidget* table)
{
while (table->rowCount())
table->removeRow(0);
}
void MarketOrdersWidget::setButtonState(MarketOrdersWidget::ButtonState state)
{
buttonState = state;
switch (state) {
case RefreshState:
refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_11")));
break;
case StopState:
refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_45")));
break;
}
}
void MarketOrdersWidget::refreshOrStop()
{
switch (buttonState) {
case RefreshState:
refresh();
break;
case StopState:
stop();
break;
}
}
void MarketOrdersWidget::refresh()
{
typeDropped(typeId);
}
void MarketOrdersWidget::stop()
{
reply->deleteLater();
setButtonState(RefreshState);
}
|
#include "marketorderswidget.hpp"
#include "ui_marketorderswidget.h"
#include <QSqlQuery>
#include <QListIterator>
#include <QPushButton>
#include <QTableWidget>
#include <QtXmlPatterns>
#include <QMovie>
#include "network.hpp"
#include "queries.hpp"
#include "settings.hpp"
#include "global.hpp"
MarketOrdersWidget::MarketOrdersWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MarketOrdersWidget)
{
ui->setupUi(this);
for (QListIterator<MarketOrdersTable*> i({ui->sellOrdersTable, ui->buyOrdersTable}); i.hasNext();) {
MarketOrdersTable* table = i.next();
table->setColumnCount(4);
table->setHorizontalHeaderLabels({tr("Station"), tr("Price"), tr("Quantity"), tr("Reported Time")});
table->verticalHeader()->hide();
table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
}
refreshOrStopButton = new QPushButton();
setButtonState(RefreshState);
ui->tabs->setCornerWidget(refreshOrStopButton);
refreshOrStopButton->hide();
typeId = -1;
connect(ui->typePixmapLabel, SIGNAL(typeDropped(int)),
this, SLOT(typeDropped(int)));
connect(refreshOrStopButton, SIGNAL(clicked()),
this, SLOT(refreshOrStop()));
}
MarketOrdersWidget::~MarketOrdersWidget()
{
delete ui;
}
void MarketOrdersWidget::typeDropped(int typeId)
{
this->typeId = typeId;
QSqlQuery* typeNameQuery = Queries::getTypeNameQuery();
typeNameQuery->bindValue(":id", typeId);
typeNameQuery->exec();
typeNameQuery->next();
QString typeName = typeNameQuery->value(0).toString();
ui->typeNameLabel->setText(QString("<h2>%1</h2>").arg(typeName));
ui->infoButton->init(typeId);
reply = Network::getOrders(typeId, Settings::getMarketOrdersTimeLimitSetting());
refreshOrStopButton->show();
setButtonState(StopState);
connect(reply, SIGNAL(finished()),
this, SLOT(replyFinished()));
}
void MarketOrdersWidget::replyFinished()
{
QString xmlString = reply->readAll();
reply->deleteLater();
clearTable(ui->sellOrdersTable);
clearTable(ui->buyOrdersTable);
parseReply(xmlString);
setButtonState(RefreshState);
}
void MarketOrdersWidget::parseReply(const QString& xmlString)
{
parseReplyForTable(xmlString, ui->sellOrdersTable, "sell_orders");
parseReplyForTable(xmlString, ui->buyOrdersTable, "buy_orders");
}
void MarketOrdersWidget::parseReplyForTable(const QString& xmlString, QTableWidget* table, const QString& tagName)
{
QXmlQuery query;
query.setFocus(xmlString);
query.setQuery(QString("for $x in //%1/order \n"
"return fn:concat($x/station/text(), \"/\","
" $x/price/text(), \"/\","
" $x/vol_remain/text(), \"/\","
" $x/reported_time/text())").arg(tagName));
QStringList strlist;
query.evaluateTo(&strlist);
for (int i = 0; i < strlist.size(); i++) {
QStringList splitted = strlist[i].split("/");
int dotIndex = splitted[3].indexOf(".");
addTableRow(table, splitted[0].toInt(), splitted[1].toDouble(),
splitted[2].toInt(), splitted[3].left(dotIndex));
}
}
void MarketOrdersWidget::addTableRow(QTableWidget* table, int stationId, double price,
int quantity, QString reportedTime)
{
QLocale locale(QLocale::English);
int rowId = table->rowCount();
table->insertRow(rowId);
QSqlQuery* stationNameQuery = Queries::getStationNameQuery();
stationNameQuery->bindValue(":id", stationId);
stationNameQuery->exec();
stationNameQuery->next();
table->setItem(rowId, 0, new QTableWidgetItem(stationNameQuery->value(0).toString()));
table->setItem(rowId, 1, new QTableWidgetItem(locale.toString(price, 'f', 2)));
table->setItem(rowId, 2, new QTableWidgetItem(locale.toString(quantity)));
table->setItem(rowId, 3, new QTableWidgetItem(reportedTime));
for (QListIterator<int> i(QList<int>({1, 2, 3})); i.hasNext();)
table->item(rowId, i.next())->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
}
void MarketOrdersWidget::clearTable(QTableWidget* table)
{
while (table->rowCount())
table->removeRow(0);
}
void MarketOrdersWidget::setButtonState(MarketOrdersWidget::ButtonState state)
{
buttonState = state;
switch (state) {
case RefreshState:
refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_11")));
break;
case StopState:
refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_45")));
break;
}
}
void MarketOrdersWidget::refreshOrStop()
{
switch (buttonState) {
case RefreshState:
refresh();
break;
case StopState:
stop();
break;
}
}
void MarketOrdersWidget::refresh()
{
typeDropped(typeId);
}
void MarketOrdersWidget::stop()
{
reply->deleteLater();
setButtonState(RefreshState);
}
|
Discard the fraction part in reported time of MarketOrdersWidget.
|
Discard the fraction part in reported time of MarketOrdersWidget.
|
C++
|
lgpl-2.1
|
yznpku/bevel
|
e26da2b7e1e4f5b3267f2f7db06d9c6618aef66d
|
cli/demos/cpp/main.cpp
|
cli/demos/cpp/main.cpp
|
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <vector>
#include <math.h>
const double PI = 3.14159265;
int main() {
using namespace std;
//Version check I/O
char protocol_version_string[32];
int version;
cin >> protocol_version_string;
cin >> version;
if (version == 1) {
cout << "COMPATIBLE 1" << endl;
}
else {
cout << "NOT_COMPATIBLE 1" << endl;
}
//Geometry input
float field_length;
float field_width;
float goal_width;
float center_circle_radius;
float defense_radius;
float defense_stretch;
float free_kick_from_defense_distance;
float penalty_spot_from_field_line_dist;
float penalty_line_from_spot_dist;
cin >> field_length
>> field_width
>> goal_width
>> center_circle_radius
>> defense_radius
>> defense_stretch
>> free_kick_from_defense_distance
>> penalty_spot_from_field_line_dist
>> penalty_line_from_spot_dist;
//Game state I/O
int counter;
float timestamp;
char referee_state;
float referee_time_left;
int score_player;
int score_opponent;
int goalkeeper_id_player;
int goalkeeper_id_opponent;
int robot_num_player;
int robot_num_opponent;
float ball_x, ball_y, ball_vx, ball_vy;
while (true) {
// State
vector<int> identifiers;
float x = 0.0f, y = 0.0f, w = 0.0f;
float tx = 0.0f, ty = 0.0f, tw = 0.0f;
// Input
cin >> counter
>> timestamp
>> referee_state >> referee_time_left
>> score_player >> score_opponent
>> goalkeeper_id_player
>> goalkeeper_id_opponent
>> robot_num_player
>> robot_num_opponent;
cin >> ball_x >> ball_y >> ball_vx >> ball_vy;
for (int i = 0; i < robot_num_player; ++i) {
int robot_id;
float robot_x, robot_y, robot_w, robot_vx, robot_vy, robot_vw;
cin >> robot_id >> robot_x >> robot_y >> robot_w >> robot_vx >> robot_vy >> robot_vw;
identifiers.push_back(robot_id);
if (robot_id == 0) {
x = robot_x;
y = robot_y;
w = robot_w;
}
}
for (int i = 0; i < robot_num_opponent; ++i) {
int robot_id;
float robot_x, robot_y, robot_w, robot_vx, robot_vy, robot_vw;
cin >> robot_id >> robot_x >> robot_y >> robot_w >> robot_vx >> robot_vy >> robot_vw;
}
tx = ball_x;
ty = ball_y;
tw = 0;
cout << counter << endl;
const float p_t = 0.4f;
const float p_w = 0.8000f;
for (int i = 0; i < identifiers.size() ; ++i) {
if (identifiers.at(i) == 0) {
const float v_tan = p_t * ((tx - x) * cos(w * PI/180.0) + (ty - y) * sin(w * PI / 180.0));
const float v_norm = p_t * ((ty - y) * cos(w * PI/180.0) + (tx - x) * sin(w * PI / 180.0));
const float v_ang = p_w*(tw-w);
const float kick_x = 4.0f;
const float kick_z = 0.0f;
const bool spin = true;
cout << v_tan << " " << v_norm << " " << v_ang << " " << kick_x << " " << kick_z << " " << spin << endl;
} else {
const float v_tan = 0.0f;
const float v_norm = 0.0f;
const float v_ang = 0.0f;
const float kick_x = 0.0f;
const float kick_z = 0.0f;
const bool spin = false;
cout << v_tan << " " << v_norm << " " << v_ang << " " << kick_x << " " << kick_z << " " << spin << endl;
}
}
}
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
int main() {
using namespace std;
cerr << "started" << endl;
// Version check I/O
char protocol_version_string[32];
int version;
cin >> protocol_version_string;
cin >> version;
if (version == 1) {
cout << "COMPATIBLE 1" << endl;
} else {
cout << "NOT_COMPATIBLE 1" << endl;
}
cerr << "compatible" << endl;
// Geometry input
float field_length;
float field_width;
float goal_width;
float center_circle_radius;
float defense_radius;
float defense_stretch;
float free_kick_from_defense_distance;
float penalty_spot_from_field_line_dist;
float penalty_line_from_spot_dist;
cin >> field_length
>> field_width
>> goal_width
>> center_circle_radius
>> defense_radius
>> defense_stretch
>> free_kick_from_defense_distance
>> penalty_spot_from_field_line_dist
>> penalty_line_from_spot_dist;
cerr << "initialized" << endl;
// Game state I/O
while (true) {
// State
vector<int> identifiers;
float x = 0.0f, y = 0.0f, w = 0.0f;
float tx = 0.0f, ty = 0.0f, tw = 0.0f;
// Input
int counter;
float timestamp;
char referee_state;
float referee_time_left;
int score_player;
int score_opponent;
int goalkeeper_id_player;
int goalkeeper_id_opponent;
int robot_num_player;
int robot_num_opponent;
float ball_x, ball_y, ball_vx, ball_vy;
cin >> counter
>> timestamp
>> referee_state >> referee_time_left
>> score_player >> score_opponent
>> goalkeeper_id_player
>> goalkeeper_id_opponent
>> robot_num_player
>> robot_num_opponent;
cin >> ball_x >> ball_y >> ball_vx >> ball_vy;
for (int i = 0; i < robot_num_player; ++i) {
int robot_id;
float robot_x, robot_y, robot_w, robot_vx, robot_vy, robot_vw;
cin >> robot_id >> robot_x >> robot_y >> robot_w >> robot_vx >> robot_vy >> robot_vw;
identifiers.push_back(robot_id);
if (robot_id == 0) {
x = robot_x;
y = robot_y;
w = robot_w;
}
}
for (int i = 0; i < robot_num_opponent; ++i) {
int robot_id;
float robot_x, robot_y, robot_w, robot_vx, robot_vy, robot_vw;
cin >> robot_id >> robot_x >> robot_y >> robot_w >> robot_vx >> robot_vy >> robot_vw;
}
tx = ball_x;
ty = ball_y;
tw = 0;
cout << counter << endl;
const float p_t = 0.40f;
const float p_w = 0.80f;
for (int i = 0; i < identifiers.size() ; ++i) {
float v_tan, v_norm, v_ang, kick_x, kick_z;
bool spin;
if (identifiers.at(i) == 0) {
v_tan = p_t * ((tx - x) * cos(w) + (ty - y) * sin(w));
v_norm = p_t * ((ty - y) * cos(w) + (tx - x) * sin(w));
v_ang = p_w * (tw - w);
kick_x = 4.0f;
kick_z = 0.0f;
spin = true;
} else {
v_tan = 0.0f;
v_norm = 0.0f;
v_ang = 0.0f;
kick_x = 0.0f;
kick_z = 0.0f;
spin = false;
}
cout << v_tan << " " << v_norm << " " << v_ang << " " << kick_x << " " << kick_z << " " << spin << endl;
}
}
}
|
Refactor cpp demo.
|
Refactor cpp demo.
|
C++
|
mpl-2.0
|
roboime/roboime-next
|
9f777de1a92274ea2955bc714321582da6699116
|
chrome/browser/device_orientation/provider_unittest.cc
|
chrome/browser/device_orientation/provider_unittest.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <queue>
#include "base/lock.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "chrome/browser/device_orientation/data_fetcher.h"
#include "chrome/browser/device_orientation/orientation.h"
#include "chrome/browser/device_orientation/provider.h"
#include "chrome/browser/device_orientation/provider_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace device_orientation {
namespace {
// Class for checking expectations on orientation updates from the Provider.
class UpdateChecker : public Provider::Observer {
public:
explicit UpdateChecker(int* expectations_count_ptr)
: expectations_count_ptr_(expectations_count_ptr) {
}
// From Provider::Observer.
virtual void OnOrientationUpdate(const Orientation& orientation) {
ASSERT_FALSE(expectations_queue_.empty());
Orientation expected = expectations_queue_.front();
expectations_queue_.pop();
EXPECT_EQ(expected.can_provide_alpha_, orientation.can_provide_alpha_);
EXPECT_EQ(expected.can_provide_beta_, orientation.can_provide_beta_);
EXPECT_EQ(expected.can_provide_gamma_, orientation.can_provide_gamma_);
if (expected.can_provide_alpha_)
EXPECT_EQ(expected.alpha_, orientation.alpha_);
if (expected.can_provide_beta_)
EXPECT_EQ(expected.beta_, orientation.beta_);
if (expected.can_provide_gamma_)
EXPECT_EQ(expected.gamma_, orientation.gamma_);
--(*expectations_count_ptr_);
if (*expectations_count_ptr_ == 0) {
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
}
void AddExpectation(const Orientation& orientation) {
expectations_queue_.push(orientation);
++(*expectations_count_ptr_);
}
private:
// Set up by the test fixture, which then blocks while it is accessed
// from OnOrientationUpdate which is executed on the test fixture's
// message_loop_.
int* expectations_count_ptr_;
std::queue<Orientation> expectations_queue_;
};
// Class for injecting test orientation data into the Provider.
class MockOrientationFactory : public base::RefCounted<MockOrientationFactory> {
public:
MockOrientationFactory() {
EXPECT_FALSE(instance_);
instance_ = this;
}
~MockOrientationFactory() {
instance_ = NULL;
}
static DataFetcher* CreateDataFetcher() {
EXPECT_TRUE(instance_);
return new MockDataFetcher(instance_);
}
void SetOrientation(const Orientation& orientation) {
AutoLock auto_lock(lock_);
orientation_ = orientation;
}
private:
// Owned by ProviderImpl. Holds a reference back to MockOrientationFactory.
class MockDataFetcher : public DataFetcher {
public:
explicit MockDataFetcher(MockOrientationFactory* orientation_factory)
: orientation_factory_(orientation_factory) { }
// From DataFetcher. Called by the Provider.
virtual bool GetOrientation(Orientation* orientation) {
AutoLock auto_lock(orientation_factory_->lock_);
*orientation = orientation_factory_->orientation_;
return true;
}
private:
scoped_refptr<MockOrientationFactory> orientation_factory_;
};
static MockOrientationFactory* instance_;
Orientation orientation_;
Lock lock_;
};
MockOrientationFactory* MockOrientationFactory::instance_;
// Mock DataFetcher that always fails to provide any orientation data.
class FailingDataFetcher : public DataFetcher {
public:
// Factory method; passed to and called by the ProviderImpl.
static DataFetcher* Create() {
return new FailingDataFetcher();
}
// From DataFetcher.
virtual bool GetOrientation(Orientation* orientation) {
return false;
}
private:
FailingDataFetcher() {}
};
class DeviceOrientationProviderTest : public testing::Test {
public:
DeviceOrientationProviderTest()
: pending_expectations_(0) {
}
virtual void TearDown() {
provider_ = NULL;
// Make sure it is really gone.
EXPECT_FALSE(Provider::GetInstanceForTests());
// Clean up in any case, so as to not break subsequent test.
Provider::SetInstanceForTests(NULL);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactories in the null-terminated factories array.
void Init(ProviderImpl::DataFetcherFactory* factories) {
provider_ = new ProviderImpl(factories);
Provider::SetInstanceForTests(provider_);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactory factory.
void Init(ProviderImpl::DataFetcherFactory factory) {
ProviderImpl::DataFetcherFactory factories[] = { factory, NULL };
Init(factories);
}
protected:
// Number of pending expectations.
int pending_expectations_;
// Provider instance under test.
scoped_refptr<Provider> provider_;
// Message loop for the test thread.
MessageLoop message_loop_;
};
TEST_F(DeviceOrientationProviderTest, FailingTest) {
Init(FailingDataFetcher::Create);
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
}
TEST_F(DeviceOrientationProviderTest, ProviderIsSingleton) {
Init(FailingDataFetcher::Create);
scoped_refptr<Provider> provider_a(Provider::GetInstance());
scoped_refptr<Provider> provider_b(Provider::GetInstance());
EXPECT_EQ(provider_a.get(), provider_b.get());
}
TEST_F(DeviceOrientationProviderTest, BasicPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker.get());
}
TEST_F(DeviceOrientationProviderTest, MultipleObserversPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientations[] = {
Orientation(true, 1, true, 2, true, 3),
Orientation(true, 4, true, 5, true, 6),
Orientation(true, 7, true, 8, true, 9)};
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_c(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(kTestOrientations[0]);
orientation_factory->SetOrientation(kTestOrientations[0]);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(kTestOrientations[1]);
checker_b->AddExpectation(kTestOrientations[0]);
checker_b->AddExpectation(kTestOrientations[1]);
orientation_factory->SetOrientation(kTestOrientations[1]);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
checker_b->AddExpectation(kTestOrientations[2]);
checker_c->AddExpectation(kTestOrientations[1]);
checker_c->AddExpectation(kTestOrientations[2]);
orientation_factory->SetOrientation(kTestOrientations[2]);
provider_->AddObserver(checker_c.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
provider_->RemoveObserver(checker_c.get());
}
TEST_F(DeviceOrientationProviderTest, ObserverNotRemoved) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
// Note that checker is not removed. This should not be a problem.
}
TEST_F(DeviceOrientationProviderTest, StartFailing) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(kTestOrientation);
checker_a->AddExpectation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(Orientation::Empty());
orientation_factory->SetOrientation(Orientation::Empty());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, StartStopStart) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
checker_a->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get()); // This stops the Provider.
checker_b->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, SignificantlyDifferent) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
// Values that should be well below or above the implementation's
// significane threshold.
const double kInsignificantDifference = 1e-6;
const double kSignificantDifference = 30;
const double kAlpha = 4, kBeta = 5, kGamma = 6;
const Orientation first_orientation(true, kAlpha, true, kBeta, true, kGamma);
const Orientation second_orientation(true, kAlpha + kInsignificantDifference,
true, kBeta + kInsignificantDifference,
true, kGamma + kInsignificantDifference);
const Orientation third_orientation(true, kAlpha + kSignificantDifference,
true, kBeta + kSignificantDifference,
true, kGamma + kSignificantDifference);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(first_orientation);
checker_a->AddExpectation(first_orientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
// The observers should not see this insignificantly different orientation.
orientation_factory->SetOrientation(second_orientation);
checker_b->AddExpectation(first_orientation);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
orientation_factory->SetOrientation(third_orientation);
checker_a->AddExpectation(third_orientation);
checker_b->AddExpectation(third_orientation);
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
} // namespace
} // namespace device_orientation
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <queue>
#include "base/lock.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "chrome/browser/device_orientation/data_fetcher.h"
#include "chrome/browser/device_orientation/orientation.h"
#include "chrome/browser/device_orientation/provider.h"
#include "chrome/browser/device_orientation/provider_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace device_orientation {
namespace {
// Class for checking expectations on orientation updates from the Provider.
class UpdateChecker : public Provider::Observer {
public:
explicit UpdateChecker(int* expectations_count_ptr)
: expectations_count_ptr_(expectations_count_ptr) {
}
// From Provider::Observer.
virtual void OnOrientationUpdate(const Orientation& orientation) {
ASSERT_FALSE(expectations_queue_.empty());
Orientation expected = expectations_queue_.front();
expectations_queue_.pop();
EXPECT_EQ(expected.can_provide_alpha_, orientation.can_provide_alpha_);
EXPECT_EQ(expected.can_provide_beta_, orientation.can_provide_beta_);
EXPECT_EQ(expected.can_provide_gamma_, orientation.can_provide_gamma_);
if (expected.can_provide_alpha_)
EXPECT_EQ(expected.alpha_, orientation.alpha_);
if (expected.can_provide_beta_)
EXPECT_EQ(expected.beta_, orientation.beta_);
if (expected.can_provide_gamma_)
EXPECT_EQ(expected.gamma_, orientation.gamma_);
--(*expectations_count_ptr_);
if (*expectations_count_ptr_ == 0) {
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
}
void AddExpectation(const Orientation& orientation) {
expectations_queue_.push(orientation);
++(*expectations_count_ptr_);
}
private:
// Set up by the test fixture, which then blocks while it is accessed
// from OnOrientationUpdate which is executed on the test fixture's
// message_loop_.
int* expectations_count_ptr_;
std::queue<Orientation> expectations_queue_;
};
// Class for injecting test orientation data into the Provider.
class MockOrientationFactory : public base::RefCounted<MockOrientationFactory> {
public:
MockOrientationFactory() {
EXPECT_FALSE(instance_);
instance_ = this;
}
~MockOrientationFactory() {
instance_ = NULL;
}
static DataFetcher* CreateDataFetcher() {
EXPECT_TRUE(instance_);
return new MockDataFetcher(instance_);
}
void SetOrientation(const Orientation& orientation) {
AutoLock auto_lock(lock_);
orientation_ = orientation;
}
private:
// Owned by ProviderImpl. Holds a reference back to MockOrientationFactory.
class MockDataFetcher : public DataFetcher {
public:
explicit MockDataFetcher(MockOrientationFactory* orientation_factory)
: orientation_factory_(orientation_factory) { }
// From DataFetcher. Called by the Provider.
virtual bool GetOrientation(Orientation* orientation) {
AutoLock auto_lock(orientation_factory_->lock_);
*orientation = orientation_factory_->orientation_;
return true;
}
private:
scoped_refptr<MockOrientationFactory> orientation_factory_;
};
static MockOrientationFactory* instance_;
Orientation orientation_;
Lock lock_;
};
MockOrientationFactory* MockOrientationFactory::instance_;
// Mock DataFetcher that always fails to provide any orientation data.
class FailingDataFetcher : public DataFetcher {
public:
// Factory method; passed to and called by the ProviderImpl.
static DataFetcher* Create() {
return new FailingDataFetcher();
}
// From DataFetcher.
virtual bool GetOrientation(Orientation* orientation) {
return false;
}
private:
FailingDataFetcher() {}
};
class DeviceOrientationProviderTest : public testing::Test {
public:
DeviceOrientationProviderTest()
: pending_expectations_(0) {
}
virtual void TearDown() {
provider_ = NULL;
// Make sure it is really gone.
EXPECT_FALSE(Provider::GetInstanceForTests());
// Clean up in any case, so as to not break subsequent test.
Provider::SetInstanceForTests(NULL);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactories in the null-terminated factories array.
void Init(ProviderImpl::DataFetcherFactory* factories) {
provider_ = new ProviderImpl(factories);
Provider::SetInstanceForTests(provider_);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactory factory.
void Init(ProviderImpl::DataFetcherFactory factory) {
ProviderImpl::DataFetcherFactory factories[] = { factory, NULL };
Init(factories);
}
protected:
// Number of pending expectations.
int pending_expectations_;
// Provider instance under test.
scoped_refptr<Provider> provider_;
// Message loop for the test thread.
MessageLoop message_loop_;
};
TEST_F(DeviceOrientationProviderTest, FailingTest) {
Init(FailingDataFetcher::Create);
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
}
TEST_F(DeviceOrientationProviderTest, ProviderIsSingleton) {
Init(FailingDataFetcher::Create);
scoped_refptr<Provider> provider_a(Provider::GetInstance());
scoped_refptr<Provider> provider_b(Provider::GetInstance());
EXPECT_EQ(provider_a.get(), provider_b.get());
}
TEST_F(DeviceOrientationProviderTest, BasicPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker.get());
}
TEST_F(DeviceOrientationProviderTest, MultipleObserversPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientations[] = {
Orientation(true, 1, true, 2, true, 3),
Orientation(true, 4, true, 5, true, 6),
Orientation(true, 7, true, 8, true, 9)};
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_c(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(kTestOrientations[0]);
orientation_factory->SetOrientation(kTestOrientations[0]);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(kTestOrientations[1]);
checker_b->AddExpectation(kTestOrientations[0]);
checker_b->AddExpectation(kTestOrientations[1]);
orientation_factory->SetOrientation(kTestOrientations[1]);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
checker_b->AddExpectation(kTestOrientations[2]);
checker_c->AddExpectation(kTestOrientations[1]);
checker_c->AddExpectation(kTestOrientations[2]);
orientation_factory->SetOrientation(kTestOrientations[2]);
provider_->AddObserver(checker_c.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
provider_->RemoveObserver(checker_c.get());
}
TEST_F(DeviceOrientationProviderTest, ObserverNotRemoved) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
checker->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
MessageLoop::current()->Run();
// Note that checker is not removed. This should not be a problem.
}
TEST_F(DeviceOrientationProviderTest, StartFailing) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(kTestOrientation);
checker_a->AddExpectation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(Orientation::Empty());
orientation_factory->SetOrientation(Orientation::Empty());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, StartStopStart) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
checker_a->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get()); // This stops the Provider.
checker_b->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, SignificantlyDifferent) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
// Values that should be well below or above the implementation's
// significane threshold.
const double kInsignificantDifference = 1e-6;
const double kSignificantDifference = 30;
const double kAlpha = 4, kBeta = 5, kGamma = 6;
const Orientation first_orientation(true, kAlpha, true, kBeta, true, kGamma);
const Orientation second_orientation(true, kAlpha + kInsignificantDifference,
true, kBeta + kInsignificantDifference,
true, kGamma + kInsignificantDifference);
const Orientation third_orientation(true, kAlpha + kSignificantDifference,
true, kBeta + kSignificantDifference,
true, kGamma + kSignificantDifference);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(first_orientation);
checker_a->AddExpectation(first_orientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
// The observers should not see this insignificantly different orientation.
orientation_factory->SetOrientation(second_orientation);
checker_b->AddExpectation(first_orientation);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
orientation_factory->SetOrientation(third_orientation);
checker_a->AddExpectation(third_orientation);
checker_b->AddExpectation(third_orientation);
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
} // namespace
} // namespace device_orientation
|
Fix DeviceOrientationProviderTest.ObserverNotRemoved.
|
Fix DeviceOrientationProviderTest.ObserverNotRemoved.
The problem was that some extra reference to Provider was left after the
ObserverNotRemoved test had finished. This reference was held by the
RunnableMethod object that executes ProviderImpl::DoInitializePollingThread on
a background thread. In the test, there were no guarantees that the body of
this function would finish before the test ended, thus causing a problem.
Fixing this by pushing another orientation through, forcing the Provider to
execute at least one Poll task on the background thread, which can only happen
after the initialization of the polling thread is done.
BUG=53865
TEST=unit_tests --gtest_filter=DeviceOrientationProviderTest.ObserverNotRemoved
Review URL: http://codereview.chromium.org/3232005
git-svn-id: http://src.chromium.org/svn/trunk/src@58359 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: db290297a1a4d3983e2084b008261af5099bb584
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
bfe3b9e2ec11565e3a1d90133d1a49d1fef1b817
|
chrome/browser/extensions/extension_omnibox_apitest.cc
|
chrome/browser/extensions/extension_omnibox_apitest.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/format_macros.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/common/content_notification_types.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#endif
// Basic test is flaky on ChromeOS.
// http://crbug.com/52929
#if defined(OS_CHROMEOS)
#define MAYBE_Basic FLAKY_Basic
#else
#define MAYBE_Basic Basic
#endif
namespace {
string16 AutocompleteResultAsString(const AutocompleteResult& result) {
std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
for (size_t i = 0; i < result.size(); ++i) {
AutocompleteMatch match = result.match_at(i);
std::string provider_name = match.provider->name();
output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
UTF16ToUTF8(match.contents).c_str(),
provider_name.c_str()));
}
return UTF8ToUTF16(output);
}
} // namespace
class OmniboxApiTest : public ExtensionApiTest {
protected:
LocationBar* GetLocationBar() const {
return browser()->window()->GetLocationBar();
}
AutocompleteController* GetAutocompleteController() const {
return GetLocationBar()->location_entry()->model()->popup_model()->
autocomplete_controller();
}
void WaitForTemplateURLServiceToLoad() {
TemplateURLService* model =
TemplateURLServiceFactory::GetForProfile(browser()->profile());
model->Load();
if (!model->loaded()) {
ui_test_utils::WaitForNotification(
chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED);
}
}
void WaitForAutocompleteDone(AutocompleteController* controller) {
while (!controller->done()) {
ui_test_utils::WaitForNotification(
chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY);
}
}
};
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_Basic) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
// Test that our extension's keyword is suggested to us when we partially type
// it.
{
autocomplete_controller->Start(
ASCIIToUTF16("keywor"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_EQ(string16(), location_bar->GetInputString());
EXPECT_EQ(string16(), location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
// First result should be to search for what was typed, second should be to
// enter "extension keyword" mode.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
match = result.match_at(1);
ASSERT_TRUE(match.template_url);
EXPECT_TRUE(match.template_url->IsExtensionKeyword());
EXPECT_EQ(ASCIIToUTF16("keyword"), match.template_url->keyword());
}
// Test that our extension can send suggestions back to us.
{
autocomplete_controller->Start(
ASCIIToUTF16("keyword suggestio"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
// First result should be to invoke the keyword with what we typed, 2-4
// should be to invoke with suggestions from the extension, and the last
// should be to search for what we typed.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
ASSERT_TRUE(result.match_at(0).template_url);
EXPECT_EQ(ASCIIToUTF16("keyword suggestio"),
result.match_at(0).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion1"),
result.match_at(1).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion2"),
result.match_at(2).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion3"),
result.match_at(3).fill_into_edit);
string16 description =
ASCIIToUTF16("Description with style: <match>, [dim], (url till end)");
EXPECT_EQ(description, result.match_at(1).contents);
ASSERT_EQ(6u, result.match_at(1).contents_class.size());
EXPECT_EQ(0u,
result.match_at(1).contents_class[0].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[0].style);
EXPECT_EQ(description.find('<'),
result.match_at(1).contents_class[1].offset);
EXPECT_EQ(ACMatchClassification::MATCH,
result.match_at(1).contents_class[1].style);
EXPECT_EQ(description.find('>') + 1u,
result.match_at(1).contents_class[2].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[2].style);
EXPECT_EQ(description.find('['),
result.match_at(1).contents_class[3].offset);
EXPECT_EQ(ACMatchClassification::DIM,
result.match_at(1).contents_class[3].style);
EXPECT_EQ(description.find(']') + 1u,
result.match_at(1).contents_class[4].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[4].style);
EXPECT_EQ(description.find('('),
result.match_at(1).contents_class[5].offset);
EXPECT_EQ(ACMatchClassification::URL,
result.match_at(1).contents_class[5].style);
AutocompleteMatch match = result.match_at(4);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
}
{
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
}
// Tests that the autocomplete popup doesn't reopen after accepting input for
// a given query.
// http://crbug.com/88552
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, PopupStaysClosed) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
AutocompletePopupModel* popup_model =
GetLocationBar()->location_entry()->model()->popup_model();
// Input a keyword query and wait for suggestions from the extension.
autocomplete_controller->Start(
ASCIIToUTF16("keyword comman"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(popup_model->IsOpen());
// Quickly type another query and accept it before getting suggestions back
// for the query. The popup will close after accepting input - ensure that it
// does not reopen when the extension returns its suggestions.
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_FALSE(popup_model->IsOpen());
}
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/format_macros.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/common/content_notification_types.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#endif
// Basic test is flaky on ChromeOS.
// http://crbug.com/52929
#if defined(OS_CHROMEOS)
#define MAYBE_Basic FLAKY_Basic
#else
#define MAYBE_Basic Basic
#endif
namespace {
string16 AutocompleteResultAsString(const AutocompleteResult& result) {
std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
for (size_t i = 0; i < result.size(); ++i) {
AutocompleteMatch match = result.match_at(i);
std::string provider_name = match.provider->name();
output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
UTF16ToUTF8(match.contents).c_str(),
provider_name.c_str()));
}
return UTF8ToUTF16(output);
}
} // namespace
class OmniboxApiTest : public ExtensionApiTest {
protected:
LocationBar* GetLocationBar() const {
return browser()->window()->GetLocationBar();
}
AutocompleteController* GetAutocompleteController() const {
return GetLocationBar()->location_entry()->model()->popup_model()->
autocomplete_controller();
}
void WaitForTemplateURLServiceToLoad() {
TemplateURLService* model =
TemplateURLServiceFactory::GetForProfile(browser()->profile());
model->Load();
if (!model->loaded()) {
ui_test_utils::WaitForNotification(
chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED);
}
}
void WaitForAutocompleteDone(AutocompleteController* controller) {
while (!controller->done()) {
ui_test_utils::WaitForNotificationFrom(
chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
Source<AutocompleteController>(controller));
}
}
};
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_Basic) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
// Test that our extension's keyword is suggested to us when we partially type
// it.
{
autocomplete_controller->Start(
ASCIIToUTF16("keywor"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_EQ(string16(), location_bar->GetInputString());
EXPECT_EQ(string16(), location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
// First result should be to search for what was typed, second should be to
// enter "extension keyword" mode.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
match = result.match_at(1);
ASSERT_TRUE(match.template_url);
EXPECT_TRUE(match.template_url->IsExtensionKeyword());
EXPECT_EQ(ASCIIToUTF16("keyword"), match.template_url->keyword());
}
// Test that our extension can send suggestions back to us.
{
autocomplete_controller->Start(
ASCIIToUTF16("keyword suggestio"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
// First result should be to invoke the keyword with what we typed, 2-4
// should be to invoke with suggestions from the extension, and the last
// should be to search for what we typed.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
ASSERT_TRUE(result.match_at(0).template_url);
EXPECT_EQ(ASCIIToUTF16("keyword suggestio"),
result.match_at(0).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion1"),
result.match_at(1).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion2"),
result.match_at(2).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion3"),
result.match_at(3).fill_into_edit);
string16 description =
ASCIIToUTF16("Description with style: <match>, [dim], (url till end)");
EXPECT_EQ(description, result.match_at(1).contents);
ASSERT_EQ(6u, result.match_at(1).contents_class.size());
EXPECT_EQ(0u,
result.match_at(1).contents_class[0].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[0].style);
EXPECT_EQ(description.find('<'),
result.match_at(1).contents_class[1].offset);
EXPECT_EQ(ACMatchClassification::MATCH,
result.match_at(1).contents_class[1].style);
EXPECT_EQ(description.find('>') + 1u,
result.match_at(1).contents_class[2].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[2].style);
EXPECT_EQ(description.find('['),
result.match_at(1).contents_class[3].offset);
EXPECT_EQ(ACMatchClassification::DIM,
result.match_at(1).contents_class[3].style);
EXPECT_EQ(description.find(']') + 1u,
result.match_at(1).contents_class[4].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[4].style);
EXPECT_EQ(description.find('('),
result.match_at(1).contents_class[5].offset);
EXPECT_EQ(ACMatchClassification::URL,
result.match_at(1).contents_class[5].style);
AutocompleteMatch match = result.match_at(4);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
}
{
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
}
// Tests that the autocomplete popup doesn't reopen after accepting input for
// a given query.
// http://crbug.com/88552
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, PopupStaysClosed) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
AutocompletePopupModel* popup_model =
GetLocationBar()->location_entry()->model()->popup_model();
// Input a keyword query and wait for suggestions from the extension.
autocomplete_controller->Start(
ASCIIToUTF16("keyword comman"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(popup_model->IsOpen());
// Quickly type another query and accept it before getting suggestions back
// for the query. The popup will close after accepting input - ensure that it
// does not reopen when the extension returns its suggestions.
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_FALSE(popup_model->IsOpen());
}
|
Use current profile rather than AllSources for notification sources when registering for NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY.
|
Use current profile rather than AllSources for notification sources when registering for NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY.
BUG=None
TEST=Run trybots.
Review URL: http://codereview.chromium.org/7795007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@99415 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
junmin-zhu/chromium-rivertrail,M4sse/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,dednal/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,rogerwang/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,rogerwang/chromium,keishi/chromium,fujunwei/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,ondra-novak/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,keishi/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,rogerwang/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,robclark/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,ondra-novak/chromium.src,ltilve/chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,robclark/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Chilledheart/chromium,Just-D/chromium-1,hujiajie/pa-chromium,M4sse/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,keishi/chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,zcbenz/cefode-chromium,robclark/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,keishi/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,markYoungH/chromium.src,Chilledheart/chromium,M4sse/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,ltilve/chromium,keishi/chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,Just-D/chromium-1,robclark/chromium,markYoungH/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,robclark/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,jaruba/chromium.src,Just-D/chromium-1,Chilledheart/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,Jonekee/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,zcbenz/cefode-chromium,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,M4sse/chromium.src,rogerwang/chromium,Just-D/chromium-1,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,robclark/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,dednal/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,rogerwang/chromium,anirudhSK/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,robclark/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,rogerwang/chromium,patrickm/chromium.src,ondra-novak/chromium.src,rogerwang/chromium,dednal/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,Jonekee/chromium.src,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,M4sse/chromium.src,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,ltilve/chromium,Jonekee/chromium.src,markYoungH/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,keishi/chromium,Jonekee/chromium.src,littlstar/chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,ltilve/chromium
|
5ae5d49e2327532728750f2a54c9fb2f87ae30cc
|
chrome/browser/extensions/extension_storage_apitest.cc
|
chrome/browser/extensions/extension_storage_apitest.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// TODO(jcampan): http://crbug.com/27216 disabled because failing.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// TODO(jcampan): http://crbug.com/27216 disabled because failing.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
|
Mark ExtensionApiTest.Storage as flaky.
|
Mark ExtensionApiTest.Storage as flaky.
BUG=27216
TEST=none
Review URL: http://codereview.chromium.org/515026
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@35251 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
rogerwang/chromium,ltilve/chromium,patrickm/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,keishi/chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,patrickm/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,zcbenz/cefode-chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,ltilve/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,keishi/chromium,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,markYoungH/chromium.src,Just-D/chromium-1,ltilve/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,keishi/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,dednal/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,M4sse/chromium.src,dednal/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,dushu1203/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,rogerwang/chromium,dushu1203/chromium.src,M4sse/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,keishi/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,Chilledheart/chromium,robclark/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,bright-sparks/chromium-spacewalk,robclark/chromium,littlstar/chromium.src,robclark/chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,hujiajie/pa-chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,robclark/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,robclark/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,rogerwang/chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ltilve/chromium,ondra-novak/chromium.src,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,robclark/chromium,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,rogerwang/chromium,pozdnyakov/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,rogerwang/chromium,keishi/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,keishi/chromium,dushu1203/chromium.src,ondra-novak/chromium.src,rogerwang/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,ltilve/chromium,robclark/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,M4sse/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,jaruba/chromium.src,M4sse/chromium.src,anirudhSK/chromium,anirudhSK/chromium,jaruba/chromium.src,ltilve/chromium,robclark/chromium,keishi/chromium,hujiajie/pa-chromium,dednal/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,ltilve/chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium
|
9640a1ea586193773748003131b7c7ab13a98cc5
|
p2p/base/portallocatorsessionproxy_unittest.cc
|
p2p/base/portallocatorsessionproxy_unittest.cc
|
/*
* libjingle
* Copyright 2012 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include "talk/base/fakenetwork.h"
#include "talk/base/gunit.h"
#include "talk/base/thread.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/portallocatorsessionproxy.h"
#include "talk/p2p/client/basicportallocator.h"
#include "talk/p2p/client/fakeportallocator.h"
using cricket::Candidate;
using cricket::PortAllocatorSession;
using cricket::PortAllocatorSessionMuxer;
using cricket::PortAllocatorSessionProxy;
// Based on ICE_UFRAG_LENGTH
static const char kIceUfrag0[] = "TESTICEUFRAG0000";
// Based on ICE_PWD_LENGTH
static const char kIcePwd0[] = "TESTICEPWD00000000000000";
class TestSessionChannel : public sigslot::has_slots<> {
public:
explicit TestSessionChannel(PortAllocatorSessionProxy* proxy)
: proxy_session_(proxy),
candidates_count_(0),
allocation_complete_(false),
ports_count_(0) {
proxy_session_->SignalCandidatesAllocationDone.connect(
this, &TestSessionChannel::OnCandidatesAllocationDone);
proxy_session_->SignalCandidatesReady.connect(
this, &TestSessionChannel::OnCandidatesReady);
proxy_session_->SignalPortReady.connect(
this, &TestSessionChannel::OnPortReady);
}
virtual ~TestSessionChannel() {}
void OnCandidatesReady(PortAllocatorSession* session,
const std::vector<Candidate>& candidates) {
EXPECT_EQ(proxy_session_, session);
candidates_count_ += static_cast<int>(candidates.size());
}
void OnCandidatesAllocationDone(PortAllocatorSession* session) {
EXPECT_EQ(proxy_session_, session);
allocation_complete_ = true;
}
void OnPortReady(PortAllocatorSession* session,
cricket::PortInterface* port) {
EXPECT_EQ(proxy_session_, session);
++ports_count_;
}
int candidates_count() { return candidates_count_; }
bool allocation_complete() { return allocation_complete_; }
int ports_count() { return ports_count_; }
void StartGettingPorts() {
proxy_session_->StartGettingPorts();
}
void StopGettingPorts() {
proxy_session_->StopGettingPorts();
}
bool IsGettingPorts() {
return proxy_session_->IsGettingPorts();
}
private:
PortAllocatorSessionProxy* proxy_session_;
int candidates_count_;
bool allocation_complete_;
int ports_count_;
};
class PortAllocatorSessionProxyTest : public testing::Test {
public:
PortAllocatorSessionProxyTest()
: socket_factory_(talk_base::Thread::Current()),
allocator_(talk_base::Thread::Current(), NULL),
session_(talk_base::Thread::Current(), &socket_factory_,
"test content", 1,
kIceUfrag0, kIcePwd0),
session_muxer_(new PortAllocatorSessionMuxer(&session_)) {
}
virtual ~PortAllocatorSessionProxyTest() {}
void RegisterSessionProxy(PortAllocatorSessionProxy* proxy) {
session_muxer_->RegisterSessionProxy(proxy);
}
TestSessionChannel* CreateChannel() {
PortAllocatorSessionProxy* proxy =
new PortAllocatorSessionProxy("test content", 1, 0);
TestSessionChannel* channel = new TestSessionChannel(proxy);
session_muxer_->RegisterSessionProxy(proxy);
channel->StartGettingPorts();
return channel;
}
protected:
talk_base::BasicPacketSocketFactory socket_factory_;
cricket::FakePortAllocator allocator_;
cricket::FakePortAllocatorSession session_;
// Muxer object will be delete itself after all registered session proxies
// are deleted.
PortAllocatorSessionMuxer* session_muxer_;
};
TEST_F(PortAllocatorSessionProxyTest, TestBasic) {
TestSessionChannel* channel = CreateChannel();
EXPECT_EQ_WAIT(1, channel->candidates_count(), 1000);
EXPECT_EQ(1, channel->ports_count());
EXPECT_TRUE(channel->allocation_complete());
delete channel;
}
TEST_F(PortAllocatorSessionProxyTest, TestLateBinding) {
TestSessionChannel* channel1 = CreateChannel();
EXPECT_EQ_WAIT(1, channel1->candidates_count(), 1000);
EXPECT_EQ(1, channel1->ports_count());
EXPECT_TRUE(channel1->allocation_complete());
EXPECT_EQ(1, session_.port_config_count());
// Creating another PortAllocatorSessionProxy and it also should receive
// already happened events.
PortAllocatorSessionProxy* proxy =
new PortAllocatorSessionProxy("test content", 2, 0);
TestSessionChannel* channel2 = new TestSessionChannel(proxy);
session_muxer_->RegisterSessionProxy(proxy);
EXPECT_TRUE(channel2->IsGettingPorts());
EXPECT_EQ_WAIT(1, channel2->candidates_count(), 1000);
EXPECT_EQ(1, channel2->ports_count());
EXPECT_TRUE_WAIT(channel2->allocation_complete(), 1000);
EXPECT_EQ(1, session_.port_config_count());
delete channel1;
delete channel2;
}
|
/*
* libjingle
* Copyright 2012 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include "talk/base/fakenetwork.h"
#include "talk/base/gunit.h"
#include "talk/base/thread.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/portallocatorsessionproxy.h"
#include "talk/p2p/client/basicportallocator.h"
#include "talk/p2p/client/fakeportallocator.h"
using cricket::Candidate;
using cricket::PortAllocatorSession;
using cricket::PortAllocatorSessionMuxer;
using cricket::PortAllocatorSessionProxy;
// Based on ICE_UFRAG_LENGTH
static const char kIceUfrag0[] = "TESTICEUFRAG0000";
// Based on ICE_PWD_LENGTH
static const char kIcePwd0[] = "TESTICEPWD00000000000000";
class TestSessionChannel : public sigslot::has_slots<> {
public:
explicit TestSessionChannel(PortAllocatorSessionProxy* proxy)
: proxy_session_(proxy),
candidates_count_(0),
allocation_complete_(false),
ports_count_(0) {
proxy_session_->SignalCandidatesAllocationDone.connect(
this, &TestSessionChannel::OnCandidatesAllocationDone);
proxy_session_->SignalCandidatesReady.connect(
this, &TestSessionChannel::OnCandidatesReady);
proxy_session_->SignalPortReady.connect(
this, &TestSessionChannel::OnPortReady);
}
virtual ~TestSessionChannel() {
delete proxy_session_;
}
void OnCandidatesReady(PortAllocatorSession* session,
const std::vector<Candidate>& candidates) {
EXPECT_EQ(proxy_session_, session);
candidates_count_ += static_cast<int>(candidates.size());
}
void OnCandidatesAllocationDone(PortAllocatorSession* session) {
EXPECT_EQ(proxy_session_, session);
allocation_complete_ = true;
}
void OnPortReady(PortAllocatorSession* session,
cricket::PortInterface* port) {
EXPECT_EQ(proxy_session_, session);
++ports_count_;
}
int candidates_count() { return candidates_count_; }
bool allocation_complete() { return allocation_complete_; }
int ports_count() { return ports_count_; }
void StartGettingPorts() {
proxy_session_->StartGettingPorts();
}
void StopGettingPorts() {
proxy_session_->StopGettingPorts();
}
bool IsGettingPorts() {
return proxy_session_->IsGettingPorts();
}
private:
PortAllocatorSessionProxy* proxy_session_;
int candidates_count_;
bool allocation_complete_;
int ports_count_;
};
class PortAllocatorSessionProxyTest : public testing::Test {
public:
PortAllocatorSessionProxyTest()
: socket_factory_(talk_base::Thread::Current()),
allocator_(talk_base::Thread::Current(), NULL),
session_(new cricket::FakePortAllocatorSession(
talk_base::Thread::Current(), &socket_factory_,
"test content", 1,
kIceUfrag0, kIcePwd0)),
session_muxer_(new PortAllocatorSessionMuxer(session_)) {
}
virtual ~PortAllocatorSessionProxyTest() {}
void RegisterSessionProxy(PortAllocatorSessionProxy* proxy) {
session_muxer_->RegisterSessionProxy(proxy);
}
TestSessionChannel* CreateChannel() {
PortAllocatorSessionProxy* proxy =
new PortAllocatorSessionProxy("test content", 1, 0);
TestSessionChannel* channel = new TestSessionChannel(proxy);
session_muxer_->RegisterSessionProxy(proxy);
channel->StartGettingPorts();
return channel;
}
protected:
talk_base::BasicPacketSocketFactory socket_factory_;
cricket::FakePortAllocator allocator_;
cricket::FakePortAllocatorSession* session_;
// Muxer object will be delete itself after all registered session proxies
// are deleted.
PortAllocatorSessionMuxer* session_muxer_;
};
TEST_F(PortAllocatorSessionProxyTest, TestBasic) {
TestSessionChannel* channel = CreateChannel();
EXPECT_EQ_WAIT(1, channel->candidates_count(), 1000);
EXPECT_EQ(1, channel->ports_count());
EXPECT_TRUE(channel->allocation_complete());
delete channel;
}
TEST_F(PortAllocatorSessionProxyTest, TestLateBinding) {
TestSessionChannel* channel1 = CreateChannel();
EXPECT_EQ_WAIT(1, channel1->candidates_count(), 1000);
EXPECT_EQ(1, channel1->ports_count());
EXPECT_TRUE(channel1->allocation_complete());
EXPECT_EQ(1, session_->port_config_count());
// Creating another PortAllocatorSessionProxy and it also should receive
// already happened events.
PortAllocatorSessionProxy* proxy =
new PortAllocatorSessionProxy("test content", 2, 0);
TestSessionChannel* channel2 = new TestSessionChannel(proxy);
session_muxer_->RegisterSessionProxy(proxy);
EXPECT_TRUE(channel2->IsGettingPorts());
EXPECT_EQ_WAIT(1, channel2->candidates_count(), 1000);
EXPECT_EQ(1, channel2->ports_count());
EXPECT_TRUE_WAIT(channel2->allocation_complete(), 1000);
EXPECT_EQ(1, session_->port_config_count());
delete channel1;
delete channel2;
}
|
Fix memory leak in portallocatorsessionproxy_unittest. Remove the suppressions that have been fixed.
|
Fix memory leak in portallocatorsessionproxy_unittest.
Remove the suppressions that have been fixed.
BUG=1972,2263
[email protected]
Review URL: https://webrtc-codereview.appspot.com/2062005
Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc
Cr-Mirrored-Commit: ebe68aad44dfd5f557f83d51d145835674781962
|
C++
|
bsd-3-clause
|
sippet/talk,sippet/talk,sippet/talk,sippet/talk,sippet/talk
|
a70848e464d71277c22b8810e446076696e81662
|
Source/Engine/LuaScript/LuaScript.cpp
|
Source/Engine/LuaScript/LuaScript.cpp
|
//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Precompiled.h"
#include "CoreEvents.h"
#include "EngineEvents.h"
#include "File.h"
#include "Log.h"
#include "LuaFile.h"
#include "LuaFunction.h"
#include "LuaScript.h"
#include "LuaScriptInstance.h"
#include "ProcessUtils.h"
#include "Profiler.h"
#include "ResourceCache.h"
#include "Scene.h"
extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#include "tolua++.h"
#include "ToluaUtils.h"
#include "DebugNew.h"
extern int tolua_AudioLuaAPI_open(lua_State*);
extern int tolua_CoreLuaAPI_open(lua_State*);
extern int tolua_EngineLuaAPI_open(lua_State*);
extern int tolua_GraphicsLuaAPI_open(lua_State*);
extern int tolua_InputLuaAPI_open(lua_State*);
extern int tolua_IOLuaAPI_open(lua_State*);
extern int tolua_MathLuaAPI_open(lua_State*);
extern int tolua_NavigationLuaAPI_open(lua_State*);
extern int tolua_NetworkLuaAPI_open(lua_State*);
extern int tolua_PhysicsLuaAPI_open(lua_State*);
extern int tolua_ResourceLuaAPI_open(lua_State*);
extern int tolua_SceneLuaAPI_open(lua_State*);
extern int tolua_UILuaAPI_open(lua_State*);
extern int tolua_Urho2DLuaAPI_open(lua_State*);
extern int tolua_LuaScriptLuaAPI_open(lua_State*);
namespace Urho3D
{
LuaScript::LuaScript(Context* context) :
Object(context),
luaState_(0),
executeConsoleCommands_(true)
{
RegisterLuaScriptLibrary(context_);
luaState_ = luaL_newstate();
if (!luaState_)
{
LOGERROR("Could not create Lua state");
return;
}
SetContext(luaState_, context_);
lua_atpanic(luaState_, &LuaScript::AtPanic);
luaL_openlibs(luaState_);
RegisterLoader();
ReplacePrint();
tolua_MathLuaAPI_open(luaState_);
tolua_CoreLuaAPI_open(luaState_);
tolua_IOLuaAPI_open(luaState_);
tolua_ResourceLuaAPI_open(luaState_);
tolua_SceneLuaAPI_open(luaState_);
tolua_AudioLuaAPI_open(luaState_);
tolua_EngineLuaAPI_open(luaState_);
tolua_GraphicsLuaAPI_open(luaState_);
tolua_InputLuaAPI_open(luaState_);
tolua_NavigationLuaAPI_open(luaState_);
tolua_NetworkLuaAPI_open(luaState_);
tolua_PhysicsLuaAPI_open(luaState_);
tolua_UILuaAPI_open(luaState_);
tolua_Urho2DLuaAPI_open(luaState_);
tolua_LuaScriptLuaAPI_open(luaState_);
coroutineUpdate_ = GetFunction("coroutine.update");
// Subscribe to post update
SubscribeToEvent(E_POSTUPDATE, HANDLER(LuaScript, HandlePostUpdate));
// Subscribe to console commands
SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
// Record the internally handled script functions so that UnsubscribeFromAllEvents doesn't destroy them
internalEvents_.Push(E_POSTUPDATE);
internalEvents_.Push(E_CONSOLECOMMAND);
}
LuaScript::~LuaScript()
{
functionNameToFunctionMap_.Clear();
lua_State* luaState = luaState_;
luaState_ = 0;
SetContext(luaState_, 0);
if (luaState)
lua_close(luaState);
}
bool LuaScript::ExecuteFile(const String& fileName)
{
PROFILE(ExecuteFile);
ResourceCache* cache = GetSubsystem<ResourceCache>();
LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
return luaFile && luaFile->LoadAndExecute(luaState_);
}
bool LuaScript::ExecuteString(const String& string)
{
PROFILE(ExecuteString);
int top = lua_gettop(luaState_);
if (luaL_dostring(luaState_, string.CString()) != 0)
{
const char* message = lua_tostring(luaState_, -1);
LOGERROR("Execute Lua string failed: " + String(message));
lua_settop(luaState_, top);
return false;
}
return true;
}
bool LuaScript::ExecuteFunction(const String& functionName)
{
WeakPtr<LuaFunction> function = GetFunction(functionName);
return function && function->BeginCall() && function->EndCall();
}
void LuaScript::ScriptSendEvent(const String& eventName, VariantMap& eventData)
{
SendEvent(StringHash(eventName), eventData);
}
void LuaScript::ScriptSubscribeToEvent(const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
WeakPtr<LuaFunction> function = GetFunction(functionName);
if (function)
{
LuaFunctionVector& functions = eventHandleFunctions_[eventType];
HashSet<Object*>* receivers = context_->GetEventReceivers(eventType);
if (!receivers || !receivers->Contains(this))
SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
if (!functions.Contains(function))
functions.Push(function);
}
}
void LuaScript::ScriptUnsubscribeFromEvent(const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
HashMap<StringHash, LuaFunctionVector>::Iterator i = eventHandleFunctions_.Find(eventType);
if (i != eventHandleFunctions_.End())
{
LuaFunctionVector& functions = i->second_;
if (!functionName.Empty())
{
WeakPtr<LuaFunction> function = GetFunction(functionName);
functions.Remove(function);
}
if (functionName.Empty() || functions.Empty())
{
UnsubscribeFromEvent(eventType);
eventHandleFunctions_.Erase(i);
}
}
}
void LuaScript::ScriptUnsubscribeFromAllEvents()
{
if (eventHandleFunctions_.Empty())
return;
UnsubscribeFromAllEventsExcept(internalEvents_, false);
eventHandleFunctions_.Clear();
}
void LuaScript::ScriptSubscribeToEvent(void* sender, const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
Object* object = (Object*)sender;
WeakPtr<LuaFunction> function = GetFunction(functionName);
if (function)
{
LuaFunctionVector& functions = objectHandleFunctions_[object][eventType];
HashSet<Object*>* receivers = context_->GetEventReceivers(object, eventType);
if (!receivers || !receivers->Contains(this))
{
SubscribeToEvent(object, eventType, HANDLER(LuaScript, HandleObjectEvent));
// Fix issue #256
if (!functions.Empty())
functions.Clear();
}
if (!functions.Contains(function))
functions.Push(function);
}
}
void LuaScript::ScriptUnsubscribeFromEvent(void* sender, const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
Object* object = (Object*)sender;
HashMap<StringHash, LuaFunctionVector>::Iterator i = objectHandleFunctions_[object].Find(eventType);
if (i != objectHandleFunctions_[object].End())
{
LuaFunctionVector& functions = i->second_;
if (!functionName.Empty())
{
WeakPtr<LuaFunction> function = GetFunction(functionName);
functions.Remove(function);
}
if (functionName.Empty() || functions.Empty())
{
UnsubscribeFromEvent(object, eventType);
objectHandleFunctions_[object].Erase(i);
}
}
}
void LuaScript::ScriptUnsubscribeFromEvents(void* sender)
{
Object* object = (Object*)sender;
HashMap<Object*, HashMap<StringHash, LuaFunctionVector> >::Iterator it = objectHandleFunctions_.Find(object);
if (it == objectHandleFunctions_.End())
return;
UnsubscribeFromEvents(object);
objectHandleFunctions_.Erase(it);
}
void LuaScript::SetExecuteConsoleCommands(bool enable)
{
executeConsoleCommands_ = enable;
}
void LuaScript::RegisterLoader()
{
// Get package.loaders table
lua_getglobal(luaState_, "package");
lua_getfield(luaState_, -1, "loaders");
// Add LuaScript::Loader to the end of the table
lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
lua_pushcfunction(luaState_, &LuaScript::Loader);
lua_settable(luaState_, -3);
lua_pop(luaState_, 2);
}
int LuaScript::AtPanic(lua_State* L)
{
String errorMessage = luaL_checkstring(L, -1);
LOGERROR("Lua error: Error message = '" + errorMessage + "'");
lua_pop(L, 1);
return 0;
}
int LuaScript::Loader(lua_State* L)
{
ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
// Get module name
const char* name = luaL_checkstring(L, 1);
// Attempt to get .luc file first.
String lucFileName = String(name) + ".luc";
LuaFile* lucFile = cache->GetResource<LuaFile>(lucFileName, false);
if (lucFile)
return lucFile->LoadChunk(L) ? 1 : 0;
// Then try to get .lua file. If this also fails, error is logged and resource not found event is sent
String luaFileName = String(name) + ".lua";
LuaFile* luaFile = cache->GetResource<LuaFile>(luaFileName);
if (luaFile)
return luaFile->LoadChunk(L) ? 1 : 0;
return 0;
}
void LuaScript::ReplacePrint()
{
static const struct luaL_reg reg[] =
{
{"print", &LuaScript::Print},
{ NULL, NULL}
};
lua_getglobal(luaState_, "_G");
luaL_register(luaState_, NULL, reg);
lua_pop(luaState_, 1);
}
int LuaScript::Print(lua_State *L)
{
String string;
int n = lua_gettop(L);
lua_getglobal(L, "tostring");
for (int i = 1; i <= n; i++)
{
const char *s;
// Function to be called
lua_pushvalue(L, -1);
// Value to print
lua_pushvalue(L, i);
lua_call(L, 1, 1);
// Get result
s = lua_tostring(L, -1);
if (s == NULL)
return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
if (i > 1)
string.Append(" ");
string.Append(s);
// Pop result
lua_pop(L, 1);
}
LOGRAW("Lua: " + string);
return 0;
}
WeakPtr<LuaFunction> LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
{
if (!luaState_)
return WeakPtr<LuaFunction>();
HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
if (i != functionNameToFunctionMap_.End())
return WeakPtr<LuaFunction>(i->second_);
int top = lua_gettop(luaState_);
SharedPtr<LuaFunction> function;
if (PushScriptFunction(functionName, silentIfNotFound))
{
int ref = luaL_ref(luaState_, LUA_REGISTRYINDEX);
function = new LuaFunction(luaState_, ref);
}
lua_settop(luaState_, top);
functionNameToFunctionMap_[functionName] = function;
return WeakPtr<LuaFunction>(function);
}
void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
{
LuaFunctionVector& functions = eventHandleFunctions_[eventType];
for (unsigned i = 0; i < functions.Size(); ++i)
{
WeakPtr<LuaFunction> function = functions[i];
if (function && function->BeginCall())
{
function->PushUserType(eventType, "StringHash");
function->PushUserType(eventData, "VariantMap");
function->EndCall();
}
}
}
void LuaScript::HandleObjectEvent(StringHash eventType, VariantMap& eventData)
{
Object* object = GetEventSender();
LuaFunctionVector& functions = objectHandleFunctions_[object][eventType];
for (unsigned i = 0; i < functions.Size(); ++i)
{
WeakPtr<LuaFunction> function = functions[i];
if (function && function->BeginCall())
{
function->PushUserType(eventType, "StringHash");
function->PushUserType(eventData, "VariantMap");
function->EndCall();
}
}
}
void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
{
using namespace PostUpdate;
float timeStep = eventData[P_TIMESTEP].GetFloat();
coroutineUpdate_->PushFloat(timeStep);
coroutineUpdate_->EndCall();
}
// Collect garbage
lua_gc(luaState_, LUA_GCCOLLECT, 0);
}
void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
{
using namespace ConsoleCommand;
if (executeConsoleCommands_)
ExecuteString(eventData[P_COMMAND].GetString());
}
bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
{
Vector<String> splitedNames = functionName.Split('.');
String currentName = splitedNames.Front();
lua_getglobal(luaState_, currentName.CString());
if (splitedNames.Size() > 1)
{
if (!lua_istable(luaState_, -1))
{
LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
return false;
}
for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
{
currentName = currentName + "." + splitedNames[i];
lua_getfield(luaState_, -1, splitedNames[i].CString());
if (!lua_istable(luaState_, -1))
{
LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
return false;
}
}
currentName = currentName + "." + splitedNames.Back().CString();
lua_getfield(luaState_, -1, splitedNames.Back().CString());
}
if (!lua_isfunction(luaState_, -1))
{
if (!silentIfNotFound)
LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
return false;
}
return true;
}
void RegisterLuaScriptLibrary(Context* context)
{
LuaFile::RegisterObject(context);
LuaScriptInstance::RegisterObject(context);
}
}
|
//
// Copyright (c) 2008-2014 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Precompiled.h"
#include "CoreEvents.h"
#include "EngineEvents.h"
#include "File.h"
#include "Log.h"
#include "LuaFile.h"
#include "LuaFunction.h"
#include "LuaScript.h"
#include "LuaScriptInstance.h"
#include "ProcessUtils.h"
#include "Profiler.h"
#include "ResourceCache.h"
#include "Scene.h"
extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#include "tolua++.h"
#include "ToluaUtils.h"
#include "DebugNew.h"
extern int tolua_AudioLuaAPI_open(lua_State*);
extern int tolua_CoreLuaAPI_open(lua_State*);
extern int tolua_EngineLuaAPI_open(lua_State*);
extern int tolua_GraphicsLuaAPI_open(lua_State*);
extern int tolua_InputLuaAPI_open(lua_State*);
extern int tolua_IOLuaAPI_open(lua_State*);
extern int tolua_MathLuaAPI_open(lua_State*);
extern int tolua_NavigationLuaAPI_open(lua_State*);
extern int tolua_NetworkLuaAPI_open(lua_State*);
extern int tolua_PhysicsLuaAPI_open(lua_State*);
extern int tolua_ResourceLuaAPI_open(lua_State*);
extern int tolua_SceneLuaAPI_open(lua_State*);
extern int tolua_UILuaAPI_open(lua_State*);
extern int tolua_Urho2DLuaAPI_open(lua_State*);
extern int tolua_LuaScriptLuaAPI_open(lua_State*);
namespace Urho3D
{
LuaScript::LuaScript(Context* context) :
Object(context),
luaState_(0),
executeConsoleCommands_(true)
{
RegisterLuaScriptLibrary(context_);
luaState_ = luaL_newstate();
if (!luaState_)
{
LOGERROR("Could not create Lua state");
return;
}
SetContext(luaState_, context_);
lua_atpanic(luaState_, &LuaScript::AtPanic);
luaL_openlibs(luaState_);
RegisterLoader();
ReplacePrint();
tolua_MathLuaAPI_open(luaState_);
tolua_CoreLuaAPI_open(luaState_);
tolua_IOLuaAPI_open(luaState_);
tolua_ResourceLuaAPI_open(luaState_);
tolua_SceneLuaAPI_open(luaState_);
tolua_AudioLuaAPI_open(luaState_);
tolua_EngineLuaAPI_open(luaState_);
tolua_GraphicsLuaAPI_open(luaState_);
tolua_InputLuaAPI_open(luaState_);
tolua_NavigationLuaAPI_open(luaState_);
tolua_NetworkLuaAPI_open(luaState_);
tolua_PhysicsLuaAPI_open(luaState_);
tolua_UILuaAPI_open(luaState_);
tolua_Urho2DLuaAPI_open(luaState_);
tolua_LuaScriptLuaAPI_open(luaState_);
coroutineUpdate_ = GetFunction("coroutine.update");
// Subscribe to post update
SubscribeToEvent(E_POSTUPDATE, HANDLER(LuaScript, HandlePostUpdate));
// Subscribe to console commands
SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
// Record the internally handled script functions so that UnsubscribeFromAllEvents doesn't destroy them
internalEvents_.Push(E_POSTUPDATE);
internalEvents_.Push(E_CONSOLECOMMAND);
}
LuaScript::~LuaScript()
{
functionNameToFunctionMap_.Clear();
lua_State* luaState = luaState_;
luaState_ = 0;
SetContext(luaState_, 0);
if (luaState)
lua_close(luaState);
}
bool LuaScript::ExecuteFile(const String& fileName)
{
PROFILE(ExecuteFile);
ResourceCache* cache = GetSubsystem<ResourceCache>();
LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
return luaFile && luaFile->LoadAndExecute(luaState_);
}
bool LuaScript::ExecuteString(const String& string)
{
PROFILE(ExecuteString);
int top = lua_gettop(luaState_);
if (luaL_dostring(luaState_, string.CString()) != 0)
{
const char* message = lua_tostring(luaState_, -1);
LOGERROR("Execute Lua string failed: " + String(message));
lua_settop(luaState_, top);
return false;
}
return true;
}
bool LuaScript::ExecuteFunction(const String& functionName)
{
WeakPtr<LuaFunction> function = GetFunction(functionName);
return function && function->BeginCall() && function->EndCall();
}
void LuaScript::ScriptSendEvent(const String& eventName, VariantMap& eventData)
{
SendEvent(StringHash(eventName), eventData);
}
void LuaScript::ScriptSubscribeToEvent(const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
WeakPtr<LuaFunction> function = GetFunction(functionName);
if (function)
{
LuaFunctionVector& functions = eventHandleFunctions_[eventType];
HashSet<Object*>* receivers = context_->GetEventReceivers(eventType);
if (!receivers || !receivers->Contains(this))
SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
if (!functions.Contains(function))
functions.Push(function);
}
}
void LuaScript::ScriptUnsubscribeFromEvent(const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
HashMap<StringHash, LuaFunctionVector>::Iterator i = eventHandleFunctions_.Find(eventType);
if (i != eventHandleFunctions_.End())
{
LuaFunctionVector& functions = i->second_;
if (!functionName.Empty())
{
WeakPtr<LuaFunction> function = GetFunction(functionName);
functions.Remove(function);
}
if (functionName.Empty() || functions.Empty())
{
UnsubscribeFromEvent(eventType);
eventHandleFunctions_.Erase(i);
}
}
}
void LuaScript::ScriptUnsubscribeFromAllEvents()
{
if (eventHandleFunctions_.Empty())
return;
UnsubscribeFromAllEventsExcept(internalEvents_, false);
eventHandleFunctions_.Clear();
}
void LuaScript::ScriptSubscribeToEvent(void* sender, const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
Object* object = (Object*)sender;
WeakPtr<LuaFunction> function = GetFunction(functionName);
if (function)
{
LuaFunctionVector& functions = objectHandleFunctions_[object][eventType];
HashSet<Object*>* receivers = context_->GetEventReceivers(object, eventType);
if (!receivers || !receivers->Contains(this))
{
SubscribeToEvent(object, eventType, HANDLER(LuaScript, HandleObjectEvent));
// Fix issue #256
if (!functions.Empty())
functions.Clear();
}
if (!functions.Contains(function))
functions.Push(function);
}
}
void LuaScript::ScriptUnsubscribeFromEvent(void* sender, const String& eventName, const String& functionName)
{
StringHash eventType(eventName);
Object* object = (Object*)sender;
HashMap<StringHash, LuaFunctionVector>::Iterator i = objectHandleFunctions_[object].Find(eventType);
if (i != objectHandleFunctions_[object].End())
{
LuaFunctionVector& functions = i->second_;
if (!functionName.Empty())
{
WeakPtr<LuaFunction> function = GetFunction(functionName);
functions.Remove(function);
}
if (functionName.Empty() || functions.Empty())
{
UnsubscribeFromEvent(object, eventType);
objectHandleFunctions_[object].Erase(i);
}
}
}
void LuaScript::ScriptUnsubscribeFromEvents(void* sender)
{
Object* object = (Object*)sender;
HashMap<Object*, HashMap<StringHash, LuaFunctionVector> >::Iterator it = objectHandleFunctions_.Find(object);
if (it == objectHandleFunctions_.End())
return;
UnsubscribeFromEvents(object);
objectHandleFunctions_.Erase(it);
}
void LuaScript::SetExecuteConsoleCommands(bool enable)
{
executeConsoleCommands_ = enable;
}
void LuaScript::RegisterLoader()
{
// Get package.loaders table
lua_getglobal(luaState_, "package");
lua_getfield(luaState_, -1, "loaders");
// Add LuaScript::Loader to the end of the table
lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
lua_pushcfunction(luaState_, &LuaScript::Loader);
lua_settable(luaState_, -3);
lua_pop(luaState_, 2);
}
int LuaScript::AtPanic(lua_State* L)
{
String errorMessage = luaL_checkstring(L, -1);
LOGERROR("Lua error: Error message = '" + errorMessage + "'");
lua_pop(L, 1);
return 0;
}
int LuaScript::Loader(lua_State* L)
{
ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
// Get module name
const char* name = luaL_checkstring(L, 1);
// Attempt to get .luc file first.
String lucFileName = String(name) + ".luc";
LuaFile* lucFile = cache->GetResource<LuaFile>(lucFileName, false);
if (lucFile)
return lucFile->LoadChunk(L) ? 1 : 0;
// Then try to get .lua file. If this also fails, error is logged and resource not found event is sent
String luaFileName = String(name) + ".lua";
LuaFile* luaFile = cache->GetResource<LuaFile>(luaFileName);
if (luaFile)
return luaFile->LoadChunk(L) ? 1 : 0;
return 0;
}
void LuaScript::ReplacePrint()
{
static const struct luaL_reg reg[] =
{
{"print", &LuaScript::Print},
{ NULL, NULL}
};
lua_getglobal(luaState_, "_G");
luaL_register(luaState_, NULL, reg);
lua_pop(luaState_, 1);
}
int LuaScript::Print(lua_State *L)
{
String string;
int n = lua_gettop(L);
lua_getglobal(L, "tostring");
for (int i = 1; i <= n; i++)
{
const char *s;
// Function to be called
lua_pushvalue(L, -1);
// Value to print
lua_pushvalue(L, i);
lua_call(L, 1, 1);
// Get result
s = lua_tostring(L, -1);
if (s == NULL)
return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
if (i > 1)
string.Append(" ");
string.Append(s);
// Pop result
lua_pop(L, 1);
}
LOGRAW("Lua: " + string);
return 0;
}
WeakPtr<LuaFunction> LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
{
if (!luaState_)
return WeakPtr<LuaFunction>();
HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
if (i != functionNameToFunctionMap_.End())
return WeakPtr<LuaFunction>(i->second_);
int top = lua_gettop(luaState_);
SharedPtr<LuaFunction> function;
if (PushScriptFunction(functionName, silentIfNotFound))
{
int ref = luaL_ref(luaState_, LUA_REGISTRYINDEX);
function = new LuaFunction(luaState_, ref);
}
lua_settop(luaState_, top);
functionNameToFunctionMap_[functionName] = function;
return WeakPtr<LuaFunction>(function);
}
void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
{
LuaFunctionVector& functions = eventHandleFunctions_[eventType];
for (unsigned i = 0; i < functions.Size(); ++i)
{
WeakPtr<LuaFunction> function = functions[i];
if (function && function->BeginCall())
{
function->PushUserType(eventType, "StringHash");
function->PushUserType(eventData, "VariantMap");
function->EndCall();
}
}
}
void LuaScript::HandleObjectEvent(StringHash eventType, VariantMap& eventData)
{
Object* object = GetEventSender();
LuaFunctionVector& functions = objectHandleFunctions_[object][eventType];
for (unsigned i = 0; i < functions.Size(); ++i)
{
WeakPtr<LuaFunction> function = functions[i];
if (function && function->BeginCall())
{
function->PushUserType(eventType, "StringHash");
function->PushUserType(eventData, "VariantMap");
function->EndCall();
}
}
}
void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
// Call also user-subscribed PostUpdate handler (if any)
HandleEvent(eventType, eventData);
if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
{
using namespace PostUpdate;
float timeStep = eventData[P_TIMESTEP].GetFloat();
coroutineUpdate_->PushFloat(timeStep);
coroutineUpdate_->EndCall();
}
// Collect garbage
lua_gc(luaState_, LUA_GCCOLLECT, 0);
}
void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
{
using namespace ConsoleCommand;
if (executeConsoleCommands_)
ExecuteString(eventData[P_COMMAND].GetString());
}
bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
{
Vector<String> splitedNames = functionName.Split('.');
String currentName = splitedNames.Front();
lua_getglobal(luaState_, currentName.CString());
if (splitedNames.Size() > 1)
{
if (!lua_istable(luaState_, -1))
{
LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
return false;
}
for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
{
currentName = currentName + "." + splitedNames[i];
lua_getfield(luaState_, -1, splitedNames[i].CString());
if (!lua_istable(luaState_, -1))
{
LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
return false;
}
}
currentName = currentName + "." + splitedNames.Back().CString();
lua_getfield(luaState_, -1, splitedNames.Back().CString());
}
if (!lua_isfunction(luaState_, -1))
{
if (!silentIfNotFound)
LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
return false;
}
return true;
}
void RegisterLuaScriptLibrary(Context* context)
{
LuaFile::RegisterObject(context);
LuaScriptInstance::RegisterObject(context);
}
}
|
Fix Lua postupdate handler not being called.
|
Fix Lua postupdate handler not being called.
|
C++
|
mit
|
299299/Urho3D,rokups/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,eugeneko/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,xiliu98/Urho3D,carnalis/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,SuperWangKai/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,henu/Urho3D,fire/Urho3D-1,299299/Urho3D,abdllhbyrktr/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,helingping/Urho3D,rokups/Urho3D,orefkov/Urho3D,urho3d/Urho3D,xiliu98/Urho3D,weitjong/Urho3D,carnalis/Urho3D,henu/Urho3D,cosmy1/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,luveti/Urho3D,codemon66/Urho3D,PredatorMF/Urho3D,eugeneko/Urho3D,PredatorMF/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,eugeneko/Urho3D,codedash64/Urho3D,MeshGeometry/Urho3D,kostik1337/Urho3D,victorholt/Urho3D,luveti/Urho3D,henu/Urho3D,abdllhbyrktr/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,rokups/Urho3D,iainmerrick/Urho3D,orefkov/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,kostik1337/Urho3D,bacsmar/Urho3D,codemon66/Urho3D,rokups/Urho3D,MonkeyFirst/Urho3D,bacsmar/Urho3D,orefkov/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,299299/Urho3D,carnalis/Urho3D,fire/Urho3D-1,xiliu98/Urho3D,iainmerrick/Urho3D,luveti/Urho3D,MeshGeometry/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,tommy3/Urho3D,abdllhbyrktr/Urho3D,weitjong/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,codedash64/Urho3D,SirNate0/Urho3D,rokups/Urho3D,tommy3/Urho3D,henu/Urho3D,MonkeyFirst/Urho3D,xiliu98/Urho3D,tommy3/Urho3D,orefkov/Urho3D,fire/Urho3D-1,victorholt/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,codemon66/Urho3D,weitjong/Urho3D,codedash64/Urho3D,carnalis/Urho3D,299299/Urho3D,c4augustus/Urho3D,codemon66/Urho3D,299299/Urho3D,MeshGeometry/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,cosmy1/Urho3D,c4augustus/Urho3D,iainmerrick/Urho3D,weitjong/Urho3D,MonkeyFirst/Urho3D,weitjong/Urho3D,PredatorMF/Urho3D,eugeneko/Urho3D,MonkeyFirst/Urho3D,abdllhbyrktr/Urho3D,victorholt/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,urho3d/Urho3D,luveti/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,helingping/Urho3D,bacsmar/Urho3D,luveti/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,SirNate0/Urho3D,urho3d/Urho3D
|
bb1001107e0ec6a0dd68ff7f62efc1fa2af07dcb
|
src/ui/linux/TogglDesktop/main.cpp
|
src/ui/linux/TogglDesktop/main.cpp
|
// Copyright 2014 Toggl Desktop developers.
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QMetaType>
#include <QVector>
#include <stdint.h>
#include <stdbool.h>
#include "qtsingleapplication.h" // NOLINT
#include "./autocompleteview.h"
#include "./bugsnag.h"
#include "./genericview.h"
#include "./mainwindowcontroller.h"
#include "./toggl.h"
class TogglApplication : public QtSingleApplication {
public:
TogglApplication(int &argc, char **argv) // NOLINT
: QtSingleApplication(argc, argv) {}
virtual bool notify(QObject *receiver, QEvent *event) {
try {
return QtSingleApplication::notify(receiver, event);
} catch(std::exception e) {
TogglApi::notifyBugsnag("std::exception", e.what(),
receiver->objectName());
} catch(...) {
TogglApi::notifyBugsnag("unspecified", "exception",
receiver->objectName());
}
return true;
}
};
int main(int argc, char *argv[]) try {
Bugsnag::apiKey = "2a46aa1157256f759053289f2d687c2f";
qRegisterMetaType<uint64_t>("uint64_t");
qRegisterMetaType<int64_t>("int64_t");
qRegisterMetaType<_Bool>("_Bool");
qRegisterMetaType<QVector<TimeEntryView*> >("QVector<TimeEntryView*>");
qRegisterMetaType<QVector<AutocompleteView*> >("QVector<AutocompleteView*");
qRegisterMetaType<QVector<GenericView*> >("QVector<GenericView*");
TogglApplication a(argc, argv);
if (a.sendMessage(("Wake up!"))) {
qDebug() << "An instance of TogglDesktop is already running. "
"This instance will now quit.";
return 0;
}
a.setApplicationName("Toggl Desktop");
a.setApplicationVersion(APP_VERSION);
Bugsnag::app.version = APP_VERSION;
QCommandLineParser parser;
parser.setApplicationDescription("Toggl Desktop");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption logPathOption(
QStringList() << "log-path",
"<path> of the app log file",
"path");
parser.addOption(logPathOption);
QCommandLineOption dbPathOption(
QStringList() << "db-path",
"<path> of the app DB file",
"path");
parser.addOption(dbPathOption);
QCommandLineOption scriptPathOption(
QStringList() << "script-path",
"<path> of a Lua script to run",
"path");
parser.addOption(scriptPathOption);
parser.process(a);
MainWindowController w(0,
parser.value(logPathOption),
parser.value(dbPathOption),
parser.value(scriptPathOption));
w.show();
return a.exec();
} catch (std::exception &e) { // NOLINT
TogglApi::notifyBugsnag("std::exception", e.what(), "main");
return 1;
} catch (...) { // NOLINT
TogglApi::notifyBugsnag("unspecified", "exception", "main");
return 1;
}
|
// Copyright 2014 Toggl Desktop developers.
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QMetaType>
#include <QVector>
#include <stdint.h>
#include <stdbool.h>
#include "qtsingleapplication.h" // NOLINT
#include "./autocompleteview.h"
#include "./bugsnag.h"
#include "./genericview.h"
#include "./mainwindowcontroller.h"
#include "./toggl.h"
class TogglApplication : public QtSingleApplication {
public:
TogglApplication(int &argc, char **argv) // NOLINT
: QtSingleApplication(argc, argv) {}
virtual bool notify(QObject *receiver, QEvent *event) {
try {
return QtSingleApplication::notify(receiver, event);
} catch(std::exception e) {
TogglApi::notifyBugsnag("std::exception", e.what(),
receiver->objectName());
} catch(...) {
TogglApi::notifyBugsnag("unspecified", "exception",
receiver->objectName());
}
return true;
}
};
int main(int argc, char *argv[]) try {
Bugsnag::apiKey = "2a46aa1157256f759053289f2d687c2f";
qRegisterMetaType<uint64_t>("uint64_t");
qRegisterMetaType<int64_t>("int64_t");
qRegisterMetaType<_Bool>("_Bool");
qRegisterMetaType<QVector<TimeEntryView*> >("QVector<TimeEntryView*>");
qRegisterMetaType<QVector<AutocompleteView*> >("QVector<AutocompleteView*");
qRegisterMetaType<QVector<GenericView*> >("QVector<GenericView*");
TogglApplication a(argc, argv);
if (a.sendMessage(("Wake up!"))) {
qDebug() << "An instance of TogglDesktop is already running. "
"This instance will now quit.";
return 0;
}
a.setApplicationName("Toggl Desktop");
a.setApplicationVersion(APP_VERSION);
Bugsnag::app.version = APP_VERSION;
// Select some font to get predictable font
QFont font("Helvetica", 10);
QApplication::setFont(font);
qDebug() << "Application font: " << QApplication::font().toString();
QCommandLineParser parser;
parser.setApplicationDescription("Toggl Desktop");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption logPathOption(
QStringList() << "log-path",
"<path> of the app log file",
"path");
parser.addOption(logPathOption);
QCommandLineOption dbPathOption(
QStringList() << "db-path",
"<path> of the app DB file",
"path");
parser.addOption(dbPathOption);
QCommandLineOption scriptPathOption(
QStringList() << "script-path",
"<path> of a Lua script to run",
"path");
parser.addOption(scriptPathOption);
parser.process(a);
MainWindowController w(0,
parser.value(logPathOption),
parser.value(dbPathOption),
parser.value(scriptPathOption));
w.show();
return a.exec();
} catch (std::exception &e) { // NOLINT
TogglApi::notifyBugsnag("std::exception", e.what(), "main");
return 1;
} catch (...) { // NOLINT
TogglApi::notifyBugsnag("unspecified", "exception", "main");
return 1;
}
|
Set app font to Helvetica 10 (linux)
|
Set app font to Helvetica 10 (linux)
|
C++
|
bsd-3-clause
|
codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop
|
fa01847b43f12b7a3e3640a345affa67161bee0f
|
test/fs/integration/memdisk/twosector.cpp
|
test/fs/integration/memdisk/twosector.cpp
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <service>
#include <stdio.h>
#include <cassert>
#include <memdisk>
void Service::start(const std::string&)
{
INFO("MemDisk", "Running tests for MemDisk");
auto disk = fs::new_shared_memdisk();
CHECKSERT(disk, "Created shared memdisk");
CHECKSERT(not disk->empty(), "Disk is not empty");
// verify that the size is indeed 2 sectors
CHECKSERT(disk->dev().size() == 2, "Disk size is correct (2 sectors)");
// read one block
auto buf = disk->dev().read_sync(0);
// verify nothing bad happened
CHECKSERT(!!buf, "Buffer for sector 0 is valid");
// convert to text (before reading sector 2)
std::string text((const char*) buf.get(), disk->dev().block_size());
// read another block
buf = disk->dev().read_sync(1);
// verify nothing bad happened
CHECKSERT(!!buf, "Buffer for sector 1 is valid");
// verify that the sector contents matches the test string
// NOTE: the 3 first characters are non-text 0xBFBBEF
std::string test1 = "\xEF\xBB\xBFThe Project Gutenberg EBook of Pride and Prejudice, by Jane Austen";
std::string test2 = text.substr(0, test1.size());
CHECKSERT(test1 == test2, "Binary comparison of sector data");
// verify that reading outside of disk returns a 0x0 pointer
buf = disk->dev().read_sync(disk->dev().size());
CHECKSERT(!buf, "Buffer outside of disk range (sector=%llu) is 0x0",
disk->dev().size());
INFO("MemDisk", "SUCCESS");
}
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <service>
#include <stdio.h>
#include <cassert>
#include <common>
#include <memdisk>
void Service::start(const std::string&)
{
INFO("MemDisk", "Running tests for MemDisk");
auto disk = fs::new_shared_memdisk();
CHECKSERT(disk, "Created shared memdisk");
CHECKSERT(not disk->empty(), "Disk is not empty");
// verify that the size is indeed 2 sectors
CHECKSERT(disk->dev().size() == 2, "Disk size is correct (2 sectors)");
// read one block
auto buf = disk->dev().read_sync(0);
// verify nothing bad happened
CHECKSERT(!!buf, "Buffer for sector 0 is valid");
// convert to text (before reading sector 2)
std::string text((const char*) buf.get(), disk->dev().block_size());
// read another block
buf = disk->dev().read_sync(1);
// verify nothing bad happened
CHECKSERT(!!buf, "Buffer for sector 1 is valid");
// verify that the sector contents matches the test string
// NOTE: the 3 first characters are non-text 0xBFBBEF
std::string test1 = "\xEF\xBB\xBFThe Project Gutenberg EBook of Pride and Prejudice, by Jane Austen";
std::string test2 = text.substr(0, test1.size());
CHECKSERT(test1 == test2, "Binary comparison of sector data");
// verify that reading outside of disk returns a 0x0 pointer
buf = disk->dev().read_sync(disk->dev().size());
CHECKSERT(!buf, "Buffer outside of disk range (sector=%llu) is 0x0",
disk->dev().size());
INFO("MemDisk", "SUCCESS");
}
|
Add missing common dependence to twosector integration test
|
Add missing common dependence to twosector integration test
|
C++
|
apache-2.0
|
alfred-bratterud/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,ingve/IncludeOS,ingve/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,alfred-bratterud/IncludeOS,alfred-bratterud/IncludeOS,ingve/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS
|
a8f7c6eee89fa2cdb29ace1f0bf244f61f724db9
|
src/sensors/qrotationsensor.cpp
|
src/sensors/qrotationsensor.cpp
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qrotationsensor.h"
#include "qrotationsensor_p.h"
QTM_BEGIN_NAMESPACE
IMPLEMENT_READING(QRotationReading)
/*!
\class QRotationReading
\ingroup sensors_reading
\preliminary
\brief The QRotationReading class represents one reading from the
rotation sensor.
\section2 QRotationReading Units
The rotation reading contains 3 angles, measured in degrees that define
the orientation of the device in three-dimensional space. The rotations
should not be confused with relative rotations such as yaw and pitch.
These rotations are of the devices axes relative to the external
reference points that define the reference co-ordinate axes: X, Y and Z
in the diagram.
The three angles are applied to the device in the following order.
\list
\o Right-handed rotation z (-180, 180]. Starting from the x-axis and
incrementing in the direction of the y-axis.
\o Right-handed rotation x (-90, 90]. Starting from the new
(once-rotated) y-axis and incrementing towards the z-axis.
\o Right-handed rotation y (-180, 180]. Starting from the new
(twice-rotated) z-axis and incrementing towards the x-axis.
\endlist
\image Rotation_angles.png Visual representation of the rotation angles.
The 0 point for the z angle is defined as a fixed, external entity and
is device-specific. While magnetic North is typically used as this
reference point it may not be. Do not attempt to compare values
for the z angle between devices or even on the same device if it has
moved a significant distance.
If the device cannot detect a fixed, external entity the z angle will
always be 0 and the QRotationSensor::hasZ property will be set to false.
The 0 point for the x and y angles are defined as when the x and y axes
of the device are oriented towards the horizon.
*/
/*!
\property QRotationReading::x
\brief the rotation around the x axis.
Measured as degrees.
\sa {QRotationReading Units}
*/
qreal QRotationReading::x() const
{
return d->x;
}
/*!
Sets the rotation around the x axis to \a x.
*/
void QRotationReading::setX(qreal x)
{
d->x = x;
}
/*!
\property QRotationReading::y
\brief the rotation around the y axis.
Measured as degrees.
\sa {QRotationReading Units}
*/
qreal QRotationReading::y() const
{
return d->y;
}
/*!
Sets the rotation around the y axis to \a y.
*/
void QRotationReading::setY(qreal y)
{
d->y = y;
}
/*!
\property QRotationReading::z
\brief the rotation around the z axis.
Measured as degrees.
\sa {QRotationReading Units}
*/
qreal QRotationReading::z() const
{
return d->z;
}
/*!
Sets the rotation around the z axis to \a z.
*/
void QRotationReading::setZ(qreal z)
{
d->z = z;
}
// =====================================================================
/*!
\class QRotationFilter
\ingroup sensors_filter
\preliminary
\brief The QRotationFilter class is a convenience wrapper around QSensorFilter.
The only difference is that the filter() method features a pointer to QRotationReading
instead of QSensorReading.
*/
/*!
\fn QRotationFilter::filter(QRotationReading *reading)
Called when \a reading changes. Returns false to prevent the reading from propagating.
\sa QSensorFilter::filter()
*/
const char *QRotationSensor::type("QRotationSensor");
/*!
\class QRotationSensor
\ingroup sensors_type
\preliminary
\brief The QRotationSensor class is a convenience wrapper around QSensor.
The only behavioural difference is that this class sets the type properly.
This class also features a reading() function that returns a QRotationReading instead of a QSensorReading.
For details about how the sensor works, see \l QRotationReading.
\sa QRotationReading
*/
/*!
\fn QRotationSensor::QRotationSensor(QObject *parent)
Construct the sensor as a child of \a parent.
*/
/*!
\fn QRotationSensor::~QRotationSensor()
Destroy the sensor. Stops the sensor if it has not already been stopped.
*/
/*!
\fn QRotationSensor::reading() const
Returns the reading class for this sensor.
\sa QSensor::reading()
*/
/*!
\property QRotationSensor::hasZ
\brief a value indicating if the z angle is available.
Returns true if z is available.
Returns false if z is not available.
*/
#include "moc_qrotationsensor.cpp"
QTM_END_NAMESPACE
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qrotationsensor.h"
#include "qrotationsensor_p.h"
QTM_BEGIN_NAMESPACE
IMPLEMENT_READING(QRotationReading)
/*!
\class QRotationReading
\ingroup sensors_reading
\preliminary
\brief The QRotationReading class represents one reading from the
rotation sensor.
\section2 QRotationReading Units
The rotation reading contains 3 angles, measured in degrees that define
the orientation of the device in three-dimensional space. The rotations
should not be confused with relative rotations such as yaw and pitch.
These rotations are of the devices axes relative to the external
reference points that define the reference co-ordinate axes: X, Y and Z
in the diagram.
The three angles are applied to the device in the following order.
\list
\o Right-handed rotation z (-180, 180]. Starting from the x-axis and
incrementing in the direction of the y-axis.
\o Right-handed rotation x [-90, 90]. Starting from the new
(once-rotated) y-axis and incrementing towards the z-axis.
\o Right-handed rotation y (-180, 180]. Starting from the new
(twice-rotated) z-axis and incrementing towards the x-axis.
\endlist
\image Rotation_angles.png Visual representation of the rotation angles.
The 0 point for the z angle is defined as a fixed, external entity and
is device-specific. While magnetic North is typically used as this
reference point it may not be. Do not attempt to compare values
for the z angle between devices or even on the same device if it has
moved a significant distance.
If the device cannot detect a fixed, external entity the z angle will
always be 0 and the QRotationSensor::hasZ property will be set to false.
The 0 point for the x and y angles are defined as when the x and y axes
of the device are oriented towards the horizon.
Note that when x is 90 or -90, values for z and y achieve rotation around
the same axis (due to the order of operations). In this case the y
rotation will be 0.
*/
/*!
\property QRotationReading::x
\brief the rotation around the x axis.
Measured as degrees.
\sa {QRotationReading Units}
*/
qreal QRotationReading::x() const
{
return d->x;
}
/*!
Sets the rotation around the x axis to \a x.
*/
void QRotationReading::setX(qreal x)
{
d->x = x;
}
/*!
\property QRotationReading::y
\brief the rotation around the y axis.
Measured as degrees.
\sa {QRotationReading Units}
*/
qreal QRotationReading::y() const
{
return d->y;
}
/*!
Sets the rotation around the y axis to \a y.
*/
void QRotationReading::setY(qreal y)
{
d->y = y;
}
/*!
\property QRotationReading::z
\brief the rotation around the z axis.
Measured as degrees.
\sa {QRotationReading Units}
*/
qreal QRotationReading::z() const
{
return d->z;
}
/*!
Sets the rotation around the z axis to \a z.
*/
void QRotationReading::setZ(qreal z)
{
d->z = z;
}
// =====================================================================
/*!
\class QRotationFilter
\ingroup sensors_filter
\preliminary
\brief The QRotationFilter class is a convenience wrapper around QSensorFilter.
The only difference is that the filter() method features a pointer to QRotationReading
instead of QSensorReading.
*/
/*!
\fn QRotationFilter::filter(QRotationReading *reading)
Called when \a reading changes. Returns false to prevent the reading from propagating.
\sa QSensorFilter::filter()
*/
const char *QRotationSensor::type("QRotationSensor");
/*!
\class QRotationSensor
\ingroup sensors_type
\preliminary
\brief The QRotationSensor class is a convenience wrapper around QSensor.
The only behavioural difference is that this class sets the type properly.
This class also features a reading() function that returns a QRotationReading instead of a QSensorReading.
For details about how the sensor works, see \l QRotationReading.
\sa QRotationReading
*/
/*!
\fn QRotationSensor::QRotationSensor(QObject *parent)
Construct the sensor as a child of \a parent.
*/
/*!
\fn QRotationSensor::~QRotationSensor()
Destroy the sensor. Stops the sensor if it has not already been stopped.
*/
/*!
\fn QRotationSensor::reading() const
Returns the reading class for this sensor.
\sa QSensor::reading()
*/
/*!
\property QRotationSensor::hasZ
\brief a value indicating if the z angle is available.
Returns true if z is available.
Returns false if z is not available.
*/
#include "moc_qrotationsensor.cpp"
QTM_END_NAMESPACE
|
Update the rotation limits.
|
Update the rotation limits.
Also note the consequence of X = -90 or X = 90 to the Y angle.
Fixes: MOBILITY-855
|
C++
|
lgpl-2.1
|
kaltsi/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility
|
df86b49c5019c31216ba081aad1b2b38bcbbd25b
|
lib/node_modules/@stdlib/math/base/special/betainc/test/fixtures/cpp/runner.cpp
|
lib/node_modules/@stdlib/math/base/special/betainc/test/fixtures/cpp/runner.cpp
|
#include <random>
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <boost/math/special_functions/beta.hpp>
using namespace std;
vector<double> linspace( double start, double end, int num ) {
double delta = (end - start) / (num - 1);
vector<double> arr( num - 1 );
for ( int i = 0; i < num - 1; ++i ){
arr[ i ] = start + delta * i;
}
arr.push_back( end );
return arr;
}
void print_vector( vector<double> vec, bool last = false ) {
int precision = std::numeric_limits<double>::max_digits10;
cout << "[";
for ( vector<double>::iterator it = vec.begin(); it != vec.end(); ++it ) {
if ( vec.end() != it+1 ) {
cout << setprecision( precision ) << *it;
cout << ",";
} else {
cout << setprecision( precision ) << *it;
cout << "]";
if ( last == false ) {
cout << ",";
}
}
}
return;
}
void print_results(
vector<double> x,
vector<double> a,
vector<double> b,
vector<double> lower_regularized,
vector<double> upper_regularized,
vector<double> lower_unregularized,
vector<double> upper_unregularized
) {
cout << "{" << endl;
cout << " \"x\": ";
print_vector( x );
cout << " \"a\": ";
print_vector( a );
cout << " \"b\": ";
print_vector( b );
cout << " \"lower_regularized\": ";
print_vector( lower_regularized );
cout << " \"upper_regularized\": ";
print_vector( upper_regularized );
cout << " \"lower_unregularized\": ";
print_vector( lower_unregularized );
cout << " \"upper_unregularized\": ";
print_vector( upper_unregularized, true );
cout << "}" << endl;
return;
}
int main() {
random_device rd;
mt19937 g(rd());
vector<double> x = linspace( 0.001, 0.999, 1000 );
shuffle( x.begin(), x.end(), g );
vector<double> a = linspace( 1.0, 40.0, 1000 );
shuffle( a.begin(), a.end(), g );
vector<double> b = linspace( 1.0, 40.0, 1000 );
shuffle( b.begin(), b.end(), g );
vector<double> lower_regularized;
vector<double> upper_regularized;
vector<double> lower_unregularized;
vector<double> upper_unregularized;
for ( int i = 0; i < 1000; i++ ) {
double arg1 = a[ i ];
double arg2 = b[ i ];
double arg3 = x[ i ];
lower_regularized.push_back( boost::math::ibeta( arg1, arg2, arg3 ) );
upper_regularized.push_back( boost::math::ibetac( arg1, arg2, arg3 ) );
lower_unregularized.push_back( boost::math::beta( arg1, arg2, arg3 ) );
upper_unregularized.push_back( boost::math::betac( arg1, arg2, arg3 ) );
}
print_results( x, a, b, lower_regularized, upper_regularized, lower_unregularized, upper_unregularized );
return 0;
}
|
#include <random>
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <boost/math/special_functions/beta.hpp>
using namespace std;
/**
* Generates a linearly spaced numeric array.
*
* @param start first array value
* @param end last array value
* @param num length of output array
* @return linearly spaced numeric array
*/
vector<double> linspace( double start, double end, int num ) {
double delta = (end - start) / (num - 1);
vector<double> arr( num - 1 );
for ( int i = 0; i < num - 1; ++i ){
arr[ i ] = start + delta * i;
}
arr.push_back( end );
return arr;
}
/**
* Prints the elements of a vector as JSON.
*
* @param vec input vector
* @param last boolean indicating whether last vector in JSON object
* @return string representation of vector for JSON output
*/
void print_vector( vector<double> vec, bool last = false ) {
int precision = std::numeric_limits<double>::max_digits10;
cout << "[";
for ( vector<double>::iterator it = vec.begin(); it != vec.end(); ++it ) {
if ( vec.end() != it+1 ) {
cout << setprecision( precision ) << *it;
cout << ",";
} else {
cout << setprecision( precision ) << *it;
cout << "]";
if ( last == false ) {
cout << ",";
}
}
}
return;
}
/**
* Prints the results as JSON.
*
* @param x input values
* @param a input values
* @param b input values
* @param lower_regularized lower regularized incomplete beta function
* @param upper_regularized upper regularized incomplete beta function
* @param lower_unregularized lower unregularized incomplete beta function
* @param upper_unregularized upper unregularized incomplete beta function
* @return JSON string
*/
void print_results(
vector<double> x,
vector<double> a,
vector<double> b,
vector<double> lower_regularized,
vector<double> upper_regularized,
vector<double> lower_unregularized,
vector<double> upper_unregularized
) {
cout << "{" << endl;
cout << " \"x\": ";
print_vector( x );
cout << " \"a\": ";
print_vector( a );
cout << " \"b\": ";
print_vector( b );
cout << " \"lower_regularized\": ";
print_vector( lower_regularized );
cout << " \"upper_regularized\": ";
print_vector( upper_regularized );
cout << " \"lower_unregularized\": ";
print_vector( lower_unregularized );
cout << " \"upper_unregularized\": ";
print_vector( upper_unregularized, true );
cout << "}" << endl;
return;
}
/**
* Main execution sequence.
*/
int main() {
random_device rd;
mt19937 g(rd());
vector<double> x = linspace( 0.001, 0.999, 1000 );
shuffle( x.begin(), x.end(), g );
vector<double> a = linspace( 1.0, 40.0, 1000 );
shuffle( a.begin(), a.end(), g );
vector<double> b = linspace( 1.0, 40.0, 1000 );
shuffle( b.begin(), b.end(), g );
vector<double> lower_regularized;
vector<double> upper_regularized;
vector<double> lower_unregularized;
vector<double> upper_unregularized;
for ( int i = 0; i < 1000; i++ ) {
double arg1 = a[ i ];
double arg2 = b[ i ];
double arg3 = x[ i ];
lower_regularized.push_back( boost::math::ibeta( arg1, arg2, arg3 ) );
upper_regularized.push_back( boost::math::ibetac( arg1, arg2, arg3 ) );
lower_unregularized.push_back( boost::math::beta( arg1, arg2, arg3 ) );
upper_unregularized.push_back( boost::math::betac( arg1, arg2, arg3 ) );
}
print_results( x, a, b, lower_regularized, upper_regularized, lower_unregularized, upper_unregularized );
return 0;
}
|
Add annotations
|
Add annotations
|
C++
|
apache-2.0
|
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
|
fba3391e382834657d23c48d5df4776afdad6f93
|
src/signal_scope/plotwidget.cpp
|
src/signal_scope/plotwidget.cpp
|
#include "plotwidget.h"
#include "plot.h"
#include "signalhandler.h"
#include "signaldata.h"
#include "setscaledialog.h"
#include "selectsignaldialog.h"
#include "signaldescription.h"
#include "pythonchannelsubscribercollection.h"
#include <qwt_scale_engine.h>
#include <qlabel.h>
#include <qlayout.h>
#include <QDoubleSpinBox>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QInputDialog>
#include <QDialogButtonBox>
#include <QListWidget>
#include <QTimer>
#include <QPushButton>
#include <QColorDialog>
PlotWidget::PlotWidget(PythonChannelSubscriberCollection* subscribers, QWidget *parent):
QWidget(parent),
mSubscribers(subscribers)
{
d_plot = new Plot(this);
mColors << Qt::green
<< Qt::red
<< Qt::blue
<< Qt::cyan
<< Qt::magenta
<< Qt::darkYellow
<< QColor(139, 69, 19) // brown
<< Qt::darkCyan
<< Qt::darkGreen
<< Qt::darkMagenta
<< Qt::black;
mTimeWindowSpin = new QDoubleSpinBox;
mTimeWindowSpin->setSingleStep(0.1);
QDoubleSpinBox* yScaleSpin = new QDoubleSpinBox;
yScaleSpin->setSingleStep(0.1);
QVBoxLayout* vLayout1 = new QVBoxLayout();
//QPushButton* resetYScaleButton = new QPushButton("Reset Y scale");
//vLayout1->addWidget(resetYScaleButton);
QWidget* frameWidget = new QWidget;
QHBoxLayout* frameLayout = new QHBoxLayout(frameWidget);
frameWidget->setContentsMargins(0, 0, 0, 0);
frameLayout->addWidget(new QLabel("Time Window [s]:"));
frameLayout->addWidget(mTimeWindowSpin);
vLayout1->addWidget(frameWidget);
mSignalListWidget = new QListWidget(this);
vLayout1->addWidget(mSignalListWidget);
mSignalInfoLabel = new QLabel(this);
vLayout1->addWidget(mSignalInfoLabel);
vLayout1->addStretch(10);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(d_plot, 10);
layout->addLayout(vLayout1);
mTimeWindowSpin->setValue(d_plot->timeWindow());
connect(mTimeWindowSpin, SIGNAL(valueChanged(double)),
d_plot, SLOT(setTimeWindow(double)));
connect(d_plot, SIGNAL(syncXAxisScale(double, double)),
this, SIGNAL(syncXAxisScale(double, double)));
//connect(yScaleSpin, SIGNAL(valueChanged(double)),
// d_plot, SLOT(setYScale(double)));
//yScaleSpin->setValue(10.0);
this->setContextMenuPolicy(Qt::CustomContextMenu);
this->connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
SLOT(onShowContextMenu(const QPoint&)));
mSignalListWidget->setDragDropMode(QAbstractItemView::DragDrop);
mSignalListWidget->setDragEnabled(true);
mSignalListWidget->setDefaultDropAction(Qt::MoveAction);
mSignalListWidget->setContextMenuPolicy(Qt::CustomContextMenu);
this->connect(mSignalListWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
SLOT(onShowSignalContextMenu(const QPoint&)));
this->connect(mSignalListWidget, SIGNAL(itemChanged(QListWidgetItem *)), SLOT(onSignalListItemChanged(QListWidgetItem*)));
QTimer* labelUpdateTimer = new QTimer(this);
this->connect(labelUpdateTimer, SIGNAL(timeout()), SLOT(updateSignalInfoLabel()));
labelUpdateTimer->start(100);
}
void PlotWidget::onShowContextMenu(const QPoint& pos)
{
QPoint globalPos = this->mapToGlobal(pos);
// for QAbstractScrollArea and derived classes you would use:
// QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);
QMenu myMenu;
myMenu.addAction("Add signal");
myMenu.addSeparator();
myMenu.addAction("Reset Y axis scale");
myMenu.addAction("Set Y axis scale");
myMenu.addSeparator();
myMenu.addAction("Remove plot");
QAction* selectedItem = myMenu.exec(globalPos);
if (!selectedItem)
{
return;
}
QString selectedAction = selectedItem->text();
if (selectedAction == "Remove plot")
{
emit this->removePlotRequested(this);
}
else if (selectedAction == "Add signal")
{
emit this->addSignalRequested(this);
}
else if (selectedAction == "Reset Y axis scale")
{
this->onResetYAxisScale();
}
else if (selectedAction == "Set Y axis scale")
{
SetScaleDialog dialog(this);
QwtInterval axisInterval = d_plot->axisInterval(QwtPlot::yLeft);
dialog.setUpper(axisInterval.maxValue());
dialog.setLower(axisInterval.minValue());
int result = dialog.exec();
if (result == QDialog::Accepted)
{
d_plot->setAxisScale(QwtPlot::yLeft, dialog.lower(), dialog.upper());
}
}
}
QList<SignalHandler*> PlotWidget::signalHandlers()
{
QList<SignalHandler*> handlers;
for (int i = 0; i < mSignalListWidget->count(); ++i)
{
handlers.append(mSignals[mSignalListWidget->item(i)]);
}
return handlers;
}
void PlotWidget::onShowSignalContextMenu(const QPoint& pos)
{
if (mSignals.empty())
{
return;
}
QPoint globalPos = mSignalListWidget->mapToGlobal(pos);
// for QAbstractScrollArea and derived classes you would use:
// QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);
QMenu myMenu;
myMenu.addAction("Change color");
myMenu.addSeparator();
myMenu.addAction("Remove signal");
QAction* selectedItem = myMenu.exec(globalPos);
if (!selectedItem)
{
return;
}
QString selectedAction = selectedItem->text();
if (selectedAction == "Change color")
{
QListWidgetItem* signalItem = mSignalListWidget->currentItem();
SignalHandler* signalHandler = signalItem->data(Qt::UserRole).value<SignalHandler*>();
QColor initialColor = signalHandler->signalDescription()->mColor;
QColor newColor = QColorDialog::getColor(initialColor, this, "Choose signal color");
if (newColor.isValid())
{
signalHandler->signalDescription()->mColor = newColor;
QPixmap pixmap(24, 24);
pixmap.fill(newColor);
signalItem->setIcon(QIcon(pixmap));
d_plot->setSignalColor(signalHandler->signalData(), newColor);
}
}
else if (selectedAction == "Remove signal")
{
QListWidgetItem* signalItem = mSignalListWidget->currentItem();
SignalHandler* signalHandler = this->signalForItem(signalItem);
mSubscribers->removeSignalHandler(signalHandler);
d_plot->removeSignal(signalHandler->signalData());
mSignals.remove(signalItem);
delete signalItem;
delete signalHandler;
}
}
void PlotWidget::updateSignalInfoLabel()
{
mSignalInfoLabel->setText(QString());
QListWidgetItem* selectedItem = mSignalListWidget->currentItem();
if (!selectedItem)
{
return;
}
SignalHandler* signalHandler = selectedItem->data(Qt::UserRole).value<SignalHandler*>();
SignalData* signalData = signalHandler->signalData();
QString signalValue = "No data";
int numberOfValues = signalData->size();
if (numberOfValues)
{
signalValue = QString::number(signalData->value(numberOfValues-1).y(), 'g', 6);
}
QString signalInfoText = QString("Freq: %1 Val: %2").arg(QString::number(signalData->messageFrequency(), 'f', 1)).arg(signalValue);
mSignalInfoLabel->setText(signalInfoText);
}
void PlotWidget::setEndTime(double endTime)
{
d_plot->setEndTime(endTime);
}
void PlotWidget::setXAxisScale(double x0, double x1)
{
d_plot->setAxisScale(QwtPlot::xBottom, x0, x1);
}
void PlotWidget::replot()
{
d_plot->replot();
}
void PlotWidget::onResetYAxisScale()
{
}
void PlotWidget::onSignalListItemChanged(QListWidgetItem* item)
{
SignalHandler* signalHandler = this->signalForItem(item);
bool checked = (item->checkState() == Qt::Checked);
d_plot->setSignalVisible(signalHandler->signalData(), checked);
}
QListWidgetItem* PlotWidget::itemForSignal(SignalHandler* signalHandler)
{
return mSignals.key(signalHandler);
}
SignalHandler* PlotWidget::signalForItem(QListWidgetItem* item)
{
return mSignals.value(item);
}
bool PlotWidget::signalIsVisible(SignalHandler* signalHandler)
{
if (!signalHandler)
{
return false;
}
return (this->itemForSignal(signalHandler)->checkState() == Qt::Checked);
}
void PlotWidget::setSignalVisibility(SignalHandler* signalHandler, bool visible)
{
QListWidgetItem* item = this->itemForSignal(signalHandler);
if (item)
{
item->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
}
}
void PlotWidget::start()
{
d_plot->start();
}
void PlotWidget::stop()
{
d_plot->stop();
}
void PlotWidget::clearHistory()
{
foreach (SignalHandler* handler, this->signalHandlers())
{
handler->signalData()->clear();
}
d_plot->replot();
}
void PlotWidget::setBackgroundColor(QString color)
{
d_plot->setBackgroundColor(color);
}
void PlotWidget::setPointSize(double pointSize)
{
d_plot->setPointSize(pointSize);
}
void PlotWidget::addSignal(const QMap<QString, QVariant>& signalSettings)
{
SignalDescription desc;
desc.mChannel = signalSettings.value("channel").toString();
desc.mMessageType = signalSettings.value("messageType").toString();
desc.mFieldName = signalSettings.value("fieldName").toString();
desc.mArrayKeys = signalSettings.value("arrayKeys").toStringList();
QList<QVariant> color = signalSettings.value("color").toList();
if (color.size() == 3)
{
desc.mColor = QColor::fromRgb(color[0].toInt(), color[1].toInt(), color[2].toInt());
}
bool visible = signalSettings.value("visible", true).toBool();
SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&desc);
if (signalHandler)
{
//printf("adding signal: %s\n", qPrintable(signalHandler->description()));
}
else
{
printf("failed to create signal from signal settings.\n");
}
this->addSignal(signalHandler);
this->setSignalVisibility(signalHandler, visible);
}
Q_DECLARE_METATYPE(SignalHandler*);
void PlotWidget::addSignal(SignalHandler* signalHandler)
{
if (!signalHandler)
{
return;
}
QColor color = signalHandler->signalDescription()->mColor;
if (!color.isValid())
{
int signalColorIndex = mSignals.size() % mColors.size();
color = mColors[signalColorIndex];
signalHandler->signalDescription()->mColor = color;
}
QString signalDescription = QString("%2 [%1]").arg(signalHandler->channel()).arg(signalHandler->description().split(".").back());
QListWidgetItem* signalItem = new QListWidgetItem(signalDescription);
mSignalListWidget->addItem(signalItem);
mSignals[signalItem] = signalHandler;
mSubscribers->addSignalHandler(signalHandler);
d_plot->addSignal(signalHandler->signalData(), color);
QPixmap pixmap(24, 24);
pixmap.fill(color);
signalItem->setIcon(QIcon(pixmap));
signalItem->setData(Qt::UserRole, qVariantFromValue(signalHandler));
signalItem->setData(Qt::CheckStateRole, Qt::Checked);
}
void PlotWidget::loadSettings(const QMap<QString, QVariant>& plotSettings)
{
QList<QVariant> signalList = plotSettings.value("signals").toList();
foreach (const QVariant& signalVariant, signalList)
{
this->addSignal(signalVariant.toMap());
}
double timeWindow = plotSettings.value("timeWindow", QVariant(10.0)).toDouble();
double ymin = plotSettings.value("ymin", QVariant(-10.0)).toDouble();
double ymax = plotSettings.value("ymax", QVariant(10.0)).toDouble();
d_plot->setAxisScale(QwtPlot::yLeft, ymin, ymax);
mTimeWindowSpin->setValue(timeWindow);
if (plotSettings.value("curveStyle", "dots") == "lines")
{
d_plot->setCurveStyle(QwtPlotCurve::Lines);
}
}
QMap<QString, QVariant> PlotWidget::saveSettings()
{
QMap<QString, QVariant> settings;
settings["ymin"] = d_plot->axisInterval(QwtPlot::yLeft).minValue();
settings["ymax"] = d_plot->axisInterval(QwtPlot::yLeft).maxValue();
settings["timeWindow"] = d_plot->timeWindow();
QList<QVariant> signalSettings;
foreach (SignalHandler* signalHandler, this->signalHandlers())
{
signalSettings.append(this->saveSignalSettings(signalHandler));
}
settings["signals"] = signalSettings;
return settings;
}
QMap<QString, QVariant> PlotWidget::saveSignalSettings(SignalHandler* signalHandler)
{
QMap<QString, QVariant> settings;
SignalDescription* signalDescription = signalHandler->signalDescription();
settings["channel"] = signalDescription->mChannel;
settings["messageType"] = signalDescription->mMessageType;
settings["fieldName"] = signalDescription->mFieldName;
settings["arrayKeys"] = QVariant(signalDescription->mArrayKeys);
settings["visible"] = QVariant(this->itemForSignal(signalHandler)->checkState() == Qt::Checked);
QList<QVariant> color;
color << signalDescription->mColor.red() << signalDescription->mColor.green() << signalDescription->mColor.blue();
settings["color"] = color;
return settings;
}
|
#include "plotwidget.h"
#include "plot.h"
#include "signalhandler.h"
#include "signaldata.h"
#include "setscaledialog.h"
#include "selectsignaldialog.h"
#include "signaldescription.h"
#include "pythonchannelsubscribercollection.h"
#include <qwt_scale_engine.h>
#include <qlabel.h>
#include <qlayout.h>
#include <QDoubleSpinBox>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QInputDialog>
#include <QDialogButtonBox>
#include <QListWidget>
#include <QTimer>
#include <QPushButton>
#include <QColorDialog>
PlotWidget::PlotWidget(PythonChannelSubscriberCollection* subscribers, QWidget *parent):
QWidget(parent),
mSubscribers(subscribers)
{
d_plot = new Plot(this);
mColors << Qt::green
<< Qt::red
<< Qt::blue
<< Qt::cyan
<< Qt::magenta
<< Qt::darkYellow
<< QColor(139, 69, 19) // brown
<< Qt::darkCyan
<< Qt::darkGreen
<< Qt::darkMagenta
<< Qt::black;
mTimeWindowSpin = new QDoubleSpinBox;
mTimeWindowSpin->setSingleStep(0.1);
QDoubleSpinBox* yScaleSpin = new QDoubleSpinBox;
yScaleSpin->setSingleStep(0.1);
QVBoxLayout* vLayout1 = new QVBoxLayout();
//QPushButton* resetYScaleButton = new QPushButton("Reset Y scale");
//vLayout1->addWidget(resetYScaleButton);
QWidget* frameWidget = new QWidget;
QHBoxLayout* frameLayout = new QHBoxLayout(frameWidget);
frameWidget->setContentsMargins(0, 0, 0, 0);
frameLayout->addWidget(new QLabel("Time Window [s]:"));
frameLayout->addWidget(mTimeWindowSpin);
vLayout1->addWidget(frameWidget);
mSignalListWidget = new QListWidget(this);
vLayout1->addWidget(mSignalListWidget);
mSignalInfoLabel = new QLabel(this);
vLayout1->addWidget(mSignalInfoLabel);
vLayout1->addStretch(10);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(d_plot, 10);
layout->addLayout(vLayout1);
mTimeWindowSpin->setValue(d_plot->timeWindow());
connect(mTimeWindowSpin, SIGNAL(valueChanged(double)),
d_plot, SLOT(setTimeWindow(double)));
connect(d_plot, SIGNAL(syncXAxisScale(double, double)),
this, SIGNAL(syncXAxisScale(double, double)));
//connect(yScaleSpin, SIGNAL(valueChanged(double)),
// d_plot, SLOT(setYScale(double)));
//yScaleSpin->setValue(10.0);
this->setContextMenuPolicy(Qt::CustomContextMenu);
this->connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
SLOT(onShowContextMenu(const QPoint&)));
//mSignalListWidget->setDragDropMode(QAbstractItemView::DragDrop);
//mSignalListWidget->setDragEnabled(true);
//mSignalListWidget->setDefaultDropAction(Qt::MoveAction);
mSignalListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
mSignalListWidget->setContextMenuPolicy(Qt::CustomContextMenu);
this->connect(mSignalListWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
SLOT(onShowSignalContextMenu(const QPoint&)));
this->connect(mSignalListWidget, SIGNAL(itemChanged(QListWidgetItem *)), SLOT(onSignalListItemChanged(QListWidgetItem*)));
QTimer* labelUpdateTimer = new QTimer(this);
this->connect(labelUpdateTimer, SIGNAL(timeout()), SLOT(updateSignalInfoLabel()));
labelUpdateTimer->start(100);
}
void PlotWidget::onShowContextMenu(const QPoint& pos)
{
QPoint globalPos = this->mapToGlobal(pos);
// for QAbstractScrollArea and derived classes you would use:
// QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);
QMenu myMenu;
myMenu.addAction("Add signal");
myMenu.addSeparator();
myMenu.addAction("Reset Y axis scale");
myMenu.addAction("Set Y axis scale");
myMenu.addSeparator();
myMenu.addAction("Remove plot");
QAction* selectedItem = myMenu.exec(globalPos);
if (!selectedItem)
{
return;
}
QString selectedAction = selectedItem->text();
if (selectedAction == "Remove plot")
{
emit this->removePlotRequested(this);
}
else if (selectedAction == "Add signal")
{
emit this->addSignalRequested(this);
}
else if (selectedAction == "Reset Y axis scale")
{
this->onResetYAxisScale();
}
else if (selectedAction == "Set Y axis scale")
{
SetScaleDialog dialog(this);
QwtInterval axisInterval = d_plot->axisInterval(QwtPlot::yLeft);
dialog.setUpper(axisInterval.maxValue());
dialog.setLower(axisInterval.minValue());
int result = dialog.exec();
if (result == QDialog::Accepted)
{
d_plot->setAxisScale(QwtPlot::yLeft, dialog.lower(), dialog.upper());
}
}
}
QList<SignalHandler*> PlotWidget::signalHandlers()
{
QList<SignalHandler*> handlers;
for (int i = 0; i < mSignalListWidget->count(); ++i)
{
handlers.append(mSignals[mSignalListWidget->item(i)]);
}
return handlers;
}
void PlotWidget::onShowSignalContextMenu(const QPoint& pos)
{
if (mSignals.empty())
{
return;
}
QPoint globalPos = mSignalListWidget->mapToGlobal(pos);
// for QAbstractScrollArea and derived classes you would use:
// QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);
QMenu myMenu;
if (mSignalListWidget->selectedItems().size() == 1)
{
myMenu.addAction("Change color");
myMenu.addSeparator();
}
myMenu.addAction("Remove signal");
QAction* selectedItem = myMenu.exec(globalPos);
if (!selectedItem)
{
return;
}
QString selectedAction = selectedItem->text();
if (selectedAction == "Change color")
{
QListWidgetItem* signalItem = mSignalListWidget->currentItem();
SignalHandler* signalHandler = signalItem->data(Qt::UserRole).value<SignalHandler*>();
QColor initialColor = signalHandler->signalDescription()->mColor;
QColor newColor = QColorDialog::getColor(initialColor, this, "Choose signal color");
if (newColor.isValid())
{
signalHandler->signalDescription()->mColor = newColor;
QPixmap pixmap(24, 24);
pixmap.fill(newColor);
signalItem->setIcon(QIcon(pixmap));
d_plot->setSignalColor(signalHandler->signalData(), newColor);
}
}
else if (selectedAction == "Remove signal")
{
QList<QListWidgetItem*> selectedItems = mSignalListWidget->selectedItems();
foreach (QListWidgetItem* selectedItem, selectedItems)
{
QListWidgetItem* signalItem = mSignalListWidget->currentItem();
SignalHandler* signalHandler = this->signalForItem(signalItem);
mSubscribers->removeSignalHandler(signalHandler);
d_plot->removeSignal(signalHandler->signalData());
mSignals.remove(signalItem);
delete signalItem;
delete signalHandler;
}
}
}
void PlotWidget::updateSignalInfoLabel()
{
mSignalInfoLabel->setText(QString());
QListWidgetItem* selectedItem = mSignalListWidget->currentItem();
if (!selectedItem)
{
return;
}
SignalHandler* signalHandler = selectedItem->data(Qt::UserRole).value<SignalHandler*>();
SignalData* signalData = signalHandler->signalData();
QString signalValue = "No data";
int numberOfValues = signalData->size();
if (numberOfValues)
{
signalValue = QString::number(signalData->value(numberOfValues-1).y(), 'g', 6);
}
QString signalInfoText = QString("Freq: %1 Val: %2").arg(QString::number(signalData->messageFrequency(), 'f', 1)).arg(signalValue);
mSignalInfoLabel->setText(signalInfoText);
}
void PlotWidget::setEndTime(double endTime)
{
d_plot->setEndTime(endTime);
}
void PlotWidget::setXAxisScale(double x0, double x1)
{
d_plot->setAxisScale(QwtPlot::xBottom, x0, x1);
}
void PlotWidget::replot()
{
d_plot->replot();
}
void PlotWidget::onResetYAxisScale()
{
}
void PlotWidget::onSignalListItemChanged(QListWidgetItem* item)
{
SignalHandler* signalHandler = this->signalForItem(item);
Qt::CheckState checkState = item->checkState();
if (!item->isSelected())
{
mSignalListWidget->clearSelection();
item->setSelected(true);
}
QList<QListWidgetItem*> selectedItems = mSignalListWidget->selectedItems();
foreach (QListWidgetItem* selectedItem, selectedItems)
{
SignalHandler* signalHandler = this->signalForItem(selectedItem);
selectedItem->setCheckState(checkState);
d_plot->setSignalVisible(signalHandler->signalData(), checkState == Qt::Checked);
}
}
QListWidgetItem* PlotWidget::itemForSignal(SignalHandler* signalHandler)
{
return mSignals.key(signalHandler);
}
SignalHandler* PlotWidget::signalForItem(QListWidgetItem* item)
{
return mSignals.value(item);
}
bool PlotWidget::signalIsVisible(SignalHandler* signalHandler)
{
if (!signalHandler)
{
return false;
}
return (this->itemForSignal(signalHandler)->checkState() == Qt::Checked);
}
void PlotWidget::setSignalVisibility(SignalHandler* signalHandler, bool visible)
{
QListWidgetItem* item = this->itemForSignal(signalHandler);
if (item)
{
item->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
}
}
void PlotWidget::start()
{
d_plot->start();
}
void PlotWidget::stop()
{
d_plot->stop();
}
void PlotWidget::clearHistory()
{
foreach (SignalHandler* handler, this->signalHandlers())
{
handler->signalData()->clear();
}
d_plot->replot();
}
void PlotWidget::setBackgroundColor(QString color)
{
d_plot->setBackgroundColor(color);
}
void PlotWidget::setPointSize(double pointSize)
{
d_plot->setPointSize(pointSize);
}
void PlotWidget::addSignal(const QMap<QString, QVariant>& signalSettings)
{
SignalDescription desc;
desc.mChannel = signalSettings.value("channel").toString();
desc.mMessageType = signalSettings.value("messageType").toString();
desc.mFieldName = signalSettings.value("fieldName").toString();
desc.mArrayKeys = signalSettings.value("arrayKeys").toStringList();
QList<QVariant> color = signalSettings.value("color").toList();
if (color.size() == 3)
{
desc.mColor = QColor::fromRgb(color[0].toInt(), color[1].toInt(), color[2].toInt());
}
bool visible = signalSettings.value("visible", true).toBool();
SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&desc);
if (signalHandler)
{
//printf("adding signal: %s\n", qPrintable(signalHandler->description()));
}
else
{
printf("failed to create signal from signal settings.\n");
}
this->addSignal(signalHandler);
this->setSignalVisibility(signalHandler, visible);
}
Q_DECLARE_METATYPE(SignalHandler*);
void PlotWidget::addSignal(SignalHandler* signalHandler)
{
if (!signalHandler)
{
return;
}
QColor color = signalHandler->signalDescription()->mColor;
if (!color.isValid())
{
int signalColorIndex = mSignals.size() % mColors.size();
color = mColors[signalColorIndex];
signalHandler->signalDescription()->mColor = color;
}
QString signalDescription = QString("%2 [%1]").arg(signalHandler->channel()).arg(signalHandler->description().split(".").back());
QListWidgetItem* signalItem = new QListWidgetItem(signalDescription);
mSignalListWidget->addItem(signalItem);
mSignals[signalItem] = signalHandler;
mSubscribers->addSignalHandler(signalHandler);
d_plot->addSignal(signalHandler->signalData(), color);
QPixmap pixmap(24, 24);
pixmap.fill(color);
signalItem->setIcon(QIcon(pixmap));
signalItem->setData(Qt::UserRole, qVariantFromValue(signalHandler));
signalItem->setData(Qt::CheckStateRole, Qt::Checked);
}
void PlotWidget::loadSettings(const QMap<QString, QVariant>& plotSettings)
{
QList<QVariant> signalList = plotSettings.value("signals").toList();
foreach (const QVariant& signalVariant, signalList)
{
this->addSignal(signalVariant.toMap());
}
double timeWindow = plotSettings.value("timeWindow", QVariant(10.0)).toDouble();
double ymin = plotSettings.value("ymin", QVariant(-10.0)).toDouble();
double ymax = plotSettings.value("ymax", QVariant(10.0)).toDouble();
d_plot->setAxisScale(QwtPlot::yLeft, ymin, ymax);
mTimeWindowSpin->setValue(timeWindow);
if (plotSettings.value("curveStyle", "dots") == "lines")
{
d_plot->setCurveStyle(QwtPlotCurve::Lines);
}
}
QMap<QString, QVariant> PlotWidget::saveSettings()
{
QMap<QString, QVariant> settings;
settings["ymin"] = d_plot->axisInterval(QwtPlot::yLeft).minValue();
settings["ymax"] = d_plot->axisInterval(QwtPlot::yLeft).maxValue();
settings["timeWindow"] = d_plot->timeWindow();
QList<QVariant> signalSettings;
foreach (SignalHandler* signalHandler, this->signalHandlers())
{
signalSettings.append(this->saveSignalSettings(signalHandler));
}
settings["signals"] = signalSettings;
return settings;
}
QMap<QString, QVariant> PlotWidget::saveSignalSettings(SignalHandler* signalHandler)
{
QMap<QString, QVariant> settings;
SignalDescription* signalDescription = signalHandler->signalDescription();
settings["channel"] = signalDescription->mChannel;
settings["messageType"] = signalDescription->mMessageType;
settings["fieldName"] = signalDescription->mFieldName;
settings["arrayKeys"] = QVariant(signalDescription->mArrayKeys);
settings["visible"] = QVariant(this->itemForSignal(signalHandler)->checkState() == Qt::Checked);
QList<QVariant> color;
color << signalDescription->mColor.red() << signalDescription->mColor.green() << signalDescription->mColor.blue();
settings["color"] = color;
return settings;
}
|
support multiselect in the signal list widget
|
support multiselect in the signal list widget
multiselect supports check/uncheck of multiple signals and removing
multiple signals
|
C++
|
bsd-3-clause
|
mitdrc/signal-scope,openhumanoids/signal-scope,mitdrc/signal-scope,openhumanoids/signal-scope,openhumanoids/signal-scope,mitdrc/signal-scope
|
38aacc4d8992783d5e838bf92fa7d6395e84840d
|
tester/libtbag/dom/json/JsonUtilsTest.cpp
|
tester/libtbag/dom/json/JsonUtilsTest.cpp
|
/**
* @file JsonUtilsTest.cpp
* @brief JsonUtils class tester.
* @author zer0
* @date 2019-06-16
*/
#include <gtest/gtest.h>
#include <libtbag/dom/json/JsonUtils.hpp>
using namespace libtbag;
using namespace libtbag::dom;
using namespace libtbag::dom::json;
TEST(JsonUtilsTest, Default)
{
char const * const TEST_JSON_TEXT = R"({"key":"value"})";
Json::Value value;
ASSERT_TRUE(parse(TEST_JSON_TEXT, value));
auto const JSON_TEXT = writeFast(value);
ASSERT_STREQ(TEST_JSON_TEXT, JSON_TEXT.c_str());
}
TEST(JsonUtilsTest, DoNotUseTheDropNull)
{
char const * const TEST_JSON_TEXT = R"({"key":null})";
Json::Value value;
ASSERT_TRUE(parse(TEST_JSON_TEXT, value));
auto const JSON_TEXT = writeFast(value);
ASSERT_STREQ(TEST_JSON_TEXT, JSON_TEXT.c_str());
}
TEST(JsonUtilsTest, OptErr)
{
char const * const TEST_JSON_TEXT = R"({"key":"warning"})";
Json::Value value;
ASSERT_TRUE(parse(TEST_JSON_TEXT, value));
ASSERT_EQ(E_WARNING, optErr(value["key"]));
}
|
/**
* @file JsonUtilsTest.cpp
* @brief JsonUtils class tester.
* @author zer0
* @date 2019-06-16
*/
#include <gtest/gtest.h>
#include <libtbag/dom/json/JsonUtils.hpp>
using namespace libtbag;
using namespace libtbag::dom;
using namespace libtbag::dom::json;
TEST(JsonUtilsTest, Path)
{
char const * const TEST_JSON_TEXT = R"(
{
"key1": { "temp": 1 },
"key2": { "temp": 2 },
"key3": { "temp": 3 }
})";
Json::Value original;
ASSERT_TRUE(parse(TEST_JSON_TEXT, original));
Json::Path path1(".key1.temp");
auto const value1 = path1.make(original);
ASSERT_TRUE(value1.isInt());
ASSERT_EQ(1, value1.asInt());
Json::Path path2(".key2.temp");
auto const value2 = path2.make(original);
ASSERT_TRUE(value2.isInt());
ASSERT_EQ(2, value2.asInt());
Json::Path path3(".key3.temp");
auto const value3 = path3.make(original);
ASSERT_TRUE(value3.isInt());
ASSERT_EQ(3, value3.asInt());
Json::Path path_error(".test");
auto const value_error = path_error.make(original);
ASSERT_TRUE(value_error.isNull());
}
TEST(JsonUtilsTest, Default)
{
char const * const TEST_JSON_TEXT = R"({"key":"value"})";
Json::Value value;
ASSERT_TRUE(parse(TEST_JSON_TEXT, value));
auto const JSON_TEXT = writeFast(value);
ASSERT_STREQ(TEST_JSON_TEXT, JSON_TEXT.c_str());
}
TEST(JsonUtilsTest, DoNotUseTheDropNull)
{
char const * const TEST_JSON_TEXT = R"({"key":null})";
Json::Value value;
ASSERT_TRUE(parse(TEST_JSON_TEXT, value));
auto const JSON_TEXT = writeFast(value);
ASSERT_STREQ(TEST_JSON_TEXT, JSON_TEXT.c_str());
}
TEST(JsonUtilsTest, OptErr)
{
char const * const TEST_JSON_TEXT = R"({"key":"warning"})";
Json::Value value;
ASSERT_TRUE(parse(TEST_JSON_TEXT, value));
ASSERT_EQ(E_WARNING, optErr(value["key"]));
}
|
Create JsonUtilsTest.Path tester.
|
Create JsonUtilsTest.Path tester.
|
C++
|
mit
|
osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag
|
8ca89f1a1d1a5517af9068108f3ebabded8ca510
|
platform/shared/api_generator/StringfyHelper.cpp
|
platform/shared/api_generator/StringfyHelper.cpp
|
#include "StringfyHelper"
#include "json/JSONIterator.h"
namespace rho
{
namespace apiGenerator
{
using namespace rho::json;
using namespace rho::common;
void StringifyVector::push_back(const rho::String& value, bool escape)
{
m_bufferLen += 1;
if (escape)
{
m_vector.push_back(CJSONEntry::quoteValue(value));
m_bufferLen += m_vector.back().length();
} else {
m_vector.push_back(value);
m_bufferLen += value.length();
}
}
void StringifyVector::push_back(const IStringSerializable& value)
{
rho::String buffer;
value.toString(buffer);
push_back(buffer, false);
}
void StringifyVector::toString(rho::String &buffer) const
{
buffer.clear();
buffer.reserve(m_bufferLen + 2);
buffer += "[";
for(rho::Vector<rho::String>::const_iterator it = m_vector.begin(); it != m_vector.end(); it++)
{
if(it != m_vector.begin())
{
buffer += ",";
}
buffer += *it;
}
buffer += "]";
}
void StringifyHash::set(const rho::String& key, const rho::String& value, bool escape)
{
m_bufferLen += 3;
rho::String bk(CJSONEntry::quoteValue(key));
if (escape)
{
rho::String bv(CJSONEntry::quoteValue(value));
m_hash[bk] = bv;
m_bufferLen += bk.length() + bv.length();
} else {
m_hash[bk] = value;
m_bufferLen += bk.length() + value.length();
}
}
void StringifyHash::set(const rho::String& key, const IStringSerializable& value)
{
rho::String buffer;
value.toString(buffer);
set(key, buffer, false);
}
void StringifyHash::toString(rho::String &buffer) const
{
buffer.clear();
buffer.reserve(m_bufferLen + 2);
buffer += "{";
for(rho::Hashtable<rho::String, rho::String>::const_iterator it = m_hash.begin(); it != m_hash.end(); it++)
{
if(it != m_hash.begin())
{
buffer += ",";
}
buffer += it->first;
buffer += ":";
buffer += it->second;
}
buffer += "}";
}
}
}
|
#include "StringfyHelper.h"
#include "json/JSONIterator.h"
namespace rho
{
namespace apiGenerator
{
using namespace rho::json;
using namespace rho::common;
void StringifyVector::push_back(const rho::String& value, bool escape)
{
m_bufferLen += 1;
if (escape)
{
m_vector.push_back(CJSONEntry::quoteValue(value));
m_bufferLen += m_vector.back().length();
} else {
m_vector.push_back(value);
m_bufferLen += value.length();
}
}
void StringifyVector::push_back(const IStringSerializable& value)
{
rho::String buffer;
value.toString(buffer);
push_back(buffer, false);
}
void StringifyVector::toString(rho::String &buffer) const
{
buffer.clear();
buffer.reserve(m_bufferLen + 2);
buffer += "[";
for(rho::Vector<rho::String>::const_iterator it = m_vector.begin(); it != m_vector.end(); it++)
{
if(it != m_vector.begin())
{
buffer += ",";
}
buffer += *it;
}
buffer += "]";
}
void StringifyHash::set(const rho::String& key, const rho::String& value, bool escape)
{
m_bufferLen += 3;
rho::String bk(CJSONEntry::quoteValue(key));
if (escape)
{
rho::String bv(CJSONEntry::quoteValue(value));
m_hash[bk] = bv;
m_bufferLen += bk.length() + bv.length();
} else {
m_hash[bk] = value;
m_bufferLen += bk.length() + value.length();
}
}
void StringifyHash::set(const rho::String& key, const IStringSerializable& value)
{
rho::String buffer;
value.toString(buffer);
set(key, buffer, false);
}
void StringifyHash::toString(rho::String &buffer) const
{
buffer.clear();
buffer.reserve(m_bufferLen + 2);
buffer += "{";
for(rho::Hashtable<rho::String, rho::String>::const_iterator it = m_hash.begin(); it != m_hash.end(); it++)
{
if(it != m_hash.begin())
{
buffer += ",";
}
buffer += it->first;
buffer += ":";
buffer += it->second;
}
buffer += "}";
}
}
}
|
add missing ".h"
|
add missing ".h"
|
C++
|
mit
|
rhosilver/rhodes-1,rhosilver/rhodes-1,louisatome/rhodes,louisatome/rhodes,louisatome/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,UIKit0/rhodes,UIKit0/rhodes,UIKit0/rhodes,louisatome/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,UIKit0/rhodes,UIKit0/rhodes,UIKit0/rhodes,louisatome/rhodes,louisatome/rhodes,rhosilver/rhodes-1,louisatome/rhodes,louisatome/rhodes
|
88daddf36ebdc8b90ebc0d61fd7fe1b135062d19
|
burg.hpp
|
burg.hpp
|
// Except for any way in which it interferes with Cedrick Collomb's 2009
// copyright assertion in the article "Burg’s Method, Algorithm and Recursion":
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef BURG_ALGORITHM_HPP
#define BURG_ALGORITHM_HPP
#include <algorithm>
#include <cmath>
#include <limits>
#include <numeric>
#include <iterator>
#include <vector>
/**
* Use Burg's recursion to find coefficients \f$a_i\f$ such that the sum
* of the squared errors in both the forward linear prediction \f$x_n =
* \sum_{i=1}^m - a_i x_{n-i}\f$ and backward linear prediction \f$x_n =
* \sum_{i=1}^m - a_i x_{n+i}\f$ are minimized. Input data \f$\vec{x}$
* is taken from the range [data_first, data_last) in a single pass.
*
* Coefficients \f$\vec{a}\f$ are stored in [coeffs_first, coeffs_last)
* with the model order determined by both <tt>k = distance(coeffs_first,
* coeffs_last)</tt> and the \c hierarchy flag. If \c hierarchy is
* false, the coefficients for an AR(<tt>k</tt>) process are output. If \c
* hierarchy is true, the <tt>m*(m+1)/2</tt> coefficients for models AR(1),
* AR(2), ..., AR(m) up to order <tt>m = floor(sqrt(2*k))</tt> are output.
* The mean squared discrepancy value \f$\sigma_\epsilon^2\f$ is also output
* for each model. Each corresponding AR(p) prediction model has the form
* \f[
* x_n + a_0 x_{n-1} + \dots + a_{p-1} x_{n - (p + 1)} = \epsilon_n
* \f]
* where \f$\epsilon_n\f$ has variance \f$\sigma_\epsilon^2\f$.
*
* The implementation has been refactored from of Cedrick Collomb's 2009
* article <a
* href="http://www.emptyloop.com/technotes/A%20tutorial%20on%20Burg's%20method,%20algorithm%20and%20recursion.pdf">"Burg’s
* Method, Algorithm and Recursion"</a>. In particular, iterators are
* employed, the working precision depends on the output coefficients
* precision, a mean squared discrepancy calculation has been added, some loop
* index transformations have been performed, and all lower order models may be
* output during the recursion using \c hierarchy.
*
* @returns the number data values processed within [data_first, data_last).
*/
template<class InputIterator, class ForwardIterator, class OutputIterator>
std::size_t burg_algorithm(InputIterator data_first,
InputIterator data_last,
ForwardIterator coeffs_first,
ForwardIterator coeffs_last,
OutputIterator msd_first,
const bool hierarchy = false)
{
using std::copy;
using std::distance;
using std::fill;
using std::inner_product;
using std::iterator_traits;
using std::numeric_limits;
using std::sqrt;
// ForwardIterator::value_type determines the working precision
typedef typename iterator_traits<ForwardIterator>::value_type value;
typedef typename std::vector<value> vector;
typedef typename vector::size_type size;
// Initialize f from [data_first, data_last), b by copying f, and data size
vector f(data_first, data_last), b(f);
const size N = f.size();
// Get the order or maximum order of autoregressive model(s) desired.
// When hierarchy is true, the maximum order is the index of the largest
// triangular number that will fit within [coeffs_first, coeffs_last).
const size m = hierarchy ? sqrt(2*distance(coeffs_first, coeffs_last))
: distance(coeffs_first, coeffs_last);
// Initialize mean squared discrepancy msd and Dk
value msd = inner_product(f.begin(), f.end(), f.begin(), value(0));
value Dk = - f[0]*f[0] - f[N - 1]*f[N - 1] + 2*msd;
msd /= N;
// Initialize Ak
vector Ak(m + 1, value(0));
Ak[0] = 1;
// Burg recursion
for (size kp1 = 1; kp1 <= m; ++kp1)
{
// Compute mu from f, b, and Dk and then update msd and Ak using mu
const value mu = 2/Dk*inner_product(f.begin() + kp1, f.end(),
b.begin(), value(0));
msd *= (1 - mu*mu);
for (size n = 0; n <= kp1/2; ++n)
{
const value t1 = Ak[n] - mu*Ak[kp1 - n];
const value t2 = Ak[kp1 - n] - mu*Ak[n];
Ak[n] = t1;
Ak[kp1 - n] = t2;
}
// Here, Ak[1:kp1] contains AR(k) coefficients by the recurrence.
if (hierarchy || kp1 == m)
{
// Output coefficients and the mean squared discrepancy
coeffs_first = copy(Ak.begin() + 1, Ak.begin() + (kp1 + 1),
coeffs_first);
*msd_first++ = msd;
}
// Update f, b, and then Dk for the next iteration if another remains
if (kp1 < m)
{
for (size n = 0; n < N - kp1; ++n)
{
const value t1 = f[n + kp1] - mu*b[n];
const value t2 = b[n] - mu*f[n + kp1];
f[n + kp1] = t1;
b[n] = t2;
}
Dk = (1 - mu*mu)*Dk - f[kp1]*f[kp1] - b[N - kp1 - 1]*b[N - kp1 - 1];
}
}
// Defensively NaN any unspecified locations within the coeffs range
if (numeric_limits<value>::has_quiet_NaN)
{
fill(coeffs_first, coeffs_last, numeric_limits<value>::quiet_NaN());
}
// Return the number of values processed in [data_first, data_last)
return N;
}
namespace { // anonymous
// Used to discard output per http://stackoverflow.com/questions/335930/
struct null_output_iterator
: std::iterator< std::output_iterator_tag, null_output_iterator >
{
template<typename T> void operator=(const T&) { }
null_output_iterator& operator++() { return *this; }
null_output_iterator operator++(int) {
null_output_iterator it(*this);
++*this;
return it;
}
null_output_iterator& operator*() { return *this; }
};
}
/**
* Use Burg's recursion to find coefficients \f$a_i\f$ such that the sum
* of the squared errors in both the forward linear prediction \f$x_n =
* \sum_{i=1}^m a_i x_{n-i}\f$ and backward linear prediction \f$x_n =
* \sum_{i=1}^m a_i x_{n+i}\f$ are minimized. Input data \f$\vec{x}$
* is taken from the range [data_first, data_last) in a single pass.
*
* Coefficients \f$\vec{a}\f$ are stored in [coeffs_first, coeffs_last) with
* the model order determined by <tt>distance(coeffs_first, coeffs_last)</tt>.
*
* @returns the number data values processed within [data_first, data_last).
*/
template<class InputIterator, class ForwardIterator>
std::size_t burg_algorithm(InputIterator data_first,
InputIterator data_last,
ForwardIterator coeffs_first,
ForwardIterator coeffs_last)
{
return burg_algorithm(data_first, data_last,
coeffs_first, coeffs_last,
null_output_iterator(), false);
}
#endif /* BURG_ALGORITHM_HPP */
|
// Except for any way in which it interferes with Cedrick Collomb's 2009
// copyright assertion in the article "Burg’s Method, Algorithm and Recursion":
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef BURG_HPP
#define BURG_HPP
#include <algorithm>
#include <cmath>
#include <limits>
#include <numeric>
#include <iterator>
#include <vector>
/**
* Use Burg's recursion to find coefficients \f$a_i\f$ such that the sum
* of the squared errors in both the forward linear prediction \f$x_n =
* \sum_{i=1}^m - a_i x_{n-i}\f$ and backward linear prediction \f$x_n =
* \sum_{i=1}^m - a_i x_{n+i}\f$ are minimized. Input data \f$\vec{x}$
* is taken from the range [data_first, data_last) in a single pass.
*
* Coefficients \f$\vec{a}\f$ are stored in [coeffs_first, coeffs_last)
* with the model order determined by both <tt>k = distance(coeffs_first,
* coeffs_last)</tt> and the \c hierarchy flag. If \c hierarchy is
* false, the coefficients for an AR(<tt>k</tt>) process are output. If \c
* hierarchy is true, the <tt>m*(m+1)/2</tt> coefficients for models AR(1),
* AR(2), ..., AR(m) up to order <tt>m = floor(sqrt(2*k))</tt> are output.
* The mean squared discrepancy value \f$\sigma_\epsilon^2\f$ is also output
* for each model. Each corresponding AR(p) prediction model has the form
* \f[
* x_n + a_0 x_{n-1} + \dots + a_{p-1} x_{n - (p + 1)} = \epsilon_n
* \f]
* where \f$\epsilon_n\f$ has variance \f$\sigma_\epsilon^2\f$.
*
* The implementation has been refactored from of Cedrick Collomb's 2009
* article <a
* href="http://www.emptyloop.com/technotes/A%20tutorial%20on%20Burg's%20method,%20algorithm%20and%20recursion.pdf">"Burg’s
* Method, Algorithm and Recursion"</a>. In particular, iterators are
* employed, the working precision depends on the output coefficients
* precision, a mean squared discrepancy calculation has been added, some loop
* index transformations have been performed, and all lower order models may be
* output during the recursion using \c hierarchy.
*
* @returns the number data values processed within [data_first, data_last).
*/
template<class InputIterator, class ForwardIterator, class OutputIterator>
std::size_t burg_algorithm(InputIterator data_first,
InputIterator data_last,
ForwardIterator coeffs_first,
ForwardIterator coeffs_last,
OutputIterator msd_first,
const bool hierarchy = false)
{
using std::copy;
using std::distance;
using std::fill;
using std::inner_product;
using std::iterator_traits;
using std::numeric_limits;
using std::sqrt;
// ForwardIterator::value_type determines the working precision
typedef typename iterator_traits<ForwardIterator>::value_type value;
typedef typename std::vector<value> vector;
typedef typename vector::size_type size;
// Initialize f from [data_first, data_last), b by copying f, and data size
vector f(data_first, data_last), b(f);
const size N = f.size();
// Get the order or maximum order of autoregressive model(s) desired.
// When hierarchy is true, the maximum order is the index of the largest
// triangular number that will fit within [coeffs_first, coeffs_last).
const size m = hierarchy ? sqrt(2*distance(coeffs_first, coeffs_last))
: distance(coeffs_first, coeffs_last);
// Initialize mean squared discrepancy msd and Dk
value msd = inner_product(f.begin(), f.end(), f.begin(), value(0));
value Dk = - f[0]*f[0] - f[N - 1]*f[N - 1] + 2*msd;
msd /= N;
// Initialize Ak
vector Ak(m + 1, value(0));
Ak[0] = 1;
// Burg recursion
for (size kp1 = 1; kp1 <= m; ++kp1)
{
// Compute mu from f, b, and Dk and then update msd and Ak using mu
const value mu = 2/Dk*inner_product(f.begin() + kp1, f.end(),
b.begin(), value(0));
msd *= (1 - mu*mu);
for (size n = 0; n <= kp1/2; ++n)
{
const value t1 = Ak[n] - mu*Ak[kp1 - n];
const value t2 = Ak[kp1 - n] - mu*Ak[n];
Ak[n] = t1;
Ak[kp1 - n] = t2;
}
// Here, Ak[1:kp1] contains AR(k) coefficients by the recurrence.
if (hierarchy || kp1 == m)
{
// Output coefficients and the mean squared discrepancy
coeffs_first = copy(Ak.begin() + 1, Ak.begin() + (kp1 + 1),
coeffs_first);
*msd_first++ = msd;
}
// Update f, b, and then Dk for the next iteration if another remains
if (kp1 < m)
{
for (size n = 0; n < N - kp1; ++n)
{
const value t1 = f[n + kp1] - mu*b[n];
const value t2 = b[n] - mu*f[n + kp1];
f[n + kp1] = t1;
b[n] = t2;
}
Dk = (1 - mu*mu)*Dk - f[kp1]*f[kp1] - b[N - kp1 - 1]*b[N - kp1 - 1];
}
}
// Defensively NaN any unspecified locations within the coeffs range
if (numeric_limits<value>::has_quiet_NaN)
{
fill(coeffs_first, coeffs_last, numeric_limits<value>::quiet_NaN());
}
// Return the number of values processed in [data_first, data_last)
return N;
}
namespace { // anonymous
// Used to discard output per http://stackoverflow.com/questions/335930/
struct null_output_iterator
: std::iterator< std::output_iterator_tag, null_output_iterator >
{
template<typename T> void operator=(const T&) { }
null_output_iterator& operator++() { return *this; }
null_output_iterator operator++(int) {
null_output_iterator it(*this);
++*this;
return it;
}
null_output_iterator& operator*() { return *this; }
};
}
/**
* Use Burg's recursion to find coefficients \f$a_i\f$ such that the sum
* of the squared errors in both the forward linear prediction \f$x_n =
* \sum_{i=1}^m a_i x_{n-i}\f$ and backward linear prediction \f$x_n =
* \sum_{i=1}^m a_i x_{n+i}\f$ are minimized. Input data \f$\vec{x}$
* is taken from the range [data_first, data_last) in a single pass.
*
* Coefficients \f$\vec{a}\f$ are stored in [coeffs_first, coeffs_last) with
* the model order determined by <tt>distance(coeffs_first, coeffs_last)</tt>.
*
* @returns the number data values processed within [data_first, data_last).
*/
template<class InputIterator, class ForwardIterator>
std::size_t burg_algorithm(InputIterator data_first,
InputIterator data_last,
ForwardIterator coeffs_first,
ForwardIterator coeffs_last)
{
return burg_algorithm(data_first, data_last,
coeffs_first, coeffs_last,
null_output_iterator(), false);
}
// zohar_linear_solve(...)
//
// Zohar, Shalhav. "The Solution of a Toeplitz Set of Linear Equations." J. ACM
// 21 (April 1974): 272-276. http://dx.doi.org/10.1145/321812.321822
//
// Problem Formulation
// \f[
// L_{n+1} s_{n+1} = d_{n+1}
// \mbox{ where }
// L_{n+1} = \bigl(\begin{smallmatrix}
// 1 & \tilde{a}_n \\
// r_n & L_n
// \end{smallmatrix}\bigr)
// \f]
// \f[
// \tilde{a}_i = \left[\rho_{-1} \rho_{-2} \dots \rho{-i}]
// \mbox{ for } 1 \leq i \leq n
// \f]
// \f[
// \tilde{r}_i = \left[\rho_{1} \rho_{2} \dots \rho{i}]
// \mbox{ for } 1 \leq i \leq n
// \f]
// \f[
// d_{n+1} = \left[\delta_1 \delta_2 \dots \delta_{n+1}]
// \f]
// \f[
// s_{n+1} = \text{?}
// \f]
//
// Initial values for recursion:
// \f[ s_1 = \delta_1 \f]
// \f[ e_1 = -\rho_{-1} \f]
// \f[ g_1 = -\rho_1 \f]
// \f[ \lambda_1 = 1 - \rho_{-1}\rho_1 \f]
//
// Tildes indicate transposes while hats indicate reversed vectors.
//
// Recursion for i = 1, 2, ..., n:
// \f[ \theta_i = \delta_{i+1} - \tilde{s}_i \hat{r}_i \f]
// \f[ \eta_i = -\rho_{-(i+1)} - \tilde{a}_i \hat{e}_i \f]
// \f[ \gamma_i = -\rho_{i+1} - \tilde{g}_i \hat{r}_i \f]
// \f[
// s_{i+1} = \bigl(\begin{smallmatrix}
// s_i + (\theta_i/\lambda_i) \hat{e}_i \\
// \theta_i/\lambda_i
// \end{smallmatrix}\bigr)
// \f]
// \f[
// hat{e}_{i+1} = \bigl(\begin{smallmatrix}
// \eta_i/\lambda_i \\
// \hat{e}_i + (\ega_i/\lambda_i) g_i
// \end{smallmatrix}\bigr)
// \f]
// \f[
// g_{i+1} = \bigl(\begin{smallmatrix}
// g_i + (\gamma_i/\lambda_i) \hat{e}_i \\
// \gamma_i/\lambda_i
// \end{smallmatrix}\bigr)
// \f]
// \f[ \lambda_{i+1} = \lambda_i - \eta_i \gamma_i / \lambda_i \f]
#endif /* BURG_HPP */
|
add writeup for Zohar Topelitz solve
|
add writeup for Zohar Topelitz solve
|
C++
|
mpl-2.0
|
RhysU/ar,RhysU/ar
|
a436d3839ad49c793e5ed6448336c526c7cad542
|
src/sync/app_service_client.hpp
|
src/sync/app_service_client.hpp
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or utilied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef APP_SERVICE_CLIENT_HPP
#define APP_SERVICE_CLIENT_HPP
#include <sync/generic_network_transport.hpp>
#include <realm/util/optional.hpp>
#include <string>
namespace realm {
namespace app {
/// A class providing the core functionality necessary to make authenticated function call requests for a particular
/// Stitch service.
class AppServiceClient {
public:
/// Calls the MongoDB Stitch function with the provided name and arguments.
/// @param name The name of the Stitch function to be called.
/// @param args The `BSONArray` of arguments to be provided to the function.
/// @param service_name The name of the service, this is optional.
/// @param completion_block Returns the result from the intended call, will return an Optional AppError is an error is thrown and a json string if successful
virtual void call_function(const std::string& name,
const std::string& args_json,
const util::Optional<std::string>& service_name,
std::function<void (util::Optional<AppError>, util::Optional<std::string>)> completion_block) = 0;
virtual ~AppServiceClient() = default;
};
} // namespace app
} // namespace realm
#endif /* APP_SERVICE_CLIENT_HPP */
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or utilied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef APP_SERVICE_CLIENT_HPP
#define APP_SERVICE_CLIENT_HPP
#include "sync/generic_network_transport.hpp"
#include <realm/util/optional.hpp>
#include <string>
namespace realm {
namespace app {
/// A class providing the core functionality necessary to make authenticated function call requests for a particular
/// Stitch service.
class AppServiceClient {
public:
/// Calls the MongoDB Stitch function with the provided name and arguments.
/// @param name The name of the Stitch function to be called.
/// @param args The `BSONArray` of arguments to be provided to the function.
/// @param service_name The name of the service, this is optional.
/// @param completion_block Returns the result from the intended call, will return an Optional AppError is an error is thrown and a json string if successful
virtual void call_function(const std::string& name,
const std::string& args_json,
const util::Optional<std::string>& service_name,
std::function<void (util::Optional<AppError>, util::Optional<std::string>)> completion_block) = 0;
virtual ~AppServiceClient() = default;
};
} // namespace app
} // namespace realm
#endif /* APP_SERVICE_CLIENT_HPP */
|
Fix angled brackets (#973)
|
Fix angled brackets (#973)
|
C++
|
apache-2.0
|
realm/realm-object-store,realm/realm-core,realm/realm-core,realm/realm-object-store,realm/realm-core,realm/realm-object-store,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core
|
90af4d2cca4ac3b1066176670232a91c349670d5
|
indra/viewer_components/updater/llupdatedownloader.cpp
|
indra/viewer_components/updater/llupdatedownloader.cpp
|
/**
* @file llupdatedownloader.cpp
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include <stdexcept>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>
#include "lldir.h"
#include "llfile.h"
#include "llmd5.h"
#include "llsd.h"
#include "llsdserialize.h"
#include "llthread.h"
#include "llupdatedownloader.h"
#include "llupdaterservice.h"
class LLUpdateDownloader::Implementation:
public LLThread
{
public:
Implementation(LLUpdateDownloader::Client & client);
~Implementation();
void cancel(void);
void download(LLURI const & uri, std::string const & hash);
bool isDownloading(void);
size_t onHeader(void * header, size_t size);
size_t onBody(void * header, size_t size);
void resume(void);
private:
bool mCancelled;
LLUpdateDownloader::Client & mClient;
CURL * mCurl;
LLSD mDownloadData;
llofstream mDownloadStream;
std::string mDownloadRecordPath;
curl_slist * mHeaderList;
void initializeCurlGet(std::string const & url, bool processHeader);
void resumeDownloading(size_t startByte);
void run(void);
void startDownloading(LLURI const & uri, std::string const & hash);
void throwOnCurlError(CURLcode code);
bool validateDownload(void);
LOG_CLASS(LLUpdateDownloader::Implementation);
};
namespace {
class DownloadError:
public std::runtime_error
{
public:
DownloadError(const char * message):
std::runtime_error(message)
{
; // No op.
}
};
const char * gSecondLifeUpdateRecord = "SecondLifeUpdateDownload.xml";
};
// LLUpdateDownloader
//-----------------------------------------------------------------------------
std::string LLUpdateDownloader::downloadMarkerPath(void)
{
return gDirUtilp->getExpandedFilename(LL_PATH_LOGS, gSecondLifeUpdateRecord);
}
LLUpdateDownloader::LLUpdateDownloader(Client & client):
mImplementation(new LLUpdateDownloader::Implementation(client))
{
; // No op.
}
void LLUpdateDownloader::cancel(void)
{
mImplementation->cancel();
}
void LLUpdateDownloader::download(LLURI const & uri, std::string const & hash)
{
mImplementation->download(uri, hash);
}
bool LLUpdateDownloader::isDownloading(void)
{
return mImplementation->isDownloading();
}
void LLUpdateDownloader::resume(void)
{
mImplementation->resume();
}
// LLUpdateDownloader::Implementation
//-----------------------------------------------------------------------------
namespace {
size_t write_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onBody(data, bytes);
}
size_t header_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onHeader(data, bytes);
}
}
LLUpdateDownloader::Implementation::Implementation(LLUpdateDownloader::Client & client):
LLThread("LLUpdateDownloader"),
mCancelled(false),
mClient(client),
mCurl(0),
mHeaderList(0)
{
CURLcode code = curl_global_init(CURL_GLOBAL_ALL); // Just in case.
llverify(code == CURLE_OK); // TODO: real error handling here.
}
LLUpdateDownloader::Implementation::~Implementation()
{
if(isDownloading()) {
cancel();
shutdown();
} else {
; // No op.
}
if(mCurl) curl_easy_cleanup(mCurl);
}
void LLUpdateDownloader::Implementation::cancel(void)
{
mCancelled = true;
}
void LLUpdateDownloader::Implementation::download(LLURI const & uri, std::string const & hash)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
mDownloadData = LLSD();
try {
startDownloading(uri, hash);
} catch(DownloadError const & e) {
mClient.downloadError(e.what());
}
}
bool LLUpdateDownloader::Implementation::isDownloading(void)
{
return !isStopped();
}
void LLUpdateDownloader::Implementation::resume(void)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
llifstream dataStream(mDownloadRecordPath);
if(!dataStream) {
mClient.downloadError("no download marker");
return;
}
LLSDSerialize::fromXMLDocument(mDownloadData, dataStream);
if(!mDownloadData.asBoolean()) {
mClient.downloadError("no download information in marker");
return;
}
std::string filePath = mDownloadData["path"].asString();
try {
if(LLFile::isfile(filePath)) {
llstat fileStatus;
LLFile::stat(filePath, &fileStatus);
if(fileStatus.st_size != mDownloadData["size"].asInteger()) {
resumeDownloading(fileStatus.st_size);
} else if(!validateDownload()) {
LLFile::remove(filePath);
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
} else {
mClient.downloadComplete(mDownloadData);
}
} else {
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
}
} catch(DownloadError & e) {
mClient.downloadError(e.what());
}
}
size_t LLUpdateDownloader::Implementation::onHeader(void * buffer, size_t size)
{
char const * headerPtr = reinterpret_cast<const char *> (buffer);
std::string header(headerPtr, headerPtr + size);
size_t colonPosition = header.find(':');
if(colonPosition == std::string::npos) return size; // HTML response; ignore.
if(header.substr(0, colonPosition) == "Content-Length") {
try {
size_t firstDigitPos = header.find_first_of("0123456789", colonPosition);
size_t lastDigitPos = header.find_last_of("0123456789");
std::string contentLength = header.substr(firstDigitPos, lastDigitPos - firstDigitPos + 1);
size_t size = boost::lexical_cast<size_t>(contentLength);
LL_INFOS("UpdateDownload") << "download size is " << size << LL_ENDL;
mDownloadData["size"] = LLSD(LLSD::Integer(size));
llofstream odataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, odataStream);
} catch (std::exception const & e) {
LL_WARNS("UpdateDownload") << "unable to read content length ("
<< e.what() << ")" << LL_ENDL;
}
} else {
; // No op.
}
return size;
}
size_t LLUpdateDownloader::Implementation::onBody(void * buffer, size_t size)
{
if(mCancelled) return 0; // Forces a write error which will halt curl thread.
if((size == 0) || (buffer == 0)) return 0;
mDownloadStream.write(reinterpret_cast<const char *>(buffer), size);
if(mDownloadStream.bad()) {
return 0;
} else {
return size;
}
}
void LLUpdateDownloader::Implementation::run(void)
{
CURLcode code = curl_easy_perform(mCurl);
mDownloadStream.close();
if(code == CURLE_OK) {
LLFile::remove(mDownloadRecordPath);
if(validateDownload()) {
LL_INFOS("UpdateDownload") << "download successful" << LL_ENDL;
mClient.downloadComplete(mDownloadData);
} else {
LL_INFOS("UpdateDownload") << "download failed hash check" << LL_ENDL;
std::string filePath = mDownloadData["path"].asString();
if(filePath.size() != 0) LLFile::remove(filePath);
mClient.downloadError("failed hash check");
}
} else if(mCancelled && (code == CURLE_WRITE_ERROR)) {
LL_INFOS("UpdateDownload") << "download canceled by user" << LL_ENDL;
// Do not call back client.
} else {
LL_WARNS("UpdateDownload") << "download failed with error '" <<
curl_easy_strerror(code) << "'" << LL_ENDL;
LLFile::remove(mDownloadRecordPath);
mClient.downloadError("curl error");
}
if(mHeaderList) {
curl_slist_free_all(mHeaderList);
mHeaderList = 0;
}
}
void LLUpdateDownloader::Implementation::initializeCurlGet(std::string const & url, bool processHeader)
{
if(mCurl == 0) {
mCurl = curl_easy_init();
} else {
curl_easy_reset(mCurl);
}
if(mCurl == 0) throw DownloadError("failed to initialize curl");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_NOSIGNAL, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_FOLLOWLOCATION, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEFUNCTION, &write_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEDATA, this));
if(processHeader) {
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERFUNCTION, &header_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERDATA, this));
}
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPGET, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_URL, url.c_str()));
}
void LLUpdateDownloader::Implementation::resumeDownloading(size_t startByte)
{
LL_INFOS("UpdateDownload") << "resuming download from " << mDownloadData["url"].asString()
<< " at byte " << startByte << LL_ENDL;
initializeCurlGet(mDownloadData["url"].asString(), false);
// The header 'Range: bytes n-' will request the bytes remaining in the
// source begining with byte n and ending with the last byte.
boost::format rangeHeaderFormat("Range: bytes=%u-");
rangeHeaderFormat % startByte;
mHeaderList = curl_slist_append(mHeaderList, rangeHeaderFormat.str().c_str());
if(mHeaderList == 0) throw DownloadError("cannot add Range header");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mHeaderList));
mDownloadStream.open(mDownloadData["path"].asString(),
std::ios_base::out | std::ios_base::binary | std::ios_base::app);
start();
}
void LLUpdateDownloader::Implementation::startDownloading(LLURI const & uri, std::string const & hash)
{
mDownloadData["url"] = uri.asString();
mDownloadData["hash"] = hash;
mDownloadData["current_version"] = ll_get_version();
LLSD path = uri.pathArray();
if(path.size() == 0) throw DownloadError("no file path");
std::string fileName = path[path.size() - 1].asString();
std::string filePath = gDirUtilp->getExpandedFilename(LL_PATH_TEMP, fileName);
mDownloadData["path"] = filePath;
LL_INFOS("UpdateDownload") << "downloading " << filePath
<< " from " << uri.asString() << LL_ENDL;
LL_INFOS("UpdateDownload") << "hash of file is " << hash << LL_ENDL;
llofstream dataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, dataStream);
mDownloadStream.open(filePath, std::ios_base::out | std::ios_base::binary);
initializeCurlGet(uri.asString(), true);
start();
}
void LLUpdateDownloader::Implementation::throwOnCurlError(CURLcode code)
{
if(code != CURLE_OK) {
const char * errorString = curl_easy_strerror(code);
if(errorString != 0) {
throw DownloadError(curl_easy_strerror(code));
} else {
throw DownloadError("unknown curl error");
}
} else {
; // No op.
}
}
bool LLUpdateDownloader::Implementation::validateDownload(void)
{
std::string filePath = mDownloadData["path"].asString();
llifstream fileStream(filePath, std::ios_base::in | std::ios_base::binary);
if(!fileStream) return false;
std::string hash = mDownloadData["hash"].asString();
if(hash.size() != 0) {
LL_INFOS("UpdateDownload") << "checking hash..." << LL_ENDL;
char digest[33];
LLMD5(fileStream).hex_digest(digest);
if(hash != digest) {
LL_WARNS("UpdateDownload") << "download hash mismatch; expeted " << hash <<
" but download is " << digest << LL_ENDL;
}
return hash == digest;
} else {
return true; // No hash check provided.
}
}
|
/**
* @file llupdatedownloader.cpp
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include <stdexcept>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>
#include "lldir.h"
#include "llfile.h"
#include "llmd5.h"
#include "llsd.h"
#include "llsdserialize.h"
#include "llthread.h"
#include "llupdatedownloader.h"
#include "llupdaterservice.h"
class LLUpdateDownloader::Implementation:
public LLThread
{
public:
Implementation(LLUpdateDownloader::Client & client);
~Implementation();
void cancel(void);
void download(LLURI const & uri, std::string const & hash);
bool isDownloading(void);
size_t onHeader(void * header, size_t size);
size_t onBody(void * header, size_t size);
void resume(void);
private:
bool mCancelled;
LLUpdateDownloader::Client & mClient;
CURL * mCurl;
LLSD mDownloadData;
llofstream mDownloadStream;
std::string mDownloadRecordPath;
curl_slist * mHeaderList;
void initializeCurlGet(std::string const & url, bool processHeader);
void resumeDownloading(size_t startByte);
void run(void);
void startDownloading(LLURI const & uri, std::string const & hash);
void throwOnCurlError(CURLcode code);
bool validateDownload(void);
LOG_CLASS(LLUpdateDownloader::Implementation);
};
namespace {
class DownloadError:
public std::runtime_error
{
public:
DownloadError(const char * message):
std::runtime_error(message)
{
; // No op.
}
};
const char * gSecondLifeUpdateRecord = "SecondLifeUpdateDownload.xml";
};
// LLUpdateDownloader
//-----------------------------------------------------------------------------
std::string LLUpdateDownloader::downloadMarkerPath(void)
{
return gDirUtilp->getExpandedFilename(LL_PATH_LOGS, gSecondLifeUpdateRecord);
}
LLUpdateDownloader::LLUpdateDownloader(Client & client):
mImplementation(new LLUpdateDownloader::Implementation(client))
{
; // No op.
}
void LLUpdateDownloader::cancel(void)
{
mImplementation->cancel();
}
void LLUpdateDownloader::download(LLURI const & uri, std::string const & hash)
{
mImplementation->download(uri, hash);
}
bool LLUpdateDownloader::isDownloading(void)
{
return mImplementation->isDownloading();
}
void LLUpdateDownloader::resume(void)
{
mImplementation->resume();
}
// LLUpdateDownloader::Implementation
//-----------------------------------------------------------------------------
namespace {
size_t write_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onBody(data, bytes);
}
size_t header_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onHeader(data, bytes);
}
}
LLUpdateDownloader::Implementation::Implementation(LLUpdateDownloader::Client & client):
LLThread("LLUpdateDownloader"),
mCancelled(false),
mClient(client),
mCurl(0),
mHeaderList(0)
{
CURLcode code = curl_global_init(CURL_GLOBAL_ALL); // Just in case.
llverify(code == CURLE_OK); // TODO: real error handling here.
}
LLUpdateDownloader::Implementation::~Implementation()
{
if(isDownloading()) {
cancel();
shutdown();
} else {
; // No op.
}
if(mCurl) curl_easy_cleanup(mCurl);
}
void LLUpdateDownloader::Implementation::cancel(void)
{
mCancelled = true;
}
void LLUpdateDownloader::Implementation::download(LLURI const & uri, std::string const & hash)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
mDownloadData = LLSD();
try {
startDownloading(uri, hash);
} catch(DownloadError const & e) {
mClient.downloadError(e.what());
}
}
bool LLUpdateDownloader::Implementation::isDownloading(void)
{
return !isStopped();
}
void LLUpdateDownloader::Implementation::resume(void)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
llifstream dataStream(mDownloadRecordPath);
if(!dataStream) {
mClient.downloadError("no download marker");
return;
}
LLSDSerialize::fromXMLDocument(mDownloadData, dataStream);
if(!mDownloadData.asBoolean()) {
mClient.downloadError("no download information in marker");
return;
}
std::string filePath = mDownloadData["path"].asString();
try {
if(LLFile::isfile(filePath)) {
llstat fileStatus;
LLFile::stat(filePath, &fileStatus);
if(fileStatus.st_size != mDownloadData["size"].asInteger()) {
resumeDownloading(fileStatus.st_size);
} else if(!validateDownload()) {
LLFile::remove(filePath);
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
} else {
mClient.downloadComplete(mDownloadData);
}
} else {
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
}
} catch(DownloadError & e) {
mClient.downloadError(e.what());
}
}
size_t LLUpdateDownloader::Implementation::onHeader(void * buffer, size_t size)
{
char const * headerPtr = reinterpret_cast<const char *> (buffer);
std::string header(headerPtr, headerPtr + size);
size_t colonPosition = header.find(':');
if(colonPosition == std::string::npos) return size; // HTML response; ignore.
if(header.substr(0, colonPosition) == "Content-Length") {
try {
size_t firstDigitPos = header.find_first_of("0123456789", colonPosition);
size_t lastDigitPos = header.find_last_of("0123456789");
std::string contentLength = header.substr(firstDigitPos, lastDigitPos - firstDigitPos + 1);
size_t size = boost::lexical_cast<size_t>(contentLength);
LL_INFOS("UpdateDownload") << "download size is " << size << LL_ENDL;
mDownloadData["size"] = LLSD(LLSD::Integer(size));
llofstream odataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, odataStream);
} catch (std::exception const & e) {
LL_WARNS("UpdateDownload") << "unable to read content length ("
<< e.what() << ")" << LL_ENDL;
}
} else {
; // No op.
}
return size;
}
size_t LLUpdateDownloader::Implementation::onBody(void * buffer, size_t size)
{
if(mCancelled) return 0; // Forces a write error which will halt curl thread.
if((size == 0) || (buffer == 0)) return 0;
mDownloadStream.write(reinterpret_cast<const char *>(buffer), size);
if(mDownloadStream.bad()) {
return 0;
} else {
return size;
}
}
void LLUpdateDownloader::Implementation::run(void)
{
CURLcode code = curl_easy_perform(mCurl);
mDownloadStream.close();
if(code == CURLE_OK) {
LLFile::remove(mDownloadRecordPath);
if(validateDownload()) {
LL_INFOS("UpdateDownload") << "download successful" << LL_ENDL;
mClient.downloadComplete(mDownloadData);
} else {
LL_INFOS("UpdateDownload") << "download failed hash check" << LL_ENDL;
std::string filePath = mDownloadData["path"].asString();
if(filePath.size() != 0) LLFile::remove(filePath);
mClient.downloadError("failed hash check");
}
} else if(mCancelled && (code == CURLE_WRITE_ERROR)) {
LL_INFOS("UpdateDownload") << "download canceled by user" << LL_ENDL;
// Do not call back client.
} else {
LL_WARNS("UpdateDownload") << "download failed with error '" <<
curl_easy_strerror(code) << "'" << LL_ENDL;
LLFile::remove(mDownloadRecordPath);
if(mDownloadData.has("path")) LLFile::remove(mDownloadData["path"].asString());
mClient.downloadError("curl error");
}
if(mHeaderList) {
curl_slist_free_all(mHeaderList);
mHeaderList = 0;
}
}
void LLUpdateDownloader::Implementation::initializeCurlGet(std::string const & url, bool processHeader)
{
if(mCurl == 0) {
mCurl = curl_easy_init();
} else {
curl_easy_reset(mCurl);
}
if(mCurl == 0) throw DownloadError("failed to initialize curl");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_NOSIGNAL, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_FOLLOWLOCATION, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEFUNCTION, &write_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEDATA, this));
if(processHeader) {
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERFUNCTION, &header_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERDATA, this));
}
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPGET, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_URL, url.c_str()));
}
void LLUpdateDownloader::Implementation::resumeDownloading(size_t startByte)
{
LL_INFOS("UpdateDownload") << "resuming download from " << mDownloadData["url"].asString()
<< " at byte " << startByte << LL_ENDL;
initializeCurlGet(mDownloadData["url"].asString(), false);
// The header 'Range: bytes n-' will request the bytes remaining in the
// source begining with byte n and ending with the last byte.
boost::format rangeHeaderFormat("Range: bytes=%u-");
rangeHeaderFormat % startByte;
mHeaderList = curl_slist_append(mHeaderList, rangeHeaderFormat.str().c_str());
if(mHeaderList == 0) throw DownloadError("cannot add Range header");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mHeaderList));
mDownloadStream.open(mDownloadData["path"].asString(),
std::ios_base::out | std::ios_base::binary | std::ios_base::app);
start();
}
void LLUpdateDownloader::Implementation::startDownloading(LLURI const & uri, std::string const & hash)
{
mDownloadData["url"] = uri.asString();
mDownloadData["hash"] = hash;
mDownloadData["current_version"] = ll_get_version();
LLSD path = uri.pathArray();
if(path.size() == 0) throw DownloadError("no file path");
std::string fileName = path[path.size() - 1].asString();
std::string filePath = gDirUtilp->getExpandedFilename(LL_PATH_TEMP, fileName);
mDownloadData["path"] = filePath;
LL_INFOS("UpdateDownload") << "downloading " << filePath
<< " from " << uri.asString() << LL_ENDL;
LL_INFOS("UpdateDownload") << "hash of file is " << hash << LL_ENDL;
llofstream dataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, dataStream);
mDownloadStream.open(filePath, std::ios_base::out | std::ios_base::binary);
initializeCurlGet(uri.asString(), true);
start();
}
void LLUpdateDownloader::Implementation::throwOnCurlError(CURLcode code)
{
if(code != CURLE_OK) {
const char * errorString = curl_easy_strerror(code);
if(errorString != 0) {
throw DownloadError(curl_easy_strerror(code));
} else {
throw DownloadError("unknown curl error");
}
} else {
; // No op.
}
}
bool LLUpdateDownloader::Implementation::validateDownload(void)
{
std::string filePath = mDownloadData["path"].asString();
llifstream fileStream(filePath, std::ios_base::in | std::ios_base::binary);
if(!fileStream) return false;
std::string hash = mDownloadData["hash"].asString();
if(hash.size() != 0) {
LL_INFOS("UpdateDownload") << "checking hash..." << LL_ENDL;
char digest[33];
LLMD5(fileStream).hex_digest(digest);
if(hash != digest) {
LL_WARNS("UpdateDownload") << "download hash mismatch; expeted " << hash <<
" but download is " << digest << LL_ENDL;
}
return hash == digest;
} else {
return true; // No hash check provided.
}
}
|
remove downloaded file on error.
|
remove downloaded file on error.
|
C++
|
lgpl-2.1
|
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
|
d99e7ffa9a8724bbf0a1ac62669864c25f384aec
|
copasi/commercial/CRegistration.cpp
|
copasi/commercial/CRegistration.cpp
|
/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/commercial/Attic/CRegistration.cpp,v $
$Revision: 1.3 $
$Name: $
$Author: shoops $
$Date: 2006/12/15 21:25:34 $
End CVS Header */
// Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <sstream>
#include "copasi.h"
#include "CRegistration.h"
#include "GenericDecode.h"
#include "Cmd5.h"
#include "commandline/COptions.h"
/*
Seed Combo :en
Seed Length: 13
Minimum Email Length: 1
Minimum Name Length: 1
Minimum HotSync ID Length: 1
Length of Constant: 1
Constant value: T
Sequence Length: 3
Alternate Text: Contact [email protected] to obtain your registration code.
Scramble Order: U7,S0,U0,U8,S2,U3,U12,U1,U11,D3,C0,U5,D2,D0,S1,D1,U4,U10,U2,U6,U9,
ASCII Digit(For text to Number Conversion):2
Math Operation(Example:36A(36->Operand,A-Addition)): 23S,5A,R,37S,1A,R,7A,13S,R,29S,17S,R,8A,R,4A,7S,R,R,3A,11S,19S,
New Base: 52
Base Character Set: dAK0QyEfTD2UkGM3aehxYRi48uz19Wb7qgFJCtXNH65ncrwmpPLj
Registration code format(^ is place holder for check digit) : COPASI-####-####-#^####-####-####-####[-#G3Q]
*/
const char config[] =
"SUPPLIERID:VTIP%E:1%N:1%H:1%COMBO:en%SDLGTH:13%CONSTLGTH:1%CONSTVAL:T%SEQL:3%"
"ALTTEXT:Contact [email protected] to obtain your registration code.%"
"SCRMBL:U7,,S0,,U0,,U8,,S2,,U3,,U12,,U1,,U11,,D3,,C0,,U5,,D2,,D0,,S1,,D1,,U4,,U10,,U2,,U6,,U9,,%"
"ASCDIG:2%MATH:23S,,5A,,R,,37S,,1A,,R,,7A,,13S,,R,,29S,,17S,,R,,8A,,R,,4A,,7S,,R,,R,,3A,,11S,,19S,,%"
"BASE:52%BASEMAP:dAK0QyEfTD2UkGM3aehxYRi48uz19Wb7qgFJCtXNH65ncrwmpPLj%"
"REGFRMT:COPASI-####-####-#^####-####-####-####[-#G3Q]";
// email: [email protected]
// name: Stefan Hoops
// day: 20061213
// code: COPASI-KcTF-kdiU-Ftf4mc-TDfr-XfG3-Qhk7
CRegistration::CRegistration(const std::string & name,
const CCopasiContainer * pParent):
CCopasiParameterGroup(name, pParent),
mpRegisteredEmail(NULL),
mpRegisteredUser(NULL),
mpRegistrationCode(NULL),
mpSignature(NULL),
mExpirationDate(-1)
{initializeParameter();}
CRegistration::CRegistration(const CRegistration & src,
const CCopasiContainer * pParent):
CCopasiParameterGroup(src, pParent),
mpRegisteredEmail(NULL),
mpRegisteredUser(NULL),
mpRegistrationCode(NULL),
mpSignature(NULL),
mExpirationDate(src.mExpirationDate)
{initializeParameter();}
CRegistration::CRegistration(const CCopasiParameterGroup & group,
const CCopasiContainer * pParent):
CCopasiParameterGroup(group, pParent),
mpRegisteredEmail(NULL),
mpRegisteredUser(NULL),
mpRegistrationCode(NULL),
mpSignature(NULL),
mExpirationDate(-1)
{initializeParameter();}
CRegistration::~CRegistration() {}
void CRegistration::initializeParameter()
{
mpRegisteredEmail =
assertParameter("Registered Email", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
mpRegisteredUser =
assertParameter("Registered User", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
mpRegistrationCode =
assertParameter("Registration Code", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
mpSignature =
assertParameter("Signature", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
}
void CRegistration::setRegisteredEmail(const std::string & registeredEmail)
{*mpRegisteredEmail = registeredEmail;}
const std::string & CRegistration::getRegisteredEmail() const
{return *mpRegisteredEmail;}
void CRegistration::setRegisteredUser(const std::string & registeredUser)
{*mpRegisteredUser = registeredUser;}
const std::string & CRegistration::getRegisteredUser() const
{return *mpRegisteredUser;}
void CRegistration::setRegistrationCode(const std::string & registrationCode)
{*mpRegistrationCode = registrationCode;}
const std::string & CRegistration::getRegistrationCode() const
{return *mpRegistrationCode;}
bool CRegistration::isValidRegistration() const
{
bool Trial = false;
// Check whether the registration code is correct.
if (!decodeGenericRegCode(config, mpRegistrationCode->c_str()))
{
// We have a valid registration code.
Trial = !strcmp("T", getConstant());
if (Trial)
{
unsigned C_INT32 Date = strtoul(getDate(), NULL, 10);
// day and year license created
unsigned C_INT32 Day = Date / 10 - 1; // 0 - 365
unsigned C_INT32 Year = Date % 10; // 0 - 9
time_t CurrentTime = time(NULL);
tm * pLocalTime = localtime(&CurrentTime);
// License creation year minus 1900
// Was the license created in the previous decade?
if (Year != 0 && (pLocalTime->tm_year % 10) == 0)
Year += pLocalTime->tm_year - 10;
else
Year += pLocalTime->tm_year - (pLocalTime->tm_year % 10);
// End of day
pLocalTime->tm_sec = 0;
pLocalTime->tm_min = 0;
pLocalTime->tm_hour = 24;
// License creation day + 31
pLocalTime->tm_year = Year;
pLocalTime->tm_mday += Day + 31 - pLocalTime->tm_yday;
mExpirationDate = mktime(pLocalTime);
}
else
{
mExpirationDate = -1;
}
}
else
{
CCopasiMessage(CCopasiMessage::RAW, MCRegistration + 1);
return false;
}
// Check whether Email and User are correct.
setUserEmail(mpRegisteredEmail->c_str());
setUserName(mpRegisteredUser->c_str());
createUserSeed();
if (strcmp(getUserSeed(), getCreatedUserSeed()))
{
CCopasiMessage(CCopasiMessage::RAW, MCRegistration + 2);
return false;
}
// Check whether a trial license is expired.
if (Trial)
{
unsigned C_INT32 CurrentTime = time(NULL);
if (CurrentTime > mExpirationDate)
{
std::string ExpirationStr = ctime(&mExpirationDate);
// Remove the line break character '\n'
ExpirationStr.erase(ExpirationStr.length() - 1);
CCopasiMessage(CCopasiMessage::RAW, MCRegistration + 3, ExpirationStr.c_str());
return false;
}
}
std::stringstream Message;
Message << *mpRegistrationCode << * mpRegisteredEmail << *mpRegisteredUser;
// To prevent copying the configuration file
std::string ConfigFile;
COptions::getValue("ConfigFile", ConfigFile);
Message << ConfigFile;
*mpSignature = Cmd5::digest(Message);
return true;
}
bool CRegistration::isValidSignature() const
{
std::stringstream Message;
Message << *mpRegistrationCode << * mpRegisteredEmail << *mpRegisteredUser;
// To prevent copying the configuration file
std::string ConfigFile;
COptions::getValue("ConfigFile", ConfigFile);
Message << ConfigFile;
if (*mpSignature == Cmd5::digest(Message))
return true;
// Detected tempering with the registration information
// therefore we reset it.
if (isValidRegistration())
{
*mpRegistrationCode = "";
*mpRegisteredEmail = "";
*mpRegisteredUser = "";
}
return false;
}
std::string CRegistration::getExpirationDate() const
{
std::string ExpirationDate;
if (mExpirationDate != -1)
{
ExpirationDate = ctime(&mExpirationDate);
// Remove the line break character '\n'
ExpirationDate.erase(ExpirationDate.length() - 1);
}
else
{
ExpirationDate = "unlimited";
}
return ExpirationDate;
}
|
// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/commercial/Attic/CRegistration.cpp,v $
// $Revision: 1.4 $
// $Name: $
// $Author: shoops $
// $Date: 2007/01/18 20:51:53 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <sstream>
#include "copasi.h"
#include "CRegistration.h"
#include "GenericDecode.h"
#include "Cmd5.h"
#include "commandline/COptions.h"
/*
Seed Combo :en
Seed Length: 13
Minimum Email Length: 1
Minimum Name Length: 1
Minimum HotSync ID Length: 1
Length of Constant: 1
Constant value: T
Sequence Length: 3
Alternate Text: Contact [email protected] to obtain your registration code.
Scramble Order: U7,S0,U0,U8,S2,U3,U12,U1,U11,D3,C0,U5,D2,D0,S1,D1,U4,U10,U2,U6,U9,
ASCII Digit(For text to Number Conversion):2
Math Operation(Example:36A(36->Operand,A-Addition)): 23S,5A,R,37S,1A,R,7A,13S,R,29S,17S,R,8A,R,4A,7S,R,R,3A,11S,19S,
New Base: 52
Base Character Set: dAK0QyEfTD2UkGM3aehxYRi48uz19Wb7qgFJCtXNH65ncrwmpPLj
Registration code format(^ is place holder for check digit) : COPASI-####-####-#^####-####-####-####[-#G3Q]
*/
const char config[] =
"SUPPLIERID:VTIP%E:1%N:1%H:1%COMBO:en%SDLGTH:13%CONSTLGTH:1%CONSTVAL:F%SEQL:3%"
"ALTTEXT:Contact [email protected] to obtain your registration code.%"
"SCRMBL:U7,,S0,,U0,,U8,,S2,,U3,,U12,,U1,,U11,,D3,,C0,,U5,,D2,,D0,,S1,,D1,,U4,,U10,,U2,,U6,,U9,,%"
"ASCDIG:2%MATH:23S,,5A,,R,,37S,,1A,,R,,7A,,13S,,R,,29S,,17S,,R,,8A,,R,,4A,,7S,,R,,R,,3A,,11S,,19S,,%"
"BASE:52%BASEMAP:dAK0QyEfTD2UkGM3aehxYRi48uz19Wb7qgFJCtXNH65ncrwmpPLj%"
"REGFRMT:COPASI-####-####-#^####-####-####-####[-#G3Q]";
CRegistration::CRegistration(const std::string & name,
const CCopasiContainer * pParent):
CCopasiParameterGroup(name, pParent),
mpRegisteredEmail(NULL),
mpRegisteredUser(NULL),
mpRegistrationCode(NULL),
mpSignature(NULL),
mExpirationDate(-1)
{initializeParameter();}
CRegistration::CRegistration(const CRegistration & src,
const CCopasiContainer * pParent):
CCopasiParameterGroup(src, pParent),
mpRegisteredEmail(NULL),
mpRegisteredUser(NULL),
mpRegistrationCode(NULL),
mpSignature(NULL),
mExpirationDate(src.mExpirationDate)
{initializeParameter();}
CRegistration::CRegistration(const CCopasiParameterGroup & group,
const CCopasiContainer * pParent):
CCopasiParameterGroup(group, pParent),
mpRegisteredEmail(NULL),
mpRegisteredUser(NULL),
mpRegistrationCode(NULL),
mpSignature(NULL),
mExpirationDate(-1)
{initializeParameter();}
CRegistration::~CRegistration() {}
void CRegistration::initializeParameter()
{
mpRegisteredEmail =
assertParameter("Registered Email", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
mpRegisteredUser =
assertParameter("Registered User", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
mpRegistrationCode =
assertParameter("Registration Code", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
mpSignature =
assertParameter("Signature", CCopasiParameter::STRING, std::string(""))->getValue().pSTRING;
}
void CRegistration::setRegisteredEmail(const std::string & registeredEmail)
{*mpRegisteredEmail = registeredEmail;}
const std::string & CRegistration::getRegisteredEmail() const
{return *mpRegisteredEmail;}
void CRegistration::setRegisteredUser(const std::string & registeredUser)
{*mpRegisteredUser = registeredUser;}
const std::string & CRegistration::getRegisteredUser() const
{return *mpRegisteredUser;}
void CRegistration::setRegistrationCode(const std::string & registrationCode)
{*mpRegistrationCode = registrationCode;}
const std::string & CRegistration::getRegistrationCode() const
{return *mpRegistrationCode;}
bool CRegistration::isValidRegistration() const
{
bool Trial = false;
// Check whether the registration code is correct.
if (!decodeGenericRegCode(config, mpRegistrationCode->c_str()))
{
// We have a valid registration code.
Trial = !strcmp("T", getConstant());
if (Trial)
{
unsigned C_INT32 Date = strtoul(getDate(), NULL, 10);
// day and year license created
unsigned C_INT32 Day = Date / 10 - 1; // 0 - 365
unsigned C_INT32 Year = Date % 10; // 0 - 9
time_t CurrentTime = time(NULL);
tm * pLocalTime = localtime(&CurrentTime);
// License creation year minus 1900
// Was the license created in the previous decade?
if (Year != 0 && (pLocalTime->tm_year % 10) == 0)
Year += pLocalTime->tm_year - 10;
else
Year += pLocalTime->tm_year - (pLocalTime->tm_year % 10);
// End of day
pLocalTime->tm_sec = 0;
pLocalTime->tm_min = 0;
pLocalTime->tm_hour = 24;
// License creation day + 31
pLocalTime->tm_year = Year;
pLocalTime->tm_mday += Day + 31 - pLocalTime->tm_yday;
mExpirationDate = mktime(pLocalTime);
}
else
{
mExpirationDate = -1;
}
}
else
{
CCopasiMessage(CCopasiMessage::RAW, MCRegistration + 1);
return false;
}
// Check whether Email and User are correct.
setUserEmail(mpRegisteredEmail->c_str());
setUserName(mpRegisteredUser->c_str());
createUserSeed();
if (strcmp(getUserSeed(), getCreatedUserSeed()))
{
CCopasiMessage(CCopasiMessage::RAW, MCRegistration + 2);
return false;
}
// Check whether a trial license is expired.
if (Trial)
{
unsigned C_INT32 CurrentTime = time(NULL);
if (CurrentTime > mExpirationDate)
{
std::string ExpirationStr = ctime(&mExpirationDate);
// Remove the line break character '\n'
ExpirationStr.erase(ExpirationStr.length() - 1);
CCopasiMessage(CCopasiMessage::RAW, MCRegistration + 3, ExpirationStr.c_str());
return false;
}
}
std::stringstream Message;
Message << *mpRegistrationCode << * mpRegisteredEmail << *mpRegisteredUser;
// To prevent copying the configuration file
std::string ConfigFile;
COptions::getValue("ConfigFile", ConfigFile);
Message << ConfigFile;
*mpSignature = Cmd5::digest(Message);
return true;
}
bool CRegistration::isValidSignature() const
{
std::stringstream Message;
Message << *mpRegistrationCode << * mpRegisteredEmail << *mpRegisteredUser;
// To prevent copying the configuration file
std::string ConfigFile;
COptions::getValue("ConfigFile", ConfigFile);
Message << ConfigFile;
if (*mpSignature == Cmd5::digest(Message))
return true;
// Detected tempering with the registration information
// therefore we reset it.
if (isValidRegistration())
{
*mpRegistrationCode = "";
*mpRegisteredEmail = "";
*mpRegisteredUser = "";
}
return false;
}
std::string CRegistration::getExpirationDate() const
{
std::string ExpirationDate;
if (mExpirationDate != -1)
{
ExpirationDate = ctime(&mExpirationDate);
// Remove the line break character '\n'
ExpirationDate.erase(ExpirationDate.length() - 1);
}
else
{
ExpirationDate = "unlimited";
}
return ExpirationDate;
}
|
Change in ACG config, which has no consequences for the code and binaries.
|
Change in ACG config, which has no consequences for the code and binaries.
|
C++
|
artistic-2.0
|
copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI
|
09cb43fdcb6b8a47832f0a9787e2cbc4e070d81e
|
mjolnir/util/color.hpp
|
mjolnir/util/color.hpp
|
#ifndef MJOLNIR_UTILITY_COLOR_HPP
#define MJOLNIR_UTILITY_COLOR_HPP
#include <mjolnir/util/io.hpp>
// This utility manipulators output some ANSI escape codes.
// On Windows (not supported by Mjolnir currently), it does not check
// the stream is connected to a tty.
namespace mjolnir
{
namespace io
{
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& red(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[31m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& green(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[32m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& yellow(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[33m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& blue(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[34m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& magenta(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[35m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& cyan(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[36m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& white(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[37m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& nocolor(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[0m";
}
return os;
}
template<typename charT, typename traits>
struct basic_lock_nocolor
{
explicit basic_lock_nocolor(std::basic_ostream<charT, traits>& os) noexcept
: os_(std::addressof(os))
{}
~basic_lock_nocolor() noexcept
{
if(os_)
{
*os_ << nocolor;
}
}
private:
std::basic_ostream<charT, traits>* os_;
};
template<typename charT, typename traits>
basic_lock_nocolor<charT, traits>
lock_nocolor(std::basic_ostream<charT, traits>& os) noexcept
{
return basic_lock_nocolor<charT, traits>(os);
}
} // io
} // mjolnir
#endif// MJOLNIR_UTILITY_COLOR_HPP
|
#ifndef MJOLNIR_UTILITY_COLOR_HPP
#define MJOLNIR_UTILITY_COLOR_HPP
#include <mjolnir/util/io.hpp>
// This utility manipulators output some ANSI escape codes.
// On Windows (not supported by Mjolnir currently), it does not check
// the stream is connected to a tty.
namespace mjolnir
{
namespace io
{
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& bold(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[01m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& red(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[31m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& green(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[32m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& yellow(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[33m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& blue(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[34m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& magenta(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[35m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& cyan(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[36m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& white(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[37m";
}
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& nocolor(std::basic_ostream<charT, traits>& os)
{
if(detail::isatty(os))
{
os << "\x1b[0m";
}
return os;
}
template<typename charT, typename traits>
struct basic_lock_nocolor
{
explicit basic_lock_nocolor(std::basic_ostream<charT, traits>& os) noexcept
: os_(std::addressof(os))
{}
~basic_lock_nocolor() noexcept
{
if(os_)
{
*os_ << nocolor;
}
}
private:
std::basic_ostream<charT, traits>* os_;
};
template<typename charT, typename traits>
basic_lock_nocolor<charT, traits>
lock_nocolor(std::basic_ostream<charT, traits>& os) noexcept
{
return basic_lock_nocolor<charT, traits>(os);
}
} // io
} // mjolnir
#endif// MJOLNIR_UTILITY_COLOR_HPP
|
add stream operator ansi bold
|
feat: add stream operator ansi bold
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
3fb41099c510f186aa93f6f637e217a31301ddbb
|
examples/ChildWidget.hpp
|
examples/ChildWidget.hpp
|
/**
* HAL
*
* Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _HAL_EXAMPLES_CHILDWIDGET_HPP_
#define _HAL_EXAMPLES_CHILDWIDGET_HPP_
#include "HAL/HAL.hpp"
#include <string>
#include "Widget.hpp"
using namespace HAL;
/*!
@class
@discussion This is an example of how to create a JavaScript object
implemented by a C++ class.
*/
class ChildWidget : public Widget, public JSExport<ChildWidget> {
public:
ChildWidget(const JSContext& js_context) HAL_NOEXCEPT;
virtual ~ChildWidget() HAL_NOEXCEPT;
ChildWidget(const ChildWidget&) HAL_NOEXCEPT = default;
ChildWidget(ChildWidget&&) HAL_NOEXCEPT = default;
ChildWidget& operator=(const ChildWidget&) HAL_NOEXCEPT = default;
ChildWidget& operator=(ChildWidget&&) HAL_NOEXCEPT = default;
static void JSExportInitialize();
virtual void postInitialize(JSObject& js_object) override;
virtual void postCallAsConstructor(const JSContext& js_context, const std::vector<JSValue>& arguments) override;
JSValue js_get_name() const HAL_NOEXCEPT;
JSValue js_get_my_name() const HAL_NOEXCEPT;
private:
};
inline
void swap(ChildWidget& first, ChildWidget& second) HAL_NOEXCEPT {
first.swap(second);
}
#endif // _HAL_EXAMPLES_CHILDWIDGET_HPP_
|
/**
* HAL
*
* Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _HAL_EXAMPLES_CHILDWIDGET_HPP_
#define _HAL_EXAMPLES_CHILDWIDGET_HPP_
#include "HAL/HAL.hpp"
#include <string>
#include "Widget.hpp"
using namespace HAL;
/*!
@class
@discussion This is an example of how to create a JavaScript object
implemented by a C++ class.
*/
class ChildWidget : public Widget, public JSExport<ChildWidget> {
public:
ChildWidget(const JSContext& js_context) HAL_NOEXCEPT;
virtual ~ChildWidget() HAL_NOEXCEPT;
static void JSExportInitialize();
virtual void postInitialize(JSObject& js_object) override;
virtual void postCallAsConstructor(const JSContext& js_context, const std::vector<JSValue>& arguments) override;
JSValue js_get_name() const HAL_NOEXCEPT;
JSValue js_get_my_name() const HAL_NOEXCEPT;
private:
};
inline
void swap(ChildWidget& first, ChildWidget& second) HAL_NOEXCEPT {
first.swap(second);
}
#endif // _HAL_EXAMPLES_CHILDWIDGET_HPP_
|
Fix compile error on Windows
|
Fix compile error on Windows
|
C++
|
apache-2.0
|
formalin14/HAL,formalin14/HAL,yuchi/HAL,yuchi/HAL,formalin14/HAL,yuchi/HAL
|
5dd626a6d34331d1712f49ed164b7aa47a2d7ea7
|
src/test/test_bitcoin_fuzzy.cpp
|
src/test/test_bitcoin_fuzzy.cpp
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "consensus/merkle.h"
#include "primitives/block.h"
#include "script/script.h"
#include "addrman.h"
#include "chain.h"
#include "coins.h"
#include "compressor.h"
#include "net.h"
#include "protocol.h"
#include "streams.h"
#include "undo.h"
#include "version.h"
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <vector>
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
TEST_ID_END
};
bool read_stdin(std::vector<char> &data) {
char buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
if (data.size() > (1<<20)) return false;
}
return length==0;
}
int main(int argc, char **argv)
{
std::vector<char> buffer;
if (!read_stdin(buffer)) return 0;
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, &buffer[0], sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return 0;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return 0;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
CCoins block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return 0;}
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
try
{
ds >> to;
} catch (const std::ios_base::failure& e) {return 0;}
CTxOutCompressor toc(to);
break;
}
default:
return 0;
}
return 0;
}
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "consensus/merkle.h"
#include "primitives/block.h"
#include "script/script.h"
#include "addrman.h"
#include "chain.h"
#include "coins.h"
#include "compressor.h"
#include "net.h"
#include "protocol.h"
#include "streams.h"
#include "undo.h"
#include "version.h"
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <vector>
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
TEST_ID_END
};
bool read_stdin(std::vector<char> &data) {
char buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
if (data.size() > (1<<20)) return false;
}
return length==0;
}
int main(int argc, char **argv)
{
std::vector<char> buffer;
if (!read_stdin(buffer)) return 0;
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, &buffer[0], sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return 0;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return 0;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
CCoins block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return 0;}
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
CTxOutCompressor toc(to);
try
{
ds >> toc;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
default:
return 0;
}
return 0;
}
|
Make fuzzer actually test CTxOutCompressor
|
Make fuzzer actually test CTxOutCompressor
|
C++
|
mit
|
bitcoin/bitcoin,mincoin-project/mincoin,midnightmagic/bitcoin,AkioNak/bitcoin,ajtowns/bitcoin,guncoin/guncoin,Bitcoin-ABC/bitcoin-abc,mruddy/bitcoin,MarcoFalke/bitcoin,EthanHeilman/bitcoin,starwels/starwels,monacoinproject/monacoin,Theshadow4all/ShadowCoin,DigiByte-Team/digibyte,afk11/bitcoin,peercoin/peercoin,Rav3nPL/PLNcoin,wiggi/huntercore,Kogser/bitcoin,ShadowMyst/creativechain-core,FeatherCoin/Feathercoin,n1bor/bitcoin,destenson/bitcoin--bitcoin,wiggi/huntercore,prusnak/bitcoin,apoelstra/bitcoin,CryptArc/bitcoin,AdrianaDinca/bitcoin,kevcooper/bitcoin,fujicoin/fujicoin,bitcoinsSG/bitcoin,GroestlCoin/GroestlCoin,spiritlinxl/BTCGPU,Rav3nPL/bitcoin,wiggi/huntercore,achow101/bitcoin,maaku/bitcoin,sbaks0820/bitcoin,kallewoof/elements,jlopp/statoshi,mincoin-project/mincoin,untrustbank/litecoin,laudaa/bitcoin,lbryio/lbrycrd,lateminer/bitcoin,Chancoin-core/CHANCOIN,sarielsaz/sarielsaz,zcoinofficial/zcoin,segsignal/bitcoin,Mirobit/bitcoin,Rav3nPL/bitcoin,jamesob/bitcoin,fanquake/bitcoin,RHavar/bitcoin,practicalswift/bitcoin,goldcoin/Goldcoin-GLD,sipsorcery/bitcoin,UFOCoins/ufo,droark/bitcoin,jtimon/bitcoin,particl/particl-core,vertcoin/vertcoin,Jcing95/iop-hd,JeremyRubin/bitcoin,zcoinofficial/zcoin,x-kalux/bitcoin_WiG-B,dgarage/bc3,GroestlCoin/GroestlCoin,rnicoll/bitcoin,rawodb/bitcoin,bitcoin/bitcoin,patricklodder/dogecoin,BitcoinHardfork/bitcoin,tecnovert/particl-core,dgarage/bc2,trippysalmon/bitcoin,joshrabinowitz/bitcoin,MarcoFalke/bitcoin,EntropyFactory/creativechain-core,CryptArc/bitcoin,RHavar/bitcoin,multicoins/marycoin,daliwangi/bitcoin,kevcooper/bitcoin,bitreserve/bitcoin,spiritlinxl/BTCGPU,kazcw/bitcoin,lbryio/lbrycrd,174high/bitcoin,anditto/bitcoin,gjhiggins/vcoincore,BitzenyCoreDevelopers/bitzeny,peercoin/peercoin,gmaxwell/bitcoin,jnewbery/bitcoin,globaltoken/globaltoken,ElementsProject/elements,tdudz/elements,afk11/bitcoin,Mirobit/bitcoin,jonasschnelli/bitcoin,tecnovert/particl-core,Flowdalic/bitcoin,Jcing95/iop-hd,zcoinofficial/zcoin,vertcoin/vertcoin,kallewoof/bitcoin,globaltoken/globaltoken,Christewart/bitcoin,kazcw/bitcoin,destenson/bitcoin--bitcoin,bitbrazilcoin-project/bitbrazilcoin,x-kalux/bitcoin_WiG-B,DigiByte-Team/digibyte,pstratem/bitcoin,OmniLayer/omnicore,digibyte/digibyte,xieta/mincoin,thrasher-/litecoin,isle2983/bitcoin,laudaa/bitcoin,kazcw/bitcoin,sebrandon1/bitcoin,n1bor/bitcoin,Rav3nPL/PLNcoin,practicalswift/bitcoin,fujicoin/fujicoin,GlobalBoost/GlobalBoost,GlobalBoost/GlobalBoost,mb300sd/bitcoin,ftrader-bitcoinabc/bitcoin-abc,argentumproject/argentum,trippysalmon/bitcoin,jonasschnelli/bitcoin,DigitalPandacoin/pandacoin,kallewoof/bitcoin,ryanofsky/bitcoin,Rav3nPL/PLNcoin,yenliangl/bitcoin,ppcoin/ppcoin,sstone/bitcoin,jonasschnelli/bitcoin,mm-s/bitcoin,xieta/mincoin,bespike/litecoin,patricklodder/dogecoin,bitreserve/bitcoin,donaloconnor/bitcoin,particl/particl-core,TheBlueMatt/bitcoin,mb300sd/bitcoin,namecoin/namecoin-core,namecoin/namecore,sstone/bitcoin,particl/particl-core,wangxinxi/litecoin,goldcoin/Goldcoin-GLD,cryptoprojects/ultimateonlinecash,anditto/bitcoin,nlgcoin/guldencoin-official,pstratem/bitcoin,monacoinproject/monacoin,myriadteam/myriadcoin,Rav3nPL/bitcoin,StarbuckBG/BTCGPU,randy-waterhouse/bitcoin,trippysalmon/bitcoin,Theshadow4all/ShadowCoin,psionin/smartcoin,Anfauglith/iop-hd,djpnewton/bitcoin,digibyte/digibyte,apoelstra/bitcoin,sstone/bitcoin,apoelstra/bitcoin,anditto/bitcoin,dgarage/bc2,jamesob/bitcoin,bitreserve/bitcoin,cculianu/bitcoin-abc,senadmd/coinmarketwatch,bespike/litecoin,ftrader-bitcoinabc/bitcoin-abc,DigiByte-Team/digibyte,GroestlCoin/bitcoin,core-bitcoin/bitcoin,plncoin/PLNcoin_Core,bitcoin/bitcoin,shelvenzhou/BTCGPU,Bushstar/UFO-Project,zcoinofficial/zcoin,jnewbery/bitcoin,senadmd/coinmarketwatch,rnicoll/dogecoin,btc1/bitcoin,x-kalux/bitcoin_WiG-B,wellenreiter01/Feathercoin,Sjors/bitcoin,UASF/bitcoin,domob1812/bitcoin,CryptArc/bitcoin,1185/starwels,rnicoll/dogecoin,Cocosoft/bitcoin,jtimon/bitcoin,vertcoin/vertcoin,Bitcoin-ABC/bitcoin-abc,pstratem/bitcoin,Anfauglith/iop-hd,uphold/bitcoin,djpnewton/bitcoin,pataquets/namecoin-core,apoelstra/bitcoin,gmaxwell/bitcoin,bitreserve/bitcoin,jimmysong/bitcoin,tdudz/elements,globaltoken/globaltoken,argentumproject/argentum,ahmedbodi/temp_vert,sarielsaz/sarielsaz,Kogser/bitcoin,ahmedbodi/temp_vert,jiangyonghang/bitcoin,mruddy/bitcoin,Kogser/bitcoin,bitcoinknots/bitcoin,AkioNak/bitcoin,Xekyo/bitcoin,ShadowMyst/creativechain-core,dogecoin/dogecoin,Xekyo/bitcoin,argentumproject/argentum,viacoin/viacoin,21E14/bitcoin,dpayne9000/Rubixz-Coin,guncoin/guncoin,ahmedbodi/vertcoin,r8921039/bitcoin,Rav3nPL/PLNcoin,Bitcoin-ABC/bitcoin-abc,GlobalBoost/GlobalBoost,domob1812/namecore,sebrandon1/bitcoin,vertcoin/vertcoin,litecoin-project/litecoin,OmniLayer/omnicore,elecoin/elecoin,lbryio/lbrycrd,matlongsi/micropay,vmp32k/litecoin,tdudz/elements,argentumproject/argentum,shelvenzhou/BTCGPU,isle2983/bitcoin,mincoin-project/mincoin,ShadowMyst/creativechain-core,pstratem/bitcoin,guncoin/guncoin,rawodb/bitcoin,bitcoinknots/bitcoin,starwels/starwels,romanornr/viacoin,jonasschnelli/bitcoin,NicolasDorier/bitcoin,psionin/smartcoin,RHavar/bitcoin,Cocosoft/bitcoin,BTCGPU/BTCGPU,dscotese/bitcoin,yenliangl/bitcoin,plncoin/PLNcoin_Core,StarbuckBG/BTCGPU,bitbrazilcoin-project/bitbrazilcoin,OmniLayer/omnicore,ajtowns/bitcoin,domob1812/bitcoin,kallewoof/elements,spiritlinxl/BTCGPU,GroestlCoin/bitcoin,DigitalPandacoin/pandacoin,segsignal/bitcoin,MarcoFalke/bitcoin,argentumproject/argentum,ajtowns/bitcoin,ryanofsky/bitcoin,dpayne9000/Rubixz-Coin,n1bor/bitcoin,tjps/bitcoin,Xekyo/bitcoin,Rav3nPL/bitcoin,elecoin/elecoin,ftrader-bitcoinabc/bitcoin-abc,litecoin-project/litecoin,senadmd/coinmarketwatch,EntropyFactory/creativechain-core,kevcooper/bitcoin,ElementsProject/elements,daliwangi/bitcoin,NicolasDorier/bitcoin,nikkitan/bitcoin,Mirobit/bitcoin,gmaxwell/bitcoin,matlongsi/micropay,Gazer022/bitcoin,BitcoinPOW/BitcoinPOW,Friedbaumer/litecoin,jamesob/bitcoin,Bitcoin-ABC/bitcoin-abc,UASF/bitcoin,randy-waterhouse/bitcoin,n1bor/bitcoin,uphold/bitcoin,NicolasDorier/bitcoin,GlobalBoost/GlobalBoost,globaltoken/globaltoken,Bitcoin-ABC/bitcoin-abc,Rav3nPL/bitcoin,FeatherCoin/Feathercoin,jambolo/bitcoin,Kogser/bitcoin,sbaks0820/bitcoin,wangxinxi/litecoin,bitreserve/bitcoin,BTCGPU/BTCGPU,r8921039/bitcoin,ryanofsky/bitcoin,achow101/bitcoin,n1bor/bitcoin,StarbuckBG/BTCGPU,bitcoinknots/bitcoin,bespike/litecoin,FeatherCoin/Feathercoin,laudaa/bitcoin,pstratem/bitcoin,Christewart/bitcoin,alecalve/bitcoin,simonmulser/bitcoin,core-bitcoin/bitcoin,afk11/bitcoin,paveljanik/bitcoin,jtimon/bitcoin,donaloconnor/bitcoin,ryanofsky/bitcoin,XertroV/bitcoin-nulldata,lateminer/bitcoin,bespike/litecoin,sarielsaz/sarielsaz,MazaCoin/maza,segsignal/bitcoin,practicalswift/bitcoin,OmniLayer/omnicore,andreaskern/bitcoin,TheBlueMatt/bitcoin,rnicoll/bitcoin,bitcoinec/bitcoinec,r8921039/bitcoin,digibyte/digibyte,vertcoin/vertcoin,namecoin/namecore,AdrianaDinca/bitcoin,sstone/bitcoin,Theshadow4all/ShadowCoin,BitcoinHardfork/bitcoin,mb300sd/bitcoin,nlgcoin/guldencoin-official,bitreserve/bitcoin,jimmysong/bitcoin,NicolasDorier/bitcoin,ElementsProject/elements,sebrandon1/bitcoin,elecoin/elecoin,mitchellcash/bitcoin,cculianu/bitcoin-abc,segsignal/bitcoin,djpnewton/bitcoin,deeponion/deeponion,pinheadmz/bitcoin,EthanHeilman/bitcoin,tjps/bitcoin,vmp32k/litecoin,Exgibichi/statusquo,gjhiggins/vcoincore,joshrabinowitz/bitcoin,deeponion/deeponion,Cocosoft/bitcoin,brandonrobertz/namecoin-core,Chancoin-core/CHANCOIN,UFOCoins/ufo,Flowdalic/bitcoin,Sjors/bitcoin,achow101/bitcoin,practicalswift/bitcoin,namecoin/namecore,UFOCoins/ufo,awemany/BitcoinUnlimited,jimmysong/bitcoin,afk11/bitcoin,Chancoin-core/CHANCOIN,trippysalmon/bitcoin,h4x3rotab/BTCGPU,multicoins/marycoin,174high/bitcoin,elecoin/elecoin,practicalswift/bitcoin,BitcoinPOW/BitcoinPOW,jiangyonghang/bitcoin,s-matthew-english/bitcoin,untrustbank/litecoin,litecoin-project/litecoin,jambolo/bitcoin,mitchellcash/bitcoin,ftrader-bitcoinabc/bitcoin-abc,earonesty/bitcoin,21E14/bitcoin,argentumproject/argentum,21E14/bitcoin,fanquake/bitcoin,BitzenyCoreDevelopers/bitzeny,qtumproject/qtum,prusnak/bitcoin,ftrader-bitcoinabc/bitcoin-abc,HashUnlimited/Einsteinium-Unlimited,Theshadow4all/ShadowCoin,stamhe/bitcoin,untrustbank/litecoin,nbenoit/bitcoin,Bitcoin-ABC/bitcoin-abc,EthanHeilman/bitcoin,ericshawlinux/bitcoin,GlobalBoost/GlobalBoost,gjhiggins/vcoincore,ftrader-bitcoinabc/bitcoin-abc,jmcorgan/bitcoin,prusnak/bitcoin,Gazer022/bitcoin,ftrader-bitcoinabc/bitcoin-abc,particl/particl-core,bespike/litecoin,MeshCollider/bitcoin,nikkitan/bitcoin,dscotese/bitcoin,Mirobit/bitcoin,vmp32k/litecoin,deeponion/deeponion,mitchellcash/bitcoin,dogecoin/dogecoin,namecoin/namecore,senadmd/coinmarketwatch,awemany/BitcoinUnlimited,MazaCoin/maza,wiggi/huntercore,jimmysong/bitcoin,jmcorgan/bitcoin,jamesob/bitcoin,rnicoll/dogecoin,rnicoll/bitcoin,s-matthew-english/bitcoin,wangxinxi/litecoin,multicoins/marycoin,nlgcoin/guldencoin-official,HashUnlimited/Einsteinium-Unlimited,dogecoin/dogecoin,BigBlueCeiling/augmentacoin,kallewoof/elements,trippysalmon/bitcoin,earonesty/bitcoin,rawodb/bitcoin,CryptArc/bitcoin,gjhiggins/vcoincore,paveljanik/bitcoin,guncoin/guncoin,FeatherCoin/Feathercoin,mincoin-project/mincoin,gmaxwell/bitcoin,Xekyo/bitcoin,ajtowns/bitcoin,h4x3rotab/BTCGPU,StarbuckBG/BTCGPU,vmp32k/litecoin,sarielsaz/sarielsaz,BTCGPU/BTCGPU,174high/bitcoin,sbaks0820/bitcoin,yenliangl/bitcoin,qtumproject/qtum,cculianu/bitcoin-abc,goldcoin/Goldcoin-GLD,ftrader-bitcoinabc/bitcoin-abc,fujicoin/fujicoin,jiangyonghang/bitcoin,cculianu/bitcoin-abc,DigiByte-Team/digibyte,Friedbaumer/litecoin,MazaCoin/maza,apoelstra/bitcoin,EthanHeilman/bitcoin,HashUnlimited/Einsteinium-Unlimited,ajtowns/bitcoin,qtumproject/qtum,dpayne9000/Rubixz-Coin,DigitalPandacoin/pandacoin,domob1812/bitcoin,dscotese/bitcoin,kevcooper/bitcoin,isle2983/bitcoin,wellenreiter01/Feathercoin,tecnovert/particl-core,simonmulser/bitcoin,midnightmagic/bitcoin,MarcoFalke/bitcoin,myriadcoin/myriadcoin,Bushstar/UFO-Project,tecnovert/particl-core,nlgcoin/guldencoin-official,peercoin/peercoin,tecnovert/particl-core,viacoin/viacoin,alecalve/bitcoin,daliwangi/bitcoin,earonesty/bitcoin,patricklodder/dogecoin,RHavar/bitcoin,goldcoin/goldcoin,BigBlueCeiling/augmentacoin,21E14/bitcoin,UASF/bitcoin,bitcoinknots/bitcoin,domob1812/bitcoin,Jcing95/iop-hd,ahmedbodi/temp_vert,ericshawlinux/bitcoin,dgarage/bc3,JeremyRubin/bitcoin,particl/particl-core,jambolo/bitcoin,Jcing95/iop-hd,AdrianaDinca/bitcoin,djpnewton/bitcoin,rnicoll/bitcoin,jambolo/bitcoin,tecnovert/particl-core,Gazer022/bitcoin,pataquets/namecoin-core,BTCGPU/BTCGPU,DigiByte-Team/digibyte,simonmulser/bitcoin,21E14/bitcoin,kallewoof/bitcoin,rnicoll/bitcoin,midnightmagic/bitcoin,tdudz/elements,digibyte/digibyte,bitcoin/bitcoin,wangxinxi/litecoin,jlopp/statoshi,globaltoken/globaltoken,rebroad/bitcoin,rebroad/bitcoin,cdecker/bitcoin,AkioNak/bitcoin,pataquets/namecoin-core,ahmedbodi/vertcoin,rawodb/bitcoin,174high/bitcoin,Bitcoin-ABC/bitcoin-abc,mb300sd/bitcoin,sipsorcery/bitcoin,prusnak/bitcoin,Bitcoin-ABC/bitcoin-abc,btc1/bitcoin,Gazer022/bitcoin,sbaks0820/bitcoin,anditto/bitcoin,ajtowns/bitcoin,shelvenzhou/BTCGPU,Friedbaumer/litecoin,myriadteam/myriadcoin,xieta/mincoin,psionin/smartcoin,monacoinproject/monacoin,BitcoinPOW/BitcoinPOW,Christewart/bitcoin,gjhiggins/vcoincore,Kogser/bitcoin,goldcoin/goldcoin,fujicoin/fujicoin,dpayne9000/Rubixz-Coin,anditto/bitcoin,h4x3rotab/BTCGPU,TheBlueMatt/bitcoin,achow101/bitcoin,starwels/starwels,btc1/bitcoin,untrustbank/litecoin,brandonrobertz/namecoin-core,dgarage/bc2,NicolasDorier/bitcoin,mruddy/bitcoin,laudaa/bitcoin,lateminer/bitcoin,donaloconnor/bitcoin,dgarage/bc2,TheBlueMatt/bitcoin,particl/particl-core,goldcoin/Goldcoin-GLD,tjps/bitcoin,Bitcoin-ABC/bitcoin-abc,1185/starwels,jlopp/statoshi,ppcoin/ppcoin,kallewoof/elements,cculianu/bitcoin-abc,kallewoof/bitcoin,DigiByte-Team/digibyte,UFOCoins/ufo,achow101/bitcoin,qtumproject/qtum,dogecoin/dogecoin,StarbuckBG/BTCGPU,MeshCollider/bitcoin,AdrianaDinca/bitcoin,BitcoinHardfork/bitcoin,bitcoinec/bitcoinec,JeremyRubin/bitcoin,segsignal/bitcoin,AkioNak/bitcoin,BitcoinPOW/BitcoinPOW,pataquets/namecoin-core,Anfauglith/iop-hd,kevcooper/bitcoin,svost/bitcoin,domob1812/namecore,stamhe/bitcoin,rebroad/bitcoin,instagibbs/bitcoin,rebroad/bitcoin,jtimon/bitcoin,BTCGPU/BTCGPU,litecoin-project/litecoin,ahmedbodi/temp_vert,MeshCollider/bitcoin,guncoin/guncoin,romanornr/viacoin,bespike/litecoin,dscotese/bitcoin,wellenreiter01/Feathercoin,ryanofsky/bitcoin,RHavar/bitcoin,Mirobit/bitcoin,pinheadmz/bitcoin,tjps/bitcoin,HashUnlimited/Einsteinium-Unlimited,ryanofsky/bitcoin,romanornr/viacoin,ppcoin/ppcoin,BitcoinPOW/BitcoinPOW,appop/bitcoin,destenson/bitcoin--bitcoin,cdecker/bitcoin,namecoin/namecoin-core,1185/starwels,instagibbs/bitcoin,mincoin-project/mincoin,Mirobit/bitcoin,brandonrobertz/namecoin-core,droark/bitcoin,lbryio/lbrycrd,s-matthew-english/bitcoin,instagibbs/bitcoin,appop/bitcoin,xieta/mincoin,namecoin/namecore,starwels/starwels,pataquets/namecoin-core,djpnewton/bitcoin,jimmysong/bitcoin,rnicoll/dogecoin,joshrabinowitz/bitcoin,practicalswift/bitcoin,core-bitcoin/bitcoin,senadmd/coinmarketwatch,jlopp/statoshi,monacoinproject/monacoin,cryptoprojects/ultimateonlinecash,andreaskern/bitcoin,BigBlueCeiling/augmentacoin,myriadcoin/myriadcoin,maaku/bitcoin,randy-waterhouse/bitcoin,UASF/bitcoin,dgarage/bc2,jambolo/bitcoin,nikkitan/bitcoin,BTCGPU/BTCGPU,alecalve/bitcoin,ShadowMyst/creativechain-core,appop/bitcoin,AkioNak/bitcoin,jnewbery/bitcoin,s-matthew-english/bitcoin,afk11/bitcoin,goldcoin/goldcoin,spiritlinxl/BTCGPU,Xekyo/bitcoin,kallewoof/bitcoin,appop/bitcoin,mm-s/bitcoin,kevcooper/bitcoin,uphold/bitcoin,FeatherCoin/Feathercoin,ericshawlinux/bitcoin,sebrandon1/bitcoin,sarielsaz/sarielsaz,matlongsi/micropay,wangxinxi/litecoin,BigBlueCeiling/augmentacoin,appop/bitcoin,svost/bitcoin,Chancoin-core/CHANCOIN,yenliangl/bitcoin,yenliangl/bitcoin,ShadowMyst/creativechain-core,daliwangi/bitcoin,earonesty/bitcoin,sarielsaz/sarielsaz,litecoin-project/litecoin,pataquets/namecoin-core,MeshCollider/bitcoin,matlongsi/micropay,jmcorgan/bitcoin,namecoin/namecore,Kogser/bitcoin,dgarage/bc3,prusnak/bitcoin,GroestlCoin/bitcoin,sbaks0820/bitcoin,myriadcoin/myriadcoin,174high/bitcoin,ahmedbodi/vertcoin,nikkitan/bitcoin,dogecoin/dogecoin,untrustbank/litecoin,btc1/bitcoin,EntropyFactory/creativechain-core,domob1812/bitcoin,wellenreiter01/Feathercoin,nbenoit/bitcoin,x-kalux/bitcoin_WiG-B,nikkitan/bitcoin,brandonrobertz/namecoin-core,Sjors/bitcoin,nbenoit/bitcoin,x-kalux/bitcoin_WiG-B,deeponion/deeponion,ppcoin/ppcoin,vmp32k/litecoin,pinheadmz/bitcoin,appop/bitcoin,andreaskern/bitcoin,Bushstar/UFO-Project,ahmedbodi/temp_vert,MazaCoin/maza,matlongsi/micropay,XertroV/bitcoin-nulldata,plncoin/PLNcoin_Core,domob1812/huntercore,sbaks0820/bitcoin,daliwangi/bitcoin,x-kalux/bitcoin_WiG-B,xieta/mincoin,ericshawlinux/bitcoin,kallewoof/bitcoin,ElementsProject/elements,viacoin/viacoin,untrustbank/litecoin,svost/bitcoin,s-matthew-english/bitcoin,bitcoinknots/bitcoin,1185/starwels,shelvenzhou/BTCGPU,BitzenyCoreDevelopers/bitzeny,multicoins/marycoin,UFOCoins/ufo,cryptoprojects/ultimateonlinecash,nlgcoin/guldencoin-official,peercoin/peercoin,earonesty/bitcoin,fanquake/bitcoin,romanornr/viacoin,r8921039/bitcoin,joshrabinowitz/bitcoin,aspanta/bitcoin,brandonrobertz/namecoin-core,fanquake/bitcoin,GlobalBoost/GlobalBoost,ahmedbodi/vertcoin,myriadcoin/myriadcoin,namecoin/namecoin-core,patricklodder/dogecoin,viacoin/viacoin,Rav3nPL/PLNcoin,Bitcoin-ABC/bitcoin-abc,r8921039/bitcoin,digibyte/digibyte,lbryio/lbrycrd,Rav3nPL/PLNcoin,isle2983/bitcoin,Exgibichi/statusquo,randy-waterhouse/bitcoin,Anfauglith/iop-hd,goldcoin/goldcoin,btc1/bitcoin,nbenoit/bitcoin,droark/bitcoin,midnightmagic/bitcoin,BigBlueCeiling/augmentacoin,Exgibichi/statusquo,jnewbery/bitcoin,zcoinofficial/zcoin,monacoinproject/monacoin,cdecker/bitcoin,destenson/bitcoin--bitcoin,Christewart/bitcoin,namecoin/namecoin-core,vertcoin/vertcoin,shelvenzhou/BTCGPU,pinheadmz/bitcoin,guncoin/guncoin,ElementsProject/elements,domob1812/huntercore,qtumproject/qtum,bitcoinec/bitcoinec,Bushstar/UFO-Project,bitcoinsSG/bitcoin,romanornr/viacoin,zcoinofficial/zcoin,kazcw/bitcoin,Exgibichi/statusquo,droark/bitcoin,Friedbaumer/litecoin,fanquake/bitcoin,joshrabinowitz/bitcoin,bitcoinec/bitcoinec,domob1812/bitcoin,paveljanik/bitcoin,FeatherCoin/Feathercoin,Cocosoft/bitcoin,plncoin/PLNcoin_Core,mm-s/bitcoin,Cocosoft/bitcoin,Kogser/bitcoin,shelvenzhou/BTCGPU,nlgcoin/guldencoin-official,ahmedbodi/temp_vert,zcoinofficial/zcoin,jiangyonghang/bitcoin,GroestlCoin/GroestlCoin,JeremyRubin/bitcoin,zcoinofficial/zcoin,simonmulser/bitcoin,starwels/starwels,awemany/BitcoinUnlimited,Gazer022/bitcoin,UASF/bitcoin,dscotese/bitcoin,alecalve/bitcoin,viacoin/viacoin,qtumproject/qtum,zcoinofficial/zcoin,maaku/bitcoin,wellenreiter01/Feathercoin,dscotese/bitcoin,CryptArc/bitcoin,myriadteam/myriadcoin,MeshCollider/bitcoin,lbryio/lbrycrd,litecoin-project/litecoin,core-bitcoin/bitcoin,AkioNak/bitcoin,GroestlCoin/GroestlCoin,jtimon/bitcoin,Friedbaumer/litecoin,psionin/smartcoin,bitbrazilcoin-project/bitbrazilcoin,dgarage/bc3,thrasher-/litecoin,cryptoprojects/ultimateonlinecash,Bitcoin-ABC/bitcoin-abc,OmniLayer/omnicore,randy-waterhouse/bitcoin,NicolasDorier/bitcoin,XertroV/bitcoin-nulldata,segsignal/bitcoin,bitcoinsSG/bitcoin,TheBlueMatt/bitcoin,wellenreiter01/Feathercoin,goldcoin/Goldcoin-GLD,lateminer/bitcoin,donaloconnor/bitcoin,prusnak/bitcoin,JeremyRubin/bitcoin,tdudz/elements,Theshadow4all/ShadowCoin,kazcw/bitcoin,elecoin/elecoin,paveljanik/bitcoin,brandonrobertz/namecoin-core,bitbrazilcoin-project/bitbrazilcoin,Theshadow4all/ShadowCoin,aspanta/bitcoin,myriadcoin/myriadcoin,simonmulser/bitcoin,matlongsi/micropay,andreaskern/bitcoin,h4x3rotab/BTCGPU,bitcoinsSG/bitcoin,pinheadmz/bitcoin,argentumproject/argentum,kazcw/bitcoin,jimmysong/bitcoin,maaku/bitcoin,bitcoinec/bitcoinec,senadmd/coinmarketwatch,gjhiggins/vcoincore,uphold/bitcoin,maaku/bitcoin,MazaCoin/maza,Flowdalic/bitcoin,DigitalPandacoin/pandacoin,stamhe/bitcoin,Flowdalic/bitcoin,andreaskern/bitcoin,rebroad/bitcoin,EntropyFactory/creativechain-core,wiggi/huntercore,andreaskern/bitcoin,domob1812/huntercore,tjps/bitcoin,BigBlueCeiling/augmentacoin,s-matthew-english/bitcoin,plncoin/PLNcoin_Core,viacoin/viacoin,cdecker/bitcoin,aspanta/bitcoin,aspanta/bitcoin,mb300sd/bitcoin,sebrandon1/bitcoin,XertroV/bitcoin-nulldata,nikkitan/bitcoin,Anfauglith/iop-hd,thrasher-/litecoin,mruddy/bitcoin,pinheadmz/bitcoin,bitcoin/bitcoin,Jcing95/iop-hd,jiangyonghang/bitcoin,Kogser/bitcoin,ShadowMyst/creativechain-core,r8921039/bitcoin,ftrader-bitcoinabc/bitcoin-abc,cculianu/bitcoin-abc,rawodb/bitcoin,bitcoinsSG/bitcoin,ahmedbodi/vertcoin,rawodb/bitcoin,lateminer/bitcoin,GroestlCoin/GroestlCoin,Bitcoin-ABC/bitcoin-abc,lateminer/bitcoin,thrasher-/litecoin,CryptArc/bitcoin,multicoins/marycoin,jamesob/bitcoin,jlopp/statoshi,simonmulser/bitcoin,awemany/BitcoinUnlimited,Sjors/bitcoin,myriadteam/myriadcoin,btc1/bitcoin,DigitalPandacoin/pandacoin,1185/starwels,rebroad/bitcoin,Bushstar/UFO-Project,Exgibichi/statusquo,randy-waterhouse/bitcoin,domob1812/huntercore,BitzenyCoreDevelopers/bitzeny,stamhe/bitcoin,sipsorcery/bitcoin,Anfauglith/iop-hd,instagibbs/bitcoin,dgarage/bc2,DigitalPandacoin/pandacoin,sebrandon1/bitcoin,thrasher-/litecoin,Cocosoft/bitcoin,lbryio/lbrycrd,namecoin/namecoin-core,jmcorgan/bitcoin,Sjors/bitcoin,sipsorcery/bitcoin,djpnewton/bitcoin,digibyte/digibyte,paveljanik/bitcoin,jnewbery/bitcoin,yenliangl/bitcoin,h4x3rotab/BTCGPU,anditto/bitcoin,psionin/smartcoin,earonesty/bitcoin,laudaa/bitcoin,spiritlinxl/BTCGPU,mm-s/bitcoin,maaku/bitcoin,myriadteam/myriadcoin,dogecoin/dogecoin,daliwangi/bitcoin,21E14/bitcoin,patricklodder/dogecoin,mb300sd/bitcoin,donaloconnor/bitcoin,plncoin/PLNcoin_Core,BitcoinHardfork/bitcoin,goldcoin/goldcoin,cculianu/bitcoin-abc,stamhe/bitcoin,XertroV/bitcoin-nulldata,Chancoin-core/CHANCOIN,domob1812/namecore,Bushstar/UFO-Project,gmaxwell/bitcoin,cryptoprojects/ultimateonlinecash,kallewoof/elements,mruddy/bitcoin,core-bitcoin/bitcoin,174high/bitcoin,XertroV/bitcoin-nulldata,Bitcoin-ABC/bitcoin-abc,alecalve/bitcoin,domob1812/huntercore,ahmedbodi/vertcoin,EntropyFactory/creativechain-core,mm-s/bitcoin,fanquake/bitcoin,ericshawlinux/bitcoin,nbenoit/bitcoin,xieta/mincoin,domob1812/namecore,romanornr/viacoin,core-bitcoin/bitcoin,midnightmagic/bitcoin,mitchellcash/bitcoin,mitchellcash/bitcoin,afk11/bitcoin,domob1812/namecore,nbenoit/bitcoin,peercoin/peercoin,mitchellcash/bitcoin,kallewoof/elements,OmniLayer/omnicore,GlobalBoost/GlobalBoost,sstone/bitcoin,trippysalmon/bitcoin,myriadteam/myriadcoin,rnicoll/bitcoin,mm-s/bitcoin,cryptoprojects/ultimateonlinecash,gmaxwell/bitcoin,wiggi/huntercore,cdecker/bitcoin,jtimon/bitcoin,svost/bitcoin,Exgibichi/statusquo,multicoins/marycoin,Friedbaumer/litecoin,MarcoFalke/bitcoin,bitcoin/bitcoin,Chancoin-core/CHANCOIN,GroestlCoin/GroestlCoin,achow101/bitcoin,RHavar/bitcoin,Flowdalic/bitcoin,droark/bitcoin,monacoinproject/monacoin,Gazer022/bitcoin,GroestlCoin/bitcoin,svost/bitcoin,peercoin/peercoin,BitcoinPOW/BitcoinPOW,bitcoinec/bitcoinec,goldcoin/goldcoin,bitcoinsSG/bitcoin,svost/bitcoin,aspanta/bitcoin,fujicoin/fujicoin,isle2983/bitcoin,Jcing95/iop-hd,AdrianaDinca/bitcoin,sstone/bitcoin,awemany/BitcoinUnlimited,Flowdalic/bitcoin,jamesob/bitcoin,fujicoin/fujicoin,EthanHeilman/bitcoin,aspanta/bitcoin,jmcorgan/bitcoin,goldcoin/Goldcoin-GLD,dgarage/bc3,cdecker/bitcoin,jiangyonghang/bitcoin,pstratem/bitcoin,apoelstra/bitcoin,EntropyFactory/creativechain-core,jambolo/bitcoin,namecoin/namecoin-core,deeponion/deeponion,UASF/bitcoin,domob1812/namecore,Xekyo/bitcoin,dpayne9000/Rubixz-Coin,deeponion/deeponion,HashUnlimited/Einsteinium-Unlimited,jlopp/statoshi,AdrianaDinca/bitcoin,vmp32k/litecoin,joshrabinowitz/bitcoin,dgarage/bc3,ericshawlinux/bitcoin,StarbuckBG/BTCGPU,starwels/starwels,isle2983/bitcoin,JeremyRubin/bitcoin,spiritlinxl/BTCGPU,destenson/bitcoin--bitcoin,qtumproject/qtum,uphold/bitcoin,alecalve/bitcoin,donaloconnor/bitcoin,awemany/BitcoinUnlimited,Christewart/bitcoin,1185/starwels,laudaa/bitcoin,ElementsProject/elements,BitcoinHardfork/bitcoin,bitbrazilcoin-project/bitbrazilcoin,uphold/bitcoin,cculianu/bitcoin-abc,Kogser/bitcoin,droark/bitcoin,BitzenyCoreDevelopers/bitzeny,BitzenyCoreDevelopers/bitzeny,h4x3rotab/BTCGPU,BitcoinHardfork/bitcoin,tjps/bitcoin,HashUnlimited/Einsteinium-Unlimited,Kogser/bitcoin,instagibbs/bitcoin,paveljanik/bitcoin,GroestlCoin/bitcoin,mincoin-project/mincoin,wangxinxi/litecoin,rnicoll/dogecoin,myriadcoin/myriadcoin,sipsorcery/bitcoin,domob1812/huntercore,elecoin/elecoin,thrasher-/litecoin,n1bor/bitcoin,destenson/bitcoin--bitcoin,EthanHeilman/bitcoin,mruddy/bitcoin,globaltoken/globaltoken,zcoinofficial/zcoin,Rav3nPL/bitcoin,tdudz/elements,sipsorcery/bitcoin,instagibbs/bitcoin,jmcorgan/bitcoin,UFOCoins/ufo,bitbrazilcoin-project/bitbrazilcoin,Kogser/bitcoin,stamhe/bitcoin,MeshCollider/bitcoin,midnightmagic/bitcoin,jonasschnelli/bitcoin,Christewart/bitcoin,GroestlCoin/bitcoin,dpayne9000/Rubixz-Coin,MazaCoin/maza,psionin/smartcoin,MarcoFalke/bitcoin,TheBlueMatt/bitcoin,Kogser/bitcoin,ftrader-bitcoinabc/bitcoin-abc
|
f6123acc9d6015d0dbbafb43c61430615ba415b9
|
examples/hello-world.cpp
|
examples/hello-world.cpp
|
/*
* %injeqt copyright begin%
* Copyright 2014 Rafał Malinowski ([email protected])
* %injeqt copyright end%
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <injeqt/injector.h>
#include <injeqt/module.h>
#include <QtCore/QDebug>
#include <QtCore/QObject>
#include <memory>
class hello_service : public QObject
{
Q_OBJECT
public:
hello_service() {}
virtual ~hello_service() {}
QString say_hello() const
{
return {"Hello"};
}
};
class world_service : public QObject
{
Q_OBJECT
public:
world_service() {}
virtual ~world_service() {}
QString say_world() const
{
return {"World"};
}
};
class hello_factory : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE hello_factory() {}
virtual ~hello_factory() {}
Q_INVOKABLE hello_service * create_service()
{
return new hello_service{};
}
};
class hello_client : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE hello_client() : _s{nullptr}, _w{nullptr} {}
virtual ~hello_client() {}
QString say() const
{
return _s->say_hello() + " " + _w->say_world() + "!";
}
private slots:
INJEQT_SET void set_hello_service(hello_service *s)
{
_s = s;
}
INJEQT_SET void set_world_service(world_service *w)
{
_w = w;
}
private:
hello_service *_s;
world_service *_w;
};
class module : public injeqt::module
{
public:
explicit module()
{
_w = std::unique_ptr<world_service>{new world_service{}};
add_type<hello_client>();
add_type<hello_factory>();
add_factory<hello_service, hello_factory>();
add_ready_object<world_service>(_w.get());
}
virtual ~module() {}
private:
std::unique_ptr<world_service> _w;
};
int main()
{
auto modules = std::vector<std::unique_ptr<injeqt::module>>{};
modules.emplace_back(std::unique_ptr<injeqt::module>{new module{}});
auto injector = injeqt::injector{std::move(modules)};
auto client = injector.get<hello_client>();
auto hello = client->say();
qDebug() << hello;
}
#include "hello-world.moc"
|
/*
* %injeqt copyright begin%
* Copyright 2014 Rafał Malinowski ([email protected])
* %injeqt copyright end%
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <injeqt/injector.h>
#include <injeqt/module.h>
#include <QtCore/QObject>
#include <iostream>
#include <memory>
#include <string>
class hello_service : public QObject
{
Q_OBJECT
public:
hello_service() {}
virtual ~hello_service() {}
std::string say_hello() const
{
return {"Hello"};
}
};
class world_service : public QObject
{
Q_OBJECT
public:
world_service() {}
virtual ~world_service() {}
std::string say_world() const
{
return {"World"};
}
};
class hello_factory : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE hello_factory() {}
virtual ~hello_factory() {}
Q_INVOKABLE hello_service * create_service()
{
return new hello_service{};
}
};
class hello_client : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE hello_client() : _s{nullptr}, _w{nullptr} {}
virtual ~hello_client() {}
std::string say() const
{
return _s->say_hello() + " " + _w->say_world() + "!";
}
private slots:
INJEQT_INIT void init()
{
std::cerr << "all services set" << std::endl;
}
INJEQT_DONE void done()
{
std::cerr << "ready for destruction" << std::endl;
}
INJEQT_SET void set_hello_service(hello_service *s)
{
_s = s;
}
INJEQT_SET void set_world_service(world_service *w)
{
_w = w;
}
private:
hello_service *_s;
world_service *_w;
};
class module : public injeqt::module
{
public:
explicit module()
{
_w = std::unique_ptr<world_service>{new world_service{}};
add_type<hello_client>();
add_type<hello_factory>();
add_factory<hello_service, hello_factory>();
add_ready_object<world_service>(_w.get());
}
virtual ~module() {}
private:
std::unique_ptr<world_service> _w;
};
int main()
{
auto modules = std::vector<std::unique_ptr<injeqt::module>>{};
modules.emplace_back(std::unique_ptr<injeqt::module>{new module{}});
auto injector = injeqt::injector{std::move(modules)};
auto client = injector.get<hello_client>();
auto hello = client->say();
std::cout << hello << std::endl;
}
#include "hello-world.moc"
|
add INJEQT_INIT and INJEQT_DONE to hello-world example
|
add INJEQT_INIT and INJEQT_DONE to hello-world example
Signed-off-by: Rafał Malinowski <[email protected]>
|
C++
|
lgpl-2.1
|
vogel/injeqt,ppekala/injeqt,ppekala/injeqt,ppekala/injeqt,vogel/injeqt,vogel/injeqt
|
1ef34aed123d5a775c874583603ffc7ba674608e
|
examples/json_parser.cpp
|
examples/json_parser.cpp
|
/**
* This example demonstrate how we can use lars::parser parse standard JSON.
* https://en.wikipedia.org/wiki/JSON#Data_types_and_syntax
*/
#include <iostream>
#include <variant>
#include <map>
#include <algorithm>
#include <vector>
#include <memory>
#include <string>
#include <lars/parser/generator.h>
/**
*
*/
struct JSON{
enum Type {
NUMBER, STRING, BOOLEAN, ARRAY, OBJECT, EMPTY
} type;
std::variant<
double,
std::string,
bool,
std::vector<JSON>,
std::map<std::string, JSON>
> data;
JSON(double v):type(NUMBER),data(v){ }
JSON(std::string && v):type(STRING),data(v){ }
JSON(bool v):type(BOOLEAN),data(v){ }
JSON(std::vector<JSON> && v):type(ARRAY),data(v){ }
JSON(std::map<std::string, JSON> &&v):type(OBJECT),data(v){ }
JSON():type(EMPTY){}
};
std::ostream &operator<<(std::ostream &stream, const JSON &json){
switch (json.type) {
case JSON::NUMBER:{
stream << std::get<double>(json.data);
break;
}
case JSON::STRING:{
stream << '"' << std::get<std::string>(json.data) << '"';
break;
}
case JSON::BOOLEAN:{
stream << (std::get<bool>(json.data) ? "true" : "false");
break;
}
case JSON::ARRAY:{
stream << '[';
for(auto v: std::get<std::vector<JSON>>(json.data)) stream << v << ',';
stream << ']';
break;
}
case JSON::OBJECT:{
stream << '{';
for(auto v: std::get<std::map<std::string, JSON>>(json.data)){
stream << '"' << v.first << '"' << ':' << v.second << ',';
}
stream << '}';
break;
}
case JSON::EMPTY:{
stream << "null";
break;
}
}
return stream;
}
lars::ParserGenerator<JSON> createJSONProgram(){
lars::ParserGenerator<JSON> g;
g.setSeparator(g["Separators"] << "[\t \n]");
g["JSON"] << "Number | String | Boolean | Array | Object | Empty";
// Number
g.setProgramRule("Number", lars::peg::createDoubleProgram());
// String
g.setProgramRule("String", lars::peg::createStringProgram("\"","\""));
// Boolean
g["Boolean"] << "True | False";
g["True"] << "'true'" >> [](auto e){ return JSON(true); };
g["False"] << "'false'" >> [](auto e){ return JSON(false); };
// Array
g["Array"] << "'[' (JSON (',' JSON)*)? ']'" >> [](auto e){
std::vector<JSON> data(e.size());
std::transform(e.begin(),e.end(),data.begin(), [](auto v){ return v.evaluate(); });
return JSON(std::move(data));
};
// Object
g["Object"] << "'{' (Pair (',' Pair)*)? '}'" >> [](auto e){
std::map<std::string, JSON> data;
for(auto p:e){ data[std::get<std::string>(p[0].evaluate().data)] = p[1].evaluate(); }
return JSON(std::move(data));
};
g["Pair"] << "String ':' JSON";
// Empty
g["Empty"] << "'null'" >> [](auto){ return JSON(); };
g.setStart(g["JSON"]);
return g;
}
int main() {
using namespace std;
auto json = createJSONProgram();
cout << "Enter a valid JSON expression.\n";
while (true) {
string str;
cout << "> ";
getline(cin,str);
if(str == "q" || str == "quit"){ break; }
try {
auto result = json.run(str);
cout << "Parsed JSON: " << result << endl;
} catch (lars::SyntaxError error) {
auto syntax = error.syntax;
cout << " ";
cout << string(syntax->begin, ' ');
cout << string(syntax->length(), '~');
cout << "^\n";
cout << " " << "Syntax error while parsing " << syntax->rule->name << endl;
}
}
return 0;
}
|
/**
* This example demonstrate how we can use lars::parser parse standard JSON.
* https://en.wikipedia.org/wiki/JSON#Data_types_and_syntax
*/
#include <iostream>
#include <variant>
#include <map>
#include <algorithm>
#include <vector>
#include <memory>
#include <string>
#include <lars/parser/generator.h>
/** Class to store JSON objects */
struct JSON{
enum Type {
NUMBER, STRING, BOOLEAN, ARRAY, OBJECT, EMPTY
} type;
std::variant<
double,
std::string,
bool,
std::vector<JSON>,
std::map<std::string, JSON>
> data;
JSON(double v):type(NUMBER),data(v){ }
JSON(std::string && v):type(STRING),data(v){ }
JSON(bool v):type(BOOLEAN),data(v){ }
JSON(std::vector<JSON> && v):type(ARRAY),data(v){ }
JSON(std::map<std::string, JSON> &&v):type(OBJECT),data(v){ }
JSON():type(EMPTY){}
};
/** Print JSON */
std::ostream &operator<<(std::ostream &stream, const JSON &json){
switch (json.type) {
case JSON::NUMBER:{
stream << std::get<double>(json.data);
break;
}
case JSON::STRING:{
stream << '"' << std::get<std::string>(json.data) << '"';
break;
}
case JSON::BOOLEAN:{
stream << (std::get<bool>(json.data) ? "true" : "false");
break;
}
case JSON::ARRAY:{
stream << '[';
for(auto v: std::get<std::vector<JSON>>(json.data)) stream << v << ',';
stream << ']';
break;
}
case JSON::OBJECT:{
stream << '{';
for(auto v: std::get<std::map<std::string, JSON>>(json.data)){
stream << '"' << v.first << '"' << ':' << v.second << ',';
}
stream << '}';
break;
}
case JSON::EMPTY:{
stream << "null";
break;
}
}
return stream;
}
/** Define the grammar */
lars::ParserGenerator<JSON> createJSONProgram(){
lars::ParserGenerator<JSON> g;
g.setSeparator(g["Separators"] << "[\t \n]");
g["JSON"] << "Number | String | Boolean | Array | Object | Empty";
// Number
g.setProgramRule("Number", lars::peg::createDoubleProgram());
// String
g.setProgramRule("String", lars::peg::createStringProgram("\"","\""));
// Boolean
g["Boolean"] << "True | False";
g["True"] << "'true'" >> [](auto e){ return JSON(true); };
g["False"] << "'false'" >> [](auto e){ return JSON(false); };
// Array
g["Array"] << "'[' (JSON (',' JSON)*)? ']'" >> [](auto e){
std::vector<JSON> data(e.size());
std::transform(e.begin(),e.end(),data.begin(), [](auto v){ return v.evaluate(); });
return JSON(std::move(data));
};
// Object
g["Object"] << "'{' (Pair (',' Pair)*)? '}'" >> [](auto e){
std::map<std::string, JSON> data;
for(auto p:e){ data[std::get<std::string>(p[0].evaluate().data)] = p[1].evaluate(); }
return JSON(std::move(data));
};
g["Pair"] << "String ':' JSON";
// Empty
g["Empty"] << "'null'" >> [](auto){ return JSON(); };
g.setStart(g["JSON"]);
return g;
}
/** Input */
int main() {
using namespace std;
auto json = createJSONProgram();
cout << "Enter a valid JSON expression.\n";
while (true) {
string str;
cout << "> ";
getline(cin,str);
if(str == "q" || str == "quit"){ break; }
try {
auto result = json.run(str);
cout << "Parsed JSON: " << result << endl;
} catch (lars::SyntaxError error) {
auto syntax = error.syntax;
cout << " ";
cout << string(syntax->begin, ' ');
cout << string(syntax->length(), '~');
cout << "^\n";
cout << " " << "Syntax error while parsing " << syntax->rule->name << endl;
}
}
return 0;
}
|
Add comments (#31)
|
Add comments (#31)
* added JSON example
* added missing includes
* ditch unordered_map for map
* add comments
|
C++
|
bsd-3-clause
|
TheLartians/Parser
|
ebc784a71ef69f5e19ef73953c0cfb988aa6b0f8
|
examples/load_balance.cp
|
examples/load_balance.cp
|
# Compile with:
#
# ./motto.byte -I examples/ --no_type_check --disable_data_model_checks -o test examples/load_balance.cp
#include "naas.cp"
#include "http.cp"
type http_request : record
src_network_address : integer
protocol : record
TCP : record
src_port : integer
request_data : string
type http_response : record
response_data : string
#fun LB : (type http_request/type http_response client, type http_response/type http_request backend; backend_choices : [type channel_metadata])
process LB : {no_backends, backend_choices} => (http_request/http_response client, http_response/http_request backend)
local set : boolean := False
# FIXME this block should be removed. It serves to make declarations that
# parts of the compiler can latch onto. The fields from the PDU should
# be translated to refer to suitable values in the runtime.
let client_src_network_address = 0
let client_protocol_TCP_src_port = 0
let backend = 0
if set = False:
let choice =
# hash(client.src_network_address + client.protocol.TCP.src_port) mod no_backends
hash(client_src_network_address + client_protocol_TCP_src_port) mod no_backends
# bind (backend, backend_choices[choice])
bind (backend, backend_choices)
set := True
else: <> #FIXME this line will be made redundant
# client <=> backend
if can ?? client:
client => backend
else: <>
backend => client
#process LB_response : {no_backends} => (http_request/http_response client, http_response/http_request backend)
# for i in 0 .. (no_backends - 1):
# if can ?? backends[i]:
# let x = ?? backends[i]
# client ! x
# ? backends[i]
# else: <>
|
# Compile with:
#
# ./motto.byte -I examples/ --no_type_check --disable_data_model_checks -o test examples/load_balance.cp
#include "naas.cp"
#include "http.cp"
type http_request : record
src_network_address : integer
protocol : record
TCP : record
src_port : integer
request_data : string
type http_response : record
response_data : string
#fun LB : (type http_request/type http_response client, type http_response/type http_request backend; backend_choices : [type channel_metadata])
fun LB : {no_backends, backend_choices} => (http_request/http_response client, http_response/http_request backend) -> ()
local set : boolean := False
# FIXME this block should be removed. It serves to make declarations that
# parts of the compiler can latch onto. The fields from the PDU should
# be translated to refer to suitable values in the runtime.
let client_src_network_address = 0
let client_protocol_TCP_src_port = 0
let backend = 0
if set = False:
let choice =
# hash(client.src_network_address + client.protocol.TCP.src_port) mod no_backends
hash(client_src_network_address + client_protocol_TCP_src_port) mod no_backends
# bind (backend, backend_choices[choice])
bind (backend, backend_choices)
set := True
else: <> #FIXME this line will be made redundant
# client <=> backend
if can ?? client:
client => backend
else: <>
backend => client
fun LB_resp : {no_backends} => (http_request/http_response client, http_response/http_request backend) -> ()
for i in 0 .. (no_backends - 1):
if can ?? backend[i]:
# backends[i] => client
let x = ? backend[target]
backend[target] ! x # Note that x was "peeked" from the channel "client".
? client
else: <>
|
Fix a bug in examples/load_balance.cp
|
Fix a bug in examples/load_balance.cp
|
C++
|
apache-2.0
|
NaaS/motto,NaaS/motto
|
3e7a2ce9774813020513070faf92df96b2850b03
|
examples/nbody/nbody.cpp
|
examples/nbody/nbody.cpp
|
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "tuner_api.h"
#define USE_CUDA 0
#define USE_PROFILING 0
#if USE_CUDA == 0
#if defined(_MSC_VER)
#define KTT_KERNEL_FILE "../examples/nbody/nbody_kernel1.cl"
#define KTT_REFERENCE_KERNEL_FILE "../examples/nbody/nbody_reference_kernel.cl"
#else
#define KTT_KERNEL_FILE "../../examples/nbody/nbody_kernel1.cl"
#define KTT_REFERENCE_KERNEL_FILE "../../examples/nbody/nbody_reference_kernel.cl"
#endif
#else
#if defined(_MSC_VER)
#define KTT_KERNEL_FILE "../examples/nbody/nbody_kernel1.cu"
#define KTT_REFERENCE_KERNEL_FILE "../examples/nbody/nbody_reference_kernel.cu"
#else
#define KTT_KERNEL_FILE "../../examples/nbody/nbody_kernel1.cu"
#define KTT_REFERENCE_KERNEL_FILE "../../examples/nbody/nbody_reference_kernel.cu"
#endif
#endif
int main(int argc, char** argv)
{
// Initialize platform and device index
ktt::PlatformIndex platformIndex = 0;
ktt::DeviceIndex deviceIndex = 0;
std::string kernelFile = KTT_KERNEL_FILE;
std::string referenceKernelFile = KTT_REFERENCE_KERNEL_FILE;
if (argc >= 2)
{
platformIndex = std::stoul(std::string(argv[1]));
if (argc >= 3)
{
deviceIndex = std::stoul(std::string(argv[2]));
if (argc >= 4)
{
kernelFile = std::string(argv[3]);
if (argc >= 5)
{
referenceKernelFile = std::string(argv[4]);
}
}
}
}
// Declare kernel parameters
const int numberOfBodies = 32 * 1024;
// Total NDRange size matches number of grid points
const ktt::DimensionVector ndRangeDimensions(numberOfBodies);
const ktt::DimensionVector workGroupDimensions;
const ktt::DimensionVector referenceWorkGroupDimensions(64);
// Declare data variables
float timeDelta = 0.001f;
float damping = 0.5f;
float softeningSqr = 0.1f * 0.1f;
std::vector<float> oldBodyInfo(4 * numberOfBodies);
std::vector<float> oldPosX(numberOfBodies);
std::vector<float> oldPosY(numberOfBodies);
std::vector<float> oldPosZ(numberOfBodies);
std::vector<float> bodyMass(numberOfBodies);
std::vector<float> newBodyInfo(4 * numberOfBodies, 0.f);
std::vector<float> oldBodyVel(4 * numberOfBodies);
std::vector<float> newBodyVel(4 * numberOfBodies);
std::vector<float> oldVelX(numberOfBodies);
std::vector<float> oldVelY(numberOfBodies);
std::vector<float> oldVelZ(numberOfBodies);
// Initialize data
std::random_device device;
std::default_random_engine engine(device());
std::uniform_real_distribution<float> distribution(0.0f, 20.0f);
for (int i = 0; i < numberOfBodies; i++)
{
oldPosX.at(i) = distribution(engine);
oldPosY.at(i) = distribution(engine);
oldPosZ.at(i) = distribution(engine);
bodyMass.at(i) = distribution(engine);
oldVelX.at(i) = distribution(engine);
oldVelY.at(i) = distribution(engine);
oldVelZ.at(i) = distribution(engine);
oldBodyInfo.at((4 * i)) = oldPosX.at(i);
oldBodyInfo.at((4 * i) + 1) = oldPosY.at(i);
oldBodyInfo.at((4 * i) + 2) = oldPosZ.at(i);
oldBodyInfo.at((4 * i) + 3) = bodyMass.at(i);
oldBodyVel.at((4 * i)) = oldVelX.at(i);
oldBodyVel.at((4 * i) + 1) = oldVelY.at(i);
oldBodyVel.at((4 * i) + 2) = oldVelZ.at(i);
oldBodyVel.at((4 * i) + 3) = 0.f;
}
// Create tuner object for chosen platform and device
#if USE_CUDA == 0
ktt::Tuner tuner(platformIndex, deviceIndex);
tuner.setCompilerOptions("-cl-fast-relaxed-math");
#else
ktt::Tuner tuner(platformIndex, deviceIndex, ktt::ComputeAPI::CUDA);
tuner.setGlobalSizeType(ktt::GlobalSizeType::OpenCL);
tuner.setCompilerOptions("-use_fast_math");
#if USE_PROFILING == 1
printf("Executing with profiling switched ON.\n");
tuner.setKernelProfiling(true);
#endif
#endif
tuner.setPrintingTimeUnit(ktt::TimeUnit::Microseconds);
// Add two kernels to tuner, one of the kernels acts as reference kernel
ktt::KernelId kernelId = tuner.addKernelFromFile(kernelFile, "nbody_kernel", ndRangeDimensions, workGroupDimensions);
ktt::KernelId referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, "nbody_kernel", ndRangeDimensions, referenceWorkGroupDimensions);
// Multiply workgroup size in dimensions x and y by two parameters that follow (effectively setting workgroup size to parameters' values)
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_X", {64, 128, 256, 512});
tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::X, "WORK_GROUP_SIZE_X", ktt::ModifierAction::Multiply);
tuner.addParameter(kernelId, "OUTER_UNROLL_FACTOR", {1, 2, 4, 8});
tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::X, "OUTER_UNROLL_FACTOR", ktt::ModifierAction::Divide);
tuner.addParameter(kernelId, "INNER_UNROLL_FACTOR1", {0, 1, 2, 4, 8, 16, 32});
tuner.addParameter(kernelId, "INNER_UNROLL_FACTOR2", {0, 1, 2, 4, 8, 16, 32});
#if USE_CUDA == 0
tuner.addParameter(kernelId, "USE_CONSTANT_MEMORY", {0, 1});
#else
tuner.addParameter(kernelId, "USE_CONSTANT_MEMORY", {0});
#endif
tuner.addParameter(kernelId, "USE_SOA", {0, 1});
tuner.addParameter(kernelId, "LOCAL_MEM", {0, 1});
#if USE_CUDA == 0
tuner.addParameter(kernelId, "VECTOR_TYPE", {1, 2, 4, 8, 16});
#else
tuner.addParameter(kernelId, "VECTOR_TYPE", {1, 2, 4});
#endif
// Add all arguments utilized by kernels
ktt::ArgumentId oldBodyInfoId = tuner.addArgumentVector(oldBodyInfo, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldPosXId = tuner.addArgumentVector(oldPosX, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldPosYId = tuner.addArgumentVector(oldPosY, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldPosZId = tuner.addArgumentVector(oldPosZ, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId massId = tuner.addArgumentVector(bodyMass, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId newBodyInfoId = tuner.addArgumentVector(newBodyInfo, ktt::ArgumentAccessType::WriteOnly);
ktt::ArgumentId oldVelId = tuner.addArgumentVector(oldBodyVel, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldVelXId = tuner.addArgumentVector(oldVelX, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldVelYId = tuner.addArgumentVector(oldVelY, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldVelZId = tuner.addArgumentVector(oldVelZ, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId newBodyVelId = tuner.addArgumentVector(newBodyVel, ktt::ArgumentAccessType::WriteOnly);
ktt::ArgumentId deltaTimeId = tuner.addArgumentScalar(timeDelta);
ktt::ArgumentId dampingId = tuner.addArgumentScalar(damping);
ktt::ArgumentId softeningSqrId = tuner.addArgumentScalar(softeningSqr);
ktt::ArgumentId numberOfBodiesId = tuner.addArgumentScalar(numberOfBodies);
// Add conditions
auto lteq = [](const std::vector<size_t>& vector) {return vector.at(0) <= vector.at(1);};
tuner.addConstraint(kernelId, {"INNER_UNROLL_FACTOR2", "OUTER_UNROLL_FACTOR"}, lteq);
auto lteq256 = [](const std::vector<size_t>& vector) {return vector.at(0) * vector.at(1) <= 256;};
tuner.addConstraint(kernelId, {"INNER_UNROLL_FACTOR1", "INNER_UNROLL_FACTOR2"}, lteq256);
auto vectorizedSoA = [](const std::vector<size_t>& vector) {return (vector.at(0) == 1 && vector.at(1) == 0) || (vector.at(1) == 1);};
tuner.addConstraint(kernelId, std::vector<std::string>{"VECTOR_TYPE", "USE_SOA"}, vectorizedSoA);
// Set kernel arguments for both tuned kernel and reference kernel, order of arguments is important
tuner.setKernelArguments(kernelId, std::vector<ktt::ArgumentId>{deltaTimeId,
oldBodyInfoId, oldPosXId, oldPosYId, oldPosZId, massId, newBodyInfoId, // position
oldVelId, oldVelXId, oldVelYId, oldVelZId, newBodyVelId, // velocity
dampingId, softeningSqrId, numberOfBodiesId});
tuner.setKernelArguments(referenceKernelId, std::vector<ktt::ArgumentId>{deltaTimeId, oldBodyInfoId, newBodyInfoId, oldVelId, newBodyVelId,
dampingId, softeningSqrId});
// Specify custom tolerance threshold for validation of floating point arguments. Default threshold is 1e-4.
tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.001);
// Set reference kernel which validates results provided by tuned kernel, provide list of arguments which will be validated
tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterPair>{}, std::vector<ktt::ArgumentId>{newBodyVelId,
newBodyInfoId});
// Launch kernel tuning
tuner.tuneKernel(kernelId);
// Print tuning results to standard output and to output.csv file
tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose);
tuner.printResult(kernelId, "nbody_output.csv", ktt::PrintFormat::CSV);
return 0;
}
|
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "tuner_api.h"
#define USE_CUDA 0
#define USE_PROFILING 0
#if USE_CUDA == 0
#if defined(_MSC_VER)
#define KTT_KERNEL_FILE "../examples/nbody/nbody_kernel1.cl"
#define KTT_REFERENCE_KERNEL_FILE "../examples/nbody/nbody_reference_kernel.cl"
#else
#define KTT_KERNEL_FILE "../../examples/nbody/nbody_kernel1.cl"
#define KTT_REFERENCE_KERNEL_FILE "../../examples/nbody/nbody_reference_kernel.cl"
#endif
#else
#if defined(_MSC_VER)
#define KTT_KERNEL_FILE "../examples/nbody/nbody_kernel1.cu"
#define KTT_REFERENCE_KERNEL_FILE "../examples/nbody/nbody_reference_kernel.cu"
#else
#define KTT_KERNEL_FILE "../../examples/nbody/nbody_kernel1.cu"
#define KTT_REFERENCE_KERNEL_FILE "../../examples/nbody/nbody_reference_kernel.cu"
#endif
#endif
int main(int argc, char** argv)
{
// Initialize platform and device index
ktt::PlatformIndex platformIndex = 0;
ktt::DeviceIndex deviceIndex = 0;
std::string kernelFile = KTT_KERNEL_FILE;
std::string referenceKernelFile = KTT_REFERENCE_KERNEL_FILE;
if (argc >= 2)
{
platformIndex = std::stoul(std::string(argv[1]));
if (argc >= 3)
{
deviceIndex = std::stoul(std::string(argv[2]));
if (argc >= 4)
{
kernelFile = std::string(argv[3]);
if (argc >= 5)
{
referenceKernelFile = std::string(argv[4]);
}
}
}
}
// Declare kernel parameters
const int numberOfBodies = 128 * 1024;
// Total NDRange size matches number of grid points
const ktt::DimensionVector ndRangeDimensions(numberOfBodies);
const ktt::DimensionVector workGroupDimensions;
const ktt::DimensionVector referenceWorkGroupDimensions(64);
// Declare data variables
float timeDelta = 0.001f;
float damping = 0.5f;
float softeningSqr = 0.1f * 0.1f;
std::vector<float> oldBodyInfo(4 * numberOfBodies);
std::vector<float> oldPosX(numberOfBodies);
std::vector<float> oldPosY(numberOfBodies);
std::vector<float> oldPosZ(numberOfBodies);
std::vector<float> bodyMass(numberOfBodies);
std::vector<float> newBodyInfo(4 * numberOfBodies, 0.f);
std::vector<float> oldBodyVel(4 * numberOfBodies);
std::vector<float> newBodyVel(4 * numberOfBodies);
std::vector<float> oldVelX(numberOfBodies);
std::vector<float> oldVelY(numberOfBodies);
std::vector<float> oldVelZ(numberOfBodies);
// Initialize data
std::random_device device;
std::default_random_engine engine(device());
std::uniform_real_distribution<float> distribution(0.0f, 20.0f);
for (int i = 0; i < numberOfBodies; i++)
{
oldPosX.at(i) = distribution(engine);
oldPosY.at(i) = distribution(engine);
oldPosZ.at(i) = distribution(engine);
bodyMass.at(i) = distribution(engine);
oldVelX.at(i) = distribution(engine);
oldVelY.at(i) = distribution(engine);
oldVelZ.at(i) = distribution(engine);
oldBodyInfo.at((4 * i)) = oldPosX.at(i);
oldBodyInfo.at((4 * i) + 1) = oldPosY.at(i);
oldBodyInfo.at((4 * i) + 2) = oldPosZ.at(i);
oldBodyInfo.at((4 * i) + 3) = bodyMass.at(i);
oldBodyVel.at((4 * i)) = oldVelX.at(i);
oldBodyVel.at((4 * i) + 1) = oldVelY.at(i);
oldBodyVel.at((4 * i) + 2) = oldVelZ.at(i);
oldBodyVel.at((4 * i) + 3) = 0.f;
}
// Create tuner object for chosen platform and device
#if USE_CUDA == 0
ktt::Tuner tuner(platformIndex, deviceIndex);
tuner.setCompilerOptions("-cl-fast-relaxed-math");
#else
ktt::Tuner tuner(platformIndex, deviceIndex, ktt::ComputeAPI::CUDA);
tuner.setGlobalSizeType(ktt::GlobalSizeType::OpenCL);
tuner.setCompilerOptions("-use_fast_math");
#if USE_PROFILING == 1
printf("Executing with profiling switched ON.\n");
tuner.setKernelProfiling(true);
#endif
#endif
tuner.setPrintingTimeUnit(ktt::TimeUnit::Microseconds);
// Add two kernels to tuner, one of the kernels acts as reference kernel
ktt::KernelId kernelId = tuner.addKernelFromFile(kernelFile, "nbody_kernel", ndRangeDimensions, workGroupDimensions);
ktt::KernelId referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, "nbody_kernel", ndRangeDimensions, referenceWorkGroupDimensions);
// Multiply workgroup size in dimensions x and y by two parameters that follow (effectively setting workgroup size to parameters' values)
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_X", {64, 128, 256, 512});
tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::X, "WORK_GROUP_SIZE_X", ktt::ModifierAction::Multiply);
tuner.addParameter(kernelId, "OUTER_UNROLL_FACTOR", {1, 2, 4, 8});
tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::X, "OUTER_UNROLL_FACTOR", ktt::ModifierAction::Divide);
tuner.addParameter(kernelId, "INNER_UNROLL_FACTOR1", {0, 1, 2, 4, 8, 16, 32});
tuner.addParameter(kernelId, "INNER_UNROLL_FACTOR2", {0, 1, 2, 4, 8, 16, 32});
#if USE_CUDA == 0
tuner.addParameter(kernelId, "USE_CONSTANT_MEMORY", {0, 1});
#else
tuner.addParameter(kernelId, "USE_CONSTANT_MEMORY", {0});
#endif
tuner.addParameter(kernelId, "USE_SOA", {0, 1});
tuner.addParameter(kernelId, "LOCAL_MEM", {0, 1});
#if USE_CUDA == 0
tuner.addParameter(kernelId, "VECTOR_TYPE", {1, 2, 4, 8, 16});
#else
tuner.addParameter(kernelId, "VECTOR_TYPE", {1, 2, 4});
#endif
// Add all arguments utilized by kernels
ktt::ArgumentId oldBodyInfoId = tuner.addArgumentVector(oldBodyInfo, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldPosXId = tuner.addArgumentVector(oldPosX, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldPosYId = tuner.addArgumentVector(oldPosY, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldPosZId = tuner.addArgumentVector(oldPosZ, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId massId = tuner.addArgumentVector(bodyMass, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId newBodyInfoId = tuner.addArgumentVector(newBodyInfo, ktt::ArgumentAccessType::WriteOnly);
ktt::ArgumentId oldVelId = tuner.addArgumentVector(oldBodyVel, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldVelXId = tuner.addArgumentVector(oldVelX, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldVelYId = tuner.addArgumentVector(oldVelY, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId oldVelZId = tuner.addArgumentVector(oldVelZ, ktt::ArgumentAccessType::ReadOnly);
ktt::ArgumentId newBodyVelId = tuner.addArgumentVector(newBodyVel, ktt::ArgumentAccessType::WriteOnly);
ktt::ArgumentId deltaTimeId = tuner.addArgumentScalar(timeDelta);
ktt::ArgumentId dampingId = tuner.addArgumentScalar(damping);
ktt::ArgumentId softeningSqrId = tuner.addArgumentScalar(softeningSqr);
ktt::ArgumentId numberOfBodiesId = tuner.addArgumentScalar(numberOfBodies);
// Add conditions
auto lteq = [](const std::vector<size_t>& vector) {return vector.at(0) <= vector.at(1);};
tuner.addConstraint(kernelId, {"INNER_UNROLL_FACTOR2", "OUTER_UNROLL_FACTOR"}, lteq);
auto lteq256 = [](const std::vector<size_t>& vector) {return vector.at(0) * vector.at(1) <= 256;};
tuner.addConstraint(kernelId, {"INNER_UNROLL_FACTOR1", "INNER_UNROLL_FACTOR2"}, lteq256);
auto vectorizedSoA = [](const std::vector<size_t>& vector) {return (vector.at(0) == 1 && vector.at(1) == 0) || (vector.at(1) == 1);};
tuner.addConstraint(kernelId, std::vector<std::string>{"VECTOR_TYPE", "USE_SOA"}, vectorizedSoA);
// Set kernel arguments for both tuned kernel and reference kernel, order of arguments is important
tuner.setKernelArguments(kernelId, std::vector<ktt::ArgumentId>{deltaTimeId,
oldBodyInfoId, oldPosXId, oldPosYId, oldPosZId, massId, newBodyInfoId, // position
oldVelId, oldVelXId, oldVelYId, oldVelZId, newBodyVelId, // velocity
dampingId, softeningSqrId, numberOfBodiesId});
tuner.setKernelArguments(referenceKernelId, std::vector<ktt::ArgumentId>{deltaTimeId, oldBodyInfoId, newBodyInfoId, oldVelId, newBodyVelId,
dampingId, softeningSqrId});
// Specify custom tolerance threshold for validation of floating point arguments. Default threshold is 1e-4.
tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.001);
// Set reference kernel which validates results provided by tuned kernel, provide list of arguments which will be validated
tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterPair>{}, std::vector<ktt::ArgumentId>{newBodyVelId,
newBodyInfoId});
// Launch kernel tuning
tuner.tuneKernel(kernelId);
// Print tuning results to standard output and to output.csv file
tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose);
tuner.printResult(kernelId, "nbody_output.csv", ktt::PrintFormat::CSV);
return 0;
}
|
use bigger input in n-body by default (old value causes heavy underutilization of high-end GPUs)
|
use bigger input in n-body by default (old value causes heavy underutilization of high-end GPUs)
|
C++
|
mit
|
Fillo7/KTT,Fillo7/KTT
|
bd3e3ef7113b49438b83633d71177309e732438d
|
tools/llvm-slicer-opts.cpp
|
tools/llvm-slicer-opts.cpp
|
#include "dg/analysis/Offset.h"
#include "dg/llvm/LLVMDependenceGraph.h"
#include "dg/llvm/LLVMDependenceGraphBuilder.h"
#include "dg/llvm/analysis/PointsTo/LLVMPointerAnalysisOptions.h"
#include "dg/llvm/analysis/ReachingDefinitions/LLVMReachingDefinitionsAnalysisOptions.h"
// ignore unused parameters in LLVM libraries
#if (__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <llvm/Support/CommandLine.h>
#if (__clang__)
#pragma clang diagnostic pop // ignore -Wunused-parameter
#else
#pragma GCC diagnostic pop
#endif
#include "llvm-slicer.h"
#include "llvm-slicer-utils.h"
#include "git-version.h"
using dg::analysis::LLVMPointerAnalysisOptions;
using dg::analysis::LLVMReachingDefinitionsAnalysisOptions;
llvm::cl::OptionCategory SlicingOpts("Slicer options", "");
// Use LLVM's CommandLine library to parse
// command line arguments
SlicerOptions parseSlicerOptions(int argc, char *argv[]) {
llvm::cl::opt<std::string> outputFile("o",
llvm::cl::desc("Save the output to given file. If not specified,\n"
"a .sliced suffix is used with the original module name."),
llvm::cl::value_desc("filename"), llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> inputFile(llvm::cl::Positional, llvm::cl::Required,
llvm::cl::desc("<input file>"), llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> slicingCriteria("c", llvm::cl::Required,
llvm::cl::desc("Slice with respect to the call-sites of a given function\n"
"i. e.: '-c foo' or '-c __assert_fail'. Special value is a 'ret'\n"
"in which case the slice is taken with respect to the return value\n"
"of the main function. Further, you can specify the criterion as\n"
"l:v where l is the line in the original code and v is the variable.\n"
"l must be empty when v is a global variable. For local variables,\n"
"the variable v must be used on the line l.\n"
"You can use comma-separated list of more slicing criteria,\n"
"e.g. -c foo,5:x,:glob\n"), llvm::cl::value_desc("crit"),
llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> secondarySlicingCriteria("2c",
llvm::cl::desc("Set secondary slicing criterion. The criterion is a call\n"
"to a given function. If just a name of the function is\n"
"given, it is a 'control' slicing criterion. If there is ()\n"
"appended, it is 'data' slicing criterion. E.g. foo means\n"
"control secondary slicing criterion, foo() means data\n"
"data secondary slicing criterion.\n"),
llvm::cl::value_desc("crit"),
llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> removeSlicingCriteria("remove-slicing-criteria",
llvm::cl::desc("By default, slicer keeps also calls to the slicing criteria\n"
"in the sliced program. This switch makes slicer to remove\n"
"also the calls (i.e. behave like Weisser's algorithm)"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> preservedFuns("preserved-functions",
llvm::cl::desc("Do not slice bodies of the given functions\n."
"The argument is a comma-separated list of functions.\n"),
llvm::cl::value_desc("funs"),
llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> terminationSensitive("termination-sensitive",
llvm::cl::desc("Do not slice away parts of programs that might make\n"
"the slicing criteria unreachable (e.g. calls to exit() or potentially infinite loops).\n"
"NOTE: at this moment we do not handle potentially infinite loops.\n"
"Default: on\n"),
llvm::cl::init(true), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<uint64_t> ptaFieldSensitivity("pta-field-sensitive",
llvm::cl::desc("Make PTA field sensitive/insensitive. The offset in a pointer\n"
"is cropped to Offset::UNKNOWN when it is greater than N bytes.\n"
"Default is full field-sensitivity (N = Offset::UNKNOWN).\n"),
llvm::cl::value_desc("N"), llvm::cl::init(dg::analysis::Offset::UNKNOWN),
llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> rdaStrongUpdateUnknown("rd-strong-update-unknown",
llvm::cl::desc("Let reaching defintions analysis do strong updates on memory defined\n"
"with uknown offset in the case, that new definition overwrites\n"
"the whole memory. May be unsound for out-of-bound access\n"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> undefinedArePure("undefined-are-pure",
llvm::cl::desc("Assume that undefined functions have no side-effects\n"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> entryFunction("entry",
llvm::cl::desc("Entry function of the program\n"),
llvm::cl::init("main"), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> forwardSlicing("forward",
llvm::cl::desc("Perform forward slicing\n"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> threads("threads",
llvm::cl::desc("Consider threads are in input file (default=false)."),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<LLVMPointerAnalysisOptions::AnalysisType> ptaType("pta",
llvm::cl::desc("Choose pointer analysis to use:"),
llvm::cl::values(
clEnumValN(LLVMPointerAnalysisOptions::AnalysisType::fi, "fi", "Flow-insensitive PTA (default)"),
clEnumValN(LLVMPointerAnalysisOptions::AnalysisType::fs, "fs", "Flow-sensitive PTA"),
clEnumValN(LLVMPointerAnalysisOptions::AnalysisType::inv, "inv", "PTA with invalidate nodes")
#if LLVM_VERSION_MAJOR < 4
, nullptr
#endif
),
llvm::cl::init(LLVMPointerAnalysisOptions::AnalysisType::fi), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<LLVMReachingDefinitionsAnalysisOptions::AnalysisType> rdaType("rda",
llvm::cl::desc("Choose reaching definitions analysis to use:"),
llvm::cl::values(
clEnumValN(LLVMReachingDefinitionsAnalysisOptions::AnalysisType::dataflow,
"dataflow", "Classical data-flow RDA (default)"),
clEnumValN(LLVMReachingDefinitionsAnalysisOptions::AnalysisType::ssa,
"ssa", "MemorySSA-based RDA")
#if LLVM_VERSION_MAJOR < 4
, nullptr
#endif
),
llvm::cl::init(LLVMReachingDefinitionsAnalysisOptions::AnalysisType::dataflow),
llvm::cl::cat(SlicingOpts));
llvm::cl::opt<dg::CD_ALG> cdAlgorithm("cd-alg",
llvm::cl::desc("Choose control dependencies algorithm to use:"),
llvm::cl::values(
clEnumValN(dg::CD_ALG::CLASSIC , "classic", "Ferrante's algorithm (default)"),
clEnumValN(dg::CD_ALG::CONTROL_EXPRESSION, "ce", "Control expression based (experimental)"),
clEnumValN(dg::CD_ALG::NTSCD, "ntscd", "Non-termination sensitive control dependencies algorithm")
#if LLVM_VERSION_MAJOR < 4
, nullptr
#endif
),
llvm::cl::init(dg::CD_ALG::CLASSIC), llvm::cl::cat(SlicingOpts));
////////////////////////////////////
// ===-- End of the options --=== //
////////////////////////////////////
// hide all options except ours options
// this method is available since LLVM 3.7
#if ((LLVM_VERSION_MAJOR > 3)\
|| ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR >= 7)))
llvm::cl::HideUnrelatedOptions(SlicingOpts);
#endif
# if ((LLVM_VERSION_MAJOR >= 6))
llvm::cl::SetVersionPrinter([](llvm::raw_ostream&){ printf("%s\n", GIT_VERSION); });
#else
llvm::cl::SetVersionPrinter([](){ printf("%s\n", GIT_VERSION); });
#endif
llvm::cl::ParseCommandLineOptions(argc, argv);
/// Fill the structure
SlicerOptions options;
options.inputFile = inputFile;
options.outputFile = outputFile;
options.slicingCriteria = slicingCriteria;
options.secondarySlicingCriteria = secondarySlicingCriteria;
options.preservedFunctions = splitList(preservedFuns);
options.removeSlicingCriteria = removeSlicingCriteria;
options.forwardSlicing = forwardSlicing;
options.dgOptions.entryFunction = entryFunction;
options.dgOptions.PTAOptions.entryFunction = entryFunction;
options.dgOptions.PTAOptions.fieldSensitivity
= dg::analysis::Offset(ptaFieldSensitivity);
options.dgOptions.PTAOptions.analysisType = ptaType;
options.dgOptions.threads = threads;
options.dgOptions.PTAOptions.threads = threads;
options.dgOptions.RDAOptions.threads = threads;
options.dgOptions.RDAOptions.entryFunction = entryFunction;
options.dgOptions.RDAOptions.strongUpdateUnknown = rdaStrongUpdateUnknown;
options.dgOptions.RDAOptions.undefinedArePure = undefinedArePure;
options.dgOptions.RDAOptions.analysisType = rdaType;
// FIXME: add options class for CD
options.dgOptions.cdAlgorithm = cdAlgorithm;
options.dgOptions.terminationSensitive = terminationSensitive;
return options;
}
|
#include "dg/analysis/Offset.h"
#include "dg/llvm/LLVMDependenceGraph.h"
#include "dg/llvm/LLVMDependenceGraphBuilder.h"
#include "dg/llvm/analysis/PointsTo/LLVMPointerAnalysisOptions.h"
#include "dg/llvm/analysis/ReachingDefinitions/LLVMReachingDefinitionsAnalysisOptions.h"
// ignore unused parameters in LLVM libraries
#if (__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <llvm/Support/CommandLine.h>
#if (__clang__)
#pragma clang diagnostic pop // ignore -Wunused-parameter
#else
#pragma GCC diagnostic pop
#endif
#include "llvm-slicer.h"
#include "llvm-slicer-utils.h"
#include "git-version.h"
using dg::analysis::LLVMPointerAnalysisOptions;
using dg::analysis::LLVMReachingDefinitionsAnalysisOptions;
static void
addAllocationFuns(dg::llvmdg::LLVMDependenceGraphOptions& dgOptions,
const std::string& allocationFuns) {
using dg::analysis::AllocationFunction;
auto items = splitList(allocationFuns);
for (auto& item : items) {
auto subitms = splitList(item, ':');
if (subitms.size() != 2) {
llvm::errs() << "ERROR: Invalid allocation function: " << item << "\n";
continue;
}
AllocationFunction type;
if (subitms[1] == "malloc")
type = AllocationFunction::MALLOC;
else if (subitms[1] == "calloc")
type = AllocationFunction::CALLOC;
else if (subitms[1] == "realloc")
type = AllocationFunction::REALLOC;
else {
llvm::errs() << "ERROR: Invalid type of allocation function: "
<< item << "\n";
continue;
}
dgOptions.PTAOptions.addAllocationFunction(subitms[0], type);
dgOptions.RDAOptions.addAllocationFunction(subitms[0], type);
}
}
llvm::cl::OptionCategory SlicingOpts("Slicer options", "");
// Use LLVM's CommandLine library to parse
// command line arguments
SlicerOptions parseSlicerOptions(int argc, char *argv[]) {
llvm::cl::opt<std::string> outputFile("o",
llvm::cl::desc("Save the output to given file. If not specified,\n"
"a .sliced suffix is used with the original module name."),
llvm::cl::value_desc("filename"), llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> inputFile(llvm::cl::Positional, llvm::cl::Required,
llvm::cl::desc("<input file>"), llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> slicingCriteria("c", llvm::cl::Required,
llvm::cl::desc("Slice with respect to the call-sites of a given function\n"
"i. e.: '-c foo' or '-c __assert_fail'. Special value is a 'ret'\n"
"in which case the slice is taken with respect to the return value\n"
"of the main function. Further, you can specify the criterion as\n"
"l:v where l is the line in the original code and v is the variable.\n"
"l must be empty when v is a global variable. For local variables,\n"
"the variable v must be used on the line l.\n"
"You can use comma-separated list of more slicing criteria,\n"
"e.g. -c foo,5:x,:glob\n"), llvm::cl::value_desc("crit"),
llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> secondarySlicingCriteria("2c",
llvm::cl::desc("Set secondary slicing criterion. The criterion is a call\n"
"to a given function. If just a name of the function is\n"
"given, it is a 'control' slicing criterion. If there is ()\n"
"appended, it is 'data' slicing criterion. E.g. foo means\n"
"control secondary slicing criterion, foo() means data\n"
"data secondary slicing criterion.\n"),
llvm::cl::value_desc("crit"),
llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> removeSlicingCriteria("remove-slicing-criteria",
llvm::cl::desc("By default, slicer keeps also calls to the slicing criteria\n"
"in the sliced program. This switch makes slicer to remove\n"
"also the calls (i.e. behave like Weisser's algorithm)"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> preservedFuns("preserved-functions",
llvm::cl::desc("Do not slice bodies of the given functions\n."
"The argument is a comma-separated list of functions.\n"),
llvm::cl::value_desc("funs"),
llvm::cl::init(""), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> terminationSensitive("termination-sensitive",
llvm::cl::desc("Do not slice away parts of programs that might make\n"
"the slicing criteria unreachable (e.g. calls to exit() or potentially infinite loops).\n"
"NOTE: at this moment we do not handle potentially infinite loops.\n"
"Default: on\n"),
llvm::cl::init(true), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<uint64_t> ptaFieldSensitivity("pta-field-sensitive",
llvm::cl::desc("Make PTA field sensitive/insensitive. The offset in a pointer\n"
"is cropped to Offset::UNKNOWN when it is greater than N bytes.\n"
"Default is full field-sensitivity (N = Offset::UNKNOWN).\n"),
llvm::cl::value_desc("N"), llvm::cl::init(dg::analysis::Offset::UNKNOWN),
llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> rdaStrongUpdateUnknown("rd-strong-update-unknown",
llvm::cl::desc("Let reaching defintions analysis do strong updates on memory defined\n"
"with uknown offset in the case, that new definition overwrites\n"
"the whole memory. May be unsound for out-of-bound access\n"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> undefinedArePure("undefined-are-pure",
llvm::cl::desc("Assume that undefined functions have no side-effects\n"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> entryFunction("entry",
llvm::cl::desc("Entry function of the program\n"),
llvm::cl::init("main"), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> forwardSlicing("forward",
llvm::cl::desc("Perform forward slicing\n"),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<bool> threads("threads",
llvm::cl::desc("Consider threads are in input file (default=false)."),
llvm::cl::init(false), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<std::string> allocationFuns("allocation-funs",
llvm::cl::desc("Treat these functions as allocation functions\n"
"The argument is a comma-separated list of func:type,\n"
"where func is the function and type is one of\n"
"malloc, calloc, or realloc.\n"
"E.g., myAlloc:malloc will treat myAlloc as malloc.\n"),
llvm::cl::init("main"), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<LLVMPointerAnalysisOptions::AnalysisType> ptaType("pta",
llvm::cl::desc("Choose pointer analysis to use:"),
llvm::cl::values(
clEnumValN(LLVMPointerAnalysisOptions::AnalysisType::fi, "fi", "Flow-insensitive PTA (default)"),
clEnumValN(LLVMPointerAnalysisOptions::AnalysisType::fs, "fs", "Flow-sensitive PTA"),
clEnumValN(LLVMPointerAnalysisOptions::AnalysisType::inv, "inv", "PTA with invalidate nodes")
#if LLVM_VERSION_MAJOR < 4
, nullptr
#endif
),
llvm::cl::init(LLVMPointerAnalysisOptions::AnalysisType::fi), llvm::cl::cat(SlicingOpts));
llvm::cl::opt<LLVMReachingDefinitionsAnalysisOptions::AnalysisType> rdaType("rda",
llvm::cl::desc("Choose reaching definitions analysis to use:"),
llvm::cl::values(
clEnumValN(LLVMReachingDefinitionsAnalysisOptions::AnalysisType::dataflow,
"dataflow", "Classical data-flow RDA (default)"),
clEnumValN(LLVMReachingDefinitionsAnalysisOptions::AnalysisType::ssa,
"ssa", "MemorySSA-based RDA")
#if LLVM_VERSION_MAJOR < 4
, nullptr
#endif
),
llvm::cl::init(LLVMReachingDefinitionsAnalysisOptions::AnalysisType::dataflow),
llvm::cl::cat(SlicingOpts));
llvm::cl::opt<dg::CD_ALG> cdAlgorithm("cd-alg",
llvm::cl::desc("Choose control dependencies algorithm to use:"),
llvm::cl::values(
clEnumValN(dg::CD_ALG::CLASSIC , "classic", "Ferrante's algorithm (default)"),
clEnumValN(dg::CD_ALG::CONTROL_EXPRESSION, "ce", "Control expression based (experimental)"),
clEnumValN(dg::CD_ALG::NTSCD, "ntscd", "Non-termination sensitive control dependencies algorithm")
#if LLVM_VERSION_MAJOR < 4
, nullptr
#endif
),
llvm::cl::init(dg::CD_ALG::CLASSIC), llvm::cl::cat(SlicingOpts));
////////////////////////////////////
// ===-- End of the options --=== //
////////////////////////////////////
// hide all options except ours options
// this method is available since LLVM 3.7
#if ((LLVM_VERSION_MAJOR > 3)\
|| ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR >= 7)))
llvm::cl::HideUnrelatedOptions(SlicingOpts);
#endif
# if ((LLVM_VERSION_MAJOR >= 6))
llvm::cl::SetVersionPrinter([](llvm::raw_ostream&){ printf("%s\n", GIT_VERSION); });
#else
llvm::cl::SetVersionPrinter([](){ printf("%s\n", GIT_VERSION); });
#endif
llvm::cl::ParseCommandLineOptions(argc, argv);
/// Fill the structure
SlicerOptions options;
options.inputFile = inputFile;
options.outputFile = outputFile;
options.slicingCriteria = slicingCriteria;
options.secondarySlicingCriteria = secondarySlicingCriteria;
options.preservedFunctions = splitList(preservedFuns);
options.removeSlicingCriteria = removeSlicingCriteria;
options.forwardSlicing = forwardSlicing;
options.dgOptions.entryFunction = entryFunction;
options.dgOptions.PTAOptions.entryFunction = entryFunction;
options.dgOptions.PTAOptions.fieldSensitivity
= dg::analysis::Offset(ptaFieldSensitivity);
options.dgOptions.PTAOptions.analysisType = ptaType;
options.dgOptions.threads = threads;
options.dgOptions.PTAOptions.threads = threads;
options.dgOptions.RDAOptions.threads = threads;
options.dgOptions.RDAOptions.entryFunction = entryFunction;
options.dgOptions.RDAOptions.strongUpdateUnknown = rdaStrongUpdateUnknown;
options.dgOptions.RDAOptions.undefinedArePure = undefinedArePure;
options.dgOptions.RDAOptions.analysisType = rdaType;
addAllocationFuns(options.dgOptions, allocationFuns);
// FIXME: add options class for CD
options.dgOptions.cdAlgorithm = cdAlgorithm;
options.dgOptions.terminationSensitive = terminationSensitive;
return options;
}
|
allow specifying allocation function on command line
|
llvm-slicer: allow specifying allocation function on command line
|
C++
|
mit
|
mchalupa/dg,mchalupa/dg,mchalupa/dg,mchalupa/dg
|
d2afe5e1342e012b45245d86c8211b3f06df0062
|
examples/qmc-example.cpp
|
examples/qmc-example.cpp
|
#include "connection.h"
#include "room.h"
#include "user.h"
#include "jobs/sendeventjob.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QStringBuilder>
#include <QtCore/QTimer>
#include <iostream>
using namespace QMatrixClient;
using std::cout;
using std::endl;
using namespace std::placeholders;
class QMCTest : public QObject
{
public:
QMCTest(Connection* conn, const QString& testRoomName, QString source);
private slots:
void onNewRoom(Room* r, const QString& testRoomName);
void doTests();
void addAndRemoveTag();
void sendAndRedact();
void finalize();
private:
QScopedPointer<Connection, QScopedPointerDeleteLater> c;
QString origin;
Room* targetRoom = nullptr;
int semaphor = 0;
};
#define QMC_CHECK(description, condition) \
cout << (description) \
<< (!!(condition) ? " successul" : " FAILED") << endl; \
targetRoom->postMessage(origin % ": " % QStringLiteral(description) % \
(!!(condition) ? QStringLiteral(" successful") : \
QStringLiteral(" FAILED")), MessageEventType::Notice)
QMCTest::QMCTest(Connection* conn, const QString& testRoomName, QString source)
: c(conn), origin(std::move(source))
{
if (!origin.isEmpty())
cout << "Origin for the test message: " << origin.toStdString() << endl;
if (!testRoomName.isEmpty())
cout << "Test room name: " << testRoomName.toStdString() << endl;
connect(c.data(), &Connection::newRoom,
this, [this,testRoomName] (Room* r) { onNewRoom(r, testRoomName); });
connect(c.data(), &Connection::syncDone, c.data(), [this] {
cout << "Sync complete, " << semaphor << " tests in the air" << endl;
if (semaphor)
{
// if (targetRoom)
// targetRoom->postMessage(
// QString("%1: sync done, %2 test(s) in the air")
// .arg(origin).arg(semaphor),
// MessageEventType::Notice);
c->sync(10000);
}
else
{
if (targetRoom)
{
auto j = c->callApi<SendEventJob>(targetRoom->id(),
RoomMessageEvent(origin % ": All tests finished"));
connect(j, &BaseJob::finished, this, &QMCTest::finalize);
}
else
finalize();
}
});
// Big countdown watchdog
QTimer::singleShot(180000, this, &QMCTest::finalize);
}
void QMCTest::onNewRoom(Room* r, const QString& testRoomName)
{
cout << "New room: " << r->id().toStdString() << endl;
connect(r, &Room::namesChanged, this, [=] {
cout << "Room " << r->id().toStdString() << ", name(s) changed:" << endl
<< " Name: " << r->name().toStdString() << endl
<< " Canonical alias: " << r->canonicalAlias().toStdString() << endl
<< endl << endl;
if (!testRoomName.isEmpty() && (r->name() == testRoomName ||
r->canonicalAlias() == testRoomName))
{
cout << "Found the target room, proceeding for tests" << endl;
targetRoom = r;
++semaphor;
auto j = targetRoom->connection()->callApi<SendEventJob>(
targetRoom->id(),
RoomMessageEvent(origin % ": connected to test room",
MessageEventType::Notice));
connect(j, &BaseJob::success,
this, [this] { doTests(); --semaphor; });
}
});
connect(r, &Room::aboutToAddNewMessages, r, [r] (RoomEventsRange timeline) {
cout << timeline.size() << " new event(s) in room "
<< r->id().toStdString() << endl;
// for (const auto& item: timeline)
// {
// cout << "From: "
// << r->roomMembername(item->senderId()).toStdString()
// << endl << "Timestamp:"
// << item->timestamp().toString().toStdString() << endl
// << "JSON:" << endl << item->originalJson().toStdString() << endl;
// }
});
}
void QMCTest::doTests()
{
addAndRemoveTag();
sendAndRedact();
}
void QMCTest::addAndRemoveTag()
{
++semaphor;
static const auto TestTag = QStringLiteral("org.qmatrixclient.test");
// Pre-requisite
if (targetRoom->tags().contains(TestTag))
targetRoom->removeTag(TestTag);
QObject::connect(targetRoom, &Room::tagsChanged, targetRoom, [=] {
cout << "Room " << targetRoom->id().toStdString()
<< ", tag(s) changed:" << endl
<< " " << targetRoom->tagNames().join(", ").toStdString() << endl;
if (targetRoom->tags().contains(TestTag))
{
cout << "Test tag set, removing it now" << endl;
targetRoom->removeTag(TestTag);
QMC_CHECK("Tagging test", !targetRoom->tags().contains(TestTag));
--semaphor;
QObject::disconnect(targetRoom, &Room::tagsChanged, nullptr, nullptr);
}
});
// The reverse order because tagsChanged is emitted synchronously.
cout << "Adding a tag" << endl;
targetRoom->addTag(TestTag);
}
void QMCTest::sendAndRedact()
{
++semaphor;
cout << "Sending a message to redact" << endl;
auto* job = targetRoom->connection()->callApi<SendEventJob>(targetRoom->id(),
RoomMessageEvent(origin % ": Message to redact"));
QObject::connect(job, &BaseJob::success, targetRoom, [job,this] {
cout << "Message to redact has been succesfully sent, redacting" << endl;
targetRoom->redactEvent(job->eventId(), "qmc-example");
});
QObject::connect(targetRoom, &Room::replacedEvent, targetRoom,
[=] (const RoomEvent* newEvent) {
QMC_CHECK("Redaction", newEvent->isRedacted() &&
newEvent->redactionReason() == "qmc-example");
--semaphor;
QObject::disconnect(targetRoom, &Room::replacedEvent,
nullptr, nullptr);
});
}
void QMCTest::finalize()
{
if (semaphor)
cout << "One or more tests FAILED" << endl;
cout << "Logging out" << endl;
c->logout();
connect(c.data(), &Connection::loggedOut, QCoreApplication::instance(),
[this] {
QCoreApplication::processEvents();
QCoreApplication::exit(semaphor);
});
}
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
if (argc < 4)
{
cout << "Usage: qmc-example <user> <passwd> <device_name> [<room_alias> [origin]]" << endl;
return -1;
}
cout << "Connecting to the server as " << argv[1] << endl;
auto conn = new Connection;
conn->connectToServer(argv[1], argv[2], argv[3]);
QObject::connect(conn, &Connection::connected, [=] {
cout << "Connected, server: "
<< conn->homeserver().toDisplayString().toStdString() << endl;
cout << "Access token: " << conn->accessToken().toStdString() << endl;
conn->sync();
});
QMCTest test { conn, argc >= 5 ? argv[4] : nullptr,
argc >= 6 ? argv[5] : nullptr };
return app.exec();
}
|
#include "connection.h"
#include "room.h"
#include "user.h"
#include "jobs/sendeventjob.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QStringBuilder>
#include <QtCore/QTimer>
#include <iostream>
#include <functional>
using namespace QMatrixClient;
using std::cout;
using std::endl;
using namespace std::placeholders;
class QMCTest : public QObject
{
public:
QMCTest(Connection* conn, const QString& testRoomName, QString source);
private slots:
void onNewRoom(Room* r, const QString& testRoomName);
void doTests();
void addAndRemoveTag();
void sendAndRedact();
void checkRedactionOutcome(QString evtIdToRedact, RoomEventsRange events);
void finalize();
private:
QScopedPointer<Connection, QScopedPointerDeleteLater> c;
QString origin;
Room* targetRoom = nullptr;
int semaphor = 0;
};
#define QMC_CHECK(description, condition) \
cout << (description) \
<< (!!(condition) ? " successul" : " FAILED") << endl; \
targetRoom->postMessage(origin % ": " % QStringLiteral(description) % \
(!!(condition) ? QStringLiteral(" successful") : \
QStringLiteral(" FAILED")), MessageEventType::Notice)
QMCTest::QMCTest(Connection* conn, const QString& testRoomName, QString source)
: c(conn), origin(std::move(source))
{
if (!origin.isEmpty())
cout << "Origin for the test message: " << origin.toStdString() << endl;
if (!testRoomName.isEmpty())
cout << "Test room name: " << testRoomName.toStdString() << endl;
connect(c.data(), &Connection::newRoom,
this, [this,testRoomName] (Room* r) { onNewRoom(r, testRoomName); });
connect(c.data(), &Connection::syncDone, c.data(), [this] {
cout << "Sync complete, " << semaphor << " tests in the air" << endl;
if (semaphor)
{
// if (targetRoom)
// targetRoom->postMessage(
// QString("%1: sync done, %2 test(s) in the air")
// .arg(origin).arg(semaphor),
// MessageEventType::Notice);
c->sync(10000);
}
else
{
if (targetRoom)
{
auto j = c->callApi<SendEventJob>(targetRoom->id(),
RoomMessageEvent(origin % ": All tests finished"));
connect(j, &BaseJob::finished, this, &QMCTest::finalize);
}
else
finalize();
}
});
// Big countdown watchdog
QTimer::singleShot(180000, this, &QMCTest::finalize);
}
void QMCTest::onNewRoom(Room* r, const QString& testRoomName)
{
cout << "New room: " << r->id().toStdString() << endl;
connect(r, &Room::namesChanged, this, [=] {
cout << "Room " << r->id().toStdString() << ", name(s) changed:" << endl
<< " Name: " << r->name().toStdString() << endl
<< " Canonical alias: " << r->canonicalAlias().toStdString() << endl
<< endl << endl;
if (!testRoomName.isEmpty() && (r->name() == testRoomName ||
r->canonicalAlias() == testRoomName))
{
cout << "Found the target room, proceeding for tests" << endl;
targetRoom = r;
++semaphor;
auto j = targetRoom->connection()->callApi<SendEventJob>(
targetRoom->id(),
RoomMessageEvent(origin % ": connected to test room",
MessageEventType::Notice));
connect(j, &BaseJob::success,
this, [this] { doTests(); --semaphor; });
}
});
connect(r, &Room::aboutToAddNewMessages, r, [r] (RoomEventsRange timeline) {
cout << timeline.size() << " new event(s) in room "
<< r->id().toStdString() << endl;
// for (const auto& item: timeline)
// {
// cout << "From: "
// << r->roomMembername(item->senderId()).toStdString()
// << endl << "Timestamp:"
// << item->timestamp().toString().toStdString() << endl
// << "JSON:" << endl << item->originalJson().toStdString() << endl;
// }
});
}
void QMCTest::doTests()
{
addAndRemoveTag();
sendAndRedact();
}
void QMCTest::addAndRemoveTag()
{
++semaphor;
static const auto TestTag = QStringLiteral("org.qmatrixclient.test");
// Pre-requisite
if (targetRoom->tags().contains(TestTag))
targetRoom->removeTag(TestTag);
QObject::connect(targetRoom, &Room::tagsChanged, targetRoom, [=] {
cout << "Room " << targetRoom->id().toStdString()
<< ", tag(s) changed:" << endl
<< " " << targetRoom->tagNames().join(", ").toStdString() << endl;
if (targetRoom->tags().contains(TestTag))
{
cout << "Test tag set, removing it now" << endl;
targetRoom->removeTag(TestTag);
QMC_CHECK("Tagging test", !targetRoom->tags().contains(TestTag));
--semaphor;
QObject::disconnect(targetRoom, &Room::tagsChanged, nullptr, nullptr);
}
});
// The reverse order because tagsChanged is emitted synchronously.
cout << "Adding a tag" << endl;
targetRoom->addTag(TestTag);
}
void QMCTest::sendAndRedact()
{
++semaphor;
cout << "Sending a message to redact" << endl;
auto* job = targetRoom->connection()->callApi<SendEventJob>(targetRoom->id(),
RoomMessageEvent(origin % ": Message to redact"));
connect(job, &BaseJob::success, targetRoom, [job,this] {
cout << "Message to redact has been succesfully sent, redacting" << endl;
targetRoom->redactEvent(job->eventId(), origin);
// Make sure to save the event id because the job is about to end.
connect(targetRoom, &Room::aboutToAddNewMessages, this,
std::bind(&QMCTest::checkRedactionOutcome,
this, job->eventId(), _1));
});
}
void QMCTest::checkRedactionOutcome(QString evtIdToRedact,
RoomEventsRange events)
{
static bool checkSucceeded = false;
// There are two possible (correct) outcomes: either the event comes already
// redacted at the next sync, or the nearest sync completes with
// the unredacted event but the next one brings redaction.
auto it = std::find_if(events.begin(), events.end(),
[=] (const RoomEventPtr& e) {
return e->id() == evtIdToRedact;
});
if (it == events.end())
return; // Waiting for the next sync
if ((*it)->isRedacted())
{
if (checkSucceeded)
{
const auto msg =
"The redacted event came in with the sync again, ignoring";
cout << msg << endl;
targetRoom->postMessage(msg);
return;
}
cout << "The sync brought already redacted message" << endl;
QMC_CHECK("Redaction", true);
--semaphor;
// Not disconnecting because there are other connections from this class
// to aboutToAddNewMessages
checkSucceeded = true;
return;
}
// The event is not redacted
if (checkSucceeded)
{
const auto msg =
"Warning: the redacted event came non-redacted with the sync!";
cout << msg << endl;
targetRoom->postMessage(msg);
}
cout << "Message came non-redacted with the sync, waiting for redaction" << endl;
connect(targetRoom, &Room::replacedEvent, targetRoom,
[=] (const RoomEvent* newEvent, const RoomEvent* oldEvent) {
QMC_CHECK("Redaction", oldEvent->id() == evtIdToRedact &&
newEvent->isRedacted() &&
newEvent->redactionReason() == origin);
--semaphor;
checkSucceeded = true;
disconnect(targetRoom, &Room::replacedEvent, nullptr, nullptr);
});
}
void QMCTest::finalize()
{
if (semaphor)
cout << "One or more tests FAILED" << endl;
cout << "Logging out" << endl;
c->logout();
connect(c.data(), &Connection::loggedOut, QCoreApplication::instance(),
[this] {
QCoreApplication::processEvents();
QCoreApplication::exit(semaphor);
});
}
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
if (argc < 4)
{
cout << "Usage: qmc-example <user> <passwd> <device_name> [<room_alias> [origin]]" << endl;
return -1;
}
cout << "Connecting to the server as " << argv[1] << endl;
auto conn = new Connection;
conn->connectToServer(argv[1], argv[2], argv[3]);
QObject::connect(conn, &Connection::connected, [=] {
cout << "Connected, server: "
<< conn->homeserver().toDisplayString().toStdString() << endl;
cout << "Access token: " << conn->accessToken().toStdString() << endl;
conn->sync();
});
QMCTest test { conn, argc >= 5 ? argv[4] : nullptr,
argc >= 6 ? argv[5] : nullptr };
return app.exec();
}
|
Fix redaction test to work even if the synced message is already redacted
|
qmc-example: Fix redaction test to work even if the synced message is already redacted
|
C++
|
lgpl-2.1
|
Fxrh/libqmatrixclient,QMatrixClient/libqmatrixclient,QMatrixClient/libqmatrixclient
|
a907fae2e3303bd52a87df3d754de2fbd582b0c8
|
lib/Target/RISCV/MCTargetDesc/RISCVELFObjectWriter.cpp
|
lib/Target/RISCV/MCTargetDesc/RISCVELFObjectWriter.cpp
|
//===-- RISCVELFObjectWriter.cpp - RISCV ELF Writer -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/RISCVFixupKinds.h"
#include "MCTargetDesc/RISCVMCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
namespace {
class RISCVELFObjectWriter : public MCELFObjectTargetWriter {
public:
RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit);
~RISCVELFObjectWriter() override;
// Return true if the given relocation must be with a symbol rather than
// section plus offset.
bool needsRelocateWithSymbol(const MCSymbol &Sym,
unsigned Type) const override {
// TODO: this is very conservative, update once RISC-V psABI requirements
// are clarified.
return true;
}
protected:
unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
const MCFixup &Fixup, bool IsPCRel) const override;
};
}
RISCVELFObjectWriter::RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
: MCELFObjectTargetWriter(Is64Bit, OSABI, ELF::EM_RISCV,
/*HasRelocationAddend*/ true) {}
RISCVELFObjectWriter::~RISCVELFObjectWriter() {}
unsigned RISCVELFObjectWriter::getRelocType(MCContext &Ctx,
const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const {
// Determine the type of the relocation
switch ((unsigned)Fixup.getKind()) {
default:
llvm_unreachable("invalid fixup kind!");
case FK_Data_4:
return ELF::R_RISCV_32;
case FK_Data_8:
return ELF::R_RISCV_64;
case FK_Data_Add_1:
return ELF::R_RISCV_ADD8;
case FK_Data_Add_2:
return ELF::R_RISCV_ADD16;
case FK_Data_Add_4:
return ELF::R_RISCV_ADD32;
case FK_Data_Add_8:
return ELF::R_RISCV_ADD64;
case FK_Data_Sub_1:
return ELF::R_RISCV_SUB8;
case FK_Data_Sub_2:
return ELF::R_RISCV_SUB16;
case FK_Data_Sub_4:
return ELF::R_RISCV_SUB32;
case FK_Data_Sub_8:
return ELF::R_RISCV_SUB64;
case RISCV::fixup_riscv_hi20:
return ELF::R_RISCV_HI20;
case RISCV::fixup_riscv_lo12_i:
return ELF::R_RISCV_LO12_I;
case RISCV::fixup_riscv_lo12_s:
return ELF::R_RISCV_LO12_S;
case RISCV::fixup_riscv_pcrel_hi20:
return ELF::R_RISCV_PCREL_HI20;
case RISCV::fixup_riscv_pcrel_lo12_i:
return ELF::R_RISCV_PCREL_LO12_I;
case RISCV::fixup_riscv_pcrel_lo12_s:
return ELF::R_RISCV_PCREL_LO12_S;
case RISCV::fixup_riscv_got_hi20:
return ELF::R_RISCV_GOT_HI20;
case RISCV::fixup_riscv_tprel_hi20:
return ELF::R_RISCV_TPREL_HI20;
case RISCV::fixup_riscv_tprel_lo12_i:
return ELF::R_RISCV_TPREL_LO12_I;
case RISCV::fixup_riscv_tprel_lo12_s:
return ELF::R_RISCV_TPREL_LO12_S;
case RISCV::fixup_riscv_tprel_add:
return ELF::R_RISCV_TPREL_ADD;
case RISCV::fixup_riscv_tls_got_hi20:
return ELF::R_RISCV_TLS_GOT_HI20;
case RISCV::fixup_riscv_tls_gd_hi20:
return ELF::R_RISCV_TLS_GD_HI20;
case RISCV::fixup_riscv_jal:
return ELF::R_RISCV_JAL;
case RISCV::fixup_riscv_branch:
return ELF::R_RISCV_BRANCH;
case RISCV::fixup_riscv_rvc_jump:
return ELF::R_RISCV_RVC_JUMP;
case RISCV::fixup_riscv_rvc_branch:
return ELF::R_RISCV_RVC_BRANCH;
case RISCV::fixup_riscv_call:
return ELF::R_RISCV_CALL;
case RISCV::fixup_riscv_call_plt:
return ELF::R_RISCV_CALL_PLT;
case RISCV::fixup_riscv_relax:
return ELF::R_RISCV_RELAX;
case RISCV::fixup_riscv_align:
return ELF::R_RISCV_ALIGN;
}
}
std::unique_ptr<MCObjectTargetWriter>
llvm::createRISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit) {
return llvm::make_unique<RISCVELFObjectWriter>(OSABI, Is64Bit);
}
|
//===-- RISCVELFObjectWriter.cpp - RISCV ELF Writer -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/RISCVFixupKinds.h"
#include "MCTargetDesc/RISCVMCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
namespace {
class RISCVELFObjectWriter : public MCELFObjectTargetWriter {
public:
RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit);
~RISCVELFObjectWriter() override;
// Return true if the given relocation must be with a symbol rather than
// section plus offset.
bool needsRelocateWithSymbol(const MCSymbol &Sym,
unsigned Type) const override {
// TODO: this is very conservative, update once RISC-V psABI requirements
// are clarified.
return true;
}
protected:
unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
const MCFixup &Fixup, bool IsPCRel) const override;
};
}
RISCVELFObjectWriter::RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
: MCELFObjectTargetWriter(Is64Bit, OSABI, ELF::EM_RISCV,
/*HasRelocationAddend*/ true) {}
RISCVELFObjectWriter::~RISCVELFObjectWriter() {}
unsigned RISCVELFObjectWriter::getRelocType(MCContext &Ctx,
const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const {
// Determine the type of the relocation
unsigned Kind = Fixup.getKind();
if (IsPCRel) {
switch (Kind) {
default:
llvm_unreachable("invalid fixup kind!");
case FK_Data_4:
case FK_PCRel_4:
return ELF::R_RISCV_32_PCREL;
case RISCV::fixup_riscv_pcrel_hi20:
return ELF::R_RISCV_PCREL_HI20;
case RISCV::fixup_riscv_pcrel_lo12_i:
return ELF::R_RISCV_PCREL_LO12_I;
case RISCV::fixup_riscv_pcrel_lo12_s:
return ELF::R_RISCV_PCREL_LO12_S;
case RISCV::fixup_riscv_got_hi20:
return ELF::R_RISCV_GOT_HI20;
case RISCV::fixup_riscv_tls_got_hi20:
return ELF::R_RISCV_TLS_GOT_HI20;
case RISCV::fixup_riscv_tls_gd_hi20:
return ELF::R_RISCV_TLS_GD_HI20;
case RISCV::fixup_riscv_jal:
return ELF::R_RISCV_JAL;
case RISCV::fixup_riscv_branch:
return ELF::R_RISCV_BRANCH;
case RISCV::fixup_riscv_rvc_jump:
return ELF::R_RISCV_RVC_JUMP;
case RISCV::fixup_riscv_rvc_branch:
return ELF::R_RISCV_RVC_BRANCH;
case RISCV::fixup_riscv_call:
return ELF::R_RISCV_CALL;
case RISCV::fixup_riscv_call_plt:
return ELF::R_RISCV_CALL_PLT;
}
}
switch (Kind) {
default:
llvm_unreachable("invalid fixup kind!");
case FK_Data_4:
return ELF::R_RISCV_32;
case FK_Data_8:
return ELF::R_RISCV_64;
case FK_Data_Add_1:
return ELF::R_RISCV_ADD8;
case FK_Data_Add_2:
return ELF::R_RISCV_ADD16;
case FK_Data_Add_4:
return ELF::R_RISCV_ADD32;
case FK_Data_Add_8:
return ELF::R_RISCV_ADD64;
case FK_Data_Sub_1:
return ELF::R_RISCV_SUB8;
case FK_Data_Sub_2:
return ELF::R_RISCV_SUB16;
case FK_Data_Sub_4:
return ELF::R_RISCV_SUB32;
case FK_Data_Sub_8:
return ELF::R_RISCV_SUB64;
case RISCV::fixup_riscv_hi20:
return ELF::R_RISCV_HI20;
case RISCV::fixup_riscv_lo12_i:
return ELF::R_RISCV_LO12_I;
case RISCV::fixup_riscv_lo12_s:
return ELF::R_RISCV_LO12_S;
case RISCV::fixup_riscv_tprel_hi20:
return ELF::R_RISCV_TPREL_HI20;
case RISCV::fixup_riscv_tprel_lo12_i:
return ELF::R_RISCV_TPREL_LO12_I;
case RISCV::fixup_riscv_tprel_lo12_s:
return ELF::R_RISCV_TPREL_LO12_S;
case RISCV::fixup_riscv_tprel_add:
return ELF::R_RISCV_TPREL_ADD;
case RISCV::fixup_riscv_relax:
return ELF::R_RISCV_RELAX;
case RISCV::fixup_riscv_align:
return ELF::R_RISCV_ALIGN;
}
}
std::unique_ptr<MCObjectTargetWriter>
llvm::createRISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit) {
return llvm::make_unique<RISCVELFObjectWriter>(OSABI, Is64Bit);
}
|
Make RISCVELFObjectWriter::getRelocType check IsPCRel
|
[RISCV] Make RISCVELFObjectWriter::getRelocType check IsPCRel
Previously, this function didn't check the IsPCRel argument. But doing so is a
useful check for errors, and also seemingly necessary for FK_Data_4 (which we
produce a R_RISCV_32_PCREL relocation for if IsPCRel).
Other than R_RISCV_32_PCREL, this should be NFC. Future exception handling
related patches will include tests that capture this behaviour.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@366172 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm
|
a67730504d6115786748bbe2a500967a5e40d6aa
|
vespalib/src/vespa/vespalib/util/time.cpp
|
vespalib/src/vespa/vespalib/util/time.cpp
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "time.h"
#include <thread>
#include <immintrin.h>
namespace vespalib {
system_time
to_utc(steady_time ts) {
system_clock::time_point nowUtc = system_clock::now();
steady_time nowSteady = steady_clock::now();
return system_time(std::chrono::duration_cast<system_time::duration>(nowUtc.time_since_epoch() - nowSteady.time_since_epoch() + ts.time_since_epoch()));
}
namespace {
string
to_string(duration dur) {
time_t timeStamp = std::chrono::duration_cast<std::chrono::seconds>(dur).count();
struct tm timeStruct;
gmtime_r(&timeStamp, &timeStruct);
char timeString[128];
strftime(timeString, sizeof(timeString), "%F %T", &timeStruct);
char retval[160];
uint32_t milliSeconds = count_ms(dur) % 1000;
snprintf(retval, sizeof(retval), "%s.%03u UTC", timeString, milliSeconds);
return std::string(retval);
}
}
string
to_string(system_time time) {
return to_string(time.time_since_epoch());
}
Timer::~Timer() = default;
void
Timer::waitAtLeast(duration dur, bool busyWait) {
if (busyWait) {
steady_clock::time_point deadline = steady_clock::now() + dur;
while (steady_clock::now() < deadline) {
for (int i = 0; i < 1000; i++) {
_mm_pause();
}
}
} else {
std::this_thread::sleep_for(dur);
}
}
}
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "time.h"
#include <thread>
#include <immintrin.h>
namespace vespalib {
system_time
to_utc(steady_time ts) {
system_clock::time_point nowUtc = system_clock::now();
steady_time nowSteady = steady_clock::now();
return system_time(std::chrono::duration_cast<system_time::duration>(nowUtc.time_since_epoch() - nowSteady.time_since_epoch() + ts.time_since_epoch()));
}
namespace {
string
to_string(duration dur) {
time_t timeStamp = std::chrono::duration_cast<std::chrono::seconds>(dur).count();
struct tm timeStruct;
gmtime_r(&timeStamp, &timeStruct);
char timeString[128];
strftime(timeString, sizeof(timeString), "%F %T", &timeStruct);
char retval[160];
uint32_t milliSeconds = count_ms(dur) % 1000;
snprintf(retval, sizeof(retval), "%s.%03u UTC", timeString, milliSeconds);
return std::string(retval);
}
}
string
to_string(system_time time) {
return to_string(time.time_since_epoch());
}
Timer::~Timer() = default;
void
Timer::waitAtLeast(duration dur, bool busyWait) {
if (busyWait) {
steady_clock::time_point deadline = steady_clock::now() + dur;
while (steady_clock::now() < deadline) {
for (int i = 0; i < 1000; i++) {
_mm_pause();
}
}
} else {
std::this_thread::sleep_for(dur);
}
}
}
namespace std::chrono {
// This is a hack to avoid the slow clock computations on RHEL7/CentOS 7 due to using systemcalls.
// This brings cost down from 550-560ns to 18-19ns
inline namespace _V2 {
system_clock::time_point
system_clock::now() noexcept {
timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
return time_point(duration(chrono::seconds(tp.tv_sec)
+ chrono::nanoseconds(tp.tv_nsec)));
}
steady_clock::time_point
steady_clock::now() noexcept {
timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
return time_point(duration(chrono::seconds(tp.tv_sec)
+ chrono::nanoseconds(tp.tv_nsec)));
}
}
}
|
Revert "Revert "There are so many combinations that the libstdc++ library can be buil…""
|
Revert "Revert "There are so many combinations that the libstdc++ library can be buil…""
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
611d2a7e46bd42abc2e948fa7ad2ad8c2bab691b
|
trunk/research/ts_info.cpp
|
trunk/research/ts_info.cpp
|
/**
g++ -o ts_info ts_info.cpp -g -O0 -ansi
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
/**
ISO/IEC 13818-1:2000(E)
Introduction
Intro. 1 Transport Stream
The Transport Stream system layer is divided into two sub-layers, one for multiplex-wide operations
(the Transport Stream packet layer), and one for stream-specific operations (the PES packet layer).
Intro. 2 Program Stream
The Program Stream system layer is divided into two sub-layers, one for multiplex-wide operations
(the pack layer), and one for stream-specific operations (the PES packet layer).
Intro. 4 Packetized Elementary Stream
SECTION 2 C TECHNICAL ELEMENTS
2.4 Transport Stream bitstream requirements
2.5 Program Stream bitstream requirements
2.6 Program and program element descriptors
2.7 Restrictions on the multiplexed stream semantics
Annex A C CRC Decoder Model
*/
#define trace(msg, ...) printf(msg"\n", ##__VA_ARGS__);
int main(int /*argc*/, char** /*argv*/)
{
const char* file = "livestream-1347.ts";
int fd = open(file, O_RDONLY);
trace("demuxer+read packet count offset P+0 P+1 P+2 P+x P+L2 P+L1 P+L0");
for (int i = 0, offset = 0; ; i++) {
unsigned char PES[188];
memset(PES, 0, sizeof(PES));
int ret = read(fd, PES, sizeof(PES));
if (ret == 0) {
trace("demuxer+read EOF, read completed, offset: %07d.", offset);
break;
}
trace("demuxer+read packet %04d %07d 0x%02x 0x%02x 0x%02x ... 0x%02x 0x%02x 0x%02x",
i, offset, PES[0], PES[1], PES[2], PES[185], PES[186], PES[187]);
offset += ret;
}
close(fd);
return 0;
}
|
/**
g++ -o ts_info ts_info.cpp -g -O0 -ansi
*/
#if 1
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#define trace(msg, ...) printf(msg"\n", ##__VA_ARGS__);
#define srs_freep(p) delete p; p = NULL
#define srs_freepa(p) delete[] p; p = NULL
#define srs_assert(p) assert(p)
#endif
/**
ISO/IEC 13818-1:2000(E)
Introduction
Intro. 1 Transport Stream
Intro. 2 Program Stream
Intro. 4 Packetized Elementary Stream
SECTION 2 C TECHNICAL ELEMENTS
2.4 Transport Stream bitstream requirements
2.4.1 Transport Stream coding structure and parameters
2.4.2 Transport Stream system target decoder
2.4.3 Specification of the Transport Stream syntax and semantics
2.4.3.1 Transport Stream
2.4.3.2 Transport Stream packet layer
2.4.3.3 Semantic definition of fields in Transport Stream packet layer
2.4.3.5 Semantic definition of fields in adaptation field
2.4.3.6 PES packet
2.4.3.7 Semantic definition of fields in PES packet
2.4.4 Program specific information
2.4.4.5 Semantic definition of fields in program association section
2.4.4.6 Conditional access Table
2.5 Program Stream bitstream requirements
2.6 Program and program element descriptors
2.7 Restrictions on the multiplexed stream semantics
Annex A C CRC Decoder Model
*/
#if 1
// Transport Stream packets are 188 bytes in length.
#define TS_PACKET_SIZE 188
// Program Association Table(see Table 2-25).
#define PID_PAT 0x00
// Conditional Access Table (see Table 2-27).
#define PID_CAT 0x01
// Transport Stream Description Table
#define PID_TSDT 0x02
// null packets (see Table 2-3)
#define PID_NULL 0x01FFF
/*adaptation_field_control*/
// No adaptation_field, payload only
#define AFC_PAYLOAD_ONLY 0x01
// Adaptation_field only, no payload
#define AFC_ADAPTION_ONLY 0x02
// Adaptation_field followed by payload
#define AFC_BOTH 0x03
#endif
struct TSPacket
{
// 4B ts packet header.
struct Header
{
// 1B
int8_t sync_byte; //8bits
// 2B
int8_t transport_error_indicator; //1bit
int8_t payload_unit_start_indicator; //1bit
int8_t transport_priority; //1bit
u_int16_t pid; //13bits
// 1B
int8_t transport_scrambling_control; //2bits
int8_t adaption_field_control; //2bits
u_int8_t continuity_counter; //4bits
int get_size()
{
return 4;
}
int demux(TSPacket* ppkt, u_int8_t* start, u_int8_t* last, u_int8_t*& p)
{
int ret = 0;
// ts packet header.
sync_byte = *p++;
if (sync_byte != 0x47) {
trace("ts+sync_bytes invalid sync_bytes: %#x, expect is 0x47", sync_byte);
return -1;
}
pid = 0;
((char*)&pid)[1] = *p++;
((char*)&pid)[0] = *p++;
transport_error_indicator = (pid >> 15) & 0x01;
payload_unit_start_indicator = (pid >> 14) & 0x01;
transport_priority = (pid >> 13) & 0x01;
pid &= 0x1FFF;
continuity_counter = *p++;
transport_scrambling_control = (continuity_counter >> 6) & 0x03;
adaption_field_control = (continuity_counter >> 4) & 0x03;
continuity_counter &= 0x0F;
trace("ts+header sync: %#x error: %d unit_start: %d priotiry: %d pid: %d scrambling: %d adaption: %d counter: %d",
sync_byte, transport_error_indicator, payload_unit_start_indicator, transport_priority, pid,
transport_scrambling_control, adaption_field_control, continuity_counter);
return ret;
}
}header;
// variant ts packet adation field.
struct AdaptionField
{
// 1B
u_int8_t adaption_field_length; //8bits
// 1B
int8_t discontinuity_indicator; //1bit
int8_t random_access_indicator; //1bit
int8_t elementary_stream_priority_indicator; //1bit
int8_t PCR_flag; //1bit
int8_t OPCR_flag; //1bit
int8_t splicing_point_flag; //1bit
int8_t transport_private_data_flag; //1bit
int8_t adaptation_field_extension_flag; //1bit
// if PCR_flag, 6B
int64_t program_clock_reference_base; //33bits
//6bits reserved.
int16_t program_clock_reference_extension; //9bits
// if OPCR_flag, 6B
int64_t original_program_clock_reference_base; //33bits
//6bits reserved.
int16_t original_program_clock_reference_extension; //9bits
// if splicing_point_flag, 1B
int8_t splice_countdown; //8bits
// if transport_private_data_flag, 1+p[0] B
u_int8_t transport_private_data_length; //8bits
char* transport_private_data; //[transport_private_data_length]bytes
// if adaptation_field_extension_flag, 2+x bytes
u_int8_t adaptation_field_extension_length; //8bits
int8_t ltw_flag; //1bit
int8_t piecewise_rate_flag; //1bit
int8_t seamless_splice_flag; //1bit
//5bits reserved
// if ltw_flag, 2B
int8_t ltw_valid_flag; //1bit
int16_t ltw_offset; //15bits
// if piecewise_rate_flag, 3B
//2bits reserved
int32_t piecewise_rate; //22bits
// if seamless_splice_flag, 5B
int8_t splice_type; //4bits
int8_t DTS_next_AU0; //3bits
int8_t marker_bit0; //1bit
int16_t DTS_next_AU1; //15bits
int8_t marker_bit1; //1bit
int16_t DTS_next_AU2; //15bits
int8_t marker_bit2; //1bit
// left bytes.
char* af_ext_reserved;
// left bytes.
char* af_reserved;
// user defined data size.
int __user_size;
AdaptionField()
{
transport_private_data = NULL;
af_ext_reserved = NULL;
af_reserved = NULL;
__user_size = 0;
}
virtual ~AdaptionField()
{
srs_freepa(transport_private_data);
srs_freepa(af_ext_reserved);
srs_freepa(af_reserved);
}
int get_size()
{
return __user_size;
}
int demux(TSPacket* ppkt, u_int8_t* start, u_int8_t* last, u_int8_t*& p)
{
int ret = 0;
adaption_field_length = *p++;
u_int8_t* pos_af = p;
__user_size = 1 + adaption_field_length;
if (adaption_field_length <= 0) {
trace("ts+af empty af decoded.");
return ret;
}
int8_t value = *p++;
discontinuity_indicator = (value >> 7) & 0x01;
random_access_indicator = (value >> 6) & 0x01;
elementary_stream_priority_indicator = (value >> 5) & 0x01;
PCR_flag = (value >> 4) & 0x01;
OPCR_flag = (value >> 3) & 0x01;
splicing_point_flag = (value >> 2) & 0x01;
transport_private_data_flag = (value >> 1) & 0x01;
adaptation_field_extension_flag = (value >> 0) & 0x01;
trace("ts+af af flags parsed, discontinuity: %d random: %d priority: %d PCR: %d OPCR: %d slicing: %d private: %d extension: %d",
discontinuity_indicator, random_access_indicator, elementary_stream_priority_indicator, PCR_flag, OPCR_flag, splicing_point_flag,
transport_private_data_flag, adaptation_field_extension_flag);
char* pp = NULL;
if (PCR_flag) {
pp = (char*)&program_clock_reference_base;
pp[5] = *p++;
pp[4] = *p++;
pp[3] = *p++;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
program_clock_reference_extension = program_clock_reference_base & 0x1F;
program_clock_reference_base = (program_clock_reference_base >> 9) & 0x1FFFFFFFF;
}
if (OPCR_flag) {
pp = (char*)&original_program_clock_reference_base;
pp[5] = *p++;
pp[4] = *p++;
pp[3] = *p++;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
original_program_clock_reference_extension = original_program_clock_reference_base & 0x1F;
original_program_clock_reference_base = (original_program_clock_reference_base >> 9) & 0x1FFFFFFFF;
}
if (splicing_point_flag) {
splice_countdown = *p++;
}
if (transport_private_data_flag) {
transport_private_data_length = *p++;
transport_private_data = new char[transport_private_data_length];
for (int i = 0; i < transport_private_data_length; i++) {
transport_private_data[i] = *p++;
}
}
if (adaptation_field_extension_flag) {
adaptation_field_extension_length = *p++;
u_int8_t* pos_af_ext = p;
ltw_flag = *p++;
piecewise_rate_flag = (ltw_flag >> 6) & 0x01;
seamless_splice_flag = (ltw_flag >> 5) & 0x01;
ltw_flag = (ltw_flag >> 7) & 0x01;
if (ltw_flag) {
pp = (char*)<w_offset;
pp[1] = *p++;
pp[0] = *p++;
ltw_valid_flag = (ltw_offset >> 15) &0x01;
ltw_offset &= 0x7FFF;
}
if (piecewise_rate_flag) {
pp = (char*)&piecewise_rate;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
piecewise_rate &= 0x3FFFFF;
}
if (seamless_splice_flag) {
// 1B
marker_bit0 = *p++;
splice_type = (marker_bit0 >> 4) & 0x0F;
DTS_next_AU0 = (marker_bit0 >> 1) & 0x07;
marker_bit0 &= 0x01;
// 2B
pp = (char*)&DTS_next_AU1;
pp[1] = *p++;
pp[0] = *p++;
marker_bit1 = DTS_next_AU1 & 0x01;
DTS_next_AU1 = (DTS_next_AU1 >> 1) & 0x7FFF;
// 2B
pp = (char*)&DTS_next_AU2;
pp[1] = *p++;
pp[0] = *p++;
marker_bit2 = DTS_next_AU2 & 0x01;
DTS_next_AU2 = (DTS_next_AU2 >> 1) & 0x7FFF;
}
// af_ext_reserved
int ext_size = adaptation_field_extension_length - (p - pos_af_ext);
if (ext_size > 0) {
af_ext_reserved = new char[ext_size];
memcpy(af_ext_reserved, p, ext_size);
p += ext_size;
}
}
// af_reserved
int af_size = adaption_field_length - (p - pos_af);
if (af_size > 0) {
af_reserved = new char[af_size];
memcpy(af_reserved, p, af_size);
p += af_size;
}
return ret;
}
}adaption_field;
// variant ts packet payload.
// PES packet or PSI table.
struct Payload
{
/**
* the size of payload(payload plush the 1byte pointer_field).
*/
int size;
int pointer_field_size;
/**
* the actually parsed type.
*/
enum Type
{
TypeUnknown=-1,
TypeReserved, // TypeReserved, nothing parsed, used reserved.
TypePAT, //TypePAT, PAT parsed, in pat field.
} type;
/**
* 2.4.4.2 Semantics definition of fields in pointer syntax
*/
u_int8_t pointer_field;
/**
* if not parsed, store data in this field.
*/
struct Reserved
{
int size;
char* bytes;
Reserved()
{
size = 0;
bytes = NULL;
}
virtual ~Reserved()
{
srs_freepa(bytes);
}
int demux(TSPacket* ppkt, u_int8_t* start, u_int8_t* last, u_int8_t*& p)
{
int ret = 0;
size = ppkt->payload.size - ppkt->payload.pointer_field_size;
// not parsed bytes.
if (size > 0) {
bytes = new char[size];
memcpy(bytes, p, size);
p += size;
}
return ret;
}
} *reserved;
/**
* 2.4.4.3 Program association Table. page 61.
*/
struct PAT {
// 1B
u_int8_t table_id; //8bits
// 2B
int8_t section_syntax_indicator; //1bit
int8_t const0_value; //1bit
// 2bits reserved.
u_int16_t section_length; //12bits
// 2B
u_int16_t transport_stream_id; //16bits
// 1B
// 2bits reerverd.
int8_t version_number; //5bits
int8_t current_next_indicator; //1bit
// 1B
u_int8_t section_number; //8bits
// 1B
u_int8_t last_section_number; //8bits
// multiple 4B program data.
// program_number 16bits
// reserved 2bits
// 13bits data: 0x1FFF
// if program_number program_map_PID 13bits
// else network_PID 13bytes.
int program_size;
int32_t* programs; //32bits
// 4B
int32_t CRC_32; //32bits
PAT()
{
programs = NULL;
}
virtual ~PAT()
{
srs_freepa(programs);
}
int get_program(int index)
{
srs_assert(index < program_size);
return programs[index] & 0x1FFF;
}
int demux(TSPacket* ppkt, u_int8_t* start, u_int8_t* last, u_int8_t*& p)
{
int ret = 0;
table_id = *p++;
char* pp = (char*)§ion_length;
pp[1] = *p++;
pp[0] = *p++;
u_int8_t* pos = p;
section_syntax_indicator = (section_length >> 15) & 0x01;
const0_value = (section_length >> 14) & 0x01;
section_length &= 0x0FFF;
pp = (char*)&transport_stream_id;
pp[1] = *p++;
pp[0] = *p++;
current_next_indicator = *p++;
version_number = (current_next_indicator >> 1) & 0x1F;
current_next_indicator &= 0x01;
section_number = *p++;
last_section_number = *p++;
// 4 is crc size.
int program_bytes = section_length - 4 - (p - pos);
program_size = program_bytes / 4;
if (program_size > 0) {
programs = new int32_t[program_size];
for (int i = 0; i < program_size; i++) {
pp = (char*)&programs[i];
pp[3] = *p++;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
}
}
pp = (char*)&CRC_32;
pp[3] = *p++;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
return ret;
}
} *pat;
/**
* 2.4.3.6 PES packet. page 49.
*/
Payload()
{
size = 0;
pointer_field_size = 0;
type = TypeUnknown;
reserved = NULL;
pat = NULL;
}
virtual ~Payload()
{
srs_freep(reserved);
srs_freep(pat);
}
int demux(TSPacket* ppkt, u_int8_t* start, u_int8_t* last, u_int8_t*& p)
{
int ret = 0;
if (ppkt->header.payload_unit_start_indicator) {
pointer_field = *p++;
pointer_field_size = 1;
}
if (ppkt->header.pid == PID_PAT) {
type = TypePAT;
pat = new PAT();
return pat->demux(ppkt, start, last, p);
}
// not parsed bytes.
type = TypeReserved;
reserved = new Reserved();
if ((ret = reserved->demux(ppkt, start, last, p)) != 0) {
return ret;
}
return ret;
}
}payload;
int demux(u_int8_t* start, u_int8_t* last, u_int8_t*& p)
{
int ret = 0;
if ((ret = header.demux(this, start, last, p)) != 0) {
return ret;
}
if (header.adaption_field_control == AFC_ADAPTION_ONLY || header.adaption_field_control == AFC_BOTH) {
if ((ret = adaption_field.demux(this, start, last, p)) != 0) {
trace("ts+header af(adaption field) decode error. ret=%d", ret);
return ret;
}
trace("ts+header af(adaption field decoded.");
}
// calc the user defined data size for payload.
payload.size = TS_PACKET_SIZE - header.get_size() - adaption_field.get_size();
if (header.adaption_field_control == AFC_PAYLOAD_ONLY || header.adaption_field_control == AFC_BOTH) {
if ((ret = payload.demux(this, start, last, p)) != 0) {
trace("ts+header payload decode error. ret=%d", ret);
return ret;
}
trace("ts+header payload decoded.");
}
trace("ts+header parsed finished. parsed: %d left: %d header: %d payload: %d(%d+%d)",
(int)(p - start), (int)(last - p), header.get_size(), payload.size, payload.pointer_field_size,
payload.size - payload.pointer_field_size);
return finish();
}
int finish()
{
return 0;
}
};
int main(int /*argc*/, char** /*argv*/)
{
const char* file = "livestream-1347.ts";
//file = "nginx-rtmp-hls/livestream-1347-currupt.ts";
int fd = open(file, O_RDONLY);
int ret = 0;
trace("demuxer+read packet count offset T+0 T+1 T+2 T+3 T+x T+L2 T+L1 T+L0");
for (int i = 0, offset = 0; ; i++) {
u_int8_t ts_packet[TS_PACKET_SIZE];
memset(ts_packet, 0, sizeof(ts_packet));
int nread = read(fd, ts_packet, sizeof(ts_packet));
if (nread == 0) {
trace("demuxer+read got EOF, read completed, offset: %07d.", offset);
break;
}
if (nread != TS_PACKET_SIZE) {
trace("demuxer+read error to read ts packet. nread=%d", nread);
break;
}
trace("demuxer+read packet %04d %07d 0x%02x 0x%02x 0x%02x 0x%02x ... 0x%02x 0x%02x 0x%02x",
i, offset, ts_packet[0], ts_packet[1], ts_packet[2], ts_packet[3],
ts_packet[TS_PACKET_SIZE - 3], ts_packet[TS_PACKET_SIZE - 2], ts_packet[TS_PACKET_SIZE - 1]);
u_int8_t* p = ts_packet;
u_int8_t* start = ts_packet;
u_int8_t* last = ts_packet + TS_PACKET_SIZE;
TSPacket pkt;
if ((ret = pkt.demux(start, last, p)) != 0) {
trace("demuxer+read decode ts packet error. ret=%d", ret);
return ret;
}
offset += nread;
}
close(fd);
return ret;
}
|
update ts_info, parse header, adaption field and PAT
|
update ts_info, parse header, adaption field and PAT
|
C++
|
mit
|
KevinHM/simple-rtmp-server,myself659/simple-rtmp-server,KevinHM/simple-rtmp-server,dymx101/simple-rtmp-server,CallMeNP/srs,millken/simple-rtmp-server,nestle1998/srs,avplus/srs,millken/simple-rtmp-server,avplus/srs,chengjunjian/simple-rtmp-server,Vincent0209/simple-rtmp-server,icevl/srs,Robinson10240/simple-rtmp-server,millken/simple-rtmp-server,dymx101/simple-rtmp-server,Vincent0209/simple-rtmp-server,CallMeNP/srs,tempbottle/simple-rtmp-server,zhiliaoniu/simple-rtmp-server,winlinvip/simple-rtmp-server,flashbuckets/srs,keyanmca/srs-May-2014,nestle1998/srs,CallMeNP/srs,winlinvip/srs,lzpfmh/simple-rtmp-server,rudeb0t/simple-rtmp-server,JinruiWang/srs,millken/simple-rtmp-server,Vincent0209/simple-rtmp-server,Robinson10240/simple-rtmp-server,icevl/srs,nestle1998/srs,lewdon/srs,oceanho/simple-rtmp-server,chengjunjian/simple-rtmp-server,KevinHM/simple-rtmp-server,tempbottle/simple-rtmp-server,myself659/simple-rtmp-server,oceanho/simple-rtmp-server,skyfe79/srs,skyfe79/srs,myself659/simple-rtmp-server,icevl/srs,drunknbass/srs,antonioparisi/srs,rudeb0t/simple-rtmp-server,antonioparisi/srs,JinruiWang/srs,newlightdd/srs,nestle1998/srs,rudeb0t/simple-rtmp-server,keyanmca/srs-May-2014,danielfree/srs,rudeb0t/simple-rtmp-server,dymx101/srs,wenqinruan/srs,dymx101/simple-rtmp-server,newlightdd/srs,chengjunjian/simple-rtmp-server,flashbuckets/srs,danielfree/srs,CallMeNP/srs,flashbuckets/srs,WilliamRen/srs,chengjunjian/simple-rtmp-server,JinruiWang/srs,WilliamRen/srs,danielfree/srs,drunknbass/srs,ossrs/srs,Robinson10240/simple-rtmp-server,antonioparisi/srs,WilliamRen/srs,tempbottle/simple-rtmp-server,lzpfmh/simple-rtmp-server,KevinHM/simple-rtmp-server,rudeb0t/simple-rtmp-server,Vincent0209/simple-rtmp-server,avplus/srs,winlinvip/srs,nestle1998/srs,zhiliaoniu/simple-rtmp-server,winlinvip/srs,Vincent0209/simple-rtmp-server,winlinvip/srs,chengjunjian/simple-rtmp-server,danielfree/srs,tribbiani/srs,lewdon/srs,dymx101/simple-rtmp-server,danielfree/srs,dymx101/srs,lzpfmh/simple-rtmp-server,avplus/srs,keyanmca/srs-May-2014,icevl/srs,oceanho/simple-rtmp-server,icevl/srs,lewdon/srs,tempbottle/simple-rtmp-server,tempbottle/simple-rtmp-server,oceanho/simple-rtmp-server,skyfe79/srs,myself659/simple-rtmp-server,zhiliaoniu/simple-rtmp-server,newlightdd/srs,WilliamRen/srs,tribbiani/srs,millken/simple-rtmp-server,oceanho/simple-rtmp-server,skyfe79/srs,WilliamRen/srs,ossrs/srs,rudeb0t/simple-rtmp-server,Robinson10240/simple-rtmp-server,keyanmca/srs-May-2014,antonioparisi/srs,JinruiWang/srs,lzpfmh/simple-rtmp-server,newlightdd/srs,wenqinruan/srs,antonioparisi/srs,icevl/srs,myself659/simple-rtmp-server,newlightdd/srs,flashbuckets/srs,Vincent0209/simple-rtmp-server,lzpfmh/simple-rtmp-server,JinruiWang/srs,ossrs/srs,KevinHM/simple-rtmp-server,danielfree/srs,skyfe79/srs,tempbottle/simple-rtmp-server,ossrs/srs,lewdon/srs,nestle1998/srs,tribbiani/srs,dymx101/simple-rtmp-server,wenqinruan/srs,avplus/srs,millken/simple-rtmp-server,KevinHM/simple-rtmp-server,tribbiani/srs,Robinson10240/simple-rtmp-server,chengjunjian/simple-rtmp-server,winlinvip/srs,JinruiWang/srs,ossrs/srs,keyanmca/srs-May-2014,dymx101/srs,antonioparisi/srs,Robinson10240/simple-rtmp-server,wenqinruan/srs,oceanho/simple-rtmp-server,tribbiani/srs,dymx101/srs,tribbiani/srs,flashbuckets/srs,avplus/srs,keyanmca/srs-May-2014,winlinvip/srs,tribbiani/srs,CallMeNP/srs,skyfe79/srs,dymx101/srs,drunknbass/srs,avplus/srs,wenqinruan/srs,drunknbass/srs,CallMeNP/srs,lzpfmh/simple-rtmp-server,flashbuckets/srs,zhiliaoniu/simple-rtmp-server,dymx101/simple-rtmp-server,ossrs/srs,wenqinruan/srs,zhiliaoniu/simple-rtmp-server,lewdon/srs,drunknbass/srs,zhiliaoniu/simple-rtmp-server,myself659/simple-rtmp-server,lewdon/srs,WilliamRen/srs,dymx101/srs,drunknbass/srs,newlightdd/srs
|
3a4175397882fe3cb8368e6e1607f345665dc641
|
primality-test.cpp
|
primality-test.cpp
|
#include<math.h>
bool isPrimeBruteForce(int x) {
if (x < 2)
return false;
float sqroot_x = sqrt(x);
for(int i=0; i <= sqroot_x; i++) {
if (x%i==0)
return false;
}
return true;
}
|
#include<math.h>
bool isPrimeBruteForce(int x) {
if (x < 2)
return false;
float sqroot_x = sqrt(x);
for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
if (x%i==0)
return false;
}
return true;
}
|
Add comment to sqrt calculation
|
Add comment to sqrt calculation
|
C++
|
mit
|
luforst/primality-test,luforst/primality-test
|
d5d85a2bb71a40c0cc915be4bce047afd18af882
|
src/yuni/core/getopt/option.cpp
|
src/yuni/core/getopt/option.cpp
|
/*
** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org).
**
** This Source Code Form is subject to the terms of the Mozilla Public License
** v.2.0. If a copy of the MPL was not distributed with this file, You can
** obtain one at http://mozilla.org/MPL/2.0/.
**
** gitlab: https://gitlab.com/libyuni/libyuni/
** github: https://github.com/libyuni/libyuni/ {mirror}
*/
#include "option.h"
#define YUNI_GETOPT_HELPUSAGE_30CHAR " "
namespace Yuni
{
namespace Private
{
namespace GetOptImpl
{
template<bool Decal, int LengthLimit>
static void PrintLongDescription(std::ostream& out, const String& description)
{
uint start = 0;
uint end = 0;
uint offset = 0;
do
{
// Jump to the next separator
offset = description.find_first_of(" .\r\n\t", offset);
// No separator, aborting
if (String::npos == offset)
break;
if (offset - start < LengthLimit)
{
if ('\n' == description.at(offset))
{
out.write(description.c_str() + start, (std::streamsize)(offset - start));
out << '\n';
if (Decal)
out.write(YUNI_GETOPT_HELPUSAGE_30CHAR, 30);
start = offset + 1;
end = offset + 1;
}
else
end = offset;
}
else
{
if (0 == end)
end = offset;
out.write(description.c_str() + start, (std::streamsize)(end - start));
out << '\n';
if (Decal)
out.write(YUNI_GETOPT_HELPUSAGE_30CHAR, 30);
start = end + 1;
end = offset + 1;
}
++offset;
}
while (true);
// Display the remaining piece of string
if (start < description.size())
out << (description.c_str() + start);
}
void DisplayHelpForOption(std::ostream& out, const String::Char shortName, const String& longName,
const String& description, bool requireParameter)
{
// Space
if ('\0' != shortName && ' ' != shortName)
{
out.write(" -", 3);
out << shortName;
if (longName.empty())
{
if (requireParameter)
out.write(" VALUE", 6);
}
else
out.write(", ", 2);
}
else
out.write(" ", 6);
// Long name
if (longName.empty())
{
if (requireParameter)
out << " ";
else
out << " ";
}
else
{
out.write("--", 2);
out << longName;
if (requireParameter)
out.write("=VALUE", 6);
if (30 <= longName.size() + 6 /*-o,*/ + 2 /*--*/ + 1 /*space*/ + (requireParameter ? 6 : 0))
out << "\n ";
else
{
for (uint i = 6 + 2 + 1 + static_cast<uint>(longName.size()) + (requireParameter ? 6 : 0); i < 30; ++i)
out.put(' ');
}
}
// Description
if (description.size() <= 50 /* 80 - 30 */)
out << description;
else
PrintLongDescription<true, 50>(out, description);
out << '\n';
}
void DisplayTextParagraph(std::ostream& out, const String& text)
{
if (text.size() <= 80)
out << text;
else
PrintLongDescription<false, 80>(out, text);
out << '\n';
}
} // namespace GetOptImpl
} // namespace Private
} // namespace Yuni
|
/*
** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org).
**
** This Source Code Form is subject to the terms of the Mozilla Public License
** v.2.0. If a copy of the MPL was not distributed with this file, You can
** obtain one at http://mozilla.org/MPL/2.0/.
**
** gitlab: https://gitlab.com/libyuni/libyuni/
** github: https://github.com/libyuni/libyuni/ {mirror}
*/
#include "option.h"
#include <iostream>
#define YUNI_GETOPT_HELPUSAGE_30CHAR " "
namespace Yuni
{
namespace Private
{
namespace GetOptImpl
{
template<bool Decal, int LengthLimit>
static void PrintLongDescription(std::ostream& out, const String& description)
{
uint start = 0;
uint end = 0;
uint offset = 0;
do
{
// Jump to the next separator
offset = description.find_first_of(" .\r\n\t", offset);
// No separator, aborting
if (String::npos == offset)
break;
if (offset - start < LengthLimit)
{
if ('\n' == description.at(offset))
{
out.write(description.c_str() + start, (std::streamsize)(offset - start));
out << '\n';
if (Decal)
out.write(YUNI_GETOPT_HELPUSAGE_30CHAR, 30);
start = offset + 1;
end = offset + 1;
}
else
end = offset;
}
else
{
if (0 == end)
end = offset;
out.write(description.c_str() + start, (std::streamsize)(end - start));
out << '\n';
if (Decal)
out.write(YUNI_GETOPT_HELPUSAGE_30CHAR, 30);
start = end + 1;
end = offset + 1;
}
++offset;
}
while (true);
// Display the remaining piece of string
if (start < description.size())
out << (description.c_str() + start);
}
void DisplayHelpForOption(std::ostream& out, const String::Char shortName, const String& longName,
const String& description, bool requireParameter)
{
// Space
if ('\0' != shortName && ' ' != shortName)
{
out.write(" -", 3);
out << shortName;
if (longName.empty())
{
if (requireParameter)
out.write(" VALUE", 6);
}
else
out.write(", ", 2);
}
else
out.write(" ", 6);
// Long name
if (longName.empty())
{
if (requireParameter)
out << " ";
else
out << " ";
}
else
{
out.write("--", 2);
out << longName;
if (requireParameter)
out.write("=VALUE", 6);
if (30 <= longName.size() + 6 /*-o,*/ + 2 /*--*/ + 1 /*space*/ + (requireParameter ? 6 : 0))
out << "\n ";
else
{
for (uint i = 6 + 2 + 1 + static_cast<uint>(longName.size()) + (requireParameter ? 6 : 0); i < 30; ++i)
out.put(' ');
}
}
// Description
if (description.size() <= 50 /* 80 - 30 */)
out << description;
else
PrintLongDescription<true, 50>(out, description);
out << '\n';
}
void DisplayTextParagraph(std::ostream& out, const String& text)
{
if (text.size() <= 80)
out << text;
else
PrintLongDescription<false, 80>(out, text);
out << '\n';
}
} // namespace GetOptImpl
} // namespace Private
} // namespace Yuni
|
add missing include iostream
|
getopt: add missing include iostream
|
C++
|
mpl-2.0
|
libyuni/libyuni,libyuni/libyuni,libyuni/libyuni,libyuni/libyuni,libyuni/libyuni,libyuni/libyuni
|
397c2f4af0dbaa9a8cb0105f61c8c902f3e97d0e
|
libcore/include/sirikata/core/transfer/HttpManager.hpp
|
libcore/include/sirikata/core/transfer/HttpManager.hpp
|
/* Sirikata Transfer -- Content Transfer management system
* HttpManager.hpp
*
* Copyright (c) 2010, Jeff Terrace
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Created on: Jun 18th, 2010 */
#ifndef SIRIKATA_HttpManager_HPP__
#define SIRIKATA_HttpManager_HPP__
#include <sirikata/proxyobject/Platform.hpp>
#include <string>
#include <deque>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
// Apple defines the check macro in AssertMacros.h, which screws up some code in boost's iostreams lib
#ifdef check
#undef check
#endif
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/copy.hpp>
#include <sirikata/core/network/IOServicePool.hpp>
#include <sirikata/core/network/IOWork.hpp>
#include <sirikata/core/network/Asio.hpp>
#include <sirikata/core/network/Address.hpp>
#include <sirikata/core/transfer/TransferData.hpp>
#include "http_parser.h"
namespace Sirikata {
namespace Transfer {
/*
* Handles managing connections to the CDN
*/
class SIRIKATA_EXPORT HttpManager
: public AutoSingleton<HttpManager> {
public:
/*
* Stores headers and data returned from an HTTP request
* Also stores HTTP status code and content length in numeric format
* for convenience. These headers are also present in raw (string) format
*
* Note that getData might return a null pointer even if the
* http request was successful, e.g. for a HEAD request
*
* Note that getContentLength might not be a valid value. If there was no
* content length header in the response, getContentLength is undefined.
*/
class HttpResponse {
protected:
// This stuff is all used internally for http-parser
enum LAST_HEADER_CB {
NONE,
FIELD,
VALUE
};
std::string mTempHeaderField;
std::string mTempHeaderValue;
LAST_HEADER_CB mLastCallback;
bool mHeaderComplete;
bool mMessageComplete;
http_parser_settings mHttpSettings;
http_parser mHttpParser;
bool mGzip;
std::stringstream mCompressedStream;
//
std::map<std::string, std::string> mHeaders;
std::tr1::shared_ptr<DenseData> mData;
ssize_t mContentLength;
unsigned short mStatusCode;
HttpResponse()
: mLastCallback(NONE), mHeaderComplete(false), mMessageComplete(false),
mGzip(false), mContentLength(0), mStatusCode(0) {}
public:
inline std::tr1::shared_ptr<DenseData> getData() { return mData; }
inline const std::map<std::string, std::string>& getHeaders() { return mHeaders; }
inline ssize_t getContentLength() { return mContentLength; }
inline unsigned short getStatusCode() { return mStatusCode; }
friend class HttpManager;
};
//Type of errors that can be given to callback
enum ERR_TYPE {
SUCCESS,
REQUEST_PARSING_FAILED,
RESPONSE_PARSING_FAILED,
BOOST_ERROR
};
/*
* Callback for an HTTP request. If error == SUCCESS, then
* response is an HttpResponse object that has headers and data.
* If error == BOOST_ERROR, then boost_error is set to the boost
* error code. If an error is returned, response is NULL.
*/
typedef std::tr1::function<void(
std::tr1::shared_ptr<HttpResponse> response,
ERR_TYPE error,
const boost::system::error_code& boost_error
)> HttpCallback;
static HttpManager& getSingleton();
static void destroy();
//Methods supported
enum HTTP_METHOD {
HEAD,
GET
};
/*
* Makes an HTTP request and calls cb when finished
*/
void makeRequest(Sirikata::Network::Address addr, HTTP_METHOD method, std::string req, HttpCallback cb);
protected:
/*
* Protect constructor and destructor so can't make an instance of this class
* but allow AutoSingleton<HttpManager> to make a copy, and give access
* to the destructor to the auto_ptr used by AutoSingleton
*/
HttpManager();
~HttpManager();
friend class AutoSingleton<HttpManager>;
friend std::auto_ptr<HttpManager>::~auto_ptr();
friend void std::auto_ptr<HttpManager>::reset(HttpManager*);
private:
//For convenience
typedef Sirikata::Network::IOServicePool IOServicePool;
typedef Sirikata::Network::TCPResolver TCPResolver;
typedef Sirikata::Network::TCPSocket TCPSocket;
typedef Sirikata::Network::IOWork IOWork;
typedef Sirikata::Network::IOCallback IOCallback;
typedef boost::asio::ip::tcp::endpoint TCPEndPoint;
//Convenience of storing request parameters together
class HttpRequest {
public:
const Sirikata::Network::Address addr;
const std::string req;
const HttpCallback cb;
const HTTP_METHOD method;
HttpRequest(Sirikata::Network::Address _addr, std::string _req, HTTP_METHOD meth, HttpCallback _cb)
: addr(_addr), req(_req), cb(_cb), method(meth), mNumTries(0) {}
friend class HttpManager;
protected:
uint32 mNumTries;
};
//Holds a queue of requests to be made
typedef std::list<std::tr1::shared_ptr<HttpRequest> > RequestQueueType;
RequestQueueType mRequestQueue;
//Lock this to access mRequestQueue
boost::mutex mRequestQueueLock;
//TODO: should get these from settings
static const uint32 MAX_CONNECTIONS_PER_ENDPOINT = 2;
static const uint32 MAX_TOTAL_CONNECTIONS = 10;
static const uint32 SOCKET_BUFFER_SIZE = 10240;
//Keeps track of the total number of connections currently open
uint32 mNumTotalConnections;
//Keeps track of the number of connections open per host:port pair
typedef std::map<Sirikata::Network::Address, uint32> NumConnsType;
NumConnsType mNumConnsPerAddr;
//Lock this to access mNumTotalConnections or mNumConnsPerAddr
boost::mutex mNumConnsLock;
//Holds connections that are open but not being used
typedef std::map<Sirikata::Network::Address,
std::queue<std::tr1::shared_ptr<TCPSocket> > > RecycleBinType;
RecycleBinType mRecycleBin;
//Lock this to access mRecycleBin
boost::mutex mRecycleBinLock;
IOServicePool* mServicePool;
TCPResolver* mResolver;
http_parser_settings EMPTY_PARSER_SETTINGS;
void processQueue();
void add_req(std::tr1::shared_ptr<HttpRequest> req);
void decrement_connection(const Sirikata::Network::Address& addr);
void write_request(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req);
void handle_resolve(std::tr1::shared_ptr<HttpRequest> req, const boost::system::error_code& err,
TCPResolver::iterator endpoint_iterator);
void handle_connect(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req,
const boost::system::error_code& err, TCPResolver::iterator endpoint_iterator);
void handle_write_request(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req,
const boost::system::error_code& err, std::tr1::shared_ptr<boost::asio::streambuf> request_stream);
void handle_read(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req,
std::tr1::shared_ptr<std::vector<unsigned char> > vecbuf, std::tr1::shared_ptr<HttpResponse> respPtr,
const boost::system::error_code& err, std::size_t bytes_transferred);
static int on_header_field(http_parser *_, const char *at, size_t len);
static int on_header_value(http_parser *_, const char *at, size_t len);
static int on_headers_complete(http_parser *_);
static int on_body(http_parser *_, const char *at, size_t len);
static int on_message_complete(http_parser *_);
enum HTTP_PARSER_FLAGS
{ F_CHUNKED = 1 << 0
, F_CONNECTION_KEEP_ALIVE = 1 << 1
, F_CONNECTION_CLOSE = 1 << 2
, F_TRAILING = 1 << 3
, F_UPGRADE = 1 << 4
, F_SKIPBODY = 1 << 5
};
static void print_flags(std::tr1::shared_ptr<HttpResponse> resp);
public:
/*
* Posts a callback on the service pool
*/
void postCallback(IOCallback cb);
};
}
}
#endif
|
/* Sirikata Transfer -- Content Transfer management system
* HttpManager.hpp
*
* Copyright (c) 2010, Jeff Terrace
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Created on: Jun 18th, 2010 */
#ifndef SIRIKATA_HttpManager_HPP__
#define SIRIKATA_HttpManager_HPP__
#include <sirikata/proxyobject/Platform.hpp>
#include <string>
#include <deque>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
// Apple defines the check macro in AssertMacros.h, which screws up some code in boost's iostreams lib
#ifdef check
#undef check
#endif
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/copy.hpp>
#include <sirikata/core/network/IOServicePool.hpp>
#include <sirikata/core/network/IOWork.hpp>
#include <sirikata/core/network/Asio.hpp>
#include <sirikata/core/network/Address.hpp>
#include <sirikata/core/transfer/TransferData.hpp>
// This is a hack around a problem created by different packages
// creating slightly different typedefs -- notably http_parser and
// v8. On windows, we need to provide typedefs and make it skip that
// part of http_parser.h.
#if defined(_WIN32) && !defined(__MINGW32__)
typedef signed __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int size_t;
typedef int ssize_t;
// We turn on mingw to make it skip the include block, but then stdint
// is included, and only available via a zzip dependency. We block
// that out as well by using its include guard define
#define _ZZIP__STDINT_H 1
#define __MINGW32__
#include "http_parser.h"
#undef __MINGW32__
#else
#include "http_parser.h"
#endif
namespace Sirikata {
namespace Transfer {
/*
* Handles managing connections to the CDN
*/
class SIRIKATA_EXPORT HttpManager
: public AutoSingleton<HttpManager> {
public:
/*
* Stores headers and data returned from an HTTP request
* Also stores HTTP status code and content length in numeric format
* for convenience. These headers are also present in raw (string) format
*
* Note that getData might return a null pointer even if the
* http request was successful, e.g. for a HEAD request
*
* Note that getContentLength might not be a valid value. If there was no
* content length header in the response, getContentLength is undefined.
*/
class HttpResponse {
protected:
// This stuff is all used internally for http-parser
enum LAST_HEADER_CB {
NONE,
FIELD,
VALUE
};
std::string mTempHeaderField;
std::string mTempHeaderValue;
LAST_HEADER_CB mLastCallback;
bool mHeaderComplete;
bool mMessageComplete;
http_parser_settings mHttpSettings;
http_parser mHttpParser;
bool mGzip;
std::stringstream mCompressedStream;
//
std::map<std::string, std::string> mHeaders;
std::tr1::shared_ptr<DenseData> mData;
ssize_t mContentLength;
unsigned short mStatusCode;
HttpResponse()
: mLastCallback(NONE), mHeaderComplete(false), mMessageComplete(false),
mGzip(false), mContentLength(0), mStatusCode(0) {}
public:
inline std::tr1::shared_ptr<DenseData> getData() { return mData; }
inline const std::map<std::string, std::string>& getHeaders() { return mHeaders; }
inline ssize_t getContentLength() { return mContentLength; }
inline unsigned short getStatusCode() { return mStatusCode; }
friend class HttpManager;
};
//Type of errors that can be given to callback
enum ERR_TYPE {
SUCCESS,
REQUEST_PARSING_FAILED,
RESPONSE_PARSING_FAILED,
BOOST_ERROR
};
/*
* Callback for an HTTP request. If error == SUCCESS, then
* response is an HttpResponse object that has headers and data.
* If error == BOOST_ERROR, then boost_error is set to the boost
* error code. If an error is returned, response is NULL.
*/
typedef std::tr1::function<void(
std::tr1::shared_ptr<HttpResponse> response,
ERR_TYPE error,
const boost::system::error_code& boost_error
)> HttpCallback;
static HttpManager& getSingleton();
static void destroy();
//Methods supported
enum HTTP_METHOD {
HEAD,
GET
};
/*
* Makes an HTTP request and calls cb when finished
*/
void makeRequest(Sirikata::Network::Address addr, HTTP_METHOD method, std::string req, HttpCallback cb);
protected:
/*
* Protect constructor and destructor so can't make an instance of this class
* but allow AutoSingleton<HttpManager> to make a copy, and give access
* to the destructor to the auto_ptr used by AutoSingleton
*/
HttpManager();
~HttpManager();
friend class AutoSingleton<HttpManager>;
friend std::auto_ptr<HttpManager>::~auto_ptr();
friend void std::auto_ptr<HttpManager>::reset(HttpManager*);
private:
//For convenience
typedef Sirikata::Network::IOServicePool IOServicePool;
typedef Sirikata::Network::TCPResolver TCPResolver;
typedef Sirikata::Network::TCPSocket TCPSocket;
typedef Sirikata::Network::IOWork IOWork;
typedef Sirikata::Network::IOCallback IOCallback;
typedef boost::asio::ip::tcp::endpoint TCPEndPoint;
//Convenience of storing request parameters together
class HttpRequest {
public:
const Sirikata::Network::Address addr;
const std::string req;
const HttpCallback cb;
const HTTP_METHOD method;
HttpRequest(Sirikata::Network::Address _addr, std::string _req, HTTP_METHOD meth, HttpCallback _cb)
: addr(_addr), req(_req), cb(_cb), method(meth), mNumTries(0) {}
friend class HttpManager;
protected:
uint32 mNumTries;
};
//Holds a queue of requests to be made
typedef std::list<std::tr1::shared_ptr<HttpRequest> > RequestQueueType;
RequestQueueType mRequestQueue;
//Lock this to access mRequestQueue
boost::mutex mRequestQueueLock;
//TODO: should get these from settings
static const uint32 MAX_CONNECTIONS_PER_ENDPOINT = 2;
static const uint32 MAX_TOTAL_CONNECTIONS = 10;
static const uint32 SOCKET_BUFFER_SIZE = 10240;
//Keeps track of the total number of connections currently open
uint32 mNumTotalConnections;
//Keeps track of the number of connections open per host:port pair
typedef std::map<Sirikata::Network::Address, uint32> NumConnsType;
NumConnsType mNumConnsPerAddr;
//Lock this to access mNumTotalConnections or mNumConnsPerAddr
boost::mutex mNumConnsLock;
//Holds connections that are open but not being used
typedef std::map<Sirikata::Network::Address,
std::queue<std::tr1::shared_ptr<TCPSocket> > > RecycleBinType;
RecycleBinType mRecycleBin;
//Lock this to access mRecycleBin
boost::mutex mRecycleBinLock;
IOServicePool* mServicePool;
TCPResolver* mResolver;
http_parser_settings EMPTY_PARSER_SETTINGS;
void processQueue();
void add_req(std::tr1::shared_ptr<HttpRequest> req);
void decrement_connection(const Sirikata::Network::Address& addr);
void write_request(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req);
void handle_resolve(std::tr1::shared_ptr<HttpRequest> req, const boost::system::error_code& err,
TCPResolver::iterator endpoint_iterator);
void handle_connect(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req,
const boost::system::error_code& err, TCPResolver::iterator endpoint_iterator);
void handle_write_request(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req,
const boost::system::error_code& err, std::tr1::shared_ptr<boost::asio::streambuf> request_stream);
void handle_read(std::tr1::shared_ptr<TCPSocket> socket, std::tr1::shared_ptr<HttpRequest> req,
std::tr1::shared_ptr<std::vector<unsigned char> > vecbuf, std::tr1::shared_ptr<HttpResponse> respPtr,
const boost::system::error_code& err, std::size_t bytes_transferred);
static int on_header_field(http_parser *_, const char *at, size_t len);
static int on_header_value(http_parser *_, const char *at, size_t len);
static int on_headers_complete(http_parser *_);
static int on_body(http_parser *_, const char *at, size_t len);
static int on_message_complete(http_parser *_);
enum HTTP_PARSER_FLAGS
{ F_CHUNKED = 1 << 0
, F_CONNECTION_KEEP_ALIVE = 1 << 1
, F_CONNECTION_CLOSE = 1 << 2
, F_TRAILING = 1 << 3
, F_UPGRADE = 1 << 4
, F_SKIPBODY = 1 << 5
};
static void print_flags(std::tr1::shared_ptr<HttpResponse> resp);
public:
/*
* Posts a callback on the service pool
*/
void postCallback(IOCallback cb);
};
}
}
#endif
|
Add hack around http_parser include to avoid conflicting typedefs between v8 and http_parser.
|
Add hack around http_parser include to avoid conflicting typedefs between v8 and http_parser.
|
C++
|
bsd-3-clause
|
sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata
|
a2cd7ffd25e6213f36139cda4a911e2e03ed417c
|
common/block_slist-t.hpp
|
common/block_slist-t.hpp
|
// This file is part of The New Aspell
// Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license
// version 2.0 or 2.1. You should have received a copy of the LGPL
// license along with this library if you did not you can find
// it at http://www.gnu.org/.
#ifndef autil__block_slist_t_hh
#define autil__block_slist_t_hh
#include <cstdlib>
#include <cassert>
#include "block_slist.hpp"
namespace acommon {
template <typename T>
void BlockSList<T>::add_block(unsigned int num)
{
assert (reinterpret_cast<const char *>(&(first_available->next))
==
reinterpret_cast<const char *>(first_available));
const unsigned int ptr_offset =
reinterpret_cast<const char *>(&(first_available->data))
- reinterpret_cast<const char *>(&(first_available->next));
void * block = malloc( ptr_offset + sizeof(Node) * num );
*reinterpret_cast<void **>(block) = first_block;
first_block = block;
Node * first = reinterpret_cast<Node *>(reinterpret_cast<char *>(block) + ptr_offset);
Node * i = first;
Node * last = i + num;
while (i + 1 != last) {
i->next = i + 1;
i = i + 1;
}
i->next = 0;
first_available = first;
}
template <typename T>
void BlockSList<T>::clear()
{
void * i = first_block;
while (i != 0) {
void * n = *reinterpret_cast<void **>(i);
free(i);
i = n;
}
first_block = 0;
first_available = 0;
}
}
#endif
|
// This file is part of The New Aspell
// Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license
// version 2.0 or 2.1. You should have received a copy of the LGPL
// license along with this library if you did not you can find
// it at http://www.gnu.org/.
#ifndef autil__block_slist_t_hh
#define autil__block_slist_t_hh
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include "block_slist.hpp"
namespace acommon {
template <typename T>
void BlockSList<T>::add_block(unsigned int num)
{
assert (offsetof(Node,next)==0);
const unsigned int ptr_offset = offsetof(Node, data);
void * block = malloc( ptr_offset + sizeof(Node) * num );
*reinterpret_cast<void **>(block) = first_block;
first_block = block;
Node * first = reinterpret_cast<Node *>(reinterpret_cast<char *>(block) + ptr_offset);
Node * i = first;
Node * last = i + num;
while (i + 1 != last) {
i->next = i + 1;
i = i + 1;
}
i->next = 0;
first_available = first;
}
template <typename T>
void BlockSList<T>::clear()
{
void * i = first_block;
while (i != 0) {
void * n = *reinterpret_cast<void **>(i);
free(i);
i = n;
}
first_block = 0;
first_available = 0;
}
}
#endif
|
use offsetof macro to avoid undefined behaviour
|
block_slist: use offsetof macro to avoid undefined behaviour
|
C++
|
lgpl-2.1
|
GNUAspell/aspell,GNUAspell/aspell,GNUAspell/aspell,GNUAspell/aspell
|
8b3d5b2da08dc867a33d7bc83e8d17a7289b6028
|
streaming/connection_handler.hh
|
streaming/connection_handler.hh
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#pragma once
#include "utils/UUID.hh"
#include "gms/inet_address.hh"
#include "streaming/stream_session.hh"
#include "streaming/session_info.hh"
#include "streaming/progress_info.hh"
namespace streaming {
/**
* ConnectionHandler manages incoming/outgoing message exchange for the {@link StreamSession}.
*
* <p>
* Internally, ConnectionHandler manages thread to receive incoming {@link StreamMessage} and thread to
* send outgoing message. Messages are encoded/decoded on those thread and handed to
* {@link StreamSession#messageReceived(org.apache.cassandra.streaming.messages.StreamMessage)}.
*/
class connection_handler {
public:
connection_handler(stream_session session)
: _session(std::move(session))
, _incoming(_session)
, _outgoing(_session) {
}
#if 0
/**
* Set up incoming message handler and initiate streaming.
*
* This method is called once on initiator.
*
* @throws IOException
*/
public void initiate() throws IOException
{
logger.debug("[Stream #{}] Sending stream init for incoming stream", session.planId());
Socket incomingSocket = session.createConnection();
incoming.start(incomingSocket, StreamMessage.CURRENT_VERSION);
incoming.sendInitMessage(incomingSocket, true);
logger.debug("[Stream #{}] Sending stream init for outgoing stream", session.planId());
Socket outgoingSocket = session.createConnection();
outgoing.start(outgoingSocket, StreamMessage.CURRENT_VERSION);
outgoing.sendInitMessage(outgoingSocket, false);
}
/**
* Set up outgoing message handler on receiving side.
*
* @param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}.
* @param version Streaming message version
* @throws IOException
*/
public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException
{
if (isForOutgoing)
outgoing.start(socket, version);
else
incoming.start(socket, version);
}
public ListenableFuture<?> close()
{
logger.debug("[Stream #{}] Closing stream connection handler on {}", session.planId(), session.peer);
ListenableFuture<?> inClosed = incoming == null ? Futures.immediateFuture(null) : incoming.close();
ListenableFuture<?> outClosed = outgoing == null ? Futures.immediateFuture(null) : outgoing.close();
return Futures.allAsList(inClosed, outClosed);
}
/**
* Enqueue messages to be sent.
*
* @param messages messages to send
*/
public void sendMessages(Collection<? extends StreamMessage> messages)
{
for (StreamMessage message : messages)
sendMessage(message);
}
public void sendMessage(StreamMessage message)
{
if (outgoing.isClosed())
throw new RuntimeException("Outgoing stream handler has been closed");
outgoing.enqueue(message);
}
/**
* @return true if outgoing connection is opened and ready to send messages
*/
public boolean isOutgoingConnected()
{
return outgoing != null && !outgoing.isClosed();
}
#endif
public:
class message_handler {
protected:
stream_session& session;
int protocol_version;
message_handler(stream_session& session_) : session(session_) {
}
#if 0
protected Socket socket;
private final AtomicReference<SettableFuture<?>> closeFuture = new AtomicReference<>();
protected abstract String name();
protected static DataOutputStreamAndChannel getWriteChannel(Socket socket) throws IOException
{
WritableByteChannel out = socket.getChannel();
// socket channel is null when encrypted(SSL)
if (out == null)
out = Channels.newChannel(socket.getOutputStream());
return new DataOutputStreamAndChannel(socket.getOutputStream(), out);
}
protected static ReadableByteChannel getReadChannel(Socket socket) throws IOException
{
ReadableByteChannel in = socket.getChannel();
// socket channel is null when encrypted(SSL)
return in == null
? Channels.newChannel(socket.getInputStream())
: in;
}
public void sendInitMessage(Socket socket, boolean isForOutgoing) throws IOException
{
StreamInitMessage message = new StreamInitMessage(
FBUtilities.getBroadcastAddress(),
session.sessionIndex(),
session.planId(),
session.description(),
isForOutgoing,
session.keepSSTableLevel());
ByteBuffer messageBuf = message.createMessage(false, protocolVersion);
getWriteChannel(socket).write(messageBuf);
}
public void start(Socket socket, int protocolVersion)
{
this.socket = socket;
this.protocolVersion = protocolVersion;
new Thread(this, name() + "-" + session.peer).start();
}
public ListenableFuture<?> close()
{
// Assume it wasn't closed. Not a huge deal if we create a future on a race
SettableFuture<?> future = SettableFuture.create();
return closeFuture.compareAndSet(null, future)
? future
: closeFuture.get();
}
public boolean isClosed()
{
return closeFuture.get() != null;
}
protected void signalCloseDone()
{
closeFuture.get().set(null);
// We can now close the socket
try
{
socket.close();
}
catch (IOException ignore) {}
}
#endif
};
/**
* Incoming streaming message handler
*/
class incoming_message_handler : public message_handler {
public:
incoming_message_handler(stream_session& session) : message_handler(session) {
}
sstring name() {
return "STREAM-IN";
}
#if 0
public void run()
{
try
{
ReadableByteChannel in = getReadChannel(socket);
while (!isClosed())
{
// receive message
StreamMessage message = StreamMessage.deserialize(in, protocolVersion, session);
// Might be null if there is an error during streaming (see FileMessage.deserialize). It's ok
// to ignore here since we'll have asked for a retry.
if (message != null)
{
logger.debug("[Stream #{}] Received {}", session.planId(), message);
session.messageReceived(message);
}
}
}
catch (SocketException e)
{
// socket is closed
close();
}
catch (Throwable t)
{
JVMStabilityInspector.inspectThrowable(t);
session.onError(t);
}
finally
{
signalCloseDone();
}
}
#endif
};
/**
* Outgoing file transfer thread
*/
class outgoing_message_handler : public message_handler {
public:
outgoing_message_handler(stream_session& session) : message_handler(session) {
}
sstring name() {
return "STREAM-OUT";
}
#if 0
/*
* All out going messages are queued up into messageQueue.
* The size will grow when received streaming request.
*
* Queue is also PriorityQueue so that prior messages can go out fast.
*/
private final PriorityBlockingQueue<StreamMessage> messageQueue = new PriorityBlockingQueue<>(64, new Comparator<StreamMessage>()
{
public int compare(StreamMessage o1, StreamMessage o2)
{
return o2.getPriority() - o1.getPriority();
}
});
public void enqueue(StreamMessage message)
{
messageQueue.put(message);
}
public void run()
{
try
{
DataOutputStreamAndChannel out = getWriteChannel(socket);
StreamMessage next;
while (!isClosed())
{
if ((next = messageQueue.poll(1, TimeUnit.SECONDS)) != null)
{
logger.debug("[Stream #{}] Sending {}", session.planId(), next);
sendMessage(out, next);
if (next.type == StreamMessage.Type.SESSION_FAILED)
close();
}
}
// Sends the last messages on the queue
while ((next = messageQueue.poll()) != null)
sendMessage(out, next);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
catch (Throwable e)
{
session.onError(e);
}
finally
{
signalCloseDone();
}
}
private void sendMessage(DataOutputStreamAndChannel out, StreamMessage message)
{
try
{
StreamMessage.serialize(message, out, protocolVersion, session);
}
catch (SocketException e)
{
session.onError(e);
close();
}
catch (IOException e)
{
session.onError(e);
}
}
#endif
};
private:
stream_session _session;
incoming_message_handler _incoming;
outgoing_message_handler _outgoing;
};
} // namespace streaming
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#pragma once
#include "utils/UUID.hh"
#include "gms/inet_address.hh"
#include "streaming/session_info.hh"
#include "streaming/progress_info.hh"
namespace streaming {
class stream_session;
/**
* ConnectionHandler manages incoming/outgoing message exchange for the {@link StreamSession}.
*
* <p>
* Internally, ConnectionHandler manages thread to receive incoming {@link StreamMessage} and thread to
* send outgoing message. Messages are encoded/decoded on those thread and handed to
* {@link StreamSession#messageReceived(org.apache.cassandra.streaming.messages.StreamMessage)}.
*/
class connection_handler {
public:
connection_handler(stream_session& session)
: _session(session)
, _incoming(session)
, _outgoing(session) {
}
#if 0
/**
* Set up incoming message handler and initiate streaming.
*
* This method is called once on initiator.
*
* @throws IOException
*/
public void initiate() throws IOException
{
logger.debug("[Stream #{}] Sending stream init for incoming stream", session.planId());
Socket incomingSocket = session.createConnection();
incoming.start(incomingSocket, StreamMessage.CURRENT_VERSION);
incoming.sendInitMessage(incomingSocket, true);
logger.debug("[Stream #{}] Sending stream init for outgoing stream", session.planId());
Socket outgoingSocket = session.createConnection();
outgoing.start(outgoingSocket, StreamMessage.CURRENT_VERSION);
outgoing.sendInitMessage(outgoingSocket, false);
}
/**
* Set up outgoing message handler on receiving side.
*
* @param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}.
* @param version Streaming message version
* @throws IOException
*/
public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException
{
if (isForOutgoing)
outgoing.start(socket, version);
else
incoming.start(socket, version);
}
public ListenableFuture<?> close()
{
logger.debug("[Stream #{}] Closing stream connection handler on {}", session.planId(), session.peer);
ListenableFuture<?> inClosed = incoming == null ? Futures.immediateFuture(null) : incoming.close();
ListenableFuture<?> outClosed = outgoing == null ? Futures.immediateFuture(null) : outgoing.close();
return Futures.allAsList(inClosed, outClosed);
}
/**
* Enqueue messages to be sent.
*
* @param messages messages to send
*/
public void sendMessages(Collection<? extends StreamMessage> messages)
{
for (StreamMessage message : messages)
sendMessage(message);
}
public void sendMessage(StreamMessage message)
{
if (outgoing.isClosed())
throw new RuntimeException("Outgoing stream handler has been closed");
outgoing.enqueue(message);
}
/**
* @return true if outgoing connection is opened and ready to send messages
*/
public boolean isOutgoingConnected()
{
return outgoing != null && !outgoing.isClosed();
}
#endif
public:
class message_handler {
protected:
stream_session& session;
int protocol_version;
message_handler(stream_session& session_) : session(session_) {
}
#if 0
protected Socket socket;
private final AtomicReference<SettableFuture<?>> closeFuture = new AtomicReference<>();
protected abstract String name();
protected static DataOutputStreamAndChannel getWriteChannel(Socket socket) throws IOException
{
WritableByteChannel out = socket.getChannel();
// socket channel is null when encrypted(SSL)
if (out == null)
out = Channels.newChannel(socket.getOutputStream());
return new DataOutputStreamAndChannel(socket.getOutputStream(), out);
}
protected static ReadableByteChannel getReadChannel(Socket socket) throws IOException
{
ReadableByteChannel in = socket.getChannel();
// socket channel is null when encrypted(SSL)
return in == null
? Channels.newChannel(socket.getInputStream())
: in;
}
public void sendInitMessage(Socket socket, boolean isForOutgoing) throws IOException
{
StreamInitMessage message = new StreamInitMessage(
FBUtilities.getBroadcastAddress(),
session.sessionIndex(),
session.planId(),
session.description(),
isForOutgoing,
session.keepSSTableLevel());
ByteBuffer messageBuf = message.createMessage(false, protocolVersion);
getWriteChannel(socket).write(messageBuf);
}
public void start(Socket socket, int protocolVersion)
{
this.socket = socket;
this.protocolVersion = protocolVersion;
new Thread(this, name() + "-" + session.peer).start();
}
public ListenableFuture<?> close()
{
// Assume it wasn't closed. Not a huge deal if we create a future on a race
SettableFuture<?> future = SettableFuture.create();
return closeFuture.compareAndSet(null, future)
? future
: closeFuture.get();
}
public boolean isClosed()
{
return closeFuture.get() != null;
}
protected void signalCloseDone()
{
closeFuture.get().set(null);
// We can now close the socket
try
{
socket.close();
}
catch (IOException ignore) {}
}
#endif
};
/**
* Incoming streaming message handler
*/
class incoming_message_handler : public message_handler {
public:
incoming_message_handler(stream_session& session) : message_handler(session) {
}
sstring name() {
return "STREAM-IN";
}
#if 0
public void run()
{
try
{
ReadableByteChannel in = getReadChannel(socket);
while (!isClosed())
{
// receive message
StreamMessage message = StreamMessage.deserialize(in, protocolVersion, session);
// Might be null if there is an error during streaming (see FileMessage.deserialize). It's ok
// to ignore here since we'll have asked for a retry.
if (message != null)
{
logger.debug("[Stream #{}] Received {}", session.planId(), message);
session.messageReceived(message);
}
}
}
catch (SocketException e)
{
// socket is closed
close();
}
catch (Throwable t)
{
JVMStabilityInspector.inspectThrowable(t);
session.onError(t);
}
finally
{
signalCloseDone();
}
}
#endif
};
/**
* Outgoing file transfer thread
*/
class outgoing_message_handler : public message_handler {
public:
outgoing_message_handler(stream_session& session) : message_handler(session) {
}
sstring name() {
return "STREAM-OUT";
}
#if 0
/*
* All out going messages are queued up into messageQueue.
* The size will grow when received streaming request.
*
* Queue is also PriorityQueue so that prior messages can go out fast.
*/
private final PriorityBlockingQueue<StreamMessage> messageQueue = new PriorityBlockingQueue<>(64, new Comparator<StreamMessage>()
{
public int compare(StreamMessage o1, StreamMessage o2)
{
return o2.getPriority() - o1.getPriority();
}
});
public void enqueue(StreamMessage message)
{
messageQueue.put(message);
}
public void run()
{
try
{
DataOutputStreamAndChannel out = getWriteChannel(socket);
StreamMessage next;
while (!isClosed())
{
if ((next = messageQueue.poll(1, TimeUnit.SECONDS)) != null)
{
logger.debug("[Stream #{}] Sending {}", session.planId(), next);
sendMessage(out, next);
if (next.type == StreamMessage.Type.SESSION_FAILED)
close();
}
}
// Sends the last messages on the queue
while ((next = messageQueue.poll()) != null)
sendMessage(out, next);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
catch (Throwable e)
{
session.onError(e);
}
finally
{
signalCloseDone();
}
}
private void sendMessage(DataOutputStreamAndChannel out, StreamMessage message)
{
try
{
StreamMessage.serialize(message, out, protocolVersion, session);
}
catch (SocketException e)
{
session.onError(e);
close();
}
catch (IOException e)
{
session.onError(e);
}
}
#endif
};
private:
stream_session& _session;
incoming_message_handler _incoming;
outgoing_message_handler _outgoing;
};
} // namespace streaming
|
Reduce dependency to stream_session in connection_handler
|
streaming: Reduce dependency to stream_session in connection_handler
|
C++
|
agpl-3.0
|
eklitzke/scylla,bowlofstew/scylla,victorbriz/scylla,tempbottle/scylla,justintung/scylla,aruanruan/scylla,raphaelsc/scylla,rluta/scylla,asias/scylla,rluta/scylla,kjniemi/scylla,gwicke/scylla,scylladb/scylla,justintung/scylla,avikivity/scylla,rentongzhang/scylla,senseb/scylla,dwdm/scylla,glommer/scylla,respu/scylla,kangkot/scylla,wildinto/scylla,linearregression/scylla,duarten/scylla,senseb/scylla,tempbottle/scylla,bowlofstew/scylla,avikivity/scylla,victorbriz/scylla,capturePointer/scylla,wildinto/scylla,respu/scylla,phonkee/scylla,duarten/scylla,rentongzhang/scylla,gwicke/scylla,guiquanz/scylla,stamhe/scylla,kjniemi/scylla,duarten/scylla,shaunstanislaus/scylla,senseb/scylla,guiquanz/scylla,victorbriz/scylla,shaunstanislaus/scylla,asias/scylla,avikivity/scylla,linearregression/scylla,aruanruan/scylla,scylladb/scylla,glommer/scylla,phonkee/scylla,stamhe/scylla,respu/scylla,eklitzke/scylla,phonkee/scylla,scylladb/scylla,guiquanz/scylla,dwdm/scylla,stamhe/scylla,rluta/scylla,raphaelsc/scylla,eklitzke/scylla,wildinto/scylla,asias/scylla,justintung/scylla,glommer/scylla,rentongzhang/scylla,acbellini/scylla,gwicke/scylla,raphaelsc/scylla,bowlofstew/scylla,linearregression/scylla,capturePointer/scylla,kangkot/scylla,capturePointer/scylla,dwdm/scylla,aruanruan/scylla,tempbottle/scylla,acbellini/scylla,kjniemi/scylla,kangkot/scylla,shaunstanislaus/scylla,scylladb/scylla,acbellini/scylla
|
4c3ff8147910d453223753ab144177c639dd278a
|
src/AudioEffectDelay_f32.cpp
|
src/AudioEffectDelay_f32.cpp
|
/* Audio Library for Teensy 3.X
* Copyright (c) 2014, Paul Stoffregen, [email protected]
* Extended by Chip Audette, Open Audio, April 2018
*
* Development of this audio library was funded by PJRC.COM, LLC by sales of
* Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
* open source software by purchasing Teensy or other PJRC products.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice, development funding notice, and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <Arduino.h>
#include "AudioEffectDelay_f32.h"
void AudioEffectDelay_F32::update(void)
{
audio_block_f32_t *input = receiveReadOnly_f32();
if (input == NULL) return; //no input data is available
audio_block_f32_t *all_output[8];
for (int channel=0; channel<8; channel++) { //loop over the different amounts of delay that might be requested
if (!(activemask & (1<<channel))) continue;
all_output[channel] = allocate_f32();
if (!all_output[channel]) continue;
}
//do the acutal processing
processData(input,all_output);
// transmit and release
AudioStream_F32::release(input); //release the block that was already successfully aquired
//const int delay_channel = 0;
for (int channel=0; channel<8; channel++) { //loop over the different amounts of delay that might be requested
if (all_output[channel] != NULL) {
AudioStream_F32::transmit(all_output[channel], channel);
AudioStream_F32::release(all_output[channel]);
}
}
return;
}
void AudioEffectDelay_F32::processData(audio_block_f32_t *input, audio_block_f32_t *output) {
receiveIncomingData(input); //put the in-coming audio data into the queue
discardUnneededBlocksFromQueue(); //clear out queued data this is no longer needed
audio_block_f32_t *all_output[8];
for (int i=0; i<8;i++) all_output[i] = NULL; //initialize to NULL
all_output[0] = output;
transmitOutgoingData(all_output); //put the queued data into the output
}
void AudioEffectDelay_F32::processData(audio_block_f32_t *input, audio_block_f32_t *all_output[8]) {
receiveIncomingData(input); //put the in-coming audio data into the queue
discardUnneededBlocksFromQueue(); //clear out queued data this is no longer needed
transmitOutgoingData(all_output); //put the queued data into the output
}
void AudioEffectDelay_F32::receiveIncomingData(audio_block_f32_t *input) {
//Serial.println("AudioEffectDelay_F32::receiveIncomingData: starting...");
//prepare the receiving queue
uint16_t head = headindex; //what block to write to
uint16_t tail = tailindex; //what block to read from
if (queue[head] == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Allocating queue[head].");
queue[head] = allocate_f32();
if (queue[head] == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 1. Returning.");
return;
}
}
//prepare target memory into which we'll copy the incoming data into the queue
int dest_ind = writeposition; //inclusive
if (dest_ind >= (queue[head]->full_length)) {
head++; dest_ind = 0;
if (head >= DELAY_QUEUE_SIZE_F32) head = 0;
if (queue[head] != NULL) {
if (head==tail) {tail++; if (tail >= DELAY_QUEUE_SIZE_F32) tail = 0; }
AudioStream_F32::release(queue[head]);
queue[head]=NULL;
}
}
if (queue[head]==NULL) {
queue[head] = allocate_f32();
if (queue[head] == NULL) {
if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 2. Returning.");
return;
}
}
//receive the in-coming audio data block
//audio_block_f32_t *input = receiveReadOnly_f32();
if (input == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Input data is NULL. Returning.");
return;
}
int n_copy = input->length;
last_received_block_id = input->id;
// Now we'll loop over the individual samples of the in-coming data
float32_t *dest = queue[head]->data;
float32_t *source = input->data;
int end_write = dest_ind + n_copy; //this may go past the end of the destination array
int end_loop = min(end_write,(int)(queue[head]->full_length)); //limit to the end of the array
int src_count=0, dest_count=dest_ind;
for (int i=dest_ind; i<end_loop; i++) dest[dest_count++] = source[src_count++];
//finish writing taking data from the next queue buffer
if (src_count < n_copy) { // there's still more input data to copy...but we need to roll-over to a new input queue
head++; dest_ind = 0;
if (head >= DELAY_QUEUE_SIZE_F32) head = 0;
if (queue[head] != NULL) {
if (head==tail) {tail++; if (tail >= DELAY_QUEUE_SIZE_F32) tail = 0; }
AudioStream_F32::release(queue[head]);
queue[head]=NULL;
}
if (queue[head]==NULL) {
queue[head] = allocate_f32();
if (queue[head] == NULL) {
Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 3. Returning.");
//AudioStream_F32::release(input);
return;
}
}
float32_t *dest = queue[head]->data;
end_loop = end_write - (queue[head]->full_length);
dest_count = dest_ind;
for (int i=dest_ind; i < end_loop; i++) dest[dest_count++]=source[src_count++];
}
//AudioStream_F32::release(input);
writeposition = dest_count;
headindex = head;
tailindex = tail;
return;
}
void AudioEffectDelay_F32::discardUnneededBlocksFromQueue(void) {
uint16_t head = headindex; //what block to write to
uint16_t tail = tailindex; //last useful block of data
uint32_t count;
// discard unneeded blocks from the queue
if (head >= tail) {
count = head - tail;
} else {
count = DELAY_QUEUE_SIZE_F32 + head - tail;
}
/* if (head>0) {
Serial.print("AudioEffectDelay_F32::discardUnneededBlocksFromQueue: head, tail, count, maxblocks, DELAY_QUEUE_SIZE_F32: ");
Serial.print(head); Serial.print(", ");
Serial.print(tail); Serial.print(", ");
Serial.print(count); Serial.print(", ");
Serial.print(maxblocks); Serial.print(", ");
Serial.print(DELAY_QUEUE_SIZE_F32); Serial.print(", ");
Serial.println();
} */
if (count > maxblocks) {
count -= maxblocks;
do {
if (queue[tail] != NULL) {
AudioStream_F32::release(queue[tail]);
queue[tail] = NULL;
}
if (++tail >= DELAY_QUEUE_SIZE_F32) tail = 0;
} while (--count > 0);
}
tailindex = tail;
}
void AudioEffectDelay_F32::transmitOutgoingData(audio_block_f32_t *all_output[8]) {
uint16_t head = headindex; //what block to write to
//uint16_t tail = tailindex; //last useful block of data
audio_block_f32_t *output;
int channel; //, index, prev, offset;
//const float32_t *src, *end;
//float32_t *dst;
// transmit the delayed outputs using queue data
for (channel = 0; channel < 8; channel++) {
if (!(activemask & (1<<channel))) continue;
//output = allocate_f32();
output = all_output[channel];
if (!output) continue;
//figure out where to start pulling the data samples from
uint32_t ref_samp_long = (head*AUDIO_BLOCK_SIZE_F32) + writeposition; //note that writepoisition has already been
//incremented by the block length by the
//receiveIncomingData method. We'll adjust it next
uint32_t offset_samp = delay_samps[channel]+output->length;
if (ref_samp_long < offset_samp) { //when (ref_samp_long - offset_samp) goes negative, the uint32_t will fail, so we do this logic check
ref_samp_long = ref_samp_long + (((uint32_t)(DELAY_QUEUE_SIZE_F32))*((uint32_t)AUDIO_BLOCK_SIZE_F32));
}
ref_samp_long = ref_samp_long - offset_samp;
uint16_t source_queue_ind = (uint16_t)(ref_samp_long / ((uint32_t)AUDIO_BLOCK_SIZE_F32));
int source_samp = (int)(ref_samp_long - (((uint32_t)source_queue_ind)*((uint32_t)AUDIO_BLOCK_SIZE_F32)));
//pull the data from the first source data block
int dest_counter=0;
int n_output = output->length;
float32_t *dest = output->data;
audio_block_f32_t *source_block = queue[source_queue_ind];
if (source_block == NULL) {
//fill destination with zeros for this source block
int Iend = min(source_samp+n_output,AUDIO_BLOCK_SIZE_F32);
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=0.0;
}
} else {
//fill destination with this source block's values
float32_t *source = source_block->data;
int Iend = min(source_samp+n_output,AUDIO_BLOCK_SIZE_F32);
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=source[Isource];
}
}
//pull the data from the second source data block, if needed
if (dest_counter < n_output) {
//yes, we need to keep filling the output
int Iend = n_output - dest_counter; //how many more data points do we need
source_queue_ind++; source_samp = 0; //which source block will we draw from (and reset the source sample counter)
if (source_queue_ind >= DELAY_QUEUE_SIZE_F32) source_queue_ind = 0; //wrap around on our source black.
source_block = queue[source_queue_ind]; //get the source block
if (source_block == NULL) { //does it have data?
//no, it doesn't have data. fill destination with zeros
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++] = 0.0;
}
} else {
//source block does have data. use this block's values
float32_t *source = source_block->data;
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=source[Isource];
}
}
}
//add the id of the last received audio block
output->id = last_received_block_id;
//transmit and release
//AudioStream_F32::transmit(output, channel);
//AudioStream_F32::release(output);
}
}
|
/* Audio Library for Teensy 3.X
* Copyright (c) 2014, Paul Stoffregen, [email protected]
* Extended by Chip Audette, Open Audio, April 2018
*
* Development of this audio library was funded by PJRC.COM, LLC by sales of
* Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
* open source software by purchasing Teensy or other PJRC products.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice, development funding notice, and this permission
* notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <Arduino.h>
#include "AudioEffectDelay_f32.h"
void AudioEffectDelay_F32::update(void)
{
audio_block_f32_t *input = receiveReadOnly_f32();
if (input == NULL) return; //no input data is available
audio_block_f32_t *all_output[8];
for (int channel=0; channel<8; channel++) { //loop over the different amounts of delay that might be requested
//if (!(activemask & (1<<channel))) continue;
all_output[channel] = allocate_f32();
//if (!all_output[channel]) continue;
}
//do the acutal processing
processData(input,all_output);
// transmit and release
AudioStream_F32::release(input); //release the block that was already successfully aquired
//const int delay_channel = 0;
for (int channel=0; channel<8; channel++) { //loop over the different amounts of delay that might be requested
if (all_output[channel] != NULL) {
AudioStream_F32::transmit(all_output[channel], channel);
AudioStream_F32::release(all_output[channel]);
}
}
return;
}
void AudioEffectDelay_F32::processData(audio_block_f32_t *input, audio_block_f32_t *output) {
receiveIncomingData(input); //put the in-coming audio data into the queue
discardUnneededBlocksFromQueue(); //clear out queued data this is no longer needed
audio_block_f32_t *all_output[8];
for (int i=0; i<8;i++) all_output[i] = NULL; //initialize to NULL
all_output[0] = output;
transmitOutgoingData(all_output); //put the queued data into the output
}
void AudioEffectDelay_F32::processData(audio_block_f32_t *input, audio_block_f32_t *all_output[8]) {
receiveIncomingData(input); //put the in-coming audio data into the queue
discardUnneededBlocksFromQueue(); //clear out queued data this is no longer needed
transmitOutgoingData(all_output); //put the queued data into the output
}
void AudioEffectDelay_F32::receiveIncomingData(audio_block_f32_t *input) {
//Serial.println("AudioEffectDelay_F32::receiveIncomingData: starting...");
//prepare the receiving queue
uint16_t head = headindex; //what block to write to
uint16_t tail = tailindex; //what block to read from
if (queue[head] == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Allocating queue[head].");
queue[head] = allocate_f32();
if (queue[head] == NULL) {
if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 1. Returning.");
return;
}
}
//prepare target memory into which we'll copy the incoming data into the queue
int dest_ind = writeposition; //inclusive
if (dest_ind >= (queue[head]->full_length)) {
head++; dest_ind = 0;
if (head >= DELAY_QUEUE_SIZE_F32) head = 0;
if (queue[head] != NULL) {
if (head==tail) {tail++; if (tail >= DELAY_QUEUE_SIZE_F32) tail = 0; }
AudioStream_F32::release(queue[head]);
queue[head]=NULL;
}
}
if (queue[head]==NULL) {
queue[head] = allocate_f32();
if (queue[head] == NULL) {
if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 2. Returning.");
return;
}
}
//receive the in-coming audio data block
//audio_block_f32_t *input = receiveReadOnly_f32();
if (input == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Input data is NULL. Returning.");
return;
}
int n_copy = input->length;
last_received_block_id = input->id;
// Now we'll loop over the individual samples of the in-coming data
float32_t *dest = queue[head]->data;
float32_t *source = input->data;
int end_write = dest_ind + n_copy; //this may go past the end of the destination array
int end_loop = min(end_write,(int)(queue[head]->full_length)); //limit to the end of the array
int src_count=0, dest_count=dest_ind;
for (int i=dest_ind; i<end_loop; i++) dest[dest_count++] = source[src_count++];
//finish writing taking data from the next queue buffer
if (src_count < n_copy) { // there's still more input data to copy...but we need to roll-over to a new input queue
head++; dest_ind = 0;
if (head >= DELAY_QUEUE_SIZE_F32) head = 0;
if (queue[head] != NULL) {
if (head==tail) {tail++; if (tail >= DELAY_QUEUE_SIZE_F32) tail = 0; }
AudioStream_F32::release(queue[head]);
queue[head]=NULL;
}
if (queue[head]==NULL) {
queue[head] = allocate_f32();
if (queue[head] == NULL) {
Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 3. Returning.");
//AudioStream_F32::release(input);
return;
}
}
float32_t *dest = queue[head]->data;
end_loop = end_write - (queue[head]->full_length);
dest_count = dest_ind;
for (int i=dest_ind; i < end_loop; i++) dest[dest_count++]=source[src_count++];
}
//AudioStream_F32::release(input);
writeposition = dest_count;
headindex = head;
tailindex = tail;
return;
}
void AudioEffectDelay_F32::discardUnneededBlocksFromQueue(void) {
uint16_t head = headindex; //what block to write to
uint16_t tail = tailindex; //last useful block of data
uint32_t count;
// discard unneeded blocks from the queue
if (head >= tail) {
count = head - tail;
} else {
count = DELAY_QUEUE_SIZE_F32 + head - tail;
}
/* if (head>0) {
Serial.print("AudioEffectDelay_F32::discardUnneededBlocksFromQueue: head, tail, count, maxblocks, DELAY_QUEUE_SIZE_F32: ");
Serial.print(head); Serial.print(", ");
Serial.print(tail); Serial.print(", ");
Serial.print(count); Serial.print(", ");
Serial.print(maxblocks); Serial.print(", ");
Serial.print(DELAY_QUEUE_SIZE_F32); Serial.print(", ");
Serial.println();
} */
if (count > maxblocks) {
count -= maxblocks;
do {
if (queue[tail] != NULL) {
AudioStream_F32::release(queue[tail]);
queue[tail] = NULL;
}
if (++tail >= DELAY_QUEUE_SIZE_F32) tail = 0;
} while (--count > 0);
}
tailindex = tail;
}
void AudioEffectDelay_F32::transmitOutgoingData(audio_block_f32_t *all_output[8]) {
uint16_t head = headindex; //what block to write to
//uint16_t tail = tailindex; //last useful block of data
audio_block_f32_t *output;
int channel; //, index, prev, offset;
//const float32_t *src, *end;
//float32_t *dst;
// transmit the delayed outputs using queue data
for (channel = 0; channel < 8; channel++) {
if (!(activemask & (1<<channel))) continue;
//output = allocate_f32();
output = all_output[channel];
if (!output) continue;
//figure out where to start pulling the data samples from
uint32_t ref_samp_long = (head*AUDIO_BLOCK_SIZE_F32) + writeposition; //note that writepoisition has already been
//incremented by the block length by the
//receiveIncomingData method. We'll adjust it next
uint32_t offset_samp = delay_samps[channel]+output->length;
if (ref_samp_long < offset_samp) { //when (ref_samp_long - offset_samp) goes negative, the uint32_t will fail, so we do this logic check
ref_samp_long = ref_samp_long + (((uint32_t)(DELAY_QUEUE_SIZE_F32))*((uint32_t)AUDIO_BLOCK_SIZE_F32));
}
ref_samp_long = ref_samp_long - offset_samp;
uint16_t source_queue_ind = (uint16_t)(ref_samp_long / ((uint32_t)AUDIO_BLOCK_SIZE_F32));
int source_samp = (int)(ref_samp_long - (((uint32_t)source_queue_ind)*((uint32_t)AUDIO_BLOCK_SIZE_F32)));
//pull the data from the first source data block
int dest_counter=0;
int n_output = output->length;
float32_t *dest = output->data;
audio_block_f32_t *source_block = queue[source_queue_ind];
if (source_block == NULL) {
//fill destination with zeros for this source block
int Iend = min(source_samp+n_output,AUDIO_BLOCK_SIZE_F32);
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=0.0;
}
} else {
//fill destination with this source block's values
float32_t *source = source_block->data;
int Iend = min(source_samp+n_output,AUDIO_BLOCK_SIZE_F32);
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=source[Isource];
}
}
//pull the data from the second source data block, if needed
if (dest_counter < n_output) {
//yes, we need to keep filling the output
int Iend = n_output - dest_counter; //how many more data points do we need
source_queue_ind++; source_samp = 0; //which source block will we draw from (and reset the source sample counter)
if (source_queue_ind >= DELAY_QUEUE_SIZE_F32) source_queue_ind = 0; //wrap around on our source black.
source_block = queue[source_queue_ind]; //get the source block
if (source_block == NULL) { //does it have data?
//no, it doesn't have data. fill destination with zeros
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++] = 0.0;
}
} else {
//source block does have data. use this block's values
float32_t *source = source_block->data;
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=source[Isource];
}
}
}
//add the id of the last received audio block
output->id = last_received_block_id;
//transmit and release
//AudioStream_F32::transmit(output, channel);
//AudioStream_F32::release(output);
}
}
|
fix memory leak, though ends up using more memory than needed
|
AudioEffectDelay_f32: fix memory leak, though ends up using more memory than needed
|
C++
|
mit
|
Tympan/Tympan_Library,Tympan/Tympan_Library,Tympan/Tympan_Library
|
0a7a7cb48c2db0835c5fc1885d1c9c69970d6093
|
Cplusplus/mexendo-com-arquivos/OUTLINE-abrir-arquivo-em-modo-saida-acrescimo.cpp
|
Cplusplus/mexendo-com-arquivos/OUTLINE-abrir-arquivo-em-modo-saida-acrescimo.cpp
|
#include <fstream>
using namespace std;
const char* NomeArquivo = "exemplo.txt";
main(){
ofstream outline(NomeArquivo, ios::out); // cria ou abre aruivo em modo saida / acrescimo
}
|
#include <fstream>
using namespace std;
const char* NomeArquivo = "exemplo.txt";
main(){
ofstream outline(NomeArquivo, ios::out); // cria ou abre aruivo em modo saida / acrescimo
/*
Você usa a constante de enumeração ios::out para abrir o arquivo no modo de saída. Para abrir o arquivo no modo de acréscimo, use o ios::app.
*/
}
|
Update OUTLINE-abrir-arquivo-em-modo-saida-acrescimo.cpp
|
Update OUTLINE-abrir-arquivo-em-modo-saida-acrescimo.cpp
|
C++
|
mit
|
carlosvilela/Funcoes-Diversas,carlosvilela/Funcoes-Diversas,carlosvilela/Funcoes-Diversas,carlosvilela/Funcoes-Diversas,carlosvilela/Funcoes-Diversas
|
5199024f68e61e9cdd1707c243e6052b6a0a0a34
|
modules/video_capture/external/device_info_external.cc
|
modules/video_capture/external/device_info_external.cc
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_capture/android/device_info_impl.h"
#include "webrtc/modules/video_capture/android/video_capture_impl.h"
namespace webrtc {
namespace videocapturemodule {
class ExternalDeviceInfo : public DeviceInfoImpl {
public:
ExternalDeviceInfo(const int32_t id)
: DeviceInfoImpl(id) {
}
virtual ~ExternalDeviceInfo() {}
virtual uint32_t NumberOfDevices() { return 0; }
virtual int32_t DisplayCaptureSettingsDialogBox(
const char* /*deviceUniqueIdUTF8*/,
const char* /*dialogTitleUTF8*/,
void* /*parentWindow*/,
uint32_t /*positionX*/,
uint32_t /*positionY*/) { return -1; }
virtual int32_t GetDeviceName(
uint32_t deviceNumber,
char* deviceNameUTF8,
uint32_t deviceNameLength,
char* deviceUniqueIdUTF8,
uint32_t deviceUniqueIdUTF8Length,
char* productUniqueIdUTF8=0,
uint32_t productUniqueIdUTF8Length=0) {
return -1;
}
virtual int32_t CreateCapabilityMap(
const char* deviceUniqueIdUTF8) { return 0; }
virtual int32_t Init() { return 0; }
};
VideoCaptureModule::DeviceInfo* VideoCaptureImpl::CreateDeviceInfo(
const int32_t id) {
return new ExternalDeviceInfo(id);
}
} // namespace videocapturemodule
} // namespace webrtc
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_capture/device_info_impl.h"
#include "webrtc/modules/video_capture/video_capture_impl.h"
namespace webrtc {
namespace videocapturemodule {
class ExternalDeviceInfo : public DeviceInfoImpl {
public:
ExternalDeviceInfo(const int32_t id)
: DeviceInfoImpl(id) {
}
virtual ~ExternalDeviceInfo() {}
virtual uint32_t NumberOfDevices() { return 0; }
virtual int32_t DisplayCaptureSettingsDialogBox(
const char* /*deviceUniqueIdUTF8*/,
const char* /*dialogTitleUTF8*/,
void* /*parentWindow*/,
uint32_t /*positionX*/,
uint32_t /*positionY*/) { return -1; }
virtual int32_t GetDeviceName(
uint32_t deviceNumber,
char* deviceNameUTF8,
uint32_t deviceNameLength,
char* deviceUniqueIdUTF8,
uint32_t deviceUniqueIdUTF8Length,
char* productUniqueIdUTF8=0,
uint32_t productUniqueIdUTF8Length=0) {
return -1;
}
virtual int32_t CreateCapabilityMap(
const char* deviceUniqueIdUTF8) { return 0; }
virtual int32_t Init() { return 0; }
};
VideoCaptureModule::DeviceInfo* VideoCaptureImpl::CreateDeviceInfo(
const int32_t id) {
return new ExternalDeviceInfo(id);
}
} // namespace videocapturemodule
} // namespace webrtc
|
Update include paths in device_info_external.cc
|
Update include paths in device_info_external.cc
[email protected]
Review URL: https://webrtc-codereview.appspot.com/1875004
git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@4401 4adac7df-926f-26a2-2b94-8c16560cd09d
|
C++
|
bsd-3-clause
|
AOSPU/external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,svn2github/webrtc-Revision-8758,Alkalyne/webrtctrunk,Omegaphora/external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,PersonifyInc/chromium_webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,jchavanton/webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,jchavanton/webrtc,bpsinc-native/src_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,AOSPU/external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,AOSPU/external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,CyanogenMod/android_external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,MIPS/external-chromium_org-third_party-webrtc,AOSPU/external_chromium_org_third_party_webrtc,jchavanton/webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,sippet/webrtc,svn2github/webrtc-Revision-8758,jgcaaprom/android_external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,Alkalyne/webrtctrunk,sippet/webrtc,krieger-od/webrtc,Alkalyne/webrtctrunk,android-ia/platform_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,krieger-od/nwjs_chromium_webrtc,aleonliao/webrtc-trunk,android-ia/platform_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,jchavanton/webrtc,AOSPU/external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,jchavanton/webrtc,svn2github/webrtc-Revision-8758,krieger-od/webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,sippet/webrtc,bpsinc-native/src_third_party_webrtc,aleonliao/webrtc-trunk,xin3liang/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,krieger-od/webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,MIPS/external-chromium_org-third_party-webrtc,sippet/webrtc,MIPS/external-chromium_org-third_party-webrtc,MIPS/external-chromium_org-third_party-webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,xin3liang/platform_external_chromium_org_third_party_webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,sippet/webrtc,PersonifyInc/chromium_webrtc,AOSPU/external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,PersonifyInc/chromium_webrtc,krieger-od/nwjs_chromium_webrtc,krieger-od/webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,Omegaphora/external_chromium_org_third_party_webrtc,SlimXperiments/external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,Omegaphora/external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,bpsinc-native/src_third_party_webrtc,PersonifyInc/chromium_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jchavanton/webrtc,MIPS/external-chromium_org-third_party-webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,krieger-od/webrtc,krieger-od/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,aleonliao/webrtc-trunk,xin3liang/platform_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,sippet/webrtc,bpsinc-native/src_third_party_webrtc,jchavanton/webrtc,svn2github/webrtc-Revision-8758,AOSPU/external_chromium_org_third_party_webrtc
|
196cb42b69d8dd013c25ad3b341eb2a86f57addc
|
PhysicsInitiation/PhysicsInitiation/main.cpp
|
PhysicsInitiation/PhysicsInitiation/main.cpp
|
#include "glew\glew.h"
#include "freeglut\freeglut.h"
#include "glm\glm\glm.hpp"
#include "glm\glm\gtc\matrix_transform.hpp"
#include "Shader_Manager.h"
#include "btBulletDynamicsCommon.h"
#include <iostream>
using namespace std;
using namespace Managers;
using glm::vec3;
using glm::mat4;
int width = 1024;
int height = 768;
int mousePositionx;
int mousePositiony;
float rotate_x = 0;
float rotate_y = 0;
GLint programID;
GLfloat vertexDataforIndex[] = {
// X Y Z U V R G B
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
};
GLuint indexData[] = {
0, 1, 2, 1, 2, 3, 4, 5, 6, 5, 6, 7, 1, 5, 7, 1, 7, 3, 0, 4, 6, 0, 6, 2, 2, 3, 7, 2, 7, 6, 0, 1, 5, 0, 5, 4
};
float Vertices[9] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f };
GLfloat uParticle[] = {
// X Y Z U V R G B
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f
};
Shader_Manager shaderManager;
//Particle particle;
GLuint VBO;
GLuint indexBuffer;
void RenderSceneCB();
void installShaders();
void specialKeys(int, int, int);
void MouseMotion(int, int);
void Timer(int);
// Global Bullet objects
btRigidBody* fallRigidBody;
btRigidBody* fallRigidBody2;
btDiscreteDynamicsWorld* dynamicsWorld;
void main(int argc, char** argv)
{
//OPENGL initialization =============================================
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE | GL_MULTISAMPLE);
glutInitWindowSize(width, height);
glutInitWindowPosition(700, 100);
glutCreateWindow("CubeTry");
glutDisplayFunc(RenderSceneCB);
//glutIdleFunc(RenderSceneCB); // Calls the function as many times as it can
glutSpecialFunc(specialKeys);
glutTimerFunc(10, Timer, 0);
glutPassiveMotionFunc(MouseMotion);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glewExperimental = GL_TRUE;
glewInit();
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//glBufferData(GL_ARRAY_BUFFER, sizeof(vertexDataforIndex), vertexDataforIndex, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(uParticle), uParticle, GL_STATIC_DRAW);
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * 2 * 3 * sizeof(GLuint), &indexData[0], GL_STATIC_DRAW);
cout << "OpenGL Version: " << (char*)glGetString(GL_VERSION) << " | Shader Language Version: " << (char*)glGetString(GL_SHADING_LANGUAGE_VERSION) << "| Glut Version : " << glutGet(GLUT_VERSION) << endl;
// Bullet Initialization and setup environment ================
btBroadphaseInterface* broadphase = new btDbvtBroadphase();
btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld->setGravity(btVector3(0, -9.8, 0));
//btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);
btCollisionShape* groundShape = new btBoxShape(btVector3(5, 5, 0));
btCollisionShape* fallShape = new btSphereShape(1);
btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
groundRigidBody->setRestitution(btScalar(1));
dynamicsWorld->addRigidBody(groundRigidBody);
btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0.1, 50, 0)));
btScalar mass = 1;
btVector3 fallInertia(0, 0, 0);
fallShape->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
fallRigidBodyCI.m_restitution = 0.8;
fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);
btDefaultMotionState* fallMotionState2 = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 5, 0)));
btScalar mass2 = 1;
btVector3 fallInertia2(0, 0, 0);
fallShape->calculateLocalInertia(mass2, fallInertia2);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI2(mass2, fallMotionState2, fallShape, fallInertia2);
fallRigidBodyCI2.m_restitution = 0;
fallRigidBody2 = new btRigidBody(fallRigidBodyCI2);
fallRigidBody2->setCollisionFlags(fallRigidBody2->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
fallRigidBody2->setActivationState(DISABLE_DEACTIVATION);
dynamicsWorld->addRigidBody(fallRigidBody2);
//=============================================================
installShaders();
glutMainLoop();
//== exit ====================================================
delete dynamicsWorld;
delete solver;
delete collisionConfiguration;
delete dispatcher;
delete broadphase;
}
void RenderSceneCB()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
btTransform trans;
float x = ((mousePositionx - width / 2) / (float)(width / 2))* 115.2;
float y = ((mousePositiony - height / 2) / (float)(height / 2))*-86.5;
y = y < 2 ? 2 : y;
fallRigidBody2->getMotionState()->getWorldTransform(trans);
trans.setOrigin(btVector3(x, y , 0));
fallRigidBody2->getMotionState()->setWorldTransform(trans);
dynamicsWorld->stepSimulation(1/30.f, 10000, 1/100.f);
fallRigidBody->getMotionState()->getWorldTransform(trans);
uParticle[0] = trans.getOrigin().getX() / 50;
uParticle[1] = trans.getOrigin().getY() / 50;
uParticle[2] = trans.getOrigin().getZ() / 50;
fallRigidBody2->getMotionState()->getWorldTransform(trans);
uParticle[8] = trans.getOrigin().getX() / 50;
uParticle[9] = trans.getOrigin().getY() / 50;
uParticle[10] = trans.getOrigin().getZ() / 50;
glBufferData(GL_ARRAY_BUFFER, sizeof(uParticle), uParticle, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
mat4 projectionMatrix = glm::perspective(glm::radians(60.0f), (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 View = glm::lookAt(
glm::vec3(rotate_x, rotate_y, 3), // Camera is at (4,3,3), in World Space
glm::vec3(0, 0, 0), // and looks at the origin
glm::vec3(0, 1, 0)); // Head is up (set to 0,-1,0 to look upside-down)
glm::mat4 mvp = projectionMatrix * View * Model;
//GLint modelTransformMatrixUniformLocation = glGetUniformLocation(programID, "modelTransdformMatrix");
//GLint projectionMatrixUniformLocation = glGetUniformLocation(programID, "projectionMatrix");
GLint mvpMatrixUniformLocation = glGetUniformLocation(programID, "mvpMatrix");
glUniformMatrix4fv(mvpMatrixUniformLocation, 1, GL_FALSE, &mvp[0][0]);
//glUniformMatrix4fv(projectionMatrixUniformLocation, 1, GL_FALSE, &projectionMatrix[0][0]);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(5 * sizeof(GLfloat)));
glEnable(GL_POINT_SMOOTH);
glPointSize(10);
glDrawArrays(GL_POINTS, 0, 2);
//glDrawElements(GL_TRIANGLES, 6 * 2 * 3, GL_UNSIGNED_INT, (void*)0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glutSwapBuffers();
//glutPostRedisplay();
}
void installShaders()
{
shaderManager.CreateProgram("greenColor", "VertexShader.glsl", "FragmentShader.glsl");
programID = shaderManager.GetShader("greenColor");
glUseProgram(programID);
}
void specialKeys(int key, int x, int y) {
// Right arrow - increase rotation by 5 degree
if (key == GLUT_KEY_RIGHT)
rotate_x += 0.1;
// Left arrow - decrease rotation by 5 degree
else if (key == GLUT_KEY_LEFT)
rotate_x -= 0.1;
else if (key == GLUT_KEY_UP)
rotate_y += 0.1;
else if (key == GLUT_KEY_DOWN)
rotate_y -= 0.1;
// Request display update
glutPostRedisplay();
}
void MouseMotion(int x, int y)
{
mousePositionx = x;
mousePositiony = y;
}
void Timer(int value)
{
glutPostRedisplay();
glutTimerFunc(10, Timer, 0);
}
|
#include "glew\glew.h"
#include "freeglut\freeglut.h"
#include "glm\glm\glm.hpp"
#include "glm\glm\gtc\matrix_transform.hpp"
#include "Shader_Manager.h"
#include "btBulletDynamicsCommon.h"
#include <iostream>
using namespace std;
using namespace Managers;
using glm::vec3;
using glm::mat4;
int width = 1024;
int height = 768;
int mousePositionx;
int mousePositiony;
float rotate_x = 0;
float rotate_y = 0;
GLint programID;
GLfloat vertexDataforIndex[] = {
// X Y Z U V R G B
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
};
GLuint indexData[] = {
0, 1, 2, 1, 2, 3, 4, 5, 6, 5, 6, 7, 1, 5, 7, 1, 7, 3, 0, 4, 6, 0, 6, 2, 2, 3, 7, 2, 7, 6, 0, 1, 5, 0, 5, 4
};
float Vertices[9] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f };
GLfloat uParticle[] = {
// X Y Z U V R G B
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f
};
Shader_Manager shaderManager;
//Particle particle;
GLuint VBO;
GLuint indexBuffer;
void RenderSceneCB();
void installShaders();
void specialKeys(int, int, int);
void MouseMotion(int, int);
void Timer(int);
// Global Bullet objects
btRigidBody* fallRigidBody;
btRigidBody* fallRigidBody2;
btDiscreteDynamicsWorld* dynamicsWorld;
void main(int argc, char** argv)
{
//OPENGL initialization =============================================
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE | GL_MULTISAMPLE);
glutInitWindowSize(width, height);
glutInitWindowPosition(700, 100);
glutCreateWindow("CubeTry");
glutDisplayFunc(RenderSceneCB);
//glutIdleFunc(RenderSceneCB); // Calls the function as many times as it can
glutSpecialFunc(specialKeys);
glutTimerFunc(10, Timer, 0);
glutPassiveMotionFunc(MouseMotion);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glewExperimental = GL_TRUE;
glewInit();
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//glBufferData(GL_ARRAY_BUFFER, sizeof(vertexDataforIndex), vertexDataforIndex, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(uParticle), uParticle, GL_STATIC_DRAW);
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * 2 * 3 * sizeof(GLuint), &indexData[0], GL_STATIC_DRAW);
cout << "OpenGL Version: " << (char*)glGetString(GL_VERSION) << " | Shader Language Version: " << (char*)glGetString(GL_SHADING_LANGUAGE_VERSION) << "| Glut Version : " << glutGet(GLUT_VERSION) << endl;
// Bullet Initialization and setup environment ================
btBroadphaseInterface* broadphase = new btDbvtBroadphase();
btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld->setGravity(btVector3(0, -9.8, 0));
btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);
//btCollisionShape* groundShape = new btBoxShape(btVector3(0, 1, 0));
btCollisionShape* fallShape = new btSphereShape(1);
btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
groundRigidBody->setRestitution(btScalar(1));
dynamicsWorld->addRigidBody(groundRigidBody);
btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0)));
btScalar mass = 1;
btVector3 fallInertia(0, 0, 0);
fallShape->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
fallRigidBodyCI.m_restitution = 0.8;
fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);
btDefaultMotionState* fallMotionState2 = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 5, 0)));
btScalar mass2 = 1;
btVector3 fallInertia2(0, 0, 0);
fallShape->calculateLocalInertia(mass2, fallInertia2);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI2(mass2, fallMotionState2, fallShape, fallInertia2);
fallRigidBodyCI2.m_restitution = 0;
fallRigidBody2 = new btRigidBody(fallRigidBodyCI2);
fallRigidBody2->setCollisionFlags(fallRigidBody2->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
fallRigidBody2->setActivationState(DISABLE_DEACTIVATION);
dynamicsWorld->addRigidBody(fallRigidBody2);
//=============================================================
installShaders();
glutMainLoop();
//== exit ====================================================
delete dynamicsWorld;
delete solver;
delete collisionConfiguration;
delete dispatcher;
delete broadphase;
}
void RenderSceneCB()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
btTransform trans;
float x = ((mousePositionx - width / 2) / (float)(width / 2))* 115.2;
float y = ((mousePositiony - height / 2) / (float)(height / 2))*-86.5;
//y = y < 2 ? 2 : y;
fallRigidBody2->getMotionState()->getWorldTransform(trans);
trans.setOrigin(btVector3(x, y , 0));
fallRigidBody2->getMotionState()->setWorldTransform(trans);
dynamicsWorld->stepSimulation(1/30.f, 10000, 1/100.f);
fallRigidBody->getMotionState()->getWorldTransform(trans);
uParticle[0] = trans.getOrigin().getX() / 50;
uParticle[1] = trans.getOrigin().getY() / 50;
uParticle[2] = trans.getOrigin().getZ() / 50;
fallRigidBody2->getMotionState()->getWorldTransform(trans);
uParticle[8] = trans.getOrigin().getX() / 50;
uParticle[9] = trans.getOrigin().getY() / 50;
uParticle[10] = trans.getOrigin().getZ() / 50;
glBufferData(GL_ARRAY_BUFFER, sizeof(uParticle), uParticle, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
mat4 projectionMatrix = glm::perspective(glm::radians(60.0f), (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 View = glm::lookAt(
glm::vec3(rotate_x, rotate_y, 3), // Camera is at (4,3,3), in World Space
glm::vec3(0, 0, 0), // and looks at the origin
glm::vec3(0, 1, 0)); // Head is up (set to 0,-1,0 to look upside-down)
glm::mat4 mvp = projectionMatrix * View * Model;
//GLint modelTransformMatrixUniformLocation = glGetUniformLocation(programID, "modelTransdformMatrix");
//GLint projectionMatrixUniformLocation = glGetUniformLocation(programID, "projectionMatrix");
GLint mvpMatrixUniformLocation = glGetUniformLocation(programID, "mvpMatrix");
glUniformMatrix4fv(mvpMatrixUniformLocation, 1, GL_FALSE, &mvp[0][0]);
//glUniformMatrix4fv(projectionMatrixUniformLocation, 1, GL_FALSE, &projectionMatrix[0][0]);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(5 * sizeof(GLfloat)));
glEnable(GL_POINT_SMOOTH);
glPointSize(10);
glDrawArrays(GL_POINTS, 0, 2);
//glDrawElements(GL_TRIANGLES, 6 * 2 * 3, GL_UNSIGNED_INT, (void*)0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glutSwapBuffers();
//glutPostRedisplay();
}
void installShaders()
{
shaderManager.CreateProgram("greenColor", "VertexShader.glsl", "FragmentShader.glsl");
programID = shaderManager.GetShader("greenColor");
glUseProgram(programID);
}
void specialKeys(int key, int x, int y) {
// Right arrow - increase rotation by 5 degree
if (key == GLUT_KEY_RIGHT)
rotate_x += 0.1;
// Left arrow - decrease rotation by 5 degree
else if (key == GLUT_KEY_LEFT)
rotate_x -= 0.1;
else if (key == GLUT_KEY_UP)
rotate_y += 0.1;
else if (key == GLUT_KEY_DOWN)
rotate_y -= 0.1;
// Request display update
glutPostRedisplay();
}
void MouseMotion(int x, int y)
{
mousePositionx = x;
mousePositiony = y;
}
void Timer(int value)
{
glutPostRedisplay();
glutTimerFunc(10, Timer, 0);
}
|
Change in plane/box shape
|
Change in plane/box shape
|
C++
|
mit
|
igormacedo/bulletstudy,igormacedo/bulletstudy,igormacedo/bulletstudy,igormacedo/bulletstudy
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.