text
stringlengths 54
60.6k
|
---|
<commit_before>// 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 "base/scoped_temp_dir.h"
#include "base/scoped_vector.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
typedef testing::Test TemplateURLPrepopulateDataTest;
// Verifies the set of prepopulate data doesn't contain entries with duplicate
// ids.
TEST_F(TemplateURLPrepopulateDataTest, UniqueIDs) {
int ids[] = { 'A'<<8|'D', 'A'<<8|'E', 'A'<<8|'F', 'A'<<8|'G', 'A'<<8|'I',
'A'<<8|'L', 'A'<<8|'M', 'A'<<8|'N', 'A'<<8|'O', 'A'<<8|'Q',
'A'<<8|'R', 'A'<<8|'S', 'A'<<8|'T', 'A'<<8|'U', 'A'<<8|'W',
'A'<<8|'X', 'A'<<8|'Z', 'B'<<8|'A', 'B'<<8|'B', 'B'<<8|'D',
'B'<<8|'E', 'B'<<8|'F', 'B'<<8|'G', 'B'<<8|'H', 'B'<<8|'I',
'B'<<8|'J', 'B'<<8|'M', 'B'<<8|'N', 'B'<<8|'O', 'B'<<8|'R',
'B'<<8|'S', 'B'<<8|'T', 'B'<<8|'V', 'B'<<8|'W', 'B'<<8|'Y',
'B'<<8|'Z', 'C'<<8|'A', 'C'<<8|'C', 'C'<<8|'D', 'C'<<8|'F',
'C'<<8|'G', 'C'<<8|'H', 'C'<<8|'I', 'C'<<8|'K', 'C'<<8|'L',
'C'<<8|'M', 'C'<<8|'N', 'C'<<8|'O', 'C'<<8|'R', 'C'<<8|'U',
'C'<<8|'V', 'C'<<8|'X', 'C'<<8|'Y', 'C'<<8|'Z', 'D'<<8|'E',
'D'<<8|'J', 'D'<<8|'K', 'D'<<8|'M', 'D'<<8|'O', 'D'<<8|'Z',
'E'<<8|'C', 'E'<<8|'E', 'E'<<8|'G', 'E'<<8|'R', 'E'<<8|'S',
'E'<<8|'T', 'F'<<8|'I', 'F'<<8|'J', 'F'<<8|'K', 'F'<<8|'M',
'F'<<8|'O', 'F'<<8|'R', 'G'<<8|'A', 'G'<<8|'B', 'G'<<8|'D',
'G'<<8|'E', 'G'<<8|'F', 'G'<<8|'G', 'G'<<8|'H', 'G'<<8|'I',
'G'<<8|'L', 'G'<<8|'M', 'G'<<8|'N', 'G'<<8|'P', 'G'<<8|'Q',
'G'<<8|'R', 'G'<<8|'S', 'G'<<8|'T', 'G'<<8|'U', 'G'<<8|'W',
'G'<<8|'Y', 'H'<<8|'K', 'H'<<8|'M', 'H'<<8|'N', 'H'<<8|'R',
'H'<<8|'T', 'H'<<8|'U', 'I'<<8|'D', 'I'<<8|'E', 'I'<<8|'L',
'I'<<8|'M', 'I'<<8|'N', 'I'<<8|'O', 'I'<<8|'P', 'I'<<8|'Q',
'I'<<8|'R', 'I'<<8|'S', 'I'<<8|'T', 'J'<<8|'E', 'J'<<8|'M',
'J'<<8|'O', 'J'<<8|'P', 'K'<<8|'E', 'K'<<8|'G', 'K'<<8|'H',
'K'<<8|'I', 'K'<<8|'M', 'K'<<8|'N', 'K'<<8|'P', 'K'<<8|'R',
'K'<<8|'W', 'K'<<8|'Y', 'K'<<8|'Z', 'L'<<8|'A', 'L'<<8|'B',
'L'<<8|'C', 'L'<<8|'I', 'L'<<8|'K', 'L'<<8|'R', 'L'<<8|'S',
'L'<<8|'T', 'L'<<8|'U', 'L'<<8|'V', 'L'<<8|'Y', 'M'<<8|'A',
'M'<<8|'C', 'M'<<8|'D', 'M'<<8|'E', 'M'<<8|'G', 'M'<<8|'H',
'M'<<8|'K', 'M'<<8|'L', 'M'<<8|'M', 'M'<<8|'N', 'M'<<8|'O',
'M'<<8|'P', 'M'<<8|'Q', 'M'<<8|'R', 'M'<<8|'S', 'M'<<8|'T',
'M'<<8|'U', 'M'<<8|'V', 'M'<<8|'W', 'M'<<8|'X', 'M'<<8|'Y',
'M'<<8|'Z', 'N'<<8|'A', 'N'<<8|'C', 'N'<<8|'E', 'N'<<8|'F',
'N'<<8|'G', 'N'<<8|'I', 'N'<<8|'L', 'N'<<8|'O', 'N'<<8|'P',
'N'<<8|'R', 'N'<<8|'U', 'N'<<8|'Z', 'O'<<8|'M', 'P'<<8|'A',
'P'<<8|'E', 'P'<<8|'F', 'P'<<8|'G', 'P'<<8|'H', 'P'<<8|'K',
'P'<<8|'L', 'P'<<8|'M', 'P'<<8|'N', 'P'<<8|'R', 'P'<<8|'S',
'P'<<8|'T', 'P'<<8|'W', 'P'<<8|'Y', 'Q'<<8|'A', 'R'<<8|'E',
'R'<<8|'O', 'R'<<8|'S', 'R'<<8|'U', 'R'<<8|'W', 'S'<<8|'A',
'S'<<8|'B', 'S'<<8|'C', 'S'<<8|'D', 'S'<<8|'E', 'S'<<8|'G',
'S'<<8|'H', 'S'<<8|'I', 'S'<<8|'J', 'S'<<8|'K', 'S'<<8|'L',
'S'<<8|'M', 'S'<<8|'N', 'S'<<8|'O', 'S'<<8|'R', 'S'<<8|'T',
'S'<<8|'V', 'S'<<8|'Y', 'S'<<8|'Z', 'T'<<8|'C', 'T'<<8|'D',
'T'<<8|'F', 'T'<<8|'G', 'T'<<8|'H', 'T'<<8|'J', 'T'<<8|'K',
'T'<<8|'L', 'T'<<8|'M', 'T'<<8|'N', 'T'<<8|'O', 'T'<<8|'R',
'T'<<8|'T', 'T'<<8|'V', 'T'<<8|'W', 'T'<<8|'Z', 'U'<<8|'A',
'U'<<8|'G', 'U'<<8|'M', 'U'<<8|'S', 'U'<<8|'Y', 'U'<<8|'Z',
'V'<<8|'A', 'V'<<8|'C', 'V'<<8|'E', 'V'<<8|'G', 'V'<<8|'I',
'V'<<8|'N', 'V'<<8|'U', 'W'<<8|'F', 'W'<<8|'S', 'Y'<<8|'E',
'Y'<<8|'T', 'Z'<<8|'A', 'Z'<<8|'M', 'Z'<<8|'W', -1 };
TestingProfile profile;
for (size_t i = 0; i < arraysize(ids); ++i) {
profile.GetPrefs()->SetInteger(prefs::kCountryIDAtInstall, ids[i]);
ScopedVector<TemplateURL> urls;
size_t url_count;
TemplateURLPrepopulateData::GetPrepopulatedEngines(
profile.GetPrefs(), &(urls.get()), &url_count);
std::set<int> unique_ids;
for (size_t turl_i = 0; turl_i < urls.size(); ++turl_i) {
ASSERT_TRUE(unique_ids.find(urls[turl_i]->prepopulate_id()) ==
unique_ids.end());
unique_ids.insert(urls[turl_i]->prepopulate_id());
}
}
}
// Verifies that default search providers from the preferences file
// override the built-in ones.
TEST_F(TemplateURLPrepopulateDataTest, ProvidersFromPrefs) {
const char pref_data[] =
"{ "
" \"search_provider_overrides_version\":1,"
" \"search_provider_overrides\": ["
" { \"name\":\"foo\","
" \"keyword\":\"fook\","
" \"search_url\":\"http://foo.com/s?q={searchTerms}\","
" \"favicon_url\":\"http://foi.com/favicon.ico\","
" \"suggest_url\":\"\","
" \"encoding\":\"UTF-8\","
" \"id\":1001"
" }"
" ]"
"}";
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath preferences_file = temp_dir.path().AppendASCII("Preferences");
file_util::WriteFile(preferences_file, pref_data, sizeof(pref_data));
scoped_ptr<PrefService> prefs(
PrefService::CreateUserPrefService(preferences_file));
TemplateURLPrepopulateData::RegisterUserPrefs(prefs.get());
int version = TemplateURLPrepopulateData::GetDataVersion(prefs.get());
EXPECT_EQ(1, version);
std::vector<TemplateURL*> t_urls;
size_t default_index;
TemplateURLPrepopulateData::GetPrepopulatedEngines(
prefs.get(), &t_urls, &default_index);
ASSERT_EQ(1u, t_urls.size());
EXPECT_EQ(L"foo", t_urls[0]->short_name());
EXPECT_EQ(L"fook", t_urls[0]->keyword());
EXPECT_EQ("foo.com", t_urls[0]->url()->GetHost());
EXPECT_EQ("foi.com", t_urls[0]->GetFavIconURL().host());
EXPECT_EQ(1u, t_urls[0]->input_encodings().size());
EXPECT_EQ(1001, t_urls[0]->prepopulate_id());
}
<commit_msg>Fix memory leak in unit test<commit_after>// 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 "base/scoped_temp_dir.h"
#include "base/scoped_vector.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
typedef testing::Test TemplateURLPrepopulateDataTest;
// Verifies the set of prepopulate data doesn't contain entries with duplicate
// ids.
TEST_F(TemplateURLPrepopulateDataTest, UniqueIDs) {
int ids[] = { 'A'<<8|'D', 'A'<<8|'E', 'A'<<8|'F', 'A'<<8|'G', 'A'<<8|'I',
'A'<<8|'L', 'A'<<8|'M', 'A'<<8|'N', 'A'<<8|'O', 'A'<<8|'Q',
'A'<<8|'R', 'A'<<8|'S', 'A'<<8|'T', 'A'<<8|'U', 'A'<<8|'W',
'A'<<8|'X', 'A'<<8|'Z', 'B'<<8|'A', 'B'<<8|'B', 'B'<<8|'D',
'B'<<8|'E', 'B'<<8|'F', 'B'<<8|'G', 'B'<<8|'H', 'B'<<8|'I',
'B'<<8|'J', 'B'<<8|'M', 'B'<<8|'N', 'B'<<8|'O', 'B'<<8|'R',
'B'<<8|'S', 'B'<<8|'T', 'B'<<8|'V', 'B'<<8|'W', 'B'<<8|'Y',
'B'<<8|'Z', 'C'<<8|'A', 'C'<<8|'C', 'C'<<8|'D', 'C'<<8|'F',
'C'<<8|'G', 'C'<<8|'H', 'C'<<8|'I', 'C'<<8|'K', 'C'<<8|'L',
'C'<<8|'M', 'C'<<8|'N', 'C'<<8|'O', 'C'<<8|'R', 'C'<<8|'U',
'C'<<8|'V', 'C'<<8|'X', 'C'<<8|'Y', 'C'<<8|'Z', 'D'<<8|'E',
'D'<<8|'J', 'D'<<8|'K', 'D'<<8|'M', 'D'<<8|'O', 'D'<<8|'Z',
'E'<<8|'C', 'E'<<8|'E', 'E'<<8|'G', 'E'<<8|'R', 'E'<<8|'S',
'E'<<8|'T', 'F'<<8|'I', 'F'<<8|'J', 'F'<<8|'K', 'F'<<8|'M',
'F'<<8|'O', 'F'<<8|'R', 'G'<<8|'A', 'G'<<8|'B', 'G'<<8|'D',
'G'<<8|'E', 'G'<<8|'F', 'G'<<8|'G', 'G'<<8|'H', 'G'<<8|'I',
'G'<<8|'L', 'G'<<8|'M', 'G'<<8|'N', 'G'<<8|'P', 'G'<<8|'Q',
'G'<<8|'R', 'G'<<8|'S', 'G'<<8|'T', 'G'<<8|'U', 'G'<<8|'W',
'G'<<8|'Y', 'H'<<8|'K', 'H'<<8|'M', 'H'<<8|'N', 'H'<<8|'R',
'H'<<8|'T', 'H'<<8|'U', 'I'<<8|'D', 'I'<<8|'E', 'I'<<8|'L',
'I'<<8|'M', 'I'<<8|'N', 'I'<<8|'O', 'I'<<8|'P', 'I'<<8|'Q',
'I'<<8|'R', 'I'<<8|'S', 'I'<<8|'T', 'J'<<8|'E', 'J'<<8|'M',
'J'<<8|'O', 'J'<<8|'P', 'K'<<8|'E', 'K'<<8|'G', 'K'<<8|'H',
'K'<<8|'I', 'K'<<8|'M', 'K'<<8|'N', 'K'<<8|'P', 'K'<<8|'R',
'K'<<8|'W', 'K'<<8|'Y', 'K'<<8|'Z', 'L'<<8|'A', 'L'<<8|'B',
'L'<<8|'C', 'L'<<8|'I', 'L'<<8|'K', 'L'<<8|'R', 'L'<<8|'S',
'L'<<8|'T', 'L'<<8|'U', 'L'<<8|'V', 'L'<<8|'Y', 'M'<<8|'A',
'M'<<8|'C', 'M'<<8|'D', 'M'<<8|'E', 'M'<<8|'G', 'M'<<8|'H',
'M'<<8|'K', 'M'<<8|'L', 'M'<<8|'M', 'M'<<8|'N', 'M'<<8|'O',
'M'<<8|'P', 'M'<<8|'Q', 'M'<<8|'R', 'M'<<8|'S', 'M'<<8|'T',
'M'<<8|'U', 'M'<<8|'V', 'M'<<8|'W', 'M'<<8|'X', 'M'<<8|'Y',
'M'<<8|'Z', 'N'<<8|'A', 'N'<<8|'C', 'N'<<8|'E', 'N'<<8|'F',
'N'<<8|'G', 'N'<<8|'I', 'N'<<8|'L', 'N'<<8|'O', 'N'<<8|'P',
'N'<<8|'R', 'N'<<8|'U', 'N'<<8|'Z', 'O'<<8|'M', 'P'<<8|'A',
'P'<<8|'E', 'P'<<8|'F', 'P'<<8|'G', 'P'<<8|'H', 'P'<<8|'K',
'P'<<8|'L', 'P'<<8|'M', 'P'<<8|'N', 'P'<<8|'R', 'P'<<8|'S',
'P'<<8|'T', 'P'<<8|'W', 'P'<<8|'Y', 'Q'<<8|'A', 'R'<<8|'E',
'R'<<8|'O', 'R'<<8|'S', 'R'<<8|'U', 'R'<<8|'W', 'S'<<8|'A',
'S'<<8|'B', 'S'<<8|'C', 'S'<<8|'D', 'S'<<8|'E', 'S'<<8|'G',
'S'<<8|'H', 'S'<<8|'I', 'S'<<8|'J', 'S'<<8|'K', 'S'<<8|'L',
'S'<<8|'M', 'S'<<8|'N', 'S'<<8|'O', 'S'<<8|'R', 'S'<<8|'T',
'S'<<8|'V', 'S'<<8|'Y', 'S'<<8|'Z', 'T'<<8|'C', 'T'<<8|'D',
'T'<<8|'F', 'T'<<8|'G', 'T'<<8|'H', 'T'<<8|'J', 'T'<<8|'K',
'T'<<8|'L', 'T'<<8|'M', 'T'<<8|'N', 'T'<<8|'O', 'T'<<8|'R',
'T'<<8|'T', 'T'<<8|'V', 'T'<<8|'W', 'T'<<8|'Z', 'U'<<8|'A',
'U'<<8|'G', 'U'<<8|'M', 'U'<<8|'S', 'U'<<8|'Y', 'U'<<8|'Z',
'V'<<8|'A', 'V'<<8|'C', 'V'<<8|'E', 'V'<<8|'G', 'V'<<8|'I',
'V'<<8|'N', 'V'<<8|'U', 'W'<<8|'F', 'W'<<8|'S', 'Y'<<8|'E',
'Y'<<8|'T', 'Z'<<8|'A', 'Z'<<8|'M', 'Z'<<8|'W', -1 };
TestingProfile profile;
for (size_t i = 0; i < arraysize(ids); ++i) {
profile.GetPrefs()->SetInteger(prefs::kCountryIDAtInstall, ids[i]);
ScopedVector<TemplateURL> urls;
size_t default_index;
TemplateURLPrepopulateData::GetPrepopulatedEngines(
profile.GetPrefs(), &(urls.get()), &default_index);
std::set<int> unique_ids;
for (size_t turl_i = 0; turl_i < urls.size(); ++turl_i) {
ASSERT_TRUE(unique_ids.find(urls[turl_i]->prepopulate_id()) ==
unique_ids.end());
unique_ids.insert(urls[turl_i]->prepopulate_id());
}
}
}
// Verifies that default search providers from the preferences file
// override the built-in ones.
TEST_F(TemplateURLPrepopulateDataTest, ProvidersFromPrefs) {
const char pref_data[] =
"{ "
" \"search_provider_overrides_version\":1,"
" \"search_provider_overrides\": ["
" { \"name\":\"foo\","
" \"keyword\":\"fook\","
" \"search_url\":\"http://foo.com/s?q={searchTerms}\","
" \"favicon_url\":\"http://foi.com/favicon.ico\","
" \"suggest_url\":\"\","
" \"encoding\":\"UTF-8\","
" \"id\":1001"
" }"
" ]"
"}";
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath preferences_file = temp_dir.path().AppendASCII("Preferences");
file_util::WriteFile(preferences_file, pref_data, sizeof(pref_data));
scoped_ptr<PrefService> prefs(
PrefService::CreateUserPrefService(preferences_file));
TemplateURLPrepopulateData::RegisterUserPrefs(prefs.get());
int version = TemplateURLPrepopulateData::GetDataVersion(prefs.get());
EXPECT_EQ(1, version);
ScopedVector<TemplateURL> t_urls;
size_t default_index;
TemplateURLPrepopulateData::GetPrepopulatedEngines(
prefs.get(), &(t_urls.get()), &default_index);
ASSERT_EQ(1u, t_urls.size());
EXPECT_EQ(L"foo", t_urls[0]->short_name());
EXPECT_EQ(L"fook", t_urls[0]->keyword());
EXPECT_EQ("foo.com", t_urls[0]->url()->GetHost());
EXPECT_EQ("foi.com", t_urls[0]->GetFavIconURL().host());
EXPECT_EQ(1u, t_urls[0]->input_encodings().size());
EXPECT_EQ(1001, t_urls[0]->prepopulate_id());
}
<|endoftext|> |
<commit_before>#include "builtin_extra.hh"
#include "lisp_ptr.hh"
#include "vm.hh"
#include "builtin_util.hh"
#include "procedure.hh"
#include "s_closure.hh"
#include "util.hh"
#include "eval.hh"
#include "env.hh"
#include "builtin_equal.hh"
using namespace std;
using namespace Procedure;
Lisp_ptr traditional_transformer(){
ZsArgs args{1};
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw zs_error("traditional-transformer: error: called with a wrong type (%s)\n",
stringify(args[0].tag()));
}
auto info = *iproc->info();
info.passing = Passing::quote;
info.returning = Returning::code;
return new IProcedure(iproc->get(), info,
iproc->arg_list(), iproc->closure());
}
Lisp_ptr gensym(){
static const string gensym_symname = {"(gensym)"};
ZsArgs args{0};
return {new Symbol(&gensym_symname)};
}
Lisp_ptr sc_macro_transformer(){
ZsArgs args{1};
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw zs_error("sc-macro-transformer: error: called with a wrong type (%s)\n",
stringify(args[0].tag()));
}
auto info = *iproc->info();
if(info.required_args != 2 || info.max_args != 2){
throw zs_error("sc-macro-transformer: error: procedure must take exactly 2 args (%d-%d)\n",
info.required_args, info.max_args);
}
info.passing = Passing::whole;
info.returning = Returning::code;
info.leaving = Leaving::after_returning_op;
return new IProcedure(iproc->get(), info,
iproc->arg_list(),
iproc->closure()->fork());
}
Lisp_ptr make_syntactic_closure(){
ZsArgs args{3};
Env* e = args[0].get<Env*>();
if(!e){
throw builtin_type_check_failed("make-syntactic-closure",
Ptr_tag::env, args[0]);
}
if(args[1].tag() != Ptr_tag::cons){
throw builtin_type_check_failed("make-syntactic-closure",
Ptr_tag::cons, args[1]);
}
Cons* c = args[1].get<Cons*>();
return new SyntacticClosure(e, c, args[2]);
}
Lisp_ptr capture_env(){
ZsArgs args{1};
if(args[0].tag() != Ptr_tag::i_procedure){
throw zs_error("eval error: first arg is not procedure (%s)\n",
stringify(args[0].tag()));
}
auto iproc = args[0].get<IProcedure*>();
assert(iproc && iproc->info());
if(iproc->info()->required_args != 1){
throw zs_error("eval error: first arg mush take 1 arg (%d)\n",
iproc->info()->required_args);
}
auto ret = make_cons_list
({intern(vm.symtable(), "eval"),
make_cons_list({intern(vm.symtable(), "apply"), iproc, vm_op_get_current_env}),
vm_op_get_current_env});
return ret;
}
Lisp_ptr proc_identifierp(){
ZsArgs args{1};
return Lisp_ptr{identifierp(args[0])};
}
Lisp_ptr proc_identifier_eq(){
ZsArgs args{4};
auto ident1_env = args[0].get<Env*>();
if(!ident1_env){
throw builtin_type_check_failed("identifier=?", Ptr_tag::env, args[0]);
}
auto ident1_sym = identifier_symbol(args[1]);
auto ident2_env = args[2].get<Env*>();
if(!ident2_env){
throw builtin_type_check_failed("identifier=?", Ptr_tag::env, args[2]);
}
auto ident2_sym = identifier_symbol(args[3]);
return Lisp_ptr{
eq_internal(ident1_env->traverse(ident1_sym, {}),
ident2_env->traverse(ident2_sym, {}))
};
}
Lisp_ptr make_synthetic_identifier(){
ZsArgs args{1};
if(!identifierp(args[0])){
throw zs_error("make-synthetic-identifier: passed value is not identifier (%s)\n",
stringify(args[0].tag()));
}
return new SyntacticClosure(new Env(nullptr), nullptr,
identifier_symbol(args[0]));
}
Lisp_ptr exit_func(){
ZsArgs args{0};
// cerr << "exiting..\n";
vm.stack.clear();
vm.code.clear();
return {};
}
<commit_msg>fixed: (exit) caused fatal memory corruption<commit_after>#include "builtin_extra.hh"
#include "lisp_ptr.hh"
#include "vm.hh"
#include "builtin_util.hh"
#include "procedure.hh"
#include "s_closure.hh"
#include "util.hh"
#include "eval.hh"
#include "env.hh"
#include "builtin_equal.hh"
using namespace std;
using namespace Procedure;
Lisp_ptr traditional_transformer(){
ZsArgs args{1};
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw zs_error("traditional-transformer: error: called with a wrong type (%s)\n",
stringify(args[0].tag()));
}
auto info = *iproc->info();
info.passing = Passing::quote;
info.returning = Returning::code;
return new IProcedure(iproc->get(), info,
iproc->arg_list(), iproc->closure());
}
Lisp_ptr gensym(){
static const string gensym_symname = {"(gensym)"};
ZsArgs args{0};
return {new Symbol(&gensym_symname)};
}
Lisp_ptr sc_macro_transformer(){
ZsArgs args{1};
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw zs_error("sc-macro-transformer: error: called with a wrong type (%s)\n",
stringify(args[0].tag()));
}
auto info = *iproc->info();
if(info.required_args != 2 || info.max_args != 2){
throw zs_error("sc-macro-transformer: error: procedure must take exactly 2 args (%d-%d)\n",
info.required_args, info.max_args);
}
info.passing = Passing::whole;
info.returning = Returning::code;
info.leaving = Leaving::after_returning_op;
return new IProcedure(iproc->get(), info,
iproc->arg_list(),
iproc->closure()->fork());
}
Lisp_ptr make_syntactic_closure(){
ZsArgs args{3};
Env* e = args[0].get<Env*>();
if(!e){
throw builtin_type_check_failed("make-syntactic-closure",
Ptr_tag::env, args[0]);
}
if(args[1].tag() != Ptr_tag::cons){
throw builtin_type_check_failed("make-syntactic-closure",
Ptr_tag::cons, args[1]);
}
Cons* c = args[1].get<Cons*>();
return new SyntacticClosure(e, c, args[2]);
}
Lisp_ptr capture_env(){
ZsArgs args{1};
if(args[0].tag() != Ptr_tag::i_procedure){
throw zs_error("eval error: first arg is not procedure (%s)\n",
stringify(args[0].tag()));
}
auto iproc = args[0].get<IProcedure*>();
assert(iproc && iproc->info());
if(iproc->info()->required_args != 1){
throw zs_error("eval error: first arg mush take 1 arg (%d)\n",
iproc->info()->required_args);
}
auto ret = make_cons_list
({intern(vm.symtable(), "eval"),
make_cons_list({intern(vm.symtable(), "apply"), iproc, vm_op_get_current_env}),
vm_op_get_current_env});
return ret;
}
Lisp_ptr proc_identifierp(){
ZsArgs args{1};
return Lisp_ptr{identifierp(args[0])};
}
Lisp_ptr proc_identifier_eq(){
ZsArgs args{4};
auto ident1_env = args[0].get<Env*>();
if(!ident1_env){
throw builtin_type_check_failed("identifier=?", Ptr_tag::env, args[0]);
}
auto ident1_sym = identifier_symbol(args[1]);
auto ident2_env = args[2].get<Env*>();
if(!ident2_env){
throw builtin_type_check_failed("identifier=?", Ptr_tag::env, args[2]);
}
auto ident2_sym = identifier_symbol(args[3]);
return Lisp_ptr{
eq_internal(ident1_env->traverse(ident1_sym, {}),
ident2_env->traverse(ident2_sym, {}))
};
}
Lisp_ptr make_synthetic_identifier(){
ZsArgs args{1};
if(!identifierp(args[0])){
throw zs_error("make-synthetic-identifier: passed value is not identifier (%s)\n",
stringify(args[0].tag()));
}
return new SyntacticClosure(new Env(nullptr), nullptr,
identifier_symbol(args[0]));
}
Lisp_ptr exit_func(){
{
ZsArgs args{0};
}
// cerr << "exiting..\n";
vm.stack.clear();
vm.code.clear();
return {};
}
<|endoftext|> |
<commit_before>//===- lib/ReaderWriter/MachO/StubsPass.cpp -------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This linker pass updates call-sites which have references to shared library
// atoms to instead have a reference to a stub (PLT entry) for the specified
// symbol. Each file format defines a subclass of StubsPass which implements
// the abstract methods for creating the file format specific StubAtoms.
//
//===----------------------------------------------------------------------===//
#include "ArchHandler.h"
#include "File.h"
#include "MachOPasses.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Reference.h"
#include "lld/Core/Simple.h"
#include "lld/ReaderWriter/MachOLinkingContext.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
namespace lld {
namespace mach_o {
//
// Lazy Pointer Atom created by the stubs pass.
//
class LazyPointerAtom : public SimpleDefinedAtom {
public:
LazyPointerAtom(const File &file, bool is64)
: SimpleDefinedAtom(file), _is64(is64) { }
ContentType contentType() const override {
return DefinedAtom::typeLazyPointer;
}
Alignment alignment() const override {
return Alignment(_is64 ? 3 : 2);
}
uint64_t size() const override {
return _is64 ? 8 : 4;
}
ContentPermissions permissions() const override {
return DefinedAtom::permRW_;
}
ArrayRef<uint8_t> rawContent() const override {
static const uint8_t zeros[] =
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
return llvm::makeArrayRef(zeros, size());
}
private:
const bool _is64;
};
//
// NonLazyPointer (GOT) Atom created by the stubs pass.
//
class NonLazyPointerAtom : public SimpleDefinedAtom {
public:
NonLazyPointerAtom(const File &file, bool is64)
: SimpleDefinedAtom(file), _is64(is64) { }
ContentType contentType() const override {
return DefinedAtom::typeGOT;
}
Alignment alignment() const override {
return Alignment(_is64 ? 3 : 2);
}
uint64_t size() const override {
return _is64 ? 8 : 4;
}
ContentPermissions permissions() const override {
return DefinedAtom::permRW_;
}
ArrayRef<uint8_t> rawContent() const override {
static const uint8_t zeros[] =
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
return llvm::makeArrayRef(zeros, size());
}
private:
const bool _is64;
};
//
// Stub Atom created by the stubs pass.
//
class StubAtom : public SimpleDefinedAtom {
public:
StubAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
: SimpleDefinedAtom(file), _stubInfo(stubInfo){ }
ContentType contentType() const override {
return DefinedAtom::typeStub;
}
Alignment alignment() const override {
return Alignment(_stubInfo.codeAlignment);
}
uint64_t size() const override {
return _stubInfo.stubSize;
}
ContentPermissions permissions() const override {
return DefinedAtom::permR_X;
}
ArrayRef<uint8_t> rawContent() const override {
return llvm::makeArrayRef(_stubInfo.stubBytes, _stubInfo.stubSize);
}
private:
const ArchHandler::StubInfo &_stubInfo;
};
//
// Stub Helper Atom created by the stubs pass.
//
class StubHelperAtom : public SimpleDefinedAtom {
public:
StubHelperAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
: SimpleDefinedAtom(file), _stubInfo(stubInfo) { }
ContentType contentType() const override {
return DefinedAtom::typeStubHelper;
}
Alignment alignment() const override {
return Alignment(_stubInfo.codeAlignment);
}
uint64_t size() const override {
return _stubInfo.stubHelperSize;
}
ContentPermissions permissions() const override {
return DefinedAtom::permR_X;
}
ArrayRef<uint8_t> rawContent() const override {
return llvm::makeArrayRef(_stubInfo.stubHelperBytes,
_stubInfo.stubHelperSize);
}
private:
const ArchHandler::StubInfo &_stubInfo;
};
//
// Stub Helper Common Atom created by the stubs pass.
//
class StubHelperCommonAtom : public SimpleDefinedAtom {
public:
StubHelperCommonAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
: SimpleDefinedAtom(file), _stubInfo(stubInfo) { }
ContentType contentType() const override {
return DefinedAtom::typeStubHelper;
}
Alignment alignment() const override {
return Alignment(_stubInfo.codeAlignment);
}
uint64_t size() const override {
return _stubInfo.stubHelperCommonSize;
}
ContentPermissions permissions() const override {
return DefinedAtom::permR_X;
}
ArrayRef<uint8_t> rawContent() const override {
return llvm::makeArrayRef(_stubInfo.stubHelperCommonBytes,
_stubInfo.stubHelperCommonSize);
}
private:
const ArchHandler::StubInfo &_stubInfo;
};
class StubsPass : public Pass {
public:
StubsPass(const MachOLinkingContext &context)
: _context(context), _archHandler(_context.archHandler()),
_stubInfo(_archHandler.stubInfo()), _file("<mach-o Stubs pass>") { }
void perform(std::unique_ptr<MutableFile> &mergedFile) override {
// Skip this pass if output format uses text relocations instead of stubs.
if (!this->noTextRelocs())
return;
// Scan all references in all atoms.
for (const DefinedAtom *atom : mergedFile->defined()) {
for (const Reference *ref : *atom) {
// Look at call-sites.
if (!this->isCallSite(*ref))
continue;
const Atom *target = ref->target();
assert(target != nullptr);
if (isa<SharedLibraryAtom>(target)) {
// Calls to shared libraries go through stubs.
_targetToUses[target].push_back(ref);
continue;
}
const DefinedAtom *defTarget = dyn_cast<DefinedAtom>(target);
if (defTarget && defTarget->interposable() != DefinedAtom::interposeNo){
// Calls to interposable functions in same linkage unit must also go
// through a stub.
assert(defTarget->scope() != DefinedAtom::scopeTranslationUnit);
_targetToUses[target].push_back(ref);
}
}
}
// Exit early if no stubs needed.
if (_targetToUses.empty())
return;
// First add help-common and GOT slots used by lazy binding.
SimpleDefinedAtom *helperCommonAtom =
new (_file.allocator()) StubHelperCommonAtom(_file, _stubInfo);
SimpleDefinedAtom *helperCacheNLPAtom =
new (_file.allocator()) NonLazyPointerAtom(_file, _context.is64Bit());
SimpleDefinedAtom *helperBinderNLPAtom =
new (_file.allocator()) NonLazyPointerAtom(_file, _context.is64Bit());
addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
helperCacheNLPAtom);
addOptReference(
helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
_stubInfo.optStubHelperCommonReferenceToCache, helperCacheNLPAtom);
addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
helperBinderNLPAtom);
addOptReference(
helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
_stubInfo.optStubHelperCommonReferenceToBinder, helperBinderNLPAtom);
mergedFile->addAtom(*helperCommonAtom);
mergedFile->addAtom(*helperBinderNLPAtom);
mergedFile->addAtom(*helperCacheNLPAtom);
// Add reference to dyld_stub_binder in libSystem.dylib
bool binderFound = false;
for (const SharedLibraryAtom *atom : mergedFile->sharedLibrary()) {
if (atom->name().equals(_stubInfo.binderSymbolName)) {
addReference(helperBinderNLPAtom,
_stubInfo.nonLazyPointerReferenceToBinder, atom);
binderFound = true;
break;
}
}
assert(binderFound && "dyld_stub_binder not found");
// Sort targets by name, so stubs and lazy pointers are consistent
std::vector<const Atom *> targetsNeedingStubs;
for (auto it : _targetToUses)
targetsNeedingStubs.push_back(it.first);
std::sort(targetsNeedingStubs.begin(), targetsNeedingStubs.end(),
[](const Atom * left, const Atom * right) {
return (left->name().compare(right->name()) < 0);
});
// Make and append stubs, lazy pointers, and helpers in alphabetical order.
unsigned lazyOffset = 0;
for (const Atom *target : targetsNeedingStubs) {
StubAtom *stub = new (_file.allocator()) StubAtom(_file, _stubInfo);
LazyPointerAtom *lp =
new (_file.allocator()) LazyPointerAtom(_file, _context.is64Bit());
StubHelperAtom *helper =
new (_file.allocator()) StubHelperAtom(_file, _stubInfo);
addReference(stub, _stubInfo.stubReferenceToLP, lp);
addOptReference(stub, _stubInfo.stubReferenceToLP,
_stubInfo.optStubReferenceToLP, lp);
addReference(lp, _stubInfo.lazyPointerReferenceToHelper, helper);
addReference(lp, _stubInfo.lazyPointerReferenceToFinal, target);
addReference(helper, _stubInfo.stubHelperReferenceToImm, helper);
addReferenceAddend(helper, _stubInfo.stubHelperReferenceToImm, helper,
lazyOffset);
addReference(helper, _stubInfo.stubHelperReferenceToHelperCommon,
helperCommonAtom);
mergedFile->addAtom(*stub);
mergedFile->addAtom(*lp);
mergedFile->addAtom(*helper);
// Update each reference to use stub.
for (const Reference *ref : _targetToUses[target]) {
assert(ref->target() == target);
// Switch call site to reference stub atom instead.
const_cast<Reference *>(ref)->setTarget(stub);
}
// Calculate new offset
lazyOffset += target->name().size() + 12;
}
}
private:
bool noTextRelocs() {
return true;
}
bool isCallSite(const Reference &ref) {
return _archHandler.isCallSite(ref);
}
void addReference(SimpleDefinedAtom* atom,
const ArchHandler::ReferenceInfo &refInfo,
const lld::Atom* target) {
atom->addReference(Reference::KindNamespace::mach_o,
refInfo.arch, refInfo.kind, refInfo.offset,
target, refInfo.addend);
}
void addReferenceAddend(SimpleDefinedAtom *atom,
const ArchHandler::ReferenceInfo &refInfo,
const lld::Atom *target, uint64_t addend) {
atom->addReference(Reference::KindNamespace::mach_o, refInfo.arch,
refInfo.kind, refInfo.offset, target, addend);
}
void addOptReference(SimpleDefinedAtom* atom,
const ArchHandler::ReferenceInfo &refInfo,
const ArchHandler::OptionalRefInfo &optRef,
const lld::Atom* target) {
if (!optRef.used)
return;
atom->addReference(Reference::KindNamespace::mach_o,
refInfo.arch, optRef.kind, optRef.offset,
target, optRef.addend);
}
typedef llvm::DenseMap<const Atom*,
llvm::SmallVector<const Reference *, 8>> TargetToUses;
const MachOLinkingContext &_context;
mach_o::ArchHandler &_archHandler;
const ArchHandler::StubInfo &_stubInfo;
MachOFile _file;
TargetToUses _targetToUses;
};
void addStubsPass(PassManager &pm, const MachOLinkingContext &ctx) {
pm.add(std::unique_ptr<Pass>(new StubsPass(ctx)));
}
} // end namespace mach_o
} // end namespace lld
<commit_msg>Avoid an unused variable warning when assertions are off<commit_after>//===- lib/ReaderWriter/MachO/StubsPass.cpp -------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This linker pass updates call-sites which have references to shared library
// atoms to instead have a reference to a stub (PLT entry) for the specified
// symbol. Each file format defines a subclass of StubsPass which implements
// the abstract methods for creating the file format specific StubAtoms.
//
//===----------------------------------------------------------------------===//
#include "ArchHandler.h"
#include "File.h"
#include "MachOPasses.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Reference.h"
#include "lld/Core/Simple.h"
#include "lld/ReaderWriter/MachOLinkingContext.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
namespace lld {
namespace mach_o {
//
// Lazy Pointer Atom created by the stubs pass.
//
class LazyPointerAtom : public SimpleDefinedAtom {
public:
LazyPointerAtom(const File &file, bool is64)
: SimpleDefinedAtom(file), _is64(is64) { }
ContentType contentType() const override {
return DefinedAtom::typeLazyPointer;
}
Alignment alignment() const override {
return Alignment(_is64 ? 3 : 2);
}
uint64_t size() const override {
return _is64 ? 8 : 4;
}
ContentPermissions permissions() const override {
return DefinedAtom::permRW_;
}
ArrayRef<uint8_t> rawContent() const override {
static const uint8_t zeros[] =
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
return llvm::makeArrayRef(zeros, size());
}
private:
const bool _is64;
};
//
// NonLazyPointer (GOT) Atom created by the stubs pass.
//
class NonLazyPointerAtom : public SimpleDefinedAtom {
public:
NonLazyPointerAtom(const File &file, bool is64)
: SimpleDefinedAtom(file), _is64(is64) { }
ContentType contentType() const override {
return DefinedAtom::typeGOT;
}
Alignment alignment() const override {
return Alignment(_is64 ? 3 : 2);
}
uint64_t size() const override {
return _is64 ? 8 : 4;
}
ContentPermissions permissions() const override {
return DefinedAtom::permRW_;
}
ArrayRef<uint8_t> rawContent() const override {
static const uint8_t zeros[] =
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
return llvm::makeArrayRef(zeros, size());
}
private:
const bool _is64;
};
//
// Stub Atom created by the stubs pass.
//
class StubAtom : public SimpleDefinedAtom {
public:
StubAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
: SimpleDefinedAtom(file), _stubInfo(stubInfo){ }
ContentType contentType() const override {
return DefinedAtom::typeStub;
}
Alignment alignment() const override {
return Alignment(_stubInfo.codeAlignment);
}
uint64_t size() const override {
return _stubInfo.stubSize;
}
ContentPermissions permissions() const override {
return DefinedAtom::permR_X;
}
ArrayRef<uint8_t> rawContent() const override {
return llvm::makeArrayRef(_stubInfo.stubBytes, _stubInfo.stubSize);
}
private:
const ArchHandler::StubInfo &_stubInfo;
};
//
// Stub Helper Atom created by the stubs pass.
//
class StubHelperAtom : public SimpleDefinedAtom {
public:
StubHelperAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
: SimpleDefinedAtom(file), _stubInfo(stubInfo) { }
ContentType contentType() const override {
return DefinedAtom::typeStubHelper;
}
Alignment alignment() const override {
return Alignment(_stubInfo.codeAlignment);
}
uint64_t size() const override {
return _stubInfo.stubHelperSize;
}
ContentPermissions permissions() const override {
return DefinedAtom::permR_X;
}
ArrayRef<uint8_t> rawContent() const override {
return llvm::makeArrayRef(_stubInfo.stubHelperBytes,
_stubInfo.stubHelperSize);
}
private:
const ArchHandler::StubInfo &_stubInfo;
};
//
// Stub Helper Common Atom created by the stubs pass.
//
class StubHelperCommonAtom : public SimpleDefinedAtom {
public:
StubHelperCommonAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
: SimpleDefinedAtom(file), _stubInfo(stubInfo) { }
ContentType contentType() const override {
return DefinedAtom::typeStubHelper;
}
Alignment alignment() const override {
return Alignment(_stubInfo.codeAlignment);
}
uint64_t size() const override {
return _stubInfo.stubHelperCommonSize;
}
ContentPermissions permissions() const override {
return DefinedAtom::permR_X;
}
ArrayRef<uint8_t> rawContent() const override {
return llvm::makeArrayRef(_stubInfo.stubHelperCommonBytes,
_stubInfo.stubHelperCommonSize);
}
private:
const ArchHandler::StubInfo &_stubInfo;
};
class StubsPass : public Pass {
public:
StubsPass(const MachOLinkingContext &context)
: _context(context), _archHandler(_context.archHandler()),
_stubInfo(_archHandler.stubInfo()), _file("<mach-o Stubs pass>") { }
void perform(std::unique_ptr<MutableFile> &mergedFile) override {
// Skip this pass if output format uses text relocations instead of stubs.
if (!this->noTextRelocs())
return;
// Scan all references in all atoms.
for (const DefinedAtom *atom : mergedFile->defined()) {
for (const Reference *ref : *atom) {
// Look at call-sites.
if (!this->isCallSite(*ref))
continue;
const Atom *target = ref->target();
assert(target != nullptr);
if (isa<SharedLibraryAtom>(target)) {
// Calls to shared libraries go through stubs.
_targetToUses[target].push_back(ref);
continue;
}
const DefinedAtom *defTarget = dyn_cast<DefinedAtom>(target);
if (defTarget && defTarget->interposable() != DefinedAtom::interposeNo){
// Calls to interposable functions in same linkage unit must also go
// through a stub.
assert(defTarget->scope() != DefinedAtom::scopeTranslationUnit);
_targetToUses[target].push_back(ref);
}
}
}
// Exit early if no stubs needed.
if (_targetToUses.empty())
return;
// First add help-common and GOT slots used by lazy binding.
SimpleDefinedAtom *helperCommonAtom =
new (_file.allocator()) StubHelperCommonAtom(_file, _stubInfo);
SimpleDefinedAtom *helperCacheNLPAtom =
new (_file.allocator()) NonLazyPointerAtom(_file, _context.is64Bit());
SimpleDefinedAtom *helperBinderNLPAtom =
new (_file.allocator()) NonLazyPointerAtom(_file, _context.is64Bit());
addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
helperCacheNLPAtom);
addOptReference(
helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
_stubInfo.optStubHelperCommonReferenceToCache, helperCacheNLPAtom);
addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
helperBinderNLPAtom);
addOptReference(
helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
_stubInfo.optStubHelperCommonReferenceToBinder, helperBinderNLPAtom);
mergedFile->addAtom(*helperCommonAtom);
mergedFile->addAtom(*helperBinderNLPAtom);
mergedFile->addAtom(*helperCacheNLPAtom);
// Add reference to dyld_stub_binder in libSystem.dylib
bool binderFound = false;
for (const SharedLibraryAtom *atom : mergedFile->sharedLibrary()) {
if (atom->name().equals(_stubInfo.binderSymbolName)) {
addReference(helperBinderNLPAtom,
_stubInfo.nonLazyPointerReferenceToBinder, atom);
binderFound = true;
break;
}
}
assert(binderFound && "dyld_stub_binder not found");
(void)binderFound;
// Sort targets by name, so stubs and lazy pointers are consistent
std::vector<const Atom *> targetsNeedingStubs;
for (auto it : _targetToUses)
targetsNeedingStubs.push_back(it.first);
std::sort(targetsNeedingStubs.begin(), targetsNeedingStubs.end(),
[](const Atom * left, const Atom * right) {
return (left->name().compare(right->name()) < 0);
});
// Make and append stubs, lazy pointers, and helpers in alphabetical order.
unsigned lazyOffset = 0;
for (const Atom *target : targetsNeedingStubs) {
StubAtom *stub = new (_file.allocator()) StubAtom(_file, _stubInfo);
LazyPointerAtom *lp =
new (_file.allocator()) LazyPointerAtom(_file, _context.is64Bit());
StubHelperAtom *helper =
new (_file.allocator()) StubHelperAtom(_file, _stubInfo);
addReference(stub, _stubInfo.stubReferenceToLP, lp);
addOptReference(stub, _stubInfo.stubReferenceToLP,
_stubInfo.optStubReferenceToLP, lp);
addReference(lp, _stubInfo.lazyPointerReferenceToHelper, helper);
addReference(lp, _stubInfo.lazyPointerReferenceToFinal, target);
addReference(helper, _stubInfo.stubHelperReferenceToImm, helper);
addReferenceAddend(helper, _stubInfo.stubHelperReferenceToImm, helper,
lazyOffset);
addReference(helper, _stubInfo.stubHelperReferenceToHelperCommon,
helperCommonAtom);
mergedFile->addAtom(*stub);
mergedFile->addAtom(*lp);
mergedFile->addAtom(*helper);
// Update each reference to use stub.
for (const Reference *ref : _targetToUses[target]) {
assert(ref->target() == target);
// Switch call site to reference stub atom instead.
const_cast<Reference *>(ref)->setTarget(stub);
}
// Calculate new offset
lazyOffset += target->name().size() + 12;
}
}
private:
bool noTextRelocs() {
return true;
}
bool isCallSite(const Reference &ref) {
return _archHandler.isCallSite(ref);
}
void addReference(SimpleDefinedAtom* atom,
const ArchHandler::ReferenceInfo &refInfo,
const lld::Atom* target) {
atom->addReference(Reference::KindNamespace::mach_o,
refInfo.arch, refInfo.kind, refInfo.offset,
target, refInfo.addend);
}
void addReferenceAddend(SimpleDefinedAtom *atom,
const ArchHandler::ReferenceInfo &refInfo,
const lld::Atom *target, uint64_t addend) {
atom->addReference(Reference::KindNamespace::mach_o, refInfo.arch,
refInfo.kind, refInfo.offset, target, addend);
}
void addOptReference(SimpleDefinedAtom* atom,
const ArchHandler::ReferenceInfo &refInfo,
const ArchHandler::OptionalRefInfo &optRef,
const lld::Atom* target) {
if (!optRef.used)
return;
atom->addReference(Reference::KindNamespace::mach_o,
refInfo.arch, optRef.kind, optRef.offset,
target, optRef.addend);
}
typedef llvm::DenseMap<const Atom*,
llvm::SmallVector<const Reference *, 8>> TargetToUses;
const MachOLinkingContext &_context;
mach_o::ArchHandler &_archHandler;
const ArchHandler::StubInfo &_stubInfo;
MachOFile _file;
TargetToUses _targetToUses;
};
void addStubsPass(PassManager &pm, const MachOLinkingContext &ctx) {
pm.add(std::unique_ptr<Pass>(new StubsPass(ctx)));
}
} // end namespace mach_o
} // end namespace lld
<|endoftext|> |
<commit_before>/* Copyright 2020 Stanford University, NVIDIA 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.
*/
// Included from legion_mapping.h - do not include this directly
// Useful for IDEs
#include "legion/legion_mapping.h"
namespace Legion {
namespace Mapping {
//--------------------------------------------------------------------------
template<typename T,
T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<T,TASK_PTR>);
return register_task_variant(ctx, registrar, desc, NULL/*UDT*/,
0/*sizeof(UDT)*/, true/*has return type*/);
}
//--------------------------------------------------------------------------
template<typename T, typename UDT,
T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*, const UDT&)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar, const UDT &user_data)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(
LegionTaskWrapper::legion_udt_task_wrapper<T,UDT,TASK_PTR>);
return register_task_variant(ctx, registrar, desc, &user_data,
sizeof(UDT), true/*has return type*/);
}
//--------------------------------------------------------------------------
template<
void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<TASK_PTR>);
return register_task_variant(ctx, registrar, desc, NULL/*UDT*/,
0/*sizeof(UDT)*/, false/*has return type*/);
}
//--------------------------------------------------------------------------
template<typename UDT,
void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*, const UDT&)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar, const UDT &user_data)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(
LegionTaskWrapper::legion_udt_task_wrapper<UDT,TASK_PTR>);
return register_variant(ctx, registrar, desc, &user_data, sizeof(UDT),
false/*has return type*/);
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::create_index_space(
MapperContext ctx, Rect<DIM,T> bounds) const
//--------------------------------------------------------------------------
{
DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(bounds)));
const Domain dom(realm_is);
return IndexSpaceT<DIM,T>(create_index_space(ctx, dom,
Legion::Internal::NT_TemplateHelper::template encode_tag<DIM,T>()));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::create_index_space(
MapperContext ctx, const std::vector<Point<DIM,T> > &points) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<Realm::Point<DIM,T> > realm_points(points.size());
for (unsigned idx = 0; idx < points.size(); idx++)
realm_points[idx] = points[idx];
DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(realm_points)));
const Domain dom(realm_is);
return IndexSpaceT<DIM,T>(create_index_space(ctx, dom,
Internal::NT_TemplateHelper::template encode_tag<DIM,T>()));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::create_index_space(
MapperContext ctx, const std::vector<Rect<DIM,T> > &rects) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<Realm::Rect<DIM,T> > realm_rects(rects.size());
for (unsigned idx = 0; idx < rects.size(); idx++)
realm_rects[idx] = rects[idx];
DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(realm_rects)));
const Domain dom(realm_is);
return IndexSpaceT<DIM,T>(create_index_space_internal(ctx, dom, &realm_is,
Internal::NT_TemplateHelper::template encode_tag<DIM,T>()));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::union_index_spaces(
MapperContext ctx, const std::vector<IndexSpaceT<DIM,T> > &srcs) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<IndexSpace> sources(srcs.size());
for (unsigned idx = 0; idx < sources.size(); idx++)
sources[idx] = srcs[idx];
return IndexSpaceT<DIM,T>(union_index_spaces(ctx, sources));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::intersect_index_spaces(
MapperContext ctx, const std::vector<IndexSpaceT<DIM,T> > &srcs) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<IndexSpace> sources(srcs.size());
for (unsigned idx = 0; idx < sources.size(); idx++)
sources[idx] = srcs[idx];
return IndexSpaceT<DIM,T>(intersect_index_spaces(ctx, sources));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::subtract_index_spaces(
MapperContext ctx, IndexSpaceT<DIM,T> left, IndexSpaceT<DIM,T> right) const
//--------------------------------------------------------------------------
{
return IndexSpaceT<DIM,T>(subtract_index_spaces(ctx,
(IndexSpace)left, (IndexSpace)right));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline bool MapperRuntime::is_index_space_empty(MapperContext ctx,
IndexSpaceT<DIM,T> handle) const
//--------------------------------------------------------------------------
{
return is_index_space_empty(ctx, (IndexSpace)handle);
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline bool MapperRuntime::index_spaces_overlap(MapperContext ctx,
IndexSpaceT<DIM,T> one, IndexSpaceT<DIM,T> two) const
//--------------------------------------------------------------------------
{
return index_spaces_overlap(ctx, (IndexSpace)one, (IndexSpace)two);
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline bool MapperRuntime::index_space_dominates(MapperContext ctx,
IndexSpaceT<DIM,T> left, IndexSpaceT<DIM,T> right) const
//--------------------------------------------------------------------------
{
return index_space_dominates(ctx, (IndexSpace)left, (IndexSpace)right);
}
//--------------------------------------------------------------------------
inline ProfilingRequest::ProfilingRequest(void)
//--------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------
inline ProfilingRequest::~ProfilingRequest(void)
//--------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------
template <typename T>
inline ProfilingRequest &ProfilingRequest::add_measurement(void)
//--------------------------------------------------------------------------
{
requested_measurements.insert((ProfilingMeasurementID)T::ID);
return *this;
}
//--------------------------------------------------------------------------
inline bool ProfilingRequest::empty(void) const
//--------------------------------------------------------------------------
{
return requested_measurements.empty();
}
//--------------------------------------------------------------------------
inline ProfilingResponse::ProfilingResponse(void)
//--------------------------------------------------------------------------
: realm_resp(NULL), overhead(NULL)
{
}
//--------------------------------------------------------------------------
inline ProfilingResponse::~ProfilingResponse(void)
//--------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------
template <typename T>
inline bool ProfilingResponse::has_measurement(void) const
//--------------------------------------------------------------------------
{
// Realm measurements, all Legion measurements are specialized templates
if (realm_resp)
return realm_resp->template has_measurement<T>();
else
return false;
}
//--------------------------------------------------------------------------
template<>
inline bool ProfilingResponse::has_measurement<
ProfilingMeasurements::RuntimeOverhead>(void) const
//--------------------------------------------------------------------------
{
return (overhead != NULL);
}
//--------------------------------------------------------------------------
template <typename T>
inline T *ProfilingResponse::get_measurement(void) const
//--------------------------------------------------------------------------
{
// Realm measurements, all Legion measurements are specialized templates
if (realm_resp)
return realm_resp->template get_measurement<T>();
else
return 0;
}
//--------------------------------------------------------------------------
template <typename T>
inline bool ProfilingResponse::get_measurement(T& result) const
//--------------------------------------------------------------------------
{
if (realm_resp)
return realm_resp->template get_measurement<T>(result);
else
return false;
}
//--------------------------------------------------------------------------
template<>
inline ProfilingMeasurements::RuntimeOverhead*
ProfilingResponse::get_measurement<
ProfilingMeasurements::RuntimeOverhead>(void) const
//--------------------------------------------------------------------------
{
// Always produce a copy for the mapper to own
return new ProfilingMeasurements::RuntimeOverhead(*overhead);
}
//--------------------------------------------------------------------------
template<>
inline bool ProfilingResponse::get_measurement<
ProfilingMeasurements::RuntimeOverhead>(
ProfilingMeasurements::RuntimeOverhead& result) const
//--------------------------------------------------------------------------
{
result = *overhead;
return true;
}
namespace ProfilingMeasurements {
//------------------------------------------------------------------------
inline RuntimeOverhead::RuntimeOverhead(void)
: application_time(0), runtime_time(0), wait_time(0)
//------------------------------------------------------------------------
{
}
};
};
};
<commit_msg>legion: fix broken mapper API call<commit_after>/* Copyright 2020 Stanford University, NVIDIA 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.
*/
// Included from legion_mapping.h - do not include this directly
// Useful for IDEs
#include "legion/legion_mapping.h"
namespace Legion {
namespace Mapping {
//--------------------------------------------------------------------------
template<typename T,
T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<T,TASK_PTR>);
return register_task_variant(ctx, registrar, desc, NULL/*UDT*/,
0/*sizeof(UDT)*/, true/*has return type*/);
}
//--------------------------------------------------------------------------
template<typename T, typename UDT,
T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*, const UDT&)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar, const UDT &user_data)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(
LegionTaskWrapper::legion_udt_task_wrapper<T,UDT,TASK_PTR>);
return register_task_variant(ctx, registrar, desc, &user_data,
sizeof(UDT), true/*has return type*/);
}
//--------------------------------------------------------------------------
template<
void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<TASK_PTR>);
return register_task_variant(ctx, registrar, desc, NULL/*UDT*/,
0/*sizeof(UDT)*/, false/*has return type*/);
}
//--------------------------------------------------------------------------
template<typename UDT,
void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&,
Context, Runtime*, const UDT&)>
VariantID MapperRuntime::register_task_variant(MapperContext ctx,
const TaskVariantRegistrar ®istrar, const UDT &user_data)
//--------------------------------------------------------------------------
{
CodeDescriptor desc(
LegionTaskWrapper::legion_udt_task_wrapper<UDT,TASK_PTR>);
return register_variant(ctx, registrar, desc, &user_data, sizeof(UDT),
false/*has return type*/);
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::create_index_space(
MapperContext ctx, Rect<DIM,T> bounds) const
//--------------------------------------------------------------------------
{
DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(bounds)));
const Domain dom(realm_is);
return IndexSpaceT<DIM,T>(create_index_space(ctx, dom,
Legion::Internal::NT_TemplateHelper::template encode_tag<DIM,T>()));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::create_index_space(
MapperContext ctx, const std::vector<Point<DIM,T> > &points) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<Realm::Point<DIM,T> > realm_points(points.size());
for (unsigned idx = 0; idx < points.size(); idx++)
realm_points[idx] = points[idx];
DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(realm_points)));
const Domain dom(realm_is);
return IndexSpaceT<DIM,T>(create_index_space(ctx, dom,
Internal::NT_TemplateHelper::template encode_tag<DIM,T>()));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::create_index_space(
MapperContext ctx, const std::vector<Rect<DIM,T> > &rects) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<Realm::Rect<DIM,T> > realm_rects(rects.size());
for (unsigned idx = 0; idx < rects.size(); idx++)
realm_rects[idx] = rects[idx];
DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(realm_rects)));
const Domain dom(realm_is);
return IndexSpaceT<DIM,T>(create_index_space(ctx, dom,
Internal::NT_TemplateHelper::template encode_tag<DIM,T>()));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::union_index_spaces(
MapperContext ctx, const std::vector<IndexSpaceT<DIM,T> > &srcs) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<IndexSpace> sources(srcs.size());
for (unsigned idx = 0; idx < sources.size(); idx++)
sources[idx] = srcs[idx];
return IndexSpaceT<DIM,T>(union_index_spaces(ctx, sources));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::intersect_index_spaces(
MapperContext ctx, const std::vector<IndexSpaceT<DIM,T> > &srcs) const
//--------------------------------------------------------------------------
{
// C++ type system is dumb
std::vector<IndexSpace> sources(srcs.size());
for (unsigned idx = 0; idx < sources.size(); idx++)
sources[idx] = srcs[idx];
return IndexSpaceT<DIM,T>(intersect_index_spaces(ctx, sources));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline IndexSpaceT<DIM,T> MapperRuntime::subtract_index_spaces(
MapperContext ctx, IndexSpaceT<DIM,T> left, IndexSpaceT<DIM,T> right) const
//--------------------------------------------------------------------------
{
return IndexSpaceT<DIM,T>(subtract_index_spaces(ctx,
(IndexSpace)left, (IndexSpace)right));
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline bool MapperRuntime::is_index_space_empty(MapperContext ctx,
IndexSpaceT<DIM,T> handle) const
//--------------------------------------------------------------------------
{
return is_index_space_empty(ctx, (IndexSpace)handle);
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline bool MapperRuntime::index_spaces_overlap(MapperContext ctx,
IndexSpaceT<DIM,T> one, IndexSpaceT<DIM,T> two) const
//--------------------------------------------------------------------------
{
return index_spaces_overlap(ctx, (IndexSpace)one, (IndexSpace)two);
}
//--------------------------------------------------------------------------
template<int DIM, typename T>
inline bool MapperRuntime::index_space_dominates(MapperContext ctx,
IndexSpaceT<DIM,T> left, IndexSpaceT<DIM,T> right) const
//--------------------------------------------------------------------------
{
return index_space_dominates(ctx, (IndexSpace)left, (IndexSpace)right);
}
//--------------------------------------------------------------------------
inline ProfilingRequest::ProfilingRequest(void)
//--------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------
inline ProfilingRequest::~ProfilingRequest(void)
//--------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------
template <typename T>
inline ProfilingRequest &ProfilingRequest::add_measurement(void)
//--------------------------------------------------------------------------
{
requested_measurements.insert((ProfilingMeasurementID)T::ID);
return *this;
}
//--------------------------------------------------------------------------
inline bool ProfilingRequest::empty(void) const
//--------------------------------------------------------------------------
{
return requested_measurements.empty();
}
//--------------------------------------------------------------------------
inline ProfilingResponse::ProfilingResponse(void)
//--------------------------------------------------------------------------
: realm_resp(NULL), overhead(NULL)
{
}
//--------------------------------------------------------------------------
inline ProfilingResponse::~ProfilingResponse(void)
//--------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------
template <typename T>
inline bool ProfilingResponse::has_measurement(void) const
//--------------------------------------------------------------------------
{
// Realm measurements, all Legion measurements are specialized templates
if (realm_resp)
return realm_resp->template has_measurement<T>();
else
return false;
}
//--------------------------------------------------------------------------
template<>
inline bool ProfilingResponse::has_measurement<
ProfilingMeasurements::RuntimeOverhead>(void) const
//--------------------------------------------------------------------------
{
return (overhead != NULL);
}
//--------------------------------------------------------------------------
template <typename T>
inline T *ProfilingResponse::get_measurement(void) const
//--------------------------------------------------------------------------
{
// Realm measurements, all Legion measurements are specialized templates
if (realm_resp)
return realm_resp->template get_measurement<T>();
else
return 0;
}
//--------------------------------------------------------------------------
template <typename T>
inline bool ProfilingResponse::get_measurement(T& result) const
//--------------------------------------------------------------------------
{
if (realm_resp)
return realm_resp->template get_measurement<T>(result);
else
return false;
}
//--------------------------------------------------------------------------
template<>
inline ProfilingMeasurements::RuntimeOverhead*
ProfilingResponse::get_measurement<
ProfilingMeasurements::RuntimeOverhead>(void) const
//--------------------------------------------------------------------------
{
// Always produce a copy for the mapper to own
return new ProfilingMeasurements::RuntimeOverhead(*overhead);
}
//--------------------------------------------------------------------------
template<>
inline bool ProfilingResponse::get_measurement<
ProfilingMeasurements::RuntimeOverhead>(
ProfilingMeasurements::RuntimeOverhead& result) const
//--------------------------------------------------------------------------
{
result = *overhead;
return true;
}
namespace ProfilingMeasurements {
//------------------------------------------------------------------------
inline RuntimeOverhead::RuntimeOverhead(void)
: application_time(0), runtime_time(0), wait_time(0)
//------------------------------------------------------------------------
{
}
};
};
};
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <ogvr/ClientKit/ContextC.h>
// Library/third-party includes
// - none
// Standard includes
#include <iostream>
int main() {
OGVR_ClientContext ctx =
ogvrClientInit("org.opengoggles.exampleclients.MinimalInit");
std::cout << "OK, library initialized, now going to shut it down."
<< std::endl;
ogvrClientShutdown(ctx);
std::cout << "Library shut down, exiting." << std::endl;
return 0;
}<commit_msg>Add mainloop to minimal init<commit_after>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <ogvr/ClientKit/ContextC.h>
// Library/third-party includes
// - none
// Standard includes
#include <iostream>
int main() {
OGVR_ClientContext ctx =
ogvrClientInit("org.opengoggles.exampleclients.MinimalInit");
std::cout << "OK, library initialized." << std::endl;
// Pretend that this is your application's mainloop.
for (int i = 0; i < 1000000; ++i) {
ogvrClientUpdate(ctx);
}
ogvrClientShutdown(ctx);
std::cout << "Library shut down, exiting." << std::endl;
return 0;
}<|endoftext|> |
<commit_before>/*
* Copyright 2008 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.
#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkContingencyStatistics.h"
//=============================================================================
int TestContingencyStatistics( int, char *[] )
{
int testStatus = 0;
vtkVariant mingledData[] =
{
123,456,80,"HTTP",
123,789,80,"HTTP",
123,789,80,"HTTP",
123,456,80,"HTTP",
456,123,80,"HTTP",
456,123,80,"HTTP",
456,123,8080,"HTTP",
789,123,1122,"HTTP",
456,789,80,"HTTP",
456,789,25,"SMTP",
456,789,25,"SMTP",
456,789,25,"SMTP",
456,789,25,"SMTP",
123,789,25,"SMTP",
789,123,80,"SMTP",
123,456,20,"FTP",
789,456,20,"FTP",
789,123,20,"FTP",
789,123,122,"FTP",
789,456,20,"FTP",
789,456,20,"FTP",
};
int nVals = 21;
vtkVariantArray* dataset0Arr = vtkVariantArray::New();
dataset0Arr->SetNumberOfComponents( 1 );
dataset0Arr->SetName( "Source" );
vtkVariantArray* dataset1Arr = vtkVariantArray::New();
dataset1Arr->SetNumberOfComponents( 1 );
dataset1Arr->SetName( "Destination" );
vtkVariantArray* dataset2Arr = vtkVariantArray::New();
dataset2Arr->SetNumberOfComponents( 1 );
dataset2Arr->SetName( "Port" );
vtkVariantArray* dataset3Arr = vtkVariantArray::New();
dataset3Arr->SetNumberOfComponents( 1 );
dataset3Arr->SetName( "Protocol" );
for ( int i = 0; i < nVals; ++ i )
{
int ti = i << 2;
dataset0Arr->InsertNextValue( mingledData[ti] );
dataset1Arr->InsertNextValue( mingledData[ti + 1] );
dataset2Arr->InsertNextValue( mingledData[ti + 2] );
dataset3Arr->InsertNextValue( mingledData[ti + 3] );
}
vtkTable* datasetTable = vtkTable::New();
datasetTable->AddColumn( dataset0Arr );
dataset0Arr->Delete();
datasetTable->AddColumn( dataset1Arr );
dataset1Arr->Delete();
datasetTable->AddColumn( dataset2Arr );
dataset2Arr->Delete();
datasetTable->AddColumn( dataset3Arr );
dataset3Arr->Delete();
int nMetricPairs = 3;
// Entropies in the summary table should normally be retrieved as follows:
// column 2: H(X,Y)
// column 3: H(Y|X)
// column 4: H(X|Y)
int iEntropies[] = { 2,
3,
4 };
int nEntropies = 3; // correct number of entropies reported in the summary table
double* H = new double[nEntropies];
vtkContingencyStatistics* haruspex = vtkContingencyStatistics::New();
haruspex->SetInput( 0, datasetTable );
vtkTable* outputData = haruspex->GetOutput( 0 );
datasetTable->Delete();
// -- Select Column Pair of Interest ( Learn Mode ) --
haruspex->AddColumnPair( "Port", "Protocol" ); // A valid pair
haruspex->AddColumnPair( "Protocol", "Port" ); // The same valid pair, just reversed
haruspex->AddColumnPair( "Source", "Port" ); // Another valid pair
haruspex->AddColumnPair( "Source", "Dummy" ); // An invalid pair
// -- Test Learn Mode --
haruspex->SetLearn( true );
haruspex->SetAssess( true );
haruspex->Update();
vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( haruspex->GetOutputDataObject( 1 ) );
vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );
int testIntValue = 0;
double testDoubleValue = 0;
vtkIdType n = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
cout << "## Calculated the following information entropies( grand total: "
<< n
<< " ):\n";
testIntValue = outputSummary->GetNumberOfColumns();
if ( testIntValue != nEntropies + 2 )
{
vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
<< testIntValue
<< " != "
<< nEntropies + 2
<< ".");
testStatus = 1;
}
else
{
// For each row in the summary table, fetch variable names and information entropies
for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )
{
// Variable names
cout << " ("
<< outputSummary->GetValue( r, 0 ).ToString()
<< ", "
<< outputSummary->GetValue( r, 1 ).ToString()
<< "):";
// Information entropies
for ( vtkIdType c = 0; c < nEntropies; ++ c )
{
H[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();
cout << ", "
<< outputSummary->GetColumnName( iEntropies[c] )
<< "="
<< H[c];
}
cout << "\n";
// Make sure that H(X,Y) > H(Y|X)+ H(X|Y)
testDoubleValue = H[1] + H[2]; // H(Y|X)+ H(X|Y)
if ( testDoubleValue > H[0] )
{
vtkGenericWarningMacro("Reported inconsistent information entropies: H(X,Y) = "
<< H[0]
<< " < "
<< testDoubleValue
<< " = H(Y|X)+ H(X|Y).");
testStatus = 1;
}
}
}
cout << "## Calculated the following probabilities:\n";
testIntValue = 0;
// Skip first row which contains data set cardinality
vtkIdType key;
for ( vtkIdType r = 1; r < outputContingency->GetNumberOfRows(); ++ r )
{
key = outputContingency->GetValue( r, 0 ).ToInt();
cout << " ("
<< outputSummary->GetValue( key, 0 ).ToString()
<< ","
<< outputSummary->GetValue( key, 1 ).ToString()
<< ") = ("
<< outputContingency->GetValue( r, 1 ).ToString()
<< ","
<< outputContingency->GetValue( r, 2 ).ToString()
<< ")";
for ( vtkIdType c = 3; c < outputContingency->GetNumberOfColumns(); ++ c )
{
cout << ", "
<< outputContingency->GetColumnName( c )
<< "="
<< outputContingency->GetValue( r, c ).ToDouble();
}
cout << "\n";
// Update total cardinality
testIntValue += outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
}
if ( testIntValue != nVals * nMetricPairs )
{
vtkGenericWarningMacro("Reported an incorrect total cardinality: "
<< testIntValue
<< " != "
<< nVals * nMetricPairs
<< ".");
testStatus = 1;
}
cout << "\n";
key = 0;
vtkStdString varX = outputSummary->GetValue( key, 0 ).ToString();
vtkStdString varY = outputSummary->GetValue( key, 1 ).ToString();
vtkStdString proName = "Px|y";
vtkStdString colName = proName + "(" + varX + "," + varY + ")";
double threshold = .2;
cout << "## Found the following outliers such that "
<< colName
<< " < "
<< threshold
<< ":\n";
double p;
testIntValue = 0;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
p = outputData->GetValueByName( r, colName ).ToDouble();
if ( p >= threshold )
{
continue;
}
++ testIntValue;
cout << " ("
<< outputData->GetValueByName( r, varX ).ToString()
<< ","
<< outputData->GetValueByName( r, varY ).ToString()
<< "): "
<< proName
<< " = "
<< p
<< "\n";
}
double nOutliers = 4;
if ( testIntValue != nOutliers )
{
vtkGenericWarningMacro("Reported an incorrect number of outliers: "
<< testIntValue
<< " != "
<< nOutliers
<< ".");
testStatus = 1;
}
cout << "\n";
// Clean up
delete [] H;
haruspex->Delete();
return testStatus;
}
<commit_msg>ENH: also test for pointwise mutual information outliers<commit_after>/*
* Copyright 2008 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.
#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkContingencyStatistics.h"
//=============================================================================
int TestContingencyStatistics( int, char *[] )
{
int testStatus = 0;
vtkVariant mingledData[] =
{
123,456,80,"HTTP",
123,789,80,"HTTP",
123,789,80,"HTTP",
123,456,80,"HTTP",
456,123,80,"HTTP",
456,123,80,"HTTP",
456,123,8080,"HTTP",
789,123,1122,"HTTP",
456,789,80,"HTTP",
456,789,25,"SMTP",
456,789,25,"SMTP",
456,789,25,"SMTP",
456,789,25,"SMTP",
123,789,25,"SMTP",
789,123,80,"SMTP",
123,456,20,"FTP",
789,456,20,"FTP",
789,123,20,"FTP",
789,123,122,"FTP",
789,456,20,"FTP",
789,456,20,"FTP",
};
int nVals = 21;
vtkVariantArray* dataset0Arr = vtkVariantArray::New();
dataset0Arr->SetNumberOfComponents( 1 );
dataset0Arr->SetName( "Source" );
vtkVariantArray* dataset1Arr = vtkVariantArray::New();
dataset1Arr->SetNumberOfComponents( 1 );
dataset1Arr->SetName( "Destination" );
vtkVariantArray* dataset2Arr = vtkVariantArray::New();
dataset2Arr->SetNumberOfComponents( 1 );
dataset2Arr->SetName( "Port" );
vtkVariantArray* dataset3Arr = vtkVariantArray::New();
dataset3Arr->SetNumberOfComponents( 1 );
dataset3Arr->SetName( "Protocol" );
for ( int i = 0; i < nVals; ++ i )
{
int ti = i << 2;
dataset0Arr->InsertNextValue( mingledData[ti] );
dataset1Arr->InsertNextValue( mingledData[ti + 1] );
dataset2Arr->InsertNextValue( mingledData[ti + 2] );
dataset3Arr->InsertNextValue( mingledData[ti + 3] );
}
vtkTable* datasetTable = vtkTable::New();
datasetTable->AddColumn( dataset0Arr );
dataset0Arr->Delete();
datasetTable->AddColumn( dataset1Arr );
dataset1Arr->Delete();
datasetTable->AddColumn( dataset2Arr );
dataset2Arr->Delete();
datasetTable->AddColumn( dataset3Arr );
dataset3Arr->Delete();
int nMetricPairs = 3;
// Entropies in the summary table should normally be retrieved as follows:
// column 2: H(X,Y)
// column 3: H(Y|X)
// column 4: H(X|Y)
int iEntropies[] = { 2,
3,
4 };
int nEntropies = 3; // correct number of entropies reported in the summary table
double* H = new double[nEntropies];
vtkContingencyStatistics* haruspex = vtkContingencyStatistics::New();
haruspex->SetInput( 0, datasetTable );
vtkTable* outputData = haruspex->GetOutput( 0 );
datasetTable->Delete();
// -- Select Column Pair of Interest ( Learn Mode ) --
haruspex->AddColumnPair( "Port", "Protocol" ); // A valid pair
haruspex->AddColumnPair( "Protocol", "Port" ); // The same valid pair, just reversed
haruspex->AddColumnPair( "Source", "Port" ); // Another valid pair
haruspex->AddColumnPair( "Source", "Dummy" ); // An invalid pair
// -- Test Learn Mode --
haruspex->SetLearn( true );
haruspex->SetAssess( true );
haruspex->Update();
vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( haruspex->GetOutputDataObject( 1 ) );
vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );
int testIntValue = 0;
double testDoubleValue = 0;
vtkIdType n = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
cout << "## Calculated the following information entropies( grand total: "
<< n
<< " ):\n";
testIntValue = outputSummary->GetNumberOfColumns();
if ( testIntValue != nEntropies + 2 )
{
vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
<< testIntValue
<< " != "
<< nEntropies + 2
<< ".");
testStatus = 1;
}
else
{
// For each row in the summary table, fetch variable names and information entropies
for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )
{
// Variable names
cout << " ("
<< outputSummary->GetValue( r, 0 ).ToString()
<< ", "
<< outputSummary->GetValue( r, 1 ).ToString()
<< "):";
// Information entropies
for ( vtkIdType c = 0; c < nEntropies; ++ c )
{
H[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();
cout << ", "
<< outputSummary->GetColumnName( iEntropies[c] )
<< "="
<< H[c];
}
cout << "\n";
// Make sure that H(X,Y) > H(Y|X)+ H(X|Y)
testDoubleValue = H[1] + H[2]; // H(Y|X)+ H(X|Y)
if ( testDoubleValue > H[0] )
{
vtkGenericWarningMacro("Reported inconsistent information entropies: H(X,Y) = "
<< H[0]
<< " < "
<< testDoubleValue
<< " = H(Y|X)+ H(X|Y).");
testStatus = 1;
}
}
}
cout << "## Calculated the following probabilities:\n";
testIntValue = 0;
// Skip first row which contains data set cardinality
vtkIdType key;
for ( vtkIdType r = 1; r < outputContingency->GetNumberOfRows(); ++ r )
{
key = outputContingency->GetValue( r, 0 ).ToInt();
cout << " ("
<< outputSummary->GetValue( key, 0 ).ToString()
<< ","
<< outputSummary->GetValue( key, 1 ).ToString()
<< ") = ("
<< outputContingency->GetValue( r, 1 ).ToString()
<< ","
<< outputContingency->GetValue( r, 2 ).ToString()
<< ")";
for ( vtkIdType c = 3; c < outputContingency->GetNumberOfColumns(); ++ c )
{
cout << ", "
<< outputContingency->GetColumnName( c )
<< "="
<< outputContingency->GetValue( r, c ).ToDouble();
}
cout << "\n";
// Update total cardinality
testIntValue += outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
}
if ( testIntValue != nVals * nMetricPairs )
{
vtkGenericWarningMacro("Reported an incorrect total cardinality: "
<< testIntValue
<< " != "
<< nVals * nMetricPairs
<< ".");
testStatus = 1;
}
cout << "\n";
// Now inspect results of the Assess mode by looking for outliers
key = 0;
vtkStdString varX = outputSummary->GetValue( key, 0 ).ToString();
vtkStdString varY = outputSummary->GetValue( key, 1 ).ToString();
// Outliers for conditional probability
vtkStdString proName = "Px|y";
vtkStdString colName = proName + "(" + varX + "," + varY + ")";
double threshold = .2;
cout << "## Found the following outliers such that "
<< colName
<< " < "
<< threshold
<< ":\n";
double p;
testIntValue = 0;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
p = outputData->GetValueByName( r, colName ).ToDouble();
if ( p >= threshold )
{
continue;
}
++ testIntValue;
cout << " ("
<< outputData->GetValueByName( r, varX ).ToString()
<< ","
<< outputData->GetValueByName( r, varY ).ToString()
<< "): "
<< proName
<< " = "
<< p
<< "\n";
}
int nOutliers = 4;
if ( testIntValue != nOutliers )
{
vtkGenericWarningMacro("Reported an incorrect number of outliers: "
<< testIntValue
<< " != "
<< nOutliers
<< ".");
testStatus = 1;
}
cout << "\n";
// Outliers for pointwise mutual information
proName = "PMI";
colName = proName + "(" + varX + "," + varY + ")";
threshold = 0.;
cout << "## Found the following outliers such that "
<< colName
<< " < "
<< threshold
<< ":\n";
double pmi;
testIntValue = 0;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
pmi = outputData->GetValueByName( r, colName ).ToDouble();
if ( pmi >= threshold )
{
continue;
}
++ testIntValue;
cout << " ("
<< outputData->GetValueByName( r, varX ).ToString()
<< ","
<< outputData->GetValueByName( r, varY ).ToString()
<< "): "
<< proName
<< " = "
<< pmi
<< "\n";
}
nOutliers = 1;
if ( testIntValue != nOutliers )
{
vtkGenericWarningMacro("Reported an incorrect number of outliers: "
<< testIntValue
<< " != "
<< nOutliers
<< ".");
testStatus = 1;
}
cout << "\n";
// Clean up
delete [] H;
haruspex->Delete();
return testStatus;
}
<|endoftext|> |
<commit_before>//
// Copyright 2012 Advanced Micro Devices, Inc. All rights reserved.
//
/*! \file commandqueue.hpp
* \brief Declarations CommandQueue object.
*
* \author Laurent Morichetti (laurent.morichetti@amd.com)
* \date October 2008
*/
#ifndef COMMAND_QUEUE_HPP_
#define COMMAND_QUEUE_HPP_
#include "thread/thread.hpp"
#include "platform/object.hpp"
#include "platform/command.hpp"
/*! \brief Holds commands that will be executed on a specific device.
*
* \details A command queue is created on a specific device in
* a Context. A new virtual device will be instantiated from the given
* device and an execution environment (a thread) will be created to run
* the CommandQueue::loop() function.
*/
namespace amd {
class HostQueue;
class DeviceQueue;
class CommandQueue : public RuntimeObject {
public:
static const uint RealTimeDisabled = 0xffffffff;
enum class Priority : uint { Normal = 0, Medium };
struct Properties {
typedef cl_command_queue_properties value_type;
const value_type mask_;
value_type value_;
Properties(value_type mask, value_type value) : mask_(mask), value_(value & mask) {}
bool set(value_type bits) {
if ((mask_ & bits) != bits) {
return false;
}
value_ |= bits;
return true;
}
bool clear(value_type bits) {
if ((mask_ & bits) != bits) {
return false;
}
value_ &= ~bits;
return true;
}
bool test(value_type bits) const { return (value_ & bits) != 0; }
};
//! Return the context this command queue is part of.
Context& context() const { return context_(); }
//! Return the device for this command queue.
Device& device() const { return device_; }
//! Return the command queue properties.
Properties properties() const { return properties_; }
Properties& properties() { return properties_; }
//! Returns the base class object
CommandQueue* asCommandQueue() { return this; }
virtual ~CommandQueue() {}
//! Returns TRUE if the object was successfully created
virtual bool create() = 0;
//! RTTI internal implementation
virtual ObjectType objectType() const { return ObjectTypeQueue; }
//! Rturns HostQueue object
virtual HostQueue* asHostQueue() { return NULL; }
//! Returns DeviceQueue object
virtual DeviceQueue* asDeviceQueue() { return NULL; }
//! Returns the number or requested real time CUs
uint rtCUs() const { return rtCUs_; }
//! Returns the queue priority
Priority priority() const { return priority_; }
protected:
//! CommandQueue constructor is protected
//! to keep the CommandQueue class as a virtual interface
CommandQueue(Context& context, //!< Context object
Device& device, //!< Device object
cl_command_queue_properties properties, //!< Queue properties
cl_command_queue_properties propMask, //!< Queue properties mask
uint rtCUs = RealTimeDisabled, //!< Avaialble real time compute units
Priority priority = Priority::Normal //!< Queue priority
)
: properties_(propMask, properties),
rtCUs_(rtCUs),
priority_(priority),
queueLock_("CommandQueue::queueLock"),
device_(device),
context_(context) {}
Properties properties_; //!< Queue properties
uint rtCUs_; //!< The number of used RT compute units
Priority priority_; //!< Queue priority
Monitor queueLock_; //!< Lock protecting the queue
Device& device_; //!< The device
SharedReference<Context> context_; //!< The context of this command queue
private:
//! Disable copy constructor
CommandQueue(const CommandQueue&);
//! Disable assignment
CommandQueue& operator=(const CommandQueue&);
};
class HostQueue : public CommandQueue {
class Thread : public amd::Thread {
public:
//! True if this command queue thread is accepting commands.
volatile bool acceptingCommands_;
//! Create a new thread
Thread()
: amd::Thread("Command Queue Thread", CQ_THREAD_STACK_SIZE),
acceptingCommands_(false),
virtualDevice_(NULL) {}
//! The command queue thread entry point.
void run(void* data) {
HostQueue* queue = static_cast<HostQueue*>(data);
virtualDevice_ = queue->device().createVirtualDevice(queue);
if (virtualDevice_ != NULL) {
queue->loop(virtualDevice_);
if (virtualDevice_->terminate()) {
delete virtualDevice_;
}
} else {
acceptingCommands_ = false;
queue->flush();
}
}
//! Get virtual device for the current thread
device::VirtualDevice* vdev() const { return virtualDevice_; }
private:
device::VirtualDevice* virtualDevice_; //!< Virtual device for this thread
} thread_; //!< The command queue thread instance.
private:
ConcurrentLinkedQueue<Command*> queue_; //!< The queue.
Command* lastEnqueueCommand_; //!< The last submitted command
//! Await commands and execute them as they become ready.
void loop(device::VirtualDevice* virtualDevice);
protected:
virtual bool terminate();
public:
/*! \brief Construct a new host queue.
*
* \note A new virtual device instance will be created from the
* given device.
*/
HostQueue(Context& context, Device& device, cl_command_queue_properties properties,
uint queueRTCUs = 0, Priority priority = Priority::Normal);
//! Returns TRUE if this command queue can accept commands.
virtual bool create() { return thread_.acceptingCommands_; }
//! Append the given command to the queue.
void append(Command& command);
//! Return the thread object running the command loop.
const Thread& thread() const { return thread_; }
//! Signal to start processing the commands in the queue.
void flush() {
ScopedLock sl(queueLock_);
queueLock_.notify();
}
//! Finish all queued commands
void finish();
//! Check if hostQueue empty snapshot
bool isEmpty();
//! Get virtual device for the current command queue
device::VirtualDevice* vdev() const { return thread_.vdev(); }
//! Return the current queue as the HostQueue
virtual HostQueue* asHostQueue() { return this; }
//! Get last enqueued command
Command* getLastQueuedCommand(bool retain);
//! Set last enqueued command
void setLastQueuedCommand(Command* lastCommand);
};
class DeviceQueue : public CommandQueue {
public:
DeviceQueue(Context& context, //!< Context object
Device& device, //!< Device object
cl_command_queue_properties properties, //!< Queue properties
uint size //!< Device queue size
)
: CommandQueue(context, device, properties, device.info().queueOnDeviceProperties_ |
CL_QUEUE_ON_DEVICE | CL_QUEUE_ON_DEVICE_DEFAULT),
size_(size),
virtualDevice_(NULL) {}
virtual ~DeviceQueue();
//! Returns TRUE if device queue was successfully created
virtual bool create();
//! Return the current queue as the DeviceQueue
virtual DeviceQueue* asDeviceQueue() { return this; }
//! Returns the size of device queue
uint size() const { return size_; }
//! Returns virtual device for this device queue
device::VirtualDevice* vDev() const { return virtualDevice_; }
//! Returns the queue lock
Monitor& lock() { return queueLock_; }
private:
uint size_; //!< Device queue size
device::VirtualDevice* virtualDevice_; //!< Virtual device for this queue
};
} // namespace amd
#endif // COMMAND_QUEUE_HPP_<commit_msg>P4 to Git Change 1777158 by cpaquot@cpaquot-ocl-lc-lnx on 2019/05/01 17:12:01<commit_after>//
// Copyright 2012 Advanced Micro Devices, Inc. All rights reserved.
//
/*! \file commandqueue.hpp
* \brief Declarations CommandQueue object.
*
* \author Laurent Morichetti (laurent.morichetti@amd.com)
* \date October 2008
*/
#ifndef COMMAND_QUEUE_HPP_
#define COMMAND_QUEUE_HPP_
#include "thread/thread.hpp"
#include "platform/object.hpp"
#include "platform/command.hpp"
/*! \brief Holds commands that will be executed on a specific device.
*
* \details A command queue is created on a specific device in
* a Context. A new virtual device will be instantiated from the given
* device and an execution environment (a thread) will be created to run
* the CommandQueue::loop() function.
*/
namespace amd {
class HostQueue;
class DeviceQueue;
class CommandQueue : public RuntimeObject {
public:
static const uint RealTimeDisabled = 0xffffffff;
enum class Priority : uint { Normal = 0, Medium, High };
struct Properties {
typedef cl_command_queue_properties value_type;
const value_type mask_;
value_type value_;
Properties(value_type mask, value_type value) : mask_(mask), value_(value & mask) {}
bool set(value_type bits) {
if ((mask_ & bits) != bits) {
return false;
}
value_ |= bits;
return true;
}
bool clear(value_type bits) {
if ((mask_ & bits) != bits) {
return false;
}
value_ &= ~bits;
return true;
}
bool test(value_type bits) const { return (value_ & bits) != 0; }
};
//! Return the context this command queue is part of.
Context& context() const { return context_(); }
//! Return the device for this command queue.
Device& device() const { return device_; }
//! Return the command queue properties.
Properties properties() const { return properties_; }
Properties& properties() { return properties_; }
//! Returns the base class object
CommandQueue* asCommandQueue() { return this; }
virtual ~CommandQueue() {}
//! Returns TRUE if the object was successfully created
virtual bool create() = 0;
//! RTTI internal implementation
virtual ObjectType objectType() const { return ObjectTypeQueue; }
//! Rturns HostQueue object
virtual HostQueue* asHostQueue() { return NULL; }
//! Returns DeviceQueue object
virtual DeviceQueue* asDeviceQueue() { return NULL; }
//! Returns the number or requested real time CUs
uint rtCUs() const { return rtCUs_; }
//! Returns the queue priority
Priority priority() const { return priority_; }
protected:
//! CommandQueue constructor is protected
//! to keep the CommandQueue class as a virtual interface
CommandQueue(Context& context, //!< Context object
Device& device, //!< Device object
cl_command_queue_properties properties, //!< Queue properties
cl_command_queue_properties propMask, //!< Queue properties mask
uint rtCUs = RealTimeDisabled, //!< Avaialble real time compute units
Priority priority = Priority::Normal //!< Queue priority
)
: properties_(propMask, properties),
rtCUs_(rtCUs),
priority_(priority),
queueLock_("CommandQueue::queueLock"),
device_(device),
context_(context) {}
Properties properties_; //!< Queue properties
uint rtCUs_; //!< The number of used RT compute units
Priority priority_; //!< Queue priority
Monitor queueLock_; //!< Lock protecting the queue
Device& device_; //!< The device
SharedReference<Context> context_; //!< The context of this command queue
private:
//! Disable copy constructor
CommandQueue(const CommandQueue&);
//! Disable assignment
CommandQueue& operator=(const CommandQueue&);
};
class HostQueue : public CommandQueue {
class Thread : public amd::Thread {
public:
//! True if this command queue thread is accepting commands.
volatile bool acceptingCommands_;
//! Create a new thread
Thread()
: amd::Thread("Command Queue Thread", CQ_THREAD_STACK_SIZE),
acceptingCommands_(false),
virtualDevice_(NULL) {}
//! The command queue thread entry point.
void run(void* data) {
HostQueue* queue = static_cast<HostQueue*>(data);
virtualDevice_ = queue->device().createVirtualDevice(queue);
if (virtualDevice_ != NULL) {
queue->loop(virtualDevice_);
if (virtualDevice_->terminate()) {
delete virtualDevice_;
}
} else {
acceptingCommands_ = false;
queue->flush();
}
}
//! Get virtual device for the current thread
device::VirtualDevice* vdev() const { return virtualDevice_; }
private:
device::VirtualDevice* virtualDevice_; //!< Virtual device for this thread
} thread_; //!< The command queue thread instance.
private:
ConcurrentLinkedQueue<Command*> queue_; //!< The queue.
Command* lastEnqueueCommand_; //!< The last submitted command
//! Await commands and execute them as they become ready.
void loop(device::VirtualDevice* virtualDevice);
protected:
virtual bool terminate();
public:
/*! \brief Construct a new host queue.
*
* \note A new virtual device instance will be created from the
* given device.
*/
HostQueue(Context& context, Device& device, cl_command_queue_properties properties,
uint queueRTCUs = 0, Priority priority = Priority::Normal);
//! Returns TRUE if this command queue can accept commands.
virtual bool create() { return thread_.acceptingCommands_; }
//! Append the given command to the queue.
void append(Command& command);
//! Return the thread object running the command loop.
const Thread& thread() const { return thread_; }
//! Signal to start processing the commands in the queue.
void flush() {
ScopedLock sl(queueLock_);
queueLock_.notify();
}
//! Finish all queued commands
void finish();
//! Check if hostQueue empty snapshot
bool isEmpty();
//! Get virtual device for the current command queue
device::VirtualDevice* vdev() const { return thread_.vdev(); }
//! Return the current queue as the HostQueue
virtual HostQueue* asHostQueue() { return this; }
//! Get last enqueued command
Command* getLastQueuedCommand(bool retain);
//! Set last enqueued command
void setLastQueuedCommand(Command* lastCommand);
};
class DeviceQueue : public CommandQueue {
public:
DeviceQueue(Context& context, //!< Context object
Device& device, //!< Device object
cl_command_queue_properties properties, //!< Queue properties
uint size //!< Device queue size
)
: CommandQueue(context, device, properties, device.info().queueOnDeviceProperties_ |
CL_QUEUE_ON_DEVICE | CL_QUEUE_ON_DEVICE_DEFAULT),
size_(size),
virtualDevice_(NULL) {}
virtual ~DeviceQueue();
//! Returns TRUE if device queue was successfully created
virtual bool create();
//! Return the current queue as the DeviceQueue
virtual DeviceQueue* asDeviceQueue() { return this; }
//! Returns the size of device queue
uint size() const { return size_; }
//! Returns virtual device for this device queue
device::VirtualDevice* vDev() const { return virtualDevice_; }
//! Returns the queue lock
Monitor& lock() { return queueLock_; }
private:
uint size_; //!< Device queue size
device::VirtualDevice* virtualDevice_; //!< Virtual device for this queue
};
} // namespace amd
#endif // COMMAND_QUEUE_HPP_
<|endoftext|> |
<commit_before>#ifndef OPTIONAL_H
#define OPTIONAL_H
#include <type_traits>
namespace experimental {
template <typename T> class Optional
{
/**
* \brief The internal storage of size T and
* properly aligned on T.
*/
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
/**
* \brief Indicates whether the storage is
* initialized.
*/
bool mStored;
public:
/**
* \brief Object constructor.
*/
Optional() : mStored(false) {}
/**
* \constructor.
* \param v the object to store.
*/
Optional(const T& v) : mStored(true) {
new (&storage) T(v);
}
/**
* \brief Copy constructor.
*/
Optional(const Optional<T>& other)
: mStored(other.mStored) {
if (mStored) {
new (&storage) T(other.get());
}
}
/**
* \brief Move constructor.
*/
Optional(Optional<T>&& other)
: mStored(other.mStored) {
if (mStored) {
new (&storage) T(std::move(other.get()));
}
}
/**
* \brief Assignment operator.
*/
Optional& operator=(const Optional<T>& other) {
if (this != &other) {
return (*this);
}
if (mStored = other.mStored) {
new (&storage) T(other.get());
}
return (*this);
}
/**
* \brief Move assignment operator.
*/
Optional& operator=(Optional<T>&& other) {
if (this != &other) {
return (*this);
}
if (mStored = other.mStored) {
new (&storage) T(std::move(other.get()));
}
return (*this);
}
/**
* \brief Object destructor.
*/
~Optional() {
if (mStored) {
get().~T();
}
}
/**
* \return the currently stored optional value.
* \note This is the const version.
*/
T const& get() const {
return *static_cast<const T*>(static_cast<const void*>(&storage));
}
/**
* \return the currently stored optional value.
* \note This is the non-const version.
*/
T& get() {
return *static_cast<T*>(static_cast<void*>(&storage));
}
/**
* \return the currently stored session token if any,
* an empty string otherwise.
*/
explicit operator bool() const {
return (mStored);
}
};
};
#endif
<commit_msg>Remove white spaces<commit_after>#ifndef OPTIONAL_H
#define OPTIONAL_H
#include <type_traits>
namespace experimental {
template <typename T> class Optional
{
/**
* \brief The internal storage of size T and
* properly aligned on T.
*/
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
/**
* \brief Indicates whether the storage is
* initialized.
*/
bool mStored;
public:
/**
* \brief Object constructor.
*/
Optional() : mStored(false) {}
/**
* \constructor.
* \param v the object to store.
*/
Optional(const T& v) : mStored(true) {
new (&storage) T(v);
}
/**
* \brief Copy constructor.
*/
Optional(const Optional<T>& other)
: mStored(other.mStored) {
if (mStored) {
new (&storage) T(other.get());
}
}
/**
* \brief Move constructor.
*/
Optional(Optional<T>&& other)
: mStored(other.mStored) {
if (mStored) {
new (&storage) T(std::move(other.get()));
}
}
/**
* \brief Assignment operator.
*/
Optional& operator=(const Optional<T>& other) {
if (this != &other) {
return (*this);
}
if (mStored = other.mStored) {
new (&storage) T(other.get());
}
return (*this);
}
/**
* \brief Move assignment operator.
*/
Optional& operator=(Optional<T>&& other) {
if (this != &other) {
return (*this);
}
if (mStored = other.mStored) {
new (&storage) T(std::move(other.get()));
}
return (*this);
}
/**
* \brief Object destructor.
*/
~Optional() {
if (mStored) {
get().~T();
}
}
/**
* \return the currently stored optional value.
* \note This is the const version.
*/
T const& get() const {
return *static_cast<const T*>(static_cast<const void*>(&storage));
}
/**
* \return the currently stored optional value.
* \note This is the non-const version.
*/
T& get() {
return *static_cast<T*>(static_cast<void*>(&storage));
}
/**
* \return the currently stored session token if any,
* an empty string otherwise.
*/
explicit operator bool() const {
return (mStored);
}
};
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: scextopt.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2005-02-21 13:20:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_SCEXTOPT_HXX
#define SC_SCEXTOPT_HXX
#include <memory>
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
// ============================================================================
/** Extended settings for the document, used in import/export filters. */
struct ScExtDocSettings
{
ScRange maOleSize; /// Visible range if embedded.
String maGlobCodeName; /// Global codename (VBA module name).
double mfTabBarWidth; /// Width of the tabbar, relative to frame window width (0.0 ... 1.0).
sal_uInt32 mnLinkCnt; /// Recursive counter for loading external documents.
SCTAB mnDisplTab; /// Index of displayed sheet.
bool mbWinProtected; /// true = Window properties are protected.
bool mbEncrypted; /// true = Imported file was encrypted.
explicit ScExtDocSettings();
};
// ============================================================================
/** Enumerates possible positions of panes in split sheets. */
enum ScExtPanePos
{
SCEXT_PANE_TOPLEFT, /// Single, top, left, or top-left pane.
SCEXT_PANE_TOPRIGHT, /// Right, or top-right pane.
SCEXT_PANE_BOTTOMLEFT, /// Bottom, or bottom-left pane.
SCEXT_PANE_BOTTOMRIGHT /// Bottom-right pane.
};
// ----------------------------------------------------------------------------
/** Extended settings for a sheet, used in import/export filters. */
struct ScExtTabSettings
{
ScRange maUsedArea; /// Used area in the sheet (columns/rows only).
ScRangeList maSelection; /// Selected cell ranges (columns/rows only).
ScAddress maCursor; /// The cursor position (column/row only).
ScAddress maFirstVis; /// Top-left visible cell (column/row only).
ScAddress maSecondVis; /// Top-left visible cell in add. panes (column/row only).
ScAddress maFreezePos; /// Position of frozen panes (column/row only).
Point maSplitPos; /// Position of split.
ScExtPanePos meActivePane; /// Active (focused) pane.
Color maGridColor; /// Grid color.
long mnNormalZoom; /// Zoom in percent for normal view.
long mnPageZoom; /// Zoom in percent for pagebreak preview.
bool mbSelected; /// true = Sheet is selected.
bool mbFrozenPanes; /// true = Frozen panes; false = Normal splits.
bool mbPageMode; /// true = Pagebreak mode; false = Normal view mode.
explicit ScExtTabSettings();
};
// ============================================================================
struct ScExtDocOptionsImpl;
/** Extended options held by an ScDocument containing additional settings for filters.
This object is owned by a Calc document. It contains global document settings
(struct ScExtDocSettings), settings for all sheets in the document
(struct ScExtTabSettings), and a list of codenames used for VBA import/export.
*/
class ScExtDocOptions
{
public:
explicit ScExtDocOptions();
ScExtDocOptions( const ScExtDocOptions& rSrc );
~ScExtDocOptions();
ScExtDocOptions& operator=( const ScExtDocOptions& rSrc );
/** Returns true, if the data needs to be copied to the view data after import. */
bool IsChanged() const;
/** If set to true, the data will be copied to the view data after import. */
void SetChanged( bool bChanged );
/** Returns read access to the global document settings. */
const ScExtDocSettings& GetDocSettings() const;
/** Returns read/write access to the global document settings. */
ScExtDocSettings& GetDocSettings();
/** Returns read access to the settings of a sheet, if extant; otherwise 0. */
const ScExtTabSettings* GetTabSettings( SCTAB nTab ) const;
/** Returns read/write access to the settings of a sheet, may create a new struct. */
ScExtTabSettings& GetOrCreateTabSettings( SCTAB nTab );
/** Returns the number of sheet codenames. */
size_t GetCodeNameCount() const;
/** Returns the specified codename (empty string = no codename). */
const String& GetCodeName( size_t nIdx ) const;
/** Appends a codename for a sheet. */
void AppendCodeName( const String& rCodeName );
private:
::std::auto_ptr< ScExtDocOptionsImpl > mxImpl;
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.146); FILE MERGED 2005/09/05 15:00:56 rt 1.11.146.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scextopt.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:53:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
#ifndef SC_SCEXTOPT_HXX
#define SC_SCEXTOPT_HXX
#include <memory>
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
// ============================================================================
/** Extended settings for the document, used in import/export filters. */
struct ScExtDocSettings
{
ScRange maOleSize; /// Visible range if embedded.
String maGlobCodeName; /// Global codename (VBA module name).
double mfTabBarWidth; /// Width of the tabbar, relative to frame window width (0.0 ... 1.0).
sal_uInt32 mnLinkCnt; /// Recursive counter for loading external documents.
SCTAB mnDisplTab; /// Index of displayed sheet.
bool mbWinProtected; /// true = Window properties are protected.
bool mbEncrypted; /// true = Imported file was encrypted.
explicit ScExtDocSettings();
};
// ============================================================================
/** Enumerates possible positions of panes in split sheets. */
enum ScExtPanePos
{
SCEXT_PANE_TOPLEFT, /// Single, top, left, or top-left pane.
SCEXT_PANE_TOPRIGHT, /// Right, or top-right pane.
SCEXT_PANE_BOTTOMLEFT, /// Bottom, or bottom-left pane.
SCEXT_PANE_BOTTOMRIGHT /// Bottom-right pane.
};
// ----------------------------------------------------------------------------
/** Extended settings for a sheet, used in import/export filters. */
struct ScExtTabSettings
{
ScRange maUsedArea; /// Used area in the sheet (columns/rows only).
ScRangeList maSelection; /// Selected cell ranges (columns/rows only).
ScAddress maCursor; /// The cursor position (column/row only).
ScAddress maFirstVis; /// Top-left visible cell (column/row only).
ScAddress maSecondVis; /// Top-left visible cell in add. panes (column/row only).
ScAddress maFreezePos; /// Position of frozen panes (column/row only).
Point maSplitPos; /// Position of split.
ScExtPanePos meActivePane; /// Active (focused) pane.
Color maGridColor; /// Grid color.
long mnNormalZoom; /// Zoom in percent for normal view.
long mnPageZoom; /// Zoom in percent for pagebreak preview.
bool mbSelected; /// true = Sheet is selected.
bool mbFrozenPanes; /// true = Frozen panes; false = Normal splits.
bool mbPageMode; /// true = Pagebreak mode; false = Normal view mode.
explicit ScExtTabSettings();
};
// ============================================================================
struct ScExtDocOptionsImpl;
/** Extended options held by an ScDocument containing additional settings for filters.
This object is owned by a Calc document. It contains global document settings
(struct ScExtDocSettings), settings for all sheets in the document
(struct ScExtTabSettings), and a list of codenames used for VBA import/export.
*/
class ScExtDocOptions
{
public:
explicit ScExtDocOptions();
ScExtDocOptions( const ScExtDocOptions& rSrc );
~ScExtDocOptions();
ScExtDocOptions& operator=( const ScExtDocOptions& rSrc );
/** Returns true, if the data needs to be copied to the view data after import. */
bool IsChanged() const;
/** If set to true, the data will be copied to the view data after import. */
void SetChanged( bool bChanged );
/** Returns read access to the global document settings. */
const ScExtDocSettings& GetDocSettings() const;
/** Returns read/write access to the global document settings. */
ScExtDocSettings& GetDocSettings();
/** Returns read access to the settings of a sheet, if extant; otherwise 0. */
const ScExtTabSettings* GetTabSettings( SCTAB nTab ) const;
/** Returns read/write access to the settings of a sheet, may create a new struct. */
ScExtTabSettings& GetOrCreateTabSettings( SCTAB nTab );
/** Returns the number of sheet codenames. */
size_t GetCodeNameCount() const;
/** Returns the specified codename (empty string = no codename). */
const String& GetCodeName( size_t nIdx ) const;
/** Appends a codename for a sheet. */
void AppendCodeName( const String& rCodeName );
private:
::std::auto_ptr< ScExtDocOptionsImpl > mxImpl;
};
// ============================================================================
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/error.h>
#include "zorbaerrors/errors.h"
#include "zorbaerrors/error_messages.h"
namespace zorba { namespace error {
SERIALIZABLE_CLASS_VERSIONS(ZorbaError)
END_SERIALIZABLE_CLASS_VERSIONS(ZorbaError)
std::string
ZorbaError::toString(const XQUERY_ERROR& code)
{
return ErrorMessages::getNameForErrorCode(code);
}
ZorbaError::~ZorbaError()
{
}
void ZorbaError::free()
{
delete this;
}
ZorbaError::ZorbaError(
XQUERY_ERROR& aErrorCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(toString(aErrorCode)),
thePrefix("err"),
theNamespace(XQUERY_ERR_NS),
theErrorCode(aErrorCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber),
theDebug(false)
{
//+debug
//printf("ZorbaError(%s %s: %s %d)\n", theLocalName.c_str(), theDescription, theFileName.c_str(), aLineNumber);
}
ZorbaError::ZorbaError(
const xqpString& aErrLocalName,
const xqpString& aErrPrefix,
const xqpString& aErrNamespace,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(aErrLocalName),
thePrefix(aErrPrefix),
theNamespace(aErrNamespace),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber),
theDebug(false)
{
// compute err code from qname
if (aErrNamespace.getStore()->byteEqual(XQUERY_ERR_NS))
theErrorCode = ErrorMessages::getErrorCodeForName(aErrLocalName.getStore()->c_str());
else
theErrorCode = XQP0021_USER_ERROR;
//+debug
//printf("ZorbaError(%s %s: %s %d)\n", theLocalName.c_str(), theDescription, theFileName.c_str(), aLineNumber);
}
ZorbaError::ZorbaError(const ZorbaError& other)
:
::zorba::serialization::SerializeBaseClass(),
theLocalName(other.theLocalName),
thePrefix(other.thePrefix),
theNamespace(other.theNamespace),
theErrorCode(other.theErrorCode),
theDescription(other.theDescription),
theQueryLine(other.theQueryLine),
theQueryColumn(other.theQueryColumn),
theQueryFileName(other.theQueryFileName),
theFileName(other.theFileName),
theLineNumber(other.theLineNumber),
theDebug(other.theDebug)
{
}
void ZorbaError::setQueryLocation(
unsigned int line,
unsigned int column,
const std::string& filename)
{
theQueryLine = line;
theQueryColumn = column;
theQueryFileName = filename;
}
bool ZorbaError::hasQueryLocation()
{
return (theQueryFileName.empty() && theQueryLine == 0 && theQueryColumn == 0);
}
std::string ZorbaError::toString()
{
std::ostringstream strstream;
strstream << "Code : " << ErrorMessages::getNameForErrorCode(theErrorCode)
<< std::endl << "Description : " << theDescription << std::endl;
return strstream.str();
}
const xqpString& ZorbaError::localName() const
{
return theLocalName;
}
const xqpString& ZorbaError::ns() const
{
return theNamespace;
}
const xqpString&
ZorbaError::prefix() const
{
return thePrefix;
}
bool ZorbaError::isXPathStaticError() const
{
return (XPST0001 <= theErrorCode && theErrorCode <= XPST0083);
}
bool ZorbaError::isXPathDynamicError() const
{
return (XPDY0002 <= theErrorCode && theErrorCode <= XPDY0050);
}
bool ZorbaError::isXPathTypeError() const
{
return XPTY0004 <= theErrorCode && theErrorCode <= XPTY0020;
}
bool ZorbaError::isXQueryDynamicError() const
{
return ((XQDY0025 <= theErrorCode && theErrorCode <= XQDY0092) ||
XUDY0009 == theErrorCode ||
(XUDY0014 <= theErrorCode && theErrorCode <= XUDY0021) ||
(XUDY0023 <= theErrorCode && theErrorCode <= XUDY0025) ||
theErrorCode == XUDY0027 ||
theErrorCode == XUDY0029 ||
theErrorCode == XUDY0030 ||
theErrorCode == XUDY0031 ||
(XDDY0000_MIN <= theErrorCode && theErrorCode <= XDDY0000_MAX) ||
(XTDE1310 <= theErrorCode && theErrorCode <= XTDE1350));
}
bool ZorbaError::isXQueryStaticError() const
{
return ((XQST0009 <= theErrorCode && theErrorCode <= XQST0093) ||
(XUST0001 <= theErrorCode && theErrorCode <= XUST0003) ||
theErrorCode == XUST0028 ||
(XDST0000_MIN <= theErrorCode && theErrorCode <= XDST0000_MAX));
}
bool ZorbaError::isXQueryTypeError() const
{
return ((XQTY0023 <= theErrorCode && theErrorCode <= XQTY0086) ||
(XUTY0004 <= theErrorCode && theErrorCode <= XUTY0008) ||
(XUTY0010 <= theErrorCode && theErrorCode <= XUTY0013) ||
theErrorCode == XUTY0022 ||
theErrorCode == XDTY0001_COLLECTION_INVALID_NODE_TYPE);
}
bool ZorbaError::isFunctionError() const
{
return FOER0000 <= theErrorCode && theErrorCode <= FOUP0002;
}
bool ZorbaError::isSerializationError() const
{
return SENR0001 <= theErrorCode && theErrorCode <= SEPM0016;
}
bool ZorbaError::isInternalError() const
{
return XQP0000_DYNAMIC_RUNTIME_ERROR <= theErrorCode &&
theErrorCode <= MAX_ZORBA_ERROR_CODE;
}
bool ZorbaError::isStaticError() const
{
return isXPathStaticError() || isXQueryStaticError();
}
bool ZorbaError::isDynamicError() const
{
return isXPathDynamicError() || isXQueryDynamicError() || isFunctionError();
}
bool ZorbaError::isTypeError() const
{
return isXPathTypeError() || isXQueryTypeError();
}
std::auto_ptr<ZorbaError> ZorbaError::clone() const
{
std::auto_ptr<ZorbaError> err(new ZorbaError(*this));
return err;
}
ZorbaWarning::ZorbaWarning(
WarningCode aWarningCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theCode(aWarningCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
}
} /* namespace error */
} /* namespace zorba */
<commit_msg>Fix hasLocation method.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/error.h>
#include "zorbaerrors/errors.h"
#include "zorbaerrors/error_messages.h"
namespace zorba { namespace error {
SERIALIZABLE_CLASS_VERSIONS(ZorbaError)
END_SERIALIZABLE_CLASS_VERSIONS(ZorbaError)
std::string
ZorbaError::toString(const XQUERY_ERROR& code)
{
return ErrorMessages::getNameForErrorCode(code);
}
ZorbaError::~ZorbaError()
{
}
void ZorbaError::free()
{
delete this;
}
ZorbaError::ZorbaError(
XQUERY_ERROR& aErrorCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(toString(aErrorCode)),
thePrefix("err"),
theNamespace(XQUERY_ERR_NS),
theErrorCode(aErrorCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber),
theDebug(false)
{
//+debug
//printf("ZorbaError(%s %s: %s %d)\n", theLocalName.c_str(), theDescription, theFileName.c_str(), aLineNumber);
}
ZorbaError::ZorbaError(
const xqpString& aErrLocalName,
const xqpString& aErrPrefix,
const xqpString& aErrNamespace,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(aErrLocalName),
thePrefix(aErrPrefix),
theNamespace(aErrNamespace),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber),
theDebug(false)
{
// compute err code from qname
if (aErrNamespace.getStore()->byteEqual(XQUERY_ERR_NS))
theErrorCode = ErrorMessages::getErrorCodeForName(aErrLocalName.getStore()->c_str());
else
theErrorCode = XQP0021_USER_ERROR;
//+debug
//printf("ZorbaError(%s %s: %s %d)\n", theLocalName.c_str(), theDescription, theFileName.c_str(), aLineNumber);
}
ZorbaError::ZorbaError(const ZorbaError& other)
:
::zorba::serialization::SerializeBaseClass(),
theLocalName(other.theLocalName),
thePrefix(other.thePrefix),
theNamespace(other.theNamespace),
theErrorCode(other.theErrorCode),
theDescription(other.theDescription),
theQueryLine(other.theQueryLine),
theQueryColumn(other.theQueryColumn),
theQueryFileName(other.theQueryFileName),
theFileName(other.theFileName),
theLineNumber(other.theLineNumber),
theDebug(other.theDebug)
{
}
void ZorbaError::setQueryLocation(
unsigned int line,
unsigned int column,
const std::string& filename)
{
theQueryLine = line;
theQueryColumn = column;
theQueryFileName = filename;
}
bool ZorbaError::hasQueryLocation()
{
return !(theQueryFileName.empty() && theQueryLine == 0 &&
theQueryColumn == 0);
}
std::string ZorbaError::toString()
{
std::ostringstream strstream;
strstream << "Code : " << ErrorMessages::getNameForErrorCode(theErrorCode)
<< std::endl << "Description : " << theDescription << std::endl;
return strstream.str();
}
const xqpString& ZorbaError::localName() const
{
return theLocalName;
}
const xqpString& ZorbaError::ns() const
{
return theNamespace;
}
const xqpString&
ZorbaError::prefix() const
{
return thePrefix;
}
bool ZorbaError::isXPathStaticError() const
{
return (XPST0001 <= theErrorCode && theErrorCode <= XPST0083);
}
bool ZorbaError::isXPathDynamicError() const
{
return (XPDY0002 <= theErrorCode && theErrorCode <= XPDY0050);
}
bool ZorbaError::isXPathTypeError() const
{
return XPTY0004 <= theErrorCode && theErrorCode <= XPTY0020;
}
bool ZorbaError::isXQueryDynamicError() const
{
return ((XQDY0025 <= theErrorCode && theErrorCode <= XQDY0092) ||
XUDY0009 == theErrorCode ||
(XUDY0014 <= theErrorCode && theErrorCode <= XUDY0021) ||
(XUDY0023 <= theErrorCode && theErrorCode <= XUDY0025) ||
theErrorCode == XUDY0027 ||
theErrorCode == XUDY0029 ||
theErrorCode == XUDY0030 ||
theErrorCode == XUDY0031 ||
(XDDY0000_MIN <= theErrorCode && theErrorCode <= XDDY0000_MAX) ||
(XTDE1310 <= theErrorCode && theErrorCode <= XTDE1350));
}
bool ZorbaError::isXQueryStaticError() const
{
return ((XQST0009 <= theErrorCode && theErrorCode <= XQST0093) ||
(XUST0001 <= theErrorCode && theErrorCode <= XUST0003) ||
theErrorCode == XUST0028 ||
(XDST0000_MIN <= theErrorCode && theErrorCode <= XDST0000_MAX));
}
bool ZorbaError::isXQueryTypeError() const
{
return ((XQTY0023 <= theErrorCode && theErrorCode <= XQTY0086) ||
(XUTY0004 <= theErrorCode && theErrorCode <= XUTY0008) ||
(XUTY0010 <= theErrorCode && theErrorCode <= XUTY0013) ||
theErrorCode == XUTY0022 ||
theErrorCode == XDTY0001_COLLECTION_INVALID_NODE_TYPE);
}
bool ZorbaError::isFunctionError() const
{
return FOER0000 <= theErrorCode && theErrorCode <= FOUP0002;
}
bool ZorbaError::isSerializationError() const
{
return SENR0001 <= theErrorCode && theErrorCode <= SEPM0016;
}
bool ZorbaError::isInternalError() const
{
return XQP0000_DYNAMIC_RUNTIME_ERROR <= theErrorCode &&
theErrorCode <= MAX_ZORBA_ERROR_CODE;
}
bool ZorbaError::isStaticError() const
{
return isXPathStaticError() || isXQueryStaticError();
}
bool ZorbaError::isDynamicError() const
{
return isXPathDynamicError() || isXQueryDynamicError() || isFunctionError();
}
bool ZorbaError::isTypeError() const
{
return isXPathTypeError() || isXQueryTypeError();
}
std::auto_ptr<ZorbaError> ZorbaError::clone() const
{
std::auto_ptr<ZorbaError> err(new ZorbaError(*this));
return err;
}
ZorbaWarning::ZorbaWarning(
WarningCode aWarningCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theCode(aWarningCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
}
} /* namespace error */
} /* namespace zorba */
<|endoftext|> |
<commit_before>//===-- MipsISelDAGToDAG.cpp - A dag to dag inst selector for Mips --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the MIPS target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-isel"
#include "Mips.h"
#include "MipsMachineFunction.h"
#include "MipsRegisterInfo.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "llvm/GlobalValue.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Support/CFG.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Instruction Selector Implementation
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// MipsDAGToDAGISel - MIPS specific code to select MIPS machine
// instructions for SelectionDAG operations.
//===----------------------------------------------------------------------===//
namespace {
class MipsDAGToDAGISel : public SelectionDAGISel {
/// TM - Keep a reference to MipsTargetMachine.
MipsTargetMachine &TM;
/// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
/// make the right decision when generating code for different targets.
const MipsSubtarget &Subtarget;
public:
explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
SelectionDAGISel(tm),
TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
// Pass Name
virtual const char *getPassName() const {
return "MIPS DAG->DAG Pattern Instruction Selection";
}
private:
// Include the pieces autogenerated from the target description.
#include "MipsGenDAGISel.inc"
/// getTargetMachine - Return a reference to the TargetMachine, casted
/// to the target-specific type.
const MipsTargetMachine &getTargetMachine() {
return static_cast<const MipsTargetMachine &>(TM);
}
/// getInstrInfo - Return a reference to the TargetInstrInfo, casted
/// to the target-specific type.
const MipsInstrInfo *getInstrInfo() {
return getTargetMachine().getInstrInfo();
}
SDNode *getGlobalBaseReg();
SDNode *Select(SDNode *N);
// Complex Pattern.
bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset);
// getI32Imm - Return a target constant with the specified
// value, of type i32.
inline SDValue getI32Imm(unsigned Imm) {
return CurDAG->getTargetConstant(Imm, MVT::i32);
}
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
char ConstraintCode,
std::vector<SDValue> &OutOps);
};
}
/// getGlobalBaseReg - Output the instructions required to put the
/// GOT address into a register.
SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
}
/// ComplexPattern used on MipsInstrInfo
/// Used on Mips Load/Store instructions
bool MipsDAGToDAGISel::
SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
// if Address is FI, get the TargetFrameIndex.
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
Offset = CurDAG->getTargetConstant(0, MVT::i32);
return true;
}
// on PIC code Load GA
if (TM.getRelocationModel() == Reloc::PIC_) {
if (Addr.getOpcode() == MipsISD::WrapperPIC) {
Base = CurDAG->getRegister(Mips::GP, MVT::i32);
Offset = Addr.getOperand(0);
return true;
}
} else {
if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
Addr.getOpcode() == ISD::TargetGlobalAddress))
return false;
else if (Addr.getOpcode() == ISD::TargetGlobalTLSAddress) {
Base = CurDAG->getRegister(Mips::GP, MVT::i32);
Offset = Addr;
return true;
}
}
// Addresses of the form FI+const or FI|const
if (CurDAG->isBaseWithConstantOffset(Addr)) {
ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
if (isInt<16>(CN->getSExtValue())) {
// If the first operand is a FI, get the TargetFI Node
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
(Addr.getOperand(0)))
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
else
Base = Addr.getOperand(0);
Offset = CurDAG->getTargetConstant(CN->getZExtValue(), MVT::i32);
return true;
}
}
// Operand is a result from an ADD.
if (Addr.getOpcode() == ISD::ADD) {
// When loading from constant pools, load the lower address part in
// the instruction itself. Example, instead of:
// lui $2, %hi($CPI1_0)
// addiu $2, $2, %lo($CPI1_0)
// lwc1 $f0, 0($2)
// Generate:
// lui $2, %hi($CPI1_0)
// lwc1 $f0, %lo($CPI1_0)($2)
if ((Addr.getOperand(0).getOpcode() == MipsISD::Hi ||
Addr.getOperand(0).getOpcode() == ISD::LOAD) &&
Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
SDValue LoVal = Addr.getOperand(1);
if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||
isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
Base = Addr.getOperand(0);
Offset = LoVal.getOperand(0);
return true;
}
}
}
Base = Addr;
Offset = CurDAG->getTargetConstant(0, MVT::i32);
return true;
}
/// Select instructions not customized! Used for
/// expanded, promoted and normal instructions
SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
unsigned Opcode = Node->getOpcode();
DebugLoc dl = Node->getDebugLoc();
// Dump information about the Node being selected
DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
// If we have a custom node, we already have selected!
if (Node->isMachineOpcode()) {
DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
return NULL;
}
///
// Instruction Selection not handled by the auto-generated
// tablegen selection should be handled here.
///
switch(Opcode) {
default: break;
case ISD::SUBE:
case ISD::ADDE: {
SDValue InFlag = Node->getOperand(2), CmpLHS;
unsigned Opc = InFlag.getOpcode(); (void)Opc;
assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
(Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
"(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
unsigned MOp;
if (Opcode == ISD::ADDE) {
CmpLHS = InFlag.getValue(0);
MOp = Mips::ADDu;
} else {
CmpLHS = InFlag.getOperand(0);
MOp = Mips::SUBu;
}
SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
SDValue LHS = Node->getOperand(0);
SDValue RHS = Node->getOperand(1);
EVT VT = LHS.getValueType();
SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
SDValue(Carry,0), RHS);
return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
LHS, SDValue(AddCarry,0));
}
/// Mul with two results
case ISD::SMUL_LOHI:
case ISD::UMUL_LOHI: {
assert(Node->getValueType(0) != MVT::i64 &&
"64-bit multiplication with two results not handled.");
SDValue Op1 = Node->getOperand(0);
SDValue Op2 = Node->getOperand(1);
unsigned Op;
Op = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
SDNode *Mul = CurDAG->getMachineNode(Op, dl, MVT::Glue, Op1, Op2);
SDValue InFlag = SDValue(Mul, 0);
SDNode *Lo = CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32,
MVT::Glue, InFlag);
InFlag = SDValue(Lo,1);
SDNode *Hi = CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
if (!SDValue(Node, 0).use_empty())
ReplaceUses(SDValue(Node, 0), SDValue(Lo,0));
if (!SDValue(Node, 1).use_empty())
ReplaceUses(SDValue(Node, 1), SDValue(Hi,0));
return NULL;
}
/// Special Muls
case ISD::MUL:
// Mips32 has a 32-bit three operand mul instruction.
if (Subtarget.hasMips32() && Node->getValueType(0) == MVT::i32)
break;
case ISD::MULHS:
case ISD::MULHU: {
assert((Opcode == ISD::MUL || Node->getValueType(0) != MVT::i64) &&
"64-bit MULH* not handled.");
EVT Ty = Node->getValueType(0);
SDValue MulOp1 = Node->getOperand(0);
SDValue MulOp2 = Node->getOperand(1);
unsigned MulOp = (Opcode == ISD::MULHU ?
Mips::MULTu :
(Ty == MVT::i32 ? Mips::MULT : Mips::DMULT));
SDNode *MulNode = CurDAG->getMachineNode(MulOp, dl,
MVT::Glue, MulOp1, MulOp2);
SDValue InFlag = SDValue(MulNode, 0);
if (Opcode == ISD::MUL) {
unsigned Opc = (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64);
return CurDAG->getMachineNode(Opc, dl, Ty, InFlag);
}
else
return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
}
// Get target GOT address.
case ISD::GLOBAL_OFFSET_TABLE:
return getGlobalBaseReg();
case ISD::ConstantFP: {
ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
Mips::ZERO, MVT::i32);
return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
Zero);
}
break;
}
case MipsISD::ThreadPointer: {
unsigned SrcReg = Mips::HWR29;
unsigned DestReg = Mips::V1;
SDNode *Rdhwr = CurDAG->getMachineNode(Mips::RDHWR, Node->getDebugLoc(),
Node->getValueType(0), CurDAG->getRegister(SrcReg, MVT::i32));
SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
SDValue(Rdhwr, 0));
SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, MVT::i32);
ReplaceUses(SDValue(Node, 0), ResNode);
return ResNode.getNode();
}
}
// Select the default instruction
SDNode *ResNode = SelectCode(Node);
DEBUG(errs() << "=> ");
if (ResNode == NULL || ResNode == Node)
DEBUG(Node->dump(CurDAG));
else
DEBUG(ResNode->dump(CurDAG));
DEBUG(errs() << "\n");
return ResNode;
}
bool MipsDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
std::vector<SDValue> &OutOps) {
assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
OutOps.push_back(Op);
return false;
}
/// createMipsISelDag - This pass converts a legalized DAG into a
/// MIPS-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
return new MipsDAGToDAGISel(TM);
}
<commit_msg>Modify MipsDAGToDAGISel::SelectAddr so that it can handle 64-bit pointers too.<commit_after>//===-- MipsISelDAGToDAG.cpp - A dag to dag inst selector for Mips --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the MIPS target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-isel"
#include "Mips.h"
#include "MipsMachineFunction.h"
#include "MipsRegisterInfo.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "llvm/GlobalValue.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Support/CFG.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Instruction Selector Implementation
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// MipsDAGToDAGISel - MIPS specific code to select MIPS machine
// instructions for SelectionDAG operations.
//===----------------------------------------------------------------------===//
namespace {
class MipsDAGToDAGISel : public SelectionDAGISel {
/// TM - Keep a reference to MipsTargetMachine.
MipsTargetMachine &TM;
/// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
/// make the right decision when generating code for different targets.
const MipsSubtarget &Subtarget;
public:
explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
SelectionDAGISel(tm),
TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
// Pass Name
virtual const char *getPassName() const {
return "MIPS DAG->DAG Pattern Instruction Selection";
}
private:
// Include the pieces autogenerated from the target description.
#include "MipsGenDAGISel.inc"
/// getTargetMachine - Return a reference to the TargetMachine, casted
/// to the target-specific type.
const MipsTargetMachine &getTargetMachine() {
return static_cast<const MipsTargetMachine &>(TM);
}
/// getInstrInfo - Return a reference to the TargetInstrInfo, casted
/// to the target-specific type.
const MipsInstrInfo *getInstrInfo() {
return getTargetMachine().getInstrInfo();
}
SDNode *getGlobalBaseReg();
SDNode *Select(SDNode *N);
// Complex Pattern.
bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset);
// getI32Imm - Return a target constant with the specified
// value, of type i32.
inline SDValue getI32Imm(unsigned Imm) {
return CurDAG->getTargetConstant(Imm, MVT::i32);
}
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
char ConstraintCode,
std::vector<SDValue> &OutOps);
};
}
/// getGlobalBaseReg - Output the instructions required to put the
/// GOT address into a register.
SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
}
/// ComplexPattern used on MipsInstrInfo
/// Used on Mips Load/Store instructions
bool MipsDAGToDAGISel::
SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
EVT ValTy = Addr.getValueType();
unsigned GPReg = ValTy == MVT::i32 ? Mips::GP : Mips::GP_64;
// if Address is FI, get the TargetFrameIndex.
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
Offset = CurDAG->getTargetConstant(0, ValTy);
return true;
}
// on PIC code Load GA
if (TM.getRelocationModel() == Reloc::PIC_) {
if (Addr.getOpcode() == MipsISD::WrapperPIC) {
Base = CurDAG->getRegister(GPReg, ValTy);
Offset = Addr.getOperand(0);
return true;
}
} else {
if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
Addr.getOpcode() == ISD::TargetGlobalAddress))
return false;
else if (Addr.getOpcode() == ISD::TargetGlobalTLSAddress) {
Base = CurDAG->getRegister(GPReg, ValTy);
Offset = Addr;
return true;
}
}
// Addresses of the form FI+const or FI|const
if (CurDAG->isBaseWithConstantOffset(Addr)) {
ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
if (isInt<16>(CN->getSExtValue())) {
// If the first operand is a FI, get the TargetFI Node
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
(Addr.getOperand(0)))
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
else
Base = Addr.getOperand(0);
Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
return true;
}
}
// Operand is a result from an ADD.
if (Addr.getOpcode() == ISD::ADD) {
// When loading from constant pools, load the lower address part in
// the instruction itself. Example, instead of:
// lui $2, %hi($CPI1_0)
// addiu $2, $2, %lo($CPI1_0)
// lwc1 $f0, 0($2)
// Generate:
// lui $2, %hi($CPI1_0)
// lwc1 $f0, %lo($CPI1_0)($2)
if ((Addr.getOperand(0).getOpcode() == MipsISD::Hi ||
Addr.getOperand(0).getOpcode() == ISD::LOAD) &&
Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
SDValue LoVal = Addr.getOperand(1);
if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||
isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
Base = Addr.getOperand(0);
Offset = LoVal.getOperand(0);
return true;
}
}
}
Base = Addr;
Offset = CurDAG->getTargetConstant(0, ValTy);
return true;
}
/// Select instructions not customized! Used for
/// expanded, promoted and normal instructions
SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
unsigned Opcode = Node->getOpcode();
DebugLoc dl = Node->getDebugLoc();
// Dump information about the Node being selected
DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
// If we have a custom node, we already have selected!
if (Node->isMachineOpcode()) {
DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
return NULL;
}
///
// Instruction Selection not handled by the auto-generated
// tablegen selection should be handled here.
///
switch(Opcode) {
default: break;
case ISD::SUBE:
case ISD::ADDE: {
SDValue InFlag = Node->getOperand(2), CmpLHS;
unsigned Opc = InFlag.getOpcode(); (void)Opc;
assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
(Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
"(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
unsigned MOp;
if (Opcode == ISD::ADDE) {
CmpLHS = InFlag.getValue(0);
MOp = Mips::ADDu;
} else {
CmpLHS = InFlag.getOperand(0);
MOp = Mips::SUBu;
}
SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
SDValue LHS = Node->getOperand(0);
SDValue RHS = Node->getOperand(1);
EVT VT = LHS.getValueType();
SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
SDValue(Carry,0), RHS);
return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
LHS, SDValue(AddCarry,0));
}
/// Mul with two results
case ISD::SMUL_LOHI:
case ISD::UMUL_LOHI: {
assert(Node->getValueType(0) != MVT::i64 &&
"64-bit multiplication with two results not handled.");
SDValue Op1 = Node->getOperand(0);
SDValue Op2 = Node->getOperand(1);
unsigned Op;
Op = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
SDNode *Mul = CurDAG->getMachineNode(Op, dl, MVT::Glue, Op1, Op2);
SDValue InFlag = SDValue(Mul, 0);
SDNode *Lo = CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32,
MVT::Glue, InFlag);
InFlag = SDValue(Lo,1);
SDNode *Hi = CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
if (!SDValue(Node, 0).use_empty())
ReplaceUses(SDValue(Node, 0), SDValue(Lo,0));
if (!SDValue(Node, 1).use_empty())
ReplaceUses(SDValue(Node, 1), SDValue(Hi,0));
return NULL;
}
/// Special Muls
case ISD::MUL:
// Mips32 has a 32-bit three operand mul instruction.
if (Subtarget.hasMips32() && Node->getValueType(0) == MVT::i32)
break;
case ISD::MULHS:
case ISD::MULHU: {
assert((Opcode == ISD::MUL || Node->getValueType(0) != MVT::i64) &&
"64-bit MULH* not handled.");
EVT Ty = Node->getValueType(0);
SDValue MulOp1 = Node->getOperand(0);
SDValue MulOp2 = Node->getOperand(1);
unsigned MulOp = (Opcode == ISD::MULHU ?
Mips::MULTu :
(Ty == MVT::i32 ? Mips::MULT : Mips::DMULT));
SDNode *MulNode = CurDAG->getMachineNode(MulOp, dl,
MVT::Glue, MulOp1, MulOp2);
SDValue InFlag = SDValue(MulNode, 0);
if (Opcode == ISD::MUL) {
unsigned Opc = (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64);
return CurDAG->getMachineNode(Opc, dl, Ty, InFlag);
}
else
return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
}
// Get target GOT address.
case ISD::GLOBAL_OFFSET_TABLE:
return getGlobalBaseReg();
case ISD::ConstantFP: {
ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
Mips::ZERO, MVT::i32);
return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
Zero);
}
break;
}
case MipsISD::ThreadPointer: {
unsigned SrcReg = Mips::HWR29;
unsigned DestReg = Mips::V1;
SDNode *Rdhwr = CurDAG->getMachineNode(Mips::RDHWR, Node->getDebugLoc(),
Node->getValueType(0), CurDAG->getRegister(SrcReg, MVT::i32));
SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
SDValue(Rdhwr, 0));
SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, MVT::i32);
ReplaceUses(SDValue(Node, 0), ResNode);
return ResNode.getNode();
}
}
// Select the default instruction
SDNode *ResNode = SelectCode(Node);
DEBUG(errs() << "=> ");
if (ResNode == NULL || ResNode == Node)
DEBUG(Node->dump(CurDAG));
else
DEBUG(ResNode->dump(CurDAG));
DEBUG(errs() << "\n");
return ResNode;
}
bool MipsDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
std::vector<SDValue> &OutOps) {
assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
OutOps.push_back(Op);
return false;
}
/// createMipsISelDag - This pass converts a legalized DAG into a
/// MIPS-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
return new MipsDAGToDAGISel(TM);
}
<|endoftext|> |
<commit_before>#ifndef DETAIL_DETECT_ARCHITECTURE_H
#define DETAIL_DETECT_ARCHITECTURE_H
//for reference see: https://sourceforge.net/p/predef/wiki/Architectures/
#define COMPASS_CT_ARCH_UNSUPPORTED
#if (defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64))
#define COMPASS_CT_ARCH_X86
#define COMPASS_CT_ARCH_64BITS
#undef COMPASS_CT_ARCH_UNSUPPORTED
#endif
#if (defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(__M_I86) || defined(_M_IX86))
#define COMPASS_CT_ARCH_X86
#undef COMPASS_CT_ARCH_UNSUPPORTED
#endif
#if (defined(__powerpc64__) || defined(_ARCH_PPC64) || defined(__ppc64__))
#define COMPASS_CT_ARCH_POWER
#define COMPASS_CT_ARCH_64BITS
#undef COMPASS_CT_ARCH_UNSUPPORTED
#endif
#if (defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) || defined(__PPC__) || defined(__ppc__))
#define COMPASS_CT_ARCH_POWER
#undef COMPASS_CT_ARCH_UNSUPPORTED
#endif
#include "detail/definitions.hpp"
#include <climits> //for CHAR_BIT
namespace compass {
namespace compiletime {
//architectures
struct x86_tag {};
struct arm_tag {};
struct power_tag {};
struct arch {
#ifdef COMPASS_CT_ARCH_X86
typedef x86_tag type;
#endif
#ifdef COMPASS_CT_ARCH_UNSUPPORTED
typedef unsupported_tag type;
static_assert(std::is_same<compass::ct::arch::type,compass::ct::unsupported_tag>::value,
"\n\ncompass is not aware of this architecture \nPlease create an issue under https://github.com/psteinb/compass\n\n");
#endif
//32 or 64bit?
const static int bitness = sizeof(void*)*CHAR_BIT;
};
} // compiletime
} // compass
#endif /* DETAIL_DETECT_ARCHITECTURE_H */
<commit_msg>added pcpp specific if clause<commit_after>#ifndef DETAIL_DETECT_ARCHITECTURE_H
#define DETAIL_DETECT_ARCHITECTURE_H
#if !__PCPP_ALWAYS_TRUE__ // Always execute except on pcpp
#define COMPASS_CT_ARCH_UNSUPPORTED
#endif
//for reference see: https://sourceforge.net/p/predef/wiki/Architectures/
#if (defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64))
#define COMPASS_CT_ARCH_X86
#define COMPASS_CT_ARCH_64BITS
#undef COMPASS_CT_ARCH_UNSUPPORTED
#endif
#if (defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(__M_I86) || defined(_M_IX86))
#define COMPASS_CT_ARCH_X86
#undef COMPASS_CT_ARCH_UNSUPPORTED
#endif
#if (defined(__powerpc64__) || defined(_ARCH_PPC64) || defined(__ppc64__))
#define COMPASS_CT_ARCH_POWER
#define COMPASS_CT_ARCH_64BITS
#define COMPASS_CT_ARCH_UNSUPPORTED //undef if support comes in this library
#endif
#if (defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) || defined(__PPC__) || defined(__ppc__))
#define COMPASS_CT_ARCH_POWER
#define COMPASS_CT_ARCH_UNSUPPORTED //undef if support lands in this library
#endif
#include "detail/definitions.hpp"
#include <climits> //for CHAR_BIT
namespace compass {
namespace compiletime {
//architectures
struct x86_tag {};
struct arm_tag {};
struct power_tag {};
struct arch {
#ifdef COMPASS_CT_ARCH_X86
typedef x86_tag type;
#endif
#ifdef COMPASS_CT_ARCH_UNSUPPORTED
typedef unsupported_tag type;
static_assert(std::is_same<compass::ct::arch::type,compass::ct::unsupported_tag>::value,
"\n\ncompass is not aware of this architecture \nPlease create an issue under https://github.com/psteinb/compass\n\n");
#endif
//32 or 64bit?
const static int bitness = sizeof(void*)*CHAR_BIT;
};
} // compiletime
} // compass
#endif /* DETAIL_DETECT_ARCHITECTURE_H */
<|endoftext|> |
<commit_before>/* -*- C++ -*-
* (c) 2004 Helge Bahmann <hcb@chaoticmind.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* Refer to the file "COPYING" for details.
*/
#include <boost/bind.hpp>
#include <boost/intrusive_ptr.hpp>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <tscb/ref>
#include <tscb/atomic>
#include <tscb/ioready>
class echo {
public:
echo(tscb::ioready_service *service, int _fd);
~echo(void);
inline void pin(void) {refcount++;}
inline void release(void) {if (!--refcount) delete this;}
tscb::atomic refcount;
private:
void data(int event);
void destroy(void);
int fd;
tscb::ioready_callback link;
tscb::ioready_service *service;
};
static inline void intrusive_ptr_add_ref(echo *e) throw()
{
e->refcount++;
}
static inline void intrusive_ptr_release(echo *e) throw()
{
if (!--e->refcount) delete e;
}
class acceptor {
public:
acceptor(tscb::ioready_service *service, int _fd);
tscb::atomic refcount;
private:
void connection_request(int event);
int fd;
tscb::ioready_callback link;
tscb::ioready_service *service;
};
static inline void intrusive_ptr_add_ref(acceptor *a) throw()
{
a->refcount++;
}
static inline void intrusive_ptr_release(acceptor *a) throw()
{
if (!--a->refcount) delete a;
}
echo::echo(tscb::ioready_service *_service, int _fd)
: fd(_fd), service(_service)
{
int flags=fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
link=service->watch(boost::bind(&echo::data, boost::intrusive_ptr<echo>(this), _1),
fd, tscb::EVMASK_INPUT);
//link=service->watch<echo, &echo::data, &echo::destroy>
// (fd, tscb::EVMASK_INPUT, this);
}
echo::~echo(void)
{
printf("connection closed\n");
close(fd);
}
void echo::data(int event)
{
char buffer[16384];
int n;
do {
n=read(fd, buffer, 16384);
if (n<0) {
if ((errno=EAGAIN)) break;
}
if (n<=0) {
printf("connection closed by client\n");
link->cancel();
break;
}
write(1, buffer, n);
write(fd, buffer, n);
} while(n==16384);
}
acceptor::acceptor(tscb::ioready_service *_service, int _fd)
: fd(_fd), service(_service)
{
int flags=fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
link=service->watch(boost::bind(&acceptor::connection_request,
boost::intrusive_ptr<acceptor>(this), _1), fd, tscb::EVMASK_INPUT);
}
void acceptor::connection_request(int event)
{
int s;
s=accept(fd, 0, 0);
while(s>=0) {
new echo(service, s);
s=accept(fd, 0, 0);
}
}
int main(int argc, char **argv)
{
int sock;
int reuse_flag=1;
struct sockaddr_in addr;
sock=socket(PF_INET, SOCK_STREAM, 0);
addr.sin_family=AF_INET;
addr.sin_port=htons(1234);
addr.sin_addr.s_addr=inet_addr("0.0.0.0");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_flag, sizeof(reuse_flag));
bind(sock, (struct sockaddr *)&addr, sizeof(addr));
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_flag, sizeof(reuse_flag));
listen(sock, 25);
tscb::ioready_dispatcher *dispatcher=tscb::create_ioready_dispatcher();
new acceptor(dispatcher, sock);
while(true) {
dispatcher->dispatch(0);
}
return 0;
}
<commit_msg>Fix embarassing "assignment instead of comparison" typo<commit_after>/* -*- C++ -*-
* (c) 2004 Helge Bahmann <hcb@chaoticmind.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* Refer to the file "COPYING" for details.
*/
#include <boost/bind.hpp>
#include <boost/intrusive_ptr.hpp>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <tscb/ref>
#include <tscb/atomic>
#include <tscb/ioready>
class echo {
public:
echo(tscb::ioready_service *service, int _fd);
~echo(void);
inline void pin(void) {refcount++;}
inline void release(void) {if (!--refcount) delete this;}
tscb::atomic refcount;
private:
void data(int event);
void destroy(void);
int fd;
tscb::ioready_callback link;
tscb::ioready_service *service;
};
static inline void intrusive_ptr_add_ref(echo *e) throw()
{
e->refcount++;
}
static inline void intrusive_ptr_release(echo *e) throw()
{
if (!--e->refcount) delete e;
}
class acceptor {
public:
acceptor(tscb::ioready_service *service, int _fd);
tscb::atomic refcount;
private:
void connection_request(int event);
int fd;
tscb::ioready_callback link;
tscb::ioready_service *service;
};
static inline void intrusive_ptr_add_ref(acceptor *a) throw()
{
a->refcount++;
}
static inline void intrusive_ptr_release(acceptor *a) throw()
{
if (!--a->refcount) delete a;
}
echo::echo(tscb::ioready_service *_service, int _fd)
: fd(_fd), service(_service)
{
int flags=fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
link=service->watch(boost::bind(&echo::data, boost::intrusive_ptr<echo>(this), _1),
fd, tscb::EVMASK_INPUT);
//link=service->watch<echo, &echo::data, &echo::destroy>
// (fd, tscb::EVMASK_INPUT, this);
}
echo::~echo(void)
{
printf("connection closed\n");
close(fd);
}
void echo::data(int event)
{
char buffer[16384];
int n;
do {
n=read(fd, buffer, 16384);
if (n<0) {
if (errno==EAGAIN) break;
}
if (n<=0) {
printf("connection closed by client\n");
link->cancel();
break;
}
write(1, buffer, n);
write(fd, buffer, n);
} while(n==16384);
}
acceptor::acceptor(tscb::ioready_service *_service, int _fd)
: fd(_fd), service(_service)
{
int flags=fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
link=service->watch(boost::bind(&acceptor::connection_request,
boost::intrusive_ptr<acceptor>(this), _1), fd, tscb::EVMASK_INPUT);
}
void acceptor::connection_request(int event)
{
int s;
s=accept(fd, 0, 0);
while(s>=0) {
new echo(service, s);
s=accept(fd, 0, 0);
}
}
int main(int argc, char **argv)
{
int sock;
int reuse_flag=1;
struct sockaddr_in addr;
sock=socket(PF_INET, SOCK_STREAM, 0);
addr.sin_family=AF_INET;
addr.sin_port=htons(1234);
addr.sin_addr.s_addr=inet_addr("0.0.0.0");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_flag, sizeof(reuse_flag));
bind(sock, (struct sockaddr *)&addr, sizeof(addr));
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_flag, sizeof(reuse_flag));
listen(sock, 25);
tscb::ioready_dispatcher *dispatcher=tscb::create_ioready_dispatcher();
new acceptor(dispatcher, sock);
while(true) {
dispatcher->dispatch(0);
}
return 0;
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/trace_reader.h"
#include <cinttypes>
#include "third_party/snappy/snappy.h"
#include "xenia/base/logging.h"
#include "xenia/base/mapped_memory.h"
#include "xenia/base/math.h"
#include "xenia/gpu/packet_disassembler.h"
#include "xenia/gpu/trace_protocol.h"
#include "xenia/memory.h"
namespace xe {
namespace gpu {
bool TraceReader::Open(const std::wstring& path) {
Close();
mmap_ = MappedMemory::Open(path, MappedMemory::Mode::kRead);
if (!mmap_) {
return false;
}
trace_data_ = reinterpret_cast<const uint8_t*>(mmap_->data());
trace_size_ = mmap_->size();
// Verify version.
auto header = reinterpret_cast<const TraceHeader*>(trace_data_);
if (header->version != kTraceFormatVersion) {
XELOGE("Trace format version mismatch, code has %u, file has %u",
kTraceFormatVersion, header->version);
if (header->version < kTraceFormatVersion) {
XELOGE("You need to regenerate your trace for the latest version");
}
return false;
}
auto path_str = xe::to_string(path);
XELOGI("Mapped %" PRId64 "b trace from %s", trace_size_, path_str.c_str());
XELOGI(" Version: %u", header->version);
auto commit_str = std::string(header->build_commit_sha,
xe::countof(header->build_commit_sha));
XELOGI(" Commit: %s", commit_str.c_str());
XELOGI(" Title ID: %u", header->title_id);
ParseTrace();
return true;
}
void TraceReader::Close() {
mmap_.reset();
trace_data_ = nullptr;
trace_size_ = 0;
}
void TraceReader::ParseTrace() {
// Skip file header.
auto trace_ptr = trace_data_;
trace_ptr += sizeof(TraceHeader);
Frame current_frame;
current_frame.start_ptr = trace_ptr;
const PacketStartCommand* packet_start = nullptr;
const uint8_t* packet_start_ptr = nullptr;
const uint8_t* last_ptr = trace_ptr;
bool pending_break = false;
auto current_command_buffer = new CommandBuffer();
current_frame.command_tree =
std::unique_ptr<CommandBuffer>(current_command_buffer);
while (trace_ptr < trace_data_ + trace_size_) {
++current_frame.command_count;
auto type = static_cast<TraceCommandType>(xe::load<uint32_t>(trace_ptr));
switch (type) {
case TraceCommandType::kPrimaryBufferStart: {
auto cmd =
reinterpret_cast<const PrimaryBufferStartCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->count * 4;
break;
}
case TraceCommandType::kPrimaryBufferEnd: {
auto cmd = reinterpret_cast<const PrimaryBufferEndCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
break;
}
case TraceCommandType::kIndirectBufferStart: {
auto cmd =
reinterpret_cast<const IndirectBufferStartCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->count * 4;
// Traverse down a level.
auto sub_command_buffer = new CommandBuffer();
sub_command_buffer->parent = current_command_buffer;
current_command_buffer->commands.push_back(
CommandBuffer::Command(sub_command_buffer));
current_command_buffer = sub_command_buffer;
break;
}
case TraceCommandType::kIndirectBufferEnd: {
auto cmd = reinterpret_cast<const IndirectBufferEndCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
// Go back up a level. If parent is null, this frame started in an
// indirect buffer.
if (current_command_buffer->parent) {
current_command_buffer = current_command_buffer->parent;
}
break;
}
case TraceCommandType::kPacketStart: {
auto cmd = reinterpret_cast<const PacketStartCommand*>(trace_ptr);
packet_start_ptr = trace_ptr;
packet_start = cmd;
trace_ptr += sizeof(*cmd) + cmd->count * 4;
break;
}
case TraceCommandType::kPacketEnd: {
auto cmd = reinterpret_cast<const PacketEndCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
if (!packet_start_ptr) {
continue;
}
auto packet_category = PacketDisassembler::GetPacketCategory(
packet_start_ptr + sizeof(*packet_start));
switch (packet_category) {
case PacketCategory::kDraw: {
Frame::Command command;
command.type = Frame::Command::Type::kDraw;
command.head_ptr = packet_start_ptr;
command.start_ptr = last_ptr;
command.end_ptr = trace_ptr;
current_frame.commands.push_back(std::move(command));
last_ptr = trace_ptr;
current_command_buffer->commands.push_back(CommandBuffer::Command(
uint32_t(current_frame.commands.size() - 1)));
break;
}
case PacketCategory::kSwap:
case PacketCategory::kGeneric: {
// Ignored.
break;
}
}
if (pending_break) {
current_frame.end_ptr = trace_ptr;
frames_.push_back(std::move(current_frame));
current_command_buffer = new CommandBuffer();
current_frame.command_tree =
std::unique_ptr<CommandBuffer>(current_command_buffer);
current_frame.start_ptr = trace_ptr;
current_frame.end_ptr = nullptr;
current_frame.command_count = 0;
pending_break = false;
}
break;
}
case TraceCommandType::kMemoryRead: {
auto cmd = reinterpret_cast<const MemoryCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->encoded_length;
break;
}
case TraceCommandType::kMemoryWrite: {
auto cmd = reinterpret_cast<const MemoryCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->encoded_length;
break;
}
case TraceCommandType::kEvent: {
auto cmd = reinterpret_cast<const EventCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
switch (cmd->event_type) {
case EventCommand::Type::kSwap: {
pending_break = true;
break;
}
}
break;
}
default:
// Broken trace file?
assert_unhandled_case(type);
break;
}
}
if (pending_break || current_frame.command_count) {
current_frame.end_ptr = trace_ptr;
frames_.push_back(std::move(current_frame));
}
}
bool TraceReader::DecompressMemory(MemoryEncodingFormat encoding_format,
const uint8_t* src, size_t src_size,
uint8_t* dest, size_t dest_size) {
switch (encoding_format) {
case MemoryEncodingFormat::kNone:
assert_true(src_size == dest_size);
std::memcpy(dest, src, src_size);
return true;
case MemoryEncodingFormat::kSnappy:
return snappy::RawUncompress(reinterpret_cast<const char*>(src), src_size,
reinterpret_cast<char*>(dest));
default:
assert_unhandled_case(encoding_format);
return false;
}
}
} // namespace gpu
} // namespace xe
<commit_msg>Skip the wrapping packet end after parsing IB end (to avoid false draws appearing)<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/trace_reader.h"
#include <cinttypes>
#include "third_party/snappy/snappy.h"
#include "xenia/base/logging.h"
#include "xenia/base/mapped_memory.h"
#include "xenia/base/math.h"
#include "xenia/gpu/packet_disassembler.h"
#include "xenia/gpu/trace_protocol.h"
#include "xenia/memory.h"
namespace xe {
namespace gpu {
bool TraceReader::Open(const std::wstring& path) {
Close();
mmap_ = MappedMemory::Open(path, MappedMemory::Mode::kRead);
if (!mmap_) {
return false;
}
trace_data_ = reinterpret_cast<const uint8_t*>(mmap_->data());
trace_size_ = mmap_->size();
// Verify version.
auto header = reinterpret_cast<const TraceHeader*>(trace_data_);
if (header->version != kTraceFormatVersion) {
XELOGE("Trace format version mismatch, code has %u, file has %u",
kTraceFormatVersion, header->version);
if (header->version < kTraceFormatVersion) {
XELOGE("You need to regenerate your trace for the latest version");
}
return false;
}
auto path_str = xe::to_string(path);
XELOGI("Mapped %" PRId64 "b trace from %s", trace_size_, path_str.c_str());
XELOGI(" Version: %u", header->version);
auto commit_str = std::string(header->build_commit_sha,
xe::countof(header->build_commit_sha));
XELOGI(" Commit: %s", commit_str.c_str());
XELOGI(" Title ID: %u", header->title_id);
ParseTrace();
return true;
}
void TraceReader::Close() {
mmap_.reset();
trace_data_ = nullptr;
trace_size_ = 0;
}
void TraceReader::ParseTrace() {
// Skip file header.
auto trace_ptr = trace_data_;
trace_ptr += sizeof(TraceHeader);
Frame current_frame;
current_frame.start_ptr = trace_ptr;
const PacketStartCommand* packet_start = nullptr;
const uint8_t* packet_start_ptr = nullptr;
const uint8_t* last_ptr = trace_ptr;
bool pending_break = false;
auto current_command_buffer = new CommandBuffer();
current_frame.command_tree =
std::unique_ptr<CommandBuffer>(current_command_buffer);
while (trace_ptr < trace_data_ + trace_size_) {
++current_frame.command_count;
auto type = static_cast<TraceCommandType>(xe::load<uint32_t>(trace_ptr));
switch (type) {
case TraceCommandType::kPrimaryBufferStart: {
auto cmd =
reinterpret_cast<const PrimaryBufferStartCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->count * 4;
break;
}
case TraceCommandType::kPrimaryBufferEnd: {
auto cmd = reinterpret_cast<const PrimaryBufferEndCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
break;
}
case TraceCommandType::kIndirectBufferStart: {
auto cmd =
reinterpret_cast<const IndirectBufferStartCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->count * 4;
// Traverse down a level.
auto sub_command_buffer = new CommandBuffer();
sub_command_buffer->parent = current_command_buffer;
current_command_buffer->commands.push_back(
CommandBuffer::Command(sub_command_buffer));
current_command_buffer = sub_command_buffer;
break;
}
case TraceCommandType::kIndirectBufferEnd: {
auto cmd = reinterpret_cast<const IndirectBufferEndCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
// IB packet is wrapped in a kPacketStart/kPacketEnd. Skip the end.
auto end_cmd = reinterpret_cast<const PacketEndCommand*>(trace_ptr);
assert_true(end_cmd->type == TraceCommandType::kPacketEnd);
trace_ptr += sizeof(*cmd);
// Go back up a level. If parent is null, this frame started in an
// indirect buffer.
if (current_command_buffer->parent) {
current_command_buffer = current_command_buffer->parent;
}
break;
}
case TraceCommandType::kPacketStart: {
auto cmd = reinterpret_cast<const PacketStartCommand*>(trace_ptr);
packet_start_ptr = trace_ptr;
packet_start = cmd;
trace_ptr += sizeof(*cmd) + cmd->count * 4;
break;
}
case TraceCommandType::kPacketEnd: {
auto cmd = reinterpret_cast<const PacketEndCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
if (!packet_start_ptr) {
continue;
}
auto packet_category = PacketDisassembler::GetPacketCategory(
packet_start_ptr + sizeof(*packet_start));
switch (packet_category) {
case PacketCategory::kDraw: {
Frame::Command command;
command.type = Frame::Command::Type::kDraw;
command.head_ptr = packet_start_ptr;
command.start_ptr = last_ptr;
command.end_ptr = trace_ptr;
current_frame.commands.push_back(std::move(command));
last_ptr = trace_ptr;
current_command_buffer->commands.push_back(CommandBuffer::Command(
uint32_t(current_frame.commands.size() - 1)));
break;
}
case PacketCategory::kSwap:
case PacketCategory::kGeneric: {
// Ignored.
break;
}
}
if (pending_break) {
current_frame.end_ptr = trace_ptr;
frames_.push_back(std::move(current_frame));
current_command_buffer = new CommandBuffer();
current_frame.command_tree =
std::unique_ptr<CommandBuffer>(current_command_buffer);
current_frame.start_ptr = trace_ptr;
current_frame.end_ptr = nullptr;
current_frame.command_count = 0;
pending_break = false;
}
break;
}
case TraceCommandType::kMemoryRead: {
auto cmd = reinterpret_cast<const MemoryCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->encoded_length;
break;
}
case TraceCommandType::kMemoryWrite: {
auto cmd = reinterpret_cast<const MemoryCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd) + cmd->encoded_length;
break;
}
case TraceCommandType::kEvent: {
auto cmd = reinterpret_cast<const EventCommand*>(trace_ptr);
trace_ptr += sizeof(*cmd);
switch (cmd->event_type) {
case EventCommand::Type::kSwap: {
pending_break = true;
break;
}
}
break;
}
default:
// Broken trace file?
assert_unhandled_case(type);
break;
}
}
if (pending_break || current_frame.command_count) {
current_frame.end_ptr = trace_ptr;
frames_.push_back(std::move(current_frame));
}
}
bool TraceReader::DecompressMemory(MemoryEncodingFormat encoding_format,
const uint8_t* src, size_t src_size,
uint8_t* dest, size_t dest_size) {
switch (encoding_format) {
case MemoryEncodingFormat::kNone:
assert_true(src_size == dest_size);
std::memcpy(dest, src, src_size);
return true;
case MemoryEncodingFormat::kSnappy:
return snappy::RawUncompress(reinterpret_cast<const char*>(src), src_size,
reinterpret_cast<char*>(dest));
default:
assert_unhandled_case(encoding_format);
return false;
}
}
} // namespace gpu
} // namespace xe
<|endoftext|> |
<commit_before>/**
* \file
* \brief ThreadState enum class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-11-28
*/
#ifndef INCLUDE_DISTORTOS_THREADSTATE_HPP_
#define INCLUDE_DISTORTOS_THREADSTATE_HPP_
#include <cstdint>
namespace distortos
{
/**
* \brief state of the thread
*
* \ingroup threads
*/
enum class ThreadState : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is terminated
Terminated,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
/// thread is waiting for signal
WaitingForSignal,
/// thread is blocked on OnceFlag
BlockedOnOnceFlag
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_THREADSTATE_HPP_
<commit_msg>ThreadState: add new value - ThreadState::Detached<commit_after>/**
* \file
* \brief ThreadState enum class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-12-24
*/
#ifndef INCLUDE_DISTORTOS_THREADSTATE_HPP_
#define INCLUDE_DISTORTOS_THREADSTATE_HPP_
#include <cstdint>
namespace distortos
{
/**
* \brief state of the thread
*
* \ingroup threads
*/
enum class ThreadState : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is terminated
Terminated,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
/// thread is waiting for signal
WaitingForSignal,
/// thread is blocked on OnceFlag
BlockedOnOnceFlag,
/// internal thread object was detached
Detached,
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_THREADSTATE_HPP_
<|endoftext|> |
<commit_before>//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-reg-info"
#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsInstrInfo.h"
#include "MipsSubtarget.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/DebugInfo.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST)
: MipsGenRegisterInfo(Mips::RA), Subtarget(ST) {}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const uint16_t* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const {
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_SaveList;
else if (!Subtarget.hasMips64())
return CSR_O32_SaveList;
else if (Subtarget.isABI_N32())
return CSR_N32_SaveList;
assert(Subtarget.isABI_N64());
return CSR_N64_SaveList;
}
const uint32_t*
MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_RegMask;
else if (!Subtarget.hasMips64())
return CSR_O32_RegMask;
else if (Subtarget.isABI_N32())
return CSR_N32_RegMask;
assert(Subtarget.isABI_N64());
return CSR_N64_RegMask;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
static const uint16_t ReservedCPURegs[] = {
Mips::ZERO, Mips::AT, Mips::K0, Mips::K1, Mips::SP
};
static const uint16_t ReservedCPU64Regs[] = {
Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64, Mips::SP_64
};
BitVector Reserved(getNumRegs());
typedef TargetRegisterClass::const_iterator RegIter;
for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
Reserved.set(ReservedCPURegs[I]);
if (Subtarget.hasMips64()) {
for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
Reserved.set(ReservedCPU64Regs[I]);
// Reserve all registers in AFGR64.
for (RegIter Reg = Mips::AFGR64RegClass.begin(),
EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
} else {
// Reserve all registers in CPU64Regs & FGR64.
for (RegIter Reg = Mips::CPU64RegsRegClass.begin(),
EReg = Mips::CPU64RegsRegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
for (RegIter Reg = Mips::FGR64RegClass.begin(),
EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
}
// Reserve FP if this function should have a dedicated frame pointer register.
if (MF.getTarget().getFrameLowering()->hasFP(MF)) {
if (Subtarget.inMips16Mode())
Reserved.set(Mips::S0);
else {
Reserved.set(Mips::FP);
Reserved.set(Mips::FP_64);
}
}
// Reserve hardware registers.
Reserved.set(Mips::HWR29);
Reserved.set(Mips::HWR29_64);
// Reserve DSP control register.
Reserved.set(Mips::DSPCtrl);
// Reserve RA if in mips16 mode.
if (Subtarget.inMips16Mode()) {
Reserved.set(Mips::RA);
Reserved.set(Mips::RA_64);
}
// Reserve GP if small section is used.
if (Subtarget.useSmallSection()) {
Reserved.set(Mips::GP);
Reserved.set(Mips::GP_64);
}
return Reserved;
}
bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
return true;
}
bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
return true;
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
DEBUG(errs() << "\nFunction : " << MF.getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(i).getIndex();
uint64_t stackSize = MF.getFrameInfo()->getStackSize();
int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
eliminateFI(MI, i, FrameIndex, stackSize, spOffset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
bool IsN64 = Subtarget.isABI_N64();
if (Subtarget.inMips16Mode())
return TFI->hasFP(MF) ? Mips::S0 : Mips::SP;
else
return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
(IsN64 ? Mips::SP_64 : Mips::SP);
}
unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
}
unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
}
<commit_msg>[mips] Do not reserve all 64-bit registers, but only the ones which need to be reserved. Without this fix, RegScavenger::getRegsAvailable incorrectly returns an empty set of integer registers.<commit_after>//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-reg-info"
#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsInstrInfo.h"
#include "MipsSubtarget.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/DebugInfo.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST)
: MipsGenRegisterInfo(Mips::RA), Subtarget(ST) {}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const uint16_t* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const {
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_SaveList;
else if (!Subtarget.hasMips64())
return CSR_O32_SaveList;
else if (Subtarget.isABI_N32())
return CSR_N32_SaveList;
assert(Subtarget.isABI_N64());
return CSR_N64_SaveList;
}
const uint32_t*
MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_RegMask;
else if (!Subtarget.hasMips64())
return CSR_O32_RegMask;
else if (Subtarget.isABI_N32())
return CSR_N32_RegMask;
assert(Subtarget.isABI_N64());
return CSR_N64_RegMask;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
static const uint16_t ReservedCPURegs[] = {
Mips::ZERO, Mips::AT, Mips::K0, Mips::K1, Mips::SP
};
static const uint16_t ReservedCPU64Regs[] = {
Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64, Mips::SP_64
};
BitVector Reserved(getNumRegs());
typedef TargetRegisterClass::const_iterator RegIter;
for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
Reserved.set(ReservedCPURegs[I]);
for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
Reserved.set(ReservedCPU64Regs[I]);
if (Subtarget.hasMips64()) {
// Reserve all registers in AFGR64.
for (RegIter Reg = Mips::AFGR64RegClass.begin(),
EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
} else {
// Reserve all registers in FGR64.
for (RegIter Reg = Mips::FGR64RegClass.begin(),
EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
}
// Reserve FP if this function should have a dedicated frame pointer register.
if (MF.getTarget().getFrameLowering()->hasFP(MF)) {
if (Subtarget.inMips16Mode())
Reserved.set(Mips::S0);
else {
Reserved.set(Mips::FP);
Reserved.set(Mips::FP_64);
}
}
// Reserve hardware registers.
Reserved.set(Mips::HWR29);
Reserved.set(Mips::HWR29_64);
// Reserve DSP control register.
Reserved.set(Mips::DSPCtrl);
// Reserve RA if in mips16 mode.
if (Subtarget.inMips16Mode()) {
Reserved.set(Mips::RA);
Reserved.set(Mips::RA_64);
}
// Reserve GP if small section is used.
if (Subtarget.useSmallSection()) {
Reserved.set(Mips::GP);
Reserved.set(Mips::GP_64);
}
return Reserved;
}
bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
return true;
}
bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
return true;
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
DEBUG(errs() << "\nFunction : " << MF.getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(i).getIndex();
uint64_t stackSize = MF.getFrameInfo()->getStackSize();
int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
eliminateFI(MI, i, FrameIndex, stackSize, spOffset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
bool IsN64 = Subtarget.isABI_N64();
if (Subtarget.inMips16Mode())
return TFI->hasFP(MF) ? Mips::S0 : Mips::SP;
else
return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
(IsN64 ? Mips::SP_64 : Mips::SP);
}
unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
}
unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
}
<|endoftext|> |
<commit_before>//===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-reg-info"
#include "Mips.h"
#include "MipsSubtarget.h"
#include "MipsRegisterInfo.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
const TargetInstrInfo &tii)
: MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}
/// getRegisterNumbering - Given the enum value for some register, e.g.
/// Mips::RA, return the number that it corresponds to (e.g. 31).
unsigned MipsRegisterInfo::
getRegisterNumbering(unsigned RegEnum)
{
switch (RegEnum) {
case Mips::ZERO : case Mips::F0 : case Mips::D0 : return 0;
case Mips::AT : case Mips::F1 : return 1;
case Mips::V0 : case Mips::F2 : case Mips::D1 : return 2;
case Mips::V1 : case Mips::F3 : return 3;
case Mips::A0 : case Mips::F4 : case Mips::D2 : return 4;
case Mips::A1 : case Mips::F5 : return 5;
case Mips::A2 : case Mips::F6 : case Mips::D3 : return 6;
case Mips::A3 : case Mips::F7 : return 7;
case Mips::T0 : case Mips::F8 : case Mips::D4 : return 8;
case Mips::T1 : case Mips::F9 : return 9;
case Mips::T2 : case Mips::F10: case Mips::D5: return 10;
case Mips::T3 : case Mips::F11: return 11;
case Mips::T4 : case Mips::F12: case Mips::D6: return 12;
case Mips::T5 : case Mips::F13: return 13;
case Mips::T6 : case Mips::F14: case Mips::D7: return 14;
case Mips::T7 : case Mips::F15: return 15;
case Mips::S0 : case Mips::F16: case Mips::D8: return 16;
case Mips::S1 : case Mips::F17: return 17;
case Mips::S2 : case Mips::F18: case Mips::D9: return 18;
case Mips::S3 : case Mips::F19: return 19;
case Mips::S4 : case Mips::F20: case Mips::D10: return 20;
case Mips::S5 : case Mips::F21: return 21;
case Mips::S6 : case Mips::F22: case Mips::D11: return 22;
case Mips::S7 : case Mips::F23: return 23;
case Mips::T8 : case Mips::F24: case Mips::D12: return 24;
case Mips::T9 : case Mips::F25: return 25;
case Mips::K0 : case Mips::F26: case Mips::D13: return 26;
case Mips::K1 : case Mips::F27: return 27;
case Mips::GP : case Mips::F28: case Mips::D14: return 28;
case Mips::SP : case Mips::F29: return 29;
case Mips::FP : case Mips::F30: case Mips::D15: return 30;
case Mips::RA : case Mips::F31: return 31;
default: llvm_unreachable("Unknown register number!");
}
return 0; // Not reached
}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const unsigned* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
// Mips callee-save register range is $16-$23, $f20-$f30
static const unsigned SingleFloatOnlyCalleeSavedRegs[] = {
Mips::F30, Mips::F29, Mips::F28, Mips::F27, Mips::F26,
Mips::F25, Mips::F24, Mips::F23, Mips::F22, Mips::F21, Mips::F20,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
static const unsigned Mips32CalleeSavedRegs[] = {
Mips::D15, Mips::D14, Mips::D13, Mips::D12, Mips::D11, Mips::D10,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
if (Subtarget.isSingleFloat())
return SingleFloatOnlyCalleeSavedRegs;
else
return Mips32CalleeSavedRegs;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
BitVector Reserved(getNumRegs());
Reserved.set(Mips::ZERO);
Reserved.set(Mips::AT);
Reserved.set(Mips::K0);
Reserved.set(Mips::K1);
Reserved.set(Mips::GP);
Reserved.set(Mips::SP);
Reserved.set(Mips::FP);
Reserved.set(Mips::RA);
Reserved.set(Mips::F31);
Reserved.set(Mips::D15);
// SRV4 requires that odd register can't be used.
if (!Subtarget.isSingleFloat() && !Subtarget.isMips32())
for (unsigned FReg=(Mips::F0)+1; FReg < Mips::F30; FReg+=2)
Reserved.set(FReg);
return Reserved;
}
// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
// Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
MBB.erase(I);
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
MachineFrameInfo *MFI = MF.getFrameInfo();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(i).getIndex();
int stackSize = MF.getFrameInfo()->getStackSize();
int spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
int MinCSFI = 0;
int MaxCSFI = -1;
if (CSI.size()) {
MinCSFI = CSI[0].getFrameIdx();
MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
}
// The following stack frame objects are always referenced relative to $sp:
// 1. Outgoing arguments.
// 2. Pointer to dynamically allocated stack space.
// 3. Locations for callee-saved registers.
// Everything else is referenced relative to whatever register
// getFrameRegister() returns.
unsigned FrameReg;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
(FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
FrameReg = Mips::SP;
else
FrameReg = getFrameRegister(MF);
// Calculate final offset.
// - There is no need to change the offset if the frame object is one of the
// following: an outgoing argument, pointer to a dynamically allocated
// stack space or a $gp restore location,
// - If the frame object is any of the following, its offset must be adjusted
// by adding the size of the stack:
// incoming argument, callee-saved register location or local variable.
int Offset;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
MipsFI->isDynAllocFI(FrameIndex))
Offset = spOffset;
else
Offset = spOffset + stackSize;
Offset += MI.getOperand(i+1).getImm();
DEBUG(errs() << "Offset : " << Offset << "\n" << "<--------->\n");
// If MI is not a debug value, make sure Offset fits in the 16-bit immediate
// field.
if (!MI.isDebugValue() && (Offset >= 0x8000 || Offset < -0x8000)) {
MachineBasicBlock &MBB = *MI.getParent();
DebugLoc DL = II->getDebugLoc();
int ImmHi = (((unsigned)Offset & 0xffff0000) >> 16) +
((Offset & 0x8000) != 0);
// FIXME: change this when mips goes MC".
BuildMI(MBB, II, DL, TII.get(Mips::NOAT));
BuildMI(MBB, II, DL, TII.get(Mips::LUi), Mips::AT).addImm(ImmHi);
BuildMI(MBB, II, DL, TII.get(Mips::ADDu), Mips::AT).addReg(FrameReg)
.addReg(Mips::AT);
FrameReg = Mips::AT;
Offset = (short)(Offset & 0xffff);
BuildMI(MBB, ++II, MI.getDebugLoc(), TII.get(Mips::ATMACRO));
}
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(Offset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
return TFI->hasFP(MF) ? Mips::FP : Mips::SP;
}
unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
return 0;
}
unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
return 0;
}
<commit_msg>Mips32 does not reserve even-numbered floating point registers.<commit_after>//===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-reg-info"
#include "Mips.h"
#include "MipsSubtarget.h"
#include "MipsRegisterInfo.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
using namespace llvm;
MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
const TargetInstrInfo &tii)
: MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}
/// getRegisterNumbering - Given the enum value for some register, e.g.
/// Mips::RA, return the number that it corresponds to (e.g. 31).
unsigned MipsRegisterInfo::
getRegisterNumbering(unsigned RegEnum)
{
switch (RegEnum) {
case Mips::ZERO : case Mips::F0 : case Mips::D0 : return 0;
case Mips::AT : case Mips::F1 : return 1;
case Mips::V0 : case Mips::F2 : case Mips::D1 : return 2;
case Mips::V1 : case Mips::F3 : return 3;
case Mips::A0 : case Mips::F4 : case Mips::D2 : return 4;
case Mips::A1 : case Mips::F5 : return 5;
case Mips::A2 : case Mips::F6 : case Mips::D3 : return 6;
case Mips::A3 : case Mips::F7 : return 7;
case Mips::T0 : case Mips::F8 : case Mips::D4 : return 8;
case Mips::T1 : case Mips::F9 : return 9;
case Mips::T2 : case Mips::F10: case Mips::D5: return 10;
case Mips::T3 : case Mips::F11: return 11;
case Mips::T4 : case Mips::F12: case Mips::D6: return 12;
case Mips::T5 : case Mips::F13: return 13;
case Mips::T6 : case Mips::F14: case Mips::D7: return 14;
case Mips::T7 : case Mips::F15: return 15;
case Mips::S0 : case Mips::F16: case Mips::D8: return 16;
case Mips::S1 : case Mips::F17: return 17;
case Mips::S2 : case Mips::F18: case Mips::D9: return 18;
case Mips::S3 : case Mips::F19: return 19;
case Mips::S4 : case Mips::F20: case Mips::D10: return 20;
case Mips::S5 : case Mips::F21: return 21;
case Mips::S6 : case Mips::F22: case Mips::D11: return 22;
case Mips::S7 : case Mips::F23: return 23;
case Mips::T8 : case Mips::F24: case Mips::D12: return 24;
case Mips::T9 : case Mips::F25: return 25;
case Mips::K0 : case Mips::F26: case Mips::D13: return 26;
case Mips::K1 : case Mips::F27: return 27;
case Mips::GP : case Mips::F28: case Mips::D14: return 28;
case Mips::SP : case Mips::F29: return 29;
case Mips::FP : case Mips::F30: case Mips::D15: return 30;
case Mips::RA : case Mips::F31: return 31;
default: llvm_unreachable("Unknown register number!");
}
return 0; // Not reached
}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const unsigned* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
// Mips callee-save register range is $16-$23, $f20-$f30
static const unsigned SingleFloatOnlyCalleeSavedRegs[] = {
Mips::F30, Mips::F29, Mips::F28, Mips::F27, Mips::F26,
Mips::F25, Mips::F24, Mips::F23, Mips::F22, Mips::F21, Mips::F20,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
static const unsigned Mips32CalleeSavedRegs[] = {
Mips::D15, Mips::D14, Mips::D13, Mips::D12, Mips::D11, Mips::D10,
Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
};
if (Subtarget.isSingleFloat())
return SingleFloatOnlyCalleeSavedRegs;
else
return Mips32CalleeSavedRegs;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
BitVector Reserved(getNumRegs());
Reserved.set(Mips::ZERO);
Reserved.set(Mips::AT);
Reserved.set(Mips::K0);
Reserved.set(Mips::K1);
Reserved.set(Mips::GP);
Reserved.set(Mips::SP);
Reserved.set(Mips::FP);
Reserved.set(Mips::RA);
Reserved.set(Mips::F31);
Reserved.set(Mips::D15);
return Reserved;
}
// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
// Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
MBB.erase(I);
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
MachineFrameInfo *MFI = MF.getFrameInfo();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(i).getIndex();
int stackSize = MF.getFrameInfo()->getStackSize();
int spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
int MinCSFI = 0;
int MaxCSFI = -1;
if (CSI.size()) {
MinCSFI = CSI[0].getFrameIdx();
MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
}
// The following stack frame objects are always referenced relative to $sp:
// 1. Outgoing arguments.
// 2. Pointer to dynamically allocated stack space.
// 3. Locations for callee-saved registers.
// Everything else is referenced relative to whatever register
// getFrameRegister() returns.
unsigned FrameReg;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
(FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
FrameReg = Mips::SP;
else
FrameReg = getFrameRegister(MF);
// Calculate final offset.
// - There is no need to change the offset if the frame object is one of the
// following: an outgoing argument, pointer to a dynamically allocated
// stack space or a $gp restore location,
// - If the frame object is any of the following, its offset must be adjusted
// by adding the size of the stack:
// incoming argument, callee-saved register location or local variable.
int Offset;
if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
MipsFI->isDynAllocFI(FrameIndex))
Offset = spOffset;
else
Offset = spOffset + stackSize;
Offset += MI.getOperand(i+1).getImm();
DEBUG(errs() << "Offset : " << Offset << "\n" << "<--------->\n");
// If MI is not a debug value, make sure Offset fits in the 16-bit immediate
// field.
if (!MI.isDebugValue() && (Offset >= 0x8000 || Offset < -0x8000)) {
MachineBasicBlock &MBB = *MI.getParent();
DebugLoc DL = II->getDebugLoc();
int ImmHi = (((unsigned)Offset & 0xffff0000) >> 16) +
((Offset & 0x8000) != 0);
// FIXME: change this when mips goes MC".
BuildMI(MBB, II, DL, TII.get(Mips::NOAT));
BuildMI(MBB, II, DL, TII.get(Mips::LUi), Mips::AT).addImm(ImmHi);
BuildMI(MBB, II, DL, TII.get(Mips::ADDu), Mips::AT).addReg(FrameReg)
.addReg(Mips::AT);
FrameReg = Mips::AT;
Offset = (short)(Offset & 0xffff);
BuildMI(MBB, ++II, MI.getDebugLoc(), TII.get(Mips::ATMACRO));
}
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(Offset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
return TFI->hasFP(MF) ? Mips::FP : Mips::SP;
}
unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
llvm_unreachable("What is the exception register");
return 0;
}
unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
llvm_unreachable("What is the exception handler register");
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
// We use ostream for logging purposes.
#include <iostream> // NOLINT(readability/streams)
#include <limits>
#include <string>
#include <type_traits>
#include "base/not_null.hpp"
#include "serialization/quantities.pb.h"
namespace principia {
using base::not_null;
namespace quantities {
template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent,
int64_t CurrentExponent, int64_t TemperatureExponent,
int64_t AmountExponent, int64_t LuminousIntensityExponent,
int64_t WindingExponent, int64_t AngleExponent,
int64_t SolidAngleExponent>
struct Dimensions;
template<typename D> class Quantity;
using NoDimensions = Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 0>;
// Base quantities
using Length = Quantity<Dimensions<1, 0, 0, 0, 0, 0, 0, 0, 0, 0>>;
using Mass = Quantity<Dimensions<0, 1, 0, 0, 0, 0, 0, 0, 0, 0>>;
using Time = Quantity<Dimensions<0, 0, 1, 0, 0, 0, 0, 0, 0, 0>>;
using Current = Quantity<Dimensions<0, 0, 0, 1, 0, 0, 0, 0, 0, 0>>;
using Temperature = Quantity<Dimensions<0, 0, 0, 0, 1, 0, 0, 0, 0, 0>>;
using Amount = Quantity<Dimensions<0, 0, 0, 0, 0, 1, 0, 0, 0, 0>>;
using LuminousIntensity = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 1, 0, 0, 0>>;
// Nonstandard; winding is a dimensionless quantity counting cycles, in order to
// strongly type the distinction between Frequency = Winding/Time and
// AngularFrequency = Angle/Time. We also strongly type angles.
using Winding = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 1, 0, 0>>;
using Angle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 1, 0>>;
using SolidAngle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>;
namespace internal {
template<typename Left, typename Right> struct ProductGenerator;
template<typename Left, typename Right> struct QuotientGenerator;
template<typename Q, typename = void> struct SquareRootGenerator;
template<typename T, int exponent, typename = void>
struct ExponentiationGenerator;
template<typename Left, typename Right>
using Product = typename ProductGenerator<Left, Right>::Type;
template<typename Left, typename Right>
using Quotient = typename QuotientGenerator<Left, Right>::Type;
} // namespace internal
// The result type of +, -, * and / on arguments of types |Left| and |Right|.
template<typename Left, typename Right>
using Sum = decltype(std::declval<Left>() = std::declval<Right>());
template<typename Left, typename Right = Left>
using Difference = decltype(std::declval<Left>() - std::declval<Right>());
template<typename Left, typename Right>
using Product = decltype(std::declval<Left>() * std::declval<Right>());
template<typename Left, typename Right>
using Quotient = decltype(std::declval<Left>() / std::declval<Right>());
// |Exponentiation<T, n>| is an alias for the following, where t is a value of
// type |T|:
// The type of ( ... (t * t) * ... * t), with n factors, if n >= 1;
// The type of t / ( ... (t * t) * ... * t), with n + 1 factors in the
// denominator, if n < 1.
template<typename T, int exponent>
using Exponentiation =
typename internal::ExponentiationGenerator<T, exponent>::Type;
// |SquareRoot<T>| is only defined if |T| is an instance of |Quantity| with only
// even dimensions. In that case, it is the unique instance |S| of |Quantity|
// such that |Product<S, S>| is |T|.
template<typename Q>
using SquareRoot = typename internal::SquareRootGenerator<Q>::Type;
// Returns the base or derived SI Unit of |Q|.
// For instance, |SIUnit<Action>() == Joule * Second|.
template<typename Q>
constexpr Q SIUnit();
// Returns 1.
template<>
constexpr double SIUnit<double>();
template<typename LDimensions, typename RDimensions>
constexpr internal::Product<Quantity<LDimensions>, Quantity<RDimensions>>
operator*(Quantity<LDimensions> const&, Quantity<RDimensions> const&);
template<typename LDimensions, typename RDimensions>
constexpr internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>>
operator/(Quantity<LDimensions> const&, Quantity<RDimensions> const&);
template<typename RDimensions>
constexpr Quantity<RDimensions>
operator*(double const, Quantity<RDimensions> const&);
template<typename RDimensions>
constexpr typename Quantity<RDimensions>::Inverse
operator/(double const, Quantity<RDimensions> const&);
// Equivalent to |std::pow(x, exponent)| unless -3 ≤ x ≤ 3, in which case
// explicit specialization yields multiplications statically.
template<int exponent>
constexpr double Pow(double x);
template<int exponent, typename D>
constexpr Exponentiation<Quantity<D>, exponent> Pow(Quantity<D> const& x);
template<typename D>
std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity);
// Equivalent to |std::abs(x)|.
double Abs(double const x);
template<typename D>
Quantity<D> Abs(Quantity<D> const& x);
template<typename D>
SquareRoot<Quantity<D>> Sqrt(Quantity<D> const& x);
template<typename D>
Angle ArcTan(Quantity<D> const& y, Quantity<D> const& x);
std::string DebugString(
double const number,
int const precision = std::numeric_limits<double>::max_digits10);
template<typename D>
std::string DebugString(
Quantity<D> const& quantity,
int const precision = std::numeric_limits<double>::max_digits10);
template<typename D>
class Quantity {
public:
using Dimensions = D;
using Inverse = internal::Quotient<double, Quantity>;
constexpr Quantity();
~Quantity() = default;
constexpr Quantity operator+() const;
constexpr Quantity operator-() const;
constexpr Quantity operator+(Quantity const& right) const;
constexpr Quantity operator-(Quantity const& right) const;
constexpr Quantity operator*(double const right) const;
constexpr Quantity operator/(double const right) const;
Quantity& operator+=(Quantity const&);
Quantity& operator-=(Quantity const&);
Quantity& operator*=(double const);
Quantity& operator/=(double const);
constexpr bool operator>(Quantity const& right) const;
constexpr bool operator<(Quantity const& right) const;
constexpr bool operator>=(Quantity const& right) const;
constexpr bool operator<=(Quantity const& right) const;
constexpr bool operator==(Quantity const& right) const;
constexpr bool operator!=(Quantity const& right) const;
void WriteToMessage(not_null<serialization::Quantity*> const message) const;
static Quantity ReadFromMessage(serialization::Quantity const& message);
private:
explicit constexpr Quantity(double const magnitude);
double magnitude_;
template<typename LDimensions, typename RDimensions>
friend constexpr internal::Product<Quantity<LDimensions>,
Quantity<RDimensions>> operator*(
Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right);
template<typename LDimensions, typename RDimensions>
friend constexpr internal::Quotient<Quantity<LDimensions>,
Quantity<RDimensions>> operator/(
Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right);
template<typename RDimensions>
friend constexpr Quantity<RDimensions> operator*(
double const left,
Quantity<RDimensions> const& right);
template<typename RDimensions>
friend constexpr typename Quantity<RDimensions>::Inverse operator/(
double const left,
Quantity<RDimensions> const& right);
template<typename Q>
friend constexpr Q SIUnit();
template<int exponent, typename BaseDimensions>
friend constexpr Exponentiation<Quantity<BaseDimensions>, exponent> Pow(
Quantity<BaseDimensions> const& x);
friend Quantity<D> Abs<>(Quantity<D> const&);
template<typename ArgumentDimensions>
friend SquareRoot<Quantity<ArgumentDimensions>> Sqrt(
Quantity<ArgumentDimensions> const& x);
friend Angle ArcTan<>(Quantity<D> const& y, Quantity<D> const& x);
friend std::string DebugString<>(Quantity<D> const&, int const);
};
// A type trait for testing if a type is a quantity.
template<typename T>
struct is_quantity : std::is_floating_point<T> {};
template<typename D>
struct is_quantity<Quantity<D>> : std::true_type {};
} // namespace quantities
} // namespace principia
#include "quantities/quantities_body.hpp"
<commit_msg>Lint.<commit_after>#pragma once
// We use ostream for logging purposes.
#include <iostream> // NOLINT(readability/streams)
#include <limits>
#include <string>
#include <type_traits>
#include "base/not_null.hpp"
#include "serialization/quantities.pb.h"
namespace principia {
using base::not_null;
namespace quantities {
template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent,
int64_t CurrentExponent, int64_t TemperatureExponent,
int64_t AmountExponent, int64_t LuminousIntensityExponent,
int64_t WindingExponent, int64_t AngleExponent,
int64_t SolidAngleExponent>
struct Dimensions;
template<typename D> class Quantity;
using NoDimensions = Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 0>;
// Base quantities
using Length = Quantity<Dimensions<1, 0, 0, 0, 0, 0, 0, 0, 0, 0>>;
using Mass = Quantity<Dimensions<0, 1, 0, 0, 0, 0, 0, 0, 0, 0>>;
using Time = Quantity<Dimensions<0, 0, 1, 0, 0, 0, 0, 0, 0, 0>>;
using Current = Quantity<Dimensions<0, 0, 0, 1, 0, 0, 0, 0, 0, 0>>;
using Temperature = Quantity<Dimensions<0, 0, 0, 0, 1, 0, 0, 0, 0, 0>>;
using Amount = Quantity<Dimensions<0, 0, 0, 0, 0, 1, 0, 0, 0, 0>>;
using LuminousIntensity = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 1, 0, 0, 0>>;
// Nonstandard; winding is a dimensionless quantity counting cycles, in order to
// strongly type the distinction between Frequency = Winding/Time and
// AngularFrequency = Angle/Time. We also strongly type angles.
using Winding = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 1, 0, 0>>;
using Angle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 1, 0>>;
using SolidAngle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>;
namespace internal {
template<typename Left, typename Right> struct ProductGenerator;
template<typename Left, typename Right> struct QuotientGenerator;
template<typename Q, typename = void> struct SquareRootGenerator;
template<typename T, int exponent, typename = void>
struct ExponentiationGenerator;
template<typename Left, typename Right>
using Product = typename ProductGenerator<Left, Right>::Type;
template<typename Left, typename Right>
using Quotient = typename QuotientGenerator<Left, Right>::Type;
} // namespace internal
// The result type of +, -, * and / on arguments of types |Left| and |Right|.
template<typename Left, typename Right>
using Sum = decltype(std::declval<Left>() = std::declval<Right>());
template<typename Left, typename Right = Left>
using Difference = decltype(std::declval<Left>() - std::declval<Right>());
template<typename Left, typename Right>
using Product = decltype(std::declval<Left>() * std::declval<Right>());
template<typename Left, typename Right>
using Quotient = decltype(std::declval<Left>() / std::declval<Right>());
// |Exponentiation<T, n>| is an alias for the following, where t is a value of
// type |T|:
// The type of ( ... (t * t) * ... * t), with n factors, if n >= 1;
// The type of t / ( ... (t * t) * ... * t), with n + 1 factors in the
// denominator, if n < 1.
template<typename T, int exponent>
using Exponentiation =
typename internal::ExponentiationGenerator<T, exponent>::Type;
// |SquareRoot<T>| is only defined if |T| is an instance of |Quantity| with only
// even dimensions. In that case, it is the unique instance |S| of |Quantity|
// such that |Product<S, S>| is |T|.
template<typename Q>
using SquareRoot = typename internal::SquareRootGenerator<Q>::Type;
// Returns the base or derived SI Unit of |Q|.
// For instance, |SIUnit<Action>() == Joule * Second|.
template<typename Q>
constexpr Q SIUnit();
// Returns 1.
template<>
constexpr double SIUnit<double>();
template<typename LDimensions, typename RDimensions>
constexpr internal::Product<Quantity<LDimensions>, Quantity<RDimensions>>
operator*(Quantity<LDimensions> const&, Quantity<RDimensions> const&);
template<typename LDimensions, typename RDimensions>
constexpr internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>>
operator/(Quantity<LDimensions> const&, Quantity<RDimensions> const&);
template<typename RDimensions>
constexpr Quantity<RDimensions>
operator*(double const, Quantity<RDimensions> const&);
template<typename RDimensions>
constexpr typename Quantity<RDimensions>::Inverse
operator/(double const, Quantity<RDimensions> const&);
// Equivalent to |std::pow(x, exponent)| unless -3 ≤ x ≤ 3, in which case
// explicit specialization yields multiplications statically.
template<int exponent>
constexpr double Pow(double x);
template<int exponent, typename D>
constexpr Exponentiation<Quantity<D>, exponent> Pow(Quantity<D> const& x);
template<typename D>
std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity);
// Equivalent to |std::abs(x)|.
double Abs(double const x);
template<typename D>
Quantity<D> Abs(Quantity<D> const& x);
template<typename D>
SquareRoot<Quantity<D>> Sqrt(Quantity<D> const& x);
template<typename D>
Angle ArcTan(Quantity<D> const& y, Quantity<D> const& x);
std::string DebugString(
double const number,
int const precision = std::numeric_limits<double>::max_digits10);
template<typename D>
std::string DebugString(
Quantity<D> const& quantity,
int const precision = std::numeric_limits<double>::max_digits10);
template<typename D>
class Quantity {
public:
using Dimensions = D;
using Inverse = internal::Quotient<double, Quantity>;
constexpr Quantity();
~Quantity() = default;
constexpr Quantity operator+() const;
constexpr Quantity operator-() const;
constexpr Quantity operator+(Quantity const& right) const;
constexpr Quantity operator-(Quantity const& right) const;
constexpr Quantity operator*(double const right) const;
constexpr Quantity operator/(double const right) const;
Quantity& operator+=(Quantity const&);
Quantity& operator-=(Quantity const&);
Quantity& operator*=(double const);
Quantity& operator/=(double const);
constexpr bool operator>(Quantity const& right) const;
constexpr bool operator<(Quantity const& right) const;
constexpr bool operator>=(Quantity const& right) const;
constexpr bool operator<=(Quantity const& right) const;
constexpr bool operator==(Quantity const& right) const;
constexpr bool operator!=(Quantity const& right) const;
void WriteToMessage(not_null<serialization::Quantity*> const message) const;
static Quantity ReadFromMessage(serialization::Quantity const& message);
private:
explicit constexpr Quantity(double const magnitude);
double magnitude_;
template<typename LDimensions, typename RDimensions>
friend constexpr internal::Product<Quantity<LDimensions>,
Quantity<RDimensions>> operator*(
Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right);
template<typename LDimensions, typename RDimensions>
friend constexpr internal::Quotient<Quantity<LDimensions>,
Quantity<RDimensions>> operator/(
Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right);
template<typename RDimensions>
friend constexpr Quantity<RDimensions> operator*(
double const left,
Quantity<RDimensions> const& right);
template<typename RDimensions>
friend constexpr typename Quantity<RDimensions>::Inverse operator/(
double const left,
Quantity<RDimensions> const& right);
template<typename Q>
friend constexpr Q SIUnit();
template<int exponent, typename BaseDimensions>
friend constexpr Exponentiation<Quantity<BaseDimensions>, exponent> Pow(
Quantity<BaseDimensions> const& x);
friend Quantity<D> Abs<>(Quantity<D> const&);
template<typename ArgumentDimensions>
friend SquareRoot<Quantity<ArgumentDimensions>> Sqrt(
Quantity<ArgumentDimensions> const& x);
friend Angle ArcTan<>(Quantity<D> const& y, Quantity<D> const& x);
friend std::string DebugString<>(Quantity<D> const&, int const);
};
// A type trait for testing if a type is a quantity.
template<typename T>
struct is_quantity : std::is_floating_point<T> {};
template<typename D>
struct is_quantity<Quantity<D>> : std::true_type {};
} // namespace quantities
} // namespace principia
#include "quantities/quantities_body.hpp"
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, 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.
*/
#ifndef TORRENT_LAZY_ENTRY_HPP_INCLUDED
#define TORRENT_LAZY_ENTRY_HPP_INCLUDED
#include <utility>
#include <vector>
#include <string>
#include <cstring>
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/size_type.hpp"
#if TORRENT_USE_IOSTREAM
#include <iosfwd>
#endif
namespace libtorrent
{
struct lazy_entry;
TORRENT_EXPORT char const* parse_int(char const* start, char const* end
, char delimiter, boost::int64_t& val);
// return 0 = success
TORRENT_EXPORT int lazy_bdecode(char const* start, char const* end, lazy_entry& ret, int depth_limit = 1000);
struct pascal_string
{
pascal_string(char const* p, int l): len(l), ptr(p) {}
int len;
char const* ptr;
bool operator<(pascal_string const& rhs) const
{
return std::memcmp(ptr, rhs.ptr, (std::min)(len, rhs.len)) < 0
|| len < rhs.len;
}
};
struct lazy_dict_entry;
struct TORRENT_EXPORT lazy_entry
{
enum entry_type_t
{
none_t, dict_t, list_t, string_t, int_t
};
lazy_entry() : m_begin(0), m_end(0), m_type(none_t)
{ m_data.start = 0; }
entry_type_t type() const { return m_type; }
// start points to the first decimal digit
// length is the number of digits
void construct_int(char const* start, int length)
{
TORRENT_ASSERT(m_type == none_t);
m_type = int_t;
m_data.start = start;
m_size = length;
m_begin = start - 1; // include 'i'
m_end = start + length + 1; // include 'e'
}
size_type int_value() const;
// string functions
// ================
void construct_string(char const* start, int length);
// the string is not null-terminated!
char const* string_ptr() const
{
TORRENT_ASSERT(m_type == string_t);
return m_data.start;
}
// this will return a null terminated string
// it will write to the source buffer!
char const* string_cstr() const
{
TORRENT_ASSERT(m_type == string_t);
const_cast<char*>(m_data.start)[m_size] = 0;
return m_data.start;
}
pascal_string string_pstr() const
{
TORRENT_ASSERT(m_type == string_t);
return pascal_string(m_data.start, m_size);
}
std::string string_value() const
{
TORRENT_ASSERT(m_type == string_t);
return std::string(m_data.start, m_size);
}
int string_length() const
{ return m_size; }
// dictionary functions
// ====================
void construct_dict(char const* begin)
{
TORRENT_ASSERT(m_type == none_t);
m_type = dict_t;
m_size = 0;
m_capacity = 0;
m_begin = begin;
}
lazy_entry* dict_append(char const* name);
lazy_entry* dict_find(char const* name);
lazy_entry const* dict_find(char const* name) const
{ return const_cast<lazy_entry*>(this)->dict_find(name); }
std::string dict_find_string_value(char const* name) const;
pascal_string dict_find_pstr(char const* name) const;
size_type dict_find_int_value(char const* name, size_type default_val = 0) const;
lazy_entry const* dict_find_dict(char const* name) const;
lazy_entry const* dict_find_list(char const* name) const;
lazy_entry const* dict_find_string(char const* name) const;
lazy_entry const* dict_find_int(char const* name) const;
std::pair<std::string, lazy_entry const*> dict_at(int i) const;
int dict_size() const
{
TORRENT_ASSERT(m_type == dict_t);
return m_size;
}
// list functions
// ==============
void construct_list(char const* begin)
{
TORRENT_ASSERT(m_type == none_t);
m_type = list_t;
m_size = 0;
m_capacity = 0;
m_begin = begin;
}
lazy_entry* list_append();
lazy_entry* list_at(int i)
{
TORRENT_ASSERT(m_type == list_t);
TORRENT_ASSERT(i < int(m_size));
return &m_data.list[i];
}
lazy_entry const* list_at(int i) const
{ return const_cast<lazy_entry*>(this)->list_at(i); }
std::string list_string_value_at(int i) const;
pascal_string list_pstr_at(int i) const;
size_type list_int_value_at(int i, size_type default_val = 0) const;
int list_size() const
{
TORRENT_ASSERT(m_type == list_t);
return int(m_size);
}
// end points one byte passed last byte
void set_end(char const* end)
{
TORRENT_ASSERT(end > m_begin);
m_end = end;
}
void clear();
// releases ownership of any memory allocated
void release()
{
m_data.start = 0;
m_size = 0;
m_capacity = 0;
m_type = none_t;
}
~lazy_entry()
{ clear(); }
// returns pointers into the source buffer where
// this entry has its bencoded data
std::pair<char const*, int> data_section() const;
void swap(lazy_entry& e)
{
using std::swap;
entry_type_t tmp1 = e.m_type;
e.m_type = m_type;
m_type = tmp1;
boost::uint32_t tmp2 = e.m_capacity;
e.m_capacity = m_capacity;
m_capacity = tmp2;
swap(m_data.start, e.m_data.start);
swap(m_size, e.m_size);
swap(m_begin, e.m_begin);
swap(m_end, e.m_end);
}
private:
union data_t
{
lazy_dict_entry* dict;
lazy_entry* list;
char const* start;
} m_data;
// used for dictionaries and lists to record the range
// in the original buffer they are based on
char const* m_begin;
char const* m_end;
boost::uint32_t m_size; // if list or dictionary, the number of items
boost::uint32_t m_capacity:29; // if list or dictionary, allocated number of items
entry_type_t m_type:3;
// non-copyable
lazy_entry(lazy_entry const&);
lazy_entry const& operator=(lazy_entry const&);
};
struct lazy_dict_entry
{
char const* name;
lazy_entry val;
};
TORRENT_EXPORT std::string print_entry(lazy_entry const& e
, bool single_line = false, int indent = 0);
#if TORRENT_USE_IOSTREAM
TORRENT_EXPORT std::ostream& operator<<(std::ostream& os, lazy_entry const& e);
#endif
}
#endif
<commit_msg>fixed unsigned type issue in lazy_entry<commit_after>/*
Copyright (c) 2003, 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.
*/
#ifndef TORRENT_LAZY_ENTRY_HPP_INCLUDED
#define TORRENT_LAZY_ENTRY_HPP_INCLUDED
#include <utility>
#include <vector>
#include <string>
#include <cstring>
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/size_type.hpp"
#if TORRENT_USE_IOSTREAM
#include <iosfwd>
#endif
namespace libtorrent
{
struct lazy_entry;
TORRENT_EXPORT char const* parse_int(char const* start, char const* end
, char delimiter, boost::int64_t& val);
// return 0 = success
TORRENT_EXPORT int lazy_bdecode(char const* start, char const* end, lazy_entry& ret, int depth_limit = 1000);
struct pascal_string
{
pascal_string(char const* p, int l): len(l), ptr(p) {}
int len;
char const* ptr;
bool operator<(pascal_string const& rhs) const
{
return std::memcmp(ptr, rhs.ptr, (std::min)(len, rhs.len)) < 0
|| len < rhs.len;
}
};
struct lazy_dict_entry;
struct TORRENT_EXPORT lazy_entry
{
enum entry_type_t
{
none_t, dict_t, list_t, string_t, int_t
};
lazy_entry() : m_begin(0), m_end(0), m_type(none_t)
{ m_data.start = 0; }
entry_type_t type() const { return (entry_type_t)m_type; }
// start points to the first decimal digit
// length is the number of digits
void construct_int(char const* start, int length)
{
TORRENT_ASSERT(m_type == none_t);
m_type = int_t;
m_data.start = start;
m_size = length;
m_begin = start - 1; // include 'i'
m_end = start + length + 1; // include 'e'
}
size_type int_value() const;
// string functions
// ================
void construct_string(char const* start, int length);
// the string is not null-terminated!
char const* string_ptr() const
{
TORRENT_ASSERT(m_type == string_t);
return m_data.start;
}
// this will return a null terminated string
// it will write to the source buffer!
char const* string_cstr() const
{
TORRENT_ASSERT(m_type == string_t);
const_cast<char*>(m_data.start)[m_size] = 0;
return m_data.start;
}
pascal_string string_pstr() const
{
TORRENT_ASSERT(m_type == string_t);
return pascal_string(m_data.start, m_size);
}
std::string string_value() const
{
TORRENT_ASSERT(m_type == string_t);
return std::string(m_data.start, m_size);
}
int string_length() const
{ return m_size; }
// dictionary functions
// ====================
void construct_dict(char const* begin)
{
TORRENT_ASSERT(m_type == none_t);
m_type = dict_t;
m_size = 0;
m_capacity = 0;
m_begin = begin;
}
lazy_entry* dict_append(char const* name);
lazy_entry* dict_find(char const* name);
lazy_entry const* dict_find(char const* name) const
{ return const_cast<lazy_entry*>(this)->dict_find(name); }
std::string dict_find_string_value(char const* name) const;
pascal_string dict_find_pstr(char const* name) const;
size_type dict_find_int_value(char const* name, size_type default_val = 0) const;
lazy_entry const* dict_find_dict(char const* name) const;
lazy_entry const* dict_find_list(char const* name) const;
lazy_entry const* dict_find_string(char const* name) const;
lazy_entry const* dict_find_int(char const* name) const;
std::pair<std::string, lazy_entry const*> dict_at(int i) const;
int dict_size() const
{
TORRENT_ASSERT(m_type == dict_t);
return m_size;
}
// list functions
// ==============
void construct_list(char const* begin)
{
TORRENT_ASSERT(m_type == none_t);
m_type = list_t;
m_size = 0;
m_capacity = 0;
m_begin = begin;
}
lazy_entry* list_append();
lazy_entry* list_at(int i)
{
TORRENT_ASSERT(m_type == list_t);
TORRENT_ASSERT(i < int(m_size));
return &m_data.list[i];
}
lazy_entry const* list_at(int i) const
{ return const_cast<lazy_entry*>(this)->list_at(i); }
std::string list_string_value_at(int i) const;
pascal_string list_pstr_at(int i) const;
size_type list_int_value_at(int i, size_type default_val = 0) const;
int list_size() const
{
TORRENT_ASSERT(m_type == list_t);
return int(m_size);
}
// end points one byte passed last byte
void set_end(char const* end)
{
TORRENT_ASSERT(end > m_begin);
m_end = end;
}
void clear();
// releases ownership of any memory allocated
void release()
{
m_data.start = 0;
m_size = 0;
m_capacity = 0;
m_type = none_t;
}
~lazy_entry()
{ clear(); }
// returns pointers into the source buffer where
// this entry has its bencoded data
std::pair<char const*, int> data_section() const;
void swap(lazy_entry& e)
{
using std::swap;
boost::uint32_t tmp = e.m_type;
e.m_type = m_type;
m_type = tmp;
tmp = e.m_capacity;
e.m_capacity = m_capacity;
m_capacity = tmp;
swap(m_data.start, e.m_data.start);
swap(m_size, e.m_size);
swap(m_begin, e.m_begin);
swap(m_end, e.m_end);
}
private:
union data_t
{
lazy_dict_entry* dict;
lazy_entry* list;
char const* start;
} m_data;
// used for dictionaries and lists to record the range
// in the original buffer they are based on
char const* m_begin;
char const* m_end;
boost::uint32_t m_size; // if list or dictionary, the number of items
boost::uint32_t m_capacity:29; // if list or dictionary, allocated number of items
unsigned int m_type:3;
// non-copyable
lazy_entry(lazy_entry const&);
lazy_entry const& operator=(lazy_entry const&);
};
struct lazy_dict_entry
{
char const* name;
lazy_entry val;
};
TORRENT_EXPORT std::string print_entry(lazy_entry const& e
, bool single_line = false, int indent = 0);
#if TORRENT_USE_IOSTREAM
TORRENT_EXPORT std::ostream& operator<<(std::ostream& os, lazy_entry const& e);
#endif
}
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_OPENCL_MULTIPLY_HPP
#define STAN_MATH_OPENCL_MULTIPLY_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernels/scalar_mul.hpp>
#include <stan/math/opencl/kernels/matrix_multiply.hpp>
#include <stan/math/opencl/kernels/multiply_rect.hpp>
#include <stan/math/opencl/kernels/add.hpp>
#include <Eigen/Dense>
namespace stan {
namespace math {
namespace opencl {
/**
* Computes the product of the specified matrices with the option
* of specifying the triangularity of either input matrices.
*
* Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]
*
* @param A first matrix
* @param B second matrix
* @tparam triangular_view_A specifies whether the matrix A is a
* lower/upper triangular or a rectangular matrix
* @tparam triangular_view_B specifies whether the matrix B is a
* lower/upper triangular or a rectangular matrix
* @return the product of the first and second matrix
*
* @throw <code>std::invalid_argument</code> if the
* number of columns in A and rows in B do not match
*/
template <TriangularViewCL triangular_view_A = TriangularViewCL::Entire,
TriangularViewCL triangular_view_B = TriangularViewCL::Entire>
inline auto multiply(const matrix_cl& A, const matrix_cl& B) {
check_size_match("multiply ((OpenCL))", "A.cols()", A.cols(), "B.rows()",
B.rows());
matrix_cl temp(A.rows(), B.cols());
if (A.size() == 0 || B.size() == 0) {
temp.zeros();
return temp;
}
const int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at(
"THREAD_BLOCK_SIZE");
const int Mpad = ((A.rows() + local - 1) / local) * local;
const int Npad = ((B.cols() + local - 1) / local) * local;
const int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at(
"WORK_PER_THREAD");
int split = (A.cols() * B.rows())/(A.rows() * B.cols());
if (split > 100) {
split = 100;
}
try {
if (split <= 1) {
opencl_kernels::matrix_multiply(
cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt),
A.buffer(), B.buffer(), temp.buffer(), A.rows(), B.cols(), B.rows(),
triangular_view_A, triangular_view_B);
} else {
matrix_cl tempSplit(A.rows(), B.cols() * split);
opencl_kernels::multiply_rect(
cl::NDRange(Mpad, Npad / wpt, split),
cl::NDRange(local, local / wpt, 1),
A.buffer(), B.buffer(), tempSplit.buffer(), A.rows(),
B.cols(), B.rows(), triangular_view_A, triangular_view_B);
opencl_kernels::add_batch(cl::NDRange(A.rows(), B.cols()),
temp.buffer(), tempSplit.buffer(),
A.rows(), B.cols(), split);
}
} catch (cl::Error& e) {
check_opencl_error("multiply", e);
}
return temp;
}
} // namespace opencl
/**
* Multiplies the specified matrix on the OpenCL device
* with the specified scalar.
*
* @param A matrix
* @param scalar scalar
* @return matrix multipled with scalar
*/
inline matrix_cl multiply(const matrix_cl& A, const double scalar) {
matrix_cl temp(A.rows(), A.cols());
if (A.size() == 0)
return temp;
try {
opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(),
A.buffer(), scalar, A.rows(), A.cols());
} catch (const cl::Error& e) {
check_opencl_error("multiply scalar", e);
}
return temp;
}
/**
* Multiplies the specified matrix on the OpenCL device
* with the specified scalar.
*
* @param scalar scalar
* @param A matrix
* @return matrix multipled with scalar
*/
inline auto multiply(const double scalar, const matrix_cl& A) {
return multiply(A, scalar);
}
/**
* Computes the product of the specified matrices.
*
* Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]
*
* @param A first matrix
* @param B second matrix
* @return the product of the first and second matrix
*
* @throw <code>std::invalid_argument</code> if the
* number of columns in A and rows in B do not match
*/
inline auto multiply(const matrix_cl& A, const matrix_cl& B) {
return opencl::multiply(A, B);
}
/**
* Templated product operator for OpenCL matrices.
*
* Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K].
*
* @param A A matrix or scalar
* @param B A matrix or scalar
* @return the product of the first and second arguments
*
* @throw <code>std::invalid_argument</code> if the
* number of columns in A and rows in B do not match
*/
inline matrix_cl operator*(const matrix_cl& A, const matrix_cl& B) {
return opencl::multiply(A, B);
}
inline matrix_cl operator*(const matrix_cl& B, const double scalar) {
return multiply(B, scalar);
}
inline matrix_cl operator*(const double scalar, const matrix_cl& B) {
return multiply(scalar, B);
}
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>missing sqrt for split<commit_after>#ifndef STAN_MATH_OPENCL_MULTIPLY_HPP
#define STAN_MATH_OPENCL_MULTIPLY_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernels/scalar_mul.hpp>
#include <stan/math/opencl/kernels/matrix_multiply.hpp>
#include <stan/math/opencl/kernels/multiply_rect.hpp>
#include <stan/math/opencl/kernels/add.hpp>
#include <Eigen/Dense>
namespace stan {
namespace math {
namespace opencl {
/**
* Computes the product of the specified matrices with the option
* of specifying the triangularity of either input matrices.
*
* Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]
*
* @param A first matrix
* @param B second matrix
* @tparam triangular_view_A specifies whether the matrix A is a
* lower/upper triangular or a rectangular matrix
* @tparam triangular_view_B specifies whether the matrix B is a
* lower/upper triangular or a rectangular matrix
* @return the product of the first and second matrix
*
* @throw <code>std::invalid_argument</code> if the
* number of columns in A and rows in B do not match
*/
template <TriangularViewCL triangular_view_A = TriangularViewCL::Entire,
TriangularViewCL triangular_view_B = TriangularViewCL::Entire>
inline auto multiply(const matrix_cl& A, const matrix_cl& B) {
check_size_match("multiply ((OpenCL))", "A.cols()", A.cols(), "B.rows()",
B.rows());
matrix_cl temp(A.rows(), B.cols());
if (A.size() == 0 || B.size() == 0) {
temp.zeros();
return temp;
}
const int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at(
"THREAD_BLOCK_SIZE");
const int Mpad = ((A.rows() + local - 1) / local) * local;
const int Npad = ((B.cols() + local - 1) / local) * local;
const int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at(
"WORK_PER_THREAD");
int split = A.cols()/std::sqrt(A.rows() * B.cols());
if (split > 100) {
split = 100;
}
try {
if (split <= 1) {
opencl_kernels::matrix_multiply(
cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt),
A.buffer(), B.buffer(), temp.buffer(), A.rows(), B.cols(), B.rows(),
triangular_view_A, triangular_view_B);
} else {
matrix_cl tempSplit(A.rows(), B.cols() * split);
opencl_kernels::multiply_rect(
cl::NDRange(Mpad, Npad / wpt, split),
cl::NDRange(local, local / wpt, 1),
A.buffer(), B.buffer(), tempSplit.buffer(), A.rows(),
B.cols(), B.rows(), triangular_view_A, triangular_view_B);
opencl_kernels::add_batch(cl::NDRange(A.rows(), B.cols()),
temp.buffer(), tempSplit.buffer(),
A.rows(), B.cols(), split);
}
} catch (cl::Error& e) {
check_opencl_error("multiply", e);
}
return temp;
}
} // namespace opencl
/**
* Multiplies the specified matrix on the OpenCL device
* with the specified scalar.
*
* @param A matrix
* @param scalar scalar
* @return matrix multipled with scalar
*/
inline matrix_cl multiply(const matrix_cl& A, const double scalar) {
matrix_cl temp(A.rows(), A.cols());
if (A.size() == 0)
return temp;
try {
opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(),
A.buffer(), scalar, A.rows(), A.cols());
} catch (const cl::Error& e) {
check_opencl_error("multiply scalar", e);
}
return temp;
}
/**
* Multiplies the specified matrix on the OpenCL device
* with the specified scalar.
*
* @param scalar scalar
* @param A matrix
* @return matrix multipled with scalar
*/
inline auto multiply(const double scalar, const matrix_cl& A) {
return multiply(A, scalar);
}
/**
* Computes the product of the specified matrices.
*
* Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]
*
* @param A first matrix
* @param B second matrix
* @return the product of the first and second matrix
*
* @throw <code>std::invalid_argument</code> if the
* number of columns in A and rows in B do not match
*/
inline auto multiply(const matrix_cl& A, const matrix_cl& B) {
return opencl::multiply(A, B);
}
/**
* Templated product operator for OpenCL matrices.
*
* Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K].
*
* @param A A matrix or scalar
* @param B A matrix or scalar
* @return the product of the first and second arguments
*
* @throw <code>std::invalid_argument</code> if the
* number of columns in A and rows in B do not match
*/
inline matrix_cl operator*(const matrix_cl& A, const matrix_cl& B) {
return opencl::multiply(A, B);
}
inline matrix_cl operator*(const matrix_cl& B, const double scalar) {
return multiply(B, scalar);
}
inline matrix_cl operator*(const double scalar, const matrix_cl& B) {
return multiply(scalar, B);
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#pragma once
#include <seastar/core/future.hh>
#ifndef SEASTAR_COROUTINES_ENABLED
#error Coroutines support disabled.
#endif
#include <seastar/core/std-coroutine.hh>
namespace seastar {
namespace internal {
template <typename T = void>
class coroutine_traits_base {
public:
class promise_type final : public seastar::task {
seastar::promise<T> _promise;
public:
promise_type() = default;
promise_type(promise_type&&) = delete;
promise_type(const promise_type&) = delete;
template<typename... U>
void return_value(U&&... value) {
_promise.set_value(std::forward<U>(value)...);
}
[[deprecated("Forwarding coroutine returns are deprecated as too dangerous. Use 'co_return co_await ...' until explicit syntax is available.")]]
void return_value(future<T>&& fut) noexcept {
fut.forward_to(std::move(_promise));
}
void unhandled_exception() noexcept {
_promise.set_exception(std::current_exception());
}
seastar::future<T> get_return_object() noexcept {
return _promise.get_future();
}
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never initial_suspend() noexcept { return { }; }
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never final_suspend() noexcept { return { }; }
virtual void run_and_dispose() noexcept override {
auto handle = SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<promise_type>::from_promise(*this);
handle.resume();
}
task* waiting_task() noexcept override { return _promise.waiting_task(); }
};
};
template <>
class coroutine_traits_base<> {
public:
class promise_type final : public seastar::task {
seastar::promise<> _promise;
public:
promise_type() = default;
promise_type(promise_type&&) = delete;
promise_type(const promise_type&) = delete;
void return_void() noexcept {
_promise.set_value();
}
// Only accepted in gcc 10; the standard says it is illegal
#if !defined(__clang__) && __GNUC__ < 11
[[deprecated("forwarding a future<> is not possible in standard C++. 'Use co_return co_wait ...' instead.")]]
void return_value(future<>&& fut) noexcept {
fut.forward_to(std::move(_promise));
}
#endif
void unhandled_exception() noexcept {
_promise.set_exception(std::current_exception());
}
seastar::future<> get_return_object() noexcept {
return _promise.get_future();
}
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never initial_suspend() noexcept { return { }; }
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never final_suspend() noexcept { return { }; }
virtual void run_and_dispose() noexcept override {
auto handle = SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<promise_type>::from_promise(*this);
handle.resume();
}
task* waiting_task() noexcept override { return _promise.waiting_task(); }
};
};
template<typename... T>
struct awaiter {
seastar::future<T...> _future;
public:
explicit awaiter(seastar::future<T...>&& f) noexcept : _future(std::move(f)) { }
awaiter(const awaiter&) = delete;
awaiter(awaiter&&) = delete;
bool await_ready() const noexcept {
return _future.available() && !need_preempt();
}
template<typename U>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
if (!_future.available()) {
_future.set_coroutine(hndl.promise());
} else {
schedule(&hndl.promise());
}
}
std::tuple<T...> await_resume() { return _future.get(); }
};
template<typename T>
struct awaiter<T> {
seastar::future<T> _future;
public:
explicit awaiter(seastar::future<T>&& f) noexcept : _future(std::move(f)) { }
awaiter(const awaiter&) = delete;
awaiter(awaiter&&) = delete;
bool await_ready() const noexcept {
return _future.available() && !need_preempt();
}
template<typename U>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
if (!_future.available()) {
_future.set_coroutine(hndl.promise());
} else {
schedule(&hndl.promise());
}
}
T await_resume() { return _future.get0(); }
};
template<>
struct awaiter<> {
seastar::future<> _future;
public:
explicit awaiter(seastar::future<>&& f) noexcept : _future(std::move(f)) { }
awaiter(const awaiter&) = delete;
awaiter(awaiter&&) = delete;
bool await_ready() const noexcept {
return _future.available() && !need_preempt();
}
template<typename U>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
if (!_future.available()) {
_future.set_coroutine(hndl.promise());
} else {
schedule(&hndl.promise());
}
}
void await_resume() { _future.get(); }
};
} // seastar::internal
template<typename... T>
auto operator co_await(future<T...> f) noexcept {
return internal::awaiter<T...>(std::move(f));
}
} // seastar
namespace SEASTAR_INTERNAL_COROUTINE_NAMESPACE {
template<typename... T, typename... Args>
class coroutine_traits<seastar::future<T...>, Args...> : public seastar::internal::coroutine_traits_base<T...> {
};
} // SEASTAR_INTERNAL_COROUTINE_NAMESPACE
<commit_msg>coroutine: Remove return_value for future<void><commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#pragma once
#include <seastar/core/future.hh>
#ifndef SEASTAR_COROUTINES_ENABLED
#error Coroutines support disabled.
#endif
#include <seastar/core/std-coroutine.hh>
namespace seastar {
namespace internal {
template <typename T = void>
class coroutine_traits_base {
public:
class promise_type final : public seastar::task {
seastar::promise<T> _promise;
public:
promise_type() = default;
promise_type(promise_type&&) = delete;
promise_type(const promise_type&) = delete;
template<typename... U>
void return_value(U&&... value) {
_promise.set_value(std::forward<U>(value)...);
}
[[deprecated("Forwarding coroutine returns are deprecated as too dangerous. Use 'co_return co_await ...' until explicit syntax is available.")]]
void return_value(future<T>&& fut) noexcept {
fut.forward_to(std::move(_promise));
}
void unhandled_exception() noexcept {
_promise.set_exception(std::current_exception());
}
seastar::future<T> get_return_object() noexcept {
return _promise.get_future();
}
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never initial_suspend() noexcept { return { }; }
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never final_suspend() noexcept { return { }; }
virtual void run_and_dispose() noexcept override {
auto handle = SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<promise_type>::from_promise(*this);
handle.resume();
}
task* waiting_task() noexcept override { return _promise.waiting_task(); }
};
};
template <>
class coroutine_traits_base<> {
public:
class promise_type final : public seastar::task {
seastar::promise<> _promise;
public:
promise_type() = default;
promise_type(promise_type&&) = delete;
promise_type(const promise_type&) = delete;
void return_void() noexcept {
_promise.set_value();
}
void unhandled_exception() noexcept {
_promise.set_exception(std::current_exception());
}
seastar::future<> get_return_object() noexcept {
return _promise.get_future();
}
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never initial_suspend() noexcept { return { }; }
SEASTAR_INTERNAL_COROUTINE_NAMESPACE::suspend_never final_suspend() noexcept { return { }; }
virtual void run_and_dispose() noexcept override {
auto handle = SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<promise_type>::from_promise(*this);
handle.resume();
}
task* waiting_task() noexcept override { return _promise.waiting_task(); }
};
};
template<typename... T>
struct awaiter {
seastar::future<T...> _future;
public:
explicit awaiter(seastar::future<T...>&& f) noexcept : _future(std::move(f)) { }
awaiter(const awaiter&) = delete;
awaiter(awaiter&&) = delete;
bool await_ready() const noexcept {
return _future.available() && !need_preempt();
}
template<typename U>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
if (!_future.available()) {
_future.set_coroutine(hndl.promise());
} else {
schedule(&hndl.promise());
}
}
std::tuple<T...> await_resume() { return _future.get(); }
};
template<typename T>
struct awaiter<T> {
seastar::future<T> _future;
public:
explicit awaiter(seastar::future<T>&& f) noexcept : _future(std::move(f)) { }
awaiter(const awaiter&) = delete;
awaiter(awaiter&&) = delete;
bool await_ready() const noexcept {
return _future.available() && !need_preempt();
}
template<typename U>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
if (!_future.available()) {
_future.set_coroutine(hndl.promise());
} else {
schedule(&hndl.promise());
}
}
T await_resume() { return _future.get0(); }
};
template<>
struct awaiter<> {
seastar::future<> _future;
public:
explicit awaiter(seastar::future<>&& f) noexcept : _future(std::move(f)) { }
awaiter(const awaiter&) = delete;
awaiter(awaiter&&) = delete;
bool await_ready() const noexcept {
return _future.available() && !need_preempt();
}
template<typename U>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<U> hndl) noexcept {
if (!_future.available()) {
_future.set_coroutine(hndl.promise());
} else {
schedule(&hndl.promise());
}
}
void await_resume() { _future.get(); }
};
} // seastar::internal
template<typename... T>
auto operator co_await(future<T...> f) noexcept {
return internal::awaiter<T...>(std::move(f));
}
} // seastar
namespace SEASTAR_INTERNAL_COROUTINE_NAMESPACE {
template<typename... T, typename... Args>
class coroutine_traits<seastar::future<T...>, Args...> : public seastar::internal::coroutine_traits_base<T...> {
};
} // SEASTAR_INTERNAL_COROUTINE_NAMESPACE
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <memory>
#include <seastar/core/task.hh>
#include <seastar/core/future.hh>
namespace seastar {
template <typename Func>
class lambda_task final : public task {
Func _func;
using futurator = futurize<std::result_of_t<Func()>>;
typename futurator::promise_type _result;
public:
lambda_task(scheduling_group sg, const Func& func) : task(sg), _func(func) {}
lambda_task(scheduling_group sg, Func&& func) : task(sg), _func(std::move(func)) {}
typename futurator::type get_future() { return _result.get_future(); }
virtual void run_and_dispose() noexcept override {
futurator::invoke(_func).forward_to(std::move(_result));
delete this;
}
virtual task* waiting_task() noexcept override {
return _result.waiting_task();
}
};
template <typename Func>
inline
lambda_task<Func>*
make_task(Func&& func) noexcept {
return new lambda_task<Func>(current_scheduling_group(), std::forward<Func>(func));
}
template <typename Func>
inline
lambda_task<Func>*
make_task(scheduling_group sg, Func&& func) noexcept {
return new lambda_task<Func>(sg, std::forward<Func>(func));
}
}
<commit_msg>task: specify get_future as noexcept<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <memory>
#include <seastar/core/task.hh>
#include <seastar/core/future.hh>
namespace seastar {
template <typename Func>
class lambda_task final : public task {
Func _func;
using futurator = futurize<std::result_of_t<Func()>>;
typename futurator::promise_type _result;
public:
lambda_task(scheduling_group sg, const Func& func) : task(sg), _func(func) {}
lambda_task(scheduling_group sg, Func&& func) : task(sg), _func(std::move(func)) {}
typename futurator::type get_future() noexcept { return _result.get_future(); }
virtual void run_and_dispose() noexcept override {
futurator::invoke(_func).forward_to(std::move(_result));
delete this;
}
virtual task* waiting_task() noexcept override {
return _result.waiting_task();
}
};
template <typename Func>
inline
lambda_task<Func>*
make_task(Func&& func) noexcept {
return new lambda_task<Func>(current_scheduling_group(), std::forward<Func>(func));
}
template <typename Func>
inline
lambda_task<Func>*
make_task(scheduling_group sg, Func&& func) noexcept {
return new lambda_task<Func>(sg, std::forward<Func>(func));
}
}
<|endoftext|> |
<commit_before>/**
* @file llinventoryicon.cpp
* @brief Implementation of the inventory icon.
*
* $LicenseInfo:firstyear=2001&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 "llviewerprecompiledheaders.h"
#include "llinventoryicon.h"
#include "lldictionary.h"
#include "llinventorydefines.h"
#include "llui.h"
#include "llwearabletype.h"
struct IconEntry : public LLDictionaryEntry
{
IconEntry(const std::string &item_name)
:
LLDictionaryEntry(item_name)
{}
};
class LLIconDictionary : public LLSingleton<LLIconDictionary>,
public LLDictionary<LLInventoryIcon::EIconName, IconEntry>
{
public:
LLIconDictionary();
};
LLIconDictionary::LLIconDictionary()
{
addEntry(LLInventoryIcon::ICONNAME_TEXTURE, new IconEntry("Inv_Texture"));
addEntry(LLInventoryIcon::ICONNAME_SOUND, new IconEntry("Inv_Texture"));
addEntry(LLInventoryIcon::ICONNAME_CALLINGCARD_ONLINE, new IconEntry("Inv_CallingCard"));
addEntry(LLInventoryIcon::ICONNAME_CALLINGCARD_OFFLINE, new IconEntry("Inv_CallingCardOffline"));
addEntry(LLInventoryIcon::ICONNAME_LANDMARK, new IconEntry("Inv_Landmark"));
addEntry(LLInventoryIcon::ICONNAME_LANDMARK_VISITED, new IconEntry("Inv_LandmarkVisited"));
addEntry(LLInventoryIcon::ICONNAME_SCRIPT, new IconEntry("Inv_Script"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING, new IconEntry("Inv_Clothing"));
addEntry(LLInventoryIcon::ICONNAME_OBJECT, new IconEntry("Inv_Object"));
addEntry(LLInventoryIcon::ICONNAME_OBJECT_MULTI, new IconEntry("Inv_Object_Multi"));
addEntry(LLInventoryIcon::ICONNAME_NOTECARD, new IconEntry("Inv_Notecard"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART, new IconEntry("Inv_Skin"));
addEntry(LLInventoryIcon::ICONNAME_SNAPSHOT, new IconEntry("Inv_Snapshot"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_SHAPE, new IconEntry("Inv_BodyShape"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_SKIN, new IconEntry("Inv_Skin"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_HAIR, new IconEntry("Inv_Hair"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_EYES, new IconEntry("Inv_Eye"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SHIRT, new IconEntry("Inv_Shirt"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_PANTS, new IconEntry("Inv_Pants"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SHOES, new IconEntry("Inv_Shoe"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SOCKS, new IconEntry("Inv_Socks"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_JACKET, new IconEntry("Inv_Jacket"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_GLOVES, new IconEntry("Inv_Gloves"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_UNDERSHIRT, new IconEntry("Inv_Undershirt"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_UNDERPANTS, new IconEntry("Inv_Underpants"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SKIRT, new IconEntry("Inv_Skirt"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_ALPHA, new IconEntry("Inv_Alpha"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_TATTOO, new IconEntry("Inv_Tattoo"));
addEntry(LLInventoryIcon::ICONNAME_ANIMATION, new IconEntry("Inv_Animation"));
addEntry(LLInventoryIcon::ICONNAME_GESTURE, new IconEntry("Inv_Gesture"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_PHYSICS, new IconEntry("Inv_Physics"));
addEntry(LLInventoryIcon::ICONNAME_LINKITEM, new IconEntry("Inv_LinkItem"));
addEntry(LLInventoryIcon::ICONNAME_LINKFOLDER, new IconEntry("Inv_LinkItem"));
addEntry(LLInventoryIcon::ICONNAME_INVALID, new IconEntry("Inv_Invalid"));
addEntry(LLInventoryIcon::ICONNAME_NONE, new IconEntry("NONE"));
}
LLUIImagePtr LLInventoryIcon::getIcon(LLAssetType::EType asset_type,
LLInventoryType::EType inventory_type,
U32 misc_flag,
BOOL item_is_multi)
{
const std::string& icon_name = getIconName(asset_type, inventory_type, misc_flag, item_is_multi);
return LLUI::getUIImage(icon_name);
}
LLUIImagePtr LLInventoryIcon::getIcon(EIconName idx)
{
return LLUI::getUIImage(getIconName(idx));
}
const std::string& LLInventoryIcon::getIconName(LLAssetType::EType asset_type,
LLInventoryType::EType inventory_type,
U32 misc_flag,
BOOL item_is_multi)
{
EIconName idx = ICONNAME_OBJECT;
if (item_is_multi)
{
idx = ICONNAME_OBJECT_MULTI;
return getIconName(idx);
}
switch(asset_type)
{
case LLAssetType::AT_TEXTURE:
idx = (inventory_type == LLInventoryType::IT_SNAPSHOT) ? ICONNAME_SNAPSHOT : ICONNAME_TEXTURE;
break;
case LLAssetType::AT_SOUND:
idx = ICONNAME_SOUND;
break;
case LLAssetType::AT_CALLINGCARD:
idx = (misc_flag != 0) ? ICONNAME_CALLINGCARD_ONLINE : ICONNAME_CALLINGCARD_OFFLINE;
break;
case LLAssetType::AT_LANDMARK:
idx = (misc_flag != 0) ? ICONNAME_LANDMARK_VISITED : ICONNAME_LANDMARK;
break;
case LLAssetType::AT_SCRIPT:
case LLAssetType::AT_LSL_TEXT:
case LLAssetType::AT_LSL_BYTECODE:
idx = ICONNAME_SCRIPT;
break;
case LLAssetType::AT_CLOTHING:
case LLAssetType::AT_BODYPART:
idx = assignWearableIcon(misc_flag);
break;
case LLAssetType::AT_NOTECARD:
idx = ICONNAME_NOTECARD;
break;
case LLAssetType::AT_ANIMATION:
idx = ICONNAME_ANIMATION;
break;
case LLAssetType::AT_GESTURE:
idx = ICONNAME_GESTURE;
break;
case LLAssetType::AT_LINK:
idx = ICONNAME_LINKITEM;
break;
case LLAssetType::AT_LINK_FOLDER:
idx = ICONNAME_LINKFOLDER;
break;
case LLAssetType::AT_OBJECT:
idx = ICONNAME_OBJECT;
break;
default:
break;
}
return getIconName(idx);
}
const std::string& LLInventoryIcon::getIconName(EIconName idx)
{
const IconEntry *entry = LLIconDictionary::instance().lookup(idx);
return entry->mName;
}
LLInventoryIcon::EIconName LLInventoryIcon::assignWearableIcon(U32 misc_flag)
{
const LLWearableType::EType wearable_type = LLWearableType::EType(LLInventoryItemFlags::II_FLAGS_WEARABLES_MASK & misc_flag);
return LLWearableType::getIconName(wearable_type);
}
<commit_msg>FIRE-486 - Inventory sound icons now appear properly<commit_after>/**
* @file llinventoryicon.cpp
* @brief Implementation of the inventory icon.
*
* $LicenseInfo:firstyear=2001&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 "llviewerprecompiledheaders.h"
#include "llinventoryicon.h"
#include "lldictionary.h"
#include "llinventorydefines.h"
#include "llui.h"
#include "llwearabletype.h"
struct IconEntry : public LLDictionaryEntry
{
IconEntry(const std::string &item_name)
:
LLDictionaryEntry(item_name)
{}
};
class LLIconDictionary : public LLSingleton<LLIconDictionary>,
public LLDictionary<LLInventoryIcon::EIconName, IconEntry>
{
public:
LLIconDictionary();
};
LLIconDictionary::LLIconDictionary()
{
addEntry(LLInventoryIcon::ICONNAME_TEXTURE, new IconEntry("Inv_Texture"));
addEntry(LLInventoryIcon::ICONNAME_SOUND, new IconEntry("Inv_Sound"));
addEntry(LLInventoryIcon::ICONNAME_CALLINGCARD_ONLINE, new IconEntry("Inv_CallingCard"));
addEntry(LLInventoryIcon::ICONNAME_CALLINGCARD_OFFLINE, new IconEntry("Inv_CallingCardOffline"));
addEntry(LLInventoryIcon::ICONNAME_LANDMARK, new IconEntry("Inv_Landmark"));
addEntry(LLInventoryIcon::ICONNAME_LANDMARK_VISITED, new IconEntry("Inv_LandmarkVisited"));
addEntry(LLInventoryIcon::ICONNAME_SCRIPT, new IconEntry("Inv_Script"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING, new IconEntry("Inv_Clothing"));
addEntry(LLInventoryIcon::ICONNAME_OBJECT, new IconEntry("Inv_Object"));
addEntry(LLInventoryIcon::ICONNAME_OBJECT_MULTI, new IconEntry("Inv_Object_Multi"));
addEntry(LLInventoryIcon::ICONNAME_NOTECARD, new IconEntry("Inv_Notecard"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART, new IconEntry("Inv_Skin"));
addEntry(LLInventoryIcon::ICONNAME_SNAPSHOT, new IconEntry("Inv_Snapshot"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_SHAPE, new IconEntry("Inv_BodyShape"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_SKIN, new IconEntry("Inv_Skin"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_HAIR, new IconEntry("Inv_Hair"));
addEntry(LLInventoryIcon::ICONNAME_BODYPART_EYES, new IconEntry("Inv_Eye"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SHIRT, new IconEntry("Inv_Shirt"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_PANTS, new IconEntry("Inv_Pants"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SHOES, new IconEntry("Inv_Shoe"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SOCKS, new IconEntry("Inv_Socks"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_JACKET, new IconEntry("Inv_Jacket"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_GLOVES, new IconEntry("Inv_Gloves"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_UNDERSHIRT, new IconEntry("Inv_Undershirt"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_UNDERPANTS, new IconEntry("Inv_Underpants"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_SKIRT, new IconEntry("Inv_Skirt"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_ALPHA, new IconEntry("Inv_Alpha"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_TATTOO, new IconEntry("Inv_Tattoo"));
addEntry(LLInventoryIcon::ICONNAME_ANIMATION, new IconEntry("Inv_Animation"));
addEntry(LLInventoryIcon::ICONNAME_GESTURE, new IconEntry("Inv_Gesture"));
addEntry(LLInventoryIcon::ICONNAME_CLOTHING_PHYSICS, new IconEntry("Inv_Physics"));
addEntry(LLInventoryIcon::ICONNAME_LINKITEM, new IconEntry("Inv_LinkItem"));
addEntry(LLInventoryIcon::ICONNAME_LINKFOLDER, new IconEntry("Inv_LinkItem"));
addEntry(LLInventoryIcon::ICONNAME_INVALID, new IconEntry("Inv_Invalid"));
addEntry(LLInventoryIcon::ICONNAME_NONE, new IconEntry("NONE"));
}
LLUIImagePtr LLInventoryIcon::getIcon(LLAssetType::EType asset_type,
LLInventoryType::EType inventory_type,
U32 misc_flag,
BOOL item_is_multi)
{
const std::string& icon_name = getIconName(asset_type, inventory_type, misc_flag, item_is_multi);
return LLUI::getUIImage(icon_name);
}
LLUIImagePtr LLInventoryIcon::getIcon(EIconName idx)
{
return LLUI::getUIImage(getIconName(idx));
}
const std::string& LLInventoryIcon::getIconName(LLAssetType::EType asset_type,
LLInventoryType::EType inventory_type,
U32 misc_flag,
BOOL item_is_multi)
{
EIconName idx = ICONNAME_OBJECT;
if (item_is_multi)
{
idx = ICONNAME_OBJECT_MULTI;
return getIconName(idx);
}
switch(asset_type)
{
case LLAssetType::AT_TEXTURE:
idx = (inventory_type == LLInventoryType::IT_SNAPSHOT) ? ICONNAME_SNAPSHOT : ICONNAME_TEXTURE;
break;
case LLAssetType::AT_SOUND:
idx = ICONNAME_SOUND;
break;
case LLAssetType::AT_CALLINGCARD:
idx = (misc_flag != 0) ? ICONNAME_CALLINGCARD_ONLINE : ICONNAME_CALLINGCARD_OFFLINE;
break;
case LLAssetType::AT_LANDMARK:
idx = (misc_flag != 0) ? ICONNAME_LANDMARK_VISITED : ICONNAME_LANDMARK;
break;
case LLAssetType::AT_SCRIPT:
case LLAssetType::AT_LSL_TEXT:
case LLAssetType::AT_LSL_BYTECODE:
idx = ICONNAME_SCRIPT;
break;
case LLAssetType::AT_CLOTHING:
case LLAssetType::AT_BODYPART:
idx = assignWearableIcon(misc_flag);
break;
case LLAssetType::AT_NOTECARD:
idx = ICONNAME_NOTECARD;
break;
case LLAssetType::AT_ANIMATION:
idx = ICONNAME_ANIMATION;
break;
case LLAssetType::AT_GESTURE:
idx = ICONNAME_GESTURE;
break;
case LLAssetType::AT_LINK:
idx = ICONNAME_LINKITEM;
break;
case LLAssetType::AT_LINK_FOLDER:
idx = ICONNAME_LINKFOLDER;
break;
case LLAssetType::AT_OBJECT:
idx = ICONNAME_OBJECT;
break;
default:
break;
}
return getIconName(idx);
}
const std::string& LLInventoryIcon::getIconName(EIconName idx)
{
const IconEntry *entry = LLIconDictionary::instance().lookup(idx);
return entry->mName;
}
LLInventoryIcon::EIconName LLInventoryIcon::assignWearableIcon(U32 misc_flag)
{
const LLWearableType::EType wearable_type = LLWearableType::EType(LLInventoryItemFlags::II_FLAGS_WEARABLES_MASK & misc_flag);
return LLWearableType::getIconName(wearable_type);
}
<|endoftext|> |
<commit_before>#include "IMultirotor_Properties.h"
#include "qmath.h"
namespace silk
{
std::vector<IMultirotor_Properties::Motor> IMultirotor_Properties::create_motors(size_t arm_count, float radius, bool plus_config, bool double_config)
{
std::vector<IMultirotor_Properties::Motor> res;
float angle_between_motors = math::anglef::_2pi / (float)arm_count;
float starting_angle = plus_config ? 0 : (angle_between_motors / 2.f);
size_t rows = double_config ? 2 : 1;
for (size_t r = 0; r < rows; r++)
{
float angle = starting_angle;
for (size_t c = 0; c < arm_count; c++)
{
float x = 0.f;
float y = 0.f;
math::sin_cos(angle, y, x);
x *= radius;
y *= radius;
Motor motor;
motor.position = math::vec3f(x, y, 0.f);
motor.thrust_vector = math::vec3f(0, 0, 1.f);
motor.clockwise = (c & 1) == 0;
res.push_back(motor);
angle += angle_between_motors;
}
}
return res;
}
}
<commit_msg>Printing out the motors<commit_after>#include "IMultirotor_Properties.h"
#include "qmath.h"
namespace silk
{
std::vector<IMultirotor_Properties::Motor> IMultirotor_Properties::create_motors(size_t arm_count, float radius, bool plus_config, bool double_config)
{
std::vector<IMultirotor_Properties::Motor> res;
float angle_between_motors = math::anglef::_2pi / (float)arm_count;
float starting_angle = plus_config ? 0 : (angle_between_motors / 2.f);
size_t rows = double_config ? 2 : 1;
for (size_t r = 0; r < rows; r++)
{
float angle = starting_angle;
for (size_t c = 0; c < arm_count; c++)
{
float x = 0.f;
float y = 0.f;
math::sin_cos(angle, y, x);
x *= radius;
y *= radius;
Motor motor;
motor.position = math::vec3f(x, y, 0.f);
motor.thrust_vector = math::vec3f(0, 0, 1.f);
motor.clockwise = (c & 1) == 0;
res.push_back(motor);
angle += angle_between_motors;
QLOGI("{}: {} motor at {}", res.size() - 1, motor.clockwise ? "CW" : "CCW", math::vec2f(motor.position));
}
}
return res;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c)2012 Jan Rheinlaender <jrheinlaender@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
******************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Bnd_Box.hxx>
# include <BRep_Tool.hxx>
# include <BRepBndLib.hxx>
# include <BRepMesh_IncrementalMesh.hxx>
# include <Standard_Version.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <Poly_Triangulation.hxx>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoDrawStyle.h>
# include <Inventor/nodes/SoIndexedFaceSet.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoMultipleCopy.h>
# include <Inventor/nodes/SoNormal.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoShapeHints.h>
# include <Inventor/nodes/SoTransparencyType.h>
# include <QAction>
# include <QMenu>
# include <QMessageBox>
#endif
#include "ViewProviderTransformed.h"
#include "TaskTransformedParameters.h"
#include <Base/Console.h>
#include <Gui/Control.h>
#include <Gui/Command.h>
#include <Gui/Application.h>
#include <Gui/Command.h>
#include <Mod/Part/App/TopoShape.h>
#include <Mod/PartDesign/App/FeatureTransformed.h>
#include <Mod/PartDesign/App/FeatureAddSub.h>
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderTransformed,PartDesignGui::ViewProvider)
void ViewProviderTransformed::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
QAction* act;
act = menu->addAction(QObject::tr((std::string("Edit ") + featureName + " feature").c_str()), receiver, member);
act->setData(QVariant((int)ViewProvider::Default));
}
bool ViewProviderTransformed::setEdit(int ModNum)
{
pcRejectedRoot = new SoSeparator();
pcRejectedRoot->ref();
SoPickStyle* rejectedPickStyle = new SoPickStyle();
rejectedPickStyle->style = SoPickStyle::UNPICKABLE;
SoShapeHints* rejectedHints = new SoShapeHints();
rejectedHints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE;
rejectedHints->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE;
SoMaterialBinding* rejectedBind = new SoMaterialBinding();
SoTransparencyType* rejectedTransparencyType = new SoTransparencyType();
rejectedTransparencyType->value.setValue(SoGLRenderAction::BLEND);
SoMaterial* rejectedMaterial = new SoMaterial();
rejectedMaterial->diffuseColor.set1Value(0,SbColor(1.f,0.f,0.f));
rejectedMaterial->transparency.setValue(0.6f);
SoDrawStyle* rejectedFaceStyle = new SoDrawStyle();
rejectedFaceStyle->style = SoDrawStyle::FILLED;
SoNormalBinding* rejectedNormb = new SoNormalBinding();
rejectedNormb->value = SoNormalBinding::PER_VERTEX_INDEXED;
// just faces with no edges or points
pcRejectedRoot->addChild(rejectedPickStyle);
pcRejectedRoot->addChild(rejectedTransparencyType);
pcRejectedRoot->addChild(rejectedBind);
pcRejectedRoot->addChild(rejectedMaterial);
pcRejectedRoot->addChild(rejectedHints);
pcRejectedRoot->addChild(rejectedFaceStyle);
pcRejectedRoot->addChild(rejectedNormb); // NOTE: The code relies on the last child added here being index 6
pcRoot->addChild(pcRejectedRoot);
recomputeFeature();
return ViewProvider::setEdit(ModNum);
}
void ViewProviderTransformed::unsetEdit(int ModNum)
{
ViewProvider::unsetEdit(ModNum);
while (pcRejectedRoot->getNumChildren() > 7) {
SoSeparator* sep = static_cast<SoSeparator*>(pcRejectedRoot->getChild(7));
SoMultipleCopy* rejectedTrfms = static_cast<SoMultipleCopy*>(sep->getChild(2));
rejectedTrfms ->removeAllChildren();
sep->removeChild(1);
sep->removeChild(0);
pcRejectedRoot ->removeChild(7);
}
pcRejectedRoot->removeAllChildren();
pcRoot->removeChild(pcRejectedRoot);
pcRejectedRoot->unref();
}
bool ViewProviderTransformed::onDelete(const std::vector<std::string> &s)
{
return ViewProvider::onDelete(s);
}
void ViewProviderTransformed::recomputeFeature(void)
{
PartDesign::Transformed* pcTransformed = static_cast<PartDesign::Transformed*>(getObject());
pcTransformed->getDocument()->recomputeFeature(pcTransformed);
const std::vector<App::DocumentObjectExecReturn*> log = pcTransformed->getDocument()->getRecomputeLog();
PartDesign::Transformed::rejectedMap rejected_trsf = pcTransformed->getRejectedTransformations();
unsigned rejected = 0;
for (PartDesign::Transformed::rejectedMap::const_iterator r = rejected_trsf.begin(); r != rejected_trsf.end(); r++)
rejected += r->second.size();
QString msg = QString::fromLatin1("%1");
if (rejected > 0) {
msg = QString::fromLatin1("<font color='orange'>%1<br/></font>\r\n%2");
if (rejected == 1)
msg = msg.arg(QObject::tr("One transformed shape does not intersect support"));
else {
msg = msg.arg(QObject::tr("%1 transformed shapes do not intersect support"));
msg = msg.arg(rejected);
}
}
if (log.size() > 0) {
msg = msg.arg(QString::fromLatin1("<font color='red'>%1<br/></font>"));
msg = msg.arg(QString::fromStdString(log.back()->Why));
} else {
msg = msg.arg(QString::fromLatin1("<font color='green'>%1<br/></font>"));
msg = msg.arg(QObject::tr("Transformation succeeded"));
}
signalDiagnosis(msg);
// Clear all the rejected stuff
while (pcRejectedRoot->getNumChildren() > 7) {
SoSeparator* sep = static_cast<SoSeparator*>(pcRejectedRoot->getChild(7));
SoMultipleCopy* rejectedTrfms = static_cast<SoMultipleCopy*>(sep->getChild(2));
rejectedTrfms ->removeAllChildren();
sep->removeChild(1);
sep->removeChild(0);
pcRejectedRoot ->removeChild(7);
}
for (PartDesign::Transformed::rejectedMap::const_iterator o = rejected_trsf.begin(); o != rejected_trsf.end(); o++) {
if (o->second.empty()) continue;
TopoDS_Shape shape;
if ((o->first)->getTypeId().isDerivedFrom(PartDesign::FeatureAddSub::getClassTypeId())) {
PartDesign::FeatureAddSub* feature = static_cast<PartDesign::FeatureAddSub*>(o->first);
shape = feature->AddSubShape.getShape().getShape();
}
if (shape.IsNull()) continue;
// Display the rejected transformations in red
TopoDS_Shape cShape(shape);
try {
// calculating the deflection value
Standard_Real xMin, yMin, zMin, xMax, yMax, zMax;
{
Bnd_Box bounds;
BRepBndLib::Add(cShape, bounds);
bounds.SetGap(0.0);
bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax);
}
Standard_Real deflection = ((xMax-xMin)+(yMax-yMin)+(zMax-zMin))/300.0 * Deviation.getValue();
// create or use the mesh on the data structure
// Note: This DOES have an effect on cShape
#if OCC_VERSION_HEX >= 0x060600
Standard_Real AngDeflectionRads = AngularDeflection.getValue() / 180.0 * M_PI;
BRepMesh_IncrementalMesh(cShape,deflection,Standard_False,
AngDeflectionRads,Standard_True);
#else
BRepMesh_IncrementalMesh(cShape,deflection);
#endif
// We must reset the location here because the transformation data
// are set in the placement property
TopLoc_Location aLoc;
cShape.Location(aLoc);
// count triangles and nodes in the mesh
int nbrTriangles=0, nbrNodes=0;
TopExp_Explorer Ex;
for (Ex.Init(cShape,TopAbs_FACE);Ex.More();Ex.Next()) {
Handle (Poly_Triangulation) mesh = BRep_Tool::Triangulation(TopoDS::Face(Ex.Current()), aLoc);
// Note: we must also count empty faces
if (!mesh.IsNull()) {
nbrTriangles += mesh->NbTriangles();
nbrNodes += mesh->NbNodes();
}
}
// create memory for the nodes and indexes
SoCoordinate3* rejectedCoords = new SoCoordinate3();
rejectedCoords ->point .setNum(nbrNodes);
SoNormal* rejectedNorms = new SoNormal();
rejectedNorms ->vector .setNum(nbrNodes);
SoIndexedFaceSet* rejectedFaceSet = new SoIndexedFaceSet();
rejectedFaceSet ->coordIndex .setNum(nbrTriangles*4);
// get the raw memory for fast fill up
SbVec3f* verts = rejectedCoords ->point .startEditing();
SbVec3f* norms = rejectedNorms ->vector .startEditing();
int32_t* index = rejectedFaceSet ->coordIndex .startEditing();
// preset the normal vector with null vector
for (int i=0; i < nbrNodes; i++)
norms[i]= SbVec3f(0.0,0.0,0.0);
int ii = 0,FaceNodeOffset=0,FaceTriaOffset=0;
for (Ex.Init(cShape, TopAbs_FACE); Ex.More(); Ex.Next(),ii++) {
TopLoc_Location aLoc;
const TopoDS_Face &actFace = TopoDS::Face(Ex.Current());
// get the mesh of the shape
Handle (Poly_Triangulation) mesh = BRep_Tool::Triangulation(actFace,aLoc);
if (mesh.IsNull()) continue;
// getting the transformation of the shape/face
gp_Trsf myTransf;
Standard_Boolean identity = true;
if (!aLoc.IsIdentity()) {
identity = false;
myTransf = aLoc.Transformation();
}
// getting size of node and triangle array of this face
int nbNodesInFace = mesh->NbNodes();
int nbTriInFace = mesh->NbTriangles();
// check orientation
TopAbs_Orientation orient = actFace.Orientation();
// cycling through the poly mesh
const Poly_Array1OfTriangle& Triangles = mesh->Triangles();
const TColgp_Array1OfPnt& Nodes = mesh->Nodes();
for (int g=1; g <= nbTriInFace; g++) {
// Get the triangle
Standard_Integer N1,N2,N3;
Triangles(g).Get(N1,N2,N3);
// change orientation of the triangle if the face is reversed
if ( orient != TopAbs_FORWARD ) {
Standard_Integer tmp = N1;
N1 = N2;
N2 = tmp;
}
// get the 3 points of this triangle
gp_Pnt V1(Nodes(N1)), V2(Nodes(N2)), V3(Nodes(N3));
// transform the vertices to the place of the face
if (!identity) {
V1.Transform(myTransf);
V2.Transform(myTransf);
V3.Transform(myTransf);
}
// calculating per vertex normals
// Calculate triangle normal
gp_Vec v1(V1.X(),V1.Y(),V1.Z()),v2(V2.X(),V2.Y(),V2.Z()),v3(V3.X(),V3.Y(),V3.Z());
gp_Vec Normal = (v2-v1)^(v3-v1);
// add the triangle normal to the vertex normal for all points of this triangle
norms[FaceNodeOffset+N1-1] += SbVec3f(Normal.X(),Normal.Y(),Normal.Z());
norms[FaceNodeOffset+N2-1] += SbVec3f(Normal.X(),Normal.Y(),Normal.Z());
norms[FaceNodeOffset+N3-1] += SbVec3f(Normal.X(),Normal.Y(),Normal.Z());
// set the vertices
verts[FaceNodeOffset+N1-1].setValue((float)(V1.X()),(float)(V1.Y()),(float)(V1.Z()));
verts[FaceNodeOffset+N2-1].setValue((float)(V2.X()),(float)(V2.Y()),(float)(V2.Z()));
verts[FaceNodeOffset+N3-1].setValue((float)(V3.X()),(float)(V3.Y()),(float)(V3.Z()));
// set the index vector with the 3 point indexes and the end delimiter
index[FaceTriaOffset*4+4*(g-1)] = FaceNodeOffset+N1-1;
index[FaceTriaOffset*4+4*(g-1)+1] = FaceNodeOffset+N2-1;
index[FaceTriaOffset*4+4*(g-1)+2] = FaceNodeOffset+N3-1;
index[FaceTriaOffset*4+4*(g-1)+3] = SO_END_FACE_INDEX;
}
// counting up the per Face offsets
FaceNodeOffset += nbNodesInFace;
FaceTriaOffset += nbTriInFace;
}
// normalize all normals
for (int i=0; i < nbrNodes; i++)
norms[i].normalize();
// end the editing of the nodes
rejectedCoords ->point .finishEditing();
rejectedNorms ->vector .finishEditing();
rejectedFaceSet ->coordIndex .finishEditing();
// fill in the transformation matrices
SoMultipleCopy* rejectedTrfms = new SoMultipleCopy();
rejectedTrfms->matrix.setNum((o->second).size());
SbMatrix* mats = rejectedTrfms->matrix.startEditing();
std::list<gp_Trsf>::const_iterator trsf = (o->second).begin();
for (unsigned int i=0; i < (o->second).size(); i++,trsf++) {
Base::Matrix4D mat;
Part::TopoShape::convertToMatrix(*trsf,mat);
mats[i] = convert(mat);
}
rejectedTrfms->matrix.finishEditing();
rejectedTrfms->addChild(rejectedFaceSet);
SoSeparator* sep = new SoSeparator();
sep->addChild(rejectedCoords);
sep->addChild(rejectedNorms);
sep->addChild(rejectedTrfms);
pcRejectedRoot->addChild(sep);
}
catch (...) {
Base::Console().Error("Cannot compute Inventor representation for the rejected transformations of shape of %s.\n",
pcTransformed->getNameInDocument());
}
}
}
<commit_msg>render both faces<commit_after>/******************************************************************************
* Copyright (c)2012 Jan Rheinlaender <jrheinlaender@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
******************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Bnd_Box.hxx>
# include <BRep_Tool.hxx>
# include <BRepBndLib.hxx>
# include <BRepMesh_IncrementalMesh.hxx>
# include <Standard_Version.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <Poly_Triangulation.hxx>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoDrawStyle.h>
# include <Inventor/nodes/SoIndexedFaceSet.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoMultipleCopy.h>
# include <Inventor/nodes/SoNormal.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoShapeHints.h>
# include <Inventor/nodes/SoTransparencyType.h>
# include <QAction>
# include <QMenu>
# include <QMessageBox>
#endif
#include "ViewProviderTransformed.h"
#include "TaskTransformedParameters.h"
#include <Base/Console.h>
#include <Gui/Control.h>
#include <Gui/Command.h>
#include <Gui/Application.h>
#include <Gui/Command.h>
#include <Mod/Part/App/TopoShape.h>
#include <Mod/PartDesign/App/FeatureTransformed.h>
#include <Mod/PartDesign/App/FeatureAddSub.h>
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderTransformed,PartDesignGui::ViewProvider)
void ViewProviderTransformed::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
QAction* act;
act = menu->addAction(QObject::tr((std::string("Edit ") + featureName + " feature").c_str()), receiver, member);
act->setData(QVariant((int)ViewProvider::Default));
}
bool ViewProviderTransformed::setEdit(int ModNum)
{
pcRejectedRoot = new SoSeparator();
pcRejectedRoot->ref();
SoPickStyle* rejectedPickStyle = new SoPickStyle();
rejectedPickStyle->style = SoPickStyle::UNPICKABLE;
SoShapeHints* rejectedHints = new SoShapeHints();
rejectedHints->vertexOrdering = SoShapeHints::UNKNOWN_ORDERING;
rejectedHints->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE;
SoMaterialBinding* rejectedBind = new SoMaterialBinding();
SoTransparencyType* rejectedTransparencyType = new SoTransparencyType();
rejectedTransparencyType->value.setValue(SoGLRenderAction::BLEND);
SoMaterial* rejectedMaterial = new SoMaterial();
rejectedMaterial->diffuseColor.set1Value(0,SbColor(1.f,0.f,0.f));
rejectedMaterial->transparency.setValue(0.6f);
SoDrawStyle* rejectedFaceStyle = new SoDrawStyle();
rejectedFaceStyle->style = SoDrawStyle::FILLED;
SoNormalBinding* rejectedNormb = new SoNormalBinding();
rejectedNormb->value = SoNormalBinding::PER_VERTEX_INDEXED;
// just faces with no edges or points
pcRejectedRoot->addChild(rejectedPickStyle);
pcRejectedRoot->addChild(rejectedTransparencyType);
pcRejectedRoot->addChild(rejectedBind);
pcRejectedRoot->addChild(rejectedMaterial);
pcRejectedRoot->addChild(rejectedHints);
pcRejectedRoot->addChild(rejectedFaceStyle);
pcRejectedRoot->addChild(rejectedNormb); // NOTE: The code relies on the last child added here being index 6
pcRoot->addChild(pcRejectedRoot);
recomputeFeature();
return ViewProvider::setEdit(ModNum);
}
void ViewProviderTransformed::unsetEdit(int ModNum)
{
ViewProvider::unsetEdit(ModNum);
while (pcRejectedRoot->getNumChildren() > 7) {
SoSeparator* sep = static_cast<SoSeparator*>(pcRejectedRoot->getChild(7));
SoMultipleCopy* rejectedTrfms = static_cast<SoMultipleCopy*>(sep->getChild(2));
rejectedTrfms ->removeAllChildren();
sep->removeChild(1);
sep->removeChild(0);
pcRejectedRoot ->removeChild(7);
}
pcRejectedRoot->removeAllChildren();
pcRoot->removeChild(pcRejectedRoot);
pcRejectedRoot->unref();
}
bool ViewProviderTransformed::onDelete(const std::vector<std::string> &s)
{
return ViewProvider::onDelete(s);
}
void ViewProviderTransformed::recomputeFeature(void)
{
PartDesign::Transformed* pcTransformed = static_cast<PartDesign::Transformed*>(getObject());
pcTransformed->getDocument()->recomputeFeature(pcTransformed);
const std::vector<App::DocumentObjectExecReturn*> log = pcTransformed->getDocument()->getRecomputeLog();
PartDesign::Transformed::rejectedMap rejected_trsf = pcTransformed->getRejectedTransformations();
unsigned rejected = 0;
for (PartDesign::Transformed::rejectedMap::const_iterator r = rejected_trsf.begin(); r != rejected_trsf.end(); r++)
rejected += r->second.size();
QString msg = QString::fromLatin1("%1");
if (rejected > 0) {
msg = QString::fromLatin1("<font color='orange'>%1<br/></font>\r\n%2");
if (rejected == 1)
msg = msg.arg(QObject::tr("One transformed shape does not intersect support"));
else {
msg = msg.arg(QObject::tr("%1 transformed shapes do not intersect support"));
msg = msg.arg(rejected);
}
}
if (log.size() > 0) {
msg = msg.arg(QString::fromLatin1("<font color='red'>%1<br/></font>"));
msg = msg.arg(QString::fromStdString(log.back()->Why));
} else {
msg = msg.arg(QString::fromLatin1("<font color='green'>%1<br/></font>"));
msg = msg.arg(QObject::tr("Transformation succeeded"));
}
signalDiagnosis(msg);
// Clear all the rejected stuff
while (pcRejectedRoot->getNumChildren() > 7) {
SoSeparator* sep = static_cast<SoSeparator*>(pcRejectedRoot->getChild(7));
SoMultipleCopy* rejectedTrfms = static_cast<SoMultipleCopy*>(sep->getChild(2));
rejectedTrfms ->removeAllChildren();
sep->removeChild(1);
sep->removeChild(0);
pcRejectedRoot ->removeChild(7);
}
for (PartDesign::Transformed::rejectedMap::const_iterator o = rejected_trsf.begin(); o != rejected_trsf.end(); o++) {
if (o->second.empty()) continue;
TopoDS_Shape shape;
if ((o->first)->getTypeId().isDerivedFrom(PartDesign::FeatureAddSub::getClassTypeId())) {
PartDesign::FeatureAddSub* feature = static_cast<PartDesign::FeatureAddSub*>(o->first);
shape = feature->AddSubShape.getShape().getShape();
}
if (shape.IsNull()) continue;
// Display the rejected transformations in red
TopoDS_Shape cShape(shape);
try {
// calculating the deflection value
Standard_Real xMin, yMin, zMin, xMax, yMax, zMax;
{
Bnd_Box bounds;
BRepBndLib::Add(cShape, bounds);
bounds.SetGap(0.0);
bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax);
}
Standard_Real deflection = ((xMax-xMin)+(yMax-yMin)+(zMax-zMin))/300.0 * Deviation.getValue();
// create or use the mesh on the data structure
// Note: This DOES have an effect on cShape
#if OCC_VERSION_HEX >= 0x060600
Standard_Real AngDeflectionRads = AngularDeflection.getValue() / 180.0 * M_PI;
BRepMesh_IncrementalMesh(cShape,deflection,Standard_False,
AngDeflectionRads,Standard_True);
#else
BRepMesh_IncrementalMesh(cShape,deflection);
#endif
// We must reset the location here because the transformation data
// are set in the placement property
TopLoc_Location aLoc;
cShape.Location(aLoc);
// count triangles and nodes in the mesh
int nbrTriangles=0, nbrNodes=0;
TopExp_Explorer Ex;
for (Ex.Init(cShape,TopAbs_FACE);Ex.More();Ex.Next()) {
Handle (Poly_Triangulation) mesh = BRep_Tool::Triangulation(TopoDS::Face(Ex.Current()), aLoc);
// Note: we must also count empty faces
if (!mesh.IsNull()) {
nbrTriangles += mesh->NbTriangles();
nbrNodes += mesh->NbNodes();
}
}
// create memory for the nodes and indexes
SoCoordinate3* rejectedCoords = new SoCoordinate3();
rejectedCoords ->point .setNum(nbrNodes);
SoNormal* rejectedNorms = new SoNormal();
rejectedNorms ->vector .setNum(nbrNodes);
SoIndexedFaceSet* rejectedFaceSet = new SoIndexedFaceSet();
rejectedFaceSet ->coordIndex .setNum(nbrTriangles*4);
// get the raw memory for fast fill up
SbVec3f* verts = rejectedCoords ->point .startEditing();
SbVec3f* norms = rejectedNorms ->vector .startEditing();
int32_t* index = rejectedFaceSet ->coordIndex .startEditing();
// preset the normal vector with null vector
for (int i=0; i < nbrNodes; i++)
norms[i]= SbVec3f(0.0,0.0,0.0);
int ii = 0,FaceNodeOffset=0,FaceTriaOffset=0;
for (Ex.Init(cShape, TopAbs_FACE); Ex.More(); Ex.Next(),ii++) {
TopLoc_Location aLoc;
const TopoDS_Face &actFace = TopoDS::Face(Ex.Current());
// get the mesh of the shape
Handle (Poly_Triangulation) mesh = BRep_Tool::Triangulation(actFace,aLoc);
if (mesh.IsNull()) continue;
// getting the transformation of the shape/face
gp_Trsf myTransf;
Standard_Boolean identity = true;
if (!aLoc.IsIdentity()) {
identity = false;
myTransf = aLoc.Transformation();
}
// getting size of node and triangle array of this face
int nbNodesInFace = mesh->NbNodes();
int nbTriInFace = mesh->NbTriangles();
// check orientation
TopAbs_Orientation orient = actFace.Orientation();
// cycling through the poly mesh
const Poly_Array1OfTriangle& Triangles = mesh->Triangles();
const TColgp_Array1OfPnt& Nodes = mesh->Nodes();
for (int g=1; g <= nbTriInFace; g++) {
// Get the triangle
Standard_Integer N1,N2,N3;
Triangles(g).Get(N1,N2,N3);
// change orientation of the triangle if the face is reversed
if ( orient != TopAbs_FORWARD ) {
Standard_Integer tmp = N1;
N1 = N2;
N2 = tmp;
}
// get the 3 points of this triangle
gp_Pnt V1(Nodes(N1)), V2(Nodes(N2)), V3(Nodes(N3));
// transform the vertices to the place of the face
if (!identity) {
V1.Transform(myTransf);
V2.Transform(myTransf);
V3.Transform(myTransf);
}
// calculating per vertex normals
// Calculate triangle normal
gp_Vec v1(V1.X(),V1.Y(),V1.Z()),v2(V2.X(),V2.Y(),V2.Z()),v3(V3.X(),V3.Y(),V3.Z());
gp_Vec Normal = (v2-v1)^(v3-v1);
// add the triangle normal to the vertex normal for all points of this triangle
norms[FaceNodeOffset+N1-1] += SbVec3f(Normal.X(),Normal.Y(),Normal.Z());
norms[FaceNodeOffset+N2-1] += SbVec3f(Normal.X(),Normal.Y(),Normal.Z());
norms[FaceNodeOffset+N3-1] += SbVec3f(Normal.X(),Normal.Y(),Normal.Z());
// set the vertices
verts[FaceNodeOffset+N1-1].setValue((float)(V1.X()),(float)(V1.Y()),(float)(V1.Z()));
verts[FaceNodeOffset+N2-1].setValue((float)(V2.X()),(float)(V2.Y()),(float)(V2.Z()));
verts[FaceNodeOffset+N3-1].setValue((float)(V3.X()),(float)(V3.Y()),(float)(V3.Z()));
// set the index vector with the 3 point indexes and the end delimiter
index[FaceTriaOffset*4+4*(g-1)] = FaceNodeOffset+N1-1;
index[FaceTriaOffset*4+4*(g-1)+1] = FaceNodeOffset+N2-1;
index[FaceTriaOffset*4+4*(g-1)+2] = FaceNodeOffset+N3-1;
index[FaceTriaOffset*4+4*(g-1)+3] = SO_END_FACE_INDEX;
}
// counting up the per Face offsets
FaceNodeOffset += nbNodesInFace;
FaceTriaOffset += nbTriInFace;
}
// normalize all normals
for (int i=0; i < nbrNodes; i++)
norms[i].normalize();
// end the editing of the nodes
rejectedCoords ->point .finishEditing();
rejectedNorms ->vector .finishEditing();
rejectedFaceSet ->coordIndex .finishEditing();
// fill in the transformation matrices
SoMultipleCopy* rejectedTrfms = new SoMultipleCopy();
rejectedTrfms->matrix.setNum((o->second).size());
SbMatrix* mats = rejectedTrfms->matrix.startEditing();
std::list<gp_Trsf>::const_iterator trsf = (o->second).begin();
for (unsigned int i=0; i < (o->second).size(); i++,trsf++) {
Base::Matrix4D mat;
Part::TopoShape::convertToMatrix(*trsf,mat);
mats[i] = convert(mat);
}
rejectedTrfms->matrix.finishEditing();
rejectedTrfms->addChild(rejectedFaceSet);
SoSeparator* sep = new SoSeparator();
sep->addChild(rejectedCoords);
sep->addChild(rejectedNorms);
sep->addChild(rejectedTrfms);
pcRejectedRoot->addChild(sep);
}
catch (...) {
Base::Console().Error("Cannot compute Inventor representation for the rejected transformations of shape of %s.\n",
pcTransformed->getNameInDocument());
}
}
}
<|endoftext|> |
<commit_before>#include "StagePanel.h"
#include "StageCanvas.h"
#include "SelectSpritesOP.h"
#include "SymbolContainer.h"
#include "LibraryPanel.h"
#include "Symbol.h"
extern d2d::StageModule MODULE_STAGE;
namespace ecomplex
{
StagePanel::StagePanel(wxWindow* parent, wxTopLevelWindow* frame,
d2d::PropertySettingPanel* property,
LibraryPanel* library)
: EditPanel(parent, frame)
, d2d::SpritesPanelImpl(parent, new SymbolContainer(m_symbol = new Symbol))
, m_library(library)
, m_viewlist(NULL)
, m_group_panel(NULL)
{
m_editOP = new d2d::ArrangeSpriteOP<SelectSpritesOP>(this, this, property);
m_canvas = new StageCanvas(this);
SetDropTarget(new d2d::StageDropTarget(this, this, library));
MODULE_STAGE.impl = this;
}
StagePanel::StagePanel(wxWindow* parent, wxTopLevelWindow* frame,
Symbol* symbol,
d2d::PropertySettingPanel* property,
LibraryPanel* library)
: EditPanel(parent, frame)
, d2d::SpritesPanelImpl(parent, new SymbolContainer(m_symbol = symbol))
, m_library(library)
, m_viewlist(NULL)
, m_group_panel(NULL)
{
m_editOP = new d2d::ArrangeSpriteOP<SelectSpritesOP>(this, this, property);
m_canvas = new StageCanvas(this);
SetDropTarget(new d2d::StageDropTarget(this, this, library));
}
void StagePanel::clear()
{
d2d::EditPanel::clear();
Symbol* symbol = getSymbol();
for (size_t i = 0, n = symbol->m_sprites.size(); i < n; ++i)
symbol->m_sprites[i]->Release();
symbol->m_sprites.clear();
symbol->m_clipbox = d2d::Rect(0, 0);
}
void StagePanel::removeSprite(d2d::ISprite* sprite)
{
d2d::SpritesPanelImpl::removeSprite(sprite);
m_viewlist->remove(sprite);
m_group_panel->Remove(sprite);
}
void StagePanel::insertSprite(d2d::ISprite* sprite)
{
d2d::SpritesPanelImpl::insertSprite(sprite);
m_viewlist->insert(sprite);
}
bool StagePanel::resetSpriteOrder(d2d::ISprite* sprite, bool up)
{
bool ret = d2d::SpritesPanelImpl::resetSpriteOrder(sprite, up);
m_viewlist->reorder(sprite, up);
return ret;
}
} // complex<commit_msg>[FIXED] ecomplex的子界面删除时空指针<commit_after>#include "StagePanel.h"
#include "StageCanvas.h"
#include "SelectSpritesOP.h"
#include "SymbolContainer.h"
#include "LibraryPanel.h"
#include "Symbol.h"
extern d2d::StageModule MODULE_STAGE;
namespace ecomplex
{
StagePanel::StagePanel(wxWindow* parent, wxTopLevelWindow* frame,
d2d::PropertySettingPanel* property,
LibraryPanel* library)
: EditPanel(parent, frame)
, d2d::SpritesPanelImpl(parent, new SymbolContainer(m_symbol = new Symbol))
, m_library(library)
, m_viewlist(NULL)
, m_group_panel(NULL)
{
m_editOP = new d2d::ArrangeSpriteOP<SelectSpritesOP>(this, this, property);
m_canvas = new StageCanvas(this);
SetDropTarget(new d2d::StageDropTarget(this, this, library));
MODULE_STAGE.impl = this;
}
StagePanel::StagePanel(wxWindow* parent, wxTopLevelWindow* frame,
Symbol* symbol,
d2d::PropertySettingPanel* property,
LibraryPanel* library)
: EditPanel(parent, frame)
, d2d::SpritesPanelImpl(parent, new SymbolContainer(m_symbol = symbol))
, m_library(library)
, m_viewlist(NULL)
, m_group_panel(NULL)
{
m_editOP = new d2d::ArrangeSpriteOP<SelectSpritesOP>(this, this, property);
m_canvas = new StageCanvas(this);
SetDropTarget(new d2d::StageDropTarget(this, this, library));
}
void StagePanel::clear()
{
d2d::EditPanel::clear();
Symbol* symbol = getSymbol();
for (size_t i = 0, n = symbol->m_sprites.size(); i < n; ++i)
symbol->m_sprites[i]->Release();
symbol->m_sprites.clear();
symbol->m_clipbox = d2d::Rect(0, 0);
}
void StagePanel::removeSprite(d2d::ISprite* sprite)
{
d2d::SpritesPanelImpl::removeSprite(sprite);
m_viewlist->remove(sprite);
if (m_group_panel) {
m_group_panel->Remove(sprite);
}
}
void StagePanel::insertSprite(d2d::ISprite* sprite)
{
d2d::SpritesPanelImpl::insertSprite(sprite);
m_viewlist->insert(sprite);
}
bool StagePanel::resetSpriteOrder(d2d::ISprite* sprite, bool up)
{
bool ret = d2d::SpritesPanelImpl::resetSpriteOrder(sprite, up);
m_viewlist->reorder(sprite, up);
return ret;
}
} // complex<|endoftext|> |
<commit_before>/*!
\file binary_radix_tree_bvh.cpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#include "binary_radix_tree_bvh.hpp"
// Standard C++ library
#include <algorithm>
#include <functional>
#include <tuple>
#include <vector>
#include <utility>
// Zisc
#include "zisc/error.hpp"
#include "zisc/memory_resource.hpp"
#include "zisc/thread_manager.hpp"
// Nanairo
#include "aabb.hpp"
#include "bvh.hpp"
#include "bvh_building_node.hpp"
#include "morton_code.hpp"
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/system.hpp"
#include "NanairoCore/Data/object.hpp"
#include "NanairoCore/Setting/setting_node_base.hpp"
namespace nanairo {
/*!
\details
No detailed.
*/
BinaryRadixTreeBvh::BinaryRadixTreeBvh(System& system,
const SettingNodeBase* settings) noexcept :
Bvh(system, settings)
{
}
/*!
\details
No detailed.
*/
void BinaryRadixTreeBvh::constructBinaryRadixTreeBvh(
System& system,
const zisc::pmr::vector<Object>& object_list,
zisc::pmr::vector<BvhBuildingNode>& tree) noexcept
{
const auto num_of_nodes = 2 * object_list.size() - 1;
tree.resize(num_of_nodes);
auto work_resource = tree.get_allocator().resource();
// Make a morton code list
zisc::pmr::vector<MortonCode> morton_code_list{work_resource};
{
zisc::pmr::vector<BvhBuildingNode> leaf_node_list{work_resource};
leaf_node_list.reserve(object_list.size());
for (const auto& object : object_list)
leaf_node_list.emplace_back(&object);
morton_code_list = MortonCode::makeList(leaf_node_list);
}
constexpr bool threading = threadingIsEnabled();
{
auto first = morton_code_list.begin();
auto begin = first;
auto end = morton_code_list.end();
constexpr uint key_bit = 8 * sizeof(MortonCode::CodeType) - 1;
split<threading>(system, key_bit, 0, tree, first, begin, end);
}
setupBoundingBoxes<threading>(system, tree, 0);
}
/*!
\details
No detailed.
*/
void BinaryRadixTreeBvh::constructBvh(
System& system,
const zisc::pmr::vector<Object>& object_list,
zisc::pmr::vector<BvhBuildingNode>& tree) const noexcept
{
constructBinaryRadixTreeBvh(system, object_list, tree);
}
/*!
\details
No detailed.
*/
template <bool threading>
void BinaryRadixTreeBvh::split(System& system,
uint bit,
const uint32 index,
zisc::pmr::vector<BvhBuildingNode>& tree,
MortonCode::Iterator first,
MortonCode::Iterator begin,
MortonCode::Iterator end) noexcept
{
using zisc::cast;
const auto size = std::distance(begin, end);
const uint32 internal_node_size = cast<uint32>(tree.size() >> 1);
ZISC_ASSERT(index < tree.size(), "The index exceeds the tree size: ", index);
ZISC_ASSERT(0 < size, "The size of the range isn't positive: ", size);
if (1 < size) {
// Internal node
// Split leaf node list using the morton code
auto split_position = end;
for (;(0 < bit) && (split_position == begin || split_position == end); --bit)
split_position = MortonCode::findSplit(bit, begin, end);
if ((bit == 0) && (split_position == begin || split_position == end))
split_position = begin + (size >> 1);
uint32 right_child_index = cast<uint32>(std::distance(first, split_position));
uint32 left_child_index = right_child_index - 1;
left_child_index = (std::distance(begin, split_position) == 1)
? left_child_index + internal_node_size // Leaf node
: left_child_index; // Internal node
right_child_index = (std::distance(split_position, end) == 1)
? right_child_index + internal_node_size // Leaf node
: right_child_index; // Internal node
if (threading) {
auto split_left_range =
[&system, bit, left_child_index, &tree, first, begin, split_position]()
{
const auto key = (0 < bit) ? bit - 1 : bit;
split<>(system, key, left_child_index, tree, first, begin, split_position);
};
auto split_right_range =
[&system, bit, right_child_index, &tree, first, split_position, end]()
{
const auto key = (0 < bit) ? bit - 1 : bit;
split<>(system, key, right_child_index, tree, first, split_position, end);
};
auto work_resource = tree.get_allocator().resource();
auto& threads = system.threadManager();
auto left_result = threads.enqueue<void>(split_left_range, work_resource);
auto right_result = threads.enqueue<void>(split_right_range, work_resource);
left_result.get();
right_result.get();
}
else {
const auto key = (0 < bit) ? bit - 1 : bit;
split<>(system, key, left_child_index, tree, first, begin, split_position);
split<>(system, key, right_child_index, tree, first, split_position, end);
}
ZISC_ASSERT(tree[index].parentIndex() == BvhBuildingNode::nullIndex(),
"The node is rewrited.");
tree[index].setLeftChildIndex(left_child_index);
tree[index].setRightChildIndex(right_child_index);
// Child nodes
tree[left_child_index].setParentIndex(index);
tree[right_child_index].setParentIndex(index);
}
else {
// Leaf node
// Check if node is leaf node
ZISC_ASSERT(internal_node_size <= index, "The index is for internal: ", index);
tree[index] = *(begin->node());
}
}
} // namespace nanairo
<commit_msg>Fix a memory bug.<commit_after>/*!
\file binary_radix_tree_bvh.cpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#include "binary_radix_tree_bvh.hpp"
// Standard C++ library
#include <algorithm>
#include <functional>
#include <tuple>
#include <vector>
#include <utility>
// Zisc
#include "zisc/error.hpp"
#include "zisc/memory_resource.hpp"
#include "zisc/thread_manager.hpp"
// Nanairo
#include "aabb.hpp"
#include "bvh.hpp"
#include "bvh_building_node.hpp"
#include "morton_code.hpp"
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/system.hpp"
#include "NanairoCore/Data/object.hpp"
#include "NanairoCore/Setting/setting_node_base.hpp"
namespace nanairo {
/*!
\details
No detailed.
*/
BinaryRadixTreeBvh::BinaryRadixTreeBvh(System& system,
const SettingNodeBase* settings) noexcept :
Bvh(system, settings)
{
}
/*!
\details
No detailed.
*/
void BinaryRadixTreeBvh::constructBinaryRadixTreeBvh(
System& system,
const zisc::pmr::vector<Object>& object_list,
zisc::pmr::vector<BvhBuildingNode>& tree) noexcept
{
const auto num_of_nodes = 2 * object_list.size() - 1;
tree.resize(num_of_nodes);
auto work_resource = tree.get_allocator().resource();
// Make a morton code list
zisc::pmr::vector<BvhBuildingNode> leaf_node_list{work_resource};
zisc::pmr::vector<MortonCode> morton_code_list{work_resource};
{
leaf_node_list.reserve(object_list.size());
for (const auto& object : object_list)
leaf_node_list.emplace_back(&object);
morton_code_list = MortonCode::makeList(leaf_node_list);
}
constexpr bool threading = threadingIsEnabled();
{
auto first = morton_code_list.begin();
auto begin = first;
auto end = morton_code_list.end();
constexpr uint key_bit = 8 * sizeof(MortonCode::CodeType) - 1;
split<threading>(system, key_bit, 0, tree, first, begin, end);
}
setupBoundingBoxes<threading>(system, tree, 0);
}
/*!
\details
No detailed.
*/
void BinaryRadixTreeBvh::constructBvh(
System& system,
const zisc::pmr::vector<Object>& object_list,
zisc::pmr::vector<BvhBuildingNode>& tree) const noexcept
{
constructBinaryRadixTreeBvh(system, object_list, tree);
}
/*!
\details
No detailed.
*/
template <bool threading>
void BinaryRadixTreeBvh::split(System& system,
uint bit,
const uint32 index,
zisc::pmr::vector<BvhBuildingNode>& tree,
MortonCode::Iterator first,
MortonCode::Iterator begin,
MortonCode::Iterator end) noexcept
{
using zisc::cast;
const auto size = std::distance(begin, end);
const uint32 internal_node_size = cast<uint32>(tree.size() >> 1);
ZISC_ASSERT(index < tree.size(), "The index exceeds the tree size: ", index);
ZISC_ASSERT(0 < size, "The size of the range isn't positive: ", size);
if (1 < size) {
// Internal node
// Split leaf node list using the morton code
auto split_position = end;
for (;(0 < bit) && (split_position == begin || split_position == end); --bit)
split_position = MortonCode::findSplit(bit, begin, end);
if ((bit == 0) && (split_position == begin || split_position == end))
split_position = begin + (size >> 1);
uint32 right_child_index = cast<uint32>(std::distance(first, split_position));
uint32 left_child_index = right_child_index - 1;
left_child_index = (std::distance(begin, split_position) == 1)
? left_child_index + internal_node_size // Leaf node
: left_child_index; // Internal node
right_child_index = (std::distance(split_position, end) == 1)
? right_child_index + internal_node_size // Leaf node
: right_child_index; // Internal node
if (threading) {
auto split_left_range =
[&system, bit, left_child_index, &tree, first, begin, split_position]()
{
const auto key = (0 < bit) ? bit - 1 : bit;
split<>(system, key, left_child_index, tree, first, begin, split_position);
};
auto split_right_range =
[&system, bit, right_child_index, &tree, first, split_position, end]()
{
const auto key = (0 < bit) ? bit - 1 : bit;
split<>(system, key, right_child_index, tree, first, split_position, end);
};
auto work_resource = tree.get_allocator().resource();
auto& threads = system.threadManager();
auto left_result = threads.enqueue<void>(split_left_range, work_resource);
auto right_result = threads.enqueue<void>(split_right_range, work_resource);
left_result.get();
right_result.get();
}
else {
const auto key = (0 < bit) ? bit - 1 : bit;
split<>(system, key, left_child_index, tree, first, begin, split_position);
split<>(system, key, right_child_index, tree, first, split_position, end);
}
ZISC_ASSERT(tree[index].parentIndex() == BvhBuildingNode::nullIndex(),
"The node is rewrited.");
tree[index].setLeftChildIndex(left_child_index);
tree[index].setRightChildIndex(right_child_index);
// Child nodes
tree[left_child_index].setParentIndex(index);
tree[right_child_index].setParentIndex(index);
}
else {
// Leaf node
// Check if node is leaf node
ZISC_ASSERT(internal_node_size <= index, "The index is for internal: ", index);
tree[index] = *(begin->node());
}
}
} // namespace nanairo
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "../test_utils.h"
#include <babylon/engines/null_engine.h>
#include <babylon/engines/scene.h>
#include <babylon/meshes/abstract_mesh.h>
TEST(TestPositionAndRotation, TestConversionBetweenQuaternionsAndEuler)
{
using namespace BABYLON;
// Converting between quaternions/euler
Vector3 originalRotation{0.1f, 0.2f, 0.3f};
auto v = originalRotation.copy();
auto q = Quaternion::FromEulerVector(v);
q.toEulerAnglesToRef(v);
EXPECT_TRUE(v.subtract(originalRotation).length() < 0.00001f);
}
TEST(TestPositionAndRotation, TestReordersVectorInPlace)
{
using namespace BABYLON;
// Converting between quaternions/euler
Vector3 originalRotation{0.1f, 0.2f, 0.3f};
auto v = originalRotation.copy();
v.reorderInPlace("ZYX");
EXPECT_TRUE(v.subtract(Vector3(0.3f, 0.2f, 0.1f)).length() < 0.00001f);
}
TEST(TestPositionAndRotation, TestParenting)
{
using namespace BABYLON;
// Parent child positions
auto subject = createSubject();
auto scene = Scene::New(subject.get());
auto child = AbstractMesh::New("", scene.get());
auto parent = AbstractMesh::New("", scene.get());
parent->position().set(0.f, 0.f, 1.f);
child->position().set(0.f, 0.f, -1.f);
child->parent = parent.get();
child->computeWorldMatrix();
EXPECT_TRUE(child->absolutePosition().equals(Vector3{0.f, 0.f, 0.f}));
// Rotate parent around child
parent->rotationQuaternion = Quaternion();
Vector3 eulerRotation{0.f, Math::PI_2, 0.f};
Quaternion rotation;
Quaternion::RotationYawPitchRollToRef(eulerRotation.y, eulerRotation.x,
eulerRotation.z, rotation);
parent->rotationQuaternion()->multiplyInPlace(rotation);
parent->position().rotateByQuaternionAroundPointToRef(
rotation, child->absolutePosition(), parent->position());
EXPECT_TRUE(parent->position().subtract(Vector3(1.f, 0.f, 0.f)).length()
< 0.00001f);
EXPECT_TRUE(parent->rotationQuaternion()
->toEulerAngles()
.subtract(eulerRotation)
.length()
< 0.00001f);
EXPECT_TRUE(
child->absolutePosition().subtract(Vector3(0.f, 0.f, 0.f)).length()
< 0.00001f);
}
<commit_msg>Formatted position and rotation test<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "../test_utils.h"
#include <babylon/engines/null_engine.h>
#include <babylon/engines/scene.h>
#include <babylon/meshes/abstract_mesh.h>
TEST(TestPositionAndRotation, TestConversionBetweenQuaternionsAndEuler)
{
using namespace BABYLON;
// Converting between quaternions/euler
Vector3 originalRotation{0.1f, 0.2f, 0.3f};
auto v = originalRotation.copy();
auto q = Quaternion::FromEulerVector(v);
q.toEulerAnglesToRef(v);
EXPECT_TRUE(v.subtract(originalRotation).length() < 0.00001f);
}
TEST(TestPositionAndRotation, TestReordersVectorInPlace)
{
using namespace BABYLON;
// Converting between quaternions/euler
Vector3 originalRotation{0.1f, 0.2f, 0.3f};
auto v = originalRotation.copy();
v.reorderInPlace("ZYX");
EXPECT_TRUE(v.subtract(Vector3(0.3f, 0.2f, 0.1f)).length() < 0.00001f);
}
TEST(TestPositionAndRotation, TestParenting)
{
using namespace BABYLON;
// Parent child positions
auto subject = createSubject();
auto scene = Scene::New(subject.get());
auto child = AbstractMesh::New("", scene.get());
auto parent = AbstractMesh::New("", scene.get());
parent->position().set(0.f, 0.f, 1.f);
child->position().set(0.f, 0.f, -1.f);
child->parent = parent.get();
child->computeWorldMatrix();
EXPECT_TRUE(child->absolutePosition().equals(Vector3{0.f, 0.f, 0.f}));
// Rotate parent around child
parent->rotationQuaternion = Quaternion();
Vector3 eulerRotation{0.f, Math::PI_2, 0.f};
Quaternion rotation;
Quaternion::RotationYawPitchRollToRef(eulerRotation.y, eulerRotation.x, eulerRotation.z,
rotation);
parent->rotationQuaternion()->multiplyInPlace(rotation);
parent->position().rotateByQuaternionAroundPointToRef(rotation, child->absolutePosition(),
parent->position());
EXPECT_TRUE(parent->position().subtract(Vector3(1.f, 0.f, 0.f)).length() < 0.00001f);
EXPECT_TRUE(parent->rotationQuaternion()->toEulerAngles().subtract(eulerRotation).length()
< 0.00001f);
EXPECT_TRUE(child->absolutePosition().subtract(Vector3(0.f, 0.f, 0.f)).length() < 0.00001f);
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* tuple_transformer.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/bridge/tuple_transformer.cpp
*
*-------------------------------------------------------------------------
*/
#include <iostream>
#include "backend/bridge/dml/tuple/tuple_transformer.h"
#include "backend/common/logger.h"
#include "backend/common/value_peeker.h"
#include "backend/storage/tuple.h"
#include "backend/common/types.h"
#include "backend/bridge/ddl/ddl.h"
#include "access/htup_details.h"
#include "nodes/print.h"
#include "utils/builtins.h"
namespace peloton {
namespace bridge {
/**
* @brief Convert from Datum to Value.
* @return converted Value.
*/
Value TupleTransformer::GetValue(Datum datum, Oid atttypid) {
Value value;
switch (atttypid) {
case POSTGRES_VALUE_TYPE_SMALLINT: {
int16_t smallint = DatumGetInt16(datum);
LOG_TRACE("%d\n", smallint);
value = ValueFactory::GetSmallIntValue(smallint);
} break;
case POSTGRES_VALUE_TYPE_INTEGER: {
int32_t integer = DatumGetInt32(datum);
LOG_TRACE("%d\n", integer);
value = ValueFactory::GetIntegerValue(integer);
} break;
case POSTGRES_VALUE_TYPE_BIGINT: {
int64_t bigint = DatumGetInt64(datum);
LOG_TRACE("%ld\n", bigint);
value = ValueFactory::GetBigIntValue(bigint);
} break;
/*
* In PG, BPCHAR and VARCHAR and TEXT are represented using
* 'struct varlena',
* which is a 4-byte header followed by the meat.
* However, the 4-byte header should not be accessed directly.
* It should be used in MACROS:
* VARSIZE(ptr), VARDATA(ptr) and VARHDRSZ.
* NB1: VARSIZE(ptr) is the size of the meat PLUS the header.
* NB2: DON'T assume strings have terminating-null's.
*/
case POSTGRES_VALUE_TYPE_BPCHAR: {
struct varlena *bpcharptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(bpcharptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(bpcharptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , bpchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_VARCHAR2: {
struct varlena *varlenptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(varlenptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(varlenptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , varchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TEXT: {
struct varlena *textptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(textptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(textptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , text = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TIMESTAMPS: {
long int timestamp = DatumGetInt64(datum);
value = ValueFactory::GetTimestampValue(timestamp);
} break;
default:
LOG_ERROR("Unknown atttypeid : %u ", atttypid);
break;
}
return value;
}
/**
* @brief Convert from Value to Datum.
* @return converted Datum.
*/
Datum TupleTransformer::GetDatum(Value value) {
ValueType value_type;
Datum datum;
value_type = value.GetValueType();
switch (value_type) {
case VALUE_TYPE_SMALLINT: {
int16_t smallint = ValuePeeker::PeekSmallInt(value);
LOG_TRACE("%d\n", smallint);
datum = Int16GetDatum(smallint);
} break;
case VALUE_TYPE_INTEGER: {
int32_t integer = ValuePeeker::PeekInteger(value);
LOG_TRACE("%d\n", integer);
datum = Int32GetDatum(integer);
} break;
case VALUE_TYPE_BIGINT: {
int64_t bigint = ValuePeeker::PeekBigInt(value);
LOG_TRACE("%ld\n", bigint);
datum = Int64GetDatum(bigint);
} break;
case VALUE_TYPE_DOUBLE: {
double double_precision = ValuePeeker::PeekDouble(value);
LOG_TRACE("%f\n", double_precision);
datum = Float8GetDatum(double_precision);
} break;
case VALUE_TYPE_VARCHAR: {
char *data_ptr = static_cast<char *>(ValuePeeker::PeekObjectValue(value));
auto data_len = ValuePeeker::PeekObjectLength(value);
// NB: Peloton object don't have terminating-null's, so
// we should use PG functions that take explicit length.
datum = PointerGetDatum(cstring_to_text_with_len(data_ptr, data_len));
} break;
case VALUE_TYPE_TIMESTAMP: {
long int timestamp = ValuePeeker::PeekTimestamp(value);
datum = Int64GetDatum(timestamp);
LOG_TRACE("%s\n", DatumGetCString(timestamp));
} break;
default:
datum = PointerGetDatum(nullptr);
LOG_ERROR("Unrecognized value type : %u\n", value_type);
break;
}
return datum;
}
/**
* @brief Convert a Postgres tuple into Peloton tuple
* @param slot Postgres tuple
* @param schema Peloton scheme of the table to which the tuple belongs
* @return a Peloton tuple
*/
storage::Tuple *TupleTransformer::GetPelotonTuple(
TupleTableSlot *slot, const catalog::Schema *schema) {
assert(slot);
TupleDesc tuple_desc = slot->tts_tupleDescriptor;
int natts = tuple_desc->natts;
bool isnull;
// Allocate space for a new tuple with given schema
storage::Tuple *tuple = new storage::Tuple(schema, true);
// Go over each attribute and convert Datum to Value
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Datum attr = slot_getattr(slot, att_itr + 1, &isnull);
if (isnull) continue;
Form_pg_attribute attribute_info = tuple_desc->attrs[att_itr];
Oid attribute_type_id = attribute_info->atttypid;
Value value = GetValue(attr, attribute_type_id);
tuple->SetValue(att_itr++, value);
}
return tuple;
}
/**
* @brief Convert a Peloton tuple into Postgres tuple slot
* @param tuple Peloton tuple
* @return a Postgres tuple
*/
TupleTableSlot *TupleTransformer::GetPostgresTuple(storage::Tuple *tuple,
TupleDesc tuple_desc) {
assert(tuple);
assert(tuple_desc);
TupleTableSlot *slot = NULL;
HeapTuple heap_tuple;
int natts = tuple_desc->natts;
Datum *datums;
bool *nulls;
if (tuple->GetColumnCount() != natts) {
LOG_WARN("tuple attr count : %u tuple desc attr count : %d \n",
tuple->GetColumnCount(), natts);
return nullptr;
}
// Allocate space for datums
datums = (Datum *)palloc0(natts * sizeof(Datum));
nulls = (bool *)palloc0(natts * sizeof(bool));
// Go over each attribute and convert Value to Datum
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Value value = tuple->GetValue(att_itr);
Datum datum = GetDatum(value);
assert(tuple_desc->attrs[att_itr]->attbyval == true ||
value.GetValueType() == VALUE_TYPE_VARCHAR ||
value.GetValueType() == VALUE_TYPE_VARBINARY);
datums[att_itr] = datum;
nulls[att_itr] = tuple->IsNull(att_itr) ? true : false;
}
// Construct tuple
// PG does a deep copy in heap_form_tuple()
heap_tuple = heap_form_tuple(tuple_desc, datums, nulls);
// Construct slot
slot = MakeSingleTupleTableSlot(tuple_desc);
// Store tuple in slot
// This function just sets a point in slot to the heap_tuple.
ExecStoreTuple(heap_tuple, slot, InvalidBuffer, true);
// Clean up Datums (A-B): seems we have to do the cleaning manually (no PG
// utility?)
// (A) Clean up any possible varlena's
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
if (tuple_desc->attrs[att_itr]->attlen < 0) { // should be a varlena
assert(tuple_desc->attrs[att_itr]->attbyval == false);
pfree((void *)(datums[att_itr]));
}
}
// (B) Free the datum array itself
pfree(datums);
pfree(nulls);
return slot;
}
} // namespace bridge
} // namespace peloton
<commit_msg>trying to support decimal.<commit_after>/*-------------------------------------------------------------------------
*
* tuple_transformer.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/bridge/tuple_transformer.cpp
*
*-------------------------------------------------------------------------
*/
#include <iostream>
#include "backend/bridge/dml/tuple/tuple_transformer.h"
#include "backend/common/logger.h"
#include "backend/common/value_peeker.h"
#include "backend/storage/tuple.h"
#include "backend/common/types.h"
#include "backend/bridge/ddl/ddl.h"
#include "access/htup_details.h"
#include "nodes/print.h"
#include "utils/builtins.h"
#include "utils/numeric.h"
extern struct NumericVar;
namespace peloton {
namespace bridge {
/**
* @brief Convert from Datum to Value.
* @return converted Value.
*/
Value TupleTransformer::GetValue(Datum datum, Oid atttypid) {
Value value;
switch (atttypid) {
case POSTGRES_VALUE_TYPE_SMALLINT: {
int16_t smallint = DatumGetInt16(datum);
LOG_TRACE("%d\n", smallint);
value = ValueFactory::GetSmallIntValue(smallint);
} break;
case POSTGRES_VALUE_TYPE_INTEGER: {
int32_t integer = DatumGetInt32(datum);
LOG_TRACE("%d\n", integer);
value = ValueFactory::GetIntegerValue(integer);
} break;
case POSTGRES_VALUE_TYPE_BIGINT: {
int64_t bigint = DatumGetInt64(datum);
LOG_TRACE("%ld\n", bigint);
value = ValueFactory::GetBigIntValue(bigint);
} break;
/*
* In PG, BPCHAR and VARCHAR and TEXT are represented using
* 'struct varlena',
* which is a 4-byte header followed by the meat.
* However, the 4-byte header should not be accessed directly.
* It should be used in MACROS:
* VARSIZE(ptr), VARDATA(ptr) and VARHDRSZ.
* NB1: VARSIZE(ptr) is the size of the meat PLUS the header.
* NB2: DON'T assume strings have terminating-null's.
*/
case POSTGRES_VALUE_TYPE_BPCHAR: {
struct varlena *bpcharptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(bpcharptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(bpcharptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , bpchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_VARCHAR2: {
struct varlena *varlenptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(varlenptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(varlenptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , varchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TEXT: {
struct varlena *textptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(textptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(textptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , text = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TIMESTAMPS: {
long int timestamp = DatumGetInt64(datum);
value = ValueFactory::GetTimestampValue(timestamp);
} break;
case POSTGRES_VALUE_TYPE_DECIMAL:{
// 1. Get string representation of the PG numeric (this is tricky)
char* cstr = DatumGetCString(DirectFunctionCall1(numeric_out, datum));
// 2. Construct Peloton Decimal from a string
value = ValueFactory::GetDecimalValueFromString(std::string(cstr));
pfree(cstr);
} break;
default:
LOG_ERROR("Unknown atttypeid : %u ", atttypid);
break;
}
return value;
}
/**
* @brief Convert from Value to Datum.
* @return converted Datum.
*/
Datum TupleTransformer::GetDatum(Value value) {
ValueType value_type;
Datum datum;
value_type = value.GetValueType();
switch (value_type) {
case VALUE_TYPE_SMALLINT: {
int16_t smallint = ValuePeeker::PeekSmallInt(value);
LOG_TRACE("%d\n", smallint);
datum = Int16GetDatum(smallint);
} break;
case VALUE_TYPE_INTEGER: {
int32_t integer = ValuePeeker::PeekInteger(value);
LOG_TRACE("%d\n", integer);
datum = Int32GetDatum(integer);
} break;
case VALUE_TYPE_BIGINT: {
int64_t bigint = ValuePeeker::PeekBigInt(value);
LOG_TRACE("%ld\n", bigint);
datum = Int64GetDatum(bigint);
} break;
case VALUE_TYPE_DOUBLE: {
double double_precision = ValuePeeker::PeekDouble(value);
LOG_TRACE("%f\n", double_precision);
datum = Float8GetDatum(double_precision);
} break;
case VALUE_TYPE_VARCHAR: {
char *data_ptr = static_cast<char *>(ValuePeeker::PeekObjectValue(value));
auto data_len = ValuePeeker::PeekObjectLength(value);
// NB: Peloton object don't have terminating-null's, so
// we should use PG functions that take explicit length.
datum = PointerGetDatum(cstring_to_text_with_len(data_ptr, data_len));
} break;
case VALUE_TYPE_TIMESTAMP: {
long int timestamp = ValuePeeker::PeekTimestamp(value);
datum = Int64GetDatum(timestamp);
LOG_TRACE("%s\n", DatumGetCString(timestamp));
} break;
default:
datum = PointerGetDatum(nullptr);
LOG_ERROR("Unrecognized value type : %u\n", value_type);
break;
}
return datum;
}
/**
* @brief Convert a Postgres tuple into Peloton tuple
* @param slot Postgres tuple
* @param schema Peloton scheme of the table to which the tuple belongs
* @return a Peloton tuple
*/
storage::Tuple *TupleTransformer::GetPelotonTuple(
TupleTableSlot *slot, const catalog::Schema *schema) {
assert(slot);
TupleDesc tuple_desc = slot->tts_tupleDescriptor;
int natts = tuple_desc->natts;
bool isnull;
// Allocate space for a new tuple with given schema
storage::Tuple *tuple = new storage::Tuple(schema, true);
// Go over each attribute and convert Datum to Value
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Datum attr = slot_getattr(slot, att_itr + 1, &isnull);
if (isnull) continue;
Form_pg_attribute attribute_info = tuple_desc->attrs[att_itr];
Oid attribute_type_id = attribute_info->atttypid;
Value value = GetValue(attr, attribute_type_id);
tuple->SetValue(att_itr++, value);
}
return tuple;
}
/**
* @brief Convert a Peloton tuple into Postgres tuple slot
* @param tuple Peloton tuple
* @return a Postgres tuple
*/
TupleTableSlot *TupleTransformer::GetPostgresTuple(storage::Tuple *tuple,
TupleDesc tuple_desc) {
assert(tuple);
assert(tuple_desc);
TupleTableSlot *slot = NULL;
HeapTuple heap_tuple;
int natts = tuple_desc->natts;
Datum *datums;
bool *nulls;
if (tuple->GetColumnCount() != natts) {
LOG_WARN("tuple attr count : %u tuple desc attr count : %d \n",
tuple->GetColumnCount(), natts);
return nullptr;
}
// Allocate space for datums
datums = (Datum *)palloc0(natts * sizeof(Datum));
nulls = (bool *)palloc0(natts * sizeof(bool));
// Go over each attribute and convert Value to Datum
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Value value = tuple->GetValue(att_itr);
Datum datum = GetDatum(value);
assert(tuple_desc->attrs[att_itr]->attbyval == true ||
value.GetValueType() == VALUE_TYPE_VARCHAR ||
value.GetValueType() == VALUE_TYPE_VARBINARY);
datums[att_itr] = datum;
nulls[att_itr] = tuple->IsNull(att_itr) ? true : false;
}
// Construct tuple
// PG does a deep copy in heap_form_tuple()
heap_tuple = heap_form_tuple(tuple_desc, datums, nulls);
// Construct slot
slot = MakeSingleTupleTableSlot(tuple_desc);
// Store tuple in slot
// This function just sets a point in slot to the heap_tuple.
ExecStoreTuple(heap_tuple, slot, InvalidBuffer, true);
// Clean up Datums (A-B): seems we have to do the cleaning manually (no PG
// utility?)
// (A) Clean up any possible varlena's
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
if (tuple_desc->attrs[att_itr]->attlen < 0) { // should be a varlena
assert(tuple_desc->attrs[att_itr]->attbyval == false);
pfree((void *)(datums[att_itr]));
}
}
// (B) Free the datum array itself
pfree(datums);
pfree(nulls);
return slot;
}
} // namespace bridge
} // namespace peloton
<|endoftext|> |
<commit_before>#include "BuildingQueue.h"
#include "bwem.h"
#include "UnitManager.h"
#include "BaseManager.h"
#include "BuildingPlacer.h"
#include "DrawingManager.h"
Neolib::BuildingQueue buildingQueue;
namespace Neolib {
void BuildingQueue::onFrame() {
for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) {
if (it->buildingType.getRace() == BWAPI::Races::Terran && !it->builder) {
}
if (it->builder) {
auto order = it->builder->getOrder();
if (order == BWAPI::Orders::ConstructingBuilding)
continue;
else if (order == BWAPI::Orders::PlaceBuilding)
continue;
if (resourceManager.canAfford(it->buildingType)) {
if (it->buildingUnit) {
it->builder->rightClick(it->buildingUnit);
}
else {
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
else {
it->builder = baseManager.findClosestBuilder(it->buildingType.whatBuilds().first, (BWAPI::Position)it->designatedLocation);
if (it->builder)
if (it->buildingUnit)
it->builder->rightClick(it->buildingUnit);
else
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
void BuildingQueue::onUnitComplete(BWAPI::Unit unit) {
// Check if our building is done
for (auto it = buildingQueue.begin(); it != buildingQueue.end();) {
if (it->buildingUnit == unit) {
if (it->buildingType.getRace() == BWAPI::Races::Terran && it->builder)
baseManager.giveBackUnit(it->builder);
it = buildingQueue.erase(it);
} else {
++it;
}
}
}
void BuildingQueue::onUnitCreate(BWAPI::Unit unit) {
// If our building was placed
for (auto &o : buildingQueue) {
if (o.buildingType == unit->getType() && o.designatedLocation == unit->getTilePosition()) {
o.buildingUnit = unit;
}
}
}
void BuildingQueue::onUnitDestroy(BWAPI::Unit unit) {
// Check if our builder died
for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) {
if (it->builder == unit) {
// Find replacement builder
it->builder = baseManager.findClosestBuilder(it->buildingType.whatBuilds().first, (BWAPI::Position)it->designatedLocation);
if (it->builder) {
baseManager.takeUnit(it->builder);
if (it->buildingUnit && it->buildingUnit->exists()) {
it->builder->rightClick(it->buildingUnit);
}
if (!it->buildingUnit) {
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
}
// Check if our building died
for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) {
if (it->buildingUnit == unit) {
it->buildingUnit = nullptr;
if (it->builder && it->builder->exists())
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
void BuildingQueue::onUnitMorph(BWAPI::Unit unit) {
onUnitCreate(unit);
}
bool BuildingQueue::doBuild(BWAPI::UnitType building, BWAPI::TilePosition at, BWAPI::Unit u) {
if (at == BWAPI::TilePositions::None) {
if (!u && !(u = baseManager.findBuilder(building))) // Could not a find builder
return false;
at = buildingPlacer.getBuildLocation(building, u->getTilePosition());
if (at == BWAPI::TilePositions::None) {
drawingManager.failedLocations.insert({ at, building });
BWAPI::Broodwar->pingMinimap((BWAPI::Position)at);
return false;
}
}
else
if (!u && !(u = baseManager.findClosestBuilder(building, (BWAPI::Position) at))) // Could not a find builder
return false;
// If build location intersects another build location, nope out
BWAPI::TilePosition buildingEnd(at + building.tileSize());
for (auto &o : buildingQueue) {
BWAPI::TilePosition otherEnd(o.designatedLocation + o.buildingType.tileSize());
if (at.x < o.designatedLocation.x) {
if (at.y < o.designatedLocation.y) {
if (o.designatedLocation.x < buildingEnd.x && o.designatedLocation.y < buildingEnd.y)
return false;
else if (o.designatedLocation.x < buildingEnd.x && at.y < otherEnd.y)
return false;
}
}
else {
if (at.y < o.designatedLocation.y) {
if (at.x < otherEnd.x && o.designatedLocation.y < buildingEnd.y)
return false;
}
else if (at.x < otherEnd.x && at.y < otherEnd.y)
return false;
}
}
//if (u)
// baseManager.takeUnit(u);
if (u->build(building, at)) {
ConstructionProject cp;
cp.builder = u;
cp.buildingType = building;
cp.designatedLocation = at;
buildingQueue.emplace_back(cp);
return true;
}
else {
if (!BWAPI::Broodwar->isVisible(at))
u->move((BWAPI::Position)at);
drawingManager.failedLocations.insert({ at, building });
BWAPI::Broodwar->pingMinimap((BWAPI::Position)at);
return false;
}
}
ResourceCount BuildingQueue::getQueuedResources() const {
ResourceCount resourceCount;
for (auto &o : this->buildingQueue)
if (!o.buildingUnit)
resourceCount += o.buildingType;
return resourceCount;
}
SupplyCount BuildingQueue::getQueuedSupply(bool countResourceDepots) const {
SupplyCount supplyCount;
for (auto &o : buildingQueue) {
// Terran
if (o.buildingType == BWAPI::UnitTypes::Terran_Supply_Depot)
supplyCount.terran += 16;
else if (o.buildingType == BWAPI::UnitTypes::Terran_Command_Center && countResourceDepots)
supplyCount.terran += 20;
// Protoss
else if (o.buildingType == BWAPI::UnitTypes::Protoss_Pylon)
supplyCount.protoss += 16;
else if (o.buildingType == BWAPI::UnitTypes::Protoss_Nexus && countResourceDepots)
supplyCount.protoss += 18;
// Zerg
else if (o.buildingType == BWAPI::UnitTypes::Zerg_Overlord)
supplyCount.zerg += 16;
else if (o.buildingType == BWAPI::UnitTypes::Zerg_Hatchery && countResourceDepots)
supplyCount.zerg += 2;
}
return supplyCount;
}
bool BuildingQueue::isWorkerBuilding(BWAPI::Unit u) const {
for (auto &o : buildingQueue)
if (o.builder == u)
return true;
return false;
}
const std::list <ConstructionProject> &BuildingQueue::buildingsQueued() {
return buildingQueue;
}
}
<commit_msg>Changed queue logic, also far from final<commit_after>#include "BuildingQueue.h"
#include "bwem.h"
#include "UnitManager.h"
#include "BaseManager.h"
#include "BuildingPlacer.h"
#include "DrawingManager.h"
Neolib::BuildingQueue buildingQueue;
namespace Neolib {
void BuildingQueue::onFrame() {
for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) {
if (it->buildingType.getRace() == BWAPI::Races::Terran && !it->builder) {
it->builder = baseManager.findClosestBuilder(it->buildingType.whatBuilds().first, (BWAPI::Position)it->designatedLocation);
if (it->builder)
if (it->buildingUnit)
it->builder->rightClick(it->buildingUnit);
else
it->builder->build(it->buildingType, it->designatedLocation);
}
if (it->builder) {
auto order = it->builder->getOrder();
if (order == BWAPI::Orders::ConstructingBuilding)
continue;
else if (order == BWAPI::Orders::PlaceBuilding)
continue;
if (it->buildingUnit)
it->builder->rightClick(it->buildingUnit);
else
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
void BuildingQueue::onUnitComplete(BWAPI::Unit unit) {
// Check if our building is done
for (auto it = buildingQueue.begin(); it != buildingQueue.end();) {
if (it->buildingUnit == unit) {
if (it->buildingType.getRace() == BWAPI::Races::Terran && it->builder)
baseManager.giveBackUnit(it->builder);
it = buildingQueue.erase(it);
} else {
++it;
}
}
}
void BuildingQueue::onUnitCreate(BWAPI::Unit unit) {
// If our building was placed
for (auto &o : buildingQueue) {
if (o.buildingType == unit->getType() && o.designatedLocation == unit->getTilePosition()) {
o.buildingUnit = unit;
}
}
}
void BuildingQueue::onUnitDestroy(BWAPI::Unit unit) {
// Check if our builder died
for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) {
if (it->builder == unit) {
// Find replacement builder
it->builder = baseManager.findClosestBuilder(it->buildingType.whatBuilds().first, (BWAPI::Position)it->designatedLocation);
if (it->builder) {
baseManager.takeUnit(it->builder);
if (it->buildingUnit && it->buildingUnit->exists()) {
it->builder->rightClick(it->buildingUnit);
}
if (!it->buildingUnit) {
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
}
// Check if our building died
for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) {
if (it->buildingUnit == unit) {
it->buildingUnit = nullptr;
if (it->builder && it->builder->exists())
it->builder->build(it->buildingType, it->designatedLocation);
}
}
}
void BuildingQueue::onUnitMorph(BWAPI::Unit unit) {
onUnitCreate(unit);
}
bool BuildingQueue::doBuild(BWAPI::UnitType building, BWAPI::TilePosition at, BWAPI::Unit u) {
if (at == BWAPI::TilePositions::None) {
if (!u && !(u = baseManager.findBuilder(building))) // Could not a find builder
return false;
at = buildingPlacer.getBuildLocation(building, u->getTilePosition());
if (at == BWAPI::TilePositions::None)
return false;
}
else
if (!u && !(u = baseManager.findClosestBuilder(building, (BWAPI::Position) at))) // Could not a find builder
return false;
// If build location intersects another build location, nope out
BWAPI::TilePosition buildingEnd(at + building.tileSize());
for (auto &o : buildingQueue) {
BWAPI::TilePosition otherEnd(o.designatedLocation + o.buildingType.tileSize());
if (at.x < o.designatedLocation.x) {
if (at.y < o.designatedLocation.y) {
if (o.designatedLocation.x < buildingEnd.x && o.designatedLocation.y < buildingEnd.y)
return false;
else if (o.designatedLocation.x < buildingEnd.x && at.y < otherEnd.y)
return false;
}
}
else {
if (at.y < o.designatedLocation.y) {
if (at.x < otherEnd.x && o.designatedLocation.y < buildingEnd.y)
return false;
}
else if (at.x < otherEnd.x && at.y < otherEnd.y)
return false;
}
}
if (u)
baseManager.takeUnit(u);
if (u->build(building, at)) {
ConstructionProject cp;
cp.builder = u;
cp.buildingType = building;
cp.designatedLocation = at;
buildingQueue.emplace_back(cp);
return true;
}
else {
drawingManager.failedLocations.insert({ at, building });
BWAPI::Broodwar->pingMinimap((BWAPI::Position)at);
return false;
}
}
ResourceCount BuildingQueue::getQueuedResources() const {
ResourceCount resourceCount;
for (auto &o : this->buildingQueue)
if (!o.buildingUnit)
resourceCount += o.buildingType;
return resourceCount;
}
SupplyCount BuildingQueue::getQueuedSupply(bool countResourceDepots) const {
SupplyCount supplyCount;
for (auto &o : buildingQueue) {
// Terran
if (o.buildingType == BWAPI::UnitTypes::Terran_Supply_Depot)
supplyCount.terran += 16;
else if (o.buildingType == BWAPI::UnitTypes::Terran_Command_Center && countResourceDepots)
supplyCount.terran += 20;
// Protoss
else if (o.buildingType == BWAPI::UnitTypes::Protoss_Pylon)
supplyCount.protoss += 16;
else if (o.buildingType == BWAPI::UnitTypes::Protoss_Nexus && countResourceDepots)
supplyCount.protoss += 18;
// Zerg
else if (o.buildingType == BWAPI::UnitTypes::Zerg_Overlord)
supplyCount.zerg += 16;
else if (o.buildingType == BWAPI::UnitTypes::Zerg_Hatchery && countResourceDepots)
supplyCount.zerg += 2;
}
return supplyCount;
}
bool BuildingQueue::isWorkerBuilding(BWAPI::Unit u) const {
for (auto &o : buildingQueue)
if (o.builder == u)
return true;
return false;
}
const std::list <ConstructionProject> &BuildingQueue::buildingsQueued() {
return buildingQueue;
}
}
<|endoftext|> |
<commit_before>// Time: O(b * b! * h!)
// Space: O(b * b! * h!)
class Solution {
public:
int findMinStep(string board, string hand) {
unordered_map<string, unordered_map<string, int>> lookup;
sort(hand.begin(), hand.end());
int result = findMinStepHelper(board, hand, &lookup);
return result > hand.size() ? -1 : result;
}
private:
int findMinStepHelper(const string& board, const string& hand,
unordered_map<string, unordered_map<string, int>> *lookup) {
if (board.empty()) {
return 0;
}
if (hand.empty()) {
return MAX_STEP;
}
if ((*lookup)[board][hand]) {
return (*lookup)[board][hand];
}
int result = MAX_STEP;
for (int i = 0; i < hand.size(); ++i) {
int j = 0;
int n = board.size();
while (j < n) {
int k = board.find(hand[i], j);
if (k == string::npos) {
break;
}
if (k < n - 1 && board[k] == board[k + 1]) {
string next_board = shrink(board.substr(0, k) + board.substr(k + 2));
string next_hand = hand.substr(0, i) + hand.substr(i + 1);
result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1);
++k;
} else if (i > 0 && hand[i] == hand[i - 1]) {
string next_board = shrink(board.substr(0, k) + board.substr(k + 1));
string next_hand = hand.substr(0, i - 1) + hand.substr(i + 1);
result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 2);
}
j = k + 1;
}
}
return (*lookup)[board][hand] = result;
}
string shrink(const string& s) { // Time: O(n), Space: O(n)
vector<pair<char, int>> stack;
for (int i = 0, start = 0; i <= s.size(); ++i) {
if (i == s.size() || s[i] != s[start]) {
if (!stack.empty() && stack.back().first == s[start]) {
stack.back().second += i - start;
if (stack.back().second >= 3) {
stack.pop_back();
}
} else if (i - start < 3) {
stack.emplace_back(s[start], i - start);
}
start = i;
}
}
string result;
for (const auto& p : stack) {
result += string(p.second, p.first);
}
return result;
}
static const int MAX_STEP = 6;
};
<commit_msg>Update zuma-game.cpp<commit_after>// Time: O(b * b! * h!)
// Space: O(b * b! * h!)
class Solution {
public:
int findMinStep(string board, string hand) {
unordered_map<string, unordered_map<string, int>> lookup;
sort(hand.begin(), hand.end());
int result = findMinStepHelper(board, hand, &lookup);
return result > hand.size() ? -1 : result;
}
private:
int findMinStepHelper(const string& board, const string& hand,
unordered_map<string, unordered_map<string, int>> *lookup) {
if (board.empty()) {
return 0;
}
if (hand.empty()) {
return MAX_STEP;
}
if ((*lookup)[board][hand]) {
return (*lookup)[board][hand];
}
int result = MAX_STEP;
for (int i = 0; i < hand.size(); ++i) {
int j = 0;
while (j < board.size()) {
int k = board.find(hand[i], j);
if (k == string::npos) {
break;
}
if (k < board.size() - 1 && board[k] == board[k + 1]) {
string next_board = shrink(board.substr(0, k) + board.substr(k + 2));
string next_hand = hand.substr(0, i) + hand.substr(i + 1);
result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1);
++k;
} else if (i > 0 && hand[i] == hand[i - 1]) {
string next_board = shrink(board.substr(0, k) + board.substr(k + 1));
string next_hand = hand.substr(0, i - 1) + hand.substr(i + 1);
result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 2);
}
j = k + 1;
}
}
return (*lookup)[board][hand] = result;
}
string shrink(const string& s) { // Time: O(n), Space: O(n)
vector<pair<char, int>> stack;
for (int i = 0, start = 0; i <= s.size(); ++i) {
if (i == s.size() || s[i] != s[start]) {
if (!stack.empty() && stack.back().first == s[start]) {
stack.back().second += i - start;
if (stack.back().second >= 3) {
stack.pop_back();
}
} else if (i - start < 3) {
stack.emplace_back(s[start], i - start);
}
start = i;
}
}
string result;
for (const auto& p : stack) {
result += string(p.second, p.first);
}
return result;
}
static const int MAX_STEP = 6;
};
<|endoftext|> |
<commit_before>//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsTargetHandler.h"
#include "MipsLinkingContext.h"
#include "MipsRelocationHandler.h"
#include "lld/ReaderWriter/RelocationHelperFunctions.h"
using namespace lld;
using namespace elf;
using namespace llvm::ELF;
static inline void applyReloc(uint8_t *loc, uint32_t result, uint32_t mask) {
auto target = reinterpret_cast<llvm::support::ulittle32_t *>(loc);
*target = (uint32_t(*target) & ~mask) | (result & mask);
}
template <size_t BITS, class T> inline T signExtend(T val) {
if (val & (T(1) << (BITS - 1)))
val |= T(-1) << BITS;
return val;
}
/// \brief R_MIPS_32
/// local/external: word32 S + A (truncate)
static void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) {
applyReloc(location, S + A, 0xffffffff);
}
/// \brief R_MIPS_PC32
/// local/external: word32 S + A i- P (truncate)
void relocpc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) {
applyReloc(location, S + A - P, 0xffffffff);
}
/// \brief R_MIPS_26
/// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2
static void reloc26loc(uint8_t *location, uint64_t P, uint64_t S, int32_t A) {
uint32_t result = ((A << 2) | ((P + 4) & 0x3f000000)) + S;
applyReloc(location, result >> 2, 0x03ffffff);
}
/// \brief LLD_R_MIPS_GLOBAL_26
/// external: (sign-extend(A) + S) >> 2
static void reloc26ext(uint8_t *location, uint64_t S, int32_t A) {
uint32_t result = signExtend<28>(A << 2) + S;
applyReloc(location, result >> 2, 0x03ffffff);
}
/// \brief R_MIPS_HI16
/// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate)
/// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify)
static void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = (AHL + S - P) - (int16_t)(AHL + S - P);
else
result = (AHL + S) - (int16_t)(AHL + S);
applyReloc(location, result >> 16, 0xffff);
}
/// \brief R_MIPS_LO16
/// local/external: lo16 AHL + S (truncate)
/// _gp_disp : lo16 AHL + GP - P + 4 (verify)
static void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = AHL + S - P + 4;
else
result = AHL + S;
applyReloc(location, result, 0xffff);
}
/// \brief R_MIPS_GOT16, R_MIPS_CALL16
/// rel16 G (verify)
static void relocGOT(uint8_t *location, uint64_t S, uint64_t GP) {
int32_t G = (int32_t)(S - GP);
applyReloc(location, G, 0xffff);
}
/// \brief R_MIPS_TLS_DTPREL_HI16, R_MIPS_TLS_TPREL_HI16, LLD_R_MIPS_HI16
/// (S + A) >> 16
static void relocGeneralHi16(uint8_t *location, uint64_t S, int64_t A) {
int32_t result = S + A + 0x8000;
applyReloc(location, result >> 16, 0xffff);
}
/// \brief R_MIPS_TLS_DTPREL_LO16, R_MIPS_TLS_TPREL_LO16, LLD_R_MIPS_LO16
/// S + A
static void relocGeneralLo16(uint8_t *location, uint64_t S, int64_t A) {
int32_t result = S + A;
applyReloc(location, result, 0xffff);
}
/// \brief R_MIPS_GPREL32
/// local: rel32 A + S + GP0 - GP (truncate)
static void relocGPRel32(uint8_t *location, uint64_t P, uint64_t S, int64_t A,
uint64_t GP) {
int32_t result = A + S + 0 - GP;
applyReloc(location, result, 0xffffffff);
}
/// \brief LLD_R_MIPS_32_HI16
static void reloc32hi16(uint8_t *location, uint64_t S, int64_t A) {
applyReloc(location, (S + A + 0x8000) & 0xffff0000, 0xffffffff);
}
std::error_code MipsTargetRelocationHandler::applyRelocation(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom,
const Reference &ref) const {
if (ref.kindNamespace() != lld::Reference::KindNamespace::ELF)
return std::error_code();
assert(ref.kindArch() == Reference::KindArch::Mips);
AtomLayout *gpAtom = _mipsTargetLayout.getGP();
uint64_t gpAddr = gpAtom ? gpAtom->_virtualAddr : 0;
AtomLayout *gpDispAtom = _mipsTargetLayout.getGPDisp();
bool isGpDisp = gpDispAtom && ref.target() == gpDispAtom->_atom;
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ref.offsetInAtom();
uint64_t targetVAddress = writer.addressOfAtom(ref.target());
uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom();
switch (ref.kindValue()) {
case R_MIPS_NONE:
break;
case R_MIPS_32:
reloc32(location, relocVAddress, targetVAddress, ref.addend());
break;
case R_MIPS_26:
reloc26loc(location, relocVAddress, targetVAddress, ref.addend());
break;
case R_MIPS_HI16:
relocHi16(location, relocVAddress, targetVAddress, ref.addend(), isGpDisp);
break;
case R_MIPS_LO16:
relocLo16(location, relocVAddress, targetVAddress, ref.addend(), isGpDisp);
break;
case R_MIPS_GOT16:
case R_MIPS_CALL16:
relocGOT(location, targetVAddress, gpAddr);
break;
case R_MIPS_TLS_GD:
case R_MIPS_TLS_LDM:
case R_MIPS_TLS_GOTTPREL:
relocGOT(location, targetVAddress, gpAddr);
break;
case R_MIPS_TLS_DTPREL_HI16:
case R_MIPS_TLS_TPREL_HI16:
relocGeneralHi16(location, targetVAddress, ref.addend());
break;
case R_MIPS_TLS_DTPREL_LO16:
case R_MIPS_TLS_TPREL_LO16:
relocGeneralLo16(location, targetVAddress, ref.addend());
break;
case R_MIPS_GPREL32:
relocGPRel32(location, relocVAddress, targetVAddress, ref.addend(), gpAddr);
break;
case R_MIPS_JALR:
// We do not do JALR optimization now.
break;
case R_MIPS_REL32:
case R_MIPS_JUMP_SLOT:
case R_MIPS_COPY:
case R_MIPS_TLS_DTPMOD32:
case R_MIPS_TLS_DTPREL32:
case R_MIPS_TLS_TPREL32:
// Ignore runtime relocations.
break;
case R_MIPS_PC32:
relocpc32(location, relocVAddress, targetVAddress, ref.addend());
break;
case LLD_R_MIPS_GLOBAL_GOT:
// Do nothing.
break;
case LLD_R_MIPS_32_HI16:
reloc32hi16(location, targetVAddress, ref.addend());
break;
case LLD_R_MIPS_GLOBAL_26:
reloc26ext(location, targetVAddress, ref.addend());
break;
case LLD_R_MIPS_HI16:
relocGeneralHi16(location, targetVAddress, 0);
break;
case LLD_R_MIPS_LO16:
relocGeneralLo16(location, targetVAddress, 0);
break;
case LLD_R_MIPS_STO_PLT:
// Do nothing.
break;
default: {
std::string str;
llvm::raw_string_ostream s(str);
s << "Unhandled Mips relocation: " << ref.kindValue();
llvm_unreachable(s.str().c_str());
}
}
return std::error_code();
}
<commit_msg>[Mips] Use endian::read/write function to load/save MIPS32 instructions<commit_after>//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsTargetHandler.h"
#include "MipsLinkingContext.h"
#include "MipsRelocationHandler.h"
#include "lld/ReaderWriter/RelocationHelperFunctions.h"
using namespace lld;
using namespace elf;
using namespace llvm::ELF;
using namespace llvm::support;
static inline void applyReloc(uint32_t &ins, uint32_t result, uint32_t mask) {
ins = (ins & ~mask) | (result & mask);
}
template <size_t BITS, class T> inline T signExtend(T val) {
if (val & (T(1) << (BITS - 1)))
val |= T(-1) << BITS;
return val;
}
/// \brief R_MIPS_32
/// local/external: word32 S + A (truncate)
static void reloc32(uint32_t &ins, uint64_t P, uint64_t S, int64_t A) {
applyReloc(ins, S + A, 0xffffffff);
}
/// \brief R_MIPS_PC32
/// local/external: word32 S + A i- P (truncate)
void relocpc32(uint32_t &ins, uint64_t P, uint64_t S, int64_t A) {
applyReloc(ins, S + A - P, 0xffffffff);
}
/// \brief R_MIPS_26
/// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2
static void reloc26loc(uint32_t &ins, uint64_t P, uint64_t S, int32_t A) {
uint32_t result = ((A << 2) | ((P + 4) & 0x3f000000)) + S;
applyReloc(ins, result >> 2, 0x03ffffff);
}
/// \brief LLD_R_MIPS_GLOBAL_26
/// external: (sign-extend(A) + S) >> 2
static void reloc26ext(uint32_t &ins, uint64_t S, int32_t A) {
uint32_t result = signExtend<28>(A << 2) + S;
applyReloc(ins, result >> 2, 0x03ffffff);
}
/// \brief R_MIPS_HI16
/// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate)
/// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify)
static void relocHi16(uint32_t &ins, uint64_t P, uint64_t S, int64_t AHL,
bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = (AHL + S - P) - (int16_t)(AHL + S - P);
else
result = (AHL + S) - (int16_t)(AHL + S);
applyReloc(ins, result >> 16, 0xffff);
}
/// \brief R_MIPS_LO16
/// local/external: lo16 AHL + S (truncate)
/// _gp_disp : lo16 AHL + GP - P + 4 (verify)
static void relocLo16(uint32_t &ins, uint64_t P, uint64_t S, int64_t AHL,
bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = AHL + S - P + 4;
else
result = AHL + S;
applyReloc(ins, result, 0xffff);
}
/// \brief R_MIPS_GOT16, R_MIPS_CALL16
/// rel16 G (verify)
static void relocGOT(uint32_t &ins, uint64_t S, uint64_t GP) {
int32_t G = (int32_t)(S - GP);
applyReloc(ins, G, 0xffff);
}
/// \brief R_MIPS_TLS_DTPREL_HI16, R_MIPS_TLS_TPREL_HI16, LLD_R_MIPS_HI16
/// (S + A) >> 16
static void relocGeneralHi16(uint32_t &ins, uint64_t S, int64_t A) {
int32_t result = S + A + 0x8000;
applyReloc(ins, result >> 16, 0xffff);
}
/// \brief R_MIPS_TLS_DTPREL_LO16, R_MIPS_TLS_TPREL_LO16, LLD_R_MIPS_LO16
/// S + A
static void relocGeneralLo16(uint32_t &ins, uint64_t S, int64_t A) {
int32_t result = S + A;
applyReloc(ins, result, 0xffff);
}
/// \brief R_MIPS_GPREL32
/// local: rel32 A + S + GP0 - GP (truncate)
static void relocGPRel32(uint32_t &ins, uint64_t P, uint64_t S, int64_t A,
uint64_t GP) {
int32_t result = A + S + 0 - GP;
applyReloc(ins, result, 0xffffffff);
}
/// \brief LLD_R_MIPS_32_HI16
static void reloc32hi16(uint32_t &ins, uint64_t S, int64_t A) {
applyReloc(ins, (S + A + 0x8000) & 0xffff0000, 0xffffffff);
}
std::error_code MipsTargetRelocationHandler::applyRelocation(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom,
const Reference &ref) const {
if (ref.kindNamespace() != lld::Reference::KindNamespace::ELF)
return std::error_code();
assert(ref.kindArch() == Reference::KindArch::Mips);
AtomLayout *gpAtom = _mipsTargetLayout.getGP();
uint64_t gpAddr = gpAtom ? gpAtom->_virtualAddr : 0;
AtomLayout *gpDispAtom = _mipsTargetLayout.getGPDisp();
bool isGpDisp = gpDispAtom && ref.target() == gpDispAtom->_atom;
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ref.offsetInAtom();
uint64_t targetVAddress = writer.addressOfAtom(ref.target());
uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom();
uint32_t ins = endian::read<uint32_t, little, 2>(location);
switch (ref.kindValue()) {
case R_MIPS_NONE:
break;
case R_MIPS_32:
reloc32(ins, relocVAddress, targetVAddress, ref.addend());
break;
case R_MIPS_26:
reloc26loc(ins, relocVAddress, targetVAddress, ref.addend());
break;
case R_MIPS_HI16:
relocHi16(ins, relocVAddress, targetVAddress, ref.addend(), isGpDisp);
break;
case R_MIPS_LO16:
relocLo16(ins, relocVAddress, targetVAddress, ref.addend(), isGpDisp);
break;
case R_MIPS_GOT16:
case R_MIPS_CALL16:
relocGOT(ins, targetVAddress, gpAddr);
break;
case R_MIPS_TLS_GD:
case R_MIPS_TLS_LDM:
case R_MIPS_TLS_GOTTPREL:
relocGOT(ins, targetVAddress, gpAddr);
break;
case R_MIPS_TLS_DTPREL_HI16:
case R_MIPS_TLS_TPREL_HI16:
relocGeneralHi16(ins, targetVAddress, ref.addend());
break;
case R_MIPS_TLS_DTPREL_LO16:
case R_MIPS_TLS_TPREL_LO16:
relocGeneralLo16(ins, targetVAddress, ref.addend());
break;
case R_MIPS_GPREL32:
relocGPRel32(ins, relocVAddress, targetVAddress, ref.addend(), gpAddr);
break;
case R_MIPS_JALR:
// We do not do JALR optimization now.
break;
case R_MIPS_REL32:
case R_MIPS_JUMP_SLOT:
case R_MIPS_COPY:
case R_MIPS_TLS_DTPMOD32:
case R_MIPS_TLS_DTPREL32:
case R_MIPS_TLS_TPREL32:
// Ignore runtime relocations.
break;
case R_MIPS_PC32:
relocpc32(ins, relocVAddress, targetVAddress, ref.addend());
break;
case LLD_R_MIPS_GLOBAL_GOT:
// Do nothing.
break;
case LLD_R_MIPS_32_HI16:
reloc32hi16(ins, targetVAddress, ref.addend());
break;
case LLD_R_MIPS_GLOBAL_26:
reloc26ext(ins, targetVAddress, ref.addend());
break;
case LLD_R_MIPS_HI16:
relocGeneralHi16(ins, targetVAddress, 0);
break;
case LLD_R_MIPS_LO16:
relocGeneralLo16(ins, targetVAddress, 0);
break;
case LLD_R_MIPS_STO_PLT:
// Do nothing.
break;
default: {
std::string str;
llvm::raw_string_ostream s(str);
s << "Unhandled Mips relocation: " << ref.kindValue();
llvm_unreachable(s.str().c_str());
}
}
endian::write<uint32_t, little, 2>(location, ins);
return std::error_code();
}
<|endoftext|> |
<commit_before><commit_msg>Eliminated a compilation warning.<commit_after><|endoftext|> |
<commit_before>#ifndef BUILDERS_BUILDINGS_ROOFS_FLATROOFBUILDER_HPP_DEFINED
#define BUILDERS_BUILDINGS_ROOFS_FLATROOFBUILDER_HPP_DEFINED
#include "builders/buildings/roofs/RoofBuilder.hpp"
#include "meshing/MeshBuilder.hpp"
#include "meshing/Polygon.hpp"
#include <vector>
namespace utymap { namespace builders {
// Builds flat roof in low poly.
class FlatRoofBuilder : public RoofBuilder
{
public:
FlatRoofBuilder(const utymap::builders::BuilderContext& builderContext,
utymap::builders::MeshContext& meshContext)
: RoofBuilder(builderContext, meshContext)
{
}
void build(utymap::meshing::Polygon& polygon) {
builderContext_.meshBuilder
.addPolygon(meshContext_.mesh,
polygon,
utymap::meshing::MeshBuilder::Options
{
0, // area
0, // ele noise
colorNoiseFreq_,
height_,
getColorGradient(),
minHeight_
});
}
};
}}
#endif // BUILDERS_BUILDINGS_ROOFS_FLATROOFBUILDER_HPP_DEFINED
<commit_msg>core: fix formatting issue<commit_after>#ifndef BUILDERS_BUILDINGS_ROOFS_FLATROOFBUILDER_HPP_DEFINED
#define BUILDERS_BUILDINGS_ROOFS_FLATROOFBUILDER_HPP_DEFINED
#include "builders/buildings/roofs/RoofBuilder.hpp"
#include "meshing/MeshBuilder.hpp"
#include "meshing/Polygon.hpp"
#include <vector>
namespace utymap { namespace builders {
// Builds flat roof in low poly.
class FlatRoofBuilder : public RoofBuilder
{
public:
FlatRoofBuilder(const utymap::builders::BuilderContext& builderContext,
utymap::builders::MeshContext& meshContext)
: RoofBuilder(builderContext, meshContext)
{
}
void build(utymap::meshing::Polygon& polygon)
{
builderContext_.meshBuilder
.addPolygon(meshContext_.mesh,
polygon,
utymap::meshing::MeshBuilder::Options
{
0, // area
0, // ele noise
colorNoiseFreq_,
height_,
getColorGradient(),
minHeight_
});
}
};
}}
#endif // BUILDERS_BUILDINGS_ROOFS_FLATROOFBUILDER_HPP_DEFINED
<|endoftext|> |
<commit_before>// Copyright Yangqing Jia 2013
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/solver.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
using std::max;
using std::min;
namespace caffe {
template <typename Dtype>
Solver<Dtype>::Solver(const SolverParameter& param)
: param_(param), net_(), test_net_() {
// Scaffolding code
NetParameter train_net_param;
ReadProtoFromTextFile(param_.train_net(), &train_net_param);
LOG(INFO) << "Creating training net.";
net_.reset(new Net<Dtype>(train_net_param));
if (param_.has_test_net()) {
LOG(INFO) << "Creating testing net.";
NetParameter test_net_param;
ReadProtoFromTextFile(param_.test_net(), &test_net_param);
test_net_.reset(new Net<Dtype>(test_net_param));
CHECK_GT(param_.test_iter(), 0);
CHECK_GT(param_.test_interval(), 0);
}
LOG(INFO) << "Solver scaffolding done.";
}
template <typename Dtype>
void Solver<Dtype>::Solve(const char* resume_file) {
Caffe::set_mode(Caffe::Brew(param_.solver_mode()));
if (param_.solver_mode() && param_.has_device_id()) {
Caffe::SetDevice(param_.device_id());
}
Caffe::set_phase(Caffe::TRAIN);
LOG(INFO) << "Solving " << net_->name();
PreSolve();
iter_ = 0;
if (resume_file) {
LOG(INFO) << "Restoring previous solver status from " << resume_file;
Restore(resume_file);
}
// For a network that is trained by the solver, no bottom or top vecs
// should be given, and we will just provide dummy vecs.
vector<Blob<Dtype>*> bottom_vec;
while (iter_++ < param_.max_iter()) {
Dtype loss = net_->ForwardBackward(bottom_vec);
ComputeUpdateValue();
net_->Update();
if (param_.display() && iter_ % param_.display() == 0) {
LOG(INFO) << "Iteration " << iter_ << ", loss = " << loss;
}
if (param_.test_interval() && iter_ % param_.test_interval() == 0) {
// We need to set phase to test before running.
Caffe::set_phase(Caffe::TEST);
Test();
Caffe::set_phase(Caffe::TRAIN);
}
// Check if we need to do snapshot
if (param_.snapshot() && iter_ % param_.snapshot() == 0) {
Snapshot();
}
}
// After the optimization is done, always do a snapshot.
iter_--;
Snapshot();
LOG(INFO) << "Optimization Done.";
}
template <typename Dtype>
void Solver<Dtype>::Test() {
LOG(INFO) << "Iteration " << iter_ << ", Testing net";
NetParameter net_param;
net_->ToProto(&net_param);
CHECK_NOTNULL(test_net_.get())->CopyTrainedLayersFrom(net_param);
vector<Dtype> test_score;
vector<Blob<Dtype>*> bottom_vec;
for (int i = 0; i < param_.test_iter(); ++i) {
const vector<Blob<Dtype>*>& result =
test_net_->Forward(bottom_vec);
if (i == 0) {
for (int j = 0; j < result.size(); ++j) {
const Dtype* result_vec = result[j]->cpu_data();
for (int k = 0; k < result[j]->count(); ++k) {
test_score.push_back(result_vec[k]);
}
}
} else {
int idx = 0;
for (int j = 0; j < result.size(); ++j) {
const Dtype* result_vec = result[j]->cpu_data();
for (int k = 0; k < result[j]->count(); ++k) {
test_score[idx++] += result_vec[k];
}
}
}
}
for (int i = 0; i < test_score.size(); ++i) {
LOG(INFO) << "Test score #" << i << ": "
<< test_score[i] / param_.test_iter();
}
}
template <typename Dtype>
void Solver<Dtype>::Snapshot() {
NetParameter net_param;
// For intermediate results, we will also dump the gradient values.
net_->ToProto(&net_param, param_.snapshot_diff());
string filename(param_.snapshot_prefix());
const int kBufferSize = 20;
char iter_str_buffer[kBufferSize];
snprintf(iter_str_buffer, kBufferSize, "_iter_%d", iter_);
filename += iter_str_buffer;
LOG(INFO) << "Snapshotting to " << filename;
WriteProtoToBinaryFile(net_param, filename.c_str());
SolverState state;
SnapshotSolverState(&state);
state.set_iter(iter_);
state.set_learned_net(filename);
filename += ".solverstate";
LOG(INFO) << "Snapshotting solver state to " << filename;
WriteProtoToBinaryFile(state, filename.c_str());
}
template <typename Dtype>
void Solver<Dtype>::Restore(const char* state_file) {
SolverState state;
NetParameter net_param;
ReadProtoFromBinaryFile(state_file, &state);
if (state.has_learned_net()) {
ReadProtoFromBinaryFile(state.learned_net().c_str(), &net_param);
net_->CopyTrainedLayersFrom(net_param);
}
iter_ = state.iter();
RestoreSolverState(state);
}
// Return the current learning rate. The currently implemented learning rate
// policies are as follows:
// - fixed: always return base_lr.
// - step: return base_lr * gamma ^ (floor(iter / step))
// - exp: return base_lr * gamma ^ iter
// - inv: return base_lr * (1 + gamma * iter) ^ (- power)
// where base_lr, gamma, step and power are defined in the solver parameter
// protocol buffer, and iter is the current iteration.
template <typename Dtype>
Dtype SGDSolver<Dtype>::GetLearningRate() {
Dtype rate;
const string& lr_policy = this->param_.lr_policy();
if (lr_policy == "fixed") {
rate = this->param_.base_lr();
} else if (lr_policy == "step") {
int current_step = this->iter_ / this->param_.stepsize();
rate = this->param_.base_lr() *
pow(this->param_.gamma(), current_step);
} else if (lr_policy == "exp") {
rate = this->param_.base_lr() * pow(this->param_.gamma(), this->iter_);
} else if (lr_policy == "inv") {
rate = this->param_.base_lr() *
pow(Dtype(1) + this->param_.gamma() * this->iter_,
- this->param_.power());
} else {
LOG(FATAL) << "Unknown learning rate policy: " << lr_policy;
}
return rate;
}
template <typename Dtype>
void SGDSolver<Dtype>::PreSolve() {
// Initialize the history
vector<shared_ptr<Blob<Dtype> > >& net_params = this->net_->params();
history_.clear();
for (int i = 0; i < net_params.size(); ++i) {
const Blob<Dtype>* net_param = net_params[i].get();
history_.push_back(shared_ptr<Blob<Dtype> >(new Blob<Dtype>(
net_param->num(), net_param->channels(), net_param->height(),
net_param->width())));
}
}
template <typename Dtype>
void SGDSolver<Dtype>::ComputeUpdateValue() {
vector<shared_ptr<Blob<Dtype> > >& net_params = this->net_->params();
vector<float>& net_params_lr = this->net_->params_lr();
vector<float>& net_params_weight_decay = this->net_->params_weight_decay();
// get the learning rate
Dtype rate = GetLearningRate();
if (this->param_.display() && this->iter_ % this->param_.display() == 0) {
LOG(INFO) << "Iteration " << this->iter_ << ", lr = " << rate;
}
Dtype momentum = this->param_.momentum();
Dtype weight_decay = this->param_.weight_decay();
switch (Caffe::mode()) {
case Caffe::CPU:
for (int param_id = 0; param_id < net_params.size(); ++param_id) {
// Compute the value to history, and then copy them to the blob's diff.
Dtype local_rate = rate * net_params_lr[param_id];
Dtype local_decay = weight_decay * net_params_weight_decay[param_id];
caffe_axpby(net_params[param_id]->count(), local_rate,
net_params[param_id]->cpu_diff(), momentum,
history_[param_id]->mutable_cpu_data());
if (local_decay) {
// add weight decay
caffe_axpy(net_params[param_id]->count(),
local_decay * local_rate,
net_params[param_id]->cpu_data(),
history_[param_id]->mutable_cpu_data());
}
// copy
caffe_copy(net_params[param_id]->count(),
history_[param_id]->cpu_data(),
net_params[param_id]->mutable_cpu_diff());
}
break;
case Caffe::GPU:
for (int param_id = 0; param_id < net_params.size(); ++param_id) {
// Compute the value to history, and then copy them to the blob's diff.
Dtype local_rate = rate * net_params_lr[param_id];
Dtype local_decay = weight_decay * net_params_weight_decay[param_id];
caffe_gpu_axpby(net_params[param_id]->count(), local_rate,
net_params[param_id]->gpu_diff(), momentum,
history_[param_id]->mutable_gpu_data());
if (local_decay) {
// add weight decay
caffe_gpu_axpy(net_params[param_id]->count(),
local_decay * local_rate,
net_params[param_id]->gpu_data(),
history_[param_id]->mutable_gpu_data());
}
// copy
caffe_gpu_copy(net_params[param_id]->count(),
history_[param_id]->gpu_data(),
net_params[param_id]->mutable_gpu_diff());
}
break;
default:
LOG(FATAL) << "Unknown caffe mode: " << Caffe::mode();
}
}
template <typename Dtype>
void SGDSolver<Dtype>::SnapshotSolverState(SolverState* state) {
state->clear_history();
for (int i = 0; i < history_.size(); ++i) {
// Add history
BlobProto* history_blob = state->add_history();
history_[i]->ToProto(history_blob);
}
}
template <typename Dtype>
void SGDSolver<Dtype>::RestoreSolverState(const SolverState& state) {
CHECK_EQ(state.history_size(), history_.size())
<< "Incorrect length of history blobs.";
LOG(INFO) << "SGDSolver: restoring history";
for (int i = 0; i < history_.size(); ++i) {
history_[i]->FromProto(state.history(i));
}
}
INSTANTIATE_CLASS(Solver);
INSTANTIATE_CLASS(SGDSolver);
} // namespace caffe
<commit_msg>[master] Synchronize before printing loss<commit_after>// Copyright Yangqing Jia 2013
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/solver.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
using std::max;
using std::min;
namespace caffe {
template <typename Dtype>
Solver<Dtype>::Solver(const SolverParameter& param)
: param_(param), net_(), test_net_() {
// Scaffolding code
NetParameter train_net_param;
ReadProtoFromTextFile(param_.train_net(), &train_net_param);
LOG(INFO) << "Creating training net.";
net_.reset(new Net<Dtype>(train_net_param));
if (param_.has_test_net()) {
LOG(INFO) << "Creating testing net.";
NetParameter test_net_param;
ReadProtoFromTextFile(param_.test_net(), &test_net_param);
test_net_.reset(new Net<Dtype>(test_net_param));
CHECK_GT(param_.test_iter(), 0);
CHECK_GT(param_.test_interval(), 0);
}
LOG(INFO) << "Solver scaffolding done.";
}
template <typename Dtype>
void Solver<Dtype>::Solve(const char* resume_file) {
Caffe::set_mode(Caffe::Brew(param_.solver_mode()));
if (param_.solver_mode() && param_.has_device_id()) {
Caffe::SetDevice(param_.device_id());
}
Caffe::set_phase(Caffe::TRAIN);
LOG(INFO) << "Solving " << net_->name();
PreSolve();
iter_ = 0;
if (resume_file) {
LOG(INFO) << "Restoring previous solver status from " << resume_file;
Restore(resume_file);
}
// For a network that is trained by the solver, no bottom or top vecs
// should be given, and we will just provide dummy vecs.
vector<Blob<Dtype>*> bottom_vec;
while (iter_++ < param_.max_iter()) {
Dtype loss = net_->ForwardBackward(bottom_vec);
ComputeUpdateValue();
net_->Update();
if (param_.display() && iter_ % param_.display() == 0) {
cudaDeviceSynchronize();
LOG(INFO) << "Iteration " << iter_ << ", loss = " << loss;
}
if (param_.test_interval() && iter_ % param_.test_interval() == 0) {
// We need to set phase to test before running.
Caffe::set_phase(Caffe::TEST);
Test();
Caffe::set_phase(Caffe::TRAIN);
}
// Check if we need to do snapshot
if (param_.snapshot() && iter_ % param_.snapshot() == 0) {
Snapshot();
}
}
// After the optimization is done, always do a snapshot.
iter_--;
Snapshot();
LOG(INFO) << "Optimization Done.";
}
template <typename Dtype>
void Solver<Dtype>::Test() {
LOG(INFO) << "Iteration " << iter_ << ", Testing net";
NetParameter net_param;
net_->ToProto(&net_param);
CHECK_NOTNULL(test_net_.get())->CopyTrainedLayersFrom(net_param);
vector<Dtype> test_score;
vector<Blob<Dtype>*> bottom_vec;
for (int i = 0; i < param_.test_iter(); ++i) {
const vector<Blob<Dtype>*>& result =
test_net_->Forward(bottom_vec);
if (i == 0) {
for (int j = 0; j < result.size(); ++j) {
const Dtype* result_vec = result[j]->cpu_data();
for (int k = 0; k < result[j]->count(); ++k) {
test_score.push_back(result_vec[k]);
}
}
} else {
int idx = 0;
for (int j = 0; j < result.size(); ++j) {
const Dtype* result_vec = result[j]->cpu_data();
for (int k = 0; k < result[j]->count(); ++k) {
test_score[idx++] += result_vec[k];
}
}
}
}
for (int i = 0; i < test_score.size(); ++i) {
LOG(INFO) << "Test score #" << i << ": "
<< test_score[i] / param_.test_iter();
}
}
template <typename Dtype>
void Solver<Dtype>::Snapshot() {
NetParameter net_param;
// For intermediate results, we will also dump the gradient values.
net_->ToProto(&net_param, param_.snapshot_diff());
string filename(param_.snapshot_prefix());
const int kBufferSize = 20;
char iter_str_buffer[kBufferSize];
snprintf(iter_str_buffer, kBufferSize, "_iter_%d", iter_);
filename += iter_str_buffer;
LOG(INFO) << "Snapshotting to " << filename;
WriteProtoToBinaryFile(net_param, filename.c_str());
SolverState state;
SnapshotSolverState(&state);
state.set_iter(iter_);
state.set_learned_net(filename);
filename += ".solverstate";
LOG(INFO) << "Snapshotting solver state to " << filename;
WriteProtoToBinaryFile(state, filename.c_str());
}
template <typename Dtype>
void Solver<Dtype>::Restore(const char* state_file) {
SolverState state;
NetParameter net_param;
ReadProtoFromBinaryFile(state_file, &state);
if (state.has_learned_net()) {
ReadProtoFromBinaryFile(state.learned_net().c_str(), &net_param);
net_->CopyTrainedLayersFrom(net_param);
}
iter_ = state.iter();
RestoreSolverState(state);
}
// Return the current learning rate. The currently implemented learning rate
// policies are as follows:
// - fixed: always return base_lr.
// - step: return base_lr * gamma ^ (floor(iter / step))
// - exp: return base_lr * gamma ^ iter
// - inv: return base_lr * (1 + gamma * iter) ^ (- power)
// where base_lr, gamma, step and power are defined in the solver parameter
// protocol buffer, and iter is the current iteration.
template <typename Dtype>
Dtype SGDSolver<Dtype>::GetLearningRate() {
Dtype rate;
const string& lr_policy = this->param_.lr_policy();
if (lr_policy == "fixed") {
rate = this->param_.base_lr();
} else if (lr_policy == "step") {
int current_step = this->iter_ / this->param_.stepsize();
rate = this->param_.base_lr() *
pow(this->param_.gamma(), current_step);
} else if (lr_policy == "exp") {
rate = this->param_.base_lr() * pow(this->param_.gamma(), this->iter_);
} else if (lr_policy == "inv") {
rate = this->param_.base_lr() *
pow(Dtype(1) + this->param_.gamma() * this->iter_,
- this->param_.power());
} else {
LOG(FATAL) << "Unknown learning rate policy: " << lr_policy;
}
return rate;
}
template <typename Dtype>
void SGDSolver<Dtype>::PreSolve() {
// Initialize the history
vector<shared_ptr<Blob<Dtype> > >& net_params = this->net_->params();
history_.clear();
for (int i = 0; i < net_params.size(); ++i) {
const Blob<Dtype>* net_param = net_params[i].get();
history_.push_back(shared_ptr<Blob<Dtype> >(new Blob<Dtype>(
net_param->num(), net_param->channels(), net_param->height(),
net_param->width())));
}
}
template <typename Dtype>
void SGDSolver<Dtype>::ComputeUpdateValue() {
vector<shared_ptr<Blob<Dtype> > >& net_params = this->net_->params();
vector<float>& net_params_lr = this->net_->params_lr();
vector<float>& net_params_weight_decay = this->net_->params_weight_decay();
// get the learning rate
Dtype rate = GetLearningRate();
if (this->param_.display() && this->iter_ % this->param_.display() == 0) {
LOG(INFO) << "Iteration " << this->iter_ << ", lr = " << rate;
}
Dtype momentum = this->param_.momentum();
Dtype weight_decay = this->param_.weight_decay();
switch (Caffe::mode()) {
case Caffe::CPU:
for (int param_id = 0; param_id < net_params.size(); ++param_id) {
// Compute the value to history, and then copy them to the blob's diff.
Dtype local_rate = rate * net_params_lr[param_id];
Dtype local_decay = weight_decay * net_params_weight_decay[param_id];
caffe_axpby(net_params[param_id]->count(), local_rate,
net_params[param_id]->cpu_diff(), momentum,
history_[param_id]->mutable_cpu_data());
if (local_decay) {
// add weight decay
caffe_axpy(net_params[param_id]->count(),
local_decay * local_rate,
net_params[param_id]->cpu_data(),
history_[param_id]->mutable_cpu_data());
}
// copy
caffe_copy(net_params[param_id]->count(),
history_[param_id]->cpu_data(),
net_params[param_id]->mutable_cpu_diff());
}
break;
case Caffe::GPU:
for (int param_id = 0; param_id < net_params.size(); ++param_id) {
// Compute the value to history, and then copy them to the blob's diff.
Dtype local_rate = rate * net_params_lr[param_id];
Dtype local_decay = weight_decay * net_params_weight_decay[param_id];
caffe_gpu_axpby(net_params[param_id]->count(), local_rate,
net_params[param_id]->gpu_diff(), momentum,
history_[param_id]->mutable_gpu_data());
if (local_decay) {
// add weight decay
caffe_gpu_axpy(net_params[param_id]->count(),
local_decay * local_rate,
net_params[param_id]->gpu_data(),
history_[param_id]->mutable_gpu_data());
}
// copy
caffe_gpu_copy(net_params[param_id]->count(),
history_[param_id]->gpu_data(),
net_params[param_id]->mutable_gpu_diff());
}
break;
default:
LOG(FATAL) << "Unknown caffe mode: " << Caffe::mode();
}
}
template <typename Dtype>
void SGDSolver<Dtype>::SnapshotSolverState(SolverState* state) {
state->clear_history();
for (int i = 0; i < history_.size(); ++i) {
// Add history
BlobProto* history_blob = state->add_history();
history_[i]->ToProto(history_blob);
}
}
template <typename Dtype>
void SGDSolver<Dtype>::RestoreSolverState(const SolverState& state) {
CHECK_EQ(state.history_size(), history_.size())
<< "Incorrect length of history blobs.";
LOG(INFO) << "SGDSolver: restoring history";
for (int i = 0; i < history_.size(); ++i) {
history_[i]->FromProto(state.history(i));
}
}
INSTANTIATE_CLASS(Solver);
INSTANTIATE_CLASS(SGDSolver);
} // namespace caffe
<|endoftext|> |
<commit_before>#include "source/extensions/matching/input_matchers/ip/config.h"
namespace Envoy {
namespace Extensions {
namespace Matching {
namespace InputMatchers {
namespace IP {
Envoy::Matcher::InputMatcherFactoryCb
Config::createInputMatcherFactoryCb(const Protobuf::Message& config,
Server::Configuration::ServerFactoryContext& factory_context) {
const auto& ip_config = MessageUtil::downcastAndValidate<
const envoy::extensions::matching::input_matchers::ip::v3::Ip&>(
config, factory_context.messageValidationVisitor());
const auto& cidr_ranges = ip_config.cidr_ranges();
std::vector<Network::Address::CidrRange> ranges;
ranges.reserve(cidr_ranges.size());
for (const auto& cidr_range : cidr_ranges) {
const std::string& address = cidr_range.address_prefix();
const uint32_t prefix_len = cidr_range.prefix_len().value();
const auto range = Network::Address::CidrRange::create(address, prefix_len);
// We only assert that the range is valid because:
// * if "address" can't be parsed, it will throw an EnvoyException
// * prefix_len can't be < 0 as per the protobuf definition as an uint32_t
// * if prefix_len is too big, CidrRange::create clamps it to a valid value
// => it is thus not possible to create an invalid range.
ASSERT(range.isValid(), "address range should be valid!");
ranges.emplace_back(std::move(range));
}
const std::string& stat_prefix = ip_config.stat_prefix();
Stats::Scope& scope = factory_context.scope();
return [ranges, stat_prefix, &scope]() {
return std::make_unique<Matcher>(ranges, stat_prefix, scope);
};
}
/**
* Static registration for the consistent hashing matcher. @see RegisterFactory.
*/
REGISTER_FACTORY(Config, Envoy::Matcher::InputMatcherFactory);
} // namespace IP
} // namespace InputMatchers
} // namespace Matching
} // namespace Extensions
} // namespace Envoy
<commit_msg>minor fix comment (#23494)<commit_after>#include "source/extensions/matching/input_matchers/ip/config.h"
namespace Envoy {
namespace Extensions {
namespace Matching {
namespace InputMatchers {
namespace IP {
Envoy::Matcher::InputMatcherFactoryCb
Config::createInputMatcherFactoryCb(const Protobuf::Message& config,
Server::Configuration::ServerFactoryContext& factory_context) {
const auto& ip_config = MessageUtil::downcastAndValidate<
const envoy::extensions::matching::input_matchers::ip::v3::Ip&>(
config, factory_context.messageValidationVisitor());
const auto& cidr_ranges = ip_config.cidr_ranges();
std::vector<Network::Address::CidrRange> ranges;
ranges.reserve(cidr_ranges.size());
for (const auto& cidr_range : cidr_ranges) {
const std::string& address = cidr_range.address_prefix();
const uint32_t prefix_len = cidr_range.prefix_len().value();
const auto range = Network::Address::CidrRange::create(address, prefix_len);
// We only assert that the range is valid because:
// * if "address" can't be parsed, it will throw an EnvoyException
// * prefix_len can't be < 0 as per the protobuf definition as an uint32_t
// * if prefix_len is too big, CidrRange::create clamps it to a valid value
// => it is thus not possible to create an invalid range.
ASSERT(range.isValid(), "address range should be valid!");
ranges.emplace_back(std::move(range));
}
const std::string& stat_prefix = ip_config.stat_prefix();
Stats::Scope& scope = factory_context.scope();
return [ranges, stat_prefix, &scope]() {
return std::make_unique<Matcher>(ranges, stat_prefix, scope);
};
}
/**
* Static registration for the IP matcher. @see RegisterFactory.
*/
REGISTER_FACTORY(Config, Envoy::Matcher::InputMatcherFactory);
} // namespace IP
} // namespace InputMatchers
} // namespace Matching
} // namespace Extensions
} // namespace Envoy
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: graphconvert.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-02-01 19:05:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#include "mtnotification.hxx"
#include "oleembobj.hxx"
// TODO: when conversion service is ready this headers should disappear
#include <svtools/filter.hxx>
#include <vcl/graph.hxx>
#include <tools/link.hxx>
#include <vcl/svapp.hxx>
#include <vos/mutex.hxx>
using namespace ::com::sun::star;
sal_Bool ConvertBufferToFormat( void* pBuf,
sal_uInt32 nBufSize,
const ::rtl::OUString& aFormatShortName,
uno::Any& aResult )
{
// produces sequence with data in requested format and returns it in aResult
if ( pBuf )
{
SvMemoryStream aBufStream( pBuf, nBufSize, STREAM_READ );
aBufStream.ObjectOwnsMemory( sal_False );
Graphic aGraph;
GraphicFilter aGrFilter( sal_True );
if ( aGrFilter.ImportGraphic( aGraph, String(), aBufStream ) == ERRCODE_NONE )
{
sal_uInt16 nFormat = aGrFilter.GetExportFormatNumberForShortName( aFormatShortName );
if ( nFormat != GRFILTER_FORMAT_DONTKNOW )
{
SvMemoryStream aNewStream( 65535, 65535 );
if ( aGrFilter.ExportGraphic( aGraph, String(), aNewStream, nFormat ) == ERRCODE_NONE )
{
/*
{
aNewStream.Seek( 0 );
SvFileStream aFile( String::CreateFromAscii( "file:///d:/test.png" ), STREAM_STD_READWRITE);
aFile.SetStreamSize( 0 );
aNewStream >> aFile;
}
*/
aResult <<= uno::Sequence< sal_Int8 >(
reinterpret_cast< const sal_Int8* >( aNewStream.GetData() ),
aNewStream.Seek( STREAM_SEEK_TO_END ) );
return sal_True;
}
}
}
}
return sal_False;
}
// =====================================================================
// MainThreadNotificationRequest
// =====================================================================
MainThreadNotificationRequest::MainThreadNotificationRequest( OleEmbeddedObject* pObj )
: m_pObject( pObj )
, m_xObject( static_cast< embed::XEmbeddedObject* >( pObj ) )
{}
void MainThreadNotificationRequest::mainThreadWorkerStart( MainThreadNotificationRequest* pMTRequest )
{
if ( Application::GetMainThreadIdentifier() == osl_getThreadIdentifier( NULL ) )
{
// this is the main thread
worker( pMTRequest, pMTRequest );
}
else
Application::PostUserEvent( STATIC_LINK( NULL, MainThreadNotificationRequest, worker ), pMTRequest );
}
IMPL_STATIC_LINK( MainThreadNotificationRequest, worker, MainThreadNotificationRequest*, pMTRequest )
{
if ( pMTRequest )
{
if ( pMTRequest->m_pObject )
{
try
{
uno::Reference< uno::XInterface > xLock = pMTRequest->m_xObject.get();
if ( xLock.is() )
{
// this is the main thread, the solar mutex must be locked
::vos::OGuard aGuard( Application::GetSolarMutex() );
pMTRequest->m_pObject->OnViewChanged_Impl();
}
}
catch( uno::Exception& )
{
// ignore all the errors
}
}
delete pMTRequest;
}
return 0;
}
// =====================================================================
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.36); FILE MERGED 2006/09/01 17:25:52 kaib 1.7.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: graphconvert.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:43:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_embeddedobj.hxx"
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#include "mtnotification.hxx"
#include "oleembobj.hxx"
// TODO: when conversion service is ready this headers should disappear
#include <svtools/filter.hxx>
#include <vcl/graph.hxx>
#include <tools/link.hxx>
#include <vcl/svapp.hxx>
#include <vos/mutex.hxx>
using namespace ::com::sun::star;
sal_Bool ConvertBufferToFormat( void* pBuf,
sal_uInt32 nBufSize,
const ::rtl::OUString& aFormatShortName,
uno::Any& aResult )
{
// produces sequence with data in requested format and returns it in aResult
if ( pBuf )
{
SvMemoryStream aBufStream( pBuf, nBufSize, STREAM_READ );
aBufStream.ObjectOwnsMemory( sal_False );
Graphic aGraph;
GraphicFilter aGrFilter( sal_True );
if ( aGrFilter.ImportGraphic( aGraph, String(), aBufStream ) == ERRCODE_NONE )
{
sal_uInt16 nFormat = aGrFilter.GetExportFormatNumberForShortName( aFormatShortName );
if ( nFormat != GRFILTER_FORMAT_DONTKNOW )
{
SvMemoryStream aNewStream( 65535, 65535 );
if ( aGrFilter.ExportGraphic( aGraph, String(), aNewStream, nFormat ) == ERRCODE_NONE )
{
/*
{
aNewStream.Seek( 0 );
SvFileStream aFile( String::CreateFromAscii( "file:///d:/test.png" ), STREAM_STD_READWRITE);
aFile.SetStreamSize( 0 );
aNewStream >> aFile;
}
*/
aResult <<= uno::Sequence< sal_Int8 >(
reinterpret_cast< const sal_Int8* >( aNewStream.GetData() ),
aNewStream.Seek( STREAM_SEEK_TO_END ) );
return sal_True;
}
}
}
}
return sal_False;
}
// =====================================================================
// MainThreadNotificationRequest
// =====================================================================
MainThreadNotificationRequest::MainThreadNotificationRequest( OleEmbeddedObject* pObj )
: m_pObject( pObj )
, m_xObject( static_cast< embed::XEmbeddedObject* >( pObj ) )
{}
void MainThreadNotificationRequest::mainThreadWorkerStart( MainThreadNotificationRequest* pMTRequest )
{
if ( Application::GetMainThreadIdentifier() == osl_getThreadIdentifier( NULL ) )
{
// this is the main thread
worker( pMTRequest, pMTRequest );
}
else
Application::PostUserEvent( STATIC_LINK( NULL, MainThreadNotificationRequest, worker ), pMTRequest );
}
IMPL_STATIC_LINK( MainThreadNotificationRequest, worker, MainThreadNotificationRequest*, pMTRequest )
{
if ( pMTRequest )
{
if ( pMTRequest->m_pObject )
{
try
{
uno::Reference< uno::XInterface > xLock = pMTRequest->m_xObject.get();
if ( xLock.is() )
{
// this is the main thread, the solar mutex must be locked
::vos::OGuard aGuard( Application::GetSolarMutex() );
pMTRequest->m_pObject->OnViewChanged_Impl();
}
}
catch( uno::Exception& )
{
// ignore all the errors
}
}
delete pMTRequest;
}
return 0;
}
// =====================================================================
<|endoftext|> |
<commit_before>#include "precomp.hpp"
//////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::viz::Color
cv::viz::Color::Color() : Scalar(0, 0, 0) {}
cv::viz::Color::Color(double gray) : Scalar(gray, gray, gray) {}
cv::viz::Color::Color(double blue, double green, double red) : Scalar(blue, green, red) {}
cv::viz::Color::Color(const Scalar& color) : Scalar(color) {}
cv::viz::Color cv::viz::Color::black() { return Color( 0, 0, 0); }
cv::viz::Color cv::viz::Color::green() { return Color( 0, 255, 0); }
cv::viz::Color cv::viz::Color::blue() { return Color(255, 0, 0); }
cv::viz::Color cv::viz::Color::cyan() { return Color(255, 255, 0); }
cv::viz::Color cv::viz::Color::red() { return Color( 0, 0, 255); }
cv::viz::Color cv::viz::Color::magenta() { return Color( 0, 255, 255); }
cv::viz::Color cv::viz::Color::yellow() { return Color(255, 0, 255); }
cv::viz::Color cv::viz::Color::white() { return Color(255, 255, 255); }
cv::viz::Color cv::viz::Color::gray() { return Color(128, 128, 128); }
////////////////////////////////////////////////////////////////////
/// cv::viz::KeyboardEvent
cv::viz::KeyboardEvent::KeyboardEvent (bool _action, const std::string& _key_sym, unsigned char key, bool alt, bool ctrl, bool shift)
: action_ (_action), modifiers_ (0), key_code_(key), key_sym_ (_key_sym)
{
if (alt)
modifiers_ = Alt;
if (ctrl)
modifiers_ |= Ctrl;
if (shift)
modifiers_ |= Shift;
}
bool cv::viz::KeyboardEvent::isAltPressed () const { return (modifiers_ & Alt) != 0; }
bool cv::viz::KeyboardEvent::isCtrlPressed () const { return (modifiers_ & Ctrl) != 0; }
bool cv::viz::KeyboardEvent::isShiftPressed () const { return (modifiers_ & Shift) != 0; }
unsigned char cv::viz::KeyboardEvent::getKeyCode () const { return key_code_; }
const cv::String& cv::viz::KeyboardEvent::getKeySym () const { return key_sym_; }
bool cv::viz::KeyboardEvent::keyDown () const { return action_; }
bool cv::viz::KeyboardEvent::keyUp () const { return !action_; }
////////////////////////////////////////////////////////////////////
/// cv::viz::MouseEvent
cv::viz::MouseEvent::MouseEvent (const Type& _type, const MouseButton& _button, const Point& _p, bool alt, bool ctrl, bool shift)
: type(_type), button(_button), pointer(_p), key_state(0)
{
if (alt)
key_state = KeyboardEvent::Alt;
if (ctrl)
key_state |= KeyboardEvent::Ctrl;
if (shift)
key_state |= KeyboardEvent::Shift;
}
////////////////////////////////////////////////////////////////////
/// cv::viz::Mesh3d
struct cv::viz::Mesh3d::loadMeshImpl
{
static cv::viz::Mesh3d loadMesh(const String &file)
{
Mesh3d mesh;
vtkSmartPointer<vtkPLYReader> reader = vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName(file.c_str());
reader->Update();
vtkSmartPointer<vtkPolyData> poly_data = reader->GetOutput ();
vtkSmartPointer<vtkPoints> mesh_points = poly_data->GetPoints ();
vtkIdType nr_points = mesh_points->GetNumberOfPoints ();
//vtkIdType nr_polygons = poly_data->GetNumberOfPolys ();
mesh.cloud.create(1, nr_points, CV_32FC3);
Vec3f *mesh_cloud = mesh.cloud.ptr<Vec3f>();
for (vtkIdType i = 0; i < mesh_points->GetNumberOfPoints (); i++)
{
Vec3d point;
mesh_points->GetPoint (i, point.val);
mesh_cloud[i] = point;
}
// Then the color information, if any
vtkUnsignedCharArray* poly_colors = NULL;
if (poly_data->GetPointData() != NULL)
poly_colors = vtkUnsignedCharArray::SafeDownCast (poly_data->GetPointData ()->GetScalars ("Colors"));
// some applications do not save the name of scalars (including PCL's native vtk_io)
if (!poly_colors && poly_data->GetPointData () != NULL)
poly_colors = vtkUnsignedCharArray::SafeDownCast (poly_data->GetPointData ()->GetScalars ("scalars"));
if (!poly_colors && poly_data->GetPointData () != NULL)
poly_colors = vtkUnsignedCharArray::SafeDownCast (poly_data->GetPointData ()->GetScalars ("RGB"));
// TODO: currently only handles rgb values with 3 components
if (poly_colors && (poly_colors->GetNumberOfComponents () == 3))
{
mesh.colors.create(1, nr_points, CV_8UC3);
Vec3b *mesh_colors = mesh.colors.ptr<cv::Vec3b>();
for (vtkIdType i = 0; i < mesh_points->GetNumberOfPoints (); i++)
{
Vec3b point_color;
poly_colors->GetTupleValue (i, point_color.val);
std::swap(point_color[0], point_color[2]); // RGB -> BGR
mesh_colors[i] = point_color;
}
}
else
mesh.colors.release();
// Now handle the polygons
vtkIdType* cell_points;
vtkIdType nr_cell_points;
vtkCellArray * mesh_polygons = poly_data->GetPolys ();
mesh_polygons->InitTraversal ();
mesh.polygons.create(1, mesh_polygons->GetSize(), CV_32SC1);
int* polygons = mesh.polygons.ptr<int>();
while (mesh_polygons->GetNextCell (nr_cell_points, cell_points))
{
*polygons++ = nr_cell_points;
for (int i = 0; i < nr_cell_points; ++i)
*polygons++ = static_cast<int> (cell_points[i]);
}
return mesh;
}
};
cv::viz::Mesh3d cv::viz::Mesh3d::loadMesh(const String& file)
{
return loadMeshImpl::loadMesh(file);
}
////////////////////////////////////////////////////////////////////
/// Camera implementation
cv::viz::Camera::Camera(float f_x, float f_y, float c_x, float c_y, const Size &window_size)
{
init(f_x, f_y, c_x, c_y, window_size);
}
cv::viz::Camera::Camera(const Vec2f &fov, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
setClip(Vec2d(0.01, 1000.01)); // Default clipping
principal_point_ = Vec2f(-1.0f, -1.0f); // Default symmetric lens
focal_ = Vec2f(-1.0f, -1.0f);
setFov(fov);
setWindowSize(window_size);
}
cv::viz::Camera::Camera(const cv::Matx33f & K, const Size &window_size)
{
float f_x = K(0,0);
float f_y = K(1,1);
float c_x = K(0,2);
float c_y = K(1,2);
init(f_x, f_y, c_x, c_y, window_size);
}
void cv::viz::Camera::init(float f_x, float f_y, float c_x, float c_y, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
setClip(Vec2d(0.01, 1000.01));// Default clipping
fov_[0] = (atan2(c_x,f_x) + atan2(window_size.width-c_x,f_x)) * 180 / CV_PI;
fov_[1] = (atan2(c_y,f_y) + atan2(window_size.height-c_y,f_y)) * 180 / CV_PI;
principal_point_[0] = c_x;
principal_point_[1] = c_y;
focal_[0] = f_x;
focal_[1] = f_y;
setWindowSize(window_size);
}
void cv::viz::Camera::setWindowSize(const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
// Vertical field of view is fixed!
// Horizontal field of view is expandable based on the aspect ratio
float aspect_ratio_new = static_cast<float>(window_size.width) / static_cast<float>(window_size.height);
if (principal_point_[0] < 0.0f)
fov_[0] = 2.f * atan(tan(fov_[1] * 0.5) * aspect_ratio_new); // This assumes that the lens is symmetric!
else
fov_[0] = (atan2(principal_point_[0],focal_[0]) + atan2(window_size.width-principal_point_[0],focal_[0])) * 180 / CV_PI;
window_size_ = window_size;
}
void cv::viz::Camera::computeProjectionMatrix(Matx44f &proj) const
{
double top = clip_[0] * tan (0.5 * fov_[1]);
double left = -(top * window_size_.width) / window_size_.height;
double right = -left;
double bottom = -top;
double temp1 = 2.0 * clip_[0];
double temp2 = 1.0 / (right - left);
double temp3 = 1.0 / (top - bottom);
double temp4 = 1.0 / clip_[1] - clip_[0];
proj = Matx44d::zeros();
proj(0,0) = temp1 * temp2;
proj(1,1) = temp1 * temp3;
proj(0,2) = (right + left) * temp2;
proj(1,2) = (top + bottom) * temp3;
proj(2,2) = (-clip_[1] - clip_[0]) * temp4;
proj(3,2) = -1.0;
proj(2,3) = (-temp1 * clip_[1]) * temp4;
}
cv::viz::Camera cv::viz::Camera::KinectCamera(const Size &window_size)
{
// Without distortion
Matx33f K = Matx33f::zeros();
K(0,0) = 5.2921508098293293e+02;
K(0,2) = 3.2894272028759258e+02;
K(1,1) = 5.2556393630057437e+02;
K(1,2) = 2.6748068171871557e+02;
K(2,2) = 1.0f;
return Camera(K, window_size);
}<commit_msg>field of views are in radians<commit_after>#include "precomp.hpp"
//////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::viz::Color
cv::viz::Color::Color() : Scalar(0, 0, 0) {}
cv::viz::Color::Color(double gray) : Scalar(gray, gray, gray) {}
cv::viz::Color::Color(double blue, double green, double red) : Scalar(blue, green, red) {}
cv::viz::Color::Color(const Scalar& color) : Scalar(color) {}
cv::viz::Color cv::viz::Color::black() { return Color( 0, 0, 0); }
cv::viz::Color cv::viz::Color::green() { return Color( 0, 255, 0); }
cv::viz::Color cv::viz::Color::blue() { return Color(255, 0, 0); }
cv::viz::Color cv::viz::Color::cyan() { return Color(255, 255, 0); }
cv::viz::Color cv::viz::Color::red() { return Color( 0, 0, 255); }
cv::viz::Color cv::viz::Color::magenta() { return Color( 0, 255, 255); }
cv::viz::Color cv::viz::Color::yellow() { return Color(255, 0, 255); }
cv::viz::Color cv::viz::Color::white() { return Color(255, 255, 255); }
cv::viz::Color cv::viz::Color::gray() { return Color(128, 128, 128); }
////////////////////////////////////////////////////////////////////
/// cv::viz::KeyboardEvent
cv::viz::KeyboardEvent::KeyboardEvent (bool _action, const std::string& _key_sym, unsigned char key, bool alt, bool ctrl, bool shift)
: action_ (_action), modifiers_ (0), key_code_(key), key_sym_ (_key_sym)
{
if (alt)
modifiers_ = Alt;
if (ctrl)
modifiers_ |= Ctrl;
if (shift)
modifiers_ |= Shift;
}
bool cv::viz::KeyboardEvent::isAltPressed () const { return (modifiers_ & Alt) != 0; }
bool cv::viz::KeyboardEvent::isCtrlPressed () const { return (modifiers_ & Ctrl) != 0; }
bool cv::viz::KeyboardEvent::isShiftPressed () const { return (modifiers_ & Shift) != 0; }
unsigned char cv::viz::KeyboardEvent::getKeyCode () const { return key_code_; }
const cv::String& cv::viz::KeyboardEvent::getKeySym () const { return key_sym_; }
bool cv::viz::KeyboardEvent::keyDown () const { return action_; }
bool cv::viz::KeyboardEvent::keyUp () const { return !action_; }
////////////////////////////////////////////////////////////////////
/// cv::viz::MouseEvent
cv::viz::MouseEvent::MouseEvent (const Type& _type, const MouseButton& _button, const Point& _p, bool alt, bool ctrl, bool shift)
: type(_type), button(_button), pointer(_p), key_state(0)
{
if (alt)
key_state = KeyboardEvent::Alt;
if (ctrl)
key_state |= KeyboardEvent::Ctrl;
if (shift)
key_state |= KeyboardEvent::Shift;
}
////////////////////////////////////////////////////////////////////
/// cv::viz::Mesh3d
struct cv::viz::Mesh3d::loadMeshImpl
{
static cv::viz::Mesh3d loadMesh(const String &file)
{
Mesh3d mesh;
vtkSmartPointer<vtkPLYReader> reader = vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName(file.c_str());
reader->Update();
vtkSmartPointer<vtkPolyData> poly_data = reader->GetOutput ();
vtkSmartPointer<vtkPoints> mesh_points = poly_data->GetPoints ();
vtkIdType nr_points = mesh_points->GetNumberOfPoints ();
//vtkIdType nr_polygons = poly_data->GetNumberOfPolys ();
mesh.cloud.create(1, nr_points, CV_32FC3);
Vec3f *mesh_cloud = mesh.cloud.ptr<Vec3f>();
for (vtkIdType i = 0; i < mesh_points->GetNumberOfPoints (); i++)
{
Vec3d point;
mesh_points->GetPoint (i, point.val);
mesh_cloud[i] = point;
}
// Then the color information, if any
vtkUnsignedCharArray* poly_colors = NULL;
if (poly_data->GetPointData() != NULL)
poly_colors = vtkUnsignedCharArray::SafeDownCast (poly_data->GetPointData ()->GetScalars ("Colors"));
// some applications do not save the name of scalars (including PCL's native vtk_io)
if (!poly_colors && poly_data->GetPointData () != NULL)
poly_colors = vtkUnsignedCharArray::SafeDownCast (poly_data->GetPointData ()->GetScalars ("scalars"));
if (!poly_colors && poly_data->GetPointData () != NULL)
poly_colors = vtkUnsignedCharArray::SafeDownCast (poly_data->GetPointData ()->GetScalars ("RGB"));
// TODO: currently only handles rgb values with 3 components
if (poly_colors && (poly_colors->GetNumberOfComponents () == 3))
{
mesh.colors.create(1, nr_points, CV_8UC3);
Vec3b *mesh_colors = mesh.colors.ptr<cv::Vec3b>();
for (vtkIdType i = 0; i < mesh_points->GetNumberOfPoints (); i++)
{
Vec3b point_color;
poly_colors->GetTupleValue (i, point_color.val);
std::swap(point_color[0], point_color[2]); // RGB -> BGR
mesh_colors[i] = point_color;
}
}
else
mesh.colors.release();
// Now handle the polygons
vtkIdType* cell_points;
vtkIdType nr_cell_points;
vtkCellArray * mesh_polygons = poly_data->GetPolys ();
mesh_polygons->InitTraversal ();
mesh.polygons.create(1, mesh_polygons->GetSize(), CV_32SC1);
int* polygons = mesh.polygons.ptr<int>();
while (mesh_polygons->GetNextCell (nr_cell_points, cell_points))
{
*polygons++ = nr_cell_points;
for (int i = 0; i < nr_cell_points; ++i)
*polygons++ = static_cast<int> (cell_points[i]);
}
return mesh;
}
};
cv::viz::Mesh3d cv::viz::Mesh3d::loadMesh(const String& file)
{
return loadMeshImpl::loadMesh(file);
}
////////////////////////////////////////////////////////////////////
/// Camera implementation
cv::viz::Camera::Camera(float f_x, float f_y, float c_x, float c_y, const Size &window_size)
{
init(f_x, f_y, c_x, c_y, window_size);
}
cv::viz::Camera::Camera(const Vec2f &fov, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
setClip(Vec2d(0.01, 1000.01)); // Default clipping
principal_point_ = Vec2f(-1.0f, -1.0f); // Default symmetric lens
focal_ = Vec2f(-1.0f, -1.0f);
setFov(fov);
setWindowSize(window_size);
}
cv::viz::Camera::Camera(const cv::Matx33f & K, const Size &window_size)
{
float f_x = K(0,0);
float f_y = K(1,1);
float c_x = K(0,2);
float c_y = K(1,2);
init(f_x, f_y, c_x, c_y, window_size);
}
void cv::viz::Camera::init(float f_x, float f_y, float c_x, float c_y, const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
setClip(Vec2d(0.01, 1000.01));// Default clipping
fov_[0] = (atan2(c_x,f_x) + atan2(window_size.width-c_x,f_x));
fov_[1] = (atan2(c_y,f_y) + atan2(window_size.height-c_y,f_y));
principal_point_[0] = c_x;
principal_point_[1] = c_y;
focal_[0] = f_x;
focal_[1] = f_y;
setWindowSize(window_size);
}
void cv::viz::Camera::setWindowSize(const Size &window_size)
{
CV_Assert(window_size.width > 0 && window_size.height > 0);
// Vertical field of view is fixed!
// Horizontal field of view is expandable based on the aspect ratio
float aspect_ratio_new = static_cast<float>(window_size.width) / static_cast<float>(window_size.height);
if (principal_point_[0] < 0.0f)
fov_[0] = 2.f * atan(tan(fov_[1] * 0.5) * aspect_ratio_new); // This assumes that the lens is symmetric!
else
fov_[0] = (atan2(principal_point_[0],focal_[0]) + atan2(window_size.width-principal_point_[0],focal_[0])); // TODO I need to check this
window_size_ = window_size;
}
void cv::viz::Camera::computeProjectionMatrix(Matx44f &proj) const
{
double top = clip_[0] * tan (0.5 * fov_[1]);
double left = -(top * window_size_.width) / window_size_.height;
double right = -left;
double bottom = -top;
double temp1 = 2.0 * clip_[0];
double temp2 = 1.0 / (right - left);
double temp3 = 1.0 / (top - bottom);
double temp4 = 1.0 / clip_[1] - clip_[0];
proj = Matx44d::zeros();
proj(0,0) = temp1 * temp2;
proj(1,1) = temp1 * temp3;
proj(0,2) = (right + left) * temp2;
proj(1,2) = (top + bottom) * temp3;
proj(2,2) = (-clip_[1] - clip_[0]) * temp4;
proj(3,2) = -1.0;
proj(2,3) = (-temp1 * clip_[1]) * temp4;
}
cv::viz::Camera cv::viz::Camera::KinectCamera(const Size &window_size)
{
// Without distortion, RGB Camera
// Received from http://nicolas.burrus.name/index.php/Research/KinectCalibration
Matx33f K = Matx33f::zeros();
K(0,0) = 5.2921508098293293e+02;
K(0,2) = 3.2894272028759258e+02;
K(1,1) = 5.2556393630057437e+02;
K(1,2) = 2.6748068171871557e+02;
K(2,2) = 1.0f;
return Camera(K, window_size);
}<|endoftext|> |
<commit_before>/******************************************************************************
Copyright 2013 Allied Telesis Labs Ltd. 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 <buildsys.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
BuildDir::BuildDir(Package * P)
{
char *gname = strdup(P->getNS()->getName().c_str());
char *pname = strdup(P->getName().c_str());
char *pwd = strdup(P->getWorld()->getWorkingDir()->c_str());
this->WORLD = P->getWorld();
int res = mkdir("output", 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException("output", strerror(errno));
}
char *path = NULL;
if(asprintf(&path, "output/%s", gname) == -1) {
fprintf(stderr, "output/global-name path: %s\n", strerror(errno));
}
res = mkdir(path, 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path, strerror(errno));
}
free(path);
path = NULL;
if(asprintf(&path, "output/%s/staging", gname) == -1) {
fprintf(stderr, "Failed creating output/global-name/staging path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path, strerror(errno));
}
free(path);
path = NULL;
if(asprintf(&path, "output/%s/install", gname) == -1) {
fprintf(stderr, "Failed creating output/global-name/install path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path, strerror(errno));
}
free(path);
{
const char *tmp = strrchr(pname, '/');
if(tmp != NULL) {
char *subpart = strdup(pname);
subpart[tmp - pname] = '\0';
asprintf(&path, "mkdir -p output/%s/staging/%s", gname, subpart);
system(path);
free(path);
path = NULL;
asprintf(&path, "mkdir -p output/%s/install/%s", gname, subpart);
system(path);
free(path);
path = NULL;
free(subpart);
}
}
path = NULL;
if(asprintf(&path, "mkdir -p output/%s/%s", gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name path: %s\n",
strerror(errno));
}
res = system(path);
free(path);
path = NULL;
if(asprintf(&path, "%s/output/%s/%s/work", pwd, gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name/work path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path, strerror(errno));
}
this->path = std::string(path);
free(path);
path = NULL;
if(asprintf(&path, "output/%s/%s/work", gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name/work path: %s\n",
strerror(errno));
}
this->rpath = std::string(path);
free(path);
path = NULL;
if(asprintf(&path, "%s/output/%s/%s/new", pwd, gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name/new path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path, strerror(errno));
}
this->new_path = std::string(path);
free(path);
path = NULL;
if(asprintf(&path, "%s/output/%s/%s/staging", pwd, gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name/staging path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if(res < 0) {
if(errno != EEXIST) {
throw DirException(path, strerror(errno));
}
}
this->staging = std::string(path);
free(path);
path = NULL;
if(asprintf(&path, "%s/output/%s/%s/new/staging", pwd, gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name/new/staging path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if(res < 0) {
if(errno != EEXIST) {
throw DirException(path, strerror(errno));
}
}
this->new_staging = std::string(path);
free(path);
path = NULL;
if(asprintf(&path, "%s/output/%s/%s/new/install", pwd, gname, pname) == -1) {
fprintf(stderr,
"Failed creating output/global-name/package-name/new/install path: %s\n",
strerror(errno));
}
res = mkdir(path, 0700);
if(res < 0) {
if(errno != EEXIST) {
throw DirException(path, strerror(errno));
}
}
this->new_install = std::string(path);
free(path);
free(gname);
free(pname);
free(pwd);
}
void BuildDir::clean()
{
char *cmd = NULL;
asprintf(&cmd, "rm -fr %s", this->path.c_str());
system(cmd);
free(cmd);
int res = mkdir(this->path.c_str(), 0700);
if(res < 0) {
// We should complain here
}
}
void BuildDir::cleanStaging()
{
char *cmd = NULL;
asprintf(&cmd, "rm -fr %s", this->staging.c_str());
system(cmd);
free(cmd);
}
<commit_msg>builddir: Replace usages of asprintf with string_format<commit_after>/******************************************************************************
Copyright 2013 Allied Telesis Labs Ltd. 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 <buildsys.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
BuildDir::BuildDir(Package * P)
{
char *gname = strdup(P->getNS()->getName().c_str());
char *pname = strdup(P->getName().c_str());
char *pwd = strdup(P->getWorld()->getWorkingDir()->c_str());
this->WORLD = P->getWorld();
int res = mkdir("output", 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException("output", strerror(errno));
}
std::string path = string_format("output/%s", gname);
res = mkdir(path.c_str(), 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path.c_str(), strerror(errno));
}
path = string_format("output/%s/staging", gname);
res = mkdir(path.c_str(), 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path.c_str(), strerror(errno));
}
path = string_format("output/%s/install", gname);
res = mkdir(path.c_str(), 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path.c_str(), strerror(errno));
}
{
const char *tmp = strrchr(pname, '/');
if(tmp != NULL) {
char *subpart = strdup(pname);
subpart[tmp - pname] = '\0';
path = string_format("mkdir -p output/%s/staging/%s", gname,
subpart);
system(path.c_str());
path = string_format("mkdir -p output/%s/install/%s", gname,
subpart);
system(path.c_str());
free(subpart);
}
}
path = string_format("mkdir -p output/%s/%s", gname, pname);
res = system(path.c_str());
path = string_format("%s/output/%s/%s/work", pwd, gname, pname);
res = mkdir(path.c_str(), 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path.c_str(), strerror(errno));
}
this->path = path;
path = string_format("output/%s/%s/work", gname, pname);
this->rpath = path;
path = string_format("%s/output/%s/%s/new", pwd, gname, pname);
res = mkdir(path.c_str(), 0700);
if((res < 0) && (errno != EEXIST)) {
throw DirException(path.c_str(), strerror(errno));
}
this->new_path = path;
path = string_format("%s/output/%s/%s/staging", pwd, gname, pname);
res = mkdir(path.c_str(), 0700);
if(res < 0) {
if(errno != EEXIST) {
throw DirException(path.c_str(), strerror(errno));
}
}
this->staging = path;
path = string_format("%s/output/%s/%s/new/staging", pwd, gname, pname);
res = mkdir(path.c_str(), 0700);
if(res < 0) {
if(errno != EEXIST) {
throw DirException(path.c_str(), strerror(errno));
}
}
this->new_staging = path;
path = string_format("%s/output/%s/%s/new/install", pwd, gname, pname);
res = mkdir(path.c_str(), 0700);
if(res < 0) {
if(errno != EEXIST) {
throw DirException(path.c_str(), strerror(errno));
}
}
this->new_install = path;
free(gname);
free(pname);
free(pwd);
}
void BuildDir::clean()
{
std::string cmd = string_format("rm -fr %s", this->path.c_str());
system(cmd.c_str());
int res = mkdir(this->path.c_str(), 0700);
if(res < 0) {
// We should complain here
}
}
void BuildDir::cleanStaging()
{
std::string cmd = string_format("rm -fr %s", this->staging.c_str());
system(cmd.c_str());
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013-2014 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "engineuwsgi.h"
#include "plugin.h"
#include <Cutelyst/application.h>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QPluginLoader>
#include <QFileInfo>
using namespace Cutelyst;
static QList<EngineUwsgi *> coreEngines;
void cuteOutput(QtMsgType, const QMessageLogContext &, const QString &);
void uwsgi_cutelyst_loop(void);
/**
* This function is called as soon as
* the plugin is loaded
*/
extern "C" void uwsgi_cutelyst_on_load()
{
uwsgi_register_loop( (char *) "CutelystQtLoop", uwsgi_cutelyst_loop);
(void) new QCoreApplication(uwsgi.argc, uwsgi.argv);
if (qEnvironmentVariableIsEmpty("CUTELYST_NO_UWSGI_LOG")) {
qInstallMessageHandler(cuteOutput);
}
}
extern "C" int uwsgi_cutelyst_init()
{
uwsgi_log("Initializing Cutelyst plugin\n");
uwsgi.loop = (char *) "CutelystQtLoop";
return 0;
}
extern "C" void uwsgi_cutelyst_post_fork()
{
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
if (engine->thread() != qApp->thread()) {
engine->thread()->start();
} else {
Q_EMIT engine->postFork();
}
}
}
extern "C" int uwsgi_cutelyst_request(struct wsgi_request *wsgi_req)
{
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
return -1;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
return -1;
}
coreEngines.at(wsgi_req->async_id)->processRequest(wsgi_req);
return UWSGI_OK;
}
#ifdef UWSGI_GO_CHEAP_CODE // Actually we only need uwsgi 2.0.1
static void fsmon_reload(struct uwsgi_fsmon *fs)
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due to file change";
QFileInfo fileInfo(fs->path);
int count = 0;
// Ugly hack to wait for 2 seconds for the file to be filled
while (fileInfo.size() == 0 && count < 10) {
++count;
qCDebug(CUTELYST_UWSGI) << "Sleeping as the application file is empty" << count;
usleep(200 * 1000);
fileInfo.refresh();
}
uwsgi_reload(uwsgi.argv);
}
#endif // UWSGI_GO_CHEAP_CODE
/**
* This function is called when the master process is exiting
*/
extern "C" void uwsgi_cutelyst_master_cleanup()
{
qCDebug(CUTELYST_UWSGI) << "Master process finishing" << QCoreApplication::applicationPid();
delete qApp;
qCDebug(CUTELYST_UWSGI) << "Master process finished" << QCoreApplication::applicationPid();
}
/**
* This function is called when the child process is exiting
*/
extern "C" void uwsgi_cutelyst_atexit()
{
uwsgi_log("Child process finishing: %d\n", QCoreApplication::applicationPid());
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
engine->stop();
}
qDeleteAll(coreEngines);
uwsgi_log("Child process finished: %d\n", QCoreApplication::applicationPid());
}
extern "C" void uwsgi_cutelyst_init_apps()
{
QString path(options.app);
if (path.isEmpty()) {
uwsgi_log("Cutelyst application name or path was not set\n");
exit(1);
}
uwsgi_log("Cutelyst loading application: \"%s\"\n", options.app);
#ifdef UWSGI_GO_CHEAP_CODE
if (options.reload) {
// Register application auto reload
char *file = qstrdup(path.toUtf8().constData());
uwsgi_register_fsmon(file, fsmon_reload, NULL);
}
#endif // UWSGI_GO_CHEAP_CODE
// Set the configuration env
QStringList args = QCoreApplication::arguments();
QString config(options.config);
if (!config.isNull()) {
qputenv("CUTELYST_CONFIG", config.toUtf8());
} else if (args.contains("--ini")) {
int index = args.indexOf("--ini");
if (index != -1 && index < args.size()) {
qputenv("CUTELYST_CONFIG", args.at(index + 1).toUtf8());
}
}
QPluginLoader *loader = new QPluginLoader(path);
if (!loader->load()) {
uwsgi_log("Could not load application: %s\n", loader->errorString().data());
exit(1);
}
QObject *instance = loader->instance();
if (!instance) {
uwsgi_log("Could not get a QObject instance: %s\n", loader->errorString().data());
exit(1);
}
Application *app = qobject_cast<Application *>(instance);
if (!app) {
uwsgi_log("Could not cast Cutelyst::Application from instance: %s\n", loader->errorString().data());
exit(1);
}
EngineUwsgi *mainEngine = new EngineUwsgi(app);
if (!mainEngine->initApplication(app, false)) {
uwsgi_log("Failed to init application.\n");
exit(1);
}
coreEngines.append(mainEngine);
EngineUwsgi *engine = mainEngine;
for (int i = 0; i < uwsgi.cores; ++i) {
// Create the desired threads
// i > 0 the main thread counts as one thread
if (uwsgi.threads > 1 && i > 0) {
engine = new EngineUwsgi(app);
engine->setThread(new QThread);
// Post fork might fail when on threaded mode
QObject::connect(engine, &EngineUwsgi::engineDisabled,
mainEngine, &EngineUwsgi::reuseEngineRequests);
coreEngines.append(engine);
}
// Add core request
struct wsgi_request *wsgi_req = new wsgi_request;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = i;
engine->addUnusedRequest(wsgi_req);
}
// register a new app under a specific "mountpoint"
uwsgi_add_app(1, CUTELYST_MODIFIER1, (char *) "", 0, NULL, NULL);
delete loader;
}
void uwsgi_cutelyst_watch_signal(int signalFD)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(signalFD, QSocketNotifier::Read);
QObject::connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
socketNotifier->setEnabled(false);
uwsgi_receive_signal(fd, (char *) "worker", uwsgi.mywid);
socketNotifier->setEnabled(true);
});
}
void uwsgi_cutelyst_loop()
{
// ensure SIGPIPE is ignored
signal(SIGPIPE, SIG_IGN);
// FIX for some reason this is not being set by UWSGI
uwsgi.wait_read_hook = uwsgi_simple_wait_read_hook;
// monitor signals
if (uwsgi.signal_socket > -1) {
uwsgi_cutelyst_watch_signal(uwsgi.signal_socket);
uwsgi_cutelyst_watch_signal(uwsgi.my_signal_socket);
}
// start the qt event loop
qApp->exec();
}
void cuteOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
uwsgi_log("%s[debug] %s\n", context.category, localMsg.constData());
break;
case QtWarningMsg:
uwsgi_log("%s[warn] %s\n", context.category, localMsg.constData());
break;
case QtCriticalMsg:
uwsgi_log("%s[crit] %s\n", context.category, localMsg.constData());
break;
case QtFatalMsg:
uwsgi_log("%s[fatal] %s\n", context.category, localMsg.constData());
abort();
}
}
<commit_msg>On applications that do not set application name set it using the class name<commit_after>/*
* Copyright (C) 2013-2014 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "engineuwsgi.h"
#include "plugin.h"
#include <Cutelyst/application.h>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QPluginLoader>
#include <QFileInfo>
using namespace Cutelyst;
static QList<EngineUwsgi *> coreEngines;
void cuteOutput(QtMsgType, const QMessageLogContext &, const QString &);
void uwsgi_cutelyst_loop(void);
/**
* This function is called as soon as
* the plugin is loaded
*/
extern "C" void uwsgi_cutelyst_on_load()
{
uwsgi_register_loop( (char *) "CutelystQtLoop", uwsgi_cutelyst_loop);
(void) new QCoreApplication(uwsgi.argc, uwsgi.argv);
if (qEnvironmentVariableIsEmpty("CUTELYST_NO_UWSGI_LOG")) {
qInstallMessageHandler(cuteOutput);
}
}
extern "C" int uwsgi_cutelyst_init()
{
uwsgi_log("Initializing Cutelyst plugin\n");
uwsgi.loop = (char *) "CutelystQtLoop";
return 0;
}
extern "C" void uwsgi_cutelyst_post_fork()
{
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
if (engine->thread() != qApp->thread()) {
engine->thread()->start();
} else {
Q_EMIT engine->postFork();
}
}
}
extern "C" int uwsgi_cutelyst_request(struct wsgi_request *wsgi_req)
{
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
return -1;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
return -1;
}
coreEngines.at(wsgi_req->async_id)->processRequest(wsgi_req);
return UWSGI_OK;
}
#ifdef UWSGI_GO_CHEAP_CODE // Actually we only need uwsgi 2.0.1
static void fsmon_reload(struct uwsgi_fsmon *fs)
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due to file change";
QFileInfo fileInfo(fs->path);
int count = 0;
// Ugly hack to wait for 2 seconds for the file to be filled
while (fileInfo.size() == 0 && count < 10) {
++count;
qCDebug(CUTELYST_UWSGI) << "Sleeping as the application file is empty" << count;
usleep(200 * 1000);
fileInfo.refresh();
}
uwsgi_reload(uwsgi.argv);
}
#endif // UWSGI_GO_CHEAP_CODE
/**
* This function is called when the master process is exiting
*/
extern "C" void uwsgi_cutelyst_master_cleanup()
{
qCDebug(CUTELYST_UWSGI) << "Master process finishing" << QCoreApplication::applicationPid();
delete qApp;
qCDebug(CUTELYST_UWSGI) << "Master process finished" << QCoreApplication::applicationPid();
}
/**
* This function is called when the child process is exiting
*/
extern "C" void uwsgi_cutelyst_atexit()
{
uwsgi_log("Child process finishing: %d\n", QCoreApplication::applicationPid());
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
engine->stop();
}
qDeleteAll(coreEngines);
uwsgi_log("Child process finished: %d\n", QCoreApplication::applicationPid());
}
extern "C" void uwsgi_cutelyst_init_apps()
{
const QString &applicationName = QCoreApplication::applicationName();
QString path(options.app);
if (path.isEmpty()) {
uwsgi_log("Cutelyst application name or path was not set\n");
exit(1);
}
uwsgi_log("Cutelyst loading application: \"%s\"\n", options.app);
#ifdef UWSGI_GO_CHEAP_CODE
if (options.reload) {
// Register application auto reload
char *file = qstrdup(path.toUtf8().constData());
uwsgi_register_fsmon(file, fsmon_reload, NULL);
}
#endif // UWSGI_GO_CHEAP_CODE
// Set the configuration env
QStringList args = QCoreApplication::arguments();
QString config(options.config);
if (!config.isNull()) {
qputenv("CUTELYST_CONFIG", config.toUtf8());
} else if (args.contains("--ini")) {
int index = args.indexOf("--ini");
if (index != -1 && index < args.size()) {
qputenv("CUTELYST_CONFIG", args.at(index + 1).toUtf8());
}
}
QPluginLoader *loader = new QPluginLoader(path);
if (!loader->load()) {
uwsgi_log("Could not load application: %s\n", loader->errorString().data());
exit(1);
}
QObject *instance = loader->instance();
if (!instance) {
uwsgi_log("Could not get a QObject instance: %s\n", loader->errorString().data());
exit(1);
}
Application *app = qobject_cast<Application *>(instance);
if (!app) {
uwsgi_log("Could not cast Cutelyst::Application from instance: %s\n", loader->errorString().data());
exit(1);
}
// Sets the application name with the name from our library
if (QCoreApplication::applicationName() == applicationName && applicationName != app->applicationName()) {
QCoreApplication::setApplicationName(app->applicationName());
}
EngineUwsgi *mainEngine = new EngineUwsgi(app);
if (!mainEngine->initApplication(app, false)) {
uwsgi_log("Failed to init application.\n");
exit(1);
}
coreEngines.append(mainEngine);
EngineUwsgi *engine = mainEngine;
for (int i = 0; i < uwsgi.cores; ++i) {
// Create the desired threads
// i > 0 the main thread counts as one thread
if (uwsgi.threads > 1 && i > 0) {
engine = new EngineUwsgi(app);
engine->setThread(new QThread);
// Post fork might fail when on threaded mode
QObject::connect(engine, &EngineUwsgi::engineDisabled,
mainEngine, &EngineUwsgi::reuseEngineRequests);
coreEngines.append(engine);
}
// Add core request
struct wsgi_request *wsgi_req = new wsgi_request;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = i;
engine->addUnusedRequest(wsgi_req);
}
// register a new app under a specific "mountpoint"
uwsgi_add_app(1, CUTELYST_MODIFIER1, (char *) "", 0, NULL, NULL);
delete loader;
}
void uwsgi_cutelyst_watch_signal(int signalFD)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(signalFD, QSocketNotifier::Read);
QObject::connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
socketNotifier->setEnabled(false);
uwsgi_receive_signal(fd, (char *) "worker", uwsgi.mywid);
socketNotifier->setEnabled(true);
});
}
void uwsgi_cutelyst_loop()
{
// ensure SIGPIPE is ignored
signal(SIGPIPE, SIG_IGN);
// FIX for some reason this is not being set by UWSGI
uwsgi.wait_read_hook = uwsgi_simple_wait_read_hook;
// monitor signals
if (uwsgi.signal_socket > -1) {
uwsgi_cutelyst_watch_signal(uwsgi.signal_socket);
uwsgi_cutelyst_watch_signal(uwsgi.my_signal_socket);
}
// start the qt event loop
qApp->exec();
}
void cuteOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
uwsgi_log("%s[debug] %s\n", context.category, localMsg.constData());
break;
case QtWarningMsg:
uwsgi_log("%s[warn] %s\n", context.category, localMsg.constData());
break;
case QtCriticalMsg:
uwsgi_log("%s[crit] %s\n", context.category, localMsg.constData());
break;
case QtFatalMsg:
uwsgi_log("%s[fatal] %s\n", context.category, localMsg.constData());
abort();
}
}
<|endoftext|> |
<commit_before><commit_msg>There is no ExportCGM<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
*/
#include "GeometryCompressor.h"
#include "../Util/SimpleLogger.h"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <limits>
int current_free_list_maximum = 0;
int UniqueNumber() { return ++current_free_list_maximum; }
GeometryCompressor::GeometryCompressor()
{
m_free_list.reserve(100);
IncreaseFreeList();
}
void GeometryCompressor::IncreaseFreeList()
{
m_compressed_geometries.resize(m_compressed_geometries.size() + 100);
for (unsigned i = 100; i > 0; --i)
{
m_free_list.push_back(current_free_list_maximum);
++current_free_list_maximum;
}
}
bool GeometryCompressor::HasEntryForID(const EdgeID edge_id) const
{
return (m_edge_id_to_list_index_map.find(edge_id) != m_edge_id_to_list_index_map.end());
}
unsigned GeometryCompressor::GetPositionForID(const EdgeID edge_id) const
{
boost::unordered_map<EdgeID, unsigned>::const_iterator map_iterator;
map_iterator = m_edge_id_to_list_index_map.find(edge_id);
BOOST_ASSERT(map_iterator != m_edge_id_to_list_index_map.end());
BOOST_ASSERT(map_iterator->second < m_compressed_geometries.size());
return map_iterator->second;
}
void GeometryCompressor::SerializeInternalVector(const std::string &path) const
{
boost::filesystem::fstream geometry_out_stream(path, std::ios::binary|std::ios::out);
const unsigned number_of_compressed_geometries = m_compressed_geometries.size() + 1;
BOOST_ASSERT(UINT_MAX != number_of_compressed_geometries);
geometry_out_stream.write((char *)&number_of_compressed_geometries, sizeof(unsigned));
// write indices array
unsigned prefix_sum_of_list_indices = 0;
for (unsigned i = 0; i < m_compressed_geometries.size(); ++i)
{
geometry_out_stream.write((char *)&prefix_sum_of_list_indices, sizeof(unsigned));
const std::vector<CompressedNode> ¤t_vector = m_compressed_geometries.at(i);
const unsigned unpacked_size = current_vector.size();
BOOST_ASSERT(UINT_MAX != unpacked_size);
prefix_sum_of_list_indices += unpacked_size;
}
// sentinel element
geometry_out_stream.write((char *)&prefix_sum_of_list_indices, sizeof(unsigned));
// number of geometry entries to follow, it is the (inclusive) prefix sum
geometry_out_stream.write((char *)&prefix_sum_of_list_indices, sizeof(unsigned));
unsigned control_sum = 0;
// write compressed geometries
for (unsigned i = 0; i < m_compressed_geometries.size(); ++i)
{
const std::vector<CompressedNode> ¤t_vector = m_compressed_geometries[i];
const unsigned unpacked_size = current_vector.size();
control_sum += unpacked_size;
BOOST_ASSERT(UINT_MAX != unpacked_size);
BOOST_FOREACH (const CompressedNode current_node, current_vector)
{
geometry_out_stream.write((char *)&(current_node.first), sizeof(NodeID));
}
}
BOOST_ASSERT(control_sum == prefix_sum_of_list_indices);
// all done, let's close the resource
geometry_out_stream.close();
}
void GeometryCompressor::CompressEdge(const EdgeID edge_id_1,
const EdgeID edge_id_2,
const NodeID via_node_id,
const NodeID target_node_id,
const EdgeWeight weight1,
const EdgeWeight weight2)
{
// remove super-trivial geometries
BOOST_ASSERT(SPECIAL_EDGEID != edge_id_1);
BOOST_ASSERT(SPECIAL_EDGEID != edge_id_2);
BOOST_ASSERT(SPECIAL_NODEID != via_node_id);
BOOST_ASSERT(SPECIAL_NODEID != target_node_id);
BOOST_ASSERT(std::numeric_limits<unsigned>::max() != weight1);
BOOST_ASSERT(std::numeric_limits<unsigned>::max() != weight2);
// append list of removed edge_id plus via node to surviving edge id:
// <surv_1, .. , surv_n, via_node_id, rem_1, .. rem_n
//
// General scheme:
// 1. append via node id to list of edge_id_1
// 2. find list for edge_id_2, if yes add all elements and delete it
// Add via node id. List is created if it does not exist
if (!HasEntryForID(edge_id_1))
{
// create a new entry in the map
if (0 == m_free_list.size())
{
// make sure there is a place to put the entries
// SimpleLogger().Write() << "increased free list";
IncreaseFreeList();
}
BOOST_ASSERT(!m_free_list.empty());
// SimpleLogger().Write() << "free list size: " << m_free_list.size();
m_edge_id_to_list_index_map[edge_id_1] = m_free_list.back();
m_free_list.pop_back();
}
const unsigned edge_bucket_id1 = m_edge_id_to_list_index_map[edge_id_1];
BOOST_ASSERT(edge_bucket_id1 == GetPositionForID(edge_id_1));
BOOST_ASSERT(edge_bucket_id1 < m_compressed_geometries.size());
std::vector<CompressedNode> &edge_bucket_list1 = m_compressed_geometries[edge_bucket_id1];
if (edge_bucket_list1.empty())
{
edge_bucket_list1.push_back(std::make_pair(via_node_id, weight1));
}
BOOST_ASSERT(0 < edge_bucket_list1.size());
BOOST_ASSERT(!edge_bucket_list1.empty());
if (HasEntryForID(edge_id_2))
{
// second edge is not atomic anymore
const unsigned list_to_remove_index = GetPositionForID(edge_id_2);
BOOST_ASSERT(list_to_remove_index < m_compressed_geometries.size());
std::vector<CompressedNode> &edge_bucket_list2 =
m_compressed_geometries[list_to_remove_index];
// found an existing list, append it to the list of edge_id_1
edge_bucket_list1.insert(
edge_bucket_list1.end(), edge_bucket_list2.begin(), edge_bucket_list2.end());
// remove the list of edge_id_2
m_edge_id_to_list_index_map.erase(edge_id_2);
BOOST_ASSERT(m_edge_id_to_list_index_map.end() ==
m_edge_id_to_list_index_map.find(edge_id_2));
edge_bucket_list2.clear();
BOOST_ASSERT(0 == edge_bucket_list2.size());
m_free_list.push_back(list_to_remove_index);
BOOST_ASSERT(list_to_remove_index == m_free_list.back());
}
else
{
// we are certain that the second edge is atomic.
edge_bucket_list1.push_back(std::make_pair(target_node_id, weight2));
}
}
void GeometryCompressor::PrintStatistics() const
{
const uint64_t compressed_edges = m_compressed_geometries.size();
BOOST_ASSERT(0 == compressed_edges % 2);
BOOST_ASSERT(m_compressed_geometries.size() + m_free_list.size() > 0);
uint64_t number_of_compressed_geometries = 0;
uint64_t longest_chain_length = 0;
BOOST_FOREACH (const std::vector<CompressedNode> ¤t_vector, m_compressed_geometries)
{
number_of_compressed_geometries += current_vector.size();
longest_chain_length = std::max(longest_chain_length, (uint64_t)current_vector.size());
}
SimpleLogger().Write() << "Geometry successfully removed:"
"\n compressed edges: " << compressed_edges
<< "\n compressed geometries: " << number_of_compressed_geometries
<< "\n longest chain length: " << longest_chain_length
<< "\n cmpr ratio: "
<< ((float)compressed_edges /
std::max(number_of_compressed_geometries, (uint64_t)1))
<< "\n avg chain length: "
<< (float)number_of_compressed_geometries /
std::max((uint64_t)1, compressed_edges);
}
const std::vector<GeometryCompressor::CompressedNode> &
GeometryCompressor::GetBucketReference(const EdgeID edge_id) const
{
const unsigned index = m_edge_id_to_list_index_map.at(edge_id);
return m_compressed_geometries.at(index);
}
<commit_msg>remove further debug things<commit_after>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
*/
#include "GeometryCompressor.h"
#include "../Util/SimpleLogger.h"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <limits>
int current_free_list_maximum = 0;
int UniqueNumber() { return ++current_free_list_maximum; }
GeometryCompressor::GeometryCompressor()
{
m_free_list.reserve(100);
IncreaseFreeList();
}
void GeometryCompressor::IncreaseFreeList()
{
m_compressed_geometries.resize(m_compressed_geometries.size() + 100);
for (unsigned i = 100; i > 0; --i)
{
m_free_list.push_back(current_free_list_maximum);
++current_free_list_maximum;
}
}
bool GeometryCompressor::HasEntryForID(const EdgeID edge_id) const
{
return (m_edge_id_to_list_index_map.find(edge_id) != m_edge_id_to_list_index_map.end());
}
unsigned GeometryCompressor::GetPositionForID(const EdgeID edge_id) const
{
boost::unordered_map<EdgeID, unsigned>::const_iterator map_iterator;
map_iterator = m_edge_id_to_list_index_map.find(edge_id);
BOOST_ASSERT(map_iterator != m_edge_id_to_list_index_map.end());
BOOST_ASSERT(map_iterator->second < m_compressed_geometries.size());
return map_iterator->second;
}
void GeometryCompressor::SerializeInternalVector(const std::string &path) const
{
boost::filesystem::fstream geometry_out_stream(path, std::ios::binary|std::ios::out);
const unsigned number_of_compressed_geometries = m_compressed_geometries.size() + 1;
BOOST_ASSERT(UINT_MAX != number_of_compressed_geometries);
geometry_out_stream.write((char *)&number_of_compressed_geometries, sizeof(unsigned));
// write indices array
unsigned prefix_sum_of_list_indices = 0;
for (unsigned i = 0; i < m_compressed_geometries.size(); ++i)
{
geometry_out_stream.write((char *)&prefix_sum_of_list_indices, sizeof(unsigned));
const std::vector<CompressedNode> ¤t_vector = m_compressed_geometries.at(i);
const unsigned unpacked_size = current_vector.size();
BOOST_ASSERT(UINT_MAX != unpacked_size);
prefix_sum_of_list_indices += unpacked_size;
}
// sentinel element
geometry_out_stream.write((char *)&prefix_sum_of_list_indices, sizeof(unsigned));
// number of geometry entries to follow, it is the (inclusive) prefix sum
geometry_out_stream.write((char *)&prefix_sum_of_list_indices, sizeof(unsigned));
unsigned control_sum = 0;
// write compressed geometries
for (unsigned i = 0; i < m_compressed_geometries.size(); ++i)
{
const std::vector<CompressedNode> ¤t_vector = m_compressed_geometries[i];
const unsigned unpacked_size = current_vector.size();
control_sum += unpacked_size;
BOOST_ASSERT(UINT_MAX != unpacked_size);
BOOST_FOREACH (const CompressedNode current_node, current_vector)
{
geometry_out_stream.write((char *)&(current_node.first), sizeof(NodeID));
}
}
BOOST_ASSERT(control_sum == prefix_sum_of_list_indices);
// all done, let's close the resource
geometry_out_stream.close();
}
void GeometryCompressor::CompressEdge(const EdgeID edge_id_1,
const EdgeID edge_id_2,
const NodeID via_node_id,
const NodeID target_node_id,
const EdgeWeight weight1,
const EdgeWeight weight2)
{
// remove super-trivial geometries
BOOST_ASSERT(SPECIAL_EDGEID != edge_id_1);
BOOST_ASSERT(SPECIAL_EDGEID != edge_id_2);
BOOST_ASSERT(SPECIAL_NODEID != via_node_id);
BOOST_ASSERT(SPECIAL_NODEID != target_node_id);
BOOST_ASSERT(std::numeric_limits<unsigned>::max() != weight1);
BOOST_ASSERT(std::numeric_limits<unsigned>::max() != weight2);
// append list of removed edge_id plus via node to surviving edge id:
// <surv_1, .. , surv_n, via_node_id, rem_1, .. rem_n
//
// General scheme:
// 1. append via node id to list of edge_id_1
// 2. find list for edge_id_2, if yes add all elements and delete it
// Add via node id. List is created if it does not exist
if (!HasEntryForID(edge_id_1))
{
// create a new entry in the map
if (0 == m_free_list.size())
{
// make sure there is a place to put the entries
IncreaseFreeList();
}
BOOST_ASSERT(!m_free_list.empty());
m_edge_id_to_list_index_map[edge_id_1] = m_free_list.back();
m_free_list.pop_back();
}
const unsigned edge_bucket_id1 = m_edge_id_to_list_index_map[edge_id_1];
BOOST_ASSERT(edge_bucket_id1 == GetPositionForID(edge_id_1));
BOOST_ASSERT(edge_bucket_id1 < m_compressed_geometries.size());
std::vector<CompressedNode> &edge_bucket_list1 = m_compressed_geometries[edge_bucket_id1];
if (edge_bucket_list1.empty())
{
edge_bucket_list1.push_back(std::make_pair(via_node_id, weight1));
}
BOOST_ASSERT(0 < edge_bucket_list1.size());
BOOST_ASSERT(!edge_bucket_list1.empty());
if (HasEntryForID(edge_id_2))
{
// second edge is not atomic anymore
const unsigned list_to_remove_index = GetPositionForID(edge_id_2);
BOOST_ASSERT(list_to_remove_index < m_compressed_geometries.size());
std::vector<CompressedNode> &edge_bucket_list2 =
m_compressed_geometries[list_to_remove_index];
// found an existing list, append it to the list of edge_id_1
edge_bucket_list1.insert(
edge_bucket_list1.end(), edge_bucket_list2.begin(), edge_bucket_list2.end());
// remove the list of edge_id_2
m_edge_id_to_list_index_map.erase(edge_id_2);
BOOST_ASSERT(m_edge_id_to_list_index_map.end() ==
m_edge_id_to_list_index_map.find(edge_id_2));
edge_bucket_list2.clear();
BOOST_ASSERT(0 == edge_bucket_list2.size());
m_free_list.push_back(list_to_remove_index);
BOOST_ASSERT(list_to_remove_index == m_free_list.back());
}
else
{
// we are certain that the second edge is atomic.
edge_bucket_list1.push_back(std::make_pair(target_node_id, weight2));
}
}
void GeometryCompressor::PrintStatistics() const
{
const uint64_t compressed_edges = m_compressed_geometries.size();
BOOST_ASSERT(0 == compressed_edges % 2);
BOOST_ASSERT(m_compressed_geometries.size() + m_free_list.size() > 0);
uint64_t number_of_compressed_geometries = 0;
uint64_t longest_chain_length = 0;
BOOST_FOREACH (const std::vector<CompressedNode> ¤t_vector, m_compressed_geometries)
{
number_of_compressed_geometries += current_vector.size();
longest_chain_length = std::max(longest_chain_length, (uint64_t)current_vector.size());
}
SimpleLogger().Write() << "Geometry successfully removed:"
"\n compressed edges: " << compressed_edges
<< "\n compressed geometries: " << number_of_compressed_geometries
<< "\n longest chain length: " << longest_chain_length
<< "\n cmpr ratio: "
<< ((float)compressed_edges /
std::max(number_of_compressed_geometries, (uint64_t)1))
<< "\n avg chain length: "
<< (float)number_of_compressed_geometries /
std::max((uint64_t)1, compressed_edges);
}
const std::vector<GeometryCompressor::CompressedNode> &
GeometryCompressor::GetBucketReference(const EdgeID edge_id) const
{
const unsigned index = m_edge_id_to_list_index_map.at(edge_id);
return m_compressed_geometries.at(index);
}
<|endoftext|> |
<commit_before>#include "sim_obj.h"
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
void sim_obj::resizeMatrix(vector<vector<double>>& p_Matrix, int newSize) {
p_Matrix.clear();
p_Matrix.resize(newSize, vector<double>(newSize, 0));
}
double sim_obj::calcCompDistance(int bodyID_A, int bodyID_B, int xy) {
double posA = bodyStore[bodyID_A].getPosition(xy);
double posB = bodyStore[bodyID_B].getPosition(xy);
// Return component distance
return posA - posB;
}
double sim_obj::calcVectDistance(double distX, double distY) {
return sqrt(pow(abs(distX),2) + pow(abs(distY), 2));
}
double sim_obj::calcForceBodyPair(int bodyID_A, int bodyID_B, int xy) {
double distX, distY, distV;
// Component Distance
distX = calcCompDistance(bodyID_A, bodyID_B, 0);
distY = calcCompDistance(bodyID_A, bodyID_B, 1);
// Vector Distance
distV = calcVectDistance(distX, distY);
// GMm/(r^3)
double forceResult;
forceResult = gravitationalConstant * bodyStore[bodyID_A].getMass() * bodyStore[bodyID_B].getMass();
forceResult /= pow(distV, 3);
if (xy)
forceResult *= distY;
else
forceResult *= distX;
return -forceResult;
}
int sim_obj::calcForceMatrix() {
resizeMatrix(forceMatrix, bodyStore.size());
prevBodyCount = bodyStore.size();
// Loop Half Matrix
for (unsigned int xAccess = 0; xAccess < bodyStore.size(); xAccess++) {
for (unsigned int yAccess = xAccess + 1; yAccess < bodyStore.size(); yAccess++) {
// Skip if checking same body
if (xAccess != yAccess) {
forceMatrix[xAccess][yAccess] = calcForceBodyPair(xAccess, yAccess, 0);
forceMatrix[yAccess][xAccess] = calcForceBodyPair(xAccess, yAccess, 1);
}
}
}
// Return Success
return 0;
}
// Applies to All Bodies, sets in body vector.
int sim_obj::calcForceSumAB() {
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].resetForce();
}
for (unsigned int xAccess = 0; xAccess < bodyStore.size(); xAccess++) {
for (unsigned int yAccess = 0; yAccess < bodyStore.size(); yAccess++) {
// Ignore Middle Diagonal
if (yAccess != xAccess) {
// If yAccess is smaller than xAccess, flip coordinates to stay within half matrix.
if (yAccess < xAccess) {
// Add Component force to get total component forces for x and y.
bodyStore[xAccess].addForce(-forceMatrix[yAccess][xAccess], 0);
bodyStore[yAccess].addForce( forceMatrix[xAccess][yAccess], 1);
} else {
bodyStore[xAccess].addForce( forceMatrix[xAccess][yAccess], 0);
bodyStore[yAccess].addForce(-forceMatrix[yAccess][xAccess], 1);
}
}
}
}
return 0;
}
int sim_obj::calcAcceleraitonAB() {
// Update Forces before Acceleration Update
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].calcAcceleration();
//cout << bodyIDC << " : " << bodyStore[bodyIDC].getAcceleration(0) << ", " << bodyStore[bodyIDC].getAcceleration(1) << endl;
}
return 0;
}
int sim_obj::calcHalfVelocityAB() {
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].calcHalfVelocity();
//cout << bodyIDC << " : " << bodyStore[bodyIDC].getVelocity(0) << ", " << bodyStore[bodyIDC].getVelocity(1) << endl;
}
return 0;
}
int sim_obj::calcPositionAB() {
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].calcPosition();
}
return 0;
}
sim_obj::sim_obj() {
}
sim_obj::~sim_obj() {
}
int sim_obj::itteration() {
if (scenarioChanged) {
// Calculate Initial Forces and Accelerations
calcForceMatrix();
calcForceSumAB();
calcAcceleraitonAB();
scenarioChanged = false;
}
// Move Half for Half Time
calcHalfVelocityAB();
calcPositionAB();
// Update Forces and Accelerations
calcForceMatrix();
calcForceSumAB();
calcAcceleraitonAB();
// Calculate New Velocity
calcHalfVelocityAB();
return 0;
}
void sim_obj::outputStore(int itteration) {
if (itteration % 1000 == 0) {
//cerr << itteration;
// Store Body Position Data in Array.
for(unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
for(unsigned int bodyXY = 0; bodyXY < 2; bodyXY++) {
outputData[itteration/1000][bodyIDC][bodyXY] = bodyStore[bodyIDC].getPosition(bodyXY);
}
}
}
}
// Output Position Array to Output Stream.
void sim_obj::outputToTerm() {
for (int i = 0; i < 1000; i++) {
for (int bodyIDC = 0; bodyIDC < 3; bodyIDC++) {
for (int bodyXY = 0; bodyXY < 2; bodyXY++) {
cout << outputData[i][bodyIDC][bodyXY] << " ";
}
}
cout << endl;
}
}
<commit_msg>Added column headers.<commit_after>#include "sim_obj.h"
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
void sim_obj::resizeMatrix(vector<vector<double>>& p_Matrix, int newSize) {
p_Matrix.clear();
p_Matrix.resize(newSize, vector<double>(newSize, 0));
}
double sim_obj::calcCompDistance(int bodyID_A, int bodyID_B, int xy) {
double posA = bodyStore[bodyID_A].getPosition(xy);
double posB = bodyStore[bodyID_B].getPosition(xy);
// Return component distance
return posA - posB;
}
double sim_obj::calcVectDistance(double distX, double distY) {
return sqrt(pow(abs(distX),2) + pow(abs(distY), 2));
}
double sim_obj::calcForceBodyPair(int bodyID_A, int bodyID_B, int xy) {
double distX, distY, distV;
// Component Distance
distX = calcCompDistance(bodyID_A, bodyID_B, 0);
distY = calcCompDistance(bodyID_A, bodyID_B, 1);
// Vector Distance
distV = calcVectDistance(distX, distY);
// GMm/(r^3)
double forceResult;
forceResult = gravitationalConstant * bodyStore[bodyID_A].getMass() * bodyStore[bodyID_B].getMass();
forceResult /= pow(distV, 3);
if (xy)
forceResult *= distY;
else
forceResult *= distX;
return -forceResult;
}
int sim_obj::calcForceMatrix() {
resizeMatrix(forceMatrix, bodyStore.size());
prevBodyCount = bodyStore.size();
// Loop Half Matrix
for (unsigned int xAccess = 0; xAccess < bodyStore.size(); xAccess++) {
for (unsigned int yAccess = xAccess + 1; yAccess < bodyStore.size(); yAccess++) {
// Skip if checking same body
if (xAccess != yAccess) {
forceMatrix[xAccess][yAccess] = calcForceBodyPair(xAccess, yAccess, 0);
forceMatrix[yAccess][xAccess] = calcForceBodyPair(xAccess, yAccess, 1);
}
}
}
// Return Success
return 0;
}
// Applies to All Bodies, sets in body vector.
int sim_obj::calcForceSumAB() {
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].resetForce();
}
for (unsigned int xAccess = 0; xAccess < bodyStore.size(); xAccess++) {
for (unsigned int yAccess = 0; yAccess < bodyStore.size(); yAccess++) {
// Ignore Middle Diagonal
if (yAccess != xAccess) {
// If yAccess is smaller than xAccess, flip coordinates to stay within half matrix.
if (yAccess < xAccess) {
// Add Component force to get total component forces for x and y.
bodyStore[xAccess].addForce(-forceMatrix[yAccess][xAccess], 0);
bodyStore[yAccess].addForce( forceMatrix[xAccess][yAccess], 1);
} else {
bodyStore[xAccess].addForce( forceMatrix[xAccess][yAccess], 0);
bodyStore[yAccess].addForce(-forceMatrix[yAccess][xAccess], 1);
}
}
}
}
return 0;
}
int sim_obj::calcAcceleraitonAB() {
// Update Forces before Acceleration Update
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].calcAcceleration();
//cout << bodyIDC << " : " << bodyStore[bodyIDC].getAcceleration(0) << ", " << bodyStore[bodyIDC].getAcceleration(1) << endl;
}
return 0;
}
int sim_obj::calcHalfVelocityAB() {
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].calcHalfVelocity();
//cout << bodyIDC << " : " << bodyStore[bodyIDC].getVelocity(0) << ", " << bodyStore[bodyIDC].getVelocity(1) << endl;
}
return 0;
}
int sim_obj::calcPositionAB() {
for (unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
bodyStore[bodyIDC].calcPosition();
}
return 0;
}
sim_obj::sim_obj() {
}
sim_obj::~sim_obj() {
}
int sim_obj::itteration() {
if (scenarioChanged) {
// Calculate Initial Forces and Accelerations
calcForceMatrix();
calcForceSumAB();
calcAcceleraitonAB();
scenarioChanged = false;
}
// Move Half for Half Time
calcHalfVelocityAB();
calcPositionAB();
// Update Forces and Accelerations
calcForceMatrix();
calcForceSumAB();
calcAcceleraitonAB();
// Calculate New Velocity
calcHalfVelocityAB();
return 0;
}
void sim_obj::outputStore(int itteration) {
if (itteration % 1000 == 0) {
//cerr << itteration;
// Store Body Position Data in Array.
for(unsigned int bodyIDC = 0; bodyIDC < bodyStore.size(); bodyIDC++) {
for(unsigned int bodyXY = 0; bodyXY < 2; bodyXY++) {
outputData[itteration/1000][bodyIDC][bodyXY] = bodyStore[bodyIDC].getPosition(bodyXY);
}
}
}
}
// Output Position Array to Output Stream.
void sim_obj::outputToTerm() {
cout << "1x 1y 2x 2y" << endl;
for (int i = 0; i < 1000; i++) {
for (int bodyIDC = 0; bodyIDC < 3; bodyIDC++) {
for (int bodyXY = 0; bodyXY < 2; bodyXY++) {
cout << outputData[i][bodyIDC][bodyXY] << " ";
}
}
cout << endl;
}
}
<|endoftext|> |
<commit_before>// Copyright 2013 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/common/metrics/caching_permuted_entropy_provider.h"
#include <string>
#include "base/basictypes.h"
#include "base/prefs/testing_pref_service.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace metrics {
// Size of the low entropy source to use for the permuted entropy provider
// in tests.
const size_t kMaxLowEntropySize = 8000;
// Field trial names used in unit tests.
const char* const kTestTrialNames[] = { "TestTrial", "AnotherTestTrial",
"NewTabButton" };
TEST(CachingPermutedEntropyProviderTest, HasConsistentResults) {
TestingPrefServiceSimple prefs;
CachingPermutedEntropyProvider::RegisterPrefs(prefs.registry());
const int kEntropyValue = 1234;
// Check that the caching provider returns the same results as the non caching
// one. Loop over the trial names twice, to test that caching returns the
// expected results.
PermutedEntropyProvider provider(kEntropyValue, kMaxLowEntropySize);
for (size_t i = 0; i < 2 * arraysize(kTestTrialNames); ++i) {
CachingPermutedEntropyProvider cached_provider(&prefs, kEntropyValue,
kMaxLowEntropySize);
const std::string trial_name =
kTestTrialNames[i % arraysize(kTestTrialNames)];
EXPECT_EQ(provider.GetEntropyForTrial(trial_name, 0),
cached_provider.GetEntropyForTrial(trial_name, 0));
}
// Now, do the same test re-using the same caching provider.
CachingPermutedEntropyProvider cached_provider(&prefs, kEntropyValue,
kMaxLowEntropySize);
for (size_t i = 0; i < 2 * arraysize(kTestTrialNames); ++i) {
const std::string trial_name =
kTestTrialNames[i % arraysize(kTestTrialNames)];
EXPECT_EQ(provider.GetEntropyForTrial(trial_name, 0),
cached_provider.GetEntropyForTrial(trial_name, 0));
}
}
} // namespace metrics
<commit_msg>Use float comparison macros in caching entropy test.<commit_after>// Copyright 2013 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/common/metrics/caching_permuted_entropy_provider.h"
#include <string>
#include "base/basictypes.h"
#include "base/prefs/testing_pref_service.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace metrics {
// Size of the low entropy source to use for the permuted entropy provider
// in tests.
const size_t kMaxLowEntropySize = 8000;
// Field trial names used in unit tests.
const char* const kTestTrialNames[] = { "TestTrial", "AnotherTestTrial",
"NewTabButton" };
TEST(CachingPermutedEntropyProviderTest, HasConsistentResults) {
TestingPrefServiceSimple prefs;
CachingPermutedEntropyProvider::RegisterPrefs(prefs.registry());
const int kEntropyValue = 1234;
// Check that the caching provider returns the same results as the non caching
// one. Loop over the trial names twice, to test that caching returns the
// expected results.
PermutedEntropyProvider provider(kEntropyValue, kMaxLowEntropySize);
for (size_t i = 0; i < 2 * arraysize(kTestTrialNames); ++i) {
CachingPermutedEntropyProvider cached_provider(&prefs, kEntropyValue,
kMaxLowEntropySize);
const std::string trial_name =
kTestTrialNames[i % arraysize(kTestTrialNames)];
EXPECT_DOUBLE_EQ(provider.GetEntropyForTrial(trial_name, 0),
cached_provider.GetEntropyForTrial(trial_name, 0));
}
// Now, do the same test re-using the same caching provider.
CachingPermutedEntropyProvider cached_provider(&prefs, kEntropyValue,
kMaxLowEntropySize);
for (size_t i = 0; i < 2 * arraysize(kTestTrialNames); ++i) {
const std::string trial_name =
kTestTrialNames[i % arraysize(kTestTrialNames)];
EXPECT_DOUBLE_EQ(provider.GetEntropyForTrial(trial_name, 0),
cached_provider.GetEntropyForTrial(trial_name, 0));
}
}
} // namespace metrics
<|endoftext|> |
<commit_before>/*
* Copyright 2016 The Cartographer Authors
*
* 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 "cartographer/mapping_2d/sparse_pose_graph/optimization_problem.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "cartographer/common/ceres_solver_options.h"
#include "cartographer/common/histogram.h"
#include "cartographer/common/math.h"
#include "cartographer/mapping_2d/sparse_pose_graph/spa_cost_function.h"
#include "cartographer/transform/transform.h"
#include "ceres/ceres.h"
#include "glog/logging.h"
namespace cartographer {
namespace mapping_2d {
namespace sparse_pose_graph {
namespace {
// Converts a pose into the 3 optimization variable format used for Ceres:
// translation in x and y, followed by the rotation angle representing the
// orientation.
std::array<double, 3> FromPose(const transform::Rigid2d& pose) {
return {{pose.translation().x(), pose.translation().y(),
pose.normalized_angle()}};
}
// Converts a pose as represented for Ceres back to an transform::Rigid2d pose.
transform::Rigid2d ToPose(const std::array<double, 3>& values) {
return transform::Rigid2d({values[0], values[1]}, values[2]);
}
} // namespace
OptimizationProblem::OptimizationProblem(
const mapping::sparse_pose_graph::proto::OptimizationProblemOptions&
options)
: options_(options) {}
OptimizationProblem::~OptimizationProblem() {}
void OptimizationProblem::AddImuData(const int trajectory_id,
const common::Time time,
const Eigen::Vector3d& linear_acceleration,
const Eigen::Vector3d& angular_velocity) {
CHECK_GE(trajectory_id, 0);
imu_data_.resize(
std::max(imu_data_.size(), static_cast<size_t>(trajectory_id) + 1));
imu_data_[trajectory_id].push_back(
sensor::ImuData{time, linear_acceleration, angular_velocity});
}
void OptimizationProblem::AddTrajectoryNode(
const int trajectory_id, const common::Time time,
const transform::Rigid2d& initial_point_cloud_pose,
const transform::Rigid2d& point_cloud_pose) {
CHECK_GE(trajectory_id, 0);
node_data_.resize(
std::max(node_data_.size(), static_cast<size_t>(trajectory_id) + 1));
node_data_[trajectory_id].push_back(
NodeData{time, initial_point_cloud_pose, point_cloud_pose});
trajectory_data_.resize(std::max(trajectory_data_.size(), node_data_.size()));
}
void OptimizationProblem::TrimTrajectoryNode(const mapping::NodeId& node_id) {
auto& trajectory_data = trajectory_data_.at(node_id.trajectory_id);
// We only allow trimming from the start.
CHECK_EQ(trajectory_data.num_trimmed_nodes, node_id.node_index);
auto& node_data = node_data_.at(node_id.trajectory_id);
CHECK(!node_data.empty());
const common::Time node_time = node_data.front().time;
auto& imu_data = imu_data_.at(node_id.trajectory_id);
while (imu_data.size() > 1 && imu_data[1].time <= node_time) {
imu_data.pop_front();
}
node_data.pop_front();
++trajectory_data.num_trimmed_nodes;
}
void OptimizationProblem::AddSubmap(const int trajectory_id,
const transform::Rigid2d& submap_pose) {
CHECK_GE(trajectory_id, 0);
submap_data_.resize(
std::max(submap_data_.size(), static_cast<size_t>(trajectory_id) + 1));
submap_data_[trajectory_id].push_back(SubmapData{submap_pose});
trajectory_data_.resize(
std::max(trajectory_data_.size(), submap_data_.size()));
}
void OptimizationProblem::TrimSubmap(const mapping::SubmapId& submap_id) {
auto& trajectory_data = trajectory_data_.at(submap_id.trajectory_id);
// We only allow trimming from the start.
CHECK_EQ(trajectory_data.num_trimmed_submaps, submap_id.submap_index);
auto& submap_data = submap_data_.at(submap_id.trajectory_id);
CHECK(!submap_data.empty());
submap_data.pop_front();
++trajectory_data.num_trimmed_submaps;
}
void OptimizationProblem::SetMaxNumIterations(const int32 max_num_iterations) {
options_.mutable_ceres_solver_options()->set_max_num_iterations(
max_num_iterations);
}
void OptimizationProblem::Solve(const std::vector<Constraint>& constraints,
const std::set<int>& frozen_trajectories) {
if (node_data_.empty()) {
// Nothing to optimize.
return;
}
ceres::Problem::Options problem_options;
ceres::Problem problem(problem_options);
// Set the starting point.
// TODO(hrapp): Move ceres data into SubmapData.
std::vector<std::vector<std::array<double, 3>>> C_submaps(
submap_data_.size());
std::vector<std::vector<std::array<double, 3>>> C_nodes(node_data_.size());
bool first_submap = true;
for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();
++trajectory_id) {
const bool frozen = frozen_trajectories.count(trajectory_id);
// Reserve guarantees that data does not move, so the pointers for Ceres
// stay valid.
C_submaps[trajectory_id].reserve(submap_data_[trajectory_id].size());
for (const SubmapData& submap_data : submap_data_[trajectory_id]) {
C_submaps[trajectory_id].push_back(FromPose(submap_data.pose));
problem.AddParameterBlock(C_submaps[trajectory_id].back().data(), 3);
if (first_submap || frozen) {
first_submap = false;
// Fix the pose of the first submap or all submaps of a frozen
// trajectory.
problem.SetParameterBlockConstant(
C_submaps[trajectory_id].back().data());
}
}
}
for (size_t trajectory_id = 0; trajectory_id != node_data_.size();
++trajectory_id) {
// Reserve guarantees that data does not move, so the pointers for Ceres
// stay valid.
C_nodes[trajectory_id].reserve(node_data_[trajectory_id].size());
for (const NodeData& node_data : node_data_[trajectory_id]) {
C_nodes[trajectory_id].push_back(FromPose(node_data.point_cloud_pose));
problem.AddParameterBlock(C_nodes[trajectory_id].back().data(), 3);
}
}
// Add cost functions for intra- and inter-submap constraints.
for (const Constraint& constraint : constraints) {
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<SpaCostFunction, 3, 3, 3>(
new SpaCostFunction(constraint.pose)),
// Only loop closure constraints should have a loss function.
constraint.tag == Constraint::INTER_SUBMAP
? new ceres::HuberLoss(options_.huber_scale())
: nullptr,
C_submaps.at(constraint.submap_id.trajectory_id)
.at(constraint.submap_id.submap_index -
trajectory_data_.at(constraint.submap_id.trajectory_id)
.num_trimmed_submaps)
.data(),
C_nodes.at(constraint.node_id.trajectory_id)
.at(constraint.node_id.node_index -
trajectory_data_.at(constraint.node_id.trajectory_id)
.num_trimmed_nodes)
.data());
}
// Add penalties for changes between consecutive scans.
for (size_t trajectory_id = 0; trajectory_id != node_data_.size();
++trajectory_id) {
for (size_t node_data_index = 1;
node_data_index < node_data_[trajectory_id].size();
++node_data_index) {
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<SpaCostFunction, 3, 3, 3>(
new SpaCostFunction(Constraint::Pose{
transform::Embed3D(
node_data_[trajectory_id][node_data_index - 1]
.initial_point_cloud_pose.inverse() *
node_data_[trajectory_id][node_data_index]
.initial_point_cloud_pose),
options_.consecutive_scan_translation_penalty_factor(),
options_.consecutive_scan_rotation_penalty_factor()})),
nullptr /* loss function */,
C_nodes[trajectory_id][node_data_index - 1].data(),
C_nodes[trajectory_id][node_data_index].data());
}
}
// Solve.
ceres::Solver::Summary summary;
ceres::Solve(
common::CreateCeresSolverOptions(options_.ceres_solver_options()),
&problem, &summary);
if (options_.log_solver_summary()) {
LOG(INFO) << summary.FullReport();
}
// Store the result.
for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();
++trajectory_id) {
for (size_t submap_data_index = 0;
submap_data_index != submap_data_[trajectory_id].size();
++submap_data_index) {
submap_data_[trajectory_id][submap_data_index].pose =
ToPose(C_submaps[trajectory_id][submap_data_index]);
}
}
for (size_t trajectory_id = 0; trajectory_id != node_data_.size();
++trajectory_id) {
for (size_t node_data_index = 0;
node_data_index != node_data_[trajectory_id].size();
++node_data_index) {
node_data_[trajectory_id][node_data_index].point_cloud_pose =
ToPose(C_nodes[trajectory_id][node_data_index]);
}
}
}
const std::vector<std::deque<NodeData>>& OptimizationProblem::node_data()
const {
return node_data_;
}
const std::vector<std::deque<SubmapData>>& OptimizationProblem::submap_data()
const {
return submap_data_;
}
int OptimizationProblem::num_trimmed_nodes(int trajectory_id) const {
return trajectory_data_.at(trajectory_id).num_trimmed_nodes;
}
int OptimizationProblem::num_trimmed_submaps(int trajectory_id) const {
return trajectory_data_.at(trajectory_id).num_trimmed_submaps;
}
} // namespace sparse_pose_graph
} // namespace mapping_2d
} // namespace cartographer
<commit_msg>Check imu_data array size before access (#392)<commit_after>/*
* Copyright 2016 The Cartographer Authors
*
* 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 "cartographer/mapping_2d/sparse_pose_graph/optimization_problem.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "cartographer/common/ceres_solver_options.h"
#include "cartographer/common/histogram.h"
#include "cartographer/common/math.h"
#include "cartographer/mapping_2d/sparse_pose_graph/spa_cost_function.h"
#include "cartographer/transform/transform.h"
#include "ceres/ceres.h"
#include "glog/logging.h"
namespace cartographer {
namespace mapping_2d {
namespace sparse_pose_graph {
namespace {
// Converts a pose into the 3 optimization variable format used for Ceres:
// translation in x and y, followed by the rotation angle representing the
// orientation.
std::array<double, 3> FromPose(const transform::Rigid2d& pose) {
return {{pose.translation().x(), pose.translation().y(),
pose.normalized_angle()}};
}
// Converts a pose as represented for Ceres back to an transform::Rigid2d pose.
transform::Rigid2d ToPose(const std::array<double, 3>& values) {
return transform::Rigid2d({values[0], values[1]}, values[2]);
}
} // namespace
OptimizationProblem::OptimizationProblem(
const mapping::sparse_pose_graph::proto::OptimizationProblemOptions&
options)
: options_(options) {}
OptimizationProblem::~OptimizationProblem() {}
void OptimizationProblem::AddImuData(const int trajectory_id,
const common::Time time,
const Eigen::Vector3d& linear_acceleration,
const Eigen::Vector3d& angular_velocity) {
CHECK_GE(trajectory_id, 0);
imu_data_.resize(
std::max(imu_data_.size(), static_cast<size_t>(trajectory_id) + 1));
imu_data_[trajectory_id].push_back(
sensor::ImuData{time, linear_acceleration, angular_velocity});
}
void OptimizationProblem::AddTrajectoryNode(
const int trajectory_id, const common::Time time,
const transform::Rigid2d& initial_point_cloud_pose,
const transform::Rigid2d& point_cloud_pose) {
CHECK_GE(trajectory_id, 0);
node_data_.resize(
std::max(node_data_.size(), static_cast<size_t>(trajectory_id) + 1));
node_data_[trajectory_id].push_back(
NodeData{time, initial_point_cloud_pose, point_cloud_pose});
trajectory_data_.resize(std::max(trajectory_data_.size(), node_data_.size()));
}
void OptimizationProblem::TrimTrajectoryNode(const mapping::NodeId& node_id) {
auto& trajectory_data = trajectory_data_.at(node_id.trajectory_id);
// We only allow trimming from the start.
CHECK_EQ(trajectory_data.num_trimmed_nodes, node_id.node_index);
auto& node_data = node_data_.at(node_id.trajectory_id);
CHECK(!node_data.empty());
if (node_id.trajectory_id < static_cast<int>(imu_data_.size())) {
const common::Time node_time = node_data.front().time;
auto& imu_data = imu_data_.at(node_id.trajectory_id);
while (imu_data.size() > 1 && imu_data[1].time <= node_time) {
imu_data.pop_front();
}
}
node_data.pop_front();
++trajectory_data.num_trimmed_nodes;
}
void OptimizationProblem::AddSubmap(const int trajectory_id,
const transform::Rigid2d& submap_pose) {
CHECK_GE(trajectory_id, 0);
submap_data_.resize(
std::max(submap_data_.size(), static_cast<size_t>(trajectory_id) + 1));
submap_data_[trajectory_id].push_back(SubmapData{submap_pose});
trajectory_data_.resize(
std::max(trajectory_data_.size(), submap_data_.size()));
}
void OptimizationProblem::TrimSubmap(const mapping::SubmapId& submap_id) {
auto& trajectory_data = trajectory_data_.at(submap_id.trajectory_id);
// We only allow trimming from the start.
CHECK_EQ(trajectory_data.num_trimmed_submaps, submap_id.submap_index);
auto& submap_data = submap_data_.at(submap_id.trajectory_id);
CHECK(!submap_data.empty());
submap_data.pop_front();
++trajectory_data.num_trimmed_submaps;
}
void OptimizationProblem::SetMaxNumIterations(const int32 max_num_iterations) {
options_.mutable_ceres_solver_options()->set_max_num_iterations(
max_num_iterations);
}
void OptimizationProblem::Solve(const std::vector<Constraint>& constraints,
const std::set<int>& frozen_trajectories) {
if (node_data_.empty()) {
// Nothing to optimize.
return;
}
ceres::Problem::Options problem_options;
ceres::Problem problem(problem_options);
// Set the starting point.
// TODO(hrapp): Move ceres data into SubmapData.
std::vector<std::vector<std::array<double, 3>>> C_submaps(
submap_data_.size());
std::vector<std::vector<std::array<double, 3>>> C_nodes(node_data_.size());
bool first_submap = true;
for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();
++trajectory_id) {
const bool frozen = frozen_trajectories.count(trajectory_id);
// Reserve guarantees that data does not move, so the pointers for Ceres
// stay valid.
C_submaps[trajectory_id].reserve(submap_data_[trajectory_id].size());
for (const SubmapData& submap_data : submap_data_[trajectory_id]) {
C_submaps[trajectory_id].push_back(FromPose(submap_data.pose));
problem.AddParameterBlock(C_submaps[trajectory_id].back().data(), 3);
if (first_submap || frozen) {
first_submap = false;
// Fix the pose of the first submap or all submaps of a frozen
// trajectory.
problem.SetParameterBlockConstant(
C_submaps[trajectory_id].back().data());
}
}
}
for (size_t trajectory_id = 0; trajectory_id != node_data_.size();
++trajectory_id) {
// Reserve guarantees that data does not move, so the pointers for Ceres
// stay valid.
C_nodes[trajectory_id].reserve(node_data_[trajectory_id].size());
for (const NodeData& node_data : node_data_[trajectory_id]) {
C_nodes[trajectory_id].push_back(FromPose(node_data.point_cloud_pose));
problem.AddParameterBlock(C_nodes[trajectory_id].back().data(), 3);
}
}
// Add cost functions for intra- and inter-submap constraints.
for (const Constraint& constraint : constraints) {
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<SpaCostFunction, 3, 3, 3>(
new SpaCostFunction(constraint.pose)),
// Only loop closure constraints should have a loss function.
constraint.tag == Constraint::INTER_SUBMAP
? new ceres::HuberLoss(options_.huber_scale())
: nullptr,
C_submaps.at(constraint.submap_id.trajectory_id)
.at(constraint.submap_id.submap_index -
trajectory_data_.at(constraint.submap_id.trajectory_id)
.num_trimmed_submaps)
.data(),
C_nodes.at(constraint.node_id.trajectory_id)
.at(constraint.node_id.node_index -
trajectory_data_.at(constraint.node_id.trajectory_id)
.num_trimmed_nodes)
.data());
}
// Add penalties for changes between consecutive scans.
for (size_t trajectory_id = 0; trajectory_id != node_data_.size();
++trajectory_id) {
for (size_t node_data_index = 1;
node_data_index < node_data_[trajectory_id].size();
++node_data_index) {
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<SpaCostFunction, 3, 3, 3>(
new SpaCostFunction(Constraint::Pose{
transform::Embed3D(
node_data_[trajectory_id][node_data_index - 1]
.initial_point_cloud_pose.inverse() *
node_data_[trajectory_id][node_data_index]
.initial_point_cloud_pose),
options_.consecutive_scan_translation_penalty_factor(),
options_.consecutive_scan_rotation_penalty_factor()})),
nullptr /* loss function */,
C_nodes[trajectory_id][node_data_index - 1].data(),
C_nodes[trajectory_id][node_data_index].data());
}
}
// Solve.
ceres::Solver::Summary summary;
ceres::Solve(
common::CreateCeresSolverOptions(options_.ceres_solver_options()),
&problem, &summary);
if (options_.log_solver_summary()) {
LOG(INFO) << summary.FullReport();
}
// Store the result.
for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();
++trajectory_id) {
for (size_t submap_data_index = 0;
submap_data_index != submap_data_[trajectory_id].size();
++submap_data_index) {
submap_data_[trajectory_id][submap_data_index].pose =
ToPose(C_submaps[trajectory_id][submap_data_index]);
}
}
for (size_t trajectory_id = 0; trajectory_id != node_data_.size();
++trajectory_id) {
for (size_t node_data_index = 0;
node_data_index != node_data_[trajectory_id].size();
++node_data_index) {
node_data_[trajectory_id][node_data_index].point_cloud_pose =
ToPose(C_nodes[trajectory_id][node_data_index]);
}
}
}
const std::vector<std::deque<NodeData>>& OptimizationProblem::node_data()
const {
return node_data_;
}
const std::vector<std::deque<SubmapData>>& OptimizationProblem::submap_data()
const {
return submap_data_;
}
int OptimizationProblem::num_trimmed_nodes(int trajectory_id) const {
return trajectory_data_.at(trajectory_id).num_trimmed_nodes;
}
int OptimizationProblem::num_trimmed_submaps(int trajectory_id) const {
return trajectory_data_.at(trajectory_id).num_trimmed_submaps;
}
} // namespace sparse_pose_graph
} // namespace mapping_2d
} // namespace cartographer
<|endoftext|> |
<commit_before><commit_msg>Explain what the function does<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TemplateScanner.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:34:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "TemplateScanner.hxx"
#ifndef _COMPHELPER_SERVICEFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COMPHELPER_DOCUMENTCONSTANTS_HXX
#include <comphelper/documentconstants.hxx>
#endif
#include <tools/debug.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#ifndef _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_
#include <com/sun/star/ucb/XContentAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#include <set>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace {
const ::rtl::OUString TITLE = ::rtl::OUString::createFromAscii ("Title");
const ::rtl::OUString TARGET_DIR_URL = ::rtl::OUString::createFromAscii ("TargetDirURL");
const ::rtl::OUString DESCRIPTION = ::rtl::OUString::createFromAscii ("TypeDescription");
const ::rtl::OUString TARGET_URL = ::rtl::OUString::createFromAscii ("TargetURL");
const ::rtl::OUString DOCTEMPLATES = ::rtl::OUString::createFromAscii ("com.sun.star.frame.DocumentTemplates");
// These strings are used to find impress templates in the tree of
// template files. Should probably be determined dynamically.
const ::rtl::OUString IMPRESS_BIN_TEMPLATE = ::rtl::OUString::createFromAscii ("application/vnd.stardivision.impress");
const ::rtl::OUString IMPRESS_XML_TEMPLATE = MIMETYPE_VND_SUN_XML_IMPRESS;
// The following id comes from the bugdoc in #i2764#.
const ::rtl::OUString IMPRESS_XML_TEMPLATE_B = ::rtl::OUString::createFromAscii ("Impress 2.0");
const ::rtl::OUString IMPRESS_XML_TEMPLATE_OASIS = MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION;
class FolderDescriptor
{
public:
FolderDescriptor (
int nPriority,
const ::rtl::OUString& rsTitle,
const ::rtl::OUString& rsTargetDir,
const ::rtl::OUString& rsContentIdentifier,
const Reference<com::sun::star::ucb::XCommandEnvironment>& rxFolderEnvironment)
: mnPriority(nPriority),
msTitle(rsTitle),
msTargetDir(rsTargetDir),
msContentIdentifier(rsContentIdentifier),
mxFolderEnvironment(rxFolderEnvironment)
{ }
int mnPriority;
::rtl::OUString msTitle;
::rtl::OUString msTargetDir;
::rtl::OUString msContentIdentifier;
// Reference<sdbc::XResultSet> mxFolderResultSet;
Reference<com::sun::star::ucb::XCommandEnvironment> mxFolderEnvironment;
class Comparator { public:
bool operator() (const FolderDescriptor& r1, const FolderDescriptor& r2)
{ return r1.mnPriority < r2.mnPriority; }
};
};
/** Use a heuristic based on the URL of a top-level template folder to
assign a priority that is used to sort the folders.
*/
int Classify (const ::rtl::OUString& rsTitle, const ::rtl::OUString& rsURL)
{
int nPriority (0);
if (rsURL.getLength() == 0)
nPriority = 100;
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("presnt"))>=0)
{
nPriority = 30;
}
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("layout"))>=0)
{
nPriority = 20;
}
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("educate"))>=0)
{
nPriority = 40;
}
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("finance"))>=0)
{
nPriority = 40;
}
else
{
// All other folders are taken for user supplied and have the
// highest priority.
nPriority = 10;
}
return nPriority;
}
} // end of anonymous namespace
namespace sd
{
class TemplateScanner::FolderDescriptorList
: public ::std::multiset<FolderDescriptor,FolderDescriptor::Comparator>
{
};
TemplateScanner::TemplateScanner (void)
: meState(INITIALIZE_SCANNING),
maFolderContent(),
mpTemplateDirectory(NULL),
maFolderList(),
mpLastAddedEntry(NULL),
mxTemplateRoot(),
mxFolderEnvironment(),
mxEntryEnvironment(),
mxFolderResultSet(),
mxEntryResultSet(),
mpFolderDescriptors(new FolderDescriptorList())
{
// empty;
}
TemplateScanner::~TemplateScanner (void)
{
mpFolderDescriptors.reset();
// Delete all entries of the template list that have not been
// transferred to another object.
std::vector<TemplateDir*>::iterator I;
for (I=maFolderList.begin(); I!=maFolderList.end(); I++)
if (*I != NULL)
delete *I;
}
TemplateScanner::State TemplateScanner::GetTemplateRoot (void)
{
State eNextState (INITIALIZE_FOLDER_SCANNING);
Reference<lang::XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory ();
DBG_ASSERT (xFactory.is(), "TemplateScanner::GetTemplateRoot: xFactory is NULL");
if (xFactory.is())
{
Reference<frame::XDocumentTemplates> xTemplates (
xFactory->createInstance (DOCTEMPLATES), UNO_QUERY);
DBG_ASSERT (xTemplates.is(), "TemplateScanner::GetTemplateRoot: xTemplates is NULL");
if (xTemplates.is())
mxTemplateRoot = xTemplates->getContent();
else
eNextState = ERROR;
}
else
eNextState = ERROR;
return eNextState;
}
TemplateScanner::State TemplateScanner::InitializeEntryScanning (void)
{
State eNextState (SCAN_ENTRY);
if (maFolderContent.isFolder())
{
mxEntryEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();
// We are interested only in three properties: the entry's name,
// its URL, and its content type.
Sequence<rtl::OUString> aProps (3);
aProps[0] = TITLE;
aProps[1] = TARGET_URL;
aProps[2] = DESCRIPTION;
// Create a cursor to iterate over the templates in this folders.
::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_DOCUMENTS_ONLY;
mxEntryResultSet = Reference<com::sun::star::sdbc::XResultSet>(
maFolderContent.createCursor(aProps, eInclude));
}
else
eNextState = ERROR;
return eNextState;
}
TemplateScanner::State TemplateScanner::ScanEntry (void)
{
State eNextState (ERROR);
Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxEntryResultSet, UNO_QUERY);
Reference<com::sun::star::sdbc::XRow> xRow (mxEntryResultSet, UNO_QUERY);
if (xContentAccess.is() && xRow.is() && mxEntryResultSet.is())
{
if (mxEntryResultSet->next())
{
::rtl::OUString sTitle (xRow->getString (1));
::rtl::OUString sTargetURL (xRow->getString (2));
::rtl::OUString sContentType (xRow->getString (3));
::rtl::OUString aId = xContentAccess->queryContentIdentifierString();
::ucb::Content aContent = ::ucb::Content (aId, mxEntryEnvironment);
if (aContent.isDocument ())
{
// Check wether the entry is an impress template. If so
// add a new entry to the resulting list (which is created
// first if necessary).
if ( (sContentType == MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE)
|| (sContentType == IMPRESS_XML_TEMPLATE_OASIS)
|| (sContentType == IMPRESS_BIN_TEMPLATE)
|| (sContentType == IMPRESS_XML_TEMPLATE)
|| (sContentType == IMPRESS_XML_TEMPLATE_B))
{
mpLastAddedEntry = new TemplateEntry(sTitle, sTargetURL);
mpTemplateDirectory->maEntries.push_back(mpLastAddedEntry);
}
}
// Continue scanning entries.
eNextState = SCAN_ENTRY;
}
else
{
if (mpTemplateDirectory->maEntries.empty())
{
delete mpTemplateDirectory;
mpTemplateDirectory = NULL;
}
else
{
::vos::OGuard aGuard(Application::GetSolarMutex());
maFolderList.push_back(mpTemplateDirectory);
}
// Continue with scanning the next folder.
eNextState = SCAN_FOLDER;
}
}
return eNextState;
}
TemplateScanner::State TemplateScanner::InitializeFolderScanning (void)
{
State eNextState (ERROR);
mxFolderResultSet = Reference<sdbc::XResultSet>();
try
{
// Create content for template folders.
mxFolderEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();
::ucb::Content aTemplateDir (mxTemplateRoot, mxFolderEnvironment);
// Define the list of properties we are interested in.
Sequence<rtl::OUString> aProps (2);
aProps[0] = TITLE;
aProps[1] = TARGET_DIR_URL;
// Create an cursor to iterate over the template folders.
::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_FOLDERS_ONLY;
mxFolderResultSet = Reference<sdbc::XResultSet>(
aTemplateDir.createCursor(aProps, eInclude));
if (mxFolderResultSet.is())
eNextState = GATHER_FOLDER_LIST;
}
catch (::com::sun::star::uno::Exception&)
{
eNextState = ERROR;
}
return eNextState;
}
TemplateScanner::State TemplateScanner::GatherFolderList (void)
{
State eNextState (ERROR);
Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxFolderResultSet, UNO_QUERY);
if (xContentAccess.is() && mxFolderResultSet.is())
{
while (mxFolderResultSet->next())
{
Reference<sdbc::XRow> xRow (mxFolderResultSet, UNO_QUERY);
if (xRow.is())
{
::rtl::OUString sTitle (xRow->getString (1));
::rtl::OUString sTargetDir (xRow->getString (2));
::rtl::OUString aId = xContentAccess->queryContentIdentifierString();
mpFolderDescriptors->insert(
FolderDescriptor(
Classify(sTitle,sTargetDir),
sTitle,
sTargetDir,
aId,
mxFolderEnvironment));
}
}
eNextState = SCAN_FOLDER;
}
return eNextState;
}
TemplateScanner::State TemplateScanner::ScanFolder (void)
{
State eNextState (ERROR);
if (mpFolderDescriptors->size() > 0)
{
FolderDescriptor aDescriptor (*mpFolderDescriptors->begin());
mpFolderDescriptors->erase(mpFolderDescriptors->begin());
::rtl::OUString sTitle (aDescriptor.msTitle);
::rtl::OUString sTargetDir (aDescriptor.msTargetDir);
::rtl::OUString aId (aDescriptor.msContentIdentifier);
maFolderContent = ::ucb::Content (aId, aDescriptor.mxFolderEnvironment);
if (maFolderContent.isFolder())
{
// Scan the folder and insert it into the list of template
// folders.
mpTemplateDirectory = new TemplateDir (sTitle, sTargetDir);
if (mpTemplateDirectory != NULL)
{
// Continue with scanning all entries in the folder.
eNextState = INITIALIZE_ENTRY_SCAN;
}
}
}
else
{
eNextState = DONE;
}
return eNextState;
}
void TemplateScanner::Scan (void)
{
while (HasNextStep())
RunNextStep();
}
std::vector<TemplateDir*>& TemplateScanner::GetFolderList (void)
{
return maFolderList;
}
void TemplateScanner::RunNextStep (void)
{
switch (meState)
{
case INITIALIZE_SCANNING:
meState = GetTemplateRoot();
break;
case INITIALIZE_FOLDER_SCANNING:
meState = InitializeFolderScanning();
break;
case SCAN_FOLDER:
meState = ScanFolder();
break;
case GATHER_FOLDER_LIST:
meState = GatherFolderList();
break;
case INITIALIZE_ENTRY_SCAN:
meState = InitializeEntryScanning();
break;
case SCAN_ENTRY:
meState = ScanEntry();
break;
}
switch (meState)
{
case DONE:
case ERROR:
mxTemplateRoot.clear();
mxTemplateRoot.clear();
mxFolderEnvironment.clear();
mxEntryEnvironment.clear();
mxFolderResultSet.clear();
mxEntryResultSet.clear();
mpLastAddedEntry = NULL;
break;
}
}
bool TemplateScanner::HasNextStep (void)
{
switch (meState)
{
case DONE:
case ERROR:
return false;
default:
return true;
}
}
const TemplateEntry* TemplateScanner::GetLastAddedEntry (void) const
{
return mpLastAddedEntry;
}
}
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.10.38); FILE MERGED 2006/11/22 12:41:44 cl 1.10.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TemplateScanner.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: kz $ $Date: 2006-12-12 16:57:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "TemplateScanner.hxx"
#ifndef _COMPHELPER_SERVICEFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COMPHELPER_DOCUMENTCONSTANTS_HXX
#include <comphelper/documentconstants.hxx>
#endif
#include <tools/debug.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#ifndef _COM_SUN_STAR_FRAME_XDOCUMENTTEMPLATES_HPP_
#include <com/sun/star/frame/XDocumentTemplates.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_
#include <com/sun/star/ucb/XContentAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#include <set>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace {
const ::rtl::OUString TITLE = ::rtl::OUString::createFromAscii ("Title");
const ::rtl::OUString TARGET_DIR_URL = ::rtl::OUString::createFromAscii ("TargetDirURL");
const ::rtl::OUString DESCRIPTION = ::rtl::OUString::createFromAscii ("TypeDescription");
const ::rtl::OUString TARGET_URL = ::rtl::OUString::createFromAscii ("TargetURL");
const ::rtl::OUString DOCTEMPLATES = ::rtl::OUString::createFromAscii ("com.sun.star.frame.DocumentTemplates");
// These strings are used to find impress templates in the tree of
// template files. Should probably be determined dynamically.
const ::rtl::OUString IMPRESS_BIN_TEMPLATE = ::rtl::OUString::createFromAscii ("application/vnd.stardivision.impress");
const ::rtl::OUString IMPRESS_XML_TEMPLATE = MIMETYPE_VND_SUN_XML_IMPRESS;
// The following id comes from the bugdoc in #i2764#.
const ::rtl::OUString IMPRESS_XML_TEMPLATE_B = ::rtl::OUString::createFromAscii ("Impress 2.0");
const ::rtl::OUString IMPRESS_XML_TEMPLATE_OASIS = MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION;
class FolderDescriptor
{
public:
FolderDescriptor (
int nPriority,
const ::rtl::OUString& rsTitle,
const ::rtl::OUString& rsTargetDir,
const ::rtl::OUString& rsContentIdentifier,
const Reference<com::sun::star::ucb::XCommandEnvironment>& rxFolderEnvironment)
: mnPriority(nPriority),
msTitle(rsTitle),
msTargetDir(rsTargetDir),
msContentIdentifier(rsContentIdentifier),
mxFolderEnvironment(rxFolderEnvironment)
{ }
int mnPriority;
::rtl::OUString msTitle;
::rtl::OUString msTargetDir;
::rtl::OUString msContentIdentifier;
// Reference<sdbc::XResultSet> mxFolderResultSet;
Reference<com::sun::star::ucb::XCommandEnvironment> mxFolderEnvironment;
class Comparator { public:
bool operator() (const FolderDescriptor& r1, const FolderDescriptor& r2)
{ return r1.mnPriority < r2.mnPriority; }
};
};
/** Use a heuristic based on the URL of a top-level template folder to
assign a priority that is used to sort the folders.
*/
int Classify (const ::rtl::OUString&, const ::rtl::OUString& rsURL)
{
int nPriority (0);
if (rsURL.getLength() == 0)
nPriority = 100;
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("presnt"))>=0)
{
nPriority = 30;
}
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("layout"))>=0)
{
nPriority = 20;
}
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("educate"))>=0)
{
nPriority = 40;
}
else if (rsURL.indexOf(::rtl::OUString::createFromAscii("finance"))>=0)
{
nPriority = 40;
}
else
{
// All other folders are taken for user supplied and have the
// highest priority.
nPriority = 10;
}
return nPriority;
}
} // end of anonymous namespace
namespace sd
{
class TemplateScanner::FolderDescriptorList
: public ::std::multiset<FolderDescriptor,FolderDescriptor::Comparator>
{
};
TemplateScanner::TemplateScanner (void)
: meState(INITIALIZE_SCANNING),
maFolderContent(),
mpTemplateDirectory(NULL),
maFolderList(),
mpLastAddedEntry(NULL),
mpFolderDescriptors(new FolderDescriptorList()),
mxTemplateRoot(),
mxFolderEnvironment(),
mxEntryEnvironment(),
mxFolderResultSet(),
mxEntryResultSet()
{
// empty;
}
TemplateScanner::~TemplateScanner (void)
{
mpFolderDescriptors.reset();
// Delete all entries of the template list that have not been
// transferred to another object.
std::vector<TemplateDir*>::iterator I;
for (I=maFolderList.begin(); I!=maFolderList.end(); I++)
if (*I != NULL)
delete *I;
}
TemplateScanner::State TemplateScanner::GetTemplateRoot (void)
{
State eNextState (INITIALIZE_FOLDER_SCANNING);
Reference<lang::XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory ();
DBG_ASSERT (xFactory.is(), "TemplateScanner::GetTemplateRoot: xFactory is NULL");
if (xFactory.is())
{
Reference<frame::XDocumentTemplates> xTemplates (
xFactory->createInstance (DOCTEMPLATES), UNO_QUERY);
DBG_ASSERT (xTemplates.is(), "TemplateScanner::GetTemplateRoot: xTemplates is NULL");
if (xTemplates.is())
mxTemplateRoot = xTemplates->getContent();
else
eNextState = ERROR;
}
else
eNextState = ERROR;
return eNextState;
}
TemplateScanner::State TemplateScanner::InitializeEntryScanning (void)
{
State eNextState (SCAN_ENTRY);
if (maFolderContent.isFolder())
{
mxEntryEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();
// We are interested only in three properties: the entry's name,
// its URL, and its content type.
Sequence<rtl::OUString> aProps (3);
aProps[0] = TITLE;
aProps[1] = TARGET_URL;
aProps[2] = DESCRIPTION;
// Create a cursor to iterate over the templates in this folders.
::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_DOCUMENTS_ONLY;
mxEntryResultSet = Reference<com::sun::star::sdbc::XResultSet>(
maFolderContent.createCursor(aProps, eInclude));
}
else
eNextState = ERROR;
return eNextState;
}
TemplateScanner::State TemplateScanner::ScanEntry (void)
{
State eNextState (ERROR);
Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxEntryResultSet, UNO_QUERY);
Reference<com::sun::star::sdbc::XRow> xRow (mxEntryResultSet, UNO_QUERY);
if (xContentAccess.is() && xRow.is() && mxEntryResultSet.is())
{
if (mxEntryResultSet->next())
{
::rtl::OUString sTitle (xRow->getString (1));
::rtl::OUString sTargetURL (xRow->getString (2));
::rtl::OUString sContentType (xRow->getString (3));
::rtl::OUString aId = xContentAccess->queryContentIdentifierString();
::ucb::Content aContent = ::ucb::Content (aId, mxEntryEnvironment);
if (aContent.isDocument ())
{
// Check wether the entry is an impress template. If so
// add a new entry to the resulting list (which is created
// first if necessary).
if ( (sContentType == MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE)
|| (sContentType == IMPRESS_XML_TEMPLATE_OASIS)
|| (sContentType == IMPRESS_BIN_TEMPLATE)
|| (sContentType == IMPRESS_XML_TEMPLATE)
|| (sContentType == IMPRESS_XML_TEMPLATE_B))
{
mpLastAddedEntry = new TemplateEntry(sTitle, sTargetURL);
mpTemplateDirectory->maEntries.push_back(mpLastAddedEntry);
}
}
// Continue scanning entries.
eNextState = SCAN_ENTRY;
}
else
{
if (mpTemplateDirectory->maEntries.empty())
{
delete mpTemplateDirectory;
mpTemplateDirectory = NULL;
}
else
{
::vos::OGuard aGuard(Application::GetSolarMutex());
maFolderList.push_back(mpTemplateDirectory);
}
// Continue with scanning the next folder.
eNextState = SCAN_FOLDER;
}
}
return eNextState;
}
TemplateScanner::State TemplateScanner::InitializeFolderScanning (void)
{
State eNextState (ERROR);
mxFolderResultSet = Reference<sdbc::XResultSet>();
try
{
// Create content for template folders.
mxFolderEnvironment = Reference<com::sun::star::ucb::XCommandEnvironment>();
::ucb::Content aTemplateDir (mxTemplateRoot, mxFolderEnvironment);
// Define the list of properties we are interested in.
Sequence<rtl::OUString> aProps (2);
aProps[0] = TITLE;
aProps[1] = TARGET_DIR_URL;
// Create an cursor to iterate over the template folders.
::ucb::ResultSetInclude eInclude = ::ucb::INCLUDE_FOLDERS_ONLY;
mxFolderResultSet = Reference<sdbc::XResultSet>(
aTemplateDir.createCursor(aProps, eInclude));
if (mxFolderResultSet.is())
eNextState = GATHER_FOLDER_LIST;
}
catch (::com::sun::star::uno::Exception&)
{
eNextState = ERROR;
}
return eNextState;
}
TemplateScanner::State TemplateScanner::GatherFolderList (void)
{
State eNextState (ERROR);
Reference<com::sun::star::ucb::XContentAccess> xContentAccess (mxFolderResultSet, UNO_QUERY);
if (xContentAccess.is() && mxFolderResultSet.is())
{
while (mxFolderResultSet->next())
{
Reference<sdbc::XRow> xRow (mxFolderResultSet, UNO_QUERY);
if (xRow.is())
{
::rtl::OUString sTitle (xRow->getString (1));
::rtl::OUString sTargetDir (xRow->getString (2));
::rtl::OUString aId = xContentAccess->queryContentIdentifierString();
mpFolderDescriptors->insert(
FolderDescriptor(
Classify(sTitle,sTargetDir),
sTitle,
sTargetDir,
aId,
mxFolderEnvironment));
}
}
eNextState = SCAN_FOLDER;
}
return eNextState;
}
TemplateScanner::State TemplateScanner::ScanFolder (void)
{
State eNextState (ERROR);
if (mpFolderDescriptors->size() > 0)
{
FolderDescriptor aDescriptor (*mpFolderDescriptors->begin());
mpFolderDescriptors->erase(mpFolderDescriptors->begin());
::rtl::OUString sTitle (aDescriptor.msTitle);
::rtl::OUString sTargetDir (aDescriptor.msTargetDir);
::rtl::OUString aId (aDescriptor.msContentIdentifier);
maFolderContent = ::ucb::Content (aId, aDescriptor.mxFolderEnvironment);
if (maFolderContent.isFolder())
{
// Scan the folder and insert it into the list of template
// folders.
mpTemplateDirectory = new TemplateDir (sTitle, sTargetDir);
if (mpTemplateDirectory != NULL)
{
// Continue with scanning all entries in the folder.
eNextState = INITIALIZE_ENTRY_SCAN;
}
}
}
else
{
eNextState = DONE;
}
return eNextState;
}
void TemplateScanner::Scan (void)
{
while (HasNextStep())
RunNextStep();
}
std::vector<TemplateDir*>& TemplateScanner::GetFolderList (void)
{
return maFolderList;
}
void TemplateScanner::RunNextStep (void)
{
switch (meState)
{
case INITIALIZE_SCANNING:
meState = GetTemplateRoot();
break;
case INITIALIZE_FOLDER_SCANNING:
meState = InitializeFolderScanning();
break;
case SCAN_FOLDER:
meState = ScanFolder();
break;
case GATHER_FOLDER_LIST:
meState = GatherFolderList();
break;
case INITIALIZE_ENTRY_SCAN:
meState = InitializeEntryScanning();
break;
case SCAN_ENTRY:
meState = ScanEntry();
break;
default:
break;
}
switch (meState)
{
case DONE:
case ERROR:
mxTemplateRoot.clear();
mxTemplateRoot.clear();
mxFolderEnvironment.clear();
mxEntryEnvironment.clear();
mxFolderResultSet.clear();
mxEntryResultSet.clear();
mpLastAddedEntry = NULL;
break;
default:
break;
}
}
bool TemplateScanner::HasNextStep (void)
{
switch (meState)
{
case DONE:
case ERROR:
return false;
default:
return true;
}
}
const TemplateEntry* TemplateScanner::GetLastAddedEntry (void) const
{
return mpLastAddedEntry;
}
}
<|endoftext|> |
<commit_before>#include "disassembler.h"
#include "util.h"
using namespace std;
struct program {
char name[7];
//TODO
program() {
for ( int i = 0 ; i < 7 ; i++ ) {
name[i] = 0;
}
//TODO
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
write_assembly(p, ofile);
status("Done writing output file");
}
bool read_record(ifstream &ifile, string &record) {
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
for ( int col = 2 ; col <= 19 ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of Header Record");
}
record += t;
}
break;
case 'T': // Text
//TODO
break;
case 'E': // End
for ( int col = 2 ; col <= 7 ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of End Record");
}
record += t;
}
break;
default:
fatal("Unknown record type " + t);
}
return true;
}
void record_to_memory(const string record, program &p) {
// TODO
}
void write_assembly(const program &p, ofstream &ofile) {
// TODO
}<commit_msg>Prevent code duplication<commit_after>#include "disassembler.h"
#include "util.h"
using namespace std;
struct program {
char name[7];
//TODO
program() {
for ( int i = 0 ; i < 7 ; i++ ) {
name[i] = 0;
}
//TODO
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
write_assembly(p, ofile);
status("Done writing output file");
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of " + record_type + string(" record"));
} else if ( !is_hex_digit(t) ) {
fatal("Unexpected character " + t + string(" in ") + record_type + string(" record"));
}
ret += t;
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_hex_columns(ifile,2,19,'H');
break;
case 'T': // Text
//TODO
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
fatal("Unknown record type " + t);
}
return true;
}
void record_to_memory(const string record, program &p) {
// TODO
}
void write_assembly(const program &p, ofstream &ofile) {
// TODO
}<|endoftext|> |
<commit_before>/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2017 Victor DENIS (victordenis01@gmail.com) **
** **
** 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 "PasswordManager.hpp"
#include <QSettings>
#include <QCryptographicHash>
#include <QUrl>
#include "Password/PasswordBackend.hpp"
#include "Password/DatabasePasswordBackend.hpp"
#include "Password/DatabaseEncryptedPasswordBackend.hpp"
namespace Sn {
static const int passwordEntryVersion = 1;
QString PasswordManager::createHost(const QUrl& url)
{
QString host{url.host()};
if (host.isEmpty())
host = url.toString();
if (url.port() != -1) {
host.append(QLatin1Char(':'));
host.append(QString::number(url.port()));
}
return host;
}
QByteArray PasswordManager::urlEncodePassword(const QString& password)
{
QByteArray encodedPass = QUrl::toPercentEncoding(password, " ");
encodedPass.replace(' ', '+');
encodedPass.replace('~', "%7E");
return encodedPass;
}
QByteArray PasswordManager::passwordToHash(const QString& masterPassword)
{
if (!masterPassword.isEmpty()) {
QByteArray result{masterPassword.toUtf8()};
result = QCryptographicHash::hash(result, QCryptographicHash::Sha1) + result;
result = QCryptographicHash::hash(result, QCryptographicHash::Sha1);
return result.toBase64();
}
else
return QByteArray();
}
QDataStream& operator<<(QDataStream& stream, const PasswordEntry& entry)
{
stream << passwordEntryVersion;
stream << entry.host;
stream << entry.id;
stream << entry.username;
stream << entry.password;
stream << entry.data;
stream << entry.updated;
return stream;
}
QDataStream& operator>>(QDataStream& stream, PasswordEntry& entry)
{
int version;
stream >> version;
if (version != passwordEntryVersion)
return stream;
stream >> entry.host;
stream >> entry.id;
stream >> entry.username;
stream >> entry.password;
stream >> entry.data;
stream >> entry.updated;
return stream;
}
PasswordManager::PasswordManager(QObject* parent) :
QObject(parent),
m_loaded(false),
m_databaseBackend(new DatabasePasswordBackend),
m_databaseEncryptedBackend(new DatabaseEncryptedPasswordBackend)
{
m_backends["database"] = m_databaseBackend;
m_backends["database-encrypted"] = m_databaseEncryptedBackend;
}
PasswordManager::~PasswordManager()
{
delete m_databaseBackend;
delete m_databaseEncryptedBackend;
}
void PasswordManager::loadSettings()
{
QSettings settings{};
QString backendId{settings.value("PasswordManager/backend", "database").toString()};
m_backend = m_backends[m_backends.contains(backendId) ? backendId : "database"];
m_backend->setActive(true);
}
QVector<PasswordEntry> PasswordManager::getEntries(const QUrl& url)
{
ensureLoaded();
return m_backend->getEntries(url);
}
QVector<PasswordEntry> PasswordManager::getAllEntries()
{
ensureLoaded();
return m_backend->getAllEntries();
}
void PasswordManager::addEntry(const PasswordEntry& entry)
{
ensureLoaded();
m_backend->addEntry(entry);
}
bool PasswordManager::updateEntry(const PasswordEntry& entry)
{
ensureLoaded();
m_backend->updateEntry(entry);
}
void PasswordManager::updateLastUsed(PasswordEntry& entry)
{
ensureLoaded();
m_backend->updateLastUsed(entry);
}
void PasswordManager::removeEntry(const PasswordEntry& entry)
{
ensureLoaded();
m_backend->removeEntry(entry);
}
void PasswordManager::removeAllEntries()
{
ensureLoaded();
m_backend->removeAll();
}
QHash<QString, PasswordBackend*> PasswordManager::availableBackends()
{
ensureLoaded();
return m_backends;
}
PasswordBackend* PasswordManager::activeBackend()
{
ensureLoaded();
return m_backend;
}
void PasswordManager::switchBackend(const QString& backendID)
{
PasswordBackend* backend = m_backends.value(backendID);
if (!backend)
return;
m_backend->setActive(false);
m_backend = backend;
m_backend->setActive(true);
QSettings settings{};
settings.setValue("PasswordManager/backend", backendID);
emit passwordBackendChanged();
}
bool PasswordManager::registerBackend(const QString& id, PasswordBackend* backend)
{
if (m_backends.contains(id))
return false;
m_backends[id] = backend;
return true;
}
void PasswordManager::unregisterBackend(PasswordBackend* backend)
{
const QString key{m_backends.key(backend)};
m_backends.remove(key);
if (m_backend == backend)
m_backend = m_databaseBackend;
}
void PasswordManager::ensureLoaded()
{
if (!m_loaded) {
loadSettings();
m_loaded = true;
}
}
}
<commit_msg>[Fix] PasswordManager errors<commit_after>/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2017 Victor DENIS (victordenis01@gmail.com) **
** **
** 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 "PasswordManager.hpp"
#include <QSettings>
#include <QCryptographicHash>
#include <QUrl>
#include "Password/PasswordBackend.hpp"
#include "Password/DatabasePasswordBackend.hpp"
#include "Password/DatabaseEncryptedPasswordBackend.hpp"
namespace Sn {
static const int passwordEntryVersion = 1;
QString PasswordManager::createHost(const QUrl& url)
{
QString host{url.host()};
if (host.isEmpty())
host = url.toString();
if (url.port() != -1) {
host.append(QLatin1Char(':'));
host.append(QString::number(url.port()));
}
return host;
}
QByteArray PasswordManager::urlEncodePassword(const QString& password)
{
QByteArray encodedPass = QUrl::toPercentEncoding(password, " ");
encodedPass.replace(' ', '+');
encodedPass.replace('~', "%7E");
return encodedPass;
}
QByteArray PasswordManager::passwordToHash(const QString& masterPassword)
{
if (!masterPassword.isEmpty()) {
QByteArray result{masterPassword.toUtf8()};
result = QCryptographicHash::hash(result, QCryptographicHash::Sha1) + result;
result = QCryptographicHash::hash(result, QCryptographicHash::Sha1);
return result.toBase64();
}
else
return QByteArray();
}
QDataStream& operator<<(QDataStream& stream, const PasswordEntry& entry)
{
stream << passwordEntryVersion;
stream << entry.host;
stream << entry.id;
stream << entry.username;
stream << entry.password;
stream << entry.data;
stream << entry.updated;
return stream;
}
QDataStream& operator>>(QDataStream& stream, PasswordEntry& entry)
{
int version;
stream >> version;
if (version != passwordEntryVersion)
return stream;
stream >> entry.host;
stream >> entry.id;
stream >> entry.username;
stream >> entry.password;
stream >> entry.data;
stream >> entry.updated;
return stream;
}
PasswordManager::PasswordManager(QObject* parent) :
QObject(parent),
m_loaded(false),
m_databaseBackend(new DatabasePasswordBackend),
m_databaseEncryptedBackend(new DatabaseEncryptedPasswordBackend)
{
m_backends["database"] = m_databaseBackend;
m_backends["database-encrypted"] = m_databaseEncryptedBackend;
}
PasswordManager::~PasswordManager()
{
delete m_databaseBackend;
delete m_databaseEncryptedBackend;
}
void PasswordManager::loadSettings()
{
QSettings settings{};
QString backendId{settings.value("PasswordManager/backend", "database").toString()};
m_backend = m_backends[m_backends.contains(backendId) ? backendId : "database"];
m_backend->setActive(true);
}
QVector<PasswordEntry> PasswordManager::getEntries(const QUrl& url)
{
ensureLoaded();
return m_backend->getEntries(url);
}
QVector<PasswordEntry> PasswordManager::getAllEntries()
{
ensureLoaded();
return m_backend->getAllEntries();
}
void PasswordManager::addEntry(const PasswordEntry& entry)
{
ensureLoaded();
m_backend->addEntry(entry);
}
bool PasswordManager::updateEntry(const PasswordEntry& entry)
{
ensureLoaded();
return m_backend->updateEntry(entry);
}
void PasswordManager::updateLastUsed(PasswordEntry& entry)
{
ensureLoaded();
m_backend->updateLastUsed(entry);
}
void PasswordManager::removeEntry(const PasswordEntry& entry)
{
ensureLoaded();
m_backend->removeEntry(entry);
}
void PasswordManager::removeAllEntries()
{
ensureLoaded();
m_backend->removeAll();
}
QHash<QString, PasswordBackend*> PasswordManager::availableBackends()
{
ensureLoaded();
return m_backends;
}
PasswordBackend* PasswordManager::activeBackend()
{
ensureLoaded();
return m_backend;
}
void PasswordManager::switchBackend(const QString& backendID)
{
PasswordBackend* backend = m_backends.value(backendID);
if (!backend)
return;
m_backend->setActive(false);
m_backend = backend;
m_backend->setActive(true);
QSettings settings{};
settings.setValue("PasswordManager/backend", backendID);
emit passwordBackendChanged();
}
bool PasswordManager::registerBackend(const QString& id, PasswordBackend* backend)
{
if (m_backends.contains(id))
return false;
m_backends[id] = backend;
return true;
}
void PasswordManager::unregisterBackend(PasswordBackend* backend)
{
const QString key{m_backends.key(backend)};
m_backends.remove(key);
if (m_backend == backend)
m_backend = m_databaseBackend;
}
void PasswordManager::ensureLoaded()
{
if (!m_loaded) {
loadSettings();
m_loaded = true;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: expop2.cxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: kz $ $Date: 2005-01-14 12:01:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------------
#include <svtools/fltrcfg.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docinf.hxx>
#include <svx/svxmsbas.hxx>
#include "scerrors.hxx"
#include "scextopt.hxx"
#include "root.hxx"
#include "exp_op.hxx"
#include "excdoc.hxx"
#include "xcl97esc.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "filtopt.hxx"
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XELINK_HXX
#include "xelink.hxx"
#endif
ExportBiff5::ExportBiff5( XclExpRootData& rExpData ):
ExportTyp( rExpData.mrBookStrm, &rExpData.mrDoc, rExpData.meCharSet ),
XclExpRoot( rExpData )
{
// nur Teil der Root-Daten gebraucht
pExcRoot = mpRD;
pExcRoot->pDoc = GetDocPtr();
pExcRoot->pER = this; // ExcRoot -> XclExpRoot
pExcRoot->bCellCut = FALSE;
pExcRoot->eHauptDateiTyp = Biff5;
pExcRoot->eDateiTyp = Biff5;
pExcRoot->pCharset = &eZielChar;
// options from configuration
ScFilterOptions aFilterOpt;
pExcRoot->fRowScale = aFilterOpt.GetExcelRowScale();
if( pExcRoot->fRowScale <= 0.0 )
pExcRoot->fRowScale = 1.0;
pExcDoc = new ExcDocument( *this );
}
ExportBiff5::~ExportBiff5()
{
delete pExcDoc;
}
FltError ExportBiff5::Write()
{
FltError eRet = eERR_OK;
SvtFilterOptions* pFiltOpt = NULL;
if( pExcRoot->eHauptDateiTyp >= Biff8 )
{
pFiltOpt = SvtFilterOptions::Get();
pExcRoot->bWriteVBAStorage = pFiltOpt && pFiltOpt->IsLoadExcelBasicStorage();
}
SfxObjectShell& rDocShell = *pExcRoot->pDoc->GetDocumentShell();
if( pExcRoot->bWriteVBAStorage )
{
SfxObjectShell& rDocShell = *pExcRoot->pDoc->GetDocumentShell();
DBG_ASSERT( GetRootStorage(), "ExportBiff5::Write - no storage" );
SvxImportMSVBasic aBasicImport( rDocShell,
*GetRootStorage(),
pFiltOpt->IsLoadExcelBasicCode(),
pFiltOpt->IsLoadExcelBasicStorage() );
ULONG nErr = aBasicImport.SaveOrDelMSVBAStorage( TRUE, EXC_STORAGE_VBA_PROJECT );
if( nErr != ERRCODE_NONE )
rDocShell.SetError( nErr );
}
// VBA-storage written?
pExcRoot->bWriteVBAStorage = GetRootStorage()->IsContained( EXC_STORAGE_VBA_PROJECT );
pExcDoc->ReadDoc(); // ScDoc -> ExcDoc
pExcDoc->Write( aOut ); // wechstreamen
SfxDocumentInfo& rInfo = rDocShell.GetDocInfo();
rInfo.SavePropertySet( GetRootStorage() );
//! TODO: separate warnings for columns and sheets
if( pExcRoot->bCellCut || IsColTruncated() || IsRowTruncated() || IsTabTruncated() )
return SCWARN_EXPORT_MAXROW;
return eERR_OK;
}
ExportBiff8::ExportBiff8( XclExpRootData& rExpData ) :
ExportBiff5( rExpData )
{
pExcRoot->eHauptDateiTyp = Biff8;
pExcRoot->eDateiTyp = Biff8;
pExcRoot->pEscher = new XclEscher( GetDoc().GetTableCount(), *pExcRoot );
}
ExportBiff8::~ExportBiff8()
{
delete pExcRoot->pEscher;
pExcRoot->pEscher = NULL;
}
<commit_msg>INTEGRATION: CWS dr32 (1.22.70); FILE MERGED 2005/02/02 14:14:50 dr 1.22.70.8: #b6219324# #i23079# #i27871# #i35812# #i37725# new address converter, import/export of view settings 2005/01/31 14:00:42 dr 1.22.70.7: #b6219324# #i23079# #i27871# #i35812# #i37725# new ScExtDocOptions, new Excel import/export of view settings 2005/01/20 14:24:27 dr 1.22.70.6: #i40570# removed RootData::bWriteVBAStorage 2005/01/20 13:38:36 dr 1.22.70.5: #i40570# removed more RootData stuff 2005/01/19 15:00:02 dr 1.22.70.4: #i40570# removed/changed constants and enums 2005/01/18 12:01:36 dr 1.22.70.3: RESYNC: (1.22-1.23); FILE MERGED 2005/01/17 16:44:37 dr 1.22.70.2: #i40570# removed RootData::pCharset and RootData::bCellCut 2005/01/14 13:32:09 dr 1.22.70.1: #i40570# remove RootData::eHauptDateiTyp, xlBiff7<commit_after>/*************************************************************************
*
* $RCSfile: expop2.cxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: vg $ $Date: 2005-02-21 13:25:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------------
#include <svtools/fltrcfg.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docinf.hxx>
#include <svx/svxmsbas.hxx>
#include "scerrors.hxx"
#include "scextopt.hxx"
#include "root.hxx"
#include "exp_op.hxx"
#include "excdoc.hxx"
#include "xcl97esc.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "filtopt.hxx"
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XELINK_HXX
#include "xelink.hxx"
#endif
ExportBiff5::ExportBiff5( XclExpRootData& rExpData ):
ExportTyp( rExpData.mrBookStrm, &rExpData.mrDoc, rExpData.meCharSet ),
XclExpRoot( rExpData )
{
// nur Teil der Root-Daten gebraucht
pExcRoot = &GetOldRoot();
pExcRoot->pER = this; // ExcRoot -> XclExpRoot
pExcRoot->eDateiTyp = Biff5;
pExcDoc = new ExcDocument( *this );
}
ExportBiff5::~ExportBiff5()
{
delete pExcDoc;
}
FltError ExportBiff5::Write()
{
FltError eRet = eERR_OK;
SfxObjectShell* pDocShell = GetDocShell();
DBG_ASSERT( pDocShell, "ExportBiff5::Write - no document shell" );
SotStorageRef xRootStrg = GetRootStorage();
DBG_ASSERT( xRootStrg.Is(), "ExportBiff5::Write - no root storage" );
bool bWriteBasicCode = false;
bool bWriteBasicStrg = false;
if( GetBiff() == EXC_BIFF8 )
{
if( SvtFilterOptions* pFilterOpt = SvtFilterOptions::Get() )
{
bWriteBasicCode = pFilterOpt->IsLoadExcelBasicCode();
bWriteBasicStrg = pFilterOpt->IsLoadExcelBasicStorage();
}
}
if( pDocShell && xRootStrg.Is() && bWriteBasicStrg )
{
SvxImportMSVBasic aBasicImport( *pDocShell, *xRootStrg, bWriteBasicCode, bWriteBasicStrg );
ULONG nErr = aBasicImport.SaveOrDelMSVBAStorage( TRUE, EXC_STORAGE_VBA_PROJECT );
if( nErr != ERRCODE_NONE )
pDocShell->SetError( nErr );
}
pExcDoc->ReadDoc(); // ScDoc -> ExcDoc
pExcDoc->Write( aOut ); // wechstreamen
if( pDocShell && xRootStrg.Is() )
{
SfxDocumentInfo& rInfo = pDocShell->GetDocInfo();
rInfo.SavePropertySet( xRootStrg );
}
//! TODO: separate warnings for columns and sheets
const XclExpAddressConverter& rAddrConv = GetAddressConverter();
if( rAddrConv.IsColTruncated() || rAddrConv.IsRowTruncated() || rAddrConv.IsTabTruncated() )
return SCWARN_EXPORT_MAXROW;
return eERR_OK;
}
ExportBiff8::ExportBiff8( XclExpRootData& rExpData ) :
ExportBiff5( rExpData )
{
pExcRoot->eDateiTyp = Biff8;
pExcRoot->pEscher = new XclEscher( GetDoc().GetTableCount(), *pExcRoot );
}
ExportBiff8::~ExportBiff8()
{
delete pExcRoot->pEscher;
pExcRoot->pEscher = NULL;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: cclass_unicode.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-24 11:06:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <cclass_unicode.hxx>
#include <com/sun/star/i18n/UnicodeScript.hpp>
#include <com/sun/star/i18n/UnicodeType.hpp>
#include <i18nutil/unicode.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
// ----------------------------------------------------
// class cclass_Unicode
// ----------------------------------------------------;
cclass_Unicode::cclass_Unicode( uno::Reference < XMultiServiceFactory > xSMgr ) : xMSF( xSMgr ),
pTable( NULL ),
pStart( NULL ),
pCont( NULL ),
nStartTypes( 0 ),
nContTypes( 0 ),
eState( ssGetChar ),
cGroupSep( ',' ),
cDecimalSep( '.' )
{
trans = new Transliteration_casemapping();
cClass = "com.sun.star.i18n.CharacterClassification_Unicode";
}
cclass_Unicode::~cclass_Unicode() {
destroyParserTable();
delete trans;
}
OUString SAL_CALL
cclass_Unicode::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
trans->setMappingType(MappingTypeToUpper, rLocale);
return trans->transliterateString2String(Text, nPos, nCount);
}
OUString SAL_CALL
cclass_Unicode::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
trans->setMappingType(MappingTypeToLower, rLocale);
return trans->transliterateString2String(Text, nPos, nCount);
}
OUString SAL_CALL
cclass_Unicode::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
trans->setMappingType(MappingTypeToTitle, rLocale);
return trans->transliterateString2String(Text, nPos, nCount);
}
sal_Int16 SAL_CALL
cclass_Unicode::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getUnicodeType(Text[nPos]);
}
sal_Int16 SAL_CALL
cclass_Unicode::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getUnicodeDirection(Text[nPos]);
}
sal_Int16 SAL_CALL
cclass_Unicode::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getUnicodeScriptType(Text[nPos], (ScriptTypeList*) 0, 0);
}
sal_Int32 SAL_CALL
cclass_Unicode::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getCharType(Text[nPos]);
}
sal_Int32 SAL_CALL
cclass_Unicode::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
if ( Text.getLength() < nPos + nCount )
nCount = Text.getLength() - nPos;
sal_Int32 result = 0;
for (int i = 0; i < nCount; i++)
result |= unicode::getCharType(Text[nPos+i]);
return result;
}
ParseResult SAL_CALL cclass_Unicode::parseAnyToken(
const OUString& Text,
sal_Int32 nPos,
const Locale& rLocale,
sal_Int32 startCharTokenType,
const OUString& userDefinedCharactersStart,
sal_Int32 contCharTokenType,
const OUString& userDefinedCharactersCont )
throw(RuntimeException)
{
ParseResult r;
if ( Text.getLength() <= nPos )
return r;
setupParserTable( rLocale,
startCharTokenType, userDefinedCharactersStart,
contCharTokenType, userDefinedCharactersCont );
parseText( r, Text, nPos );
return r;
}
ParseResult SAL_CALL cclass_Unicode::parsePredefinedToken(
sal_Int32 nTokenType,
const OUString& Text,
sal_Int32 nPos,
const Locale& rLocale,
sal_Int32 startCharTokenType,
const OUString& userDefinedCharactersStart,
sal_Int32 contCharTokenType,
const OUString& userDefinedCharactersCont )
throw(RuntimeException)
{
ParseResult r;
if ( Text.getLength() <= nPos )
return r;
setupParserTable( rLocale,
startCharTokenType, userDefinedCharactersStart,
contCharTokenType, userDefinedCharactersCont );
parseText( r, Text, nPos, nTokenType );
return r;
}
OUString SAL_CALL cclass_Unicode::getImplementationName() throw( RuntimeException )
{
return OUString::createFromAscii(cClass);
}
sal_Bool SAL_CALL cclass_Unicode::supportsService(const OUString& rServiceName) throw( RuntimeException )
{
return !rServiceName.compareToAscii(cClass);
}
Sequence< OUString > SAL_CALL cclass_Unicode::getSupportedServiceNames() throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(cClass);
return aRet;
}
} } } }
<commit_msg>INTEGRATION: CWS i18n14 (1.6.130); FILE MERGED 2004/07/26 22:18:43 khong 1.6.130.1: #i30863# make toTitle() only convert first letter of a word to upper case<commit_after>/*************************************************************************
*
* $RCSfile: cclass_unicode.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2004-09-08 15:25:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <cclass_unicode.hxx>
#include <com/sun/star/i18n/UnicodeScript.hpp>
#include <com/sun/star/i18n/UnicodeType.hpp>
#include <i18nutil/unicode.hxx>
#include <i18nutil/x_rtl_ustring.h>
#include <breakiteratorImpl.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
// ----------------------------------------------------
// class cclass_Unicode
// ----------------------------------------------------;
cclass_Unicode::cclass_Unicode( uno::Reference < XMultiServiceFactory > xSMgr ) : xMSF( xSMgr ),
pTable( NULL ),
pStart( NULL ),
pCont( NULL ),
nStartTypes( 0 ),
nContTypes( 0 ),
eState( ssGetChar ),
cGroupSep( ',' ),
cDecimalSep( '.' )
{
trans = new Transliteration_casemapping();
cClass = "com.sun.star.i18n.CharacterClassification_Unicode";
}
cclass_Unicode::~cclass_Unicode() {
destroyParserTable();
delete trans;
}
OUString SAL_CALL
cclass_Unicode::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
sal_Int32 len = Text.getLength();
if (nPos >= len)
return OUString();
if (nCount + nPos > len)
nCount = len - nPos;
trans->setMappingType(MappingTypeToUpper, rLocale);
return trans->transliterateString2String(Text, nPos, nCount);
}
OUString SAL_CALL
cclass_Unicode::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
sal_Int32 len = Text.getLength();
if (nPos >= len)
return OUString();
if (nCount + nPos > len)
nCount = len - nPos;
trans->setMappingType(MappingTypeToLower, rLocale);
return trans->transliterateString2String(Text, nPos, nCount);
}
OUString SAL_CALL
cclass_Unicode::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
sal_Int32 len = Text.getLength();
if (nPos >= len)
return OUString();
if (nCount + nPos > len)
nCount = len - nPos;
trans->setMappingType(MappingTypeToTitle, rLocale);
rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 );
sal_Unicode* out = pStr->buffer;
BreakIteratorImpl brk(xMSF);
Boundary bdy = brk.getWordBoundary(Text, nPos, rLocale,
WordType::ANYWORD_IGNOREWHITESPACES, sal_True);
for (sal_Int32 i = nPos; i < nCount + nPos; i++, out++) {
if (i >= bdy.endPos)
bdy = brk.nextWord(Text, bdy.endPos, rLocale,
WordType::ANYWORD_IGNOREWHITESPACES);
*out = (i == bdy.startPos) ?
trans->transliterateChar2Char(Text[i]) : Text[i];
}
*out = 0;
return OUString( pStr, SAL_NO_ACQUIRE );
}
sal_Int16 SAL_CALL
cclass_Unicode::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getUnicodeType(Text[nPos]);
}
sal_Int16 SAL_CALL
cclass_Unicode::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getUnicodeDirection(Text[nPos]);
}
sal_Int16 SAL_CALL
cclass_Unicode::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getUnicodeScriptType(Text[nPos], (ScriptTypeList*) 0, 0);
}
sal_Int32 SAL_CALL
cclass_Unicode::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
return unicode::getCharType(Text[nPos]);
}
sal_Int32 SAL_CALL
cclass_Unicode::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) {
if ( Text.getLength() <= nPos ) return 0;
if ( Text.getLength() < nPos + nCount )
nCount = Text.getLength() - nPos;
sal_Int32 result = 0;
for (int i = 0; i < nCount; i++)
result |= unicode::getCharType(Text[nPos+i]);
return result;
}
ParseResult SAL_CALL cclass_Unicode::parseAnyToken(
const OUString& Text,
sal_Int32 nPos,
const Locale& rLocale,
sal_Int32 startCharTokenType,
const OUString& userDefinedCharactersStart,
sal_Int32 contCharTokenType,
const OUString& userDefinedCharactersCont )
throw(RuntimeException)
{
ParseResult r;
if ( Text.getLength() <= nPos )
return r;
setupParserTable( rLocale,
startCharTokenType, userDefinedCharactersStart,
contCharTokenType, userDefinedCharactersCont );
parseText( r, Text, nPos );
return r;
}
ParseResult SAL_CALL cclass_Unicode::parsePredefinedToken(
sal_Int32 nTokenType,
const OUString& Text,
sal_Int32 nPos,
const Locale& rLocale,
sal_Int32 startCharTokenType,
const OUString& userDefinedCharactersStart,
sal_Int32 contCharTokenType,
const OUString& userDefinedCharactersCont )
throw(RuntimeException)
{
ParseResult r;
if ( Text.getLength() <= nPos )
return r;
setupParserTable( rLocale,
startCharTokenType, userDefinedCharactersStart,
contCharTokenType, userDefinedCharactersCont );
parseText( r, Text, nPos, nTokenType );
return r;
}
OUString SAL_CALL cclass_Unicode::getImplementationName() throw( RuntimeException )
{
return OUString::createFromAscii(cClass);
}
sal_Bool SAL_CALL cclass_Unicode::supportsService(const OUString& rServiceName) throw( RuntimeException )
{
return !rServiceName.compareToAscii(cClass);
}
Sequence< OUString > SAL_CALL cclass_Unicode::getSupportedServiceNames() throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(cClass);
return aRet;
}
} } } }
<|endoftext|> |
<commit_before>/// \file libuobject/uobject.cc
#include <iostream>
#include <sstream>
#include <list>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/unistd.h>
#include <libport/format.hh>
#include <liburbi/compatibility.hh>
#include <urbi/uexternal.hh>
#include <urbi/uobject.hh>
#include <urbi/ustarter.hh>
#include <urbi/usyncclient.hh>
#include <urbi/uvar.hh>
#include <urbi/ucontext-factory.hh>
#include <libuobject/remoteucontextimpl.hh>
namespace urbi
{
UObjectMode running_mode()
{
return MODE_REMOTE;
}
namespace impl
{
namespace
{
/// Look for the function args[1] in \a t, and make a call to the
/// associated callback with arguments (args[2], args[3], etc.).
static
void
eval_call(UTable& t, UList& args)
{
if (UTable::callbacks_type* cs = t.find0(args[1]))
{
args.setOffset(2);
foreach (UGenericCallback* c, *cs)
c->__evalcall(args);
args.setOffset(0);
}
}
}
typedef libport::hash_map<std::string, impl::UContextImpl*> contexts_type;
static contexts_type contexts;
impl::UContextImpl* makeRemoteContext(const std::string& host,
const std::string& port)
{
impl::UContextImpl* c = new impl::RemoteUContextImpl(
new USyncClient(host, strtol(port.c_str(), 0, 0)));
return c;
}
impl::UContextImpl* getRemoteContext(const std::string& host,
const std::string& port)
{
std::string key = host + ':' + port;
contexts_type::iterator i = contexts.find(key);
if (i != contexts.end())
return i->second;
impl::UContextImpl* c = new impl::RemoteUContextImpl(
new USyncClient(host, strtol(port.c_str(), 0, 0)));
contexts[key] = c;
return c;
}
USyncClient*
RemoteUContextImpl::getClient()
{
return client_;
}
UObject*
RemoteUContextImpl::getDummyUObject()
{
if (!dummyUObject)
dummyUObject = new UObject(0, this);
return dummyUObject;
}
RemoteUContextImpl::RemoteUContextImpl(USyncClient* client)
: client_(client)
, dummyUObject(0)
{
client_->setCallback(callback(*this, &RemoteUContextImpl::dispatcher),
externalModuleTag.c_str());
}
void RemoteUContextImpl::uobject_unarmorAndSend(const char* a)
{
unarmorAndSend(a, client_);
}
void RemoteUContextImpl::send(const char* a)
{
(*client_) << a;
}
void RemoteUContextImpl::send(const void* buf, size_t size)
{
client_->rdbuf()->sputn(static_cast<const char*> (buf), size);
}
UObjectMode RemoteUContextImpl::getRunningMode()
{
return MODE_REMOTE;
}
UTable&
RemoteUContextImpl::tableByName(const std::string& n)
{
#define CHECK(v) if (n == #v) return v##map##_
CHECK(access);
CHECK(event);
CHECK(eventend);
CHECK(function);
CHECK(monitor);
#undef CHECK
if (n == "var" || n =="var_onrequest")
return monitormap_;
if (n == "varaccess")
return accessmap_;
throw std::runtime_error("Unexpected table name. " + n);
}
// **************************************************************************
//! UObject constructor.
void RemoteUObjectImpl::initialize(UObject* owner)
{
period = -1;
this->owner_ = owner;
if (owner->__name == "_dummy")
return;
owner_->ctx_->registerObject(owner);
UClient* client = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_)->client_;
URBI_SEND_PIPED_COMMAND_C((*client),
"class " << owner_->__name << "{}");
URBI_SEND_PIPED_COMMAND_C((*client),
"external object " << owner_->__name);
}
//! UObject cleaner
void
RemoteUObjectImpl::clean()
{
RemoteUContextImpl& ctx = dynamic_cast<RemoteUContextImpl&>
(*(owner_->ctx_));
ctx.monitormap().clean(owner_->__name);
ctx.accessmap().clean(owner_->__name);
ctx.functionmap().clean(owner_->__name);
ctx.eventmap().clean(owner_->__name);
ctx.eventendmap().clean(owner_->__name);
if (owner_->objecthub)
owner_->objecthub->members.remove(owner_);
}
void
RemoteUObjectImpl::setUpdate(ufloat t)
{
RemoteUContextImpl& ctx = dynamic_cast<RemoteUContextImpl&>
(*(owner_->ctx_));
// Forge names for callback and tag
std::string tagName = "maintimer_" + owner_->__name;
std::string cbName = owner_->__name + ".maintimer";
// Stop any previous update
if (2 <= kernelMajor())
URBI_SEND_COMMAND
(libport::format("if (!%s.hasLocalSlot(\"%s\"))\n"
" var %s.%s = Tag.new(\"%s\")|\n"
" %s.%s.stop",
owner_->__name, tagName,
owner_->__name, tagName, tagName,
owner_->__name, tagName));
else
URBI_SEND_COMMAND("stop " << tagName);
// Find previous update timer on this object and delete.
{
std::string cbFullName = cbName + "__0";
std::list<UGenericCallback*>& cs = ctx.eventmap()[cbFullName];
typedef std::list<UGenericCallback*>::iterator iterator;
for (iterator i = cs.begin(); i != cs.end(); ++i)
if ((*i)->getName() == cbFullName)
{
delete *i;
cs.erase(i);
break;
}
}
// Set period value
period = t;
// Do nothing more if negative value given
if (period < 0)
return;
// FIXME: setting update at 0 put the kernel in infinite loop
// and memory usage goes up to 100%
if (period == 0)
period = 1;
// Create callback
createUCallback(owner_->__name, "event",
owner_, &UObject::update, cbName, false);
// Set update at given period
std::string base = 2 <= kernelMajor() ? owner_->__name + "." : "";
URBI_SEND_COMMAND(
base << tagName << ": every(" << period << "ms)"
" { " << compatibility::emit(cbName) << ";},");
return;
}
void RemoteUContextImpl::yield()
{
yield_until(libport::utime());
}
void RemoteUContextImpl::yield_until(libport::utime_t deadline)
{
// Ensure processEvents is called at least once.
while (true)
{
bool processed = dynamic_cast<USyncClient*>(client_)
->processEvents(0);
if (deadline < libport::utime())
return;
if (!processed)
usleep(0);
}
}
void RemoteUContextImpl::yield_until_things_changed()
{
while (true)
{
if (dynamic_cast<USyncClient*>(client_)->processEvents(0))
return;
usleep(0);
}
}
void RemoteUContextImpl::side_effect_free_set(bool)
{}
bool RemoteUContextImpl::side_effect_free_get()
{
return false;
}
UCallbackAction
RemoteUContextImpl::dispatcher(const UMessage& msg)
{
setCurrentContext(this);
typedef UTable::callbacks_type callbacks_type;
//check message type
if (msg.type != MESSAGE_DATA || msg.value->type != DATA_LIST)
{
msg.client.printf("Component Error: "
"unknown message content, type %d\n",
msg.type);
return URBI_CONTINUE;
}
UList& array = *msg.value->list;
if (array.size() < 2)
{
msg.client.printf("Component Error: Invalid number "
"of arguments in the server message: %lu\n",
static_cast<unsigned long>(array.size()));
return URBI_CONTINUE;
}
if (array[0].type != DATA_DOUBLE)
{
msg.client.printf("Component Error: "
"invalid server message type %d\n",
array[0].type);
return URBI_CONTINUE;
}
switch ((USystemExternalMessage)(int)array[0])
{
case UEM_ASSIGNVALUE:
{
if (array.size() != 3)
{
msg.client.printf("Component Error: Invalid number "
"of arguments in the server message: %lu"
" (expected 3)\n",
static_cast<unsigned long>(array.size()));
return URBI_CONTINUE;
}
if (std::list<UVar*> *us = varmap().find0(array[1]))
{
foreach (UVar* u, *us)
dynamic_cast<RemoteUVarImpl*>(u->impl_)->update(array[2]);
}
if (callbacks_type* cs = monitormap().find0(array[1]))
{
foreach (UGenericCallback *c, *cs)
{
// test of return value here
UList u;
u.array.push_back(new UValue());
u[0].storage = c->storage;
c->__evalcall(u);
}
}
}
break;
case UEM_EVALFUNCTION:
{
callbacks_type tmpfun = functionmap()[array[1]];
const std::string var = array[2];
callbacks_type::iterator tmpfunit = tmpfun.begin();
if (tmpfunit == tmpfun.end())
throw std::runtime_error("no callback found");
array.setOffset(3);
UValue retval = (*tmpfunit)->__evalcall(array);
array.setOffset(0);
switch (retval.type)
{
case DATA_BINARY:
// Send it
if (UClient* client = urbi::getDefaultClient())
{
// URBI_SEND_COMMAND does not now how to send binary since it
// depends on the kernel version.
client->startPack();
*client << " var " << var << "=";
client->send(retval);
*client << ";";
client->endPack();
}
else
// Send void if no client. Would block anyway.
goto case_void;
break;
case DATA_VOID:
case_void:
URBI_SEND_COMMAND("var " << var);
break;
default:
URBI_SEND_COMMAND("var " << var << "=" << retval);
break;
}
}
break;
case UEM_EMITEVENT:
eval_call(eventmap(), array);
break;
case UEM_ENDEVENT:
eval_call(eventendmap(), array);
break;
case UEM_NEW:
{
objects_type::iterator i = objects.find(std::string(array[2]));
if (i == objects.end())
msg.client.printf("No such objects %s\n",
std::string(array[2]).c_str());
else
{
baseURBIStarter* bsa = i->second->cloner;
std::cerr << "instantiating from " << bsa << std::endl;
std::cerr << "name: " << (std::string) array[1] << std::endl;
bsa->instanciate(this, (std::string) array[1]);
}
}
break;
case UEM_DELETE:
{
objects_type::iterator i = objects.find(std::string(array[1]));
if (i == objects.end())
break;
if (objects.size() == 1)
exit(0);
else
delete i->second;
objects.erase(i);
}
break;
default:
msg.client.printf("Component Error: "
"unknown server message type number %d\n",
(int)array[0]);
return URBI_CONTINUE;
}
// Send a terminating ';' since code send by the UObject API uses '|'.
URBI_SEND_COMMAND("");
return URBI_CONTINUE;
}
void
RemoteUContextImpl::newUObjectClass(baseURBIStarter* s)
{
s->instanciate(this);
}
void
RemoteUContextImpl::newUObjectHubClass(baseURBIStarterHub* s)
{
s->instanciate(this);
}
/*---------------------.
| UObjects accessors. |
`---------------------*/
void RemoteUContextImpl::setTimer(UTimerCallback* cb)
{
// Register ourself as an event.
std::string cbname = "timer" + string_cast(cb);
std::string event = cb->objname + "." + cbname;
createUCallback(cb->objname, "event", cb, &UTimerCallback::call,
event, false);
URBI_SEND_COMMAND_C((*client_),
"timer_" << cb->objname << ": every("
<< cb->period << "ms)"
"{ " << compatibility::emit(event) << ";}");
}
void
RemoteUContextImpl::call(const std::string& object,
const std::string& method,
UAutoValue v1,
UAutoValue v2,
UAutoValue v3,
UAutoValue v4,
UAutoValue v5,
UAutoValue v6,
UAutoValue v7,
UAutoValue v8)
{
std::stringstream s;
s << object << "." << method <<"(";
#define CHECK(v) if (v.type != DATA_VOID) s << v << ","
CHECK(v1); CHECK(v2); CHECK(v3); CHECK(v4);
CHECK(v5); CHECK(v6); CHECK(v7); CHECK(v8);
#undef CHECK
std::string r = s.str();
r = r.substr(0, r.length() - 1) + ")";
URBI_SEND_COMMAND_C((*client_), r);
}
UVarImpl*
RemoteUContextImpl::getVarImpl()
{
return new RemoteUVarImpl();
}
UObjectImpl*
RemoteUContextImpl::getObjectImpl()
{
return new RemoteUObjectImpl();
}
UGenericCallbackImpl*
RemoteUContextImpl::getGenericCallbackImpl()
{
return new RemoteUGenericCallbackImpl();
}
/*-------------.
| UObjectHub. |
`-------------*/
void
RemoteUContextImpl::setHubUpdate(UObjectHub*, ufloat)
{
// nothing happend in remote mode...
}
void
RemoteUContextImpl::removeHub(UObjectHub*)
{
}
void
RemoteUContextImpl::registerHub(UObjectHub*)
{
}
}
/*find out where it is used
std::string
baseURBIStarter::getFullName(const std::string& name)
{
if (local)
return name + "_" + getClientConnectionID(client_);
else
return name;
}*/
} // namespace urbi
<commit_msg>Check the down-cast to the remote uobjects implementation works.<commit_after>/// \file libuobject/uobject.cc
#include <iostream>
#include <sstream>
#include <list>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/unistd.h>
#include <libport/debug.hh>
#include <libport/format.hh>
#include <liburbi/compatibility.hh>
#include <urbi/uexternal.hh>
#include <urbi/uobject.hh>
#include <urbi/ustarter.hh>
#include <urbi/usyncclient.hh>
#include <urbi/uvar.hh>
#include <urbi/ucontext-factory.hh>
#include <libuobject/remoteucontextimpl.hh>
namespace urbi
{
UObjectMode running_mode()
{
return MODE_REMOTE;
}
namespace impl
{
namespace
{
/// Look for the function args[1] in \a t, and make a call to the
/// associated callback with arguments (args[2], args[3], etc.).
static
void
eval_call(UTable& t, UList& args)
{
if (UTable::callbacks_type* cs = t.find0(args[1]))
{
args.setOffset(2);
foreach (UGenericCallback* c, *cs)
c->__evalcall(args);
args.setOffset(0);
}
}
}
typedef libport::hash_map<std::string, impl::UContextImpl*> contexts_type;
static contexts_type contexts;
impl::UContextImpl* makeRemoteContext(const std::string& host,
const std::string& port)
{
impl::UContextImpl* c = new impl::RemoteUContextImpl(
new USyncClient(host, strtol(port.c_str(), 0, 0)));
return c;
}
impl::UContextImpl* getRemoteContext(const std::string& host,
const std::string& port)
{
std::string key = host + ':' + port;
contexts_type::iterator i = contexts.find(key);
if (i != contexts.end())
return i->second;
impl::UContextImpl* c = new impl::RemoteUContextImpl(
new USyncClient(host, strtol(port.c_str(), 0, 0)));
contexts[key] = c;
return c;
}
USyncClient*
RemoteUContextImpl::getClient()
{
return client_;
}
UObject*
RemoteUContextImpl::getDummyUObject()
{
if (!dummyUObject)
dummyUObject = new UObject(0, this);
return dummyUObject;
}
RemoteUContextImpl::RemoteUContextImpl(USyncClient* client)
: client_(client)
, dummyUObject(0)
{
client_->setCallback(callback(*this, &RemoteUContextImpl::dispatcher),
externalModuleTag.c_str());
}
void RemoteUContextImpl::uobject_unarmorAndSend(const char* a)
{
unarmorAndSend(a, client_);
}
void RemoteUContextImpl::send(const char* a)
{
(*client_) << a;
}
void RemoteUContextImpl::send(const void* buf, size_t size)
{
client_->rdbuf()->sputn(static_cast<const char*> (buf), size);
}
UObjectMode RemoteUContextImpl::getRunningMode()
{
return MODE_REMOTE;
}
UTable&
RemoteUContextImpl::tableByName(const std::string& n)
{
#define CHECK(v) if (n == #v) return v##map##_
CHECK(access);
CHECK(event);
CHECK(eventend);
CHECK(function);
CHECK(monitor);
#undef CHECK
if (n == "var" || n =="var_onrequest")
return monitormap_;
if (n == "varaccess")
return accessmap_;
throw std::runtime_error("Unexpected table name. " + n);
}
// **************************************************************************
//! UObject constructor.
void RemoteUObjectImpl::initialize(UObject* owner)
{
period = -1;
this->owner_ = owner;
if (owner->__name == "_dummy")
return;
owner_->ctx_->registerObject(owner);
UClient* client = dynamic_cast<RemoteUContextImpl*>(owner_->ctx_)->client_;
URBI_SEND_PIPED_COMMAND_C((*client),
"class " << owner_->__name << "{}");
URBI_SEND_PIPED_COMMAND_C((*client),
"external object " << owner_->__name);
}
//! UObject cleaner
void
RemoteUObjectImpl::clean()
{
RemoteUContextImpl& ctx = dynamic_cast<RemoteUContextImpl&>
(*(owner_->ctx_));
ctx.monitormap().clean(owner_->__name);
ctx.accessmap().clean(owner_->__name);
ctx.functionmap().clean(owner_->__name);
ctx.eventmap().clean(owner_->__name);
ctx.eventendmap().clean(owner_->__name);
if (owner_->objecthub)
owner_->objecthub->members.remove(owner_);
}
void
RemoteUObjectImpl::setUpdate(ufloat t)
{
RemoteUContextImpl& ctx = dynamic_cast<RemoteUContextImpl&>
(*(owner_->ctx_));
// Forge names for callback and tag
std::string tagName = "maintimer_" + owner_->__name;
std::string cbName = owner_->__name + ".maintimer";
// Stop any previous update
if (2 <= kernelMajor())
URBI_SEND_COMMAND
(libport::format("if (!%s.hasLocalSlot(\"%s\"))\n"
" var %s.%s = Tag.new(\"%s\")|\n"
" %s.%s.stop",
owner_->__name, tagName,
owner_->__name, tagName, tagName,
owner_->__name, tagName));
else
URBI_SEND_COMMAND("stop " << tagName);
// Find previous update timer on this object and delete.
{
std::string cbFullName = cbName + "__0";
std::list<UGenericCallback*>& cs = ctx.eventmap()[cbFullName];
typedef std::list<UGenericCallback*>::iterator iterator;
for (iterator i = cs.begin(); i != cs.end(); ++i)
if ((*i)->getName() == cbFullName)
{
delete *i;
cs.erase(i);
break;
}
}
// Set period value
period = t;
// Do nothing more if negative value given
if (period < 0)
return;
// FIXME: setting update at 0 put the kernel in infinite loop
// and memory usage goes up to 100%
if (period == 0)
period = 1;
// Create callback
createUCallback(owner_->__name, "event",
owner_, &UObject::update, cbName, false);
// Set update at given period
std::string base = 2 <= kernelMajor() ? owner_->__name + "." : "";
URBI_SEND_COMMAND(
base << tagName << ": every(" << period << "ms)"
" { " << compatibility::emit(cbName) << ";},");
return;
}
void RemoteUContextImpl::yield()
{
yield_until(libport::utime());
}
void RemoteUContextImpl::yield_until(libport::utime_t deadline)
{
// Ensure processEvents is called at least once.
while (true)
{
bool processed = dynamic_cast<USyncClient*>(client_)
->processEvents(0);
if (deadline < libport::utime())
return;
if (!processed)
usleep(0);
}
}
void RemoteUContextImpl::yield_until_things_changed()
{
while (true)
{
if (dynamic_cast<USyncClient*>(client_)->processEvents(0))
return;
usleep(0);
}
}
void RemoteUContextImpl::side_effect_free_set(bool)
{}
bool RemoteUContextImpl::side_effect_free_get()
{
return false;
}
UCallbackAction
RemoteUContextImpl::dispatcher(const UMessage& msg)
{
setCurrentContext(this);
typedef UTable::callbacks_type callbacks_type;
//check message type
if (msg.type != MESSAGE_DATA || msg.value->type != DATA_LIST)
{
msg.client.printf("Component Error: "
"unknown message content, type %d\n",
msg.type);
return URBI_CONTINUE;
}
UList& array = *msg.value->list;
if (array.size() < 2)
{
msg.client.printf("Component Error: Invalid number "
"of arguments in the server message: %lu\n",
static_cast<unsigned long>(array.size()));
return URBI_CONTINUE;
}
if (array[0].type != DATA_DOUBLE)
{
msg.client.printf("Component Error: "
"invalid server message type %d\n",
array[0].type);
return URBI_CONTINUE;
}
switch ((USystemExternalMessage)(int)array[0])
{
case UEM_ASSIGNVALUE:
{
if (array.size() != 3)
{
msg.client.printf("Component Error: Invalid number "
"of arguments in the server message: %lu"
" (expected 3)\n",
static_cast<unsigned long>(array.size()));
return URBI_CONTINUE;
}
if (std::list<UVar*> *us = varmap().find0(array[1]))
{
foreach (UVar* u, *us)
{
if (RemoteUVarImpl* impl = dynamic_cast<RemoteUVarImpl*>(u->impl_))
impl->update(array[2]);
else
{
GD_FERROR("Unable to cast %x to a RemoteUVarImpl.", (u->impl_));
std::abort();
}
}
}
if (callbacks_type* cs = monitormap().find0(array[1]))
{
foreach (UGenericCallback *c, *cs)
{
// test of return value here
UList u;
u.array.push_back(new UValue());
u[0].storage = c->storage;
c->__evalcall(u);
}
}
}
break;
case UEM_EVALFUNCTION:
{
callbacks_type tmpfun = functionmap()[array[1]];
const std::string var = array[2];
callbacks_type::iterator tmpfunit = tmpfun.begin();
if (tmpfunit == tmpfun.end())
throw std::runtime_error("no callback found");
array.setOffset(3);
UValue retval = (*tmpfunit)->__evalcall(array);
array.setOffset(0);
switch (retval.type)
{
case DATA_BINARY:
// Send it
if (UClient* client = urbi::getDefaultClient())
{
// URBI_SEND_COMMAND does not now how to send binary since it
// depends on the kernel version.
client->startPack();
*client << " var " << var << "=";
client->send(retval);
*client << ";";
client->endPack();
}
else
// Send void if no client. Would block anyway.
goto case_void;
break;
case DATA_VOID:
case_void:
URBI_SEND_COMMAND("var " << var);
break;
default:
URBI_SEND_COMMAND("var " << var << "=" << retval);
break;
}
}
break;
case UEM_EMITEVENT:
eval_call(eventmap(), array);
break;
case UEM_ENDEVENT:
eval_call(eventendmap(), array);
break;
case UEM_NEW:
{
objects_type::iterator i = objects.find(std::string(array[2]));
if (i == objects.end())
msg.client.printf("No such objects %s\n",
std::string(array[2]).c_str());
else
{
baseURBIStarter* bsa = i->second->cloner;
std::cerr << "instantiating from " << bsa << std::endl;
std::cerr << "name: " << (std::string) array[1] << std::endl;
bsa->instanciate(this, (std::string) array[1]);
}
}
break;
case UEM_DELETE:
{
objects_type::iterator i = objects.find(std::string(array[1]));
if (i == objects.end())
break;
if (objects.size() == 1)
exit(0);
else
delete i->second;
objects.erase(i);
}
break;
default:
msg.client.printf("Component Error: "
"unknown server message type number %d\n",
(int)array[0]);
return URBI_CONTINUE;
}
// Send a terminating ';' since code send by the UObject API uses '|'.
URBI_SEND_COMMAND("");
return URBI_CONTINUE;
}
void
RemoteUContextImpl::newUObjectClass(baseURBIStarter* s)
{
s->instanciate(this);
}
void
RemoteUContextImpl::newUObjectHubClass(baseURBIStarterHub* s)
{
s->instanciate(this);
}
/*---------------------.
| UObjects accessors. |
`---------------------*/
void RemoteUContextImpl::setTimer(UTimerCallback* cb)
{
// Register ourself as an event.
std::string cbname = "timer" + string_cast(cb);
std::string event = cb->objname + "." + cbname;
createUCallback(cb->objname, "event", cb, &UTimerCallback::call,
event, false);
URBI_SEND_COMMAND_C((*client_),
"timer_" << cb->objname << ": every("
<< cb->period << "ms)"
"{ " << compatibility::emit(event) << ";}");
}
void
RemoteUContextImpl::call(const std::string& object,
const std::string& method,
UAutoValue v1,
UAutoValue v2,
UAutoValue v3,
UAutoValue v4,
UAutoValue v5,
UAutoValue v6,
UAutoValue v7,
UAutoValue v8)
{
std::stringstream s;
s << object << "." << method <<"(";
#define CHECK(v) if (v.type != DATA_VOID) s << v << ","
CHECK(v1); CHECK(v2); CHECK(v3); CHECK(v4);
CHECK(v5); CHECK(v6); CHECK(v7); CHECK(v8);
#undef CHECK
std::string r = s.str();
r = r.substr(0, r.length() - 1) + ")";
URBI_SEND_COMMAND_C((*client_), r);
}
UVarImpl*
RemoteUContextImpl::getVarImpl()
{
return new RemoteUVarImpl();
}
UObjectImpl*
RemoteUContextImpl::getObjectImpl()
{
return new RemoteUObjectImpl();
}
UGenericCallbackImpl*
RemoteUContextImpl::getGenericCallbackImpl()
{
return new RemoteUGenericCallbackImpl();
}
/*-------------.
| UObjectHub. |
`-------------*/
void
RemoteUContextImpl::setHubUpdate(UObjectHub*, ufloat)
{
// nothing happend in remote mode...
}
void
RemoteUContextImpl::removeHub(UObjectHub*)
{
}
void
RemoteUContextImpl::registerHub(UObjectHub*)
{
}
}
/*find out where it is used
std::string
baseURBIStarter::getFullName(const std::string& name)
{
if (local)
return name + "_" + getClientConnectionID(client_);
else
return name;
}*/
} // namespace urbi
<|endoftext|> |
<commit_before>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#include <infoware/cpu.hpp>
#include <infoware/detail/cpuid.hpp>
#ifdef _WIN32
#include <intrin.h>
#define INFOWARE_XCR_XFEATURE_ENABLED_MASK _XCR_XFEATURE_ENABLED_MASK
#else
#define INFOWARE_XCR_XFEATURE_ENABLED_MASK 0
#endif // Windows or not
static bool has_os_avx() {
bool avxsupport = false;
int32_t cpuinfo[4];
iware::detail::cpuid(cpuinfo, 1);
bool osusesxsave_restore = (cpuinfo[2] & (1 << 27)) != 0;
bool cpusupportsavx = (cpuinfo[2] & (1 << 28)) != 0;
if (osusesxsave_restore && cpusupportsavx) {
uint64_t xcrFeatureMask = iware::detail::xgetbv(INFOWARE_XCR_XFEATURE_ENABLED_MASK);
avxsupport = (xcrFeatureMask & 0x6) == 0x6;
}
return avxsupport;
}
static bool has_os_avx_512() {
if (!has_os_avx())
return false;
uint64_t xcrFeatureMask = iware::detail::xgetbv(INFOWARE_XCR_XFEATURE_ENABLED_MASK);
return (xcrFeatureMask & 0xe6) == 0xe6;
}
std::vector<iware::cpu::instruction_set_t> iware::cpu::supported_instruction_sets() {
int info[4];
iware::detail::cpuid(info, 0);
int idinfo = info[0];
iware::detail::cpuid(info, 0x80000000);
uint32_t extendedidinfo = info[0];
std::vector<iware::cpu::instruction_set_t> supported;
supported.reserve(64);
#define ADD_SET_IF( infoindex, bitindex, name ) if ((info[(infoindex)] & ((int)1 << (bitindex)) ) != 0) { supported.push_back(iware::cpu::name); }
if (idinfo >= 0x00000001) {
iware::detail::cpuid(info, 0x00000001);
ADD_SET_IF(3, 22, instruction_set_t::mmx_extended);
ADD_SET_IF(3, 23, instruction_set_t::mmx);
ADD_SET_IF(3, 25, instruction_set_t::sse);
ADD_SET_IF(3, 26, instruction_set_t::sse2);
ADD_SET_IF(2, 0, instruction_set_t::sse3);
ADD_SET_IF(2, 9, instruction_set_t::ssse3);
ADD_SET_IF(2, 19, instruction_set_t::sse41);
ADD_SET_IF(2, 20, instruction_set_t::sse42);
ADD_SET_IF(2, 25, instruction_set_t::aes);
ADD_SET_IF(2, 28, instruction_set_t::fma3);
ADD_SET_IF(2, 12, instruction_set_t::rd_rand);
}
if (idinfo >= 0x00000007) {
iware::detail::cpuid(info, 0x00000007);
if (has_os_avx()) {
// Both must be present to have AVX
ADD_SET_IF(1, 5, instruction_set_t::avx2);
}
ADD_SET_IF(1, 4, instruction_set_t::hle);
ADD_SET_IF(1, 3, instruction_set_t::bmi1);
ADD_SET_IF(1, 8, instruction_set_t::bmi2);
ADD_SET_IF(1, 19, instruction_set_t::adx);
ADD_SET_IF(1, 14, instruction_set_t::mpx);
ADD_SET_IF(1, 29, instruction_set_t::sha);
if (has_os_avx_512()) {
supported.push_back(iware::cpu::instruction_set_t::avx_512);
ADD_SET_IF(1, 16, instruction_set_t::avx_512_f);
ADD_SET_IF(1, 28, instruction_set_t::avx_512_cd);
ADD_SET_IF(1, 26, instruction_set_t::avx_512_pf);
ADD_SET_IF(1, 27, instruction_set_t::avx_512_er);
ADD_SET_IF(1, 31, instruction_set_t::avx_512_vl);
ADD_SET_IF(1, 30, instruction_set_t::avx_512_bw);
ADD_SET_IF(1, 17, instruction_set_t::avx_512_dq);
ADD_SET_IF(1, 21, instruction_set_t::avx_512_ifma);
ADD_SET_IF(2, 1, instruction_set_t::avx_512_vbmi);
}
ADD_SET_IF(2, 0, instruction_set_t::prefetch_wt1);
}
if (extendedidinfo >= 0x80000001) {
iware::detail::cpuid(info, 0x80000001);
ADD_SET_IF(3, 29, instruction_set_t::x64);
ADD_SET_IF(3, 0, instruction_set_t::x87_fpu);
ADD_SET_IF(3, 30, instruction_set_t::s3d_now);
ADD_SET_IF(3, 31, instruction_set_t::s3d_now_extended);
ADD_SET_IF(3, 29, instruction_set_t::x64);
ADD_SET_IF(2, 5, instruction_set_t::bmi1);
ADD_SET_IF(2, 6, instruction_set_t::bmi2);
ADD_SET_IF(2, 16, instruction_set_t::adx);
ADD_SET_IF(2, 11, instruction_set_t::mpx);
}
#undef ADD_SET_IF
return supported;
}<commit_msg>Fuck you too, MinGW<commit_after>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#include "infoware/cpu.hpp"
#include "infoware/detail/cpuid.hpp"
#if defined _WIN32 && defined _MSC_VER
#include <intrin.h>
#define INFOWARE_XCR_XFEATURE_ENABLED_MASK _XCR_XFEATURE_ENABLED_MASK
#else
#define INFOWARE_XCR_XFEATURE_ENABLED_MASK 0
#endif // Windows or not
static bool has_os_avx() {
bool avxsupport = false;
int32_t cpuinfo[4];
iware::detail::cpuid(cpuinfo, 1);
bool osusesxsave_restore = (cpuinfo[2] & (1 << 27)) != 0;
bool cpusupportsavx = (cpuinfo[2] & (1 << 28)) != 0;
if (osusesxsave_restore && cpusupportsavx) {
uint64_t xcrFeatureMask = iware::detail::xgetbv(INFOWARE_XCR_XFEATURE_ENABLED_MASK);
avxsupport = (xcrFeatureMask & 0x6) == 0x6;
}
return avxsupport;
}
static bool has_os_avx_512() {
if (!has_os_avx())
return false;
uint64_t xcrFeatureMask = iware::detail::xgetbv(INFOWARE_XCR_XFEATURE_ENABLED_MASK);
return (xcrFeatureMask & 0xe6) == 0xe6;
}
std::vector<iware::cpu::instruction_set_t> iware::cpu::supported_instruction_sets() {
int info[4];
iware::detail::cpuid(info, 0);
int idinfo = info[0];
iware::detail::cpuid(info, 0x80000000);
uint32_t extendedidinfo = info[0];
std::vector<iware::cpu::instruction_set_t> supported;
supported.reserve(64);
#define ADD_SET_IF( infoindex, bitindex, name ) if ((info[(infoindex)] & ((int)1 << (bitindex)) ) != 0) { supported.push_back(iware::cpu::name); }
if (idinfo >= 0x00000001) {
iware::detail::cpuid(info, 0x00000001);
ADD_SET_IF(3, 22, instruction_set_t::mmx_extended);
ADD_SET_IF(3, 23, instruction_set_t::mmx);
ADD_SET_IF(3, 25, instruction_set_t::sse);
ADD_SET_IF(3, 26, instruction_set_t::sse2);
ADD_SET_IF(2, 0, instruction_set_t::sse3);
ADD_SET_IF(2, 9, instruction_set_t::ssse3);
ADD_SET_IF(2, 19, instruction_set_t::sse41);
ADD_SET_IF(2, 20, instruction_set_t::sse42);
ADD_SET_IF(2, 25, instruction_set_t::aes);
ADD_SET_IF(2, 28, instruction_set_t::fma3);
ADD_SET_IF(2, 12, instruction_set_t::rd_rand);
}
if (idinfo >= 0x00000007) {
iware::detail::cpuid(info, 0x00000007);
if (has_os_avx()) {
// Both must be present to have AVX
ADD_SET_IF(1, 5, instruction_set_t::avx2);
}
ADD_SET_IF(1, 4, instruction_set_t::hle);
ADD_SET_IF(1, 3, instruction_set_t::bmi1);
ADD_SET_IF(1, 8, instruction_set_t::bmi2);
ADD_SET_IF(1, 19, instruction_set_t::adx);
ADD_SET_IF(1, 14, instruction_set_t::mpx);
ADD_SET_IF(1, 29, instruction_set_t::sha);
if (has_os_avx_512()) {
supported.push_back(iware::cpu::instruction_set_t::avx_512);
ADD_SET_IF(1, 16, instruction_set_t::avx_512_f);
ADD_SET_IF(1, 28, instruction_set_t::avx_512_cd);
ADD_SET_IF(1, 26, instruction_set_t::avx_512_pf);
ADD_SET_IF(1, 27, instruction_set_t::avx_512_er);
ADD_SET_IF(1, 31, instruction_set_t::avx_512_vl);
ADD_SET_IF(1, 30, instruction_set_t::avx_512_bw);
ADD_SET_IF(1, 17, instruction_set_t::avx_512_dq);
ADD_SET_IF(1, 21, instruction_set_t::avx_512_ifma);
ADD_SET_IF(2, 1, instruction_set_t::avx_512_vbmi);
}
ADD_SET_IF(2, 0, instruction_set_t::prefetch_wt1);
}
if (extendedidinfo >= 0x80000001) {
iware::detail::cpuid(info, 0x80000001);
ADD_SET_IF(3, 29, instruction_set_t::x64);
ADD_SET_IF(3, 0, instruction_set_t::x87_fpu);
ADD_SET_IF(3, 30, instruction_set_t::s3d_now);
ADD_SET_IF(3, 31, instruction_set_t::s3d_now_extended);
ADD_SET_IF(3, 29, instruction_set_t::x64);
ADD_SET_IF(2, 5, instruction_set_t::bmi1);
ADD_SET_IF(2, 6, instruction_set_t::bmi2);
ADD_SET_IF(2, 16, instruction_set_t::adx);
ADD_SET_IF(2, 11, instruction_set_t::mpx);
}
#undef ADD_SET_IF
return supported;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MultipleItemConverter.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:01:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "MultipleItemConverter.hxx"
#include "ItemPropertyMap.hxx"
#include <algorithm>
using namespace ::com::sun::star;
namespace comphelper
{
MultipleItemConverter::MultipleItemConverter( SfxItemPool& rItemPool )
: ItemConverter( NULL, rItemPool )
{
}
MultipleItemConverter::~MultipleItemConverter()
{
::std::for_each( m_aConverters.begin(), m_aConverters.end(),
DeleteItemConverterPtr() );
}
void MultipleItemConverter::FillItemSet( SfxItemSet & rOutItemSet ) const
{
::std::vector< ItemConverter* >::const_iterator aIter = m_aConverters.begin();
const ::std::vector< ItemConverter* >::const_iterator aEnd = m_aConverters.end();
if( aIter != aEnd )
{
(*aIter)->FillItemSet( rOutItemSet );
aIter++;
}
for( ; aIter != aEnd; aIter++ )
{
SfxItemSet aSet = this->CreateEmptyItemSet();
(*aIter)->FillItemSet( aSet );
InvalidateUnequalItems( rOutItemSet, aSet );
}
// no own items
}
bool MultipleItemConverter::ApplyItemSet( const SfxItemSet & rItemSet )
{
bool bResult = false;
::std::for_each( m_aConverters.begin(), m_aConverters.end(),
ApplyItemSetFunc( rItemSet, bResult ));
// no own items
return bResult;
}
bool MultipleItemConverter::GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const
{
return false;
}
} // namespace comphelper
<commit_msg>INTEGRATION: CWS chart07 (1.6.12); FILE MERGED 2007/07/10 11:57:29 bm 1.6.12.1: #i69281# warnings removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MultipleItemConverter.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2007-07-25 08:41:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "MultipleItemConverter.hxx"
#include "ItemPropertyMap.hxx"
#include <algorithm>
using namespace ::com::sun::star;
namespace comphelper
{
MultipleItemConverter::MultipleItemConverter( SfxItemPool& rItemPool )
: ItemConverter( NULL, rItemPool )
{
}
MultipleItemConverter::~MultipleItemConverter()
{
::std::for_each( m_aConverters.begin(), m_aConverters.end(),
DeleteItemConverterPtr() );
}
void MultipleItemConverter::FillItemSet( SfxItemSet & rOutItemSet ) const
{
::std::vector< ItemConverter* >::const_iterator aIter = m_aConverters.begin();
const ::std::vector< ItemConverter* >::const_iterator aEnd = m_aConverters.end();
if( aIter != aEnd )
{
(*aIter)->FillItemSet( rOutItemSet );
aIter++;
}
for( ; aIter != aEnd; aIter++ )
{
SfxItemSet aSet = this->CreateEmptyItemSet();
(*aIter)->FillItemSet( aSet );
InvalidateUnequalItems( rOutItemSet, aSet );
}
// no own items
}
bool MultipleItemConverter::ApplyItemSet( const SfxItemSet & rItemSet )
{
bool bResult = false;
::std::for_each( m_aConverters.begin(), m_aConverters.end(),
ApplyItemSetFunc( rItemSet, bResult ));
// no own items
return bResult;
}
bool MultipleItemConverter::GetItemProperty( tWhichIdType /*nWhichId*/, tPropertyNameWithMemberId & /*rOutProperty*/ ) const
{
return false;
}
} // namespace comphelper
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tokstack.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:36:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
#ifndef _TOKSTACK_HXX
#define _TOKSTACK_HXX
#ifndef _INC_STRING
#include <string.h>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif
typedef OpCode DefTokenId;
// in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16
// Unfortunately a typedef is just a dumb alias and not a real type ...
//typedef UINT16 TokenId;
struct TokenId
{
UINT16 nId;
TokenId() {}
TokenId( UINT16 n ) : nId( n ) {}
TokenId( const TokenId& r ) : nId( r.nId ) {}
inline TokenId& operator =( const TokenId& r ) { nId = r.nId; return *this; }
inline TokenId& operator =( UINT16 n ) { nId = n; return *this; }
inline operator UINT16&() { return nId; }
inline operator const UINT16&() const { return nId; }
inline BOOL operator <( UINT16 n ) const { return nId < n; }
inline BOOL operator >( UINT16 n ) const { return nId > n; }
inline BOOL operator <=( UINT16 n ) const { return nId <= n; }
inline BOOL operator >=( UINT16 n ) const { return nId >= n; }
inline BOOL operator ==( UINT16 n ) const { return nId == n; }
inline BOOL operator !=( UINT16 n ) const { return nId != n; }
};
//------------------------------------------------------------------------
struct ComplRefData;
class TokenStack;
class ScToken;
enum E_TYPE
{
T_Id, // Id-Folge
T_Str, // String
T_D, // Double
T_RefC, // Cell Reference
T_RefA, // Area Reference
T_RN, // Range Name
T_Ext, // irgendwas Unbekanntes mit Funktionsnamen
T_Nlf, // token for natural language formula
T_Error // fuer Abfrage im Fehlerfall
};
class TokenPool
{
// !ACHTUNG!: externe Id-Basis ist 1, interne 0!
// Ausgabe Id = 0 -> Fehlerfall
private:
String** ppP_Str; // Pool fuer Strings
UINT16 nP_Str; // ...mit Groesse
UINT16 nP_StrAkt; // ...und Schreibmarke
double* pP_Dbl; // Pool fuer Doubles
UINT16 nP_Dbl;
UINT16 nP_DblAkt;
SingleRefData** ppP_RefTr; // Pool fuer Referenzen
UINT16 nP_RefTr;
UINT16 nP_RefTrAkt;
UINT16* pP_Id; // Pool fuer Id-Folgen
UINT16 nP_Id;
UINT16 nP_IdAkt;
UINT16 nP_IdLast; // letzter Folgen-Beginn
struct EXTCONT
{
DefTokenId eId;
String aText;
EXTCONT( const DefTokenId e, const String& r ) :
eId( e ), aText( r ){}
};
EXTCONT** ppP_Ext;
UINT16 nP_Ext;
UINT16 nP_ExtAkt;
struct NLFCONT
{
SingleRefData aRef;
NLFCONT( const SingleRefData& r ) : aRef( r ) {}
};
NLFCONT** ppP_Nlf;
UINT16 nP_Nlf;
UINT16 nP_NlfAkt;
UINT16* pElement; // Array mit Indizes fuer Elemente
E_TYPE* pType; // ...mit Typ-Info
UINT16* pSize; // ...mit Laengenangabe (Anz. UINT16)
UINT16 nElement;
UINT16 nElementAkt;
static const UINT16 nScTokenOff;// Offset fuer SC-Token
#ifdef DBG_UTIL
UINT16 nRek; // Rekursionszaehler
#endif
ScTokenArray* pScToken; // Tokenbastler
void GrowString( void );
void GrowDouble( void );
void GrowTripel( void );
void GrowId( void );
void GrowElement( void );
void GrowExt( void );
void GrowNlf( void );
void GetElement( const UINT16 nId );
void GetElementRek( const UINT16 nId );
public:
TokenPool( void );
~TokenPool();
inline TokenPool& operator <<( const TokenId nId );
inline TokenPool& operator <<( const DefTokenId eId );
inline TokenPool& operator <<( TokenStack& rStack );
void operator >>( TokenId& rId );
inline void operator >>( TokenStack& rStack );
inline const TokenId Store( void );
const TokenId Store( const double& rDouble );
// nur fuer Range-Names
const TokenId Store( const UINT16 nIndex );
inline const TokenId Store( const INT16 nWert );
const TokenId Store( const String& rString );
const TokenId Store( const SingleRefData& rTr );
const TokenId Store( const ComplRefData& rTr );
const TokenId Store( const DefTokenId eId, const String& rName );
// 4 externals (e.g. AddIns, Makros...)
const TokenId StoreNlf( const SingleRefData& rTr );
inline const TokenId LastId( void ) const;
inline const ScTokenArray* operator []( const TokenId nId );
void Reset( void );
inline E_TYPE GetType( const TokenId& nId ) const;
inline const SingleRefData* GetSRD( const TokenId& nId ) const;
BOOL IsSingleOp( const TokenId& nId, const DefTokenId eId ) const;
const String* GetExternal( const TokenId& nId ) const;
const String* GetString( const TokenId& nId ) const;
};
class TokenStack
// Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als
// fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert
{
private:
TokenId* pStack; // Stack als Array
UINT16 nPos; // Schreibmarke
UINT16 nSize; // Erster Index ausserhalb des Stacks
public:
TokenStack( UINT16 nNewSize = 1024 );
~TokenStack();
inline TokenStack& operator <<( const TokenId nNewId );
inline void operator >>( TokenId &rId );
inline void Reset( void );
inline bool HasMoreTokens() const { return nPos > 0; }
inline const TokenId Get( void );
};
inline const TokenId TokenStack::Get( void )
{
DBG_ASSERT( nPos > 0,
"*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." );
TokenId nRet;
if( nPos == 0 )
nRet = 0;
else
{
nPos--;
nRet = pStack[ nPos ];
}
return nRet;
}
inline TokenStack &TokenStack::operator <<( const TokenId nNewId )
{// Element auf Stack
DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" );
if( nPos < nSize )
{
pStack[ nPos ] = nNewId;
nPos++;
}
return *this;
}
inline void TokenStack::operator >>( TokenId& rId )
{// Element von Stack
DBG_ASSERT( nPos > 0,
"*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." );
if( nPos > 0 )
{
nPos--;
rId = pStack[ nPos ];
}
}
inline void TokenStack::Reset( void )
{
nPos = 0;
}
inline TokenPool& TokenPool::operator <<( const TokenId nId )
{
// POST: nId's werden hintereinander im Pool unter einer neuen Id
// abgelegt. Vorgang wird mit >> oder Store() abgeschlossen
// nId -> ( UINT16 ) nId - 1;
DBG_ASSERT( ( UINT16 ) nId < nScTokenOff,
"-TokenPool::operator <<: TokenId im DefToken-Bereich!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( const DefTokenId eId )
{
DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF,
"-TokenPool::operator<<: enmum zu gross!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( TokenStack& rStack )
{
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1;
nP_IdAkt++;
return *this;
}
inline void TokenPool::operator >>( TokenStack& rStack )
{
TokenId nId;
*this >> nId;
rStack << nId;
}
inline const TokenId TokenPool::Store( void )
{
TokenId nId;
*this >> nId;
return nId;
}
inline const TokenId TokenPool::Store( const INT16 nWert )
{
return Store( ( double ) nWert );
}
inline const TokenId TokenPool::LastId( void ) const
{
return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1!
}
const inline ScTokenArray* TokenPool::operator []( const TokenId nId )
{
pScToken->Clear();
if( nId )
{//...nur wenn nId > 0!
#ifdef DBG_UTIL
nRek = 0;
#endif
GetElement( ( UINT16 ) nId - 1 );
}
return pScToken;
}
inline E_TYPE TokenPool::GetType( const TokenId& rId ) const
{
E_TYPE nRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt )
nRet = pType[ nId ] ;
else
nRet = T_Error;
return nRet;
}
inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const
{
SingleRefData* pRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt && pType[ nId ] == T_RefC )
pRet = ppP_RefTr[ pElement[ nId ] ];
else
pRet = NULL;
return pRet;
}
#endif
<commit_msg>INTEGRATION: CWS pj75 (1.10.2); FILE MERGED 2007/03/04 16:14:07 pjanik 1.10.2.1: #i75099#: Prevent warnings on Mac OS X/gcc-4.0.1.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tokstack.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2007-03-05 14:43:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
#ifndef _TOKSTACK_HXX
#define _TOKSTACK_HXX
#ifndef _INC_STRING
#include <string.h>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif
typedef OpCode DefTokenId;
// in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16
// Unfortunately a typedef is just a dumb alias and not a real type ...
//typedef UINT16 TokenId;
struct TokenId
{
UINT16 nId;
TokenId() : nId( 0 ) {}
TokenId( UINT16 n ) : nId( n ) {}
TokenId( const TokenId& r ) : nId( r.nId ) {}
inline TokenId& operator =( const TokenId& r ) { nId = r.nId; return *this; }
inline TokenId& operator =( UINT16 n ) { nId = n; return *this; }
inline operator UINT16&() { return nId; }
inline operator const UINT16&() const { return nId; }
inline BOOL operator <( UINT16 n ) const { return nId < n; }
inline BOOL operator >( UINT16 n ) const { return nId > n; }
inline BOOL operator <=( UINT16 n ) const { return nId <= n; }
inline BOOL operator >=( UINT16 n ) const { return nId >= n; }
inline BOOL operator ==( UINT16 n ) const { return nId == n; }
inline BOOL operator !=( UINT16 n ) const { return nId != n; }
};
//------------------------------------------------------------------------
struct ComplRefData;
class TokenStack;
class ScToken;
enum E_TYPE
{
T_Id, // Id-Folge
T_Str, // String
T_D, // Double
T_RefC, // Cell Reference
T_RefA, // Area Reference
T_RN, // Range Name
T_Ext, // irgendwas Unbekanntes mit Funktionsnamen
T_Nlf, // token for natural language formula
T_Error // fuer Abfrage im Fehlerfall
};
class TokenPool
{
// !ACHTUNG!: externe Id-Basis ist 1, interne 0!
// Ausgabe Id = 0 -> Fehlerfall
private:
String** ppP_Str; // Pool fuer Strings
UINT16 nP_Str; // ...mit Groesse
UINT16 nP_StrAkt; // ...und Schreibmarke
double* pP_Dbl; // Pool fuer Doubles
UINT16 nP_Dbl;
UINT16 nP_DblAkt;
SingleRefData** ppP_RefTr; // Pool fuer Referenzen
UINT16 nP_RefTr;
UINT16 nP_RefTrAkt;
UINT16* pP_Id; // Pool fuer Id-Folgen
UINT16 nP_Id;
UINT16 nP_IdAkt;
UINT16 nP_IdLast; // letzter Folgen-Beginn
struct EXTCONT
{
DefTokenId eId;
String aText;
EXTCONT( const DefTokenId e, const String& r ) :
eId( e ), aText( r ){}
};
EXTCONT** ppP_Ext;
UINT16 nP_Ext;
UINT16 nP_ExtAkt;
struct NLFCONT
{
SingleRefData aRef;
NLFCONT( const SingleRefData& r ) : aRef( r ) {}
};
NLFCONT** ppP_Nlf;
UINT16 nP_Nlf;
UINT16 nP_NlfAkt;
UINT16* pElement; // Array mit Indizes fuer Elemente
E_TYPE* pType; // ...mit Typ-Info
UINT16* pSize; // ...mit Laengenangabe (Anz. UINT16)
UINT16 nElement;
UINT16 nElementAkt;
static const UINT16 nScTokenOff;// Offset fuer SC-Token
#ifdef DBG_UTIL
UINT16 nRek; // Rekursionszaehler
#endif
ScTokenArray* pScToken; // Tokenbastler
void GrowString( void );
void GrowDouble( void );
void GrowTripel( void );
void GrowId( void );
void GrowElement( void );
void GrowExt( void );
void GrowNlf( void );
void GetElement( const UINT16 nId );
void GetElementRek( const UINT16 nId );
public:
TokenPool( void );
~TokenPool();
inline TokenPool& operator <<( const TokenId nId );
inline TokenPool& operator <<( const DefTokenId eId );
inline TokenPool& operator <<( TokenStack& rStack );
void operator >>( TokenId& rId );
inline void operator >>( TokenStack& rStack );
inline const TokenId Store( void );
const TokenId Store( const double& rDouble );
// nur fuer Range-Names
const TokenId Store( const UINT16 nIndex );
inline const TokenId Store( const INT16 nWert );
const TokenId Store( const String& rString );
const TokenId Store( const SingleRefData& rTr );
const TokenId Store( const ComplRefData& rTr );
const TokenId Store( const DefTokenId eId, const String& rName );
// 4 externals (e.g. AddIns, Makros...)
const TokenId StoreNlf( const SingleRefData& rTr );
inline const TokenId LastId( void ) const;
inline const ScTokenArray* operator []( const TokenId nId );
void Reset( void );
inline E_TYPE GetType( const TokenId& nId ) const;
inline const SingleRefData* GetSRD( const TokenId& nId ) const;
BOOL IsSingleOp( const TokenId& nId, const DefTokenId eId ) const;
const String* GetExternal( const TokenId& nId ) const;
const String* GetString( const TokenId& nId ) const;
};
class TokenStack
// Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als
// fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert
{
private:
TokenId* pStack; // Stack als Array
UINT16 nPos; // Schreibmarke
UINT16 nSize; // Erster Index ausserhalb des Stacks
public:
TokenStack( UINT16 nNewSize = 1024 );
~TokenStack();
inline TokenStack& operator <<( const TokenId nNewId );
inline void operator >>( TokenId &rId );
inline void Reset( void );
inline bool HasMoreTokens() const { return nPos > 0; }
inline const TokenId Get( void );
};
inline const TokenId TokenStack::Get( void )
{
DBG_ASSERT( nPos > 0,
"*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." );
TokenId nRet;
if( nPos == 0 )
nRet = 0;
else
{
nPos--;
nRet = pStack[ nPos ];
}
return nRet;
}
inline TokenStack &TokenStack::operator <<( const TokenId nNewId )
{// Element auf Stack
DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" );
if( nPos < nSize )
{
pStack[ nPos ] = nNewId;
nPos++;
}
return *this;
}
inline void TokenStack::operator >>( TokenId& rId )
{// Element von Stack
DBG_ASSERT( nPos > 0,
"*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." );
if( nPos > 0 )
{
nPos--;
rId = pStack[ nPos ];
}
}
inline void TokenStack::Reset( void )
{
nPos = 0;
}
inline TokenPool& TokenPool::operator <<( const TokenId nId )
{
// POST: nId's werden hintereinander im Pool unter einer neuen Id
// abgelegt. Vorgang wird mit >> oder Store() abgeschlossen
// nId -> ( UINT16 ) nId - 1;
DBG_ASSERT( ( UINT16 ) nId < nScTokenOff,
"-TokenPool::operator <<: TokenId im DefToken-Bereich!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( const DefTokenId eId )
{
DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF,
"-TokenPool::operator<<: enmum zu gross!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( TokenStack& rStack )
{
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1;
nP_IdAkt++;
return *this;
}
inline void TokenPool::operator >>( TokenStack& rStack )
{
TokenId nId;
*this >> nId;
rStack << nId;
}
inline const TokenId TokenPool::Store( void )
{
TokenId nId;
*this >> nId;
return nId;
}
inline const TokenId TokenPool::Store( const INT16 nWert )
{
return Store( ( double ) nWert );
}
inline const TokenId TokenPool::LastId( void ) const
{
return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1!
}
const inline ScTokenArray* TokenPool::operator []( const TokenId nId )
{
pScToken->Clear();
if( nId )
{//...nur wenn nId > 0!
#ifdef DBG_UTIL
nRek = 0;
#endif
GetElement( ( UINT16 ) nId - 1 );
}
return pScToken;
}
inline E_TYPE TokenPool::GetType( const TokenId& rId ) const
{
E_TYPE nRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt )
nRet = pType[ nId ] ;
else
nRet = T_Error;
return nRet;
}
inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const
{
SingleRefData* pRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt && pType[ nId ] == T_RefC )
pRet = ppP_RefTr[ pElement[ nId ] ];
else
pRet = NULL;
return pRet;
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: drawsh2.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: sab $ $Date: 2002-11-11 13:40:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/eeitem.hxx>
#include <svx/sizeitem.hxx>
#include <svx/svdpagv.hxx>
#include <svx/xdef.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/ptitem.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdouno.hxx>
#include "drawsh.hxx"
#include "drawview.hxx"
#include "viewdata.hxx"
#include "sc.hrc"
#include "tabvwsh.hxx"
#ifndef _IPOBJ_HXX
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX
#include <svx/svdoole2.hxx>
#endif
USHORT ScGetFontWorkId(); // in drtxtob
//------------------------------------------------------------------
ScDrawShell::ScDrawShell( ScViewData* pData ) :
SfxShell(pData->GetViewShell()),
pViewData( pData )
{
SetPool( &pViewData->GetScDrawView()->GetModel()->GetItemPool() );
SetUndoManager( pViewData->GetSfxDocShell()->GetUndoManager() );
SetHelpId( HID_SCSHELL_DRAWSH );
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Drawing")));
}
ScDrawShell::~ScDrawShell()
{
}
void ScDrawShell::GetState( SfxItemSet& rSet ) // Zustaende / Toggles
{
ScDrawView* pView = pViewData->GetScDrawView();
SdrDragMode eMode = pView->GetDragMode();
rSet.Put( SfxBoolItem( SID_OBJECT_ROTATE, eMode == SDRDRAG_ROTATE ) );
rSet.Put( SfxBoolItem( SID_OBJECT_MIRROR, eMode == SDRDRAG_MIRROR ) );
rSet.Put( SfxBoolItem( SID_BEZIER_EDIT, !pView->IsFrameDragSingles() ) );
USHORT nFWId = ScGetFontWorkId();
SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame();
rSet.Put(SfxBoolItem(SID_FONTWORK, pViewFrm->HasChildWindow(nFWId)));
switch( pView->GetAnchor() )
{
case SCA_PAGE:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, TRUE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
case SCA_CELL:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, TRUE ) );
break;
default:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
}
}
void ScDrawShell::GetDrawFuncState( SfxItemSet& rSet ) // Funktionen disablen
{
ScDrawView* pView = pViewData->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkList();
ULONG nMarkCount = rMarkList.GetMarkCount();
if ( nMarkCount <= 1 || !pView->IsGroupPossible() )
rSet.DisableItem( SID_GROUP );
if ( nMarkCount == 0 || !pView->IsUnGroupPossible() )
rSet.DisableItem( SID_UNGROUP );
if ( nMarkCount != 1 || !pView->IsGroupEnterPossible() )
rSet.DisableItem( SID_ENTER_GROUP );
if ( !pView->IsGroupEntered() )
rSet.DisableItem( SID_LEAVE_GROUP );
if (!pView->IsMirrorAllowed(TRUE,TRUE))
{
rSet.DisableItem( SID_MIRROR_HORIZONTAL );
rSet.DisableItem( SID_MIRROR_VERTICAL );
}
if ( nMarkCount <= 1 ) // nichts oder nur ein Objekt selektiert
{
// Ausrichtung
rSet.DisableItem( SID_OBJECT_ALIGN_LEFT ); // keine Ausrichtung an der Seite
rSet.DisableItem( SID_OBJECT_ALIGN_CENTER );
rSet.DisableItem( SID_OBJECT_ALIGN_RIGHT );
rSet.DisableItem( SID_OBJECT_ALIGN_UP );
rSet.DisableItem( SID_OBJECT_ALIGN_MIDDLE );
rSet.DisableItem( SID_OBJECT_ALIGN_DOWN );
}
if ( !nMarkCount || pView->HasMarkedControl() )
{
// Layer von Controls darf nicht veraendert werden
rSet.DisableItem( SID_OBJECT_HEAVEN );
rSet.DisableItem( SID_OBJECT_HELL );
}
else
{
if(AreAllObjectsOnLayer(SC_LAYER_FRONT,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HEAVEN );
}
else if(AreAllObjectsOnLayer(SC_LAYER_BACK,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HELL );
}
}
BOOL bCanRename = FALSE;
if ( nMarkCount == 1 )
{
UINT16 nObjType = rMarkList.GetMark( 0 )->GetObj()->GetObjIdentifier();
if ( nObjType == OBJ_OLE2 || nObjType == OBJ_GRAF || nObjType == OBJ_GRUP )
bCanRename = TRUE;
// #91929#; don't show original size entry if not possible
if ( nObjType == OBJ_OLE2 )
{
SdrOle2Obj* pOleObj = static_cast<SdrOle2Obj*>(rMarkList.GetMark( 0 )->GetObj());
if (pOleObj && ((pOleObj->GetObjRef()->GetMiscStatus() & SVOBJ_MISCSTATUS_SERVERRESIZE) == SVOBJ_MISCSTATUS_SERVERRESIZE))
rSet.DisableItem(SID_ORIGINALSIZE);
}
}
if ( !bCanRename )
rSet.DisableItem( SID_RENAME_OBJECT );
if ( !nMarkCount ) // nichts selektiert
{
// Anordnung
rSet.DisableItem( SID_FRAME_UP );
rSet.DisableItem( SID_FRAME_DOWN );
rSet.DisableItem( SID_FRAME_TO_TOP );
rSet.DisableItem( SID_FRAME_TO_BOTTOM );
// Clipboard / loeschen
rSet.DisableItem( SID_DELETE );
rSet.DisableItem( SID_DELETE_CONTENTS );
rSet.DisableItem( SID_CUT );
rSet.DisableItem( SID_COPY );
// sonstiges
rSet.DisableItem( SID_ANCHOR_TOGGLE );
rSet.DisableItem( SID_ORIGINALSIZE );
rSet.DisableItem( SID_ATTR_TRANSFORM );
}
if ( rSet.GetItemState( SID_ENABLE_HYPHENATION ) != SFX_ITEM_UNKNOWN )
{
SfxItemSet aAttrs( pView->GetModel()->GetItemPool() );
pView->GetAttributes( aAttrs );
if( aAttrs.GetItemState( EE_PARA_HYPHENATE ) >= SFX_ITEM_AVAILABLE )
{
BOOL bValue = ( (const SfxBoolItem&) aAttrs.Get( EE_PARA_HYPHENATE ) ).GetValue();
rSet.Put( SfxBoolItem( SID_ENABLE_HYPHENATION, bValue ) );
}
}
}
//
// Attribute fuer Drawing-Objekte
//
void ScDrawShell::GetDrawAttrState( SfxItemSet& rSet )
{
Point aMousePos = pViewData->GetMousePosPixel();
Window* pWindow = pViewData->GetActiveWin();
ScDrawView* pDrView = pViewData->GetScDrawView();
Point aPos = pWindow->PixelToLogic(aMousePos);
BOOL bHasMarked = pDrView->HasMarkedObj();
if( bHasMarked )
{
rSet.Put( pDrView->GetAttrFromMarked(FALSE) );
// Wenn die View selektierte Objekte besitzt, muessen entspr. Items
// von SFX_ITEM_DEFAULT (_ON) auf SFX_ITEM_DISABLED geaendert werden
SfxWhichIter aIter( rSet, XATTR_LINE_FIRST, XATTR_FILL_LAST );
USHORT nWhich = aIter.FirstWhich();
while( nWhich )
{
if( SFX_ITEM_DEFAULT == rSet.GetItemState( nWhich ) )
rSet.DisableItem( nWhich );
nWhich = aIter.NextWhich();
}
}
else
rSet.Put( pDrView->GetDefaultAttr() );
// Position- und Groesse-Items
if ( pDrView->IsAction() )
{
Rectangle aRect;
pDrView->TakeActionRect( aRect );
if ( aRect.IsEmpty() )
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
else
{
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SfxPointItem( SID_ATTR_POSITION, aRect.TopLeft() ) );
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top() ) ) );
}
}
else
{
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
if ( bHasMarked )
{
Rectangle aRect = pDrView->GetAllMarkedRect();
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top()) ) );
}
else
rSet.Put( SvxSizeItem( SID_ATTR_SIZE, Size( 0, 0 ) ) );
}
}
void ScDrawShell::GetAttrFuncState(SfxItemSet &rSet)
{
// Dialoge fuer Draw-Attribute disablen, wenn noetig
ScDrawView* pDrView = pViewData->GetScDrawView();
SfxItemSet aViewSet = pDrView->GetAttrFromMarked(FALSE);
if ( aViewSet.GetItemState( XATTR_LINESTYLE ) == SFX_ITEM_DEFAULT )
{
rSet.DisableItem( SID_ATTRIBUTES_LINE );
rSet.DisableItem( SID_ATTR_LINEEND_STYLE ); // Tbx-Controller
}
if ( aViewSet.GetItemState( XATTR_FILLSTYLE ) == SFX_ITEM_DEFAULT )
rSet.DisableItem( SID_ATTRIBUTES_AREA );
}
BOOL ScDrawShell::AreAllObjectsOnLayer(USHORT nLayerNo,const SdrMarkList& rMark)
{
BOOL bResult=TRUE;
ULONG nCount = rMark.GetMarkCount();
for (ULONG i=0; i<nCount; i++)
{
SdrObject* pObj = rMark.GetMark(i)->GetObj();
if ( !pObj->ISA(SdrUnoObj) )
{
if(nLayerNo!=pObj->GetLayer())
{
bResult=FALSE;
break;
}
}
}
return bResult;
}
<commit_msg>#91929#; test whether SvInPlaceObject is<commit_after>/*************************************************************************
*
* $RCSfile: drawsh2.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: sab $ $Date: 2002-11-11 13:59:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/eeitem.hxx>
#include <svx/sizeitem.hxx>
#include <svx/svdpagv.hxx>
#include <svx/xdef.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/ptitem.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdouno.hxx>
#include "drawsh.hxx"
#include "drawview.hxx"
#include "viewdata.hxx"
#include "sc.hrc"
#include "tabvwsh.hxx"
#ifndef _IPOBJ_HXX
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX
#include <svx/svdoole2.hxx>
#endif
USHORT ScGetFontWorkId(); // in drtxtob
//------------------------------------------------------------------
ScDrawShell::ScDrawShell( ScViewData* pData ) :
SfxShell(pData->GetViewShell()),
pViewData( pData )
{
SetPool( &pViewData->GetScDrawView()->GetModel()->GetItemPool() );
SetUndoManager( pViewData->GetSfxDocShell()->GetUndoManager() );
SetHelpId( HID_SCSHELL_DRAWSH );
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Drawing")));
}
ScDrawShell::~ScDrawShell()
{
}
void ScDrawShell::GetState( SfxItemSet& rSet ) // Zustaende / Toggles
{
ScDrawView* pView = pViewData->GetScDrawView();
SdrDragMode eMode = pView->GetDragMode();
rSet.Put( SfxBoolItem( SID_OBJECT_ROTATE, eMode == SDRDRAG_ROTATE ) );
rSet.Put( SfxBoolItem( SID_OBJECT_MIRROR, eMode == SDRDRAG_MIRROR ) );
rSet.Put( SfxBoolItem( SID_BEZIER_EDIT, !pView->IsFrameDragSingles() ) );
USHORT nFWId = ScGetFontWorkId();
SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame();
rSet.Put(SfxBoolItem(SID_FONTWORK, pViewFrm->HasChildWindow(nFWId)));
switch( pView->GetAnchor() )
{
case SCA_PAGE:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, TRUE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
case SCA_CELL:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, TRUE ) );
break;
default:
rSet.Put( SfxBoolItem( SID_ANCHOR_PAGE, FALSE ) );
rSet.Put( SfxBoolItem( SID_ANCHOR_CELL, FALSE ) );
break;
}
}
void ScDrawShell::GetDrawFuncState( SfxItemSet& rSet ) // Funktionen disablen
{
ScDrawView* pView = pViewData->GetScDrawView();
const SdrMarkList& rMarkList = pView->GetMarkList();
ULONG nMarkCount = rMarkList.GetMarkCount();
if ( nMarkCount <= 1 || !pView->IsGroupPossible() )
rSet.DisableItem( SID_GROUP );
if ( nMarkCount == 0 || !pView->IsUnGroupPossible() )
rSet.DisableItem( SID_UNGROUP );
if ( nMarkCount != 1 || !pView->IsGroupEnterPossible() )
rSet.DisableItem( SID_ENTER_GROUP );
if ( !pView->IsGroupEntered() )
rSet.DisableItem( SID_LEAVE_GROUP );
if (!pView->IsMirrorAllowed(TRUE,TRUE))
{
rSet.DisableItem( SID_MIRROR_HORIZONTAL );
rSet.DisableItem( SID_MIRROR_VERTICAL );
}
if ( nMarkCount <= 1 ) // nichts oder nur ein Objekt selektiert
{
// Ausrichtung
rSet.DisableItem( SID_OBJECT_ALIGN_LEFT ); // keine Ausrichtung an der Seite
rSet.DisableItem( SID_OBJECT_ALIGN_CENTER );
rSet.DisableItem( SID_OBJECT_ALIGN_RIGHT );
rSet.DisableItem( SID_OBJECT_ALIGN_UP );
rSet.DisableItem( SID_OBJECT_ALIGN_MIDDLE );
rSet.DisableItem( SID_OBJECT_ALIGN_DOWN );
}
if ( !nMarkCount || pView->HasMarkedControl() )
{
// Layer von Controls darf nicht veraendert werden
rSet.DisableItem( SID_OBJECT_HEAVEN );
rSet.DisableItem( SID_OBJECT_HELL );
}
else
{
if(AreAllObjectsOnLayer(SC_LAYER_FRONT,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HEAVEN );
}
else if(AreAllObjectsOnLayer(SC_LAYER_BACK,rMarkList))
{
rSet.DisableItem( SID_OBJECT_HELL );
}
}
BOOL bCanRename = FALSE;
if ( nMarkCount == 1 )
{
UINT16 nObjType = rMarkList.GetMark( 0 )->GetObj()->GetObjIdentifier();
if ( nObjType == OBJ_OLE2 || nObjType == OBJ_GRAF || nObjType == OBJ_GRUP )
bCanRename = TRUE;
// #91929#; don't show original size entry if not possible
if ( nObjType == OBJ_OLE2 )
{
SdrOle2Obj* pOleObj = static_cast<SdrOle2Obj*>(rMarkList.GetMark( 0 )->GetObj());
if (pOleObj->GetObjRef().Is() && ((pOleObj->GetObjRef()->GetMiscStatus() & SVOBJ_MISCSTATUS_SERVERRESIZE) == SVOBJ_MISCSTATUS_SERVERRESIZE))
rSet.DisableItem(SID_ORIGINALSIZE);
}
}
if ( !bCanRename )
rSet.DisableItem( SID_RENAME_OBJECT );
if ( !nMarkCount ) // nichts selektiert
{
// Anordnung
rSet.DisableItem( SID_FRAME_UP );
rSet.DisableItem( SID_FRAME_DOWN );
rSet.DisableItem( SID_FRAME_TO_TOP );
rSet.DisableItem( SID_FRAME_TO_BOTTOM );
// Clipboard / loeschen
rSet.DisableItem( SID_DELETE );
rSet.DisableItem( SID_DELETE_CONTENTS );
rSet.DisableItem( SID_CUT );
rSet.DisableItem( SID_COPY );
// sonstiges
rSet.DisableItem( SID_ANCHOR_TOGGLE );
rSet.DisableItem( SID_ORIGINALSIZE );
rSet.DisableItem( SID_ATTR_TRANSFORM );
}
if ( rSet.GetItemState( SID_ENABLE_HYPHENATION ) != SFX_ITEM_UNKNOWN )
{
SfxItemSet aAttrs( pView->GetModel()->GetItemPool() );
pView->GetAttributes( aAttrs );
if( aAttrs.GetItemState( EE_PARA_HYPHENATE ) >= SFX_ITEM_AVAILABLE )
{
BOOL bValue = ( (const SfxBoolItem&) aAttrs.Get( EE_PARA_HYPHENATE ) ).GetValue();
rSet.Put( SfxBoolItem( SID_ENABLE_HYPHENATION, bValue ) );
}
}
}
//
// Attribute fuer Drawing-Objekte
//
void ScDrawShell::GetDrawAttrState( SfxItemSet& rSet )
{
Point aMousePos = pViewData->GetMousePosPixel();
Window* pWindow = pViewData->GetActiveWin();
ScDrawView* pDrView = pViewData->GetScDrawView();
Point aPos = pWindow->PixelToLogic(aMousePos);
BOOL bHasMarked = pDrView->HasMarkedObj();
if( bHasMarked )
{
rSet.Put( pDrView->GetAttrFromMarked(FALSE) );
// Wenn die View selektierte Objekte besitzt, muessen entspr. Items
// von SFX_ITEM_DEFAULT (_ON) auf SFX_ITEM_DISABLED geaendert werden
SfxWhichIter aIter( rSet, XATTR_LINE_FIRST, XATTR_FILL_LAST );
USHORT nWhich = aIter.FirstWhich();
while( nWhich )
{
if( SFX_ITEM_DEFAULT == rSet.GetItemState( nWhich ) )
rSet.DisableItem( nWhich );
nWhich = aIter.NextWhich();
}
}
else
rSet.Put( pDrView->GetDefaultAttr() );
// Position- und Groesse-Items
if ( pDrView->IsAction() )
{
Rectangle aRect;
pDrView->TakeActionRect( aRect );
if ( aRect.IsEmpty() )
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
else
{
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SfxPointItem( SID_ATTR_POSITION, aRect.TopLeft() ) );
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top() ) ) );
}
}
else
{
rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
if ( bHasMarked )
{
Rectangle aRect = pDrView->GetAllMarkedRect();
pDrView->GetPageViewPvNum(0)->LogicToPagePos(aRect);
rSet.Put( SvxSizeItem( SID_ATTR_SIZE,
Size( aRect.Right() - aRect.Left(),
aRect.Bottom() - aRect.Top()) ) );
}
else
rSet.Put( SvxSizeItem( SID_ATTR_SIZE, Size( 0, 0 ) ) );
}
}
void ScDrawShell::GetAttrFuncState(SfxItemSet &rSet)
{
// Dialoge fuer Draw-Attribute disablen, wenn noetig
ScDrawView* pDrView = pViewData->GetScDrawView();
SfxItemSet aViewSet = pDrView->GetAttrFromMarked(FALSE);
if ( aViewSet.GetItemState( XATTR_LINESTYLE ) == SFX_ITEM_DEFAULT )
{
rSet.DisableItem( SID_ATTRIBUTES_LINE );
rSet.DisableItem( SID_ATTR_LINEEND_STYLE ); // Tbx-Controller
}
if ( aViewSet.GetItemState( XATTR_FILLSTYLE ) == SFX_ITEM_DEFAULT )
rSet.DisableItem( SID_ATTRIBUTES_AREA );
}
BOOL ScDrawShell::AreAllObjectsOnLayer(USHORT nLayerNo,const SdrMarkList& rMark)
{
BOOL bResult=TRUE;
ULONG nCount = rMark.GetMarkCount();
for (ULONG i=0; i<nCount; i++)
{
SdrObject* pObj = rMark.GetMark(i)->GetObj();
if ( !pObj->ISA(SdrUnoObj) )
{
if(nLayerNo!=pObj->GetLayer())
{
bResult=FALSE;
break;
}
}
}
return bResult;
}
<|endoftext|> |
<commit_before>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include <queue>
#include <uv.h>
#include "lib/OSXAudioInput.h"
#include "lib/OSXAudioInput.cc"
/**
* # Audio Classes
*
* Thanks to:
* - Justin Latimer: https://github.com/justinlatimer (node-midi, which this
* module is adapted from.
*/
using namespace node;
const char* symbol_emit = "emit";
const char* symbol_message = "message";
class AudioInput : public ObjectWrap
{
private:
OSXAudioInput* in;
public:
uv_async_t message_async;
uv_mutex_t message_mutex;
struct AudioMessage
{
char* message;
UInt32 size;
};
std::queue<AudioMessage*> message_queue;
static v8::Persistent<v8::FunctionTemplate> s_ct;
static void Init(v8::Handle<v8::Object> target)
{
v8::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
s_ct = v8::Persistent<v8::FunctionTemplate>::New(t);
s_ct->InstanceTemplate()->SetInternalFieldCount(1);
s_ct->SetClassName(v8::String::NewSymbol("AudioInput"));
NODE_SET_PROTOTYPE_METHOD(s_ct, "openInput", OpenInput);
NODE_SET_PROTOTYPE_METHOD(s_ct, "closeInput", CloseInput);
target->Set(v8::String::NewSymbol("input"),
s_ct->GetFunction());
}
AudioInput()
{
in = new OSXAudioInput();
uv_mutex_init(&message_mutex);
}
~AudioInput()
{
in->closeInput();
delete in;
uv_mutex_destroy(&message_mutex);
}
static void EmitMessage(uv_async_t *w, int status)
{
assert(status == 0);
v8::HandleScope scope;
AudioInput *input = static_cast<AudioInput*>(w->data);
uv_mutex_lock(&input->message_mutex);
while (!input->message_queue.empty())
{
AudioMessage* message = input->message_queue.front();
v8::Local<v8::Value> args[3];
args[0] = v8::String::New(symbol_message);
args[1] = v8::Local<v8::Value>::New(v8::Number::New(message->size));
// create the node buffer for audio data
node::Buffer *slowBuffer = node::Buffer::New(message->size);
memcpy(node::Buffer::Data(slowBuffer), message->message, message->size);
v8::Local<v8::Object> globalObj = v8::Context::GetCurrent()->Global();
v8::Local<v8::Function> bufferConstructor = v8::Local<v8::Function>::Cast(globalObj->Get(v8::String::New("Buffer")));
v8::Handle<v8::Value> constructorArgs[3] = { slowBuffer->handle_, v8::Integer::New(message->size), v8::Integer::New(0) };
args[2] = bufferConstructor->NewInstance(3, constructorArgs);
MakeCallback(input->handle_, symbol_emit, 3, args);
input->message_queue.pop();
delete message;
}
uv_mutex_unlock(&input->message_mutex);
}
static void Callback(UInt32 size, char *message, void *userData)
{
AudioInput *input = static_cast<AudioInput*>(userData);
AudioMessage* data = new AudioMessage();
data->message = message;
data->size = size;
uv_mutex_lock(&input->message_mutex);
input->message_queue.push(data);
uv_mutex_unlock(&input->message_mutex);
uv_async_send(&input->message_async);
}
static v8::Handle<v8::Value> New(const v8::Arguments& args)
{
v8::HandleScope scope;
if (!args.IsConstructCall()) {
return ThrowException(v8::Exception::TypeError(
v8::String::New("Use the new operator to create instances of this object.")));
}
AudioInput* input = new AudioInput();
input->message_async.data = input;
uv_async_init(uv_default_loop(), &input->message_async, AudioInput::EmitMessage);
input->Wrap(args.This());
return args.This();
}
static v8::Handle<v8::Value> OpenInput(const v8::Arguments& args)
{
v8::HandleScope scope;
AudioInput* input = ObjectWrap::Unwrap<AudioInput>(args.This());
input->Ref();
input->in->openInput(&AudioInput::Callback, ObjectWrap::Unwrap<AudioInput>(args.This()));
return scope.Close(v8::Undefined());
}
static v8::Handle<v8::Value> CloseInput(const v8::Arguments& args)
{
v8::HandleScope scope;
AudioInput* input = ObjectWrap::Unwrap<AudioInput>(args.This());
input->in->closeInput();
uv_close((uv_handle_t*)&input->message_async, NULL);
return scope.Close(v8::Undefined());
}
};
v8::Persistent<v8::FunctionTemplate> AudioInput::s_ct;
extern "C" {
void init (v8::Handle<v8::Object> target)
{
AudioInput::Init(target);
}
NODE_MODULE(audio, init)
}
<commit_msg>adjust buffer size correctly.<commit_after>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include <queue>
#include <uv.h>
#include "lib/OSXAudioInput.h"
#include "lib/OSXAudioInput.cc"
/**
* # Audio Classes
*
* Thanks to:
* - Justin Latimer: https://github.com/justinlatimer (node-midi, which this
* module is adapted from.
*/
using namespace node;
const char* symbol_emit = "emit";
const char* symbol_message = "message";
class AudioInput : public ObjectWrap
{
private:
OSXAudioInput* in;
public:
uv_async_t message_async;
uv_mutex_t message_mutex;
struct AudioMessage
{
char* message;
UInt32 size;
};
std::queue<AudioMessage*> message_queue;
static v8::Persistent<v8::FunctionTemplate> s_ct;
static void Init(v8::Handle<v8::Object> target)
{
v8::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
s_ct = v8::Persistent<v8::FunctionTemplate>::New(t);
s_ct->InstanceTemplate()->SetInternalFieldCount(1);
s_ct->SetClassName(v8::String::NewSymbol("AudioInput"));
NODE_SET_PROTOTYPE_METHOD(s_ct, "openInput", OpenInput);
NODE_SET_PROTOTYPE_METHOD(s_ct, "closeInput", CloseInput);
target->Set(v8::String::NewSymbol("input"),
s_ct->GetFunction());
}
AudioInput()
{
in = new OSXAudioInput();
uv_mutex_init(&message_mutex);
}
~AudioInput()
{
in->closeInput();
delete in;
uv_mutex_destroy(&message_mutex);
}
static void EmitMessage(uv_async_t *w, int status)
{
assert(status == 0);
v8::HandleScope scope;
AudioInput *input = static_cast<AudioInput*>(w->data);
uv_mutex_lock(&input->message_mutex);
while (!input->message_queue.empty())
{
AudioMessage* message = input->message_queue.front();
v8::Local<v8::Value> args[3];
args[0] = v8::String::New(symbol_message);
args[1] = v8::Local<v8::Value>::New(v8::Number::New(message->size));
// create the node buffer for audio data
node::Buffer *slowBuffer = node::Buffer::New(message->size);
memcpy(node::Buffer::Data(slowBuffer), message->message, message->size);
v8::Local<v8::Object> globalObj = v8::Context::GetCurrent()->Global();
v8::Local<v8::Function> bufferConstructor = v8::Local<v8::Function>::Cast(globalObj->Get(v8::String::New("Buffer")));
v8::Handle<v8::Value> constructorArgs[3] = { slowBuffer->handle_, v8::Integer::New(message->size), v8::Integer::New(0) };
args[2] = bufferConstructor->NewInstance(3, constructorArgs);
MakeCallback(input->handle_, symbol_emit, 3, args);
input->message_queue.pop();
delete message;
}
uv_mutex_unlock(&input->message_mutex);
}
static void Callback(UInt32 size, char *message, void *userData)
{
AudioInput *input = static_cast<AudioInput*>(userData);
AudioMessage* data = new AudioMessage();
data->message = message;
data->size = size * 4;
uv_mutex_lock(&input->message_mutex);
input->message_queue.push(data);
uv_mutex_unlock(&input->message_mutex);
uv_async_send(&input->message_async);
}
static v8::Handle<v8::Value> New(const v8::Arguments& args)
{
v8::HandleScope scope;
if (!args.IsConstructCall()) {
return ThrowException(v8::Exception::TypeError(
v8::String::New("Use the new operator to create instances of this object.")));
}
AudioInput* input = new AudioInput();
input->message_async.data = input;
uv_async_init(uv_default_loop(), &input->message_async, AudioInput::EmitMessage);
input->Wrap(args.This());
return args.This();
}
static v8::Handle<v8::Value> OpenInput(const v8::Arguments& args)
{
v8::HandleScope scope;
AudioInput* input = ObjectWrap::Unwrap<AudioInput>(args.This());
input->Ref();
input->in->openInput(&AudioInput::Callback, ObjectWrap::Unwrap<AudioInput>(args.This()));
return scope.Close(v8::Undefined());
}
static v8::Handle<v8::Value> CloseInput(const v8::Arguments& args)
{
v8::HandleScope scope;
AudioInput* input = ObjectWrap::Unwrap<AudioInput>(args.This());
input->in->closeInput();
uv_close((uv_handle_t*)&input->message_async, NULL);
return scope.Close(v8::Undefined());
}
};
v8::Persistent<v8::FunctionTemplate> AudioInput::s_ct;
extern "C" {
void init (v8::Handle<v8::Object> target)
{
AudioInput::Init(target);
}
NODE_MODULE(audio, init)
}
<|endoftext|> |
<commit_before>#include "driveredit.h"
#include "ui_driveredit.h"
#include <QFileDialog>
string toStdString(const QString& s);
DriverEdit::DriverEdit(RobotWorld* _world,WorldSimulation* _sim,QWidget *parent) :
QDialog(parent),
ui(new Ui::DriverEdit),
world(_world),sim(_sim),robot(NULL),current(0)
{
ui->setupUi(this);
if(world->robots.size() > 0) {
robot=world->robots[0].get();
addDrivers(robot->driverNames);
}
RequestDriverParameters();
ui->slider->setValue(500);
}
DriverEdit::~DriverEdit()
{
delete ui;
}
void DriverEdit::RequestDriverValue(){
if(robot) {
value=robot->GetDriverValue(current);
ui->doubleSpinBox->setValue(value);
HandleSpinBox(value);
}
}
void DriverEdit::RequestDriverParameters(){
//emit GetDriverValues(index);
if(robot) {
Assert(current >= 0 && current < (int)robot->drivers.size());
Vector2 limits=robot->GetDriverLimits(current);
min=limits[0];
max=limits[1];
value=robot->GetDriverValue(current);
ui->lbl_max->setText(QString::number(max));
ui->lbl_min->setText(QString::number(min));
ui->doubleSpinBox->setMaximum(max);
ui->doubleSpinBox->setMinimum(min);
ui->doubleSpinBox->setValue(value);
ui->kPSpinBox->setMaximum(Max(robot->drivers[current].servoP*2.0,100.0));
ui->kPSpinBox->setValue(robot->drivers[current].servoP);
ui->kDSpinBox->setMaximum(Max(robot->drivers[current].servoD*2.0,100.0));
ui->kDSpinBox->setValue(robot->drivers[current].servoD);
ui->kISpinBox->setMaximum(Max(robot->drivers[current].servoI*2.0,100.0));
ui->kISpinBox->setValue(robot->drivers[current].servoI);
ui->dryFrictionSpinBox->setMaximum(Max(robot->drivers[current].dryFriction*2.0,10.0));
ui->dryFrictionSpinBox->setValue(robot->drivers[current].dryFriction);
ui->viscousFrictionSpinBox->setMaximum(Max(robot->drivers[current].viscousFriction*2.0,10.0));
ui->viscousFrictionSpinBox->setValue(robot->drivers[current].viscousFriction);
if(!IsFinite(robot->drivers[current].vmax)) {
ui->vmaxSpinBox->setMaximum(10000);
ui->vmaxSpinBox->setValue(10000);
}
else {
ui->vmaxSpinBox->setMaximum(Max(robot->drivers[current].vmax*2,10.0));
ui->vmaxSpinBox->setValue(robot->drivers[current].vmax);
}
if(!IsFinite(robot->drivers[current].amax)) {
ui->amaxSpinBox->setMaximum(10000);
ui->amaxSpinBox->setValue(10000);
}
else {
ui->amaxSpinBox->setMaximum(Max(robot->drivers[current].amax*2,100.0));
ui->amaxSpinBox->setValue(robot->drivers[current].amax);
}
if(!IsFinite(robot->drivers[current].tmax)) {
ui->tmaxSpinBox->setMaximum(10000);
ui->tmaxSpinBox->setValue(10000);
}
else {
ui->tmaxSpinBox->setMaximum(Max(robot->drivers[current].tmax*2,100.0));
ui->tmaxSpinBox->setValue(robot->drivers[current].tmax);
}
HandleSpinBox(value);
}
//current=index;
}
void DriverEdit::NewSelection(int _current){
current=_current;
RequestDriverParameters();
}
void DriverEdit::AddDriver(QString name){
ui->comboBox->addItem(name);
}
void DriverEdit::addDrivers(vector<string> drivers){
for(int i=0;i<drivers.size();i++)
ui->comboBox->addItem(QString::fromStdString(drivers[i]));
}
void DriverEdit::SendDriverValue(){
float value=ui->doubleSpinBox->value();
emit SetDriverValue(current,value);
}
void DriverEdit::HandleSlider(int pos){
float inc=(max-min)/1000;
value=min+inc*pos;
ui->doubleSpinBox->setValue(value);
SendDriverValue();
}
void DriverEdit::HandleSpinBox(double _value){
if(value==_value)return;//looping
value=_value;
float range=max-min;
float relative=value-min;
ui->slider->setValue(relative/range*1000);
SendDriverValue();
}
void DriverEdit::HandleKP(double _value){
if(robot==NULL) return;
robot->drivers[current].servoP = _value;
if(sim)
sim->controlSimulators[0].command.actuators[current].kP = _value;
ui->kPSpinBox->setMaximum(Max(ui->kPSpinBox->maximum(),robot->drivers[current].servoP*2.0,100.0));
}
void DriverEdit::HandleKD(double _value){
if(robot==NULL) return;
robot->drivers[current].servoD = _value;
if(sim)
sim->controlSimulators[0].command.actuators[current].kD = _value;
ui->kDSpinBox->setMaximum(Max(ui->kDSpinBox->maximum(),robot->drivers[current].servoD*2.0,100.0));
}
void DriverEdit::HandleKI(double _value){
if(robot==NULL) return;
robot->drivers[current].servoI = _value;
if(sim)
sim->controlSimulators[0].command.actuators[current].kI = _value;
ui->kISpinBox->setMaximum(Max(ui->kISpinBox->maximum(),robot->drivers[current].servoI*2.0,100.0));
}
void DriverEdit::HandleDryFriction(double _value){
if(robot==NULL) return;
robot->drivers[current].dryFriction = _value;
ui->dryFrictionSpinBox->setMaximum(Max(ui->dryFrictionSpinBox->maximum(),robot->drivers[current].dryFriction*2.0,10.0));
}
void DriverEdit::HandleViscousFriction(double _value){
if(robot==NULL) return;
robot->drivers[current].viscousFriction = _value;
ui->viscousFrictionSpinBox->setMaximum(Max(ui->viscousFrictionSpinBox->maximum(),robot->drivers[current].viscousFriction*2.0,10.0));
}
void DriverEdit::HandleVmax(double _value){
if(robot==NULL) return;
robot->drivers[current].vmax = _value;
robot->drivers[current].vmin = -_value;
ui->vmaxSpinBox->setMaximum(Max(ui->vmaxSpinBox->maximum(),robot->drivers[current].vmax*2,10.0));
}
void DriverEdit::HandleAmax(double _value){
if(robot==NULL) return;
robot->drivers[current].amax = _value;
robot->drivers[current].amin = -_value;
ui->amaxSpinBox->setMaximum(Max(ui->amaxSpinBox->maximum(),robot->drivers[current].amax*2,100.0));
}
void DriverEdit::HandleTmax(double _value){
if(robot==NULL) return;
robot->drivers[current].tmax = _value;
robot->drivers[current].tmin = -_value;
ui->tmaxSpinBox->setMaximum(Max(ui->tmaxSpinBox->maximum(),robot->drivers[current].tmax*2,100.0));
}
void DriverEdit::SaveSettings()
{
if(robot==NULL) return;
QString filename = QFileDialog::getSaveFileName(0, "Modified robot file", QString(), "Robot (*.rob *.urdf);;All Files (*)");
if (filename.isNull()) return;
robot->Save(toStdString(filename).c_str());
}<commit_msg>fixed crash when robots have no drivers<commit_after>#include "driveredit.h"
#include "ui_driveredit.h"
#include <QFileDialog>
string toStdString(const QString& s);
DriverEdit::DriverEdit(RobotWorld* _world,WorldSimulation* _sim,QWidget *parent) :
QDialog(parent),
ui(new Ui::DriverEdit),
world(_world),sim(_sim),robot(NULL),current(0)
{
ui->setupUi(this);
if(world->robots.size() > 0) {
robot=world->robots[0].get();
addDrivers(robot->driverNames);
}
if(!robot || robot->drivers.size()==0)
current = -1;
RequestDriverParameters();
ui->slider->setValue(500);
}
DriverEdit::~DriverEdit()
{
delete ui;
}
void DriverEdit::RequestDriverValue(){
if(robot) {
value=robot->GetDriverValue(current);
ui->doubleSpinBox->setValue(value);
HandleSpinBox(value);
}
}
void DriverEdit::RequestDriverParameters(){
//emit GetDriverValues(index);
if(!robot) return;
if(current < 0) return;
Assert(current >= 0 && current < (int)robot->drivers.size());
Vector2 limits=robot->GetDriverLimits(current);
min=limits[0];
max=limits[1];
value=robot->GetDriverValue(current);
ui->lbl_max->setText(QString::number(max));
ui->lbl_min->setText(QString::number(min));
ui->doubleSpinBox->setMaximum(max);
ui->doubleSpinBox->setMinimum(min);
ui->doubleSpinBox->setValue(value);
ui->kPSpinBox->setMaximum(Max(robot->drivers[current].servoP*2.0,100.0));
ui->kPSpinBox->setValue(robot->drivers[current].servoP);
ui->kDSpinBox->setMaximum(Max(robot->drivers[current].servoD*2.0,100.0));
ui->kDSpinBox->setValue(robot->drivers[current].servoD);
ui->kISpinBox->setMaximum(Max(robot->drivers[current].servoI*2.0,100.0));
ui->kISpinBox->setValue(robot->drivers[current].servoI);
ui->dryFrictionSpinBox->setMaximum(Max(robot->drivers[current].dryFriction*2.0,10.0));
ui->dryFrictionSpinBox->setValue(robot->drivers[current].dryFriction);
ui->viscousFrictionSpinBox->setMaximum(Max(robot->drivers[current].viscousFriction*2.0,10.0));
ui->viscousFrictionSpinBox->setValue(robot->drivers[current].viscousFriction);
if(!IsFinite(robot->drivers[current].vmax)) {
ui->vmaxSpinBox->setMaximum(10000);
ui->vmaxSpinBox->setValue(10000);
}
else {
ui->vmaxSpinBox->setMaximum(Max(robot->drivers[current].vmax*2,10.0));
ui->vmaxSpinBox->setValue(robot->drivers[current].vmax);
}
if(!IsFinite(robot->drivers[current].amax)) {
ui->amaxSpinBox->setMaximum(10000);
ui->amaxSpinBox->setValue(10000);
}
else {
ui->amaxSpinBox->setMaximum(Max(robot->drivers[current].amax*2,100.0));
ui->amaxSpinBox->setValue(robot->drivers[current].amax);
}
if(!IsFinite(robot->drivers[current].tmax)) {
ui->tmaxSpinBox->setMaximum(10000);
ui->tmaxSpinBox->setValue(10000);
}
else {
ui->tmaxSpinBox->setMaximum(Max(robot->drivers[current].tmax*2,100.0));
ui->tmaxSpinBox->setValue(robot->drivers[current].tmax);
}
HandleSpinBox(value);
}
void DriverEdit::NewSelection(int _current){
current=_current;
RequestDriverParameters();
}
void DriverEdit::AddDriver(QString name){
ui->comboBox->addItem(name);
}
void DriverEdit::addDrivers(vector<string> drivers){
for(int i=0;i<drivers.size();i++)
ui->comboBox->addItem(QString::fromStdString(drivers[i]));
}
void DriverEdit::SendDriverValue(){
float value=ui->doubleSpinBox->value();
emit SetDriverValue(current,value);
}
void DriverEdit::HandleSlider(int pos){
float inc=(max-min)/1000;
value=min+inc*pos;
ui->doubleSpinBox->setValue(value);
SendDriverValue();
}
void DriverEdit::HandleSpinBox(double _value){
if(value==_value)return;//looping
value=_value;
float range=max-min;
float relative=value-min;
ui->slider->setValue(relative/range*1000);
SendDriverValue();
}
void DriverEdit::HandleKP(double _value){
if(robot==NULL) return;
robot->drivers[current].servoP = _value;
if(sim)
sim->controlSimulators[0].command.actuators[current].kP = _value;
ui->kPSpinBox->setMaximum(Max(ui->kPSpinBox->maximum(),robot->drivers[current].servoP*2.0,100.0));
}
void DriverEdit::HandleKD(double _value){
if(robot==NULL) return;
robot->drivers[current].servoD = _value;
if(sim)
sim->controlSimulators[0].command.actuators[current].kD = _value;
ui->kDSpinBox->setMaximum(Max(ui->kDSpinBox->maximum(),robot->drivers[current].servoD*2.0,100.0));
}
void DriverEdit::HandleKI(double _value){
if(robot==NULL) return;
robot->drivers[current].servoI = _value;
if(sim)
sim->controlSimulators[0].command.actuators[current].kI = _value;
ui->kISpinBox->setMaximum(Max(ui->kISpinBox->maximum(),robot->drivers[current].servoI*2.0,100.0));
}
void DriverEdit::HandleDryFriction(double _value){
if(robot==NULL) return;
robot->drivers[current].dryFriction = _value;
ui->dryFrictionSpinBox->setMaximum(Max(ui->dryFrictionSpinBox->maximum(),robot->drivers[current].dryFriction*2.0,10.0));
}
void DriverEdit::HandleViscousFriction(double _value){
if(robot==NULL) return;
robot->drivers[current].viscousFriction = _value;
ui->viscousFrictionSpinBox->setMaximum(Max(ui->viscousFrictionSpinBox->maximum(),robot->drivers[current].viscousFriction*2.0,10.0));
}
void DriverEdit::HandleVmax(double _value){
if(robot==NULL) return;
robot->drivers[current].vmax = _value;
robot->drivers[current].vmin = -_value;
ui->vmaxSpinBox->setMaximum(Max(ui->vmaxSpinBox->maximum(),robot->drivers[current].vmax*2,10.0));
}
void DriverEdit::HandleAmax(double _value){
if(robot==NULL) return;
robot->drivers[current].amax = _value;
robot->drivers[current].amin = -_value;
ui->amaxSpinBox->setMaximum(Max(ui->amaxSpinBox->maximum(),robot->drivers[current].amax*2,100.0));
}
void DriverEdit::HandleTmax(double _value){
if(robot==NULL) return;
robot->drivers[current].tmax = _value;
robot->drivers[current].tmin = -_value;
ui->tmaxSpinBox->setMaximum(Max(ui->tmaxSpinBox->maximum(),robot->drivers[current].tmax*2,100.0));
}
void DriverEdit::SaveSettings()
{
if(robot==NULL) return;
QString filename = QFileDialog::getSaveFileName(0, "Modified robot file", QString(), "Robot (*.rob *.urdf);;All Files (*)");
if (filename.isNull()) return;
robot->Save(toStdString(filename).c_str());
}<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file ScriptMetaTypeDefines.cpp
* @brief Registration of the Core API objects to Javascript.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "ScriptMetaTypeDefines.h"
#include "SceneAPI.h"
#include "ChangeRequest.h"
#include "Entity.h"
#include "IModule.h"
#include "IAssetTransfer.h"
#include "IAssetUploadTransfer.h"
#include "IAssetStorage.h"
#include "ScriptAsset.h"
#include "AssetCache.h"
#include "KeyEvent.h"
#include "MouseEvent.h"
#include "UiProxyWidget.h"
#include "FrameAPI.h"
#include "ConsoleAPI.h"
#include "Scene.h"
#include "AudioAPI.h"
#include "SoundChannel.h"
#include "InputContext.h"
#include "IRenderer.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "EntityAction.h"
#include "InputFwd.h"
#include "ConfigAPI.h"
#include "LoggingFunctions.h"
#include "AssetAPI.h"
#include "Math/MathFunc.h"
#include "QScriptEngineHelpers.h"
#include <QUiLoader>
#include <QFile>
#include <QFontDatabase>
#include "MemoryLeakCheck.h"
/// Input API defines
Q_DECLARE_METATYPE(MouseEvent*)
Q_DECLARE_METATYPE(KeyEvent*)
Q_DECLARE_METATYPE(GestureEvent*)
Q_DECLARE_METATYPE(InputContext*)
/// Asset API defines
Q_DECLARE_METATYPE(AssetPtr);
Q_DECLARE_METATYPE(AssetTransferPtr);
Q_DECLARE_METATYPE(IAssetTransfer*);
Q_DECLARE_METATYPE(AssetUploadTransferPtr);
Q_DECLARE_METATYPE(IAssetUploadTransfer*);
Q_DECLARE_METATYPE(AssetStoragePtr);
Q_DECLARE_METATYPE(IAssetStorage*);
Q_DECLARE_METATYPE(ScriptAssetPtr);
Q_DECLARE_METATYPE(ScriptAsset*);
Q_DECLARE_METATYPE(AssetCache*);
Q_DECLARE_METATYPE(AssetMap);
Q_DECLARE_METATYPE(AssetStorageVector);
QScriptValue qScriptValueFromAssetMap(QScriptEngine *engine, const AssetMap &assetMap)
{
QScriptValue v = engine->newArray(assetMap.size());
int idx = 0;
for(AssetMap::const_iterator iter = assetMap.begin(); iter != assetMap.end(); ++iter)
{
QScriptValue elem = qScriptValueFromBoostSharedPtr(engine, iter->second);
v.setProperty(idx++, elem);
}
return v;
}
/// Deliberately a null function. Currently we don't need setting asset maps from the script side.
void qScriptValueToAssetMap(const QScriptValue &value, AssetMap &assetMap)
{
}
QScriptValue qScriptValueFromAssetStoragePtrVector(QScriptEngine *engine, const AssetStorageVector& vec)
{
QScriptValue v = engine->newArray(vec.size());
int idx = 0;
for(std::vector<AssetStoragePtr>::const_iterator iter = vec.begin(); iter != vec.end(); ++iter)
{
QScriptValue elem = qScriptValueFromBoostSharedPtr(engine, *iter);
v.setProperty(idx++, elem);
}
return v;
}
/// Deliberately a null function. Currently we don't need setting asset storage vectors from the script side.
void qScriptValueToAssetStoragePtrVector(const QScriptValue &value, AssetStorageVector& vec)
{
}
/// Ui defines
Q_DECLARE_METATYPE(UiProxyWidget*);
Q_DECLARE_METATYPE(UiMainWindow*);
Q_DECLARE_METATYPE(UiGraphicsView*);
Q_SCRIPT_DECLARE_QMETAOBJECT(UiProxyWidget, QWidget*)
/// Scene API defines.
Q_DECLARE_METATYPE(SceneAPI*);
Q_DECLARE_METATYPE(Scene*);
Q_DECLARE_METATYPE(Entity*);
Q_DECLARE_METATYPE(EntityAction*);
Q_DECLARE_METATYPE(EntityAction::ExecType);
Q_DECLARE_METATYPE(EntityAction::ExecTypeField);
Q_DECLARE_METATYPE(AttributeChange*);
Q_DECLARE_METATYPE(ChangeRequest*);
Q_DECLARE_METATYPE(IComponent*);
Q_DECLARE_METATYPE(AttributeChange::Type);
/// Frame, Console and Debug API object defines.
Q_DECLARE_METATYPE(Framework*);
Q_DECLARE_METATYPE(IModule*);
Q_DECLARE_METATYPE(FrameAPI*);
Q_DECLARE_METATYPE(ConsoleAPI*);
Q_DECLARE_METATYPE(ConsoleCommand*);
Q_DECLARE_METATYPE(DelayedSignal*);
/// Audio API defines.
Q_DECLARE_METATYPE(AudioAPI*);
Q_DECLARE_METATYPE(SoundChannel*);
/// Config API defines.
Q_DECLARE_METATYPE(ConfigAPI*);
/// Renderer defines.
Q_DECLARE_METATYPE(RaycastResult*);
QScriptValue findChild(QScriptContext *ctx, QScriptEngine *eng)
{
if(ctx->argumentCount() == 2)
{
QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
QString childName = qscriptvalue_cast<QString>(ctx->argument(1));
if(object)
{
QObject *obj = object->findChild<QObject*>(childName);
if (obj)
return eng->newQObject(obj);
}
}
return QScriptValue();
}
QScriptValue addApplicationFont(QScriptContext *ctx, QScriptEngine *eng)
{
if(ctx->argumentCount() == 1)
{
QString fontName = qscriptvalue_cast<QString>(ctx->argument(0));
QFontDatabase::addApplicationFont(fontName);
}
return QScriptValue();
}
// Helper function. Added because new'ing a QPixmap in script seems to lead into growing memory use
QScriptValue setPixmapToLabel(QScriptContext *ctx, QScriptEngine *eng)
{
if(ctx->argumentCount() == 2)
{
QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
QString filename = qscriptvalue_cast<QString>(ctx->argument(1));
QLabel *label = dynamic_cast<QLabel *>(object);
if (label && QFile::exists(filename))
label->setPixmap(QPixmap(filename));
}
return QScriptValue();
}
void ExposeQtMetaTypes(QScriptEngine *engine)
{
assert(engine);
if (!engine)
return;
engine->globalObject().setProperty("findChild", engine->newFunction(findChild));
engine->globalObject().setProperty("setPixmapToLabel", engine->newFunction(setPixmapToLabel));
engine->globalObject().setProperty("addApplicationFont", engine->newFunction(addApplicationFont));
/*
engine->importExtension("qt.core");
engine->importExtension("qt.gui");
engine->importExtension("qt.network");
engine->importExtension("qt.uitools");
engine->importExtension("qt.xml");
engine->importExtension("qt.xmlpatterns");
*/
// Our deps contain these plugins as well, but we don't use them (for now at least).
// engine->importExtension("qt.opengl");
// engine->importExtension("qt.phonon");
// engine->importExtension("qt.webkit"); //cvetan hacked this to build with msvc, patch is somewhere
}
Q_DECLARE_METATYPE(SoundChannelPtr);
Q_DECLARE_METATYPE(InputContextPtr);
QScriptValue register_AABB_prototype(QScriptEngine *engine);
QScriptValue register_float2_prototype(QScriptEngine *engine);
QScriptValue register_float3_prototype(QScriptEngine *engine);
QScriptValue register_float3x3_prototype(QScriptEngine *engine);
QScriptValue register_float3x4_prototype(QScriptEngine *engine);
QScriptValue register_float4_prototype(QScriptEngine *engine);
QScriptValue register_float4x4_prototype(QScriptEngine *engine);
QScriptValue register_LCG_prototype(QScriptEngine *engine);
QScriptValue register_Line_prototype(QScriptEngine *engine);
QScriptValue register_LineSegment_prototype(QScriptEngine *engine);
QScriptValue register_OBB_prototype(QScriptEngine *engine);
QScriptValue register_Quat_prototype(QScriptEngine *engine);
QScriptValue register_Ray_prototype(QScriptEngine *engine);
QScriptValue register_ScaleOp_prototype(QScriptEngine *engine);
QScriptValue register_Sphere_prototype(QScriptEngine *engine);
QScriptValue register_TranslateOp_prototype(QScriptEngine *engine);
QScriptValue register_Transform_prototype(QScriptEngine *engine);
QScriptValue register_Triangle_prototype(QScriptEngine *engine);
static QScriptValue math_SetMathBreakOnAssume(QScriptContext *context, QScriptEngine *engine)
{
SetMathBreakOnAssume(qscriptvalue_cast<bool>(context->argument(0)));
return QScriptValue();
}
static QScriptValue math_MathBreakOnAssume(QScriptContext *context, QScriptEngine *engine)
{
return qScriptValueFromValue(engine, MathBreakOnAssume());
}
void ExposeCoreApiMetaTypes(QScriptEngine *engine)
{
register_float2_prototype(engine);
register_float3_prototype(engine);
register_float3x3_prototype(engine);
register_float3x4_prototype(engine);
register_float4_prototype(engine);
register_float4x4_prototype(engine);
register_AABB_prototype(engine);
register_LCG_prototype(engine);
register_Line_prototype(engine);
register_LineSegment_prototype(engine);
register_OBB_prototype(engine);
register_Quat_prototype(engine);
register_Ray_prototype(engine);
register_ScaleOp_prototype(engine);
register_Sphere_prototype(engine);
register_TranslateOp_prototype(engine);
register_Triangle_prototype(engine);
register_Transform_prototype(engine);
QScriptValue mathNamespace = engine->newObject();
mathNamespace.setProperty("SetMathBreakOnAssume", engine->newFunction(math_SetMathBreakOnAssume, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
mathNamespace.setProperty("MathBreakOnAssume", engine->newFunction(math_SetMathBreakOnAssume, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
engine->globalObject().setProperty("math", mathNamespace);
// Input metatypes.
qScriptRegisterQObjectMetaType<MouseEvent*>(engine);
qScriptRegisterQObjectMetaType<KeyEvent*>(engine);
qScriptRegisterQObjectMetaType<GestureEvent*>(engine);
qScriptRegisterQObjectMetaType<InputContext*>(engine);
qRegisterMetaType<InputContextPtr>("InputContextPtr");
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<InputContext>, qScriptValueToBoostSharedPtr<InputContext>);
qRegisterMetaType<KeyEvent::EventType>("KeyEvent::EventType");
qRegisterMetaType<MouseEvent::EventType>("MouseEvent::EventType");
qRegisterMetaType<MouseEvent::MouseButton>("MouseEvent::MouseButton");
qRegisterMetaType<GestureEvent::EventType>("GestureEvent::EventType");
// Scene metatypes.
qScriptRegisterQObjectMetaType<SceneAPI*>(engine);
qScriptRegisterQObjectMetaType<Scene*>(engine);
qScriptRegisterQObjectMetaType<Entity*>(engine);
qScriptRegisterQObjectMetaType<EntityAction*>(engine);
qScriptRegisterQObjectMetaType<AttributeChange*>(engine);
qScriptRegisterQObjectMetaType<ChangeRequest*>(engine);
qScriptRegisterQObjectMetaType<IComponent*>(engine);
//qRegisterMetaType<AttributeChange::Type>("AttributeChange::Type");
qScriptRegisterMetaType(engine, toScriptValueEnum<AttributeChange::Type>, fromScriptValueEnum<AttributeChange::Type>);
//qRegisterMetaType<EntityAction::ExecType>("EntityAction::ExecutionType");
qScriptRegisterMetaType(engine, toScriptValueEnum<EntityAction::ExecType>, fromScriptValueEnum<EntityAction::ExecType>);
qRegisterMetaType<EntityAction::ExecTypeField>("EntityAction::ExecTypeField");
qRegisterMetaType<entity_id_t>("entity_id_t");
qScriptRegisterMetaType(engine, toScriptUInt<entity_id_t>, fromScriptUInt<entity_id_t>);
qRegisterMetaType<component_id_t>("component_id_t");
qScriptRegisterMetaType(engine, toScriptUInt<component_id_t>, fromScriptUInt<component_id_t>);
// Framework metatype
qScriptRegisterQObjectMetaType<Framework*>(engine);
qScriptRegisterQObjectMetaType<IModule*>(engine);
// Console metatypes.
qScriptRegisterQObjectMetaType<ConsoleAPI*>(engine);
qScriptRegisterQObjectMetaType<ConsoleCommand*>(engine);
// Frame metatypes.
qScriptRegisterQObjectMetaType<FrameAPI*>(engine);
qScriptRegisterQObjectMetaType<DelayedSignal*>(engine);
// Config metatypes.
qScriptRegisterQObjectMetaType<ConfigAPI*>(engine);
// Asset API
qRegisterMetaType<AssetPtr>("AssetPtr");
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAsset>, qScriptValueToBoostSharedPtr<IAsset>);
qRegisterMetaType<AssetTransferPtr>("AssetTransferPtr");
qScriptRegisterQObjectMetaType<IAssetTransfer*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetTransfer>, qScriptValueToBoostSharedPtr<IAssetTransfer>);
qRegisterMetaType<AssetUploadTransferPtr>("AssetUploadTransferPtr");
qScriptRegisterQObjectMetaType<IAssetUploadTransfer*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetUploadTransfer>, qScriptValueToBoostSharedPtr<IAssetUploadTransfer>);
qRegisterMetaType<AssetStoragePtr>("AssetStoragePtr");
qScriptRegisterQObjectMetaType<IAssetStorage*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetStorage>, qScriptValueToBoostSharedPtr<IAssetStorage>);
/*
qRegisterMetaType<AssetStoragePtr>("ScriptAssetPtr");
qScriptRegisterQObjectMetaType<ScriptAsset*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<ScriptAsset>, qScriptValueToBoostSharedPtr<ScriptAsset>);
*/
qScriptRegisterQObjectMetaType<AssetCache*>(engine);
qRegisterMetaType<AssetMap>("AssetMap");
qScriptRegisterMetaType<AssetMap>(engine, qScriptValueFromAssetMap, qScriptValueToAssetMap);
qRegisterMetaType<AssetStorageVector>("AssetStorageVector");
qScriptRegisterMetaType<AssetStorageVector>(engine, qScriptValueFromAssetStoragePtrVector, qScriptValueToAssetStoragePtrVector);
// Ui metatypes.
qScriptRegisterQObjectMetaType<UiMainWindow*>(engine);
qScriptRegisterQObjectMetaType<UiGraphicsView*>(engine);
qScriptRegisterQObjectMetaType<UiProxyWidget*>(engine);
qScriptRegisterQObjectMetaType<QGraphicsScene*>(engine);
// Add support to create proxy widgets in javascript side.
QScriptValue object = engine->scriptValueFromQMetaObject<UiProxyWidget>();
engine->globalObject().setProperty("UiProxyWidget", object);
// Sound metatypes.
qRegisterMetaType<sound_id_t>("sound_id_t");
qRegisterMetaType<SoundChannel::SoundState>("SoundState");
qRegisterMetaType<SoundChannelPtr>("SoundChannelPtr");
qScriptRegisterQObjectMetaType<SoundChannel*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<SoundChannel>, qScriptValueToBoostSharedPtr<SoundChannel>);
qRegisterMetaType<SoundChannel::SoundState>("SoundChannel::SoundState");
qRegisterMetaType<SoundChannel::SoundType>("SoundType");
qRegisterMetaType<SoundChannel::SoundType>("SoundChannel::SoundType");
// Renderer metatypes
qScriptRegisterQObjectMetaType<RaycastResult*>(engine);
// Communications metatypes
// qScriptRegisterQObjectMetaType<Communications::InWorldVoice::SessionInterface*>(engine);
// qScriptRegisterQObjectMetaType<Communications::InWorldVoice::ParticipantInterface*>(engine);
}
<commit_msg>Expose/register SoundChannel::SoundState and SoundChannel::SoundType enums properly to QtScript.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file ScriptMetaTypeDefines.cpp
* @brief Registration of the Core API objects to Javascript.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "ScriptMetaTypeDefines.h"
#include "SceneAPI.h"
#include "ChangeRequest.h"
#include "Entity.h"
#include "IModule.h"
#include "IAssetTransfer.h"
#include "IAssetUploadTransfer.h"
#include "IAssetStorage.h"
#include "ScriptAsset.h"
#include "AssetCache.h"
#include "KeyEvent.h"
#include "MouseEvent.h"
#include "UiProxyWidget.h"
#include "FrameAPI.h"
#include "ConsoleAPI.h"
#include "Scene.h"
#include "AudioAPI.h"
#include "SoundChannel.h"
#include "InputContext.h"
#include "IRenderer.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "EntityAction.h"
#include "InputFwd.h"
#include "ConfigAPI.h"
#include "LoggingFunctions.h"
#include "AssetAPI.h"
#include "Math/MathFunc.h"
#include "QScriptEngineHelpers.h"
#include <QUiLoader>
#include <QFile>
#include <QFontDatabase>
#include "MemoryLeakCheck.h"
/// Input API defines
Q_DECLARE_METATYPE(MouseEvent*)
Q_DECLARE_METATYPE(KeyEvent*)
Q_DECLARE_METATYPE(GestureEvent*)
Q_DECLARE_METATYPE(InputContext*)
Q_DECLARE_METATYPE(InputContextPtr);
/// Asset API defines
Q_DECLARE_METATYPE(AssetPtr);
Q_DECLARE_METATYPE(AssetTransferPtr);
Q_DECLARE_METATYPE(IAssetTransfer*);
Q_DECLARE_METATYPE(AssetUploadTransferPtr);
Q_DECLARE_METATYPE(IAssetUploadTransfer*);
Q_DECLARE_METATYPE(AssetStoragePtr);
Q_DECLARE_METATYPE(IAssetStorage*);
Q_DECLARE_METATYPE(ScriptAssetPtr);
Q_DECLARE_METATYPE(ScriptAsset*);
Q_DECLARE_METATYPE(AssetCache*);
Q_DECLARE_METATYPE(AssetMap);
Q_DECLARE_METATYPE(AssetStorageVector);
/// Ui defines
Q_DECLARE_METATYPE(UiProxyWidget*);
Q_DECLARE_METATYPE(UiMainWindow*);
Q_DECLARE_METATYPE(UiGraphicsView*);
Q_SCRIPT_DECLARE_QMETAOBJECT(UiProxyWidget, QWidget*)
/// Scene API defines.
Q_DECLARE_METATYPE(SceneAPI*);
Q_DECLARE_METATYPE(Scene*);
Q_DECLARE_METATYPE(Entity*);
Q_DECLARE_METATYPE(EntityAction*);
Q_DECLARE_METATYPE(EntityAction::ExecType);
Q_DECLARE_METATYPE(EntityAction::ExecTypeField);
Q_DECLARE_METATYPE(AttributeChange*);
Q_DECLARE_METATYPE(ChangeRequest*);
Q_DECLARE_METATYPE(IComponent*);
Q_DECLARE_METATYPE(AttributeChange::Type);
/// Frame, Console and Debug API object defines.
Q_DECLARE_METATYPE(Framework*);
Q_DECLARE_METATYPE(IModule*);
Q_DECLARE_METATYPE(FrameAPI*);
Q_DECLARE_METATYPE(ConsoleAPI*);
Q_DECLARE_METATYPE(ConsoleCommand*);
Q_DECLARE_METATYPE(DelayedSignal*);
/// Audio API defines.
Q_DECLARE_METATYPE(AudioAPI*);
Q_DECLARE_METATYPE(SoundChannel*);
Q_DECLARE_METATYPE(SoundChannel::SoundType)
Q_DECLARE_METATYPE(SoundChannel::SoundState)
Q_DECLARE_METATYPE(SoundChannelPtr);
/// Config API defines.
Q_DECLARE_METATYPE(ConfigAPI*);
Q_DECLARE_METATYPE(ConfigData*);
/// Renderer defines.
Q_DECLARE_METATYPE(RaycastResult*);
QScriptValue qScriptValueFromAssetMap(QScriptEngine *engine, const AssetMap &assetMap)
{
QScriptValue v = engine->newArray(assetMap.size());
int idx = 0;
for(AssetMap::const_iterator iter = assetMap.begin(); iter != assetMap.end(); ++iter)
{
QScriptValue elem = qScriptValueFromBoostSharedPtr(engine, iter->second);
v.setProperty(idx++, elem);
}
return v;
}
/// Deliberately a null function. Currently we don't need setting asset maps from the script side.
void qScriptValueToAssetMap(const QScriptValue &value, AssetMap &assetMap)
{
}
QScriptValue qScriptValueFromAssetStoragePtrVector(QScriptEngine *engine, const AssetStorageVector& vec)
{
QScriptValue v = engine->newArray(vec.size());
int idx = 0;
for(std::vector<AssetStoragePtr>::const_iterator iter = vec.begin(); iter != vec.end(); ++iter)
{
QScriptValue elem = qScriptValueFromBoostSharedPtr(engine, *iter);
v.setProperty(idx++, elem);
}
return v;
}
/// Deliberately a null function. Currently we don't need setting asset storage vectors from the script side.
void qScriptValueToAssetStoragePtrVector(const QScriptValue &value, AssetStorageVector& vec)
{
}
QScriptValue findChild(QScriptContext *ctx, QScriptEngine *eng)
{
if(ctx->argumentCount() == 2)
{
QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
QString childName = qscriptvalue_cast<QString>(ctx->argument(1));
if(object)
{
QObject *obj = object->findChild<QObject*>(childName);
if (obj)
return eng->newQObject(obj);
}
}
return QScriptValue();
}
QScriptValue addApplicationFont(QScriptContext *ctx, QScriptEngine *eng)
{
if(ctx->argumentCount() == 1)
{
QString fontName = qscriptvalue_cast<QString>(ctx->argument(0));
QFontDatabase::addApplicationFont(fontName);
}
return QScriptValue();
}
// Helper function. Added because new'ing a QPixmap in script seems to lead into growing memory use
QScriptValue setPixmapToLabel(QScriptContext *ctx, QScriptEngine *eng)
{
if(ctx->argumentCount() == 2)
{
QObject *object = qscriptvalue_cast<QObject*>(ctx->argument(0));
QString filename = qscriptvalue_cast<QString>(ctx->argument(1));
QLabel *label = dynamic_cast<QLabel *>(object);
if (label && QFile::exists(filename))
label->setPixmap(QPixmap(filename));
}
return QScriptValue();
}
void ExposeQtMetaTypes(QScriptEngine *engine)
{
assert(engine);
if (!engine)
return;
engine->globalObject().setProperty("findChild", engine->newFunction(findChild));
engine->globalObject().setProperty("setPixmapToLabel", engine->newFunction(setPixmapToLabel));
engine->globalObject().setProperty("addApplicationFont", engine->newFunction(addApplicationFont));
/*
engine->importExtension("qt.core");
engine->importExtension("qt.gui");
engine->importExtension("qt.network");
engine->importExtension("qt.uitools");
engine->importExtension("qt.xml");
engine->importExtension("qt.xmlpatterns");
*/
// Our deps contain these plugins as well, but we don't use them (for now at least).
// engine->importExtension("qt.opengl");
// engine->importExtension("qt.phonon");
// engine->importExtension("qt.webkit"); //cvetan hacked this to build with msvc, patch is somewhere
}
QScriptValue register_AABB_prototype(QScriptEngine *engine);
QScriptValue register_float2_prototype(QScriptEngine *engine);
QScriptValue register_float3_prototype(QScriptEngine *engine);
QScriptValue register_float3x3_prototype(QScriptEngine *engine);
QScriptValue register_float3x4_prototype(QScriptEngine *engine);
QScriptValue register_float4_prototype(QScriptEngine *engine);
QScriptValue register_float4x4_prototype(QScriptEngine *engine);
QScriptValue register_LCG_prototype(QScriptEngine *engine);
QScriptValue register_Line_prototype(QScriptEngine *engine);
QScriptValue register_LineSegment_prototype(QScriptEngine *engine);
QScriptValue register_OBB_prototype(QScriptEngine *engine);
QScriptValue register_Quat_prototype(QScriptEngine *engine);
QScriptValue register_Ray_prototype(QScriptEngine *engine);
QScriptValue register_ScaleOp_prototype(QScriptEngine *engine);
QScriptValue register_Sphere_prototype(QScriptEngine *engine);
QScriptValue register_TranslateOp_prototype(QScriptEngine *engine);
QScriptValue register_Transform_prototype(QScriptEngine *engine);
QScriptValue register_Triangle_prototype(QScriptEngine *engine);
static QScriptValue math_SetMathBreakOnAssume(QScriptContext *context, QScriptEngine *engine)
{
SetMathBreakOnAssume(qscriptvalue_cast<bool>(context->argument(0)));
return QScriptValue();
}
static QScriptValue math_MathBreakOnAssume(QScriptContext *context, QScriptEngine *engine)
{
return qScriptValueFromValue(engine, MathBreakOnAssume());
}
void ExposeCoreApiMetaTypes(QScriptEngine *engine)
{
register_float2_prototype(engine);
register_float3_prototype(engine);
register_float3x3_prototype(engine);
register_float3x4_prototype(engine);
register_float4_prototype(engine);
register_float4x4_prototype(engine);
register_AABB_prototype(engine);
register_LCG_prototype(engine);
register_Line_prototype(engine);
register_LineSegment_prototype(engine);
register_OBB_prototype(engine);
register_Quat_prototype(engine);
register_Ray_prototype(engine);
register_ScaleOp_prototype(engine);
register_Sphere_prototype(engine);
register_TranslateOp_prototype(engine);
register_Triangle_prototype(engine);
register_Transform_prototype(engine);
QScriptValue mathNamespace = engine->newObject();
mathNamespace.setProperty("SetMathBreakOnAssume", engine->newFunction(math_SetMathBreakOnAssume, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly);
mathNamespace.setProperty("MathBreakOnAssume", engine->newFunction(math_SetMathBreakOnAssume, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly);
engine->globalObject().setProperty("math", mathNamespace);
// Input metatypes.
qScriptRegisterQObjectMetaType<MouseEvent*>(engine);
qScriptRegisterQObjectMetaType<KeyEvent*>(engine);
qScriptRegisterQObjectMetaType<GestureEvent*>(engine);
qScriptRegisterQObjectMetaType<InputContext*>(engine);
qRegisterMetaType<InputContextPtr>("InputContextPtr");
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<InputContext>, qScriptValueToBoostSharedPtr<InputContext>);
qRegisterMetaType<KeyEvent::EventType>("KeyEvent::EventType");
qRegisterMetaType<MouseEvent::EventType>("MouseEvent::EventType");
qRegisterMetaType<MouseEvent::MouseButton>("MouseEvent::MouseButton");
qRegisterMetaType<GestureEvent::EventType>("GestureEvent::EventType");
// Scene metatypes.
qScriptRegisterQObjectMetaType<SceneAPI*>(engine);
qScriptRegisterQObjectMetaType<Scene*>(engine);
qScriptRegisterQObjectMetaType<Entity*>(engine);
qScriptRegisterQObjectMetaType<EntityAction*>(engine);
qScriptRegisterQObjectMetaType<AttributeChange*>(engine);
qScriptRegisterQObjectMetaType<ChangeRequest*>(engine);
qScriptRegisterQObjectMetaType<IComponent*>(engine);
qScriptRegisterMetaType(engine, toScriptValueEnum<AttributeChange::Type>, fromScriptValueEnum<AttributeChange::Type>);
qScriptRegisterMetaType(engine, toScriptValueEnum<EntityAction::ExecType>, fromScriptValueEnum<EntityAction::ExecType>);
qRegisterMetaType<EntityAction::ExecTypeField>("EntityAction::ExecTypeField");
qRegisterMetaType<entity_id_t>("entity_id_t");
qScriptRegisterMetaType(engine, toScriptUInt<entity_id_t>, fromScriptUInt<entity_id_t>);
qRegisterMetaType<component_id_t>("component_id_t");
qScriptRegisterMetaType(engine, toScriptUInt<component_id_t>, fromScriptUInt<component_id_t>);
// Framework metatype
qScriptRegisterQObjectMetaType<Framework*>(engine);
qScriptRegisterQObjectMetaType<IModule*>(engine);
// Console metatypes.
qScriptRegisterQObjectMetaType<ConsoleAPI*>(engine);
qScriptRegisterQObjectMetaType<ConsoleCommand*>(engine);
// Frame metatypes.
qScriptRegisterQObjectMetaType<FrameAPI*>(engine);
qScriptRegisterQObjectMetaType<DelayedSignal*>(engine);
// Config metatypes.
qScriptRegisterQObjectMetaType<ConfigAPI*>(engine);
qScriptRegisterQObjectMetaType<ConfigData*>(engine);
// Asset API
qRegisterMetaType<AssetPtr>("AssetPtr");
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAsset>, qScriptValueToBoostSharedPtr<IAsset>);
qRegisterMetaType<AssetTransferPtr>("AssetTransferPtr");
qScriptRegisterQObjectMetaType<IAssetTransfer*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetTransfer>, qScriptValueToBoostSharedPtr<IAssetTransfer>);
qRegisterMetaType<AssetUploadTransferPtr>("AssetUploadTransferPtr");
qScriptRegisterQObjectMetaType<IAssetUploadTransfer*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetUploadTransfer>, qScriptValueToBoostSharedPtr<IAssetUploadTransfer>);
qRegisterMetaType<AssetStoragePtr>("AssetStoragePtr");
qScriptRegisterQObjectMetaType<IAssetStorage*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<IAssetStorage>, qScriptValueToBoostSharedPtr<IAssetStorage>);
/*
qRegisterMetaType<AssetStoragePtr>("ScriptAssetPtr");
qScriptRegisterQObjectMetaType<ScriptAsset*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<ScriptAsset>, qScriptValueToBoostSharedPtr<ScriptAsset>);
*/
qScriptRegisterQObjectMetaType<AssetCache*>(engine);
qRegisterMetaType<AssetMap>("AssetMap");
qScriptRegisterMetaType<AssetMap>(engine, qScriptValueFromAssetMap, qScriptValueToAssetMap);
qRegisterMetaType<AssetStorageVector>("AssetStorageVector");
qScriptRegisterMetaType<AssetStorageVector>(engine, qScriptValueFromAssetStoragePtrVector, qScriptValueToAssetStoragePtrVector);
// Ui metatypes.
qScriptRegisterQObjectMetaType<UiMainWindow*>(engine);
qScriptRegisterQObjectMetaType<UiGraphicsView*>(engine);
qScriptRegisterQObjectMetaType<UiProxyWidget*>(engine);
qScriptRegisterQObjectMetaType<QGraphicsScene*>(engine);
// Add support to create proxy widgets in javascript side.
QScriptValue object = engine->scriptValueFromQMetaObject<UiProxyWidget>();
engine->globalObject().setProperty("UiProxyWidget", object);
// Sound metatypes.
qRegisterMetaType<sound_id_t>("sound_id_t");
qScriptRegisterMetaType(engine, toScriptValueEnum<SoundChannel::SoundState>, fromScriptValueEnum<SoundChannel::SoundState>);
qScriptRegisterMetaType(engine, toScriptValueEnum<SoundChannel::SoundType>, fromScriptValueEnum<SoundChannel::SoundType>);
qRegisterMetaType<SoundChannelPtr>("SoundChannelPtr");
qScriptRegisterQObjectMetaType<SoundChannel*>(engine);
qScriptRegisterMetaType(engine, qScriptValueFromBoostSharedPtr<SoundChannel>, qScriptValueToBoostSharedPtr<SoundChannel>);
// Renderer metatypes
qScriptRegisterQObjectMetaType<RaycastResult*>(engine);
}
<|endoftext|> |
<commit_before>#include "data-student.hpp"
using namespace std;
void Student::init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
addMajors(m);
}
Student::Student() {
init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
int startYear = stringToInt(s), endYear = stringToInt(e);
init(n, startYear, endYear, m);
}
Student::Student(string fn) {
string yearS, yearE;
ifstream infile(fn.c_str());
string nextLine;
vector<string> lines;
// load the entire file
while (infile.peek() != -1) {
getline(infile, nextLine);
lines.push_back(nextLine);
}
string previousHeading;
for (vector<string>::iterator i = lines.begin(); i != lines.end(); ++i) {
string str = *i;
if (previousHeading.empty())
previousHeading = "# NAME";
if (str[0] == '#') {
previousHeading = *i;
continue;
}
else if (str != "") {
if (str.substr(0, 2) == "//") {
// it's a comment
}
else if (previousHeading == "# NAME")
name = str;
else if (previousHeading == "# MAJORS")
addMajor(Major(str));
else if (previousHeading == "# CONCENTRATIONS")
addConcentration(Concentration(str));
else if (previousHeading == "# COURSES")
addCourse(Course(str));
else if (previousHeading == "# LABS")
addCourse(Course(str));
}
}
}
void Student::addMajor(const Major& m) {
majors.push_back(m);
}
void Student::addMajors(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
addMajor(Major(*i));
}
void Student::addConcentration(const Concentration& m) {
concentrations.push_back(m);
}
void Student::addConcentrations(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
addConcentration(Concentration(*i));
}
void Student::addCourse(const Course& c) {
courses.push_back(c);
}
void Student::addCourses(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
addCourse(Course(*i));
}
bool Student::hasTakenCourse(string str) {
bool userHasTaken = false;
Course checkAgainst = getCourse(str);
for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
if (*i == checkAgainst)
userHasTaken = true;
return userHasTaken;
}
ostream& Student::getData(ostream &os) {
os << name << ", ";
if (majors.size()) {
os << "you are majoring in ";
for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
if (majors.size() == 1) {
os << *i << " ";
}
else if (majors.size() == 2) {
os << *i;
if (i != majors.end()-1)
os << " and ";
else
os << " ";
}
else {
if (i != majors.end()-1)
os << *i << ", ";
else
os << "and " << *i << ", ";
}
}
}
if (concentrations.size()) {
os << "with concentrations in ";
for (vector<Concentration>::iterator i = concentrations.begin(); i != concentrations.end(); ++i) {
if (concentrations.size() == 1) {
os << *i << " ";
}
if (concentrations.size() == 2) {
os << *i;
if (i != concentrations.end()-1)
os << " and ";
else
os << " ";
}
else {
if (i != concentrations.end()-1)
os << *i << ", ";
else
os << "and " << *i << ", ";
}
}
}
if (!majors.size())
os << "you are taking: " << endl;
else
os << "while taking:" << endl;
for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
os << *i << endl;
return os;
}
void Student::display() {
cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
return item.getData(os);
}
<commit_msg>Improve the Student file parser again<commit_after>#include "data-student.hpp"
using namespace std;
void Student::init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
addMajors(m);
}
Student::Student() {
init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
int startYear = stringToInt(s), endYear = stringToInt(e);
init(n, startYear, endYear, m);
}
Student::Student(string fn) {
string yearS, yearE;
ifstream infile(fn.c_str());
string nextLine;
vector<string> lines;
// load the entire file
while (infile.peek() != -1) {
getline(infile, nextLine);
lines.push_back(nextLine);
}
string previousHeading;
for (vector<string>::iterator i = lines.begin(); i != lines.end(); ++i) {
string str = *i;
if (previousHeading.empty())
previousHeading = "# NAME";
if (str[0] == '#') {
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
previousHeading = *i;
continue;
}
else if (str != "") {
if (str.substr(0, 2) == "//") {
// it's a comment
}
else if (previousHeading == "# NAME")
name = str;
else if (previousHeading == "# MAJORS")
addMajor(Major(str));
else if (previousHeading == "# CONCENTRATIONS")
addConcentration(Concentration(str));
else if (previousHeading == "# COURSES")
addCourse(Course(str));
else if (previousHeading == "# LABS")
addCourse(Course(str));
}
}
}
void Student::addMajor(const Major& m) {
majors.push_back(m);
}
void Student::addMajors(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
addMajor(Major(*i));
}
void Student::addConcentration(const Concentration& m) {
concentrations.push_back(m);
}
void Student::addConcentrations(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
addConcentration(Concentration(*i));
}
void Student::addCourse(const Course& c) {
courses.push_back(c);
}
void Student::addCourses(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
addCourse(Course(*i));
}
bool Student::hasTakenCourse(string str) {
bool userHasTaken = false;
Course checkAgainst = getCourse(str);
for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
if (*i == checkAgainst)
userHasTaken = true;
return userHasTaken;
}
ostream& Student::getData(ostream &os) {
os << name << ", ";
if (majors.size()) {
os << "you are majoring in ";
for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
if (majors.size() == 1) {
os << *i << " ";
}
else if (majors.size() == 2) {
os << *i;
if (i != majors.end()-1)
os << " and ";
else
os << " ";
}
else {
if (i != majors.end()-1)
os << *i << ", ";
else
os << "and " << *i << ", ";
}
}
}
if (concentrations.size()) {
os << "with concentrations in ";
for (vector<Concentration>::iterator i = concentrations.begin(); i != concentrations.end(); ++i) {
if (concentrations.size() == 1) {
os << *i << " ";
}
if (concentrations.size() == 2) {
os << *i;
if (i != concentrations.end()-1)
os << " and ";
else
os << " ";
}
else {
if (i != concentrations.end()-1)
os << *i << ", ";
else
os << "and " << *i << ", ";
}
}
}
if (!majors.size())
os << "you are taking: " << endl;
else
os << "while taking:" << endl;
for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i) {
if (i != courses.end()-1)
os << *i << endl;
else
os << *i;
}
return os;
}
void Student::display() {
cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
return item.getData(os);
}
<|endoftext|> |
<commit_before>#include "ComponentCamera.h"
#include "Glew/include/glew.h"
#include "SDL/include/SDL_opengl.h"
#include "GameObject.h"
#include "ComponentTransform.h"
#include "Application.h"
#include "ModuleScene.h"
#include "ModuleRenderer3D.h"
// Constructors =================================
ComponentCamera::ComponentCamera()
{
}
ComponentCamera::ComponentCamera(const ComponentCamera & cpy) :Component(cpy)
{
}
// Destructors ==================================
ComponentCamera::~ComponentCamera()
{
}
bool ComponentCamera::Start()
{
frustum.nearPlaneDistance = 1;
frustum.farPlaneDistance = 15;
UpdateFrustrum();
//Set frustum looking to GameObject Z axis
const ComponentTransform* parent_transform = (ComponentTransform*)this->parent->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION);
frustum.type = math::PerspectiveFrustum;
frustum.pos = parent_transform->GetPosition();
frustum.front = math::float3(0, 0, 1);
frustum.up = math::float3(0, 1, 0);
frustum.orthographicHeight = 5;
frustum.orthographicWidth = 2;
frustum.verticalFov = 5;
frustum.horizontalFov = 8;
App->renderer3D->SetMainCamera(this);
return true;
}
bool ComponentCamera::Update()
{
UpdateFrustumTransform();
DrawFrustum();
if (frustum_culling)
{
ApplyFrustum(App->scene->GetRoot());
}
return true;
}
const math::Frustum ComponentCamera::GetFrustum() const
{
return frustum;
}
// Functionality ================================
void ComponentCamera::SetTransform(const ComponentTransform * trans)
{
}
void ComponentCamera::UpdateFrustrum()
{
//Set frustum looking to GameObject Z axis
const ComponentTransform* parent_transform = (ComponentTransform*)this->parent->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION);
frustum.type = math::PerspectiveFrustum;
frustum.pos = math::float3(0, 0, 0);
frustum.front = math::float3(0, 0, 1);
frustum.up = math::float3(0, 1, 0);
frustum.orthographicHeight = 5;
frustum.orthographicWidth = 2;
frustum.verticalFov = 5;
frustum.horizontalFov = 8;
}
void ComponentCamera::UpdateFrustumTransform()
{
const ComponentTransform* parent_transform = (ComponentTransform*)this->parent->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION);
//Z axis of the transform
frustum.front = parent_transform->transform_matrix.Row3(2);
//Y axis of the transform
frustum.up = parent_transform->transform_matrix.Row3(1);
frustum.pos = parent_transform->GetPosition();
}
void ComponentCamera::DrawFrustum() const
{
App->renderer3D->DisableGLRenderFlags();
float color[4] = { 0.7f, 0.5f, 0.5f, 1 };
frustum.Draw(3.0f, color);
App->renderer3D->EnableGLRenderFlags();
}
void ComponentCamera::ApplyFrustum(GameObject * target)
{
if (target == nullptr)return;
std::vector<GameObject*> childs = *target->GetChilds();
uint size = childs.size();
for (uint k = 0; k < size; k++)
{
ApplyFrustum(childs[k]);
}
if (target != parent && !frustum.Contact(*target->GetBoundingBox()))
{
target->SetActiveState(false);
}
else target->SetActiveState(true);
}
void ComponentCamera::UnApplyFrustum(GameObject * target)
{
if (target == nullptr)return;
std::vector<GameObject*> childs = *target->GetChilds();
uint size = childs.size();
for (uint k = 0; k < size; k++)
{
UnApplyFrustum(childs[k]);
}
target->SetActiveState(true);
}
void ComponentCamera::BlitComponentInspector()
{
ImGui::Separator();
ImGui::Checkbox("##camera_comp", &actived);
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f, 0.64f, 0.0f, 1.0f), "Camera");
//Culling
if (ImGui::Checkbox("Frustum Culling", &frustum_culling))
{
if (!frustum_culling)
{
UnApplyFrustum(App->scene->GetRoot());
}
}
//Camera frustum variables
//Front Vec
float f_vec[3] = { frustum.front.x ,frustum.front.y,frustum.front.z };
ImGui::DragFloat3("Front Vec", f_vec);
frustum.front = { f_vec[0],f_vec[1],f_vec[2] };
//Up Vec
float u_vec[3] = { frustum.up.x ,frustum.up.y,frustum.up.z };
ImGui::DragFloat3("Up Vec", u_vec);
frustum.up = { u_vec[0],u_vec[1],u_vec[2] };
//Near plane dist
ImGui::DragFloat("Near Plane Dist", &frustum.nearPlaneDistance, 0.2f, 0.01f, 50, "%.2f");
//Far plane dist
ImGui::DragFloat("Far Plane Dist", &frustum.farPlaneDistance, 0.2f, 0.1f, 50, "%.2f");
//Ortographic Height
ImGui::DragFloat("Ortographic Height", &frustum.orthographicHeight, 0.05, 0.0, 2);
//Ortographic Width
ImGui::DragFloat("Ortographic Width", &frustum.orthographicWidth, 0.05, 0.0, 2);
}
<commit_msg>Fixed Frustrum rotating bug<commit_after>#include "ComponentCamera.h"
#include "Glew/include/glew.h"
#include "SDL/include/SDL_opengl.h"
#include "GameObject.h"
#include "ComponentTransform.h"
#include "Application.h"
#include "ModuleScene.h"
#include "ModuleRenderer3D.h"
// Constructors =================================
ComponentCamera::ComponentCamera()
{
}
ComponentCamera::ComponentCamera(const ComponentCamera & cpy) :Component(cpy)
{
}
// Destructors ==================================
ComponentCamera::~ComponentCamera()
{
}
bool ComponentCamera::Start()
{
frustum.nearPlaneDistance = 1;
frustum.farPlaneDistance = 15;
UpdateFrustrum();
//Set frustum looking to GameObject Z axis
const ComponentTransform* parent_transform = (ComponentTransform*)this->parent->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION);
frustum.type = math::PerspectiveFrustum;
frustum.pos = parent_transform->GetPosition();
frustum.front = math::float3(0, 0, 1);
frustum.up = math::float3(0, 1, 0);
frustum.orthographicHeight = 5;
frustum.orthographicWidth = 2;
frustum.verticalFov = 5;
frustum.horizontalFov = 8;
App->renderer3D->SetMainCamera(this);
return true;
}
bool ComponentCamera::Update()
{
UpdateFrustumTransform();
DrawFrustum();
if (frustum_culling)
{
ApplyFrustum(App->scene->GetRoot());
}
return true;
}
const math::Frustum ComponentCamera::GetFrustum() const
{
return frustum;
}
// Functionality ================================
void ComponentCamera::SetTransform(const ComponentTransform * trans)
{
}
void ComponentCamera::UpdateFrustrum()
{
//Set frustum looking to GameObject Z axis
const ComponentTransform* parent_transform = (ComponentTransform*)this->parent->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION);
frustum.type = math::PerspectiveFrustum;
frustum.pos = math::float3(0, 0, 0);
frustum.front = math::float3(0, 0, 1);
frustum.up = math::float3(0, 1, 0);
frustum.orthographicHeight = 5;
frustum.orthographicWidth = 2;
frustum.verticalFov = 5;
frustum.horizontalFov = 8;
}
void ComponentCamera::UpdateFrustumTransform()
{
const ComponentTransform* parent_transform = (ComponentTransform*)this->parent->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION);
//Z axis of the transform
frustum.front = parent_transform->GetTransform().Col3(2);
//Y axis of the transform
frustum.up = parent_transform->GetTransform().Col3(1);
frustum.pos = parent_transform->GetPosition();
}
void ComponentCamera::DrawFrustum() const
{
App->renderer3D->DisableGLRenderFlags();
float color[4] = { 0.7f, 0.5f, 0.5f, 1 };
frustum.Draw(3.0f, color);
App->renderer3D->EnableGLRenderFlags();
}
void ComponentCamera::ApplyFrustum(GameObject * target)
{
if (target == nullptr)return;
std::vector<GameObject*> childs = *target->GetChilds();
uint size = childs.size();
for (uint k = 0; k < size; k++)
{
ApplyFrustum(childs[k]);
}
if (target != parent && !frustum.Contact(*target->GetBoundingBox()))
{
target->SetActiveState(false);
}
else target->SetActiveState(true);
}
void ComponentCamera::UnApplyFrustum(GameObject * target)
{
if (target == nullptr)return;
std::vector<GameObject*> childs = *target->GetChilds();
uint size = childs.size();
for (uint k = 0; k < size; k++)
{
UnApplyFrustum(childs[k]);
}
target->SetActiveState(true);
}
void ComponentCamera::BlitComponentInspector()
{
ImGui::Separator();
ImGui::Checkbox("##camera_comp", &actived);
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f, 0.64f, 0.0f, 1.0f), "Camera");
//Culling
if (ImGui::Checkbox("Frustum Culling", &frustum_culling))
{
if (!frustum_culling)
{
UnApplyFrustum(App->scene->GetRoot());
}
}
//Camera frustum variables
//Front Vec
float f_vec[3] = { frustum.front.x ,frustum.front.y,frustum.front.z };
ImGui::DragFloat3("Front Vec", f_vec);
frustum.front = { f_vec[0],f_vec[1],f_vec[2] };
//Up Vec
float u_vec[3] = { frustum.up.x ,frustum.up.y,frustum.up.z };
ImGui::DragFloat3("Up Vec", u_vec);
frustum.up = { u_vec[0],u_vec[1],u_vec[2] };
//Near plane dist
ImGui::DragFloat("Near Plane Dist", &frustum.nearPlaneDistance, 0.2f, 0.01f, 50, "%.2f");
//Far plane dist
ImGui::DragFloat("Far Plane Dist", &frustum.farPlaneDistance, 0.2f, 0.1f, 50, "%.2f");
//Ortographic Height
ImGui::DragFloat("Ortographic Height", &frustum.orthographicHeight, 0.05, 0.0, 2);
//Ortographic Width
ImGui::DragFloat("Ortographic Width", &frustum.orthographicWidth, 0.05, 0.0, 2);
}
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* DataDifferential Utility Library
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* 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.
*
* * The names of its contributors may not 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 "gear_config.h"
#include "util/instance.hpp"
#include "libgearman/ssl.h"
#include <cstdio>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <sstream>
#include <sys/socket.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
namespace datadifferential {
namespace util {
Instance::Instance(const std::string& hostname_arg, const std::string& service_arg) :
_host(hostname_arg),
_service(service_arg),
_sockfd(INVALID_SOCKET),
_use_ssl(false),
state(NOT_WRITING),
_addrinfo(0),
_addrinfo_next(0),
_finish_fn(NULL),
_operations(),
_ctx_ssl(NULL),
_ssl(NULL)
{
}
Instance::Instance(const std::string& hostname_arg, const in_port_t port_arg) :
_host(hostname_arg),
_sockfd(INVALID_SOCKET),
_use_ssl(false),
state(NOT_WRITING),
_addrinfo(0),
_addrinfo_next(0),
_finish_fn(NULL),
_operations(),
_ctx_ssl(NULL),
_ssl(NULL)
{
char tmp[BUFSIZ];
snprintf(tmp, sizeof(tmp), "%u", static_cast<unsigned int>(port_arg));
_service= tmp;
}
Instance::~Instance()
{
close_socket();
free_addrinfo();
for (Operation::vector::iterator iter= _operations.begin(); iter != _operations.end(); ++iter)
{
delete *iter;
}
_operations.clear();
delete _finish_fn;
#if defined(HAVE_SSL) && HAVE_SSL
if (_ssl)
{
SSL_shutdown(_ssl);
SSL_free(_ssl);
}
if (_ctx_ssl)
{
SSL_CTX_free(_ctx_ssl);
}
# if defined(HAVE_WOLFSSL) && HAVE_WOLFSSL
wolfSSL_Cleanup();
# endif // defined(HAVE_WOLFSSL)
#endif
}
bool Instance::init_ssl()
{
#if defined(HAVE_SSL) && HAVE_SSL
SSL_load_error_strings();
SSL_library_init();
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
if ((_ctx_ssl= SSL_CTX_new(TLSv1_2_client_method())) == NULL)
#else
if ((_ctx_ssl= SSL_CTX_new(TLS_client_method())) == NULL)
#endif
{
_last_error= "SSL_CTX_new error";
return false;
}
if (SSL_CTX_load_verify_locations(_ctx_ssl, ssl_ca_file(), 0) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error loading CA file " << ssl_ca_file();
_last_error= message.str();
return false;
}
if (SSL_CTX_use_certificate_file(_ctx_ssl, ssl_certificate(), SSL_FILETYPE_PEM) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error loading certificate file " << ssl_certificate();
_last_error= message.str();
return false;
}
if (SSL_CTX_use_PrivateKey_file(_ctx_ssl, ssl_key(), SSL_FILETYPE_PEM) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error loading private key file " << ssl_key();
_last_error= message.str();
return false;
}
if (SSL_CTX_check_private_key(_ctx_ssl) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error check private key.";
_last_error = message.str();
return false;
}
#endif // defined(HAVE_SSL) && HAVE_SSL
return true;
}
#if __GNUC__ >= 7
#pragma GCC diagnostic warning "-Wimplicit-fallthrough"
#endif
bool Instance::run()
{
if (_use_ssl)
{
if (not init_ssl())
{
return false;
}
}
while (not _operations.empty())
{
Operation::vector::value_type operation= _operations.back();
switch (state)
{
case NOT_WRITING:
{
free_addrinfo();
struct addrinfo ai;
memset(&ai, 0, sizeof(struct addrinfo));
ai.ai_socktype= SOCK_STREAM;
ai.ai_protocol= IPPROTO_TCP;
int ret= getaddrinfo(_host.c_str(), _service.c_str(), &ai, &_addrinfo);
if (ret)
{
std::stringstream message;
message << "Failed to connect on " << _host.c_str() << ":" << _service.c_str() << " with " << gai_strerror(ret);
_last_error= message.str();
return false;
}
}
_addrinfo_next= _addrinfo;
state= CONNECT;
break;
case NEXT_CONNECT_ADDRINFO:
if (_addrinfo_next->ai_next == NULL)
{
std::stringstream message;
message << "Error connecting to " << _host.c_str() << "." << std::endl;
_last_error= message.str();
return false;
}
_addrinfo_next= _addrinfo_next->ai_next;
/* fall-thru */
case CONNECT:
close_socket();
_sockfd= socket(_addrinfo_next->ai_family,
_addrinfo_next->ai_socktype,
_addrinfo_next->ai_protocol);
if (_sockfd == INVALID_SOCKET)
{
perror("socket");
continue;
}
if (connect(_sockfd, _addrinfo_next->ai_addr, _addrinfo_next->ai_addrlen) < 0)
{
switch(errno)
{
case EAGAIN:
case EINTR:
state= CONNECT;
break;
case EINPROGRESS:
state= CONNECTING;
break;
case ECONNREFUSED:
case ENETUNREACH:
case ETIMEDOUT:
default:
state= NEXT_CONNECT_ADDRINFO;
break;
}
}
else
{
state= CONNECTING;
}
break;
case CONNECTING:
// Add logic for poll() for nonblocking.
state= CONNECTED;
break;
case CONNECTED:
case WRITING:
{
size_t packet_length= operation->size();
const char *packet= operation->ptr();
#if defined(HAVE_SSL) && HAVE_SSL
if (_ctx_ssl and not _ssl)
{
_ssl= SSL_new(_ctx_ssl);
if (_ssl == NULL)
{
_last_error= "SSL_new() failed";
return false;
}
int ssl_error;
if ((ssl_error= SSL_set_fd(_ssl, _sockfd)) != SSL_SUCCESS)
{
_last_error= "SSL_set_fd() failed";
return false;
}
SSL_set_connect_state(_ssl);
}
#endif
while(packet_length)
{
ssize_t write_size;
#if defined(HAVE_SSL) && HAVE_SSL
if (_ssl)
{
write_size= SSL_write(_ssl, (const void*)packet, int(packet_length));
int ssl_error;
switch ((ssl_error= SSL_get_error(_ssl, int(write_size))))
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_ZERO_RETURN:
errno= ECONNRESET;
write_size= SOCKET_ERROR;
break;
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_X509_LOOKUP:
errno= EAGAIN;
write_size= SOCKET_ERROR;
break;
case SSL_ERROR_SYSCALL:
{
if (errno)
{
write_size= SOCKET_ERROR;
break;
}
}
/* fall-thru */
case SSL_ERROR_SSL:
default:
{
if (ERR_peek_last_error())
{
ssl_error = ERR_peek_last_error();
}
char ssl_error_buffer[SSL_ERROR_SIZE]= { 0 };
ERR_error_string_n(ssl_error, ssl_error_buffer, sizeof(ssl_error_buffer));
_last_error= ssl_error_buffer;
errno= ECONNRESET;
write_size= SOCKET_ERROR;
break;
}
}
}
else
#endif
{
write_size= send(_sockfd, packet, packet_length, 0);
}
if (write_size == SOCKET_ERROR)
{
if (_last_error.empty())
{
std::stringstream msg;
msg << "Failed during send(" << strerror(errno) << ")";
_last_error= msg.str();
}
return false;
}
packet_length-= static_cast<size_t>(write_size);
packet+= static_cast<size_t>(write_size);
}
}
state= READING;
break;
case READING:
if (operation->has_response())
{
ssize_t read_size;
do
{
char buffer[BUFSIZ];
#if defined(HAVE_SSL) && HAVE_SSL
if (_ssl)
{
{
read_size= SSL_read(_ssl, (void *)buffer, sizeof(buffer));
int ssl_error;
switch ((ssl_error= SSL_get_error(_ssl, int(read_size))))
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_ZERO_RETURN:
read_size= 0;
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_X509_LOOKUP:
read_size= SOCKET_ERROR;
errno= EAGAIN;
break;
case SSL_ERROR_SYSCALL:
{
if (errno)
{
std::stringstream msg;
msg << "Error occurred on SSL_acceptsend(" << strerror(errno) << ")";
_last_error= msg.str();
read_size= SOCKET_ERROR;
break;
}
}
/* fall-thru */
case SSL_ERROR_SSL:
default:
{
if (ERR_peek_last_error())
{
ssl_error = ERR_peek_last_error();
}
char ssl_error_buffer[SSL_ERROR_SIZE]= { 0 };
ERR_error_string_n(ssl_error, ssl_error_buffer, sizeof(ssl_error_buffer));
_last_error= ssl_error_buffer;
read_size= SOCKET_ERROR;
break;
}
}
}
}
else
#endif
{
read_size= ::recv(_sockfd, buffer, sizeof(buffer), 0);
}
if (read_size == 0)
{
_last_error.clear();
_last_error+= "Socket was shutdown while reading from ";
_last_error+= _host;
return false;
}
else if (read_size == SOCKET_ERROR)
{
if (_last_error.empty())
{
_last_error.clear();
_last_error+= "Error occurred while reading data from ";
_last_error+= _host;
}
return false;
}
operation->push(buffer, static_cast<size_t>(read_size));
} while (more_to_read());
} // end has_response
state= FINISHED;
break;
case FINISHED:
std::string response;
bool success= operation->response(response);
if (_finish_fn)
{
if (not _finish_fn->call(success, response))
{
// Error was sent from _finish_fn
return false;
}
}
if (operation->reconnect())
{
}
_operations.pop_back();
delete operation;
state= CONNECTED;
break;
} // end switch
}
return true;
} // end run()
bool Instance::more_to_read() const
{
struct pollfd fds;
fds.fd= _sockfd;
fds.events = POLLIN;
if (poll(&fds, 1, 5) < 1) // Default timeout is 5
{
return false;
}
return true;
}
void Instance::close_socket()
{
if (_sockfd != INVALID_SOCKET)
{
/* in case of death shutdown to avoid blocking at close() */
if (shutdown(_sockfd, SHUT_RDWR) == SOCKET_ERROR && get_socket_errno() != ENOTCONN)
{
perror("shutdown");
}
else if (closesocket(_sockfd) == SOCKET_ERROR)
{
perror("close");
}
_sockfd= INVALID_SOCKET;
}
}
void Instance::free_addrinfo()
{
if (_addrinfo)
{
freeaddrinfo(_addrinfo);
_addrinfo= NULL;
_addrinfo_next= NULL;
}
}
} /* namespace util */
} /* namespace datadifferential */
<commit_msg>Tweak error message<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* DataDifferential Utility Library
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* 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.
*
* * The names of its contributors may not 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 "gear_config.h"
#include "util/instance.hpp"
#include "libgearman/ssl.h"
#include <cstdio>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <sstream>
#include <sys/socket.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
namespace datadifferential {
namespace util {
Instance::Instance(const std::string& hostname_arg, const std::string& service_arg) :
_host(hostname_arg),
_service(service_arg),
_sockfd(INVALID_SOCKET),
_use_ssl(false),
state(NOT_WRITING),
_addrinfo(0),
_addrinfo_next(0),
_finish_fn(NULL),
_operations(),
_ctx_ssl(NULL),
_ssl(NULL)
{
}
Instance::Instance(const std::string& hostname_arg, const in_port_t port_arg) :
_host(hostname_arg),
_sockfd(INVALID_SOCKET),
_use_ssl(false),
state(NOT_WRITING),
_addrinfo(0),
_addrinfo_next(0),
_finish_fn(NULL),
_operations(),
_ctx_ssl(NULL),
_ssl(NULL)
{
char tmp[BUFSIZ];
snprintf(tmp, sizeof(tmp), "%u", static_cast<unsigned int>(port_arg));
_service= tmp;
}
Instance::~Instance()
{
close_socket();
free_addrinfo();
for (Operation::vector::iterator iter= _operations.begin(); iter != _operations.end(); ++iter)
{
delete *iter;
}
_operations.clear();
delete _finish_fn;
#if defined(HAVE_SSL) && HAVE_SSL
if (_ssl)
{
SSL_shutdown(_ssl);
SSL_free(_ssl);
}
if (_ctx_ssl)
{
SSL_CTX_free(_ctx_ssl);
}
# if defined(HAVE_WOLFSSL) && HAVE_WOLFSSL
wolfSSL_Cleanup();
# endif // defined(HAVE_WOLFSSL)
#endif
}
bool Instance::init_ssl()
{
#if defined(HAVE_SSL) && HAVE_SSL
SSL_load_error_strings();
SSL_library_init();
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
if ((_ctx_ssl= SSL_CTX_new(TLSv1_2_client_method())) == NULL)
#else
if ((_ctx_ssl= SSL_CTX_new(TLS_client_method())) == NULL)
#endif
{
_last_error= "SSL_CTX_new error";
return false;
}
if (SSL_CTX_load_verify_locations(_ctx_ssl, ssl_ca_file(), 0) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error loading CA file " << ssl_ca_file();
_last_error= message.str();
return false;
}
if (SSL_CTX_use_certificate_file(_ctx_ssl, ssl_certificate(), SSL_FILETYPE_PEM) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error loading certificate file " << ssl_certificate();
_last_error= message.str();
return false;
}
if (SSL_CTX_use_PrivateKey_file(_ctx_ssl, ssl_key(), SSL_FILETYPE_PEM) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error loading private key file " << ssl_key();
_last_error= message.str();
return false;
}
if (SSL_CTX_check_private_key(_ctx_ssl) != SSL_SUCCESS)
{
std::stringstream message;
message << "Error checking private key";
_last_error = message.str();
return false;
}
#endif // defined(HAVE_SSL) && HAVE_SSL
return true;
}
#if __GNUC__ >= 7
#pragma GCC diagnostic warning "-Wimplicit-fallthrough"
#endif
bool Instance::run()
{
if (_use_ssl)
{
if (not init_ssl())
{
return false;
}
}
while (not _operations.empty())
{
Operation::vector::value_type operation= _operations.back();
switch (state)
{
case NOT_WRITING:
{
free_addrinfo();
struct addrinfo ai;
memset(&ai, 0, sizeof(struct addrinfo));
ai.ai_socktype= SOCK_STREAM;
ai.ai_protocol= IPPROTO_TCP;
int ret= getaddrinfo(_host.c_str(), _service.c_str(), &ai, &_addrinfo);
if (ret)
{
std::stringstream message;
message << "Failed to connect on " << _host.c_str() << ":" << _service.c_str() << " with " << gai_strerror(ret);
_last_error= message.str();
return false;
}
}
_addrinfo_next= _addrinfo;
state= CONNECT;
break;
case NEXT_CONNECT_ADDRINFO:
if (_addrinfo_next->ai_next == NULL)
{
std::stringstream message;
message << "Error connecting to " << _host.c_str() << "." << std::endl;
_last_error= message.str();
return false;
}
_addrinfo_next= _addrinfo_next->ai_next;
/* fall-thru */
case CONNECT:
close_socket();
_sockfd= socket(_addrinfo_next->ai_family,
_addrinfo_next->ai_socktype,
_addrinfo_next->ai_protocol);
if (_sockfd == INVALID_SOCKET)
{
perror("socket");
continue;
}
if (connect(_sockfd, _addrinfo_next->ai_addr, _addrinfo_next->ai_addrlen) < 0)
{
switch(errno)
{
case EAGAIN:
case EINTR:
state= CONNECT;
break;
case EINPROGRESS:
state= CONNECTING;
break;
case ECONNREFUSED:
case ENETUNREACH:
case ETIMEDOUT:
default:
state= NEXT_CONNECT_ADDRINFO;
break;
}
}
else
{
state= CONNECTING;
}
break;
case CONNECTING:
// Add logic for poll() for nonblocking.
state= CONNECTED;
break;
case CONNECTED:
case WRITING:
{
size_t packet_length= operation->size();
const char *packet= operation->ptr();
#if defined(HAVE_SSL) && HAVE_SSL
if (_ctx_ssl and not _ssl)
{
_ssl= SSL_new(_ctx_ssl);
if (_ssl == NULL)
{
_last_error= "SSL_new() failed";
return false;
}
int ssl_error;
if ((ssl_error= SSL_set_fd(_ssl, _sockfd)) != SSL_SUCCESS)
{
_last_error= "SSL_set_fd() failed";
return false;
}
SSL_set_connect_state(_ssl);
}
#endif
while(packet_length)
{
ssize_t write_size;
#if defined(HAVE_SSL) && HAVE_SSL
if (_ssl)
{
write_size= SSL_write(_ssl, (const void*)packet, int(packet_length));
int ssl_error;
switch ((ssl_error= SSL_get_error(_ssl, int(write_size))))
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_ZERO_RETURN:
errno= ECONNRESET;
write_size= SOCKET_ERROR;
break;
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_X509_LOOKUP:
errno= EAGAIN;
write_size= SOCKET_ERROR;
break;
case SSL_ERROR_SYSCALL:
{
if (errno)
{
write_size= SOCKET_ERROR;
break;
}
}
/* fall-thru */
case SSL_ERROR_SSL:
default:
{
if (ERR_peek_last_error())
{
ssl_error = ERR_peek_last_error();
}
char ssl_error_buffer[SSL_ERROR_SIZE]= { 0 };
ERR_error_string_n(ssl_error, ssl_error_buffer, sizeof(ssl_error_buffer));
_last_error= ssl_error_buffer;
errno= ECONNRESET;
write_size= SOCKET_ERROR;
break;
}
}
}
else
#endif
{
write_size= send(_sockfd, packet, packet_length, 0);
}
if (write_size == SOCKET_ERROR)
{
if (_last_error.empty())
{
std::stringstream msg;
msg << "Failed during send(" << strerror(errno) << ")";
_last_error= msg.str();
}
return false;
}
packet_length-= static_cast<size_t>(write_size);
packet+= static_cast<size_t>(write_size);
}
}
state= READING;
break;
case READING:
if (operation->has_response())
{
ssize_t read_size;
do
{
char buffer[BUFSIZ];
#if defined(HAVE_SSL) && HAVE_SSL
if (_ssl)
{
{
read_size= SSL_read(_ssl, (void *)buffer, sizeof(buffer));
int ssl_error;
switch ((ssl_error= SSL_get_error(_ssl, int(read_size))))
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_ZERO_RETURN:
read_size= 0;
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_X509_LOOKUP:
read_size= SOCKET_ERROR;
errno= EAGAIN;
break;
case SSL_ERROR_SYSCALL:
{
if (errno)
{
std::stringstream msg;
msg << "Error occurred on SSL_acceptsend(" << strerror(errno) << ")";
_last_error= msg.str();
read_size= SOCKET_ERROR;
break;
}
}
/* fall-thru */
case SSL_ERROR_SSL:
default:
{
if (ERR_peek_last_error())
{
ssl_error = ERR_peek_last_error();
}
char ssl_error_buffer[SSL_ERROR_SIZE]= { 0 };
ERR_error_string_n(ssl_error, ssl_error_buffer, sizeof(ssl_error_buffer));
_last_error= ssl_error_buffer;
read_size= SOCKET_ERROR;
break;
}
}
}
}
else
#endif
{
read_size= ::recv(_sockfd, buffer, sizeof(buffer), 0);
}
if (read_size == 0)
{
_last_error.clear();
_last_error+= "Socket was shutdown while reading from ";
_last_error+= _host;
return false;
}
else if (read_size == SOCKET_ERROR)
{
if (_last_error.empty())
{
_last_error.clear();
_last_error+= "Error occurred while reading data from ";
_last_error+= _host;
}
return false;
}
operation->push(buffer, static_cast<size_t>(read_size));
} while (more_to_read());
} // end has_response
state= FINISHED;
break;
case FINISHED:
std::string response;
bool success= operation->response(response);
if (_finish_fn)
{
if (not _finish_fn->call(success, response))
{
// Error was sent from _finish_fn
return false;
}
}
if (operation->reconnect())
{
}
_operations.pop_back();
delete operation;
state= CONNECTED;
break;
} // end switch
}
return true;
} // end run()
bool Instance::more_to_read() const
{
struct pollfd fds;
fds.fd= _sockfd;
fds.events = POLLIN;
if (poll(&fds, 1, 5) < 1) // Default timeout is 5
{
return false;
}
return true;
}
void Instance::close_socket()
{
if (_sockfd != INVALID_SOCKET)
{
/* in case of death shutdown to avoid blocking at close() */
if (shutdown(_sockfd, SHUT_RDWR) == SOCKET_ERROR && get_socket_errno() != ENOTCONN)
{
perror("shutdown");
}
else if (closesocket(_sockfd) == SOCKET_ERROR)
{
perror("close");
}
_sockfd= INVALID_SOCKET;
}
}
void Instance::free_addrinfo()
{
if (_addrinfo)
{
freeaddrinfo(_addrinfo);
_addrinfo= NULL;
_addrinfo_next= NULL;
}
}
} /* namespace util */
} /* namespace datadifferential */
<|endoftext|> |
<commit_before>#ifndef __ENCODER_HPP
#define __ENCODER_HPP
#ifndef __ODRIVE_MAIN_H
#error "This file should not be included directly. Include odrive_main.h instead."
#endif
class Encoder {
public:
enum Error_t {
ERROR_NONE = 0,
ERROR_UNSTABLE_GAIN = 0x01,
ERROR_CPR_OUT_OF_RANGE = 0x02,
ERROR_NO_RESPONSE = 0x04,
ERROR_UNSUPPORTED_ENCODER_MODE = 0x08,
ERROR_ILLEGAL_HALL_STATE = 0x10,
ERROR_INDEX_NOT_FOUND_YET = 0x20,
};
enum Mode_t {
MODE_INCREMENTAL,
MODE_HALL
};
struct Config_t {
Encoder::Mode_t mode = Encoder::MODE_INCREMENTAL;
bool use_index = false;
bool pre_calibrated = false; // If true, this means the offset stored in
// configuration is valid and does not need
// be determined by run_offset_calibration.
// In this case the encoder will enter ready
// state as soon as the index is found.
float idx_search_speed = 10.0f; // [rad/s electrical]
int32_t cpr = (2048 * 4); // Default resolution of CUI-AMT102 encoder,
int32_t offset = 0; // Offset between encoder count and rotor electrical phase
float offset_float = 0.0f; // Sub-count phase alignment offset
float calib_range = 0.02f;
float bandwidth = 1000.0f;
};
Encoder(const EncoderHardwareConfig_t& hw_config,
Config_t& config);
void setup();
void set_error(Error_t error);
bool do_checks();
void enc_index_cb();
void set_linear_count(int32_t count);
void set_circular_count(int32_t count, bool update_offset);
bool calib_enc_offset(float voltage_magnitude);
bool scan_for_enc_idx(float omega, float voltage_magnitude);
bool run_index_search();
bool run_offset_calibration();
bool update();
void update_pll_gains();
const EncoderHardwareConfig_t& hw_config_;
Config_t& config_;
Axis* axis_ = nullptr; // set by Axis constructor
Error_t error_ = ERROR_NONE;
bool index_found_ = false;
bool is_ready_ = false;
int32_t shadow_count_ = 0;
int32_t count_in_cpr_ = 0;
float interpolation_ = 0.0f;
float phase_ = 0.0f; // [rad]
float pos_estimate_ = 0.0f; // [rad]
float pos_cpr_ = 0.0f; // [rad]
float vel_estimate_ = 0.0f; // [rad/s]
float pll_kp_ = 0.0f; // [rad/s / rad]
float pll_ki_ = 0.0f; // [(rad/s^2) / rad]
// Updated by low_level pwm_adc_cb
uint8_t hall_state_ = 0x0; // bit[0] = HallA, .., bit[2] = HallC
// Communication protocol definitions
auto make_protocol_definitions() {
return make_protocol_member_list(
make_protocol_property("error", &error_),
make_protocol_ro_property("is_ready", &is_ready_),
make_protocol_ro_property("index_found", const_cast<bool*>(&index_found_)),
make_protocol_property("shadow_count", &shadow_count_),
make_protocol_property("count_in_cpr", &count_in_cpr_),
make_protocol_property("interpolation", &interpolation_),
make_protocol_property("phase", &phase_),
make_protocol_property("pos_estimate", &pos_estimate_),
make_protocol_property("pos_cpr", &pos_cpr_),
make_protocol_property("hall_state", &hall_state_),
make_protocol_property("vel_estimate", &vel_estimate_),
// make_protocol_property("pll_kp", &pll_kp_),
// make_protocol_property("pll_ki", &pll_ki_),
make_protocol_object("config",
make_protocol_property("mode", &config_.mode),
make_protocol_property("use_index", &config_.use_index),
make_protocol_property("pre_calibrated", &config_.pre_calibrated),
make_protocol_property("idx_search_speed", &config_.idx_search_speed),
make_protocol_property("cpr", &config_.cpr),
make_protocol_property("offset", &config_.offset),
make_protocol_property("offset_float", &config_.offset_float),
make_protocol_property("bandwidth", &config_.bandwidth,
[](void* ctx) { static_cast<Encoder*>(ctx)->update_pll_gains(); }, this),
make_protocol_property("calib_range", &config_.calib_range)
)
);
}
};
DEFINE_ENUM_FLAG_OPERATORS(Encoder::Error_t)
#endif // __ENCODER_HPP
<commit_msg>fix units comment in encoder.hpp<commit_after>#ifndef __ENCODER_HPP
#define __ENCODER_HPP
#ifndef __ODRIVE_MAIN_H
#error "This file should not be included directly. Include odrive_main.h instead."
#endif
class Encoder {
public:
enum Error_t {
ERROR_NONE = 0,
ERROR_UNSTABLE_GAIN = 0x01,
ERROR_CPR_OUT_OF_RANGE = 0x02,
ERROR_NO_RESPONSE = 0x04,
ERROR_UNSUPPORTED_ENCODER_MODE = 0x08,
ERROR_ILLEGAL_HALL_STATE = 0x10,
ERROR_INDEX_NOT_FOUND_YET = 0x20,
};
enum Mode_t {
MODE_INCREMENTAL,
MODE_HALL
};
struct Config_t {
Encoder::Mode_t mode = Encoder::MODE_INCREMENTAL;
bool use_index = false;
bool pre_calibrated = false; // If true, this means the offset stored in
// configuration is valid and does not need
// be determined by run_offset_calibration.
// In this case the encoder will enter ready
// state as soon as the index is found.
float idx_search_speed = 10.0f; // [rad/s electrical]
int32_t cpr = (2048 * 4); // Default resolution of CUI-AMT102 encoder,
int32_t offset = 0; // Offset between encoder count and rotor electrical phase
float offset_float = 0.0f; // Sub-count phase alignment offset
float calib_range = 0.02f;
float bandwidth = 1000.0f;
};
Encoder(const EncoderHardwareConfig_t& hw_config,
Config_t& config);
void setup();
void set_error(Error_t error);
bool do_checks();
void enc_index_cb();
void set_linear_count(int32_t count);
void set_circular_count(int32_t count, bool update_offset);
bool calib_enc_offset(float voltage_magnitude);
bool scan_for_enc_idx(float omega, float voltage_magnitude);
bool run_index_search();
bool run_offset_calibration();
bool update();
void update_pll_gains();
const EncoderHardwareConfig_t& hw_config_;
Config_t& config_;
Axis* axis_ = nullptr; // set by Axis constructor
Error_t error_ = ERROR_NONE;
bool index_found_ = false;
bool is_ready_ = false;
int32_t shadow_count_ = 0;
int32_t count_in_cpr_ = 0;
float interpolation_ = 0.0f;
float phase_ = 0.0f; // [count]
float pos_estimate_ = 0.0f; // [count]
float pos_cpr_ = 0.0f; // [count]
float vel_estimate_ = 0.0f; // [count/s]
float pll_kp_ = 0.0f; // [count/s / count]
float pll_ki_ = 0.0f; // [(count/s^2) / count]
// Updated by low_level pwm_adc_cb
uint8_t hall_state_ = 0x0; // bit[0] = HallA, .., bit[2] = HallC
// Communication protocol definitions
auto make_protocol_definitions() {
return make_protocol_member_list(
make_protocol_property("error", &error_),
make_protocol_ro_property("is_ready", &is_ready_),
make_protocol_ro_property("index_found", const_cast<bool*>(&index_found_)),
make_protocol_property("shadow_count", &shadow_count_),
make_protocol_property("count_in_cpr", &count_in_cpr_),
make_protocol_property("interpolation", &interpolation_),
make_protocol_property("phase", &phase_),
make_protocol_property("pos_estimate", &pos_estimate_),
make_protocol_property("pos_cpr", &pos_cpr_),
make_protocol_property("hall_state", &hall_state_),
make_protocol_property("vel_estimate", &vel_estimate_),
// make_protocol_property("pll_kp", &pll_kp_),
// make_protocol_property("pll_ki", &pll_ki_),
make_protocol_object("config",
make_protocol_property("mode", &config_.mode),
make_protocol_property("use_index", &config_.use_index),
make_protocol_property("pre_calibrated", &config_.pre_calibrated),
make_protocol_property("idx_search_speed", &config_.idx_search_speed),
make_protocol_property("cpr", &config_.cpr),
make_protocol_property("offset", &config_.offset),
make_protocol_property("offset_float", &config_.offset_float),
make_protocol_property("bandwidth", &config_.bandwidth,
[](void* ctx) { static_cast<Encoder*>(ctx)->update_pll_gains(); }, this),
make_protocol_property("calib_range", &config_.calib_range)
)
);
}
};
DEFINE_ENUM_FLAG_OPERATORS(Encoder::Error_t)
#endif // __ENCODER_HPP
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include "resource.hh"
#include "core/align.hh"
#ifdef HAVE_HWLOC
#include "util/defer.hh"
#include <hwloc.h>
#include <unordered_map>
cpu_set_t cpuid_to_cpuset(unsigned cpuid) {
cpu_set_t cs;
CPU_ZERO(&cs);
CPU_SET(cpuid, &cs);
return cs;
}
namespace resource {
size_t div_roundup(size_t num, size_t denom) {
return (num + denom - 1) / denom;
}
static unsigned find_memory_depth(hwloc_topology_t& topology) {
auto depth = hwloc_get_type_depth(topology, HWLOC_OBJ_PU);
auto obj = hwloc_get_next_obj_by_depth(topology, depth, nullptr);
while (!obj->memory.local_memory && obj) {
obj = hwloc_get_ancestor_obj_by_depth(topology, --depth, obj);
}
assert(obj);
return depth;
}
static size_t alloc_from_node(cpu& this_cpu, hwloc_obj_t node, std::unordered_map<hwloc_obj_t, size_t>& used_mem, size_t alloc) {
auto taken = std::min(node->memory.local_memory - used_mem[node], alloc);
if (taken) {
used_mem[node] += taken;
auto node_id = hwloc_bitmap_first(node->nodeset);
assert(node_id != -1);
this_cpu.mem.push_back({taken, unsigned(node_id)});
}
return taken;
}
std::vector<cpu> allocate(configuration c) {
hwloc_topology_t topology;
hwloc_topology_init(&topology);
auto free_hwloc = defer([&] { hwloc_topology_destroy(topology); });
hwloc_topology_load(topology);
if (c.cpu_set) {
auto bm = hwloc_bitmap_alloc();
auto free_bm = defer([&] { hwloc_bitmap_free(bm); });
for (auto idx : *c.cpu_set) {
hwloc_bitmap_set(bm, idx);
}
auto r = hwloc_topology_restrict(topology, bm,
HWLOC_RESTRICT_FLAG_ADAPT_DISTANCES
| HWLOC_RESTRICT_FLAG_ADAPT_MISC
| HWLOC_RESTRICT_FLAG_ADAPT_IO);
if (r == -1) {
if (errno == ENOMEM) {
throw std::bad_alloc();
}
if (errno == EINVAL) {
throw std::runtime_error("bad cpuset");
}
abort();
}
}
auto machine_depth = hwloc_get_type_depth(topology, HWLOC_OBJ_MACHINE);
assert(hwloc_get_nbobjs_by_depth(topology, machine_depth) == 1);
auto machine = hwloc_get_obj_by_depth(topology, machine_depth, 0);
auto available_memory = machine->memory.total_memory;
available_memory -= c.reserve_memory.value_or(256 << 20);
size_t mem = c.total_memory.value_or(available_memory);
if (mem > available_memory) {
throw std::runtime_error("insufficient physical memory");
}
unsigned available_procs = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);
unsigned procs = c.cpus.value_or(available_procs);
if (procs > available_procs) {
throw std::runtime_error("insufficient processing units");
}
auto mem_per_proc = align_down<size_t>(mem / procs, 2 << 20);
std::vector<hwloc_cpuset_t> cpu_sets{procs};
auto free_cpu_sets = defer([&] {
for (auto&& cs : cpu_sets) {
hwloc_bitmap_free(cs);
}
});
auto root = hwloc_get_root_obj(topology);
#if HWLOC_API_VERSION >= 0x00010900
hwloc_distrib(topology, &root, 1, cpu_sets.data(), cpu_sets.size(), INT_MAX, 0);
#else
hwloc_distribute(topology, root, cpu_sets.data(), cpu_sets.size(), INT_MAX);
#endif
std::vector<cpu> ret;
std::unordered_map<hwloc_obj_t, size_t> topo_used_mem;
std::vector<std::pair<cpu, size_t>> remains;
size_t remain;
unsigned depth = find_memory_depth(topology);
// Divide local memory to cpus
for (auto&& cs : cpu_sets) {
auto cpu_id = hwloc_bitmap_first(cs);
assert(cpu_id != -1);
auto pu = hwloc_get_pu_obj_by_os_index(topology, cpu_id);
auto node = hwloc_get_ancestor_obj_by_depth(topology, depth, pu);
cpu this_cpu;
this_cpu.cpu_id = cpu_id;
remain = mem_per_proc - alloc_from_node(this_cpu, node, topo_used_mem, mem_per_proc);
remains.emplace_back(std::move(this_cpu), remain);
}
// Divide the rest of the memory
for (auto&& r : remains) {
cpu this_cpu;
size_t remain;
std::tie(this_cpu, remain) = r;
auto pu = hwloc_get_pu_obj_by_os_index(topology, this_cpu.cpu_id);
auto node = hwloc_get_ancestor_obj_by_depth(topology, depth, pu);
auto obj = node;
while (remain) {
remain -= alloc_from_node(this_cpu, obj, topo_used_mem, remain);
do {
obj = hwloc_get_next_obj_by_depth(topology, depth, obj);
} while (!obj);
if (obj == node)
break;
}
assert(!remain);
ret.push_back(std::move(this_cpu));
}
return ret;
}
unsigned nr_processing_units() {
hwloc_topology_t topology;
hwloc_topology_init(&topology);
auto free_hwloc = defer([&] { hwloc_topology_destroy(topology); });
hwloc_topology_load(topology);
return hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);
}
}
#else
#include "resource.hh"
#include <unistd.h>
namespace resource {
std::vector<cpu> allocate(configuration c) {
auto available_memory = ::sysconf(_SC_PAGESIZE) * size_t(::sysconf(_SC_PHYS_PAGES));
available_memory -= c.reserve_memory.value_or(256 << 20);
size_t mem = c.total_memory.value_or(available_memory);
if (mem > available_memory) {
throw std::runtime_error("insufficient physical memory");
}
auto cpuset_procs = c.cpu_set ? c.cpu_set->size() : nr_processing_units();
auto procs = c.cpus.value_or(cpuset_procs);
std::vector<cpu> ret;
ret.reserve(procs);
for (unsigned i = 0; i < procs; ++i) {
ret.push_back(cpu{i, {{mem / procs, 0}}});
}
return ret;
}
unsigned nr_processing_units() {
return ::sysconf(_SC_NPROCESSORS_ONLN);
}
}
#endif
<commit_msg>resource: increase default reserve memory<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include "resource.hh"
#include "core/align.hh"
#ifdef HAVE_HWLOC
#include "util/defer.hh"
#include <hwloc.h>
#include <unordered_map>
cpu_set_t cpuid_to_cpuset(unsigned cpuid) {
cpu_set_t cs;
CPU_ZERO(&cs);
CPU_SET(cpuid, &cs);
return cs;
}
namespace resource {
size_t div_roundup(size_t num, size_t denom) {
return (num + denom - 1) / denom;
}
static unsigned find_memory_depth(hwloc_topology_t& topology) {
auto depth = hwloc_get_type_depth(topology, HWLOC_OBJ_PU);
auto obj = hwloc_get_next_obj_by_depth(topology, depth, nullptr);
while (!obj->memory.local_memory && obj) {
obj = hwloc_get_ancestor_obj_by_depth(topology, --depth, obj);
}
assert(obj);
return depth;
}
static size_t alloc_from_node(cpu& this_cpu, hwloc_obj_t node, std::unordered_map<hwloc_obj_t, size_t>& used_mem, size_t alloc) {
auto taken = std::min(node->memory.local_memory - used_mem[node], alloc);
if (taken) {
used_mem[node] += taken;
auto node_id = hwloc_bitmap_first(node->nodeset);
assert(node_id != -1);
this_cpu.mem.push_back({taken, unsigned(node_id)});
}
return taken;
}
std::vector<cpu> allocate(configuration c) {
hwloc_topology_t topology;
hwloc_topology_init(&topology);
auto free_hwloc = defer([&] { hwloc_topology_destroy(topology); });
hwloc_topology_load(topology);
if (c.cpu_set) {
auto bm = hwloc_bitmap_alloc();
auto free_bm = defer([&] { hwloc_bitmap_free(bm); });
for (auto idx : *c.cpu_set) {
hwloc_bitmap_set(bm, idx);
}
auto r = hwloc_topology_restrict(topology, bm,
HWLOC_RESTRICT_FLAG_ADAPT_DISTANCES
| HWLOC_RESTRICT_FLAG_ADAPT_MISC
| HWLOC_RESTRICT_FLAG_ADAPT_IO);
if (r == -1) {
if (errno == ENOMEM) {
throw std::bad_alloc();
}
if (errno == EINVAL) {
throw std::runtime_error("bad cpuset");
}
abort();
}
}
auto machine_depth = hwloc_get_type_depth(topology, HWLOC_OBJ_MACHINE);
assert(hwloc_get_nbobjs_by_depth(topology, machine_depth) == 1);
auto machine = hwloc_get_obj_by_depth(topology, machine_depth, 0);
auto available_memory = machine->memory.total_memory;
available_memory -= c.reserve_memory.value_or(256 << 20);
size_t mem = c.total_memory.value_or(available_memory);
if (mem > available_memory) {
throw std::runtime_error("insufficient physical memory");
}
unsigned available_procs = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);
unsigned procs = c.cpus.value_or(available_procs);
if (procs > available_procs) {
throw std::runtime_error("insufficient processing units");
}
auto mem_per_proc = align_down<size_t>(mem / procs, 2 << 20);
std::vector<hwloc_cpuset_t> cpu_sets{procs};
auto free_cpu_sets = defer([&] {
for (auto&& cs : cpu_sets) {
hwloc_bitmap_free(cs);
}
});
auto root = hwloc_get_root_obj(topology);
#if HWLOC_API_VERSION >= 0x00010900
hwloc_distrib(topology, &root, 1, cpu_sets.data(), cpu_sets.size(), INT_MAX, 0);
#else
hwloc_distribute(topology, root, cpu_sets.data(), cpu_sets.size(), INT_MAX);
#endif
std::vector<cpu> ret;
std::unordered_map<hwloc_obj_t, size_t> topo_used_mem;
std::vector<std::pair<cpu, size_t>> remains;
size_t remain;
unsigned depth = find_memory_depth(topology);
// Divide local memory to cpus
for (auto&& cs : cpu_sets) {
auto cpu_id = hwloc_bitmap_first(cs);
assert(cpu_id != -1);
auto pu = hwloc_get_pu_obj_by_os_index(topology, cpu_id);
auto node = hwloc_get_ancestor_obj_by_depth(topology, depth, pu);
cpu this_cpu;
this_cpu.cpu_id = cpu_id;
remain = mem_per_proc - alloc_from_node(this_cpu, node, topo_used_mem, mem_per_proc);
remains.emplace_back(std::move(this_cpu), remain);
}
// Divide the rest of the memory
for (auto&& r : remains) {
cpu this_cpu;
size_t remain;
std::tie(this_cpu, remain) = r;
auto pu = hwloc_get_pu_obj_by_os_index(topology, this_cpu.cpu_id);
auto node = hwloc_get_ancestor_obj_by_depth(topology, depth, pu);
auto obj = node;
while (remain) {
remain -= alloc_from_node(this_cpu, obj, topo_used_mem, remain);
do {
obj = hwloc_get_next_obj_by_depth(topology, depth, obj);
} while (!obj);
if (obj == node)
break;
}
assert(!remain);
ret.push_back(std::move(this_cpu));
}
return ret;
}
unsigned nr_processing_units() {
hwloc_topology_t topology;
hwloc_topology_init(&topology);
auto free_hwloc = defer([&] { hwloc_topology_destroy(topology); });
hwloc_topology_load(topology);
return hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);
}
}
#else
#include "resource.hh"
#include <unistd.h>
namespace resource {
std::vector<cpu> allocate(configuration c) {
auto available_memory = ::sysconf(_SC_PAGESIZE) * size_t(::sysconf(_SC_PHYS_PAGES));
auto default_reserve_memory = std::max<size_t>(1 << 30, 0.05 * available_memory);
available_memory -= c.reserve_memory.value_or(default_reserve_memory);
size_t mem = c.total_memory.value_or(available_memory);
if (mem > available_memory) {
throw std::runtime_error("insufficient physical memory");
}
auto cpuset_procs = c.cpu_set ? c.cpu_set->size() : nr_processing_units();
auto procs = c.cpus.value_or(cpuset_procs);
std::vector<cpu> ret;
ret.reserve(procs);
for (unsigned i = 0; i < procs; ++i) {
ret.push_back(cpu{i, {{mem / procs, 0}}});
}
return ret;
}
unsigned nr_processing_units() {
return ::sysconf(_SC_NPROCESSORS_ONLN);
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Flagging as flaky again, they like to fail with some frequency on Chromium XP but not the testers.<commit_after><|endoftext|> |
<commit_before>/* Copyright (C) 2006-2008 Joris Mooij [j dot mooij at science dot ru dot nl]
Radboud University Nijmegen, The Netherlands
This file is part of libDAI.
libDAI 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 2 of the License, or
(at your option) any later version.
libDAI 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 libDAI; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <dai/factorgraph.h>
using namespace dai;
using namespace std;
int main( int argc, char *argv[] ) {
if( argc != 3 ) {
cout << "Usage: " << argv[0] << " <in.fg> <out.dot>" << endl << endl;
cout << "Converts a .fg (FactorGraph) file to a .dot (GraphViz) file for visualization." << endl;
cout << "The .dot file can be converted to .ps (PostScript by 'neato -T ps out.dot > out.ps'" << endl;
return 1;
} else {
// Read factorgraph
FactorGraph fg;
char *infile = argv[1];
if( fg.ReadFromFile( infile ) ) {
cerr << "Error reading file " << infile << endl;
return 2;
} else {
if( string( argv[2] ) == "-" )
fg.WriteToDotFile( argv[2] );
else {
cout << "graph G {" << endl;
cout << "graph[size=\"9,9\"];" << endl;
cout << "node[shape=circle,width=0.4,fixedsize=true];" << endl;
for( size_t i = 0; i < fg.nrVars(); i++ )
cout << "\tx" << fg.var(i).label() << ";" << endl;
cout << "node[shape=box,style=filled,color=lightgrey,width=0.3,height=0.3,fixedsize=true];" << endl;
for( size_t I = 0; I < fg.nrFactors(); I++ )
cout << "\tp" << I << ";" << endl;
for( size_t iI = 0; iI < fg.nr_edges(); iI++ )
cout << "\tx" << fg.var(fg.edge(iI).first).label() << " -- p" << fg.edge(iI).second << ";" << endl;
cout << "}" << endl;
}
return 0;
}
}
}
<commit_msg>Fixed little bug in fg2dot.cpp<commit_after>/* Copyright (C) 2006-2008 Joris Mooij [j dot mooij at science dot ru dot nl]
Radboud University Nijmegen, The Netherlands
This file is part of libDAI.
libDAI 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 2 of the License, or
(at your option) any later version.
libDAI 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 libDAI; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <dai/factorgraph.h>
using namespace dai;
using namespace std;
int main( int argc, char *argv[] ) {
if( argc != 3 ) {
cout << "Usage: " << argv[0] << " <in.fg> <out.dot>" << endl << endl;
cout << "Converts a .fg (FactorGraph) file to a .dot (GraphViz) file for visualization." << endl;
cout << "The .dot file can be converted to .ps (PostScript by 'neato -T ps out.dot > out.ps'" << endl;
return 1;
} else {
// Read factorgraph
FactorGraph fg;
char *infile = argv[1];
if( fg.ReadFromFile( infile ) ) {
cerr << "Error reading file " << infile << endl;
return 2;
} else {
if( string( argv[2] ) != "-" )
fg.WriteToDotFile( argv[2] );
else {
cout << "graph G {" << endl;
cout << "graph[size=\"9,9\"];" << endl;
cout << "node[shape=circle,width=0.4,fixedsize=true];" << endl;
for( size_t i = 0; i < fg.nrVars(); i++ )
cout << "\tx" << fg.var(i).label() << ";" << endl;
cout << "node[shape=box,style=filled,color=lightgrey,width=0.3,height=0.3,fixedsize=true];" << endl;
for( size_t I = 0; I < fg.nrFactors(); I++ )
cout << "\tp" << I << ";" << endl;
for( size_t iI = 0; iI < fg.nr_edges(); iI++ )
cout << "\tx" << fg.var(fg.edge(iI).first).label() << " -- p" << fg.edge(iI).second << ";" << endl;
cout << "}" << endl;
}
return 0;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) {
ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<commit_msg>disable toolstrip test for chromeos/linux_view<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#if !defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) {
ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2008 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/user_script_master.h"
#include <fstream>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
// Test bringing up a master on a specific directory, putting a script in there, etc.
class UserScriptMasterTest : public testing::Test,
public NotificationObserver {
public:
UserScriptMasterTest() : shared_memory_(NULL) {}
virtual void SetUp() {
// Name a subdirectory of the temp directory.
FilePath tmp_dir;
ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &tmp_dir));
script_dir_ = tmp_dir.AppendASCII("UserScriptTest");
// Create a fresh, empty copy of this directory.
file_util::Delete(script_dir_, true);
file_util::CreateDirectory(script_dir_);
// Register for all user script notifications.
NotificationService::current()->AddObserver(this,
NOTIFY_USER_SCRIPTS_LOADED,
NotificationService::AllSources());
}
virtual void TearDown() {
NotificationService::current()->RemoveObserver(this,
NOTIFY_USER_SCRIPTS_LOADED,
NotificationService::AllSources());
// Clean up test directory.
ASSERT_TRUE(file_util::Delete(script_dir_, true));
ASSERT_FALSE(file_util::PathExists(script_dir_));
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NOTIFY_USER_SCRIPTS_LOADED);
shared_memory_ = Details<base::SharedMemory>(details).ptr();
if (MessageLoop::current() == &message_loop_)
MessageLoop::current()->Quit();
}
// MessageLoop used in tests.
MessageLoop message_loop_;
// Directory containing user scripts.
FilePath script_dir_;
// Updated to the script shared memory when we get notified.
base::SharedMemory* shared_memory_;
};
// Test that we *don't* get spurious notifications.
TEST_F(UserScriptMasterTest, NoScripts) {
// Set shared_memory_ to something non-NULL, so we can check it became NULL.
shared_memory_ = reinterpret_cast<base::SharedMemory*>(1);
scoped_refptr<UserScriptMaster> master(
new UserScriptMaster(MessageLoop::current(), script_dir_));
master->StartScan();
message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
message_loop_.Run();
// There were no scripts in the script dir, so we shouldn't have gotten
// a notification.
ASSERT_EQ(NULL, shared_memory_);
}
// Test that we get notified about new scripts after they're added.
TEST_F(UserScriptMasterTest, NewScripts) {
scoped_refptr<UserScriptMaster> master(
new UserScriptMaster(MessageLoop::current(), script_dir_));
FilePath path = script_dir_.AppendASCII("script.user.js");
FILE* file = file_util::OpenFile(path, "w");
const char content[] = "some content";
fwrite(content, 1, arraysize(content), file);
file_util::CloseFile(file);
message_loop_.Run();
ASSERT_TRUE(shared_memory_ != NULL);
}
// Test that we get notified about scripts if they're already in the test dir.
TEST_F(UserScriptMasterTest, ExistingScripts) {
FilePath path = script_dir_.AppendASCII("script.user.js");
FILE* file = file_util::OpenFile(path, "w");
const char content[] = "some content";
fwrite(content, 1, arraysize(content), file);
file_util::CloseFile(file);
scoped_refptr<UserScriptMaster> master(
new UserScriptMaster(MessageLoop::current(), script_dir_));
master->StartScan();
message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
message_loop_.Run();
ASSERT_TRUE(shared_memory_ != NULL);
}
TEST_F(UserScriptMasterTest, Parse1) {
const std::string text(
"// This is my awesome script\n"
"// It does stuff.\n"
"// ==UserScript== trailing garbage\n"
"// @name foobar script\n"
"// @namespace http://www.google.com/\n"
"// @include *mail.google.com*\n"
"// \n"
"// @othergarbage\n"
"// @include *mail.yahoo.com*\r\n"
"// @include \t *mail.msn.com*\n" // extra spaces after "@include" OK
"//@include not-recognized\n" // must have one space after "//"
"// ==/UserScript== trailing garbage\n"
"\n"
"\n"
"alert('hoo!');\n");
std::vector<std::string> includes;
UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &includes);
EXPECT_EQ(3U, includes.size());
EXPECT_EQ("*mail.google.com*", includes[0]);
EXPECT_EQ("*mail.yahoo.com*", includes[1]);
EXPECT_EQ("*mail.msn.com*", includes[2]);
}
TEST_F(UserScriptMasterTest, Parse2) {
const std::string text("default to @include *");
std::vector<std::string> includes;
UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &includes);
EXPECT_EQ(1U, includes.size());
EXPECT_EQ("*", includes[0]);
}
TEST_F(UserScriptMasterTest, Parse3) {
const std::string text(
"// ==UserScript==\n"
"// @include *foo*\n"
"// ==/UserScript=="); // no trailing newline
std::vector<std::string> includes;
UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &includes);
EXPECT_EQ(1U, includes.size());
EXPECT_EQ("*foo*", includes[0]);
}
<commit_msg>Temporarily disable failing test while I fix it.<commit_after>// Copyright (c) 2008 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/user_script_master.h"
#include <fstream>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
// Test bringing up a master on a specific directory, putting a script in there, etc.
class UserScriptMasterTest : public testing::Test,
public NotificationObserver {
public:
UserScriptMasterTest() : shared_memory_(NULL) {}
virtual void SetUp() {
// Name a subdirectory of the temp directory.
FilePath tmp_dir;
ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &tmp_dir));
script_dir_ = tmp_dir.AppendASCII("UserScriptTest");
// Create a fresh, empty copy of this directory.
file_util::Delete(script_dir_, true);
file_util::CreateDirectory(script_dir_);
// Register for all user script notifications.
NotificationService::current()->AddObserver(this,
NOTIFY_USER_SCRIPTS_LOADED,
NotificationService::AllSources());
}
virtual void TearDown() {
NotificationService::current()->RemoveObserver(this,
NOTIFY_USER_SCRIPTS_LOADED,
NotificationService::AllSources());
// Clean up test directory.
ASSERT_TRUE(file_util::Delete(script_dir_, true));
ASSERT_FALSE(file_util::PathExists(script_dir_));
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NOTIFY_USER_SCRIPTS_LOADED);
shared_memory_ = Details<base::SharedMemory>(details).ptr();
if (MessageLoop::current() == &message_loop_)
MessageLoop::current()->Quit();
}
// MessageLoop used in tests.
MessageLoop message_loop_;
// Directory containing user scripts.
FilePath script_dir_;
// Updated to the script shared memory when we get notified.
base::SharedMemory* shared_memory_;
};
// Test that we *don't* get spurious notifications.
TEST_F(UserScriptMasterTest, DISABLED_NoScripts) {
// Set shared_memory_ to something non-NULL, so we can check it became NULL.
shared_memory_ = reinterpret_cast<base::SharedMemory*>(1);
scoped_refptr<UserScriptMaster> master(
new UserScriptMaster(MessageLoop::current(), script_dir_));
master->StartScan();
message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
message_loop_.Run();
// There were no scripts in the script dir, so we shouldn't have gotten
// a notification.
ASSERT_EQ(NULL, shared_memory_);
}
// Test that we get notified about new scripts after they're added.
TEST_F(UserScriptMasterTest, NewScripts) {
scoped_refptr<UserScriptMaster> master(
new UserScriptMaster(MessageLoop::current(), script_dir_));
FilePath path = script_dir_.AppendASCII("script.user.js");
FILE* file = file_util::OpenFile(path, "w");
const char content[] = "some content";
fwrite(content, 1, arraysize(content), file);
file_util::CloseFile(file);
message_loop_.Run();
ASSERT_TRUE(shared_memory_ != NULL);
}
// Test that we get notified about scripts if they're already in the test dir.
TEST_F(UserScriptMasterTest, ExistingScripts) {
FilePath path = script_dir_.AppendASCII("script.user.js");
FILE* file = file_util::OpenFile(path, "w");
const char content[] = "some content";
fwrite(content, 1, arraysize(content), file);
file_util::CloseFile(file);
scoped_refptr<UserScriptMaster> master(
new UserScriptMaster(MessageLoop::current(), script_dir_));
master->StartScan();
message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
message_loop_.Run();
ASSERT_TRUE(shared_memory_ != NULL);
}
TEST_F(UserScriptMasterTest, Parse1) {
const std::string text(
"// This is my awesome script\n"
"// It does stuff.\n"
"// ==UserScript== trailing garbage\n"
"// @name foobar script\n"
"// @namespace http://www.google.com/\n"
"// @include *mail.google.com*\n"
"// \n"
"// @othergarbage\n"
"// @include *mail.yahoo.com*\r\n"
"// @include \t *mail.msn.com*\n" // extra spaces after "@include" OK
"//@include not-recognized\n" // must have one space after "//"
"// ==/UserScript== trailing garbage\n"
"\n"
"\n"
"alert('hoo!');\n");
std::vector<std::string> includes;
UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &includes);
EXPECT_EQ(3U, includes.size());
EXPECT_EQ("*mail.google.com*", includes[0]);
EXPECT_EQ("*mail.yahoo.com*", includes[1]);
EXPECT_EQ("*mail.msn.com*", includes[2]);
}
TEST_F(UserScriptMasterTest, Parse2) {
const std::string text("default to @include *");
std::vector<std::string> includes;
UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &includes);
EXPECT_EQ(1U, includes.size());
EXPECT_EQ("*", includes[0]);
}
TEST_F(UserScriptMasterTest, Parse3) {
const std::string text(
"// ==UserScript==\n"
"// @include *foo*\n"
"// ==/UserScript=="); // no trailing newline
std::vector<std::string> includes;
UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &includes);
EXPECT_EQ(1U, includes.size());
EXPECT_EQ("*foo*", includes[0]);
}
<|endoftext|> |
<commit_before>/*
*********************************************************
Author: *
this file provides the detector algorithm for HMPID. *
*********************************************************
*/
extern "C" {
#include <daqDA.h>
}
#include "event.h"
#include "monitor.h"
#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>
//AliRoot
#include "AliHMPIDRawStream.h"
#include "AliHMPIDCalib.h"
#include "AliRawReaderDate.h"
#include "AliBitPacking.h"
#include "TMath.h"
//ROOT
#include "TFile.h"
#include "TSystem.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TMath.h"
#include "TRandom.h"
int main(int argc, char **argv){
int status;
/* log start of process */
printf("HMPID DA program started\n");
/* check that we got some arguments = list of files */
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;
}
/* copy locally a file from daq detector config db
status=daqDA_DB_getFile("myconfig","./myconfig.txt");
if (status) {
printf("Failed to get config file : %d\n",status);
return -1;
}
and possibly use it */
/* report progress */
daqDA_progressReport(10);
/* init the pedestal calculation */
AliHMPIDCalib *pCal=new AliHMPIDCalib();
/* init event counter */
Int_t iEvtNcal=0;
Int_t cnt=0;
int n;
for (n=1;n<argc;n++) {
status=monitorSetDataSource( argv[n] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* report progress */
/* in this example, indexed on the number of files */
daqDA_progressReport(10+80*n/argc);
for(;;) { // infinite loop
struct eventHeaderStruct *event;
eventTypeType eventT;
/* get next event */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) /* end of monitoring file has been reached */
{
printf("End of monitoring file has been reached! \n");
break;
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* retry if got no event */
if (event==NULL) {
//break;
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) { //we use PHYSICS_EVENT for pedestal not CALIBRATION_EVENT
iEvtNcal++;
AliRawReader *reader = new AliRawReaderDate((void*)event);
// Temporary there. Shall be removed as soon as the equipment ID is set correctly
// For the moment ddl.map file contains one line which maps
// the observed eqID=225 to the first HMPID DDL with ID=1536
// reader->LoadEquipmentIdsMap("ddl.map");
AliHMPIDRawStream stream(reader);
while(stream.Next()) {
Int_t nDDL=stream.GetDDLNumber();
for(Int_t row = 1; row <=AliHMPIDRawStream::kNRows; row++){
for(Int_t dil = 1; dil <=AliHMPIDRawStream::kNDILOGICAdd; dil++){
for(Int_t pad = 0; pad < AliHMPIDRawStream::kNPadAdd; pad++){
pCal->FillPedestal(nDDL,row,dil,pad,stream.GetCharge(nDDL,row,dil,pad));
}//pad
}//dil
}//row
} //raw data loop
delete reader;
}// if CALIBRATION_EVENT
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
} // events loop
free(event);
}
}//arg
/* write report */
printf("Run #%s, received %d calibration events\n",getenv("DATE_RUN_NUMBER"),iEvtNcal);
if (!iEvtNcal) {
printf("No calibration events have been read. Exiting\n");
return -1;
}
/* report progress */
daqDA_progressReport(90);
for(Int_t nDDL=0; nDDL < AliHMPIDCalib::kNDDL; nDDL++) {
/* Calculate pedestal for the given ddl, if there is no ddl go t next */
if(!pCal->CalcPedestal(nDDL,Form("./HmpidPedDdl%02i.txt",nDDL),iEvtNcal)) continue;
/* store the result file on FES */
status=daqDA_FES_storeFile(Form("./HmpidPedDdl%02i.txt",nDDL),Form("HMPID_DA_Pedestals_ddl=%02i",nDDL));
if (status) {
printf("Failed to export file : %d\n",status);
return -1;
}
}//nDDL
/* report progress */
daqDA_progressReport(100);
return status;
}
<commit_msg>Updated error definitions.<commit_after>/*
HMPID DA for online calibration
Contact: Levente.Molnar@ba.infn.it, Giacomo.Volpe@ba.infn.it
Link: http://richpc1.ba.infn.it/~levente/Files4Public/ValidateHmpidDA/
Run Type: PEDESTAL -- but we select on the PHYSICS_EVENTS in th HMPIDda.cxx
DA Type: LDC
Number of events needed: 1000 events
Input Files: Raw pedestal file, no external config file
Output Files: 14 txt files including pedestal values
Trigger types used: PEDESTAL RUN (selecting on PHYSICS_EVENT)
*/
extern "C" {
#include <daqDA.h>
}
#include "event.h"
#include "monitor.h"
#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>
//AliRoot
#include "AliHMPIDRawStream.h"
#include "AliHMPIDCalib.h"
#include "AliRawReaderDate.h"
#include "AliBitPacking.h"
#include "TMath.h"
//ROOT
#include "TFile.h"
#include "TSystem.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TMath.h"
#include "TRandom.h"
int main(int argc, char **argv){
int status;
/* log start of process */
printf("HMPID DA program started\n");
/* check that we got some arguments = list of files */
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;
}
/* copy locally a file from daq detector config db
status=daqDA_DB_getFile("myconfig","./myconfig.txt");
if (status) {
printf("Failed to get config file : %d\n",status);
return -1;
}
and possibly use it */
/* report progress */
daqDA_progressReport(10);
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* init the pedestal calculation */
AliHMPIDCalib *pCal=new AliHMPIDCalib();
/* init event counter */
Int_t iEvtNcal=0;
ULong_t runNum=0;
int n;
for (n=1;n<argc;n++) {
status=monitorSetDataSource( argv[n] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* report progress */
/* in this example, indexed on the number of files */
daqDA_progressReport(10+80*n/argc);
for(;;) { // infinite loop
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
struct eventHeaderStruct *event;
eventTypeType eventT;
/* get next event */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) /* end of monitoring file has been reached */
{
printf("End of monitoring file has been reached! \n");
break;
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* retry if got no event */
if (event==NULL) {
//break;
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) { //we use PHYSICS_EVENT for pedestal not CALIBRATION_EVENT
runNum=(unsigned long)event->eventRunNb; //assuming that only one run is processed at a time
iEvtNcal++;
AliRawReader *reader = new AliRawReaderDate((void*)event);
AliHMPIDRawStream stream(reader);
while(stream.Next())
{
for(Int_t iPad=0;iPad<stream.GetNPads();iPad++) {
pCal->FillPedestal(stream.GetPadArray()[iPad],stream.GetChargeArray()[iPad]);
}
for(Int_t iddl=0;iddl<AliHMPIDRawStream::kNDDL;iddl++){
for(Int_t ierr=0; ierr < AliHMPIDRawStream::kSumErr; ierr++) {
pCal->FillErrors(iddl,ierr,stream.GetErrors(iddl,ierr));
}
}
}//Next()
stream.Delete();
}// if CALIBRATION_EVENT
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
} // events loop
free(event);
}
}//arg
/* write report */
printf("HMPID DA processed RUN #%s, with %d calibration events\n",getenv("DATE_RUN_NUMBER"),iEvtNcal);
if (!iEvtNcal) {
printf("No calibration events have been read. Exiting\n");
return -1;
}
/* report progress */
daqDA_progressReport(90);
for(Int_t nDDL=0; nDDL < AliHMPIDCalib::kNDDL; nDDL++) {
/* Calculate pedestal for the given ddl, if there is no ddl go t next */
if(!pCal->CalcPedestal(runNum,nDDL,Form("./HmpidPedDdl%02i.txt",nDDL),iEvtNcal)) continue;
if(!pCal->WriteErrors(runNum,nDDL,Form("./HmpidErrorsDdl%02i.txt",nDDL),iEvtNcal)) continue;
/* store the result file on FES */
/*
status=daqDA_FES_storeFile(Form("./HmpidPedDdl%02i.txt",nDDL),Form("HMPID_DA_Pedestals_ddl=%02i",nDDL));
if (status) {
printf("Failed to export file : %d\n",status);
return -1;
}
*/
status=daqDA_FES_storeFile(Form("./HmpidPedDdl%02i.txt",nDDL),Form("HMPID_DA_Pedestals_ddl=%02i",nDDL));
if (status) { printf("Failed to export file : %d\n",status); }
status=daqDA_FES_storeFile(Form("./HmpidErrorsDdl%02i.txt",nDDL),Form("HMPID_DA_Errors_ddl=%02i",nDDL));
if (status) { printf("Failed to export file : %d\n",status); }
}//nDDL
delete pCal;
if (status) return -1;
/* report progress */
daqDA_progressReport(100);
return status;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher_observer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/point.h"
class TestMouseObserver : public PanelMouseWatcherObserver {
public:
// Overridden from PanelMouseWatcherObserver:
virtual void OnMouseMove(const gfx::Point& mouse_position) OVERRIDE {
++mouse_movements_;
}
int mouse_movements_;
};
class PanelMouseWatcherTest : public testing::Test {
};
TEST_F(PanelMouseWatcherTest, StartStopWatching) {
MessageLoop loop(MessageLoop::TYPE_UI);
scoped_ptr<PanelMouseWatcher> watcher(PanelMouseWatcher::Create());
EXPECT_FALSE(watcher->IsActive());
scoped_ptr<TestMouseObserver> user1(new TestMouseObserver());
scoped_ptr<TestMouseObserver> user2(new TestMouseObserver());
// No observers.
watcher->NotifyMouseMovement(gfx::Point(42, 101));
EXPECT_EQ(0, user1->mouse_movements_);
EXPECT_EQ(0, user2->mouse_movements_);
// Only one mouse observer.
watcher->AddObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
watcher->NotifyMouseMovement(gfx::Point(42, 101));
EXPECT_GE(user1->mouse_movements_, 1);
EXPECT_EQ(0, user2->mouse_movements_);
watcher->RemoveObserver(user1.get());
EXPECT_FALSE(watcher->IsActive());
// More than one mouse observer.
watcher->AddObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
watcher->AddObserver(user2.get());
watcher->NotifyMouseMovement(gfx::Point(101, 42));
EXPECT_GE(user1->mouse_movements_, 2);
EXPECT_GE(user2->mouse_movements_, 1);
// Back to one observer.
watcher->RemoveObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
int saved_count = user1->mouse_movements_;
watcher->NotifyMouseMovement(gfx::Point(1, 2));
EXPECT_EQ(saved_count, user1->mouse_movements_);
EXPECT_GE(user2->mouse_movements_, 2);
watcher->RemoveObserver(user2.get());
EXPECT_FALSE(watcher->IsActive());
}
<commit_msg>Fix an uninitialized memory read in PanelMouseWatcherTest.StartStopWatching.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher_observer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/point.h"
class TestMouseObserver : public PanelMouseWatcherObserver {
public:
TestMouseObserver() : mouse_movements_(0) {}
// Overridden from PanelMouseWatcherObserver:
virtual void OnMouseMove(const gfx::Point& mouse_position) OVERRIDE {
++mouse_movements_;
}
int mouse_movements_;
};
class PanelMouseWatcherTest : public testing::Test {
};
TEST_F(PanelMouseWatcherTest, StartStopWatching) {
MessageLoop loop(MessageLoop::TYPE_UI);
scoped_ptr<PanelMouseWatcher> watcher(PanelMouseWatcher::Create());
EXPECT_FALSE(watcher->IsActive());
scoped_ptr<TestMouseObserver> user1(new TestMouseObserver());
scoped_ptr<TestMouseObserver> user2(new TestMouseObserver());
// No observers.
watcher->NotifyMouseMovement(gfx::Point(42, 101));
EXPECT_EQ(0, user1->mouse_movements_);
EXPECT_EQ(0, user2->mouse_movements_);
// Only one mouse observer.
watcher->AddObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
watcher->NotifyMouseMovement(gfx::Point(42, 101));
EXPECT_GE(user1->mouse_movements_, 1);
EXPECT_EQ(0, user2->mouse_movements_);
watcher->RemoveObserver(user1.get());
EXPECT_FALSE(watcher->IsActive());
// More than one mouse observer.
watcher->AddObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
watcher->AddObserver(user2.get());
watcher->NotifyMouseMovement(gfx::Point(101, 42));
EXPECT_GE(user1->mouse_movements_, 2);
EXPECT_GE(user2->mouse_movements_, 1);
// Back to one observer.
watcher->RemoveObserver(user1.get());
EXPECT_TRUE(watcher->IsActive());
int saved_count = user1->mouse_movements_;
watcher->NotifyMouseMovement(gfx::Point(1, 2));
EXPECT_EQ(saved_count, user1->mouse_movements_);
EXPECT_GE(user2->mouse_movements_, 2);
watcher->RemoveObserver(user2.get());
EXPECT_FALSE(watcher->IsActive());
}
<|endoftext|> |
<commit_before>#include "musicbottomareawidget.h"
#include "ui_musicapplication.h"
#include "musicuiobject.h"
#include "musicsystemtraymenu.h"
#include "musicwindowextras.h"
MusicBottomAreaWidget::MusicBottomAreaWidget(QWidget *parent)
: QWidget(parent)
{
m_supperClass = parent;
m_systemCloseConfig = false;//Control the mode to exit
createSystemTrayIcon();
m_musicWindowExtras = new MusicWindowExtras(parent);
}
MusicBottomAreaWidget::~MusicBottomAreaWidget()
{
delete m_systemTrayMenu;
delete m_systemTray;
delete m_musicWindowExtras;
}
void MusicBottomAreaWidget::setupUi(Ui::MusicApplication* ui)
{
m_ui = ui;
ui->menuSetting->setIcon(QIcon(QString::fromUtf8(":/image/menu")));
ui->menuSetting->setIconSize(QSize(50,50));
ui->menuSetting->setStyleSheet(MusicUIObject::MToolButtonStyle04);
ui->menuSetting->setCursor(QCursor(Qt::PointingHandCursor));
ui->menuSetting->setToolTip(tr("Menu"));
ui->menuSetting->setMenu(&m_toolPopupMenu);
ui->musicImport->setIcon(QIcon(QString::fromUtf8(":/appTools/import")));
ui->musicImport->setIconSize(QSize(40,40));
ui->musicImport->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicImport->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicImport->setToolTip(tr("Import"));
connect(ui->musicImport,SIGNAL(clicked()), m_supperClass, SLOT(musicImportSongs()));
ui->musicSetting->setIcon(QIcon(QString::fromUtf8(":/appTools/setting")));
ui->musicSetting->setIconSize(QSize(40,40));
ui->musicSetting->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicSetting->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicSetting->setToolTip(tr("Setting"));
connect(ui->musicSetting,SIGNAL(clicked()), m_supperClass, SLOT(musicSetting()));
ui->musicSearch->setIcon(QIcon(QString::fromUtf8(":/appTools/search")));
ui->musicSearch->setIconSize(QSize(40,40));
ui->musicSearch->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicSearch->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicSearch->setToolTip(tr("musicSearch"));
ui->musicCurrentLocation->setIcon(QIcon(QString::fromUtf8(":/appTools/location")));
ui->musicCurrentLocation->setIconSize(QSize(40,40));
ui->musicCurrentLocation->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicCurrentLocation->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicCurrentLocation->setToolTip(tr("musicLocation"));
connect(ui->musicCurrentLocation, SIGNAL(clicked()), m_supperClass, SLOT(musicCurrentPlayLocation()));
connect(ui->musicDesktopLrc, SIGNAL(clicked()), m_systemTrayMenu, SLOT(showDesktopLrc()));
createToolPopupMenu();
}
void MusicBottomAreaWidget::createToolPopupMenu()
{
m_toolPopupMenu.setStyleSheet(MusicUIObject::MMenuStyle02);
m_toolPopupMenu.addAction(m_ui->action_ImportSongs);
m_toolPopupMenu.addAction(m_ui->action_Setting);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_Privious);
m_toolPopupMenu.addAction(m_ui->action_Play);
m_toolPopupMenu.addAction(m_ui->action_Next);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_OrderPlay);
m_toolPopupMenu.addAction(m_ui->action_RandomPlay);
m_toolPopupMenu.addAction(m_ui->action_SingleCycle);
m_toolPopupMenu.addAction(m_ui->action_ListCycle);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_VolumeSub);
m_toolPopupMenu.addAction(m_ui->action_VolumePlus);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_About);
m_toolPopupMenu.addAction(m_ui->action_Quit);
createMenuActions();
}
void MusicBottomAreaWidget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch(reason)
{
case QSystemTrayIcon::DoubleClick:
break;
case QSystemTrayIcon::Trigger:
if(!m_supperClass->isVisible())
{
m_supperClass->show();
m_supperClass->activateWindow();
}
break;
default:
break;
}
}
void MusicBottomAreaWidget::setVolumeValue(int value) const
{
m_ui->musicSoundSlider->setValue(value);
}
void MusicBottomAreaWidget::createMenuActions() const
{
connect(m_ui->action_ImportSongs,SIGNAL(triggered()),m_supperClass,SLOT(musicImportSongs()));
connect(m_ui->action_Setting,SIGNAL(triggered()),m_supperClass,SLOT(musicSetting()));
connect(m_ui->action_Quit,SIGNAL(triggered()),m_supperClass,SLOT(quitWindowClose()));
connect(m_ui->action_Next,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayNext()));
connect(m_ui->action_Play,SIGNAL(triggered()),m_supperClass,SLOT(musicKey()));
connect(m_ui->action_Privious,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayPrivious()));
connect(m_ui->action_VolumeSub,SIGNAL(triggered()),m_supperClass,SLOT(musicActionVolumeSub()));
connect(m_ui->action_VolumePlus,SIGNAL(triggered()),m_supperClass,SLOT(musicActionVolumePlus()));
connect(m_ui->action_OrderPlay,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayOrder()));
connect(m_ui->action_RandomPlay,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayRandom()));
connect(m_ui->action_SingleCycle,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayOneLoop()));
connect(m_ui->action_ListCycle,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayListLoop()));
}
void MusicBottomAreaWidget::createSystemTrayIcon()
{
m_systemTray = new QSystemTrayIcon(m_supperClass);
m_systemTray->setIcon(QIcon(QString::fromUtf8(":/image/windowicon")));
m_systemTray->setToolTip(tr("QMusicPlayer"));
m_systemTrayMenu = new MusicSystemTrayMenu(m_supperClass);
connect(m_systemTrayMenu, SIGNAL(setShowDesktopLrc(bool)), SIGNAL(setShowDesktopLrc(bool)));
connect(m_systemTrayMenu, SIGNAL(setWindowLockedChanged()), SIGNAL(setWindowLockedChanged()));
m_systemTray->setContextMenu(m_systemTrayMenu);
m_systemTray->show();
connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void MusicBottomAreaWidget::setDestopLrcVisible(const QString& status) const
{
m_systemTrayMenu->showDesktopLrc(status);
}
void MusicBottomAreaWidget::showPlayStatus(bool status) const
{
m_systemTrayMenu->showPlayStatus(status);
#if defined MUSIC_DEBUG && defined Q_OS_WIN
m_musicWindowExtras->showPlayStatus(status);
#endif
}
void MusicBottomAreaWidget::setLabelText(const QString &name) const
{
m_systemTrayMenu->setLabelText(name);
}
void MusicBottomAreaWidget::setSystemCloseConfig(const QString &status)
{
m_systemCloseConfig = (status == "true") ? true : false;
}
void MusicBottomAreaWidget::showMessage(const QString &title, const QString &text)
{
m_systemTray->showMessage(title, text);
}
#if defined MUSIC_DEBUG && defined Q_OS_WIN
void MusicBottomAreaWidget::setValue(int value) const
{
m_musicWindowExtras->setValue(value);
}
void MusicBottomAreaWidget::setRange(int min, int max) const
{
m_musicWindowExtras->setRange(min, max);
}
#endif
void MusicBottomAreaWidget::setWindowConcise()
{
bool con = m_musicWindowExtras->isDisableBlurBehindWindow();
m_supperClass->resize( con ? 400 : 990, m_supperClass->height());
m_ui->musicWindowConcise->setGeometry(con ? 315 : 848, 27, 25, 25);
m_ui->minimization->setGeometry(con ? 345 : 909, 27, 25, 25);
m_ui->windowClose->setGeometry(con ? 370 : 937, 27, 25, 25);
m_ui->resizeWindowLabel->setGeometry(con ? 380 : 950, 620, 15, 15);
m_musicWindowExtras->disableBlurBehindWindow( !con );
m_ui->musicWindowConcise->setIcon(QIcon(QString::fromUtf8(con ? ":/image/conciseout"
: ":/image/concisein")));
}
void MusicBottomAreaWidget::lockDesktopLrc(bool lock)
{
m_systemTrayMenu->lockDesktopLrc(lock);
}
void MusicBottomAreaWidget::desktopLrcClosed()
{
m_ui->musicDesktopLrc->setChecked(false);
m_systemTrayMenu->showDesktopLrc("false");
M_SETTING->setValue(MusicSettingManager::ShowDesktopLrcChoiced, false);
}
<commit_msg>update lrc button concise[002158]<commit_after>#include "musicbottomareawidget.h"
#include "ui_musicapplication.h"
#include "musicuiobject.h"
#include "musicsystemtraymenu.h"
#include "musicwindowextras.h"
MusicBottomAreaWidget::MusicBottomAreaWidget(QWidget *parent)
: QWidget(parent)
{
m_supperClass = parent;
m_systemCloseConfig = false;//Control the mode to exit
createSystemTrayIcon();
m_musicWindowExtras = new MusicWindowExtras(parent);
}
MusicBottomAreaWidget::~MusicBottomAreaWidget()
{
delete m_systemTrayMenu;
delete m_systemTray;
delete m_musicWindowExtras;
}
void MusicBottomAreaWidget::setupUi(Ui::MusicApplication* ui)
{
m_ui = ui;
ui->menuSetting->setIcon(QIcon(QString::fromUtf8(":/image/menu")));
ui->menuSetting->setIconSize(QSize(50,50));
ui->menuSetting->setStyleSheet(MusicUIObject::MToolButtonStyle04);
ui->menuSetting->setCursor(QCursor(Qt::PointingHandCursor));
ui->menuSetting->setToolTip(tr("Menu"));
ui->menuSetting->setMenu(&m_toolPopupMenu);
ui->musicImport->setIcon(QIcon(QString::fromUtf8(":/appTools/import")));
ui->musicImport->setIconSize(QSize(40,40));
ui->musicImport->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicImport->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicImport->setToolTip(tr("Import"));
connect(ui->musicImport,SIGNAL(clicked()), m_supperClass, SLOT(musicImportSongs()));
ui->musicSetting->setIcon(QIcon(QString::fromUtf8(":/appTools/setting")));
ui->musicSetting->setIconSize(QSize(40,40));
ui->musicSetting->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicSetting->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicSetting->setToolTip(tr("Setting"));
connect(ui->musicSetting,SIGNAL(clicked()), m_supperClass, SLOT(musicSetting()));
ui->musicSearch->setIcon(QIcon(QString::fromUtf8(":/appTools/search")));
ui->musicSearch->setIconSize(QSize(40,40));
ui->musicSearch->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicSearch->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicSearch->setToolTip(tr("musicSearch"));
ui->musicCurrentLocation->setIcon(QIcon(QString::fromUtf8(":/appTools/location")));
ui->musicCurrentLocation->setIconSize(QSize(40,40));
ui->musicCurrentLocation->setStyleSheet(MusicUIObject::MToolButtonStyle03);
ui->musicCurrentLocation->setCursor(QCursor(Qt::PointingHandCursor));
ui->musicCurrentLocation->setToolTip(tr("musicLocation"));
connect(ui->musicCurrentLocation, SIGNAL(clicked()), m_supperClass, SLOT(musicCurrentPlayLocation()));
connect(ui->musicDesktopLrc, SIGNAL(clicked()), m_systemTrayMenu, SLOT(showDesktopLrc()));
createToolPopupMenu();
}
void MusicBottomAreaWidget::createToolPopupMenu()
{
m_toolPopupMenu.setStyleSheet(MusicUIObject::MMenuStyle02);
m_toolPopupMenu.addAction(m_ui->action_ImportSongs);
m_toolPopupMenu.addAction(m_ui->action_Setting);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_Privious);
m_toolPopupMenu.addAction(m_ui->action_Play);
m_toolPopupMenu.addAction(m_ui->action_Next);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_OrderPlay);
m_toolPopupMenu.addAction(m_ui->action_RandomPlay);
m_toolPopupMenu.addAction(m_ui->action_SingleCycle);
m_toolPopupMenu.addAction(m_ui->action_ListCycle);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_VolumeSub);
m_toolPopupMenu.addAction(m_ui->action_VolumePlus);
m_toolPopupMenu.addSeparator();
m_toolPopupMenu.addAction(m_ui->action_About);
m_toolPopupMenu.addAction(m_ui->action_Quit);
createMenuActions();
}
void MusicBottomAreaWidget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch(reason)
{
case QSystemTrayIcon::DoubleClick:
break;
case QSystemTrayIcon::Trigger:
if(!m_supperClass->isVisible())
{
m_supperClass->show();
m_supperClass->activateWindow();
}
break;
default:
break;
}
}
void MusicBottomAreaWidget::setVolumeValue(int value) const
{
m_ui->musicSoundSlider->setValue(value);
}
void MusicBottomAreaWidget::createMenuActions() const
{
connect(m_ui->action_ImportSongs,SIGNAL(triggered()),m_supperClass,SLOT(musicImportSongs()));
connect(m_ui->action_Setting,SIGNAL(triggered()),m_supperClass,SLOT(musicSetting()));
connect(m_ui->action_Quit,SIGNAL(triggered()),m_supperClass,SLOT(quitWindowClose()));
connect(m_ui->action_Next,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayNext()));
connect(m_ui->action_Play,SIGNAL(triggered()),m_supperClass,SLOT(musicKey()));
connect(m_ui->action_Privious,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayPrivious()));
connect(m_ui->action_VolumeSub,SIGNAL(triggered()),m_supperClass,SLOT(musicActionVolumeSub()));
connect(m_ui->action_VolumePlus,SIGNAL(triggered()),m_supperClass,SLOT(musicActionVolumePlus()));
connect(m_ui->action_OrderPlay,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayOrder()));
connect(m_ui->action_RandomPlay,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayRandom()));
connect(m_ui->action_SingleCycle,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayOneLoop()));
connect(m_ui->action_ListCycle,SIGNAL(triggered()),m_supperClass,SLOT(musicPlayListLoop()));
}
void MusicBottomAreaWidget::createSystemTrayIcon()
{
m_systemTray = new QSystemTrayIcon(m_supperClass);
m_systemTray->setIcon(QIcon(QString::fromUtf8(":/image/windowicon")));
m_systemTray->setToolTip(tr("QMusicPlayer"));
m_systemTrayMenu = new MusicSystemTrayMenu(m_supperClass);
connect(m_systemTrayMenu, SIGNAL(setShowDesktopLrc(bool)), SIGNAL(setShowDesktopLrc(bool)));
connect(m_systemTrayMenu, SIGNAL(setWindowLockedChanged()), SIGNAL(setWindowLockedChanged()));
m_systemTray->setContextMenu(m_systemTrayMenu);
m_systemTray->show();
connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void MusicBottomAreaWidget::setDestopLrcVisible(const QString& status) const
{
m_systemTrayMenu->showDesktopLrc(status);
}
void MusicBottomAreaWidget::showPlayStatus(bool status) const
{
m_systemTrayMenu->showPlayStatus(status);
#if defined MUSIC_DEBUG && defined Q_OS_WIN
m_musicWindowExtras->showPlayStatus(status);
#endif
}
void MusicBottomAreaWidget::setLabelText(const QString &name) const
{
m_systemTrayMenu->setLabelText(name);
}
void MusicBottomAreaWidget::setSystemCloseConfig(const QString &status)
{
m_systemCloseConfig = (status == "true") ? true : false;
}
void MusicBottomAreaWidget::showMessage(const QString &title, const QString &text)
{
m_systemTray->showMessage(title, text);
}
#if defined MUSIC_DEBUG && defined Q_OS_WIN
void MusicBottomAreaWidget::setValue(int value) const
{
m_musicWindowExtras->setValue(value);
}
void MusicBottomAreaWidget::setRange(int min, int max) const
{
m_musicWindowExtras->setRange(min, max);
}
#endif
void MusicBottomAreaWidget::setWindowConcise()
{
bool con = m_musicWindowExtras->isDisableBlurBehindWindow();
m_supperClass->resize( con ? 400 : 990, m_supperClass->height());
m_ui->musicWindowConcise->setGeometry(con ? 315 : 848, 27, 25, 25);
m_ui->minimization->setGeometry(con ? 345 : 909, 27, 25, 25);
m_ui->windowClose->setGeometry(con ? 370 : 937, 27, 25, 25);
m_ui->resizeWindowLabel->setGeometry(con ? 380 : 950, 620, 15, 15);
m_ui->lrcDisplayAllButton->setHidden(con);
m_ui->musicWindowConcise->setIcon(QIcon(QString::fromUtf8(con ? ":/image/conciseout"
: ":/image/concisein")));
m_musicWindowExtras->disableBlurBehindWindow( !con );
}
void MusicBottomAreaWidget::lockDesktopLrc(bool lock)
{
m_systemTrayMenu->lockDesktopLrc(lock);
}
void MusicBottomAreaWidget::desktopLrcClosed()
{
m_ui->musicDesktopLrc->setChecked(false);
m_systemTrayMenu->showDesktopLrc("false");
M_SETTING->setValue(MusicSettingManager::ShowDesktopLrcChoiced, false);
}
<|endoftext|> |
<commit_before>// Copyright 2015 Headcrash Industries LLC. All Rights Reserved.
#include "VlcMediaPCH.h"
#include "Vlc.h"
#include "VlcMediaPlayer.h"
#include "VlcMediaUtils.h"
/* FVlcMediaPlayer structors
*****************************************************************************/
FVlcMediaPlayer::FVlcMediaPlayer(FLibvlcInstance* InVlcInstance)
: CurrentTime(FTimespan::Zero())
, DesiredRate(0.0)
, LastPlatformSeconds(0.0)
, MediaSource(InVlcInstance)
, Player(nullptr)
, ShouldLoop(false)
{ }
FVlcMediaPlayer::~FVlcMediaPlayer()
{
Close();
}
/* FTickerObjectBase interface
*****************************************************************************/
bool FVlcMediaPlayer::Tick(float DeltaTime)
{
if (Player == nullptr)
{
return true;
}
// interpolate time, because FVlc::MediaPlayerGetTime is too low-res
if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing)
{
double PlatformSeconds = FPlatformTime::Seconds();
CurrentTime += FTimespan::FromSeconds(DesiredRate * (PlatformSeconds - LastPlatformSeconds));
LastPlatformSeconds = PlatformSeconds;
}
// process events
ELibvlcEventType Event;
while (Events.Dequeue(Event))
{
switch (Event)
{
case ELibvlcEventType::MediaParsedChanged:
MediaEvent.Broadcast(EMediaEvent::TracksChanged);
break;
case ELibvlcEventType::MediaPlayerEndReached:
// begin hack: this causes a short delay, but there seems to be no
// other way. looping via VLC Media List players is also broken :(
FVlc::MediaPlayerStop(Player);
// end hack
if (ShouldLoop && (DesiredRate != 0.0f))
{
SetRate(DesiredRate);
}
MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended);
MediaEvent.Broadcast(EMediaEvent::PlaybackEndReached);
break;
case ELibvlcEventType::MediaPlayerPaused:
LastPlatformSeconds = FPlatformTime::Seconds();
MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended);
break;
case ELibvlcEventType::MediaPlayerPlaying:
LastPlatformSeconds = FPlatformTime::Seconds();
MediaEvent.Broadcast(EMediaEvent::PlaybackResumed);
break;
case ELibvlcEventType::MediaPlayerPositionChanged:
CurrentTime = FTimespan::FromMilliseconds(FMath::Max<int64>(0, FVlc::MediaPlayerGetTime(Player)));
LastPlatformSeconds = FPlatformTime::Seconds();
break;
default:
continue;
}
}
return true;
}
/* IMediaControls interface
*****************************************************************************/
FTimespan FVlcMediaPlayer::GetDuration() const
{
if (Player == nullptr)
{
return FTimespan::Zero();
}
int64 Length = FVlc::MediaPlayerGetLength(Player);
if (Length <= 0)
{
return GetTime();
}
return FTimespan::FromMilliseconds(Length);
}
float FVlcMediaPlayer::GetRate() const
{
if ((Player == nullptr) || (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing))
{
return 0.0f;
}
return FVlc::MediaPlayerGetRate(Player);
}
EMediaState FVlcMediaPlayer::GetState() const
{
if (Player == nullptr)
{
return EMediaState::Closed;
}
ELibvlcState State = FVlc::MediaPlayerGetState(Player);
switch (State)
{
case ELibvlcState::Buffering:
case ELibvlcState::NothingSpecial:
return EMediaState::Closed;
case ELibvlcState::Error:
return EMediaState::Error;
case ELibvlcState::Opening:
return EMediaState::Preparing;
case ELibvlcState::Paused:
return EMediaState::Paused;
case ELibvlcState::Playing:
return EMediaState::Playing;
case ELibvlcState::Ended:
case ELibvlcState::Stopped:
return EMediaState::Stopped;
}
return EMediaState::Error; // should never get here
}
TRange<float> FVlcMediaPlayer::GetSupportedRates(EMediaPlaybackDirections Direction, bool Unthinned) const
{
if (Direction == EMediaPlaybackDirections::Reverse)
{
return TRange<float>::Empty();
}
return TRange<float>(0.0f, 10.0f);
}
FTimespan FVlcMediaPlayer::GetTime() const
{
return CurrentTime;
}
bool FVlcMediaPlayer::IsLooping() const
{
return ShouldLoop;
}
bool FVlcMediaPlayer::SetLooping(bool Looping)
{
ShouldLoop = Looping;
return true;
}
bool FVlcMediaPlayer::SetRate(float Rate)
{
if (Player == nullptr)
{
return false;
}
if ((FVlc::MediaPlayerSetRate(Player, Rate) == -1))
{
return false;
}
if (FMath::IsNearlyZero(Rate))
{
if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing)
{
if (FVlc::MediaPlayerCanPause(Player) == 0)
{
return false;
}
FVlc::MediaPlayerPause(Player);
}
}
else if (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing)
{
if (FVlc::MediaPlayerPlay(Player) == -1)
{
return false;
}
}
DesiredRate = Rate;
return true;
}
bool FVlcMediaPlayer::SupportsRate(float Rate, bool Unthinned) const
{
return (Rate >= 0.0f) && (Rate <= 10.0f);
}
bool FVlcMediaPlayer::SupportsScrubbing() const
{
return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0));
}
bool FVlcMediaPlayer::SupportsSeeking() const
{
return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0));
}
/* IMediaPlayer interface
*****************************************************************************/
void FVlcMediaPlayer::Close()
{
if (Player == nullptr)
{
return;
}
// detach callback handlers
Output.Shutdown();
Tracks.Shutdown();
// release player
FVlc::MediaPlayerStop(Player);
FVlc::MediaPlayerRelease(Player);
Player = nullptr;
// reset fields
CurrentTime = FTimespan::Zero();
MediaSource.Close();
// notify listeners
MediaEvent.Broadcast(EMediaEvent::TracksChanged);
MediaEvent.Broadcast(EMediaEvent::MediaClosed);
}
IMediaControls& FVlcMediaPlayer::GetControls()
{
return *this;
}
FString FVlcMediaPlayer::GetInfo() const
{
return TEXT("VlcMedia media information not implemented yet");
}
IMediaOutput& FVlcMediaPlayer::GetOutput()
{
return Output;
}
FString FVlcMediaPlayer::GetStats() const
{
return TEXT("VlcMedia stats information not implemented yet");
}
IMediaTracks& FVlcMediaPlayer::GetTracks()
{
return Tracks;
}
FString FVlcMediaPlayer::GetUrl() const
{
return MediaSource.GetCurrentUrl();
}
bool FVlcMediaPlayer::Open(const FString& Url, const IMediaOptions& Options)
{
Close();
if (Url.IsEmpty())
{
return false;
}
if (Url.StartsWith(TEXT("file://")))
{
// open local files via platform file system
TSharedPtr<FArchive, ESPMode::ThreadSafe> Archive;
const TCHAR* FilePath = &Url[7];
if (Options.GetMediaOption("PrecacheFile", false))
{
FBufferArchive* Buffer = new FBufferArchive;
if (FFileHelper::LoadFileToArray(*Buffer, FilePath))
{
Archive = MakeShareable(Buffer);
}
else
{
delete Buffer;
}
}
else
{
Archive = MakeShareable(IFileManager::Get().CreateFileReader(FilePath));
}
if (!Archive.IsValid())
{
UE_LOG(LogVlcMedia, Warning, TEXT("Failed to open media file: %s"), FilePath);
return false;
}
if (!MediaSource.OpenArchive(Archive.ToSharedRef(), Url))
{
return false;
}
}
else
{
if (!MediaSource.OpenUrl(Url))
{
return false;
}
}
return InitializePlayer();
}
bool FVlcMediaPlayer::Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions& Options)
{
Close();
if (OriginalUrl.IsEmpty() || !MediaSource.OpenArchive(Archive, OriginalUrl))
{
return false;
}
return InitializePlayer();
}
bool FVlcMediaPlayer::Seek(const FTimespan& Time)
{
ELibvlcState State = FVlc::MediaPlayerGetState(Player);
if ((State != ELibvlcState::Opening) ||
(State == ELibvlcState::Buffering) ||
(State == ELibvlcState::Error))
{
return false;
}
FVlc::MediaPlayerSetTime(Player, Time.GetTotalMilliseconds());
return true;
}
/* FVlcMediaPlayer implementation
*****************************************************************************/
bool FVlcMediaPlayer::InitializePlayer()
{
Player = FVlc::MediaPlayerNewFromMedia(MediaSource.GetMedia());
if (Player == nullptr)
{
UE_LOG(LogVlcMedia, Warning, TEXT("Failed to initialize media player: %s"), ANSI_TO_TCHAR(FVlc::Errmsg()));
return false;
}
// attach to event managers
FLibvlcEventManager* MediaEventManager = FVlc::MediaEventManager(MediaSource.GetMedia());
FLibvlcEventManager* PlayerEventManager = FVlc::MediaPlayerEventManager(Player);
if ((MediaEventManager == nullptr) || (PlayerEventManager == nullptr))
{
FVlc::MediaPlayerRelease(Player);
Player = nullptr;
return false;
}
FVlc::EventAttach(MediaEventManager, ELibvlcEventType::MediaParsedChanged, &FVlcMediaPlayer::StaticEventCallback, this);
FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerEndReached, &FVlcMediaPlayer::StaticEventCallback, this);
FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPlaying, &FVlcMediaPlayer::StaticEventCallback, this);
FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPositionChanged, &FVlcMediaPlayer::StaticEventCallback, this);
MediaEvent.Broadcast(EMediaEvent::MediaOpened);
return true;
}
/* FVlcMediaPlayer static functions
*****************************************************************************/
void FVlcMediaPlayer::StaticEventCallback(FLibvlcEvent* Event, void* UserData)
{
UE_LOG(LogVlcMedia, Verbose, TEXT("LibVLC event: %s"), *VlcMedia::EventToString(Event));
auto MediaPlayer = (FVlcMediaPlayer*)UserData;
if (MediaPlayer == nullptr)
{
return;
}
if (Event->Type == ELibvlcEventType::MediaParsedChanged)
{
MediaPlayer->Tracks.Initialize(*MediaPlayer->Player);
MediaPlayer->Output.Initialize(*MediaPlayer->Player);
}
else if (Event->Type == ELibvlcEventType::MediaPlayerPlaying)
{
MediaPlayer->Output.Resume(MediaPlayer->CurrentTime);
}
MediaPlayer->Events.Enqueue(Event->Type);
}
<commit_msg>Fixed player not in ready state after media opened.<commit_after>// Copyright 2015 Headcrash Industries LLC. All Rights Reserved.
#include "VlcMediaPCH.h"
#include "Vlc.h"
#include "VlcMediaPlayer.h"
#include "VlcMediaUtils.h"
/* FVlcMediaPlayer structors
*****************************************************************************/
FVlcMediaPlayer::FVlcMediaPlayer(FLibvlcInstance* InVlcInstance)
: CurrentTime(FTimespan::Zero())
, DesiredRate(0.0)
, LastPlatformSeconds(0.0)
, MediaSource(InVlcInstance)
, Player(nullptr)
, ShouldLoop(false)
{ }
FVlcMediaPlayer::~FVlcMediaPlayer()
{
Close();
}
/* FTickerObjectBase interface
*****************************************************************************/
bool FVlcMediaPlayer::Tick(float DeltaTime)
{
if (Player == nullptr)
{
return true;
}
// interpolate time, because FVlc::MediaPlayerGetTime is too low-res
if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing)
{
double PlatformSeconds = FPlatformTime::Seconds();
CurrentTime += FTimespan::FromSeconds(DesiredRate * (PlatformSeconds - LastPlatformSeconds));
LastPlatformSeconds = PlatformSeconds;
}
// process events
ELibvlcEventType Event;
while (Events.Dequeue(Event))
{
switch (Event)
{
case ELibvlcEventType::MediaParsedChanged:
MediaEvent.Broadcast(EMediaEvent::TracksChanged);
break;
case ELibvlcEventType::MediaPlayerEndReached:
// begin hack: this causes a short delay, but there seems to be no
// other way. looping via VLC Media List players is also broken :(
FVlc::MediaPlayerStop(Player);
// end hack
if (ShouldLoop && (DesiredRate != 0.0f))
{
SetRate(DesiredRate);
}
MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended);
MediaEvent.Broadcast(EMediaEvent::PlaybackEndReached);
break;
case ELibvlcEventType::MediaPlayerPaused:
LastPlatformSeconds = FPlatformTime::Seconds();
MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended);
break;
case ELibvlcEventType::MediaPlayerPlaying:
LastPlatformSeconds = FPlatformTime::Seconds();
MediaEvent.Broadcast(EMediaEvent::PlaybackResumed);
break;
case ELibvlcEventType::MediaPlayerPositionChanged:
CurrentTime = FTimespan::FromMilliseconds(FMath::Max<int64>(0, FVlc::MediaPlayerGetTime(Player)));
LastPlatformSeconds = FPlatformTime::Seconds();
break;
default:
continue;
}
}
return true;
}
/* IMediaControls interface
*****************************************************************************/
FTimespan FVlcMediaPlayer::GetDuration() const
{
if (Player == nullptr)
{
return FTimespan::Zero();
}
int64 Length = FVlc::MediaPlayerGetLength(Player);
if (Length <= 0)
{
return GetTime();
}
return FTimespan::FromMilliseconds(Length);
}
float FVlcMediaPlayer::GetRate() const
{
if ((Player == nullptr) || (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing))
{
return 0.0f;
}
return FVlc::MediaPlayerGetRate(Player);
}
EMediaState FVlcMediaPlayer::GetState() const
{
if (Player == nullptr)
{
return EMediaState::Closed;
}
ELibvlcState State = FVlc::MediaPlayerGetState(Player);
switch (State)
{
case ELibvlcState::Error:
return EMediaState::Error;
case ELibvlcState::Buffering:
case ELibvlcState::Opening:
return EMediaState::Preparing;
case ELibvlcState::Paused:
return EMediaState::Paused;
case ELibvlcState::Playing:
return EMediaState::Playing;
case ELibvlcState::Ended:
case ELibvlcState::NothingSpecial:
case ELibvlcState::Stopped:
return EMediaState::Stopped;
}
return EMediaState::Error; // should never get here
}
TRange<float> FVlcMediaPlayer::GetSupportedRates(EMediaPlaybackDirections Direction, bool Unthinned) const
{
if (Direction == EMediaPlaybackDirections::Reverse)
{
return TRange<float>::Empty();
}
return TRange<float>(0.0f, 10.0f);
}
FTimespan FVlcMediaPlayer::GetTime() const
{
return CurrentTime;
}
bool FVlcMediaPlayer::IsLooping() const
{
return ShouldLoop;
}
bool FVlcMediaPlayer::SetLooping(bool Looping)
{
ShouldLoop = Looping;
return true;
}
bool FVlcMediaPlayer::SetRate(float Rate)
{
if (Player == nullptr)
{
return false;
}
if ((FVlc::MediaPlayerSetRate(Player, Rate) == -1))
{
return false;
}
if (FMath::IsNearlyZero(Rate))
{
if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing)
{
if (FVlc::MediaPlayerCanPause(Player) == 0)
{
return false;
}
FVlc::MediaPlayerPause(Player);
}
}
else if (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing)
{
if (FVlc::MediaPlayerPlay(Player) == -1)
{
return false;
}
}
DesiredRate = Rate;
return true;
}
bool FVlcMediaPlayer::SupportsRate(float Rate, bool Unthinned) const
{
return (Rate >= 0.0f) && (Rate <= 10.0f);
}
bool FVlcMediaPlayer::SupportsScrubbing() const
{
return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0));
}
bool FVlcMediaPlayer::SupportsSeeking() const
{
return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0));
}
/* IMediaPlayer interface
*****************************************************************************/
void FVlcMediaPlayer::Close()
{
if (Player == nullptr)
{
return;
}
// detach callback handlers
Output.Shutdown();
Tracks.Shutdown();
// release player
FVlc::MediaPlayerStop(Player);
FVlc::MediaPlayerRelease(Player);
Player = nullptr;
// reset fields
CurrentTime = FTimespan::Zero();
MediaSource.Close();
// notify listeners
MediaEvent.Broadcast(EMediaEvent::TracksChanged);
MediaEvent.Broadcast(EMediaEvent::MediaClosed);
}
IMediaControls& FVlcMediaPlayer::GetControls()
{
return *this;
}
FString FVlcMediaPlayer::GetInfo() const
{
return TEXT("VlcMedia media information not implemented yet");
}
IMediaOutput& FVlcMediaPlayer::GetOutput()
{
return Output;
}
FString FVlcMediaPlayer::GetStats() const
{
return TEXT("VlcMedia stats information not implemented yet");
}
IMediaTracks& FVlcMediaPlayer::GetTracks()
{
return Tracks;
}
FString FVlcMediaPlayer::GetUrl() const
{
return MediaSource.GetCurrentUrl();
}
bool FVlcMediaPlayer::Open(const FString& Url, const IMediaOptions& Options)
{
Close();
if (Url.IsEmpty())
{
return false;
}
if (Url.StartsWith(TEXT("file://")))
{
// open local files via platform file system
TSharedPtr<FArchive, ESPMode::ThreadSafe> Archive;
const TCHAR* FilePath = &Url[7];
if (Options.GetMediaOption("PrecacheFile", false))
{
FBufferArchive* Buffer = new FBufferArchive;
if (FFileHelper::LoadFileToArray(*Buffer, FilePath))
{
Archive = MakeShareable(Buffer);
}
else
{
delete Buffer;
}
}
else
{
Archive = MakeShareable(IFileManager::Get().CreateFileReader(FilePath));
}
if (!Archive.IsValid())
{
UE_LOG(LogVlcMedia, Warning, TEXT("Failed to open media file: %s"), FilePath);
return false;
}
if (!MediaSource.OpenArchive(Archive.ToSharedRef(), Url))
{
return false;
}
}
else
{
if (!MediaSource.OpenUrl(Url))
{
return false;
}
}
return InitializePlayer();
}
bool FVlcMediaPlayer::Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions& Options)
{
Close();
if (OriginalUrl.IsEmpty() || !MediaSource.OpenArchive(Archive, OriginalUrl))
{
return false;
}
return InitializePlayer();
}
bool FVlcMediaPlayer::Seek(const FTimespan& Time)
{
ELibvlcState State = FVlc::MediaPlayerGetState(Player);
if ((State != ELibvlcState::Opening) ||
(State == ELibvlcState::Buffering) ||
(State == ELibvlcState::Error))
{
return false;
}
FVlc::MediaPlayerSetTime(Player, Time.GetTotalMilliseconds());
return true;
}
/* FVlcMediaPlayer implementation
*****************************************************************************/
bool FVlcMediaPlayer::InitializePlayer()
{
Player = FVlc::MediaPlayerNewFromMedia(MediaSource.GetMedia());
if (Player == nullptr)
{
UE_LOG(LogVlcMedia, Warning, TEXT("Failed to initialize media player: %s"), ANSI_TO_TCHAR(FVlc::Errmsg()));
return false;
}
// attach to event managers
FLibvlcEventManager* MediaEventManager = FVlc::MediaEventManager(MediaSource.GetMedia());
FLibvlcEventManager* PlayerEventManager = FVlc::MediaPlayerEventManager(Player);
if ((MediaEventManager == nullptr) || (PlayerEventManager == nullptr))
{
FVlc::MediaPlayerRelease(Player);
Player = nullptr;
return false;
}
FVlc::EventAttach(MediaEventManager, ELibvlcEventType::MediaParsedChanged, &FVlcMediaPlayer::StaticEventCallback, this);
FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerEndReached, &FVlcMediaPlayer::StaticEventCallback, this);
FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPlaying, &FVlcMediaPlayer::StaticEventCallback, this);
FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPositionChanged, &FVlcMediaPlayer::StaticEventCallback, this);
MediaEvent.Broadcast(EMediaEvent::MediaOpened);
return true;
}
/* FVlcMediaPlayer static functions
*****************************************************************************/
void FVlcMediaPlayer::StaticEventCallback(FLibvlcEvent* Event, void* UserData)
{
UE_LOG(LogVlcMedia, Verbose, TEXT("LibVLC event: %s"), *VlcMedia::EventToString(Event));
auto MediaPlayer = (FVlcMediaPlayer*)UserData;
if (MediaPlayer == nullptr)
{
return;
}
if (Event->Type == ELibvlcEventType::MediaParsedChanged)
{
MediaPlayer->Tracks.Initialize(*MediaPlayer->Player);
MediaPlayer->Output.Initialize(*MediaPlayer->Player);
}
else if (Event->Type == ELibvlcEventType::MediaPlayerPlaying)
{
MediaPlayer->Output.Resume(MediaPlayer->CurrentTime);
}
MediaPlayer->Events.Enqueue(Event->Type);
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2004 Joseph Wenninger <jowenn@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "katesavemodifieddialog.h"
#include "katesavemodifieddialog.moc"
#include <QTreeWidget>
#include <QLabel>
#include <QPushButton>
#include <KLocale>
#include <KGuiItem>
#include <KStandardGuiItem>
#include <KVBox>
#include <KIconLoader>
#include <KMessageBox>
#include <kdebug.h>
#include <KEncodingFileDialog>
class AbstractKateSaveModifiedDialogCheckListItem: public QTreeWidgetItem
{
public:
AbstractKateSaveModifiedDialogCheckListItem(const QString& title, const QString& url): QTreeWidgetItem()
{
setFlags(flags() | Qt::ItemIsUserCheckable);
setText(0, title);
setText(1, url);
setCheckState(0, Qt::Checked);
setState(InitialState);
}
virtual ~AbstractKateSaveModifiedDialogCheckListItem()
{}
virtual bool synchronousSave(QWidget *dialogParent) = 0;
enum STATE{InitialState, SaveOKState, SaveFailedState};
STATE state() const
{
return m_state;
}
void setState(enum STATE state)
{
m_state = state;
KIconLoader *loader = KIconLoader::global();
switch (state)
{
case InitialState:
setIcon(0, QIcon());
break;
case SaveOKState:
setIcon(0, loader->loadIcon("dialog-ok", KIconLoader::NoGroup,/*height()*/16));
// "ok" icon should probably be "dialog-success", but we don't have that icon in KDE 4.0
break;
case SaveFailedState:
setIcon(0, loader->loadIcon("dialog-error", KIconLoader::NoGroup,/*height()*/16));
break;
}
}
private:
STATE m_state;
};
class KateSaveModifiedDocumentCheckListItem: public AbstractKateSaveModifiedDialogCheckListItem
{
public:
KateSaveModifiedDocumentCheckListItem(KTextEditor::Document *document)
: AbstractKateSaveModifiedDialogCheckListItem(document->documentName(), document->url().pathOrUrl())
{
m_document = document;
}
virtual ~KateSaveModifiedDocumentCheckListItem()
{}
virtual bool synchronousSave(QWidget *dialogParent)
{
if (m_document->url().isEmpty() )
{
KEncodingFileDialog::Result r = KEncodingFileDialog::getSaveUrlAndEncoding(
m_document->encoding(), QString(), QString(), dialogParent, i18n("Save As (%1)", m_document->documentName()));
if (!r.URLs.isEmpty())
{
KUrl tmp = r.URLs.first();
// check for overwriting a file
if( tmp.isLocalFile() )
{
QFileInfo info( tmp.path() );
if( info.exists() ) {
if (KMessageBox::Cancel == KMessageBox::warningContinueCancel( dialogParent,
i18n( "A file named \"%1\" already exists. "
"Are you sure you want to overwrite it?" , info.fileName() ),
i18n( "Overwrite File?" ), KStandardGuiItem::overwrite(),
KStandardGuiItem::cancel(), QString(), KMessageBox::Notify | KMessageBox::Dangerous ))
{
setState(SaveFailedState);
return false;
}
}
}
m_document->setEncoding( r.encoding );
if ( !m_document->saveAs( tmp ) )
{
setState(SaveFailedState);
setText(1, m_document->url().pathOrUrl());
return false;
}
else
{
bool sc = m_document->waitSaveComplete();
setText(1, m_document->url().pathOrUrl());
if (!sc)
{
setState(SaveFailedState);
return false;
}
else
{
setState(SaveOKState);
return true;
}
}
}
else
{
setState(SaveFailedState);
return false;
}
}
else
{ //document has an exising location
if ( !m_document->save() )
{
setState(SaveFailedState);
setText(1, m_document->url().pathOrUrl());
return false;
}
else
{
bool sc = m_document->waitSaveComplete();
setText(1, m_document->url().pathOrUrl());
if (!sc)
{
setState(SaveFailedState);
return false;
}
else
{
setState(SaveOKState);
return true;
}
}
}
return false;
}
private:
KTextEditor::Document *m_document;
};
KateSaveModifiedDialog::KateSaveModifiedDialog(QWidget *parent, QList<KTextEditor::Document*> documents):
KDialog( parent)
{
setCaption( i18n("Save Documents") );
setButtons( User1 | User2 | Cancel );
setObjectName( "KateSaveModifiedDialog" );
setModal( true );
KGuiItem saveItem = KStandardGuiItem::save();
saveItem.setText(i18n("&Save Selected"));
setButtonGuiItem(KDialog::User1, saveItem);
connect(this, SIGNAL(user1Clicked()), this, SLOT(slotSaveSelected()));
setButtonGuiItem(KDialog::User2, KStandardGuiItem::dontSave());
connect(this, SIGNAL(user2Clicked()), this, SLOT(slotDoNotSave()));
KGuiItem cancelItem = KStandardGuiItem::cancel();
cancelItem.setText(i18n("Do &Not Close"));
setButtonGuiItem(KDialog::Cancel, cancelItem);
setDefaultButton(KDialog::Cancel);
setButtonFocus(KDialog::Cancel);
KVBox *box = new KVBox(this);
setMainWidget(box);
new QLabel(i18n("<qt>The following documents have been modified. Do you want to save them before closing?</qt>"), box);
m_list = new QTreeWidget(box);
m_list->setColumnCount(2);
m_list->setHeaderLabels(QStringList() << i18n("Documents") << i18n("Location"));
m_list->setRootIsDecorated(true);
foreach (KTextEditor::Document* doc, documents) {
m_list->addTopLevelItem(new KateSaveModifiedDocumentCheckListItem(doc));
}
m_list->resizeColumnToContents(0);
connect(m_list, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(slotItemActivated(QTreeWidgetItem*,int)));
connect(new QPushButton(i18n("Se&lect All"), box), SIGNAL(clicked()), this, SLOT(slotSelectAll()));
}
KateSaveModifiedDialog::~KateSaveModifiedDialog()
{}
void KateSaveModifiedDialog::slotItemActivated(QTreeWidgetItem*, int)
{
bool enableSaveButton = false;
for (int i = 0; i < m_list->topLevelItemCount(); ++i) {
if (m_list->topLevelItem(i)->checkState(0) == Qt::Checked) {
enableSaveButton = true;
break;
}
}
// enable or disable the Save button
enableButton(KDialog::User1, enableSaveButton);
}
void KateSaveModifiedDialog::slotSelectAll()
{
for (int i = 0; i < m_list->topLevelItemCount(); ++i) {
m_list->topLevelItem(i)->setCheckState(0, Qt::Checked);
}
// enable Save button
enableButton(KDialog::User1, true);
}
void KateSaveModifiedDialog::slotSaveSelected()
{
if (doSave()) done(QDialog::Accepted);
}
void KateSaveModifiedDialog::slotDoNotSave()
{
done(QDialog::Accepted);
}
bool KateSaveModifiedDialog::doSave()
{
for (int i = 0; i < m_list->topLevelItemCount(); ++i) {
AbstractKateSaveModifiedDialogCheckListItem * cit = static_cast<AbstractKateSaveModifiedDialogCheckListItem*>(m_list->topLevelItem(i));
if (cit->checkState(0) == Qt::Checked && (cit->state() != AbstractKateSaveModifiedDialogCheckListItem::SaveOKState))
{
if (!cit->synchronousSave(this /*perhaps that should be the kate mainwindow*/))
{
KMessageBox::sorry( this, i18n("Data you requested to be saved could not be written. Please choose how you want to proceed."));
return false;
}
}
else if ((cit->checkState(0) != Qt::Checked) && (cit->state() == AbstractKateSaveModifiedDialogCheckListItem::SaveFailedState))
{
cit->setState(AbstractKateSaveModifiedDialogCheckListItem::InitialState);
}
}
return true;
}
bool KateSaveModifiedDialog::queryClose(QWidget *parent, QList<KTextEditor::Document*> documents)
{
KateSaveModifiedDialog d(parent, documents);
return (d.exec() != QDialog::Rejected);
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Don't show an error if the user aborts saving of files on app exit, just return to the dialog. If saving fails, there are still some dialogs one after another, since they are from different levels, not optimal, but I don't have a plan to fix that yet BUG: 252004<commit_after>/* This file is part of the KDE project
Copyright (C) 2004 Joseph Wenninger <jowenn@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "katesavemodifieddialog.h"
#include "katesavemodifieddialog.moc"
#include <QTreeWidget>
#include <QLabel>
#include <QPushButton>
#include <KLocale>
#include <KGuiItem>
#include <KStandardGuiItem>
#include <KVBox>
#include <KIconLoader>
#include <KMessageBox>
#include <kdebug.h>
#include <KEncodingFileDialog>
class AbstractKateSaveModifiedDialogCheckListItem: public QTreeWidgetItem
{
public:
AbstractKateSaveModifiedDialogCheckListItem(const QString& title, const QString& url): QTreeWidgetItem()
{
setFlags(flags() | Qt::ItemIsUserCheckable);
setText(0, title);
setText(1, url);
setCheckState(0, Qt::Checked);
setState(InitialState);
}
virtual ~AbstractKateSaveModifiedDialogCheckListItem()
{}
virtual bool synchronousSave(QWidget *dialogParent) = 0;
enum STATE{InitialState, SaveOKState, SaveFailedState};
STATE state() const
{
return m_state;
}
void setState(enum STATE state)
{
m_state = state;
KIconLoader *loader = KIconLoader::global();
switch (state)
{
case InitialState:
setIcon(0, QIcon());
break;
case SaveOKState:
setIcon(0, loader->loadIcon("dialog-ok", KIconLoader::NoGroup,/*height()*/16));
// "ok" icon should probably be "dialog-success", but we don't have that icon in KDE 4.0
break;
case SaveFailedState:
setIcon(0, loader->loadIcon("dialog-error", KIconLoader::NoGroup,/*height()*/16));
break;
}
}
private:
STATE m_state;
};
class KateSaveModifiedDocumentCheckListItem: public AbstractKateSaveModifiedDialogCheckListItem
{
public:
KateSaveModifiedDocumentCheckListItem(KTextEditor::Document *document)
: AbstractKateSaveModifiedDialogCheckListItem(document->documentName(), document->url().pathOrUrl())
{
m_document = document;
}
virtual ~KateSaveModifiedDocumentCheckListItem()
{}
virtual bool synchronousSave(QWidget *dialogParent)
{
if (m_document->url().isEmpty() )
{
KEncodingFileDialog::Result r = KEncodingFileDialog::getSaveUrlAndEncoding(
m_document->encoding(), QString(), QString(), dialogParent, i18n("Save As (%1)", m_document->documentName()));
if (!r.URLs.isEmpty())
{
KUrl tmp = r.URLs.first();
// check for overwriting a file
if( tmp.isLocalFile() )
{
QFileInfo info( tmp.path() );
if( info.exists() ) {
if (KMessageBox::Cancel == KMessageBox::warningContinueCancel( dialogParent,
i18n( "A file named \"%1\" already exists. "
"Are you sure you want to overwrite it?" , info.fileName() ),
i18n( "Overwrite File?" ), KStandardGuiItem::overwrite(),
KStandardGuiItem::cancel(), QString(), KMessageBox::Notify | KMessageBox::Dangerous ))
{
setState(SaveFailedState);
return false;
}
}
}
m_document->setEncoding( r.encoding );
if ( !m_document->saveAs( tmp ) )
{
setState(SaveFailedState);
setText(1, m_document->url().pathOrUrl());
return false;
}
else
{
bool sc = m_document->waitSaveComplete();
setText(1, m_document->url().pathOrUrl());
if (!sc)
{
setState(SaveFailedState);
return false;
}
else
{
setState(SaveOKState);
return true;
}
}
}
else
{
//setState(SaveFailedState);
return false;
}
}
else
{ //document has an exising location
if ( !m_document->save() )
{
setState(SaveFailedState);
setText(1, m_document->url().pathOrUrl());
return false;
}
else
{
bool sc = m_document->waitSaveComplete();
setText(1, m_document->url().pathOrUrl());
if (!sc)
{
setState(SaveFailedState);
return false;
}
else
{
setState(SaveOKState);
return true;
}
}
}
return false;
}
private:
KTextEditor::Document *m_document;
};
KateSaveModifiedDialog::KateSaveModifiedDialog(QWidget *parent, QList<KTextEditor::Document*> documents):
KDialog( parent)
{
setCaption( i18n("Save Documents") );
setButtons( User1 | User2 | Cancel );
setObjectName( "KateSaveModifiedDialog" );
setModal( true );
KGuiItem saveItem = KStandardGuiItem::save();
saveItem.setText(i18n("&Save Selected"));
setButtonGuiItem(KDialog::User1, saveItem);
connect(this, SIGNAL(user1Clicked()), this, SLOT(slotSaveSelected()));
setButtonGuiItem(KDialog::User2, KStandardGuiItem::dontSave());
connect(this, SIGNAL(user2Clicked()), this, SLOT(slotDoNotSave()));
KGuiItem cancelItem = KStandardGuiItem::cancel();
cancelItem.setText(i18n("Do &Not Close"));
setButtonGuiItem(KDialog::Cancel, cancelItem);
setDefaultButton(KDialog::Cancel);
setButtonFocus(KDialog::Cancel);
KVBox *box = new KVBox(this);
setMainWidget(box);
new QLabel(i18n("<qt>The following documents have been modified. Do you want to save them before closing?</qt>"), box);
m_list = new QTreeWidget(box);
m_list->setColumnCount(2);
m_list->setHeaderLabels(QStringList() << i18n("Documents") << i18n("Location"));
m_list->setRootIsDecorated(true);
foreach (KTextEditor::Document* doc, documents) {
m_list->addTopLevelItem(new KateSaveModifiedDocumentCheckListItem(doc));
}
m_list->resizeColumnToContents(0);
connect(m_list, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(slotItemActivated(QTreeWidgetItem*,int)));
connect(new QPushButton(i18n("Se&lect All"), box), SIGNAL(clicked()), this, SLOT(slotSelectAll()));
}
KateSaveModifiedDialog::~KateSaveModifiedDialog()
{}
void KateSaveModifiedDialog::slotItemActivated(QTreeWidgetItem*, int)
{
bool enableSaveButton = false;
for (int i = 0; i < m_list->topLevelItemCount(); ++i) {
if (m_list->topLevelItem(i)->checkState(0) == Qt::Checked) {
enableSaveButton = true;
break;
}
}
// enable or disable the Save button
enableButton(KDialog::User1, enableSaveButton);
}
void KateSaveModifiedDialog::slotSelectAll()
{
for (int i = 0; i < m_list->topLevelItemCount(); ++i) {
m_list->topLevelItem(i)->setCheckState(0, Qt::Checked);
}
// enable Save button
enableButton(KDialog::User1, true);
}
void KateSaveModifiedDialog::slotSaveSelected()
{
if (doSave()) done(QDialog::Accepted);
}
void KateSaveModifiedDialog::slotDoNotSave()
{
done(QDialog::Accepted);
}
bool KateSaveModifiedDialog::doSave()
{
for (int i = 0; i < m_list->topLevelItemCount(); ++i) {
AbstractKateSaveModifiedDialogCheckListItem * cit = static_cast<AbstractKateSaveModifiedDialogCheckListItem*>(m_list->topLevelItem(i));
if (cit->checkState(0) == Qt::Checked && (cit->state() != AbstractKateSaveModifiedDialogCheckListItem::SaveOKState))
{
if (!cit->synchronousSave(this /*perhaps that should be the kate mainwindow*/))
{
if (cit->state()==AbstractKateSaveModifiedDialogCheckListItem::SaveFailedState)
KMessageBox::sorry( this, i18n("Data you requested to be saved could not be written. Please choose how you want to proceed."));
return false;
}
}
else if ((cit->checkState(0) != Qt::Checked) && (cit->state() == AbstractKateSaveModifiedDialogCheckListItem::SaveFailedState))
{
cit->setState(AbstractKateSaveModifiedDialogCheckListItem::InitialState);
}
}
return true;
}
bool KateSaveModifiedDialog::queryClose(QWidget *parent, QList<KTextEditor::Document*> documents)
{
KateSaveModifiedDialog d(parent, documents);
return (d.exec() != QDialog::Rejected);
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>
#include "kgreet_ovirtcred.h"
#include "OVirtCred.h"
#include <kglobal.h>
#include <klocale.h>
#include <QtGui/QLayout>
#include <QtGui/QLabel>
#define KDM_OVIRTCRED_SERVER_DBUS_NAME "org.ovirt.vdsm.Credentials"
#define KDM_OVIRTCRED_SERVER_DBUS_PATH "/org/ovirt/vdsm/Credentials"
#define KDM_OVIRTCRED_SERVER_DBUS_INTERFACE KDM_OVIRTCRED_SERVER_DBUS_NAME
KOVirtCredGreeter::KOVirtCredGreeter(KGreeterPluginHandler *handler,
QWidget *parent,
const QString &fixedEntity,
Function func, Context ctx) :
QObject(),
KGreeterPlugin(handler)
{
Q_UNUSED(parent);
Q_UNUSED(fixedEntity);
Q_UNUSED(func);
Q_UNUSED(ctx);
parent = new QWidget(parent);
parent->setObjectName("talker");
widgetList << parent;
QBoxLayout *grid = new QBoxLayout(QBoxLayout::LeftToRight, parent);
m_titleLabel = new QLabel(i18n("oVirt Automatic Login System"), parent);
grid->addWidget(m_titleLabel, 0, Qt::AlignHCenter);
m_Credentials = new OVirtCred(KDM_OVIRTCRED_SERVER_DBUS_NAME, KDM_OVIRTCRED_SERVER_DBUS_PATH,
QDBusConnection::systemBus(), 0);
QObject::connect(m_Credentials, SIGNAL(UserAuthenticated(QString)),
this, SLOT(userAuthenticated(QString)));
}
KOVirtCredGreeter::~KOVirtCredGreeter()
{
abort();
qDeleteAll(widgetList);
delete m_Credentials;
}
void KOVirtCredGreeter::loadUsers(const QStringList &users)
{
// We do no offer a selectable users list.
Q_UNUSED(users);
}
void KOVirtCredGreeter::presetEntity(const QString &entity, int field)
{
// We do not care about preloaded users either.
Q_UNUSED(entity);
Q_UNUSED(field);
}
QString KOVirtCredGreeter::getEntity() const
{
return QString();
}
void KOVirtCredGreeter::setUser(const QString &user)
{
Q_UNUSED(user);
}
void KOVirtCredGreeter::setEnabled(bool on)
{
Q_UNUSED(on);
}
bool KOVirtCredGreeter::textMessage(const char *message, bool error)
{
if (error) {
// Stop authentication.
abort();
} else {
handler->gplugMsgBox(QMessageBox::Information, message);
}
return true;
}
void KOVirtCredGreeter::textPrompt(const char *prompt, bool echo, bool nonBlocking)
{
Q_UNUSED(echo);
Q_UNUSED(nonBlocking);
QString text = QString(prompt);
if (text.contains(QString("Token?"), Qt::CaseInsensitive)) {
handler->gplugReturnText(m_token.toAscii(), KGreeterPluginHandler::IsSecret);
m_token.clear();
} else {
abort();
}
}
bool KOVirtCredGreeter::binaryPrompt(const char *prompt, bool nonBlocking)
{
Q_UNUSED(prompt);
Q_UNUSED(nonBlocking);
return true;
}
void KOVirtCredGreeter::start()
{
}
void KOVirtCredGreeter::suspend()
{
}
void KOVirtCredGreeter::resume()
{
}
void KOVirtCredGreeter::next()
{
}
void KOVirtCredGreeter::abort()
{
}
void KOVirtCredGreeter::succeeded()
{
}
void KOVirtCredGreeter::failed()
{
}
void KOVirtCredGreeter::revive()
{
}
void KOVirtCredGreeter::clear()
{
}
void KOVirtCredGreeter::userAuthenticated(QString token)
{
m_token = token;
handler->gplugStart();
}
static bool init(const QString &,
QVariant (*getConf)(void *, const char *, const QVariant &),
void *ctx)
{
Q_UNUSED(getConf);
Q_UNUSED(ctx);
KGlobal::locale()->insertCatalog("kgreet_ovirtcred");
return true;
}
static void done()
{
KGlobal::locale()->removeCatalog("kgreet_ovirtcred");
}
static KGreeterPlugin* create(KGreeterPluginHandler *handler,
QWidget *parent,
const QString &fixedEntity,
KGreeterPlugin::Function func,
KGreeterPlugin::Context ctx)
{
return new KOVirtCredGreeter(handler, parent, fixedEntity, func, ctx);
}
KDE_EXPORT KGreeterPluginInfo kgreeterplugin_info = {
I18N_NOOP2("@item:inmenu authentication method", "oVirt Authentication"), "ovirtcred",
KGreeterPluginInfo::Local | KGreeterPluginInfo::Presettable,
init, done, create
};
#include "kgreet_ovirtcred.moc"
<commit_msg>kdm: handled the error message when plugin was selected.<commit_after>
#include "kgreet_ovirtcred.h"
#include "OVirtCred.h"
#include <kglobal.h>
#include <klocale.h>
#include <QtGui/QLayout>
#include <QtGui/QLabel>
#define KDM_OVIRTCRED_SERVER_DBUS_NAME "org.ovirt.vdsm.Credentials"
#define KDM_OVIRTCRED_SERVER_DBUS_PATH "/org/ovirt/vdsm/Credentials"
#define KDM_OVIRTCRED_SERVER_DBUS_INTERFACE KDM_OVIRTCRED_SERVER_DBUS_NAME
KOVirtCredGreeter::KOVirtCredGreeter(KGreeterPluginHandler *handler,
QWidget *parent,
const QString &fixedEntity,
Function func, Context ctx) :
QObject(),
KGreeterPlugin(handler)
{
Q_UNUSED(parent);
Q_UNUSED(fixedEntity);
Q_UNUSED(func);
Q_UNUSED(ctx);
parent = new QWidget(parent);
parent->setObjectName("welcome");
widgetList << parent;
QBoxLayout *grid = new QBoxLayout(QBoxLayout::LeftToRight, parent);
m_titleLabel = new QLabel(i18n("oVirt Automatic Login System"), parent);
grid->addWidget(m_titleLabel, 0, Qt::AlignHCenter);
m_Credentials = new OVirtCred(KDM_OVIRTCRED_SERVER_DBUS_NAME, KDM_OVIRTCRED_SERVER_DBUS_PATH,
QDBusConnection::systemBus(), 0);
QObject::connect(m_Credentials, SIGNAL(UserAuthenticated(QString)),
this, SLOT(userAuthenticated(QString)));
}
KOVirtCredGreeter::~KOVirtCredGreeter()
{
abort();
qDeleteAll(widgetList);
delete m_Credentials;
}
void KOVirtCredGreeter::loadUsers(const QStringList &users)
{
// We do no offer a selectable users list.
Q_UNUSED(users);
}
void KOVirtCredGreeter::presetEntity(const QString &entity, int field)
{
// We do not care about preloaded users either.
Q_UNUSED(entity);
Q_UNUSED(field);
}
QString KOVirtCredGreeter::getEntity() const
{
return QString();
}
void KOVirtCredGreeter::setUser(const QString &user)
{
Q_UNUSED(user);
}
void KOVirtCredGreeter::setEnabled(bool on)
{
Q_UNUSED(on);
}
bool KOVirtCredGreeter::textMessage(const char *message, bool error)
{
if (error) {
// Stop authentication.
abort();
} else {
handler->gplugMsgBox(QMessageBox::Information, message);
}
return true;
}
void KOVirtCredGreeter::textPrompt(const char *prompt, bool echo, bool nonBlocking)
{
Q_UNUSED(echo);
Q_UNUSED(nonBlocking);
QString text = QString(prompt);
if (text.contains(QString("Token?"), Qt::CaseInsensitive)) {
handler->gplugReturnText(m_token.toAscii(), KGreeterPluginHandler::IsSecret);
m_token.clear();
} else {
abort();
}
}
bool KOVirtCredGreeter::binaryPrompt(const char *prompt, bool nonBlocking)
{
Q_UNUSED(prompt);
Q_UNUSED(nonBlocking);
return true;
}
void KOVirtCredGreeter::start()
{
}
void KOVirtCredGreeter::suspend()
{
}
void KOVirtCredGreeter::resume()
{
}
void KOVirtCredGreeter::next()
{
}
void KOVirtCredGreeter::abort()
{
}
void KOVirtCredGreeter::succeeded()
{
}
void KOVirtCredGreeter::failed()
{
}
void KOVirtCredGreeter::revive()
{
}
void KOVirtCredGreeter::clear()
{
}
void KOVirtCredGreeter::userAuthenticated(QString token)
{
m_token = token;
handler->gplugStart();
}
static bool init(const QString &,
QVariant (*getConf)(void *, const char *, const QVariant &),
void *ctx)
{
Q_UNUSED(getConf);
Q_UNUSED(ctx);
KGlobal::locale()->insertCatalog("kgreet_ovirtcred");
return true;
}
static void done()
{
KGlobal::locale()->removeCatalog("kgreet_ovirtcred");
}
static KGreeterPlugin* create(KGreeterPluginHandler *handler,
QWidget *parent,
const QString &fixedEntity,
KGreeterPlugin::Function func,
KGreeterPlugin::Context ctx)
{
return new KOVirtCredGreeter(handler, parent, fixedEntity, func, ctx);
}
KDE_EXPORT KGreeterPluginInfo kgreeterplugin_info = {
I18N_NOOP2("@item:inmenu authentication method", "oVirt Authentication"), "ovirtcred",
KGreeterPluginInfo::Local | KGreeterPluginInfo::Presettable,
init, done, create
};
#include "kgreet_ovirtcred.moc"
<|endoftext|> |
<commit_before>/*
* UnknownWordPenalty.cpp
*
* Created on: 28 Oct 2015
* Author: hieu
*/
#include <boost/foreach.hpp>
#include "UnknownWordPenalty.h"
#include "../System.h"
#include "../Scores.h"
#include "../PhraseBased/Manager.h"
#include "../PhraseBased/TargetPhraseImpl.h"
#include "../PhraseBased/InputPath.h"
#include "../PhraseBased/TargetPhrases.h"
#include "../SCFG/InputPath.h"
#include "../SCFG/TargetPhraseImpl.h"
#include "../SCFG/Manager.h"
#include "../SCFG/Sentence.h"
using namespace std;
namespace Moses2
{
UnknownWordPenalty::UnknownWordPenalty(size_t startInd, const std::string &line) :
PhraseTable(startInd, line)
{
ReadParameters();
}
UnknownWordPenalty::~UnknownWordPenalty()
{
// TODO Auto-generated destructor stub
}
void UnknownWordPenalty::Lookup(const Manager &mgr,
InputPathsBase &inputPaths) const
{
BOOST_FOREACH(InputPathBase *pathBase, inputPaths){
InputPath *path = static_cast<InputPath*>(pathBase);
const SubPhrase<Moses2::Word> &phrase = path->subPhrase;
TargetPhrases *tpsPtr;
tpsPtr = Lookup(mgr, mgr.GetPool(), *path);
path->AddTargetPhrases(*this, tpsPtr);
}
}
TargetPhrases *UnknownWordPenalty::Lookup(const Manager &mgr, MemPool &pool,
InputPath &inputPath) const
{
const System &system = mgr.system;
TargetPhrases *tps = NULL;
size_t numWords = inputPath.range.GetNumWordsCovered();
if (numWords > 1) {
// only create 1 word phrases
return tps;
}
// any other pt translate this?
size_t numPt = mgr.system.mappings.size();
const TargetPhrases **allTPS =
static_cast<InputPath&>(inputPath).targetPhrases;
for (size_t i = 0; i < numPt; ++i) {
const TargetPhrases *otherTps = allTPS[i];
if (otherTps && otherTps->GetSize()) {
return tps;
}
}
const SubPhrase<Moses2::Word> &source = inputPath.subPhrase;
const Moses2::Word &sourceWord = source[0];
const Factor *factor = sourceWord[0];
tps = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, 1);
TargetPhraseImpl *target =
new (pool.Allocate<TargetPhraseImpl>()) TargetPhraseImpl(pool, *this,
system, 1);
Moses2::Word &word = (*target)[0];
//FactorCollection &fc = system.vocab;
//const Factor *factor = fc.AddFactor("SSS", false);
word[0] = factor;
Scores &scores = target->GetScores();
scores.PlusEquals(mgr.system, *this, -100);
MemPool &memPool = mgr.GetPool();
system.featureFunctions.EvaluateInIsolation(memPool, system, source, *target);
tps->AddTargetPhrase(*target);
system.featureFunctions.EvaluateAfterTablePruning(memPool, *tps, source);
return tps;
}
void UnknownWordPenalty::EvaluateInIsolation(const System &system,
const Phrase<Moses2::Word> &source, const TargetPhrase<Moses2::Word> &targetPhrase, Scores &scores,
SCORE *estimatedScore) const
{
}
void UnknownWordPenalty::InitActiveChart(MemPool &pool, SCFG::InputPath &path) const
{
}
void UnknownWordPenalty::Lookup(MemPool &pool,
const SCFG::Manager &mgr,
size_t maxChartSpan,
const SCFG::Stacks &stacks,
SCFG::InputPath &path) const
{
const System &system = mgr.system;
size_t numWords = path.range.GetNumWordsCovered();
if (numWords > 1) {
// only create 1 word phrases
return;
}
// don't do 1st of last word
if (path.range.GetStartPos() == 0) {
return;
}
const SCFG::Sentence &sentence = static_cast<const SCFG::Sentence&>(mgr.GetInput());
if (path.range.GetStartPos() + 1 == sentence.GetSize()) {
return;
}
// terminal
const SCFG::Word &lastWord = path.subPhrase.Back();
//cerr << "UnknownWordPenalty lastWord=" << lastWord << endl;
const Factor *factor = lastWord[0];
SCFG::TargetPhraseImpl *tp = new (pool.Allocate<SCFG::TargetPhraseImpl>(1)) SCFG::TargetPhraseImpl(pool, *this, system, 1);
SCFG::Word &word = (*tp)[0];
word.CreateFromString(system.GetVocab(), system, factor->GetString().as_string());
tp->lhs.CreateFromString(system.GetVocab(), system, "[X]");
size_t endPos = path.range.GetEndPos();
const SCFG::InputPath &subPhrasePath = *mgr.GetInputPaths().GetMatrix().GetValue(endPos, 1);
SCFG::SymbolBind symbolBind(pool);
symbolBind.Add(subPhrasePath.range, lastWord, NULL);
Scores &scores = tp->GetScores();
scores.PlusEquals(mgr.system, *this, -100);
MemPool &memPool = mgr.GetPool();
const SubPhrase<SCFG::Word> &source = path.subPhrase;
system.featureFunctions.EvaluateInIsolation(memPool, system, source, *tp);
path.AddTargetPhrase(pool, *this, symbolBind, tp);
}
void UnknownWordPenalty::LookupUnary(MemPool &pool,
const SCFG::Manager &mgr,
const SCFG::Stacks &stacks,
SCFG::InputPath &path) const
{
}
}
<commit_msg>don't create rules with unk pt if there are already rules<commit_after>/*
* UnknownWordPenalty.cpp
*
* Created on: 28 Oct 2015
* Author: hieu
*/
#include <boost/foreach.hpp>
#include "UnknownWordPenalty.h"
#include "../System.h"
#include "../Scores.h"
#include "../PhraseBased/Manager.h"
#include "../PhraseBased/TargetPhraseImpl.h"
#include "../PhraseBased/InputPath.h"
#include "../PhraseBased/TargetPhrases.h"
#include "../SCFG/InputPath.h"
#include "../SCFG/TargetPhraseImpl.h"
#include "../SCFG/Manager.h"
#include "../SCFG/Sentence.h"
using namespace std;
namespace Moses2
{
UnknownWordPenalty::UnknownWordPenalty(size_t startInd, const std::string &line) :
PhraseTable(startInd, line)
{
ReadParameters();
}
UnknownWordPenalty::~UnknownWordPenalty()
{
// TODO Auto-generated destructor stub
}
void UnknownWordPenalty::Lookup(const Manager &mgr,
InputPathsBase &inputPaths) const
{
BOOST_FOREACH(InputPathBase *pathBase, inputPaths){
InputPath *path = static_cast<InputPath*>(pathBase);
const SubPhrase<Moses2::Word> &phrase = path->subPhrase;
TargetPhrases *tpsPtr;
tpsPtr = Lookup(mgr, mgr.GetPool(), *path);
path->AddTargetPhrases(*this, tpsPtr);
}
}
TargetPhrases *UnknownWordPenalty::Lookup(const Manager &mgr, MemPool &pool,
InputPath &inputPath) const
{
const System &system = mgr.system;
TargetPhrases *tps = NULL;
size_t numWords = inputPath.range.GetNumWordsCovered();
if (numWords > 1) {
// only create 1 word phrases
return tps;
}
// any other pt translate this?
size_t numPt = mgr.system.mappings.size();
const TargetPhrases **allTPS =
static_cast<InputPath&>(inputPath).targetPhrases;
for (size_t i = 0; i < numPt; ++i) {
const TargetPhrases *otherTps = allTPS[i];
if (otherTps && otherTps->GetSize()) {
return tps;
}
}
const SubPhrase<Moses2::Word> &source = inputPath.subPhrase;
const Moses2::Word &sourceWord = source[0];
const Factor *factor = sourceWord[0];
tps = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, 1);
TargetPhraseImpl *target =
new (pool.Allocate<TargetPhraseImpl>()) TargetPhraseImpl(pool, *this,
system, 1);
Moses2::Word &word = (*target)[0];
//FactorCollection &fc = system.vocab;
//const Factor *factor = fc.AddFactor("SSS", false);
word[0] = factor;
Scores &scores = target->GetScores();
scores.PlusEquals(mgr.system, *this, -100);
MemPool &memPool = mgr.GetPool();
system.featureFunctions.EvaluateInIsolation(memPool, system, source, *target);
tps->AddTargetPhrase(*target);
system.featureFunctions.EvaluateAfterTablePruning(memPool, *tps, source);
return tps;
}
void UnknownWordPenalty::EvaluateInIsolation(const System &system,
const Phrase<Moses2::Word> &source, const TargetPhrase<Moses2::Word> &targetPhrase, Scores &scores,
SCORE *estimatedScore) const
{
}
void UnknownWordPenalty::InitActiveChart(MemPool &pool, SCFG::InputPath &path) const
{
}
void UnknownWordPenalty::Lookup(MemPool &pool,
const SCFG::Manager &mgr,
size_t maxChartSpan,
const SCFG::Stacks &stacks,
SCFG::InputPath &path) const
{
const System &system = mgr.system;
size_t numWords = path.range.GetNumWordsCovered();
if (numWords > 1) {
// only create 1 word phrases
return;
}
if (path.GetNumRules()) {
return;
}
// don't do 1st of last word
if (path.range.GetStartPos() == 0) {
return;
}
const SCFG::Sentence &sentence = static_cast<const SCFG::Sentence&>(mgr.GetInput());
if (path.range.GetStartPos() + 1 == sentence.GetSize()) {
return;
}
// terminal
const SCFG::Word &lastWord = path.subPhrase.Back();
//cerr << "UnknownWordPenalty lastWord=" << lastWord << endl;
const Factor *factor = lastWord[0];
SCFG::TargetPhraseImpl *tp = new (pool.Allocate<SCFG::TargetPhraseImpl>(1)) SCFG::TargetPhraseImpl(pool, *this, system, 1);
SCFG::Word &word = (*tp)[0];
word.CreateFromString(system.GetVocab(), system, factor->GetString().as_string());
tp->lhs.CreateFromString(system.GetVocab(), system, "[X]");
size_t endPos = path.range.GetEndPos();
const SCFG::InputPath &subPhrasePath = *mgr.GetInputPaths().GetMatrix().GetValue(endPos, 1);
SCFG::SymbolBind symbolBind(pool);
symbolBind.Add(subPhrasePath.range, lastWord, NULL);
Scores &scores = tp->GetScores();
scores.PlusEquals(mgr.system, *this, -100);
MemPool &memPool = mgr.GetPool();
const SubPhrase<SCFG::Word> &source = path.subPhrase;
system.featureFunctions.EvaluateInIsolation(memPool, system, source, *tp);
path.AddTargetPhrase(pool, *this, symbolBind, tp);
}
void UnknownWordPenalty::LookupUnary(MemPool &pool,
const SCFG::Manager &mgr,
const SCFG::Stacks &stacks,
SCFG::InputPath &path) const
{
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 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. //
// ======================================================================== //
#include "scene_instance.h"
#include "scene.h"
namespace embree
{
DECLARE_SYMBOL2(RTCBoundsFunction,InstanceBoundsFunc);
DECLARE_SYMBOL2(AccelSet::IntersectorN,InstanceIntersectorN);
InstanceFactory::InstanceFactory(int features)
{
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,InstanceBoundsFunc);
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL_AVX512SKX(features,InstanceIntersectorN);
}
Instance::Instance (Device* device, Scene* object, unsigned int numTimeSteps)
: AccelSet(device,1,numTimeSteps), object(object), local2world(nullptr)
{
if (object) object->refInc();
world2local0 = one;
local2world = (AffineSpace3fa*) alignedMalloc(numTimeSteps*sizeof(AffineSpace3fa));
for (unsigned int i=0; i<numTimeSteps; i++) local2world[i] = one;
intersectors.ptr = this;
boundsFunc = device->instance_factory->InstanceBoundsFunc();
intersectors.intersectorN = device->instance_factory->InstanceIntersectorN();
}
Instance::~Instance()
{
alignedFree(local2world);
if (object) object->refDec();
}
void Instance::setNumTimeSteps (unsigned int numTimeSteps_in)
{
if (numTimeSteps_in == numTimeSteps)
return;
AffineSpace3fa* local2world2 = (AffineSpace3fa*) alignedMalloc(numTimeSteps_in*sizeof(AffineSpace3fa));
for (size_t i=0; i<numTimeSteps_in; i++)
local2world2[i] = one;
for (size_t i=0; i<min(numTimeSteps,numTimeSteps_in); i++)
local2world2[i] = local2world[i];
alignedFree(local2world);
local2world = local2world2;
Geometry::setNumTimeSteps(numTimeSteps_in);
}
void Instance::setInstancedScene(const Ref<Scene>& scene)
{
if (object) object->refDec();
object = scene.ptr;
if (object) object->refInc();
Geometry::update();
}
void Instance::setTransform(const AffineSpace3fa& xfm, unsigned int timeStep)
{
if (timeStep >= numTimeSteps)
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"invalid timestep");
local2world[timeStep] = xfm;
if (timeStep == 0) world2local0 = rcp(xfm);
}
AffineSpace3fa Instance::getTransform(float time)
{
return getWorld2Local(time);
}
void Instance::setMask (unsigned mask)
{
this->mask = mask;
Geometry::update();
}
}
<commit_msg>minor instance implementation cleanup<commit_after>// ======================================================================== //
// Copyright 2009-2017 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. //
// ======================================================================== //
#include "scene_instance.h"
#include "scene.h"
namespace embree
{
DECLARE_SYMBOL2(RTCBoundsFunction,InstanceBoundsFunc);
DECLARE_SYMBOL2(AccelSet::IntersectorN,InstanceIntersectorN);
InstanceFactory::InstanceFactory(int features)
{
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,InstanceBoundsFunc);
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL_AVX512SKX(features,InstanceIntersectorN);
}
Instance::Instance (Device* device, Scene* object, unsigned int numTimeSteps)
: AccelSet(device,1,numTimeSteps), object(object), local2world(nullptr)
{
if (object) object->refInc();
world2local0 = one;
local2world = (AffineSpace3fa*) alignedMalloc(numTimeSteps*sizeof(AffineSpace3fa));
for (size_t i = 0; i < numTimeSteps; i++)
local2world[i] = one;
intersectors.ptr = this;
boundsFunc = device->instance_factory->InstanceBoundsFunc();
intersectors.intersectorN = device->instance_factory->InstanceIntersectorN();
}
Instance::~Instance()
{
alignedFree(local2world);
if (object) object->refDec();
}
void Instance::setNumTimeSteps (unsigned int numTimeSteps_in)
{
if (numTimeSteps_in == numTimeSteps)
return;
AffineSpace3fa* local2world2 = (AffineSpace3fa*) alignedMalloc(numTimeSteps_in*sizeof(AffineSpace3fa));
for (size_t i = 0; i < min(numTimeSteps, numTimeSteps_in); i++)
local2world2[i] = local2world[i];
for (size_t i = numTimeSteps; i < numTimeSteps_in; i++)
local2world2[i] = one;
alignedFree(local2world);
local2world = local2world2;
Geometry::setNumTimeSteps(numTimeSteps_in);
}
void Instance::setInstancedScene(const Ref<Scene>& scene)
{
if (object) object->refDec();
object = scene.ptr;
if (object) object->refInc();
Geometry::update();
}
void Instance::setTransform(const AffineSpace3fa& xfm, unsigned int timeStep)
{
if (timeStep >= numTimeSteps)
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"invalid timestep");
local2world[timeStep] = xfm;
if (timeStep == 0)
world2local0 = rcp(xfm);
}
AffineSpace3fa Instance::getTransform(float time)
{
return getWorld2Local(time);
}
void Instance::setMask (unsigned mask)
{
this->mask = mask;
Geometry::update();
}
}
<|endoftext|> |
<commit_before>#include "houdini_file_saver.h"
#include <sstream>
#include <iomanip>
#include <string>
#include "../../util/houdini_geo/HoudiniFileDumpHelper.h"
#ifdef USE_PARTIO
#include "../../util/partio/PartioFunctions.h"
#endif
#define OUTPUT_FILE_NAME "frames/frame"
//Taken from http://www.cplusplus.com/forum/general/15952/
std::string ZeroPadNumber(int num)
{
std::ostringstream ss;
ss << std::setw(9) << std::setfill('0') << num;
std::string result = ss.str();
if (result.length() > 7)
{
result.erase(0, result.length() - 7);
}
return result;
}
int houdini_file_saver::writeFrameToFile(particle* particles, const simulation_parameters& parameters) {
//TODO Find a way to use the same struct for the simulation and writing to file
houdini_Particle *houdini_Particles = new houdini_Particle[parameters.particles_count];
#ifndef USE_PARTIO
std::stringstream ss;
ss << frames_folder_prefix << OUTPUT_FILE_NAME << ZeroPadNumber(++frame_count) << ".geo";
std::string fileName = ss.str();
for(int i=0;i<parameters.particles_count;i++){
houdini_Particles[i].px = particles[i].position.s[0];
houdini_Particles[i].py = particles[i].position.s[1];
houdini_Particles[i].pz = particles[i].position.s[2];
houdini_Particles[i].vx = particles[i].velocity.s[0];
houdini_Particles[i].vy = particles[i].velocity.s[1];
houdini_Particles[i].vz = particles[i].velocity.s[2];
//TODO Use actual colors
houdini_Particles[i].colorR =
particles[i].density > 1000.f && particles[i].density <= 2000.f ?
(particles[i].density - 1000.f) / 1000.f :
0.f;
houdini_Particles[i].colorG =
particles[i].density >= 0.f && particles[i].density < 1000.f ?
1.f - (particles[i].density) / 1000.f :
0.f;
houdini_Particles[i].colorB =
particles[i].density >= 500.f && particles[i].density <= 1000.f ?
(particles[i].density - 500.f) / 500.f :
particles[i].density >= 1000.f && particles[i].density <= 1500.f ?
1.f - (particles[i].density - 1000.f) / 500.f:
0.f;
houdini_Particles[i].mass = parameters.particle_mass;
}
std::ofstream fichier(fileName, std::ios::out | std::ios::trunc);
if (fichier.is_open())
{
ConcreteDataProvider dataProvider(houdini_Particles, parameters.particles_count);
HoudiniFileDumpParticles partsDumper(&dataProvider);
partsDumper.dump(fichier);
fichier.close();
}
else
{
std::cerr << "Error while writing to " << fileName << std::endl;
}
delete[] houdini_Particles;
#else
std::stringstream ss;
ss << frames_folder_prefix << OUTPUT_FILE_NAME << ZeroPadNumber(++frame_count) << ".bgeo";
std::string fileName = ss.str();
Partio::ParticlesDataMutable* data = makeData(particles,parameters);
Partio::write(fileName.c_str(),*data);
data->release();
#endif
return 0;
}
<commit_msg>Fix warning<commit_after>#include "houdini_file_saver.h"
#include <sstream>
#include <iomanip>
#include <string>
#include "../../util/houdini_geo/HoudiniFileDumpHelper.h"
#ifdef USE_PARTIO
#include "../../util/partio/PartioFunctions.h"
#endif
#define OUTPUT_FILE_NAME "frames/frame"
//Taken from http://www.cplusplus.com/forum/general/15952/
std::string ZeroPadNumber(int num)
{
std::ostringstream ss;
ss << std::setw(9) << std::setfill('0') << num;
std::string result = ss.str();
if (result.length() > 7)
{
result.erase(0, result.length() - 7);
}
return result;
}
int houdini_file_saver::writeFrameToFile(particle* particles, const simulation_parameters& parameters) {
#ifndef USE_PARTIO
//TODO Find a way to use the same struct for the simulation and writing to file
houdini_Particle *houdini_Particles = new houdini_Particle[parameters.particles_count];
std::stringstream ss;
ss << frames_folder_prefix << OUTPUT_FILE_NAME << ZeroPadNumber(++frame_count) << ".geo";
std::string fileName = ss.str();
for(int i=0;i<parameters.particles_count;i++){
houdini_Particles[i].px = particles[i].position.s[0];
houdini_Particles[i].py = particles[i].position.s[1];
houdini_Particles[i].pz = particles[i].position.s[2];
houdini_Particles[i].vx = particles[i].velocity.s[0];
houdini_Particles[i].vy = particles[i].velocity.s[1];
houdini_Particles[i].vz = particles[i].velocity.s[2];
//TODO Use actual colors
houdini_Particles[i].colorR =
particles[i].density > 1000.f && particles[i].density <= 2000.f ?
(particles[i].density - 1000.f) / 1000.f :
0.f;
houdini_Particles[i].colorG =
particles[i].density >= 0.f && particles[i].density < 1000.f ?
1.f - (particles[i].density) / 1000.f :
0.f;
houdini_Particles[i].colorB =
particles[i].density >= 500.f && particles[i].density <= 1000.f ?
(particles[i].density - 500.f) / 500.f :
particles[i].density >= 1000.f && particles[i].density <= 1500.f ?
1.f - (particles[i].density - 1000.f) / 500.f:
0.f;
houdini_Particles[i].mass = parameters.particle_mass;
}
std::ofstream fichier(fileName, std::ios::out | std::ios::trunc);
if (fichier.is_open())
{
ConcreteDataProvider dataProvider(houdini_Particles, parameters.particles_count);
HoudiniFileDumpParticles partsDumper(&dataProvider);
partsDumper.dump(fichier);
fichier.close();
}
else
{
std::cerr << "Error while writing to " << fileName << std::endl;
}
delete[] houdini_Particles;
#else
std::stringstream ss;
ss << frames_folder_prefix << OUTPUT_FILE_NAME << ZeroPadNumber(++frame_count) << ".bgeo";
std::string fileName = ss.str();
Partio::ParticlesDataMutable* data = makeData(particles,parameters);
Partio::write(fileName.c_str(),*data);
data->release();
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2015 The Regents of
the University of Michigan All rights reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: jglaser
#include "ForceDistanceConstraintGPU.h"
#include "ForceDistanceConstraintGPU.cuh"
#include <string.h>
#include <boost/python.hpp>
#include <boost/bind.hpp>
/*! \file ForceDistanceConstraintGPU.cc
\brief Contains code for the ForceDistanceConstraintGPU class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
*/
ForceDistanceConstraintGPU::ForceDistanceConstraintGPU(boost::shared_ptr<SystemDefinition> sysdef)
: ForceDistanceConstraint(sysdef), m_constraints_dirty(true), m_nnz(m_exec_conf), m_nnz_tot(0),
m_csr_val(m_exec_conf), m_csr_rowptr(m_exec_conf), m_csr_colind(m_exec_conf)
{
m_tuner_fill.reset(new Autotuner(32, 1024, 32, 5, 100000, "dist_constraint_fill_matrix_vec", this->m_exec_conf));
m_tuner_force.reset(new Autotuner(32, 1024, 32, 5, 100000, "dist_constraint_force", this->m_exec_conf));
cusparseCreate(&m_cusparse_handle);
cusparseCreateSolveAnalysisInfo(&m_cusparse_solve_info);
// cusparse matrix descriptor
cusparseCreateMatDescr(&m_cusparse_mat_descr);
cusparseSetMatType(m_cusparse_mat_descr,CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(m_cusparse_mat_descr,CUSPARSE_INDEX_BASE_ZERO);
cusparseSetMatDiagType(m_cusparse_mat_descr, CUSPARSE_DIAG_TYPE_NON_UNIT);
// connect to the ConstraintData to recieve notifications when constraints change order in memory
m_constraints_dirty_connection = m_cdata->connectGroupsDirty(boost::bind(&ForceDistanceConstraintGPU::slotConstraintsDirty, this));
}
//! Destructor
ForceDistanceConstraintGPU::~ForceDistanceConstraintGPU()
{
// clean up cusparse
cusparseDestroy(m_cusparse_handle);
cusparseDestroySolveAnalysisInfo(m_cusparse_solve_info);
cusparseDestroyMatDescr(m_cusparse_mat_descr);
// disconnect from signal in ConstaraintData
m_constraints_dirty_connection.disconnect();
}
void ForceDistanceConstraintGPU::fillMatrixVector(unsigned int timestep)
{
if (m_prof)
m_prof->push(m_exec_conf, "fill matrix");
// fill the matrix in row-major order
unsigned int n_constraint = m_cdata->getN();
// access particle data
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read);
ArrayHandle<Scalar4> d_netforce(m_pdata->getNetForce(), access_location::device, access_mode::read);
{
// access matrix elements
ArrayHandle<Scalar> d_cmatrix(m_cmatrix, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar> d_cvec(m_cvec, access_location::device, access_mode::overwrite);
// access GPU constraint table on device
const GPUArray<BondData::members_t>& gpu_constraint_list = this->m_cdata->getGPUTable();
const Index2D& gpu_table_indexer = this->m_cdata->getGPUTableIndexer();
ArrayHandle<BondData::members_t> d_gpu_clist(gpu_constraint_list, access_location::device, access_mode::read);
ArrayHandle<unsigned int > d_gpu_n_constraints(this->m_cdata->getNGroupsArray(),
access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cpos(m_cdata->getGPUPosTable(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cidx(m_cdata->getGPUIdxTable(), access_location::device, access_mode::read);
// launch GPU kernel
m_tuner_fill->begin();
gpu_fill_matrix_vector(
n_constraint,
m_pdata->getN(),
d_cmatrix.data,
d_cvec.data,
d_pos.data,
d_vel.data,
d_netforce.data,
d_gpu_clist.data,
gpu_table_indexer,
d_gpu_n_constraints.data,
d_gpu_cpos.data,
d_gpu_cidx.data,
m_deltaT,
m_pdata->getBox(),
m_constraints_dirty,
m_tuner_fill->getParam());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_fill->end();
}
if (m_prof)
m_prof->pop(m_exec_conf);
}
void ForceDistanceConstraintGPU::computeConstraintForces(unsigned int timestep)
{
if (m_prof)
m_prof->push(m_exec_conf,"constraint forces");
unsigned int n_constraint = m_cdata->getN();
bool done = false;
while (!done)
{
// reallocate array of constraint forces
m_lagrange.resize(n_constraint);
// resize sparse matrix storage
m_nnz.resize(n_constraint);
m_csr_rowptr.resize(n_constraint+1);
m_csr_colind.resize(n_constraint*n_constraint);
m_csr_val.resize(n_constraint*n_constraint);
// access matrix and vector
ArrayHandle<Scalar> d_cmatrix(m_cmatrix, access_location::device, access_mode::read);
ArrayHandle<Scalar> d_cvec(m_cvec, access_location::device, access_mode::read);
ArrayHandle<Scalar> d_lagrange(m_lagrange, access_location::device, access_mode::overwrite);
// access sparse matrix structural data
ArrayHandle<int> d_nnz(m_nnz, access_location::device, access_mode::readwrite);
ArrayHandle<int> d_csr_colind(m_csr_colind, access_location::device, access_mode::readwrite);
ArrayHandle<int> d_csr_rowptr(m_csr_rowptr, access_location::device, access_mode::readwrite);
ArrayHandle<Scalar> d_csr_val(m_csr_val, access_location::device, access_mode::readwrite);
// access particle data arrays
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
// access force array
ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite);
// access GPU constraint table on device
const GPUArray<BondData::members_t>& gpu_constraint_list = this->m_cdata->getGPUTable();
const Index2D& gpu_table_indexer = this->m_cdata->getGPUTableIndexer();
ArrayHandle<BondData::members_t> d_gpu_clist(gpu_constraint_list, access_location::device, access_mode::read);
ArrayHandle<unsigned int > d_gpu_n_constraints(this->m_cdata->getNGroupsArray(),
access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cpos(m_cdata->getGPUPosTable(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cidx(m_cdata->getGPUIdxTable(), access_location::device, access_mode::read);
const BoxDim& box = m_pdata->getBox();
unsigned int n_ptl = m_pdata->getN();
// compute constraint forces by solving linear system of equations
m_tuner_force->begin();
gpu_compute_constraint_forces(n_constraint,
d_cmatrix.data,
d_cvec.data,
d_nnz.data,
m_nnz_tot,
d_pos.data,
d_gpu_clist.data,
gpu_table_indexer,
d_gpu_n_constraints.data,
d_gpu_cpos.data,
d_gpu_cidx.data,
d_force.data,
box,
n_ptl,
m_tuner_force->getParam(),
m_cusparse_handle,
m_cusparse_mat_descr,
m_cusparse_solve_info,
m_constraints_dirty,
d_csr_rowptr.data,
d_csr_colind.data,
d_csr_val.data,
d_lagrange.data);
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_force->end();
// if we have just initialized the solver, re-run
if (m_constraints_dirty)
{
m_constraints_dirty = false;
// now fill with real values
fillMatrixVector(timestep);
}
else
{
done = true;
}
}
if (m_prof)
m_prof->pop(m_exec_conf);
}
void export_ForceDistanceConstraintGPU()
{
class_< ForceDistanceConstraintGPU, boost::shared_ptr<ForceDistanceConstraintGPU>, bases<ForceConstraint>, boost::noncopyable >
("ForceDistanceConstraintGPU", init< boost::shared_ptr<SystemDefinition> >())
;
}
<commit_msg>Correct scoping<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2015 The Regents of
the University of Michigan All rights reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: jglaser
#include "ForceDistanceConstraintGPU.h"
#include "ForceDistanceConstraintGPU.cuh"
#include <string.h>
#include <boost/python.hpp>
#include <boost/bind.hpp>
/*! \file ForceDistanceConstraintGPU.cc
\brief Contains code for the ForceDistanceConstraintGPU class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
*/
ForceDistanceConstraintGPU::ForceDistanceConstraintGPU(boost::shared_ptr<SystemDefinition> sysdef)
: ForceDistanceConstraint(sysdef), m_constraints_dirty(true), m_nnz(m_exec_conf), m_nnz_tot(0),
m_csr_val(m_exec_conf), m_csr_rowptr(m_exec_conf), m_csr_colind(m_exec_conf)
{
m_tuner_fill.reset(new Autotuner(32, 1024, 32, 5, 100000, "dist_constraint_fill_matrix_vec", this->m_exec_conf));
m_tuner_force.reset(new Autotuner(32, 1024, 32, 5, 100000, "dist_constraint_force", this->m_exec_conf));
cusparseCreate(&m_cusparse_handle);
cusparseCreateSolveAnalysisInfo(&m_cusparse_solve_info);
// cusparse matrix descriptor
cusparseCreateMatDescr(&m_cusparse_mat_descr);
cusparseSetMatType(m_cusparse_mat_descr,CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(m_cusparse_mat_descr,CUSPARSE_INDEX_BASE_ZERO);
cusparseSetMatDiagType(m_cusparse_mat_descr, CUSPARSE_DIAG_TYPE_NON_UNIT);
// connect to the ConstraintData to recieve notifications when constraints change order in memory
m_constraints_dirty_connection = m_cdata->connectGroupsDirty(boost::bind(&ForceDistanceConstraintGPU::slotConstraintsDirty, this));
}
//! Destructor
ForceDistanceConstraintGPU::~ForceDistanceConstraintGPU()
{
// clean up cusparse
cusparseDestroy(m_cusparse_handle);
cusparseDestroySolveAnalysisInfo(m_cusparse_solve_info);
cusparseDestroyMatDescr(m_cusparse_mat_descr);
// disconnect from signal in ConstaraintData
m_constraints_dirty_connection.disconnect();
}
void ForceDistanceConstraintGPU::fillMatrixVector(unsigned int timestep)
{
if (m_prof)
m_prof->push(m_exec_conf, "fill matrix");
// fill the matrix in row-major order
unsigned int n_constraint = m_cdata->getN();
// access particle data
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read);
ArrayHandle<Scalar4> d_netforce(m_pdata->getNetForce(), access_location::device, access_mode::read);
{
// access matrix elements
ArrayHandle<Scalar> d_cmatrix(m_cmatrix, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar> d_cvec(m_cvec, access_location::device, access_mode::overwrite);
// access GPU constraint table on device
const GPUArray<BondData::members_t>& gpu_constraint_list = this->m_cdata->getGPUTable();
const Index2D& gpu_table_indexer = this->m_cdata->getGPUTableIndexer();
ArrayHandle<BondData::members_t> d_gpu_clist(gpu_constraint_list, access_location::device, access_mode::read);
ArrayHandle<unsigned int > d_gpu_n_constraints(this->m_cdata->getNGroupsArray(),
access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cpos(m_cdata->getGPUPosTable(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cidx(m_cdata->getGPUIdxTable(), access_location::device, access_mode::read);
// launch GPU kernel
m_tuner_fill->begin();
gpu_fill_matrix_vector(
n_constraint,
m_pdata->getN(),
d_cmatrix.data,
d_cvec.data,
d_pos.data,
d_vel.data,
d_netforce.data,
d_gpu_clist.data,
gpu_table_indexer,
d_gpu_n_constraints.data,
d_gpu_cpos.data,
d_gpu_cidx.data,
m_deltaT,
m_pdata->getBox(),
m_constraints_dirty,
m_tuner_fill->getParam());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_fill->end();
}
if (m_prof)
m_prof->pop(m_exec_conf);
}
void ForceDistanceConstraintGPU::computeConstraintForces(unsigned int timestep)
{
if (m_prof)
m_prof->push(m_exec_conf,"constraint forces");
unsigned int n_constraint = m_cdata->getN();
bool done = false;
while (!done)
{
// reallocate array of constraint forces
m_lagrange.resize(n_constraint);
// resize sparse matrix storage
m_nnz.resize(n_constraint);
m_csr_rowptr.resize(n_constraint+1);
m_csr_colind.resize(n_constraint*n_constraint);
m_csr_val.resize(n_constraint*n_constraint);
{
// access matrix and vector
ArrayHandle<Scalar> d_cmatrix(m_cmatrix, access_location::device, access_mode::read);
ArrayHandle<Scalar> d_cvec(m_cvec, access_location::device, access_mode::read);
ArrayHandle<Scalar> d_lagrange(m_lagrange, access_location::device, access_mode::overwrite);
// access sparse matrix structural data
ArrayHandle<int> d_nnz(m_nnz, access_location::device, access_mode::readwrite);
ArrayHandle<int> d_csr_colind(m_csr_colind, access_location::device, access_mode::readwrite);
ArrayHandle<int> d_csr_rowptr(m_csr_rowptr, access_location::device, access_mode::readwrite);
ArrayHandle<Scalar> d_csr_val(m_csr_val, access_location::device, access_mode::readwrite);
// access particle data arrays
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
// access force array
ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite);
// access GPU constraint table on device
const GPUArray<BondData::members_t>& gpu_constraint_list = this->m_cdata->getGPUTable();
const Index2D& gpu_table_indexer = this->m_cdata->getGPUTableIndexer();
ArrayHandle<BondData::members_t> d_gpu_clist(gpu_constraint_list, access_location::device, access_mode::read);
ArrayHandle<unsigned int > d_gpu_n_constraints(this->m_cdata->getNGroupsArray(),
access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cpos(m_cdata->getGPUPosTable(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_gpu_cidx(m_cdata->getGPUIdxTable(), access_location::device, access_mode::read);
const BoxDim& box = m_pdata->getBox();
unsigned int n_ptl = m_pdata->getN();
// compute constraint forces by solving linear system of equations
m_tuner_force->begin();
gpu_compute_constraint_forces(n_constraint,
d_cmatrix.data,
d_cvec.data,
d_nnz.data,
m_nnz_tot,
d_pos.data,
d_gpu_clist.data,
gpu_table_indexer,
d_gpu_n_constraints.data,
d_gpu_cpos.data,
d_gpu_cidx.data,
d_force.data,
box,
n_ptl,
m_tuner_force->getParam(),
m_cusparse_handle,
m_cusparse_mat_descr,
m_cusparse_solve_info,
m_constraints_dirty,
d_csr_rowptr.data,
d_csr_colind.data,
d_csr_val.data,
d_lagrange.data);
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_force->end();
}
// if we have just initialized the solver, re-run
if (m_constraints_dirty)
{
m_constraints_dirty = false;
// now fill with real values
fillMatrixVector(timestep);
}
else
{
done = true;
}
}
if (m_prof)
m_prof->pop(m_exec_conf);
}
void export_ForceDistanceConstraintGPU()
{
class_< ForceDistanceConstraintGPU, boost::shared_ptr<ForceDistanceConstraintGPU>, bases<ForceConstraint>, boost::noncopyable >
("ForceDistanceConstraintGPU", init< boost::shared_ptr<SystemDefinition> >())
;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2005-2007 by the FIFE Team *
* fife-public@lists.sourceforge.net *
* This file is part of FIFE. *
* *
* FIFE 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 2 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., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// Platform specific includes
#include "util/fife_opengl.h"
// 3rd party library includes
#include <guichan/opengl.hpp>
#include <guichan/sdl.hpp>
#include <guichan.hpp>
#include <SDL.h>
// FIFE includes
#include "video/gui/guimanager.h"
#include "debugutils.h"
#include "exception.h"
#include "glimage.h"
#include "glscreen.h"
#include "renderbackendopengl.h"
namespace FIFE {
RenderBackendOpenGL::RenderBackendOpenGL() : RenderBackend("OpenGL"), m_screen(0){
// Get the pixelformat we want.
SDL_Surface* testsurface = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, 1, 1, 32,
0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
m_rgba_format = *(testsurface->format);
SDL_FreeSurface(testsurface);
}
RenderBackendOpenGL::~RenderBackendOpenGL() {
delete m_screen;
}
void RenderBackendOpenGL::init() {
Uint32 flags = SDL_INIT_VIDEO;
if (SDL_InitSubSystem(flags) < 0)
throw SDLException(SDL_GetError());
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // temporary hack
}
void RenderBackendOpenGL::deinit() {
delete m_screen;
m_screen = 0;
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
Screen* RenderBackendOpenGL::createMainScreen(unsigned int width, unsigned int height, unsigned char bitsPerPixel, bool fs) {
delete m_screen;
m_screen = 0;
Uint32 flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_HWACCEL;
if ( fs ) {
flags |= SDL_FULLSCREEN;
}
SDL_Surface* screen = NULL;
if( 0 == bitsPerPixel ) {
/// autodetect best mode
unsigned char possibleBitsPerPixel[] = {32, 24, 16, 0};
int i = 0;
while( true ) {
bitsPerPixel = possibleBitsPerPixel[i];
if( !bitsPerPixel ) {
throw SDLException("Videomode not available");
}
if ( SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) {
screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags);
if( screen ) {
break;
}
}
++i;
}
} else {
if ( !SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) {
throw SDLException("Videomode not available");
}
screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags);
}
SDL_WM_SetCaption("FIFE", 0);
if (!screen) {
throw SDLException(SDL_GetError());
}
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, width, height, 0);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
m_screen = new GLScreen();
GUIManager* guimanager = GUIManager::instance();
guimanager->init();
return m_screen;
}
void RenderBackendOpenGL::startFrame() {
glClear(GL_COLOR_BUFFER_BIT);
}
void RenderBackendOpenGL::endFrame() {
SDL_GL_SwapBuffers();
}
Image* RenderBackendOpenGL::createStaticImageFromRGBA(const uint8_t* data, unsigned int width, unsigned int height) {
return new GLImage(data, width, height);
}
Image* RenderBackendOpenGL::createStaticImageFromSDL(SDL_Surface* surface, bool freesurface) {
// Given an abritary surface, we must convert it to the format GLImage will understand.
// It's easiest to let SDL do this for us.
// We may want to check if the surface already is in the correct form, to avoid unneeded
// copying.
SDL_Surface* conv = SDL_ConvertSurface(surface, &m_rgba_format, SDL_SWSURFACE);
if (freesurface) {
SDL_FreeSurface(surface);
}
if (conv != 0) {
SDL_LockSurface(conv);
Image* image = new GLImage(static_cast<const uint8_t*>(conv->pixels), conv->w, conv->h, conv->pitch);
SDL_UnlockSurface(conv);
SDL_FreeSurface(conv);
return image;
}
return 0;
}
Screen* RenderBackendOpenGL::getMainScreen() const {
return m_screen;
}
void RenderBackendOpenGL::captureScreen(const std::string& filename) {
unsigned int swidth = getMainScreen()->getWidth();
unsigned int sheight = getMainScreen()->getHeight();
// We need unsigned char to avoid pointer alignment issues
uint8_t *pixels = new uint8_t[swidth * sheight * 3];
// Read in the pixel data
glReadPixels(0, 0, swidth, sheight, GL_RGB, GL_UNSIGNED_BYTE, reinterpret_cast<GLvoid*>(pixels));
/* At this point the image has been reversed, so we need to re-reverse it so that
it is the correct way around. We do this by copying the "image" pixels to another
surface in reverse order */
SDL_Surface* image = SDL_CreateRGBSurface(SDL_SWSURFACE, swidth, sheight, 24,
255U << (0), // Blue channel
255U << (8), // Green channel
255U << (16), // Red channel
0 /* no alpha! */);
SDL_LockSurface(image);
uint8_t *imagepixels = reinterpret_cast<uint8_t*>(image->pixels);
// Copy the "reversed_image" memory to the "image" memory
for (int y = (sheight - 1); y >= 0; --y) {
uint8_t *row_begin = pixels + y * swidth * 3;
uint8_t *row_end = row_begin + swidth * 3;
std::copy(row_begin, row_end, imagepixels);
// Advance a row in the output surface.
imagepixels += image->pitch;
}
SDL_UnlockSurface(image);
// Save file
SDL_SaveBMP(image, filename.c_str());
// Clear memory
delete []pixels;
SDL_FreeSurface( image );
}
}
<commit_msg>simple fix for OpenGL clipping (multi-camera example)<commit_after>/***************************************************************************
* Copyright (C) 2005-2007 by the FIFE Team *
* fife-public@lists.sourceforge.net *
* This file is part of FIFE. *
* *
* FIFE 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 2 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., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// Platform specific includes
#include "util/fife_opengl.h"
// 3rd party library includes
#include <guichan/opengl.hpp>
#include <guichan/sdl.hpp>
#include <guichan.hpp>
#include <SDL.h>
// FIFE includes
#include "video/gui/guimanager.h"
#include "debugutils.h"
#include "exception.h"
#include "glimage.h"
#include "glscreen.h"
#include "renderbackendopengl.h"
namespace FIFE {
RenderBackendOpenGL::RenderBackendOpenGL() : RenderBackend("OpenGL"), m_screen(0){
// Get the pixelformat we want.
SDL_Surface* testsurface = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, 1, 1, 32,
0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
m_rgba_format = *(testsurface->format);
SDL_FreeSurface(testsurface);
}
RenderBackendOpenGL::~RenderBackendOpenGL() {
delete m_screen;
}
void RenderBackendOpenGL::init() {
Uint32 flags = SDL_INIT_VIDEO;
if (SDL_InitSubSystem(flags) < 0)
throw SDLException(SDL_GetError());
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // temporary hack
}
void RenderBackendOpenGL::deinit() {
delete m_screen;
m_screen = 0;
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
Screen* RenderBackendOpenGL::createMainScreen(unsigned int width, unsigned int height, unsigned char bitsPerPixel, bool fs) {
delete m_screen;
m_screen = 0;
Uint32 flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_HWACCEL;
if ( fs ) {
flags |= SDL_FULLSCREEN;
}
SDL_Surface* screen = NULL;
if( 0 == bitsPerPixel ) {
/// autodetect best mode
unsigned char possibleBitsPerPixel[] = {32, 24, 16, 0};
int i = 0;
while( true ) {
bitsPerPixel = possibleBitsPerPixel[i];
if( !bitsPerPixel ) {
throw SDLException("Videomode not available");
}
if ( SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) {
screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags);
if( screen ) {
break;
}
}
++i;
}
} else {
if ( !SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) {
throw SDLException("Videomode not available");
}
screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags);
}
SDL_WM_SetCaption("FIFE", 0);
if (!screen) {
throw SDLException(SDL_GetError());
}
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, width, height, 0);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_SCISSOR_TEST);
m_screen = new GLScreen();
GUIManager* guimanager = GUIManager::instance();
guimanager->init();
return m_screen;
}
void RenderBackendOpenGL::startFrame() {
glClear(GL_COLOR_BUFFER_BIT);
}
void RenderBackendOpenGL::endFrame() {
SDL_GL_SwapBuffers();
}
Image* RenderBackendOpenGL::createStaticImageFromRGBA(const uint8_t* data, unsigned int width, unsigned int height) {
return new GLImage(data, width, height);
}
Image* RenderBackendOpenGL::createStaticImageFromSDL(SDL_Surface* surface, bool freesurface) {
// Given an abritary surface, we must convert it to the format GLImage will understand.
// It's easiest to let SDL do this for us.
// We may want to check if the surface already is in the correct form, to avoid unneeded
// copying.
SDL_Surface* conv = SDL_ConvertSurface(surface, &m_rgba_format, SDL_SWSURFACE);
if (freesurface) {
SDL_FreeSurface(surface);
}
if (conv != 0) {
SDL_LockSurface(conv);
Image* image = new GLImage(static_cast<const uint8_t*>(conv->pixels), conv->w, conv->h, conv->pitch);
SDL_UnlockSurface(conv);
SDL_FreeSurface(conv);
return image;
}
return 0;
}
Screen* RenderBackendOpenGL::getMainScreen() const {
return m_screen;
}
void RenderBackendOpenGL::captureScreen(const std::string& filename) {
unsigned int swidth = getMainScreen()->getWidth();
unsigned int sheight = getMainScreen()->getHeight();
// We need unsigned char to avoid pointer alignment issues
uint8_t *pixels = new uint8_t[swidth * sheight * 3];
// Read in the pixel data
glReadPixels(0, 0, swidth, sheight, GL_RGB, GL_UNSIGNED_BYTE, reinterpret_cast<GLvoid*>(pixels));
/* At this point the image has been reversed, so we need to re-reverse it so that
it is the correct way around. We do this by copying the "image" pixels to another
surface in reverse order */
SDL_Surface* image = SDL_CreateRGBSurface(SDL_SWSURFACE, swidth, sheight, 24,
255U << (0), // Blue channel
255U << (8), // Green channel
255U << (16), // Red channel
0 /* no alpha! */);
SDL_LockSurface(image);
uint8_t *imagepixels = reinterpret_cast<uint8_t*>(image->pixels);
// Copy the "reversed_image" memory to the "image" memory
for (int y = (sheight - 1); y >= 0; --y) {
uint8_t *row_begin = pixels + y * swidth * 3;
uint8_t *row_end = row_begin + swidth * 3;
std::copy(row_begin, row_end, imagepixels);
// Advance a row in the output surface.
imagepixels += image->pitch;
}
SDL_UnlockSurface(image);
// Save file
SDL_SaveBMP(image, filename.c_str());
// Clear memory
delete []pixels;
SDL_FreeSurface( image );
}
}
<|endoftext|> |
<commit_before>//
// SegmentParser.cpp
// Clock Signal
//
// Created by Thomas Harte on 04/05/2018.
// Copyright 2018 Thomas Harte. All rights reserved.
//
#include "SegmentParser.hpp"
#include "Encoder.hpp"
#include <array>
namespace {
const uint8_t six_and_two_unmapping[] = {
/* 0x96 */ 0x00, 0x01,
/* 0x98 */ 0xff, 0xff, 0x02, 0x03, 0xff, 0x04, 0x05, 0x06,
/* 0xa0 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x08,
/* 0xa8 */ 0xff, 0xff, 0xff, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
/* 0xb0 */ 0xff, 0xff, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
/* 0xb8 */ 0xff, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
/* 0xc0 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
/* 0xc8 */ 0xff, 0xff, 0xff, 0x1b, 0xff, 0x1c, 0x1d, 0x1e,
/* 0xd0 */ 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0x20, 0x21,
/* 0xd8 */ 0xff, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
/* 0xe0 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0x29, 0x2a, 0x2b,
/* 0xe8 */ 0xff, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
/* 0xf0 */ 0xff, 0xff, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
/* 0xf8 */ 0xff, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
};
uint8_t unmap_six_and_two(uint8_t source) {
if(source < 0x96) return 0xff;
return six_and_two_unmapping[source - 0x96];
}
}
using namespace Storage::Encodings::AppleGCR;
std::map<std::size_t, Sector> Storage::Encodings::AppleGCR::sectors_from_segment(const Disk::PCMSegment &segment) {
std::map<std::size_t, Sector> result;
uint_fast8_t shift_register = 0;
const std::size_t scanning_sentinel = std::numeric_limits<std::size_t>::max();
std::unique_ptr<Sector> new_sector;
std::size_t sector_location = 0;
std::size_t pointer = scanning_sentinel;
std::array<uint_fast8_t, 8> header{{0, 0, 0, 0, 0, 0, 0, 0}};
std::array<uint_fast8_t, 3> scanner{{0, 0, 0}};
// Scan the track 1 and 1/8th times; that's long enough to make sure that any sector which straddles the
// end of the track is caught. Since they're put into a map, it doesn't matter if they're caught twice.
const size_t extended_length = segment.data.size() + (segment.data.size() >> 3);
for(size_t bit = 0; bit < extended_length; ++bit) {
shift_register = static_cast<uint_fast8_t>((shift_register << 1) | (segment.data[bit % segment.data.size()] ? 1 : 0));
// Apple GCR parsing: bytes always have the top bit set.
if(!(shift_register&0x80)) continue;
// Grab the byte.
const uint_fast8_t value = shift_register;
shift_register = 0;
scanner[0] = scanner[1];
scanner[1] = scanner[2];
scanner[2] = value;
if(pointer == scanning_sentinel) {
if(
scanner[0] == header_prologue[0] &&
scanner[1] == header_prologue[1] &&
(
scanner[2] == header_prologue[2] ||
scanner[2] == data_prologue[2]
)) {
pointer = 0;
// If this is the start of a data section, and at least
// one header has been witnessed, start a sector.
if(scanner[2] == data_prologue[2]) {
new_sector.reset(new Sector);
new_sector->data.reserve(412);
} else {
sector_location = static_cast<std::size_t>(bit % segment.data.size());
}
}
} else {
if(new_sector) {
// Check whether the value just read is a legal GCR byte, in six-and-two
// encoding (which is a strict superset of five-and-three).
if(unmap_six_and_two(value) == 0xff) {
// The second byte of the standard epilogue is illegal, so this still may
// be a valid sector. If the final byte was the first byte of an epilogue,
// chop it off and see whether the sector is otherwise intelligible.
if(new_sector->data.empty() || new_sector->data.back() != epilogue[0]) {
// No sector found; reset scanning procedure.
new_sector.reset();
pointer = scanning_sentinel;
continue;
}
// Chop off the last byte.
new_sector->data.resize(new_sector->data.size() - 1);
// Move the sector elsewhere for processing; there's definitely no way to proceed with
// the prospective sector if it doesn't parse.
std::unique_ptr<Sector> sector = std::move(new_sector);
new_sector.reset();
pointer = scanning_sentinel;
// Check for valid decoding options.
switch(sector->data.size()) {
default: // This is not a decodeable sector.
break;
// TODO: check for five-and-three / 13-sector form sectors.
case 343: { // Potentially this is an Apple II six-and-two sector.
// Check for apparent four and four encoding.
uint_fast8_t header_mask = 0xff;
for(auto c : header) header_mask &= c;
header_mask &= 0xaa;
if(header_mask != 0xaa) continue;
sector->address.volume = ((header[0] << 1) | 1) & header[1];
sector->address.track = ((header[2] << 1) | 1) & header[3];
sector->address.sector = ((header[4] << 1) | 1) & header[5];
// Check the header checksum.
uint_fast8_t checksum = ((header[6] << 1) | 1) & header[7];
if(checksum != (sector->address.volume^sector->address.track^sector->address.sector)) continue;
// Unmap the sector contents as 6 and 2 data.
bool out_of_bounds = false;
for(auto &c : sector->data) {
c = unmap_six_and_two(c);
if(c == 0xff) {
out_of_bounds = true;
break;
}
}
if(out_of_bounds) continue;
// Undo the XOR step on sector contents and check that checksum.
for(std::size_t c = 1; c < sector->data.size(); ++c) {
sector->data[c] ^= sector->data[c-1];
}
if(sector->data.back()) continue;
// Having checked the checksum, remove it.
sector->data.resize(sector->data.size() - 1);
// Undo the 6 and 2 mapping.
const uint8_t bit_reverse[] = {0, 2, 1, 3};
#define unmap(byte, nibble, shift) \
sector->data[86 + byte] = static_cast<uint8_t>(\
(sector->data[86 + byte] << 2) | bit_reverse[(sector->data[nibble] >> shift)&3]);
for(std::size_t c = 0; c < 84; ++c) {
unmap(c, c, 0);
unmap(c+86, c, 2);
unmap(c+172, c, 4);
}
unmap(84, 84, 0);
unmap(170, 84, 2);
unmap(85, 85, 0);
unmap(171, 85, 2);
#undef unmap
// Throw away the collection of two-bit chunks from the start of the sector.
sector->data.erase(sector->data.begin(), sector->data.end() - 256);
// Add this sector to the map.
sector->encoding = Sector::Encoding::SixAndTwo;
result.insert(std::make_pair(sector_location, std::move(*sector)));
} break;
case 704: { // Potentially this is a Macintosh sector.
// Attempt a six-and-two unmapping of the header.
std::array<uint_fast8_t, 5> decoded_header;
bool out_of_bounds = false;
for(size_t c = 0; c < decoded_header.size(); ++c) {
decoded_header[c] = unmap_six_and_two(header[c]);
if(decoded_header[c] == 0xff) {
out_of_bounds = true;
break;
}
}
if(out_of_bounds) continue;
// Test the checksum.
if(decoded_header[4] != (decoded_header[0] ^ decoded_header[1] ^ decoded_header[2] ^ decoded_header[3]))
sector->has_header_checksum_error = true;
// Decode the header.
sector->address.track = uint8_t(decoded_header[0] | ((decoded_header[2]&0x1f) << 6));
sector->address.sector = decoded_header[1];
sector->address.format = decoded_header[3];
sector->address.is_side_two = decoded_header[2] & 0x20;
// Reverse the GCR encoding of the sector contents to get back to 6-bit data.
for(auto &c: sector->data) {
c = unmap_six_and_two(c);
if(c == 0xff) {
out_of_bounds = true;
break;
}
}
if(out_of_bounds) continue;
// The first byte in the sector is a repeat of the sector number; test it
// for correctness.
if(sector->data[0] != sector->address.sector) continue;
// Cf. the corresponding section of Encoder.cpp for logic below.
int checksum[3] = {0, 0, 0};
for(size_t c = 0; c < 175; ++c) {
// Calculate the rolling checcksum in order to decode the bytes.
checksum[0] = (checksum[0] << 1) | (checksum[0] >> 7);
// All offsets are +1 below, to skip the initial sector number duplicate.
const uint8_t top_bits = sector->data[1 + c*4];
// Decode first byte.
sector->data[0 + c * 3] = uint8_t((sector->data[2 + c*4] + ((top_bits & 0x30) << 2)) ^ checksum[0]);
checksum[2] += sector->data[0 + c * 3] + (checksum[0] >> 8);
// Decode second byte;
sector->data[1 + c * 3] = uint8_t((sector->data[3 + c*4] + ((top_bits & 0x0c) << 4)) ^ checksum[2]);
checksum[1] += sector->data[1 + c * 3] + (checksum[2] >> 8);
// Decode third byte, if there is one.
if(c != 174) {
sector->data[2 + c * 3] = uint8_t((sector->data[4 + c*4] + ((top_bits & 0x03) << 6)) ^ checksum[1]);
checksum[0] += sector->data[2 + c * 3] + (checksum[1] >> 8);
}
// Reset carries.
checksum[0] &= 0xff;
checksum[1] &= 0xff;
checksum[2] &= 0xff;
}
// Test the checksum.
if(
checksum[0] != uint8_t(sector->data[703] + ((sector->data[700] & 0x03) << 6)) ||
checksum[1] != uint8_t(sector->data[702] + ((sector->data[700] & 0x0c) << 4)) ||
checksum[2] != uint8_t(sector->data[701] + ((sector->data[700] & 0x30) << 2))
) sector->has_data_checksum_error = true;
// Chop to size, and that's that.
sector->data.resize(524);
// Add this sector to the map.
sector->encoding = Sector::Encoding::Macintosh;
result.insert(std::make_pair(sector_location, std::move(*sector)));
} break;
}
} else {
new_sector->data.push_back(value);
}
} else {
// Just capture the header in place; it'll be decoded
// once a whole sector has been read.
header[pointer] = value;
++pointer;
if(pointer == 8) {
pointer = scanning_sentinel;
}
}
}
}
return result;
}
<commit_msg>Bumps up the amount of reserved storage.<commit_after>//
// SegmentParser.cpp
// Clock Signal
//
// Created by Thomas Harte on 04/05/2018.
// Copyright 2018 Thomas Harte. All rights reserved.
//
#include "SegmentParser.hpp"
#include "Encoder.hpp"
#include <array>
namespace {
const uint8_t six_and_two_unmapping[] = {
/* 0x96 */ 0x00, 0x01,
/* 0x98 */ 0xff, 0xff, 0x02, 0x03, 0xff, 0x04, 0x05, 0x06,
/* 0xa0 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x08,
/* 0xa8 */ 0xff, 0xff, 0xff, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
/* 0xb0 */ 0xff, 0xff, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
/* 0xb8 */ 0xff, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
/* 0xc0 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
/* 0xc8 */ 0xff, 0xff, 0xff, 0x1b, 0xff, 0x1c, 0x1d, 0x1e,
/* 0xd0 */ 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0x20, 0x21,
/* 0xd8 */ 0xff, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
/* 0xe0 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0x29, 0x2a, 0x2b,
/* 0xe8 */ 0xff, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
/* 0xf0 */ 0xff, 0xff, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
/* 0xf8 */ 0xff, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
};
uint8_t unmap_six_and_two(uint8_t source) {
if(source < 0x96) return 0xff;
return six_and_two_unmapping[source - 0x96];
}
}
using namespace Storage::Encodings::AppleGCR;
std::map<std::size_t, Sector> Storage::Encodings::AppleGCR::sectors_from_segment(const Disk::PCMSegment &segment) {
std::map<std::size_t, Sector> result;
uint_fast8_t shift_register = 0;
const std::size_t scanning_sentinel = std::numeric_limits<std::size_t>::max();
std::unique_ptr<Sector> new_sector;
std::size_t sector_location = 0;
std::size_t pointer = scanning_sentinel;
std::array<uint_fast8_t, 8> header{{0, 0, 0, 0, 0, 0, 0, 0}};
std::array<uint_fast8_t, 3> scanner{{0, 0, 0}};
// Scan the track 1 and 1/8th times; that's long enough to make sure that any sector which straddles the
// end of the track is caught. Since they're put into a map, it doesn't matter if they're caught twice.
const size_t extended_length = segment.data.size() + (segment.data.size() >> 3);
for(size_t bit = 0; bit < extended_length; ++bit) {
shift_register = static_cast<uint_fast8_t>((shift_register << 1) | (segment.data[bit % segment.data.size()] ? 1 : 0));
// Apple GCR parsing: bytes always have the top bit set.
if(!(shift_register&0x80)) continue;
// Grab the byte.
const uint_fast8_t value = shift_register;
shift_register = 0;
scanner[0] = scanner[1];
scanner[1] = scanner[2];
scanner[2] = value;
if(pointer == scanning_sentinel) {
if(
scanner[0] == header_prologue[0] &&
scanner[1] == header_prologue[1] &&
(
scanner[2] == header_prologue[2] ||
scanner[2] == data_prologue[2]
)) {
pointer = 0;
// If this is the start of a data section, and at least
// one header has been witnessed, start a sector.
if(scanner[2] == data_prologue[2]) {
new_sector.reset(new Sector);
new_sector->data.reserve(710);
} else {
sector_location = static_cast<std::size_t>(bit % segment.data.size());
}
}
} else {
if(new_sector) {
// Check whether the value just read is a legal GCR byte, in six-and-two
// encoding (which is a strict superset of five-and-three).
if(unmap_six_and_two(value) == 0xff) {
// The second byte of the standard epilogue is illegal, so this still may
// be a valid sector. If the final byte was the first byte of an epilogue,
// chop it off and see whether the sector is otherwise intelligible.
if(new_sector->data.empty() || new_sector->data.back() != epilogue[0]) {
// No sector found; reset scanning procedure.
new_sector.reset();
pointer = scanning_sentinel;
continue;
}
// Chop off the last byte.
new_sector->data.resize(new_sector->data.size() - 1);
// Move the sector elsewhere for processing; there's definitely no way to proceed with
// the prospective sector if it doesn't parse.
std::unique_ptr<Sector> sector = std::move(new_sector);
new_sector.reset();
pointer = scanning_sentinel;
// Check for valid decoding options.
switch(sector->data.size()) {
default: // This is not a decodeable sector.
break;
// TODO: check for five-and-three / 13-sector form sectors.
case 343: { // Potentially this is an Apple II six-and-two sector.
// Check for apparent four and four encoding.
uint_fast8_t header_mask = 0xff;
for(auto c : header) header_mask &= c;
header_mask &= 0xaa;
if(header_mask != 0xaa) continue;
sector->address.volume = ((header[0] << 1) | 1) & header[1];
sector->address.track = ((header[2] << 1) | 1) & header[3];
sector->address.sector = ((header[4] << 1) | 1) & header[5];
// Check the header checksum.
uint_fast8_t checksum = ((header[6] << 1) | 1) & header[7];
if(checksum != (sector->address.volume^sector->address.track^sector->address.sector)) continue;
// Unmap the sector contents as 6 and 2 data.
bool out_of_bounds = false;
for(auto &c : sector->data) {
c = unmap_six_and_two(c);
if(c == 0xff) {
out_of_bounds = true;
break;
}
}
if(out_of_bounds) continue;
// Undo the XOR step on sector contents and check that checksum.
for(std::size_t c = 1; c < sector->data.size(); ++c) {
sector->data[c] ^= sector->data[c-1];
}
if(sector->data.back()) continue;
// Having checked the checksum, remove it.
sector->data.resize(sector->data.size() - 1);
// Undo the 6 and 2 mapping.
const uint8_t bit_reverse[] = {0, 2, 1, 3};
#define unmap(byte, nibble, shift) \
sector->data[86 + byte] = static_cast<uint8_t>(\
(sector->data[86 + byte] << 2) | bit_reverse[(sector->data[nibble] >> shift)&3]);
for(std::size_t c = 0; c < 84; ++c) {
unmap(c, c, 0);
unmap(c+86, c, 2);
unmap(c+172, c, 4);
}
unmap(84, 84, 0);
unmap(170, 84, 2);
unmap(85, 85, 0);
unmap(171, 85, 2);
#undef unmap
// Throw away the collection of two-bit chunks from the start of the sector.
sector->data.erase(sector->data.begin(), sector->data.end() - 256);
// Add this sector to the map.
sector->encoding = Sector::Encoding::SixAndTwo;
result.insert(std::make_pair(sector_location, std::move(*sector)));
} break;
case 704: { // Potentially this is a Macintosh sector.
// Attempt a six-and-two unmapping of the header.
std::array<uint_fast8_t, 5> decoded_header;
bool out_of_bounds = false;
for(size_t c = 0; c < decoded_header.size(); ++c) {
decoded_header[c] = unmap_six_and_two(header[c]);
if(decoded_header[c] == 0xff) {
out_of_bounds = true;
break;
}
}
if(out_of_bounds) continue;
// Test the checksum.
if(decoded_header[4] != (decoded_header[0] ^ decoded_header[1] ^ decoded_header[2] ^ decoded_header[3]))
sector->has_header_checksum_error = true;
// Decode the header.
sector->address.track = uint8_t(decoded_header[0] | ((decoded_header[2]&0x1f) << 6));
sector->address.sector = decoded_header[1];
sector->address.format = decoded_header[3];
sector->address.is_side_two = decoded_header[2] & 0x20;
// Reverse the GCR encoding of the sector contents to get back to 6-bit data.
for(auto &c: sector->data) {
c = unmap_six_and_two(c);
if(c == 0xff) {
out_of_bounds = true;
break;
}
}
if(out_of_bounds) continue;
// The first byte in the sector is a repeat of the sector number; test it
// for correctness.
if(sector->data[0] != sector->address.sector) continue;
// Cf. the corresponding section of Encoder.cpp for logic below.
int checksum[3] = {0, 0, 0};
for(size_t c = 0; c < 175; ++c) {
// Calculate the rolling checcksum in order to decode the bytes.
checksum[0] = (checksum[0] << 1) | (checksum[0] >> 7);
// All offsets are +1 below, to skip the initial sector number duplicate.
const uint8_t top_bits = sector->data[1 + c*4];
// Decode first byte.
sector->data[0 + c * 3] = uint8_t((sector->data[2 + c*4] + ((top_bits & 0x30) << 2)) ^ checksum[0]);
checksum[2] += sector->data[0 + c * 3] + (checksum[0] >> 8);
// Decode second byte;
sector->data[1 + c * 3] = uint8_t((sector->data[3 + c*4] + ((top_bits & 0x0c) << 4)) ^ checksum[2]);
checksum[1] += sector->data[1 + c * 3] + (checksum[2] >> 8);
// Decode third byte, if there is one.
if(c != 174) {
sector->data[2 + c * 3] = uint8_t((sector->data[4 + c*4] + ((top_bits & 0x03) << 6)) ^ checksum[1]);
checksum[0] += sector->data[2 + c * 3] + (checksum[1] >> 8);
}
// Reset carries.
checksum[0] &= 0xff;
checksum[1] &= 0xff;
checksum[2] &= 0xff;
}
// Test the checksum.
if(
checksum[0] != uint8_t(sector->data[703] + ((sector->data[700] & 0x03) << 6)) ||
checksum[1] != uint8_t(sector->data[702] + ((sector->data[700] & 0x0c) << 4)) ||
checksum[2] != uint8_t(sector->data[701] + ((sector->data[700] & 0x30) << 2))
) sector->has_data_checksum_error = true;
// Chop to size, and that's that.
sector->data.resize(524);
// Add this sector to the map.
sector->encoding = Sector::Encoding::Macintosh;
result.insert(std::make_pair(sector_location, std::move(*sector)));
} break;
}
} else {
new_sector->data.push_back(value);
}
} else {
// Just capture the header in place; it'll be decoded
// once a whole sector has been read.
header[pointer] = value;
++pointer;
if(pointer == 8) {
pointer = scanning_sentinel;
}
}
}
}
return result;
}
<|endoftext|> |
<commit_before>
/**
* @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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.
*
* @file ImageReco.cpp
*/
#include "ImageReco.h"
#include <TH3D.h>
#include <TH1I.h>
#include "./JPetOptionsTools/JPetOptionsTools.h"
using namespace jpet_options_tools;
const int numberOfBins = 100;
const int xRange = 100;
const int yRange = 100;
const int zRange = 50;
const int numberOfHitsInEventHisto = 10;
const int numberOfConditions = 6;
int CUT_ON_Z_VALUE = 23;
int CUT_ON_LOR_DISTANCE_FROM_CENTER = 25;
int ANNIHILATION_POINT_Z = 23;
int TOT_MIN_VALUE_IN_NS = 15;
int TOT_MAX_VALUE_IN_NS = 25;
int ANGLE_DELTA_MIN_VALUE = 20;
ImageReco::ImageReco(const char* name) : JPetUserTask(name) {}
ImageReco::~ImageReco() {}
bool ImageReco::init()
{
auto opts = getOptions();
CUT_ON_Z_VALUE = getOptionAsInt(opts, "ImageReco_CUT_ON_Z_VALUE_int");
CUT_ON_LOR_DISTANCE_FROM_CENTER = getOptionAsInt(opts, "ImageReco_CUT_ON_LOR_DISTANCE_FROM_CENTER_int");
ANNIHILATION_POINT_Z = getOptionAsInt(opts, "ImageReco_ANNIHILATION_POINT_Z_int");
TOT_MIN_VALUE_IN_NS = getOptionAsInt(opts, "ImageReco_TOT_MIN_VALUE_IN_NS_int");
TOT_MAX_VALUE_IN_NS = getOptionAsInt(opts, "ImageReco_TOT_MAX_VALUE_IN_NS_int");
ANGLE_DELTA_MIN_VALUE = getOptionAsInt(opts, "ImageReco_ANGLE_DELTA_MIN_VALUE_int");
fOutputEvents = new JPetTimeWindow("JPetEvent");
getStatistics().createHistogram(new TH3D("hits_pos",
"Reconstructed hit pos",
numberOfBins, -xRange, xRange,
numberOfBins, -yRange, yRange,
numberOfBins, -zRange, zRange));
getStatistics().createHistogram(new TH1I("number_of_events",
"Number of events with n hits",
numberOfHitsInEventHisto, 0, numberOfHitsInEventHisto));
getStatistics().createHistogram(new TH1I("number_of_hits_filtered_by_condition",
"Number of hits filtered by condition",
numberOfConditions, 0, numberOfConditions));
//it is not really nessesery, but it is creating labels in given order
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on Z", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on LOR distance", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on delta angle", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on first hit TOT", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on second hit TOT", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on annihilation point Z", 1);
return true;
}
bool ImageReco::exec()
{
if (auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {
unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();
for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {
auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));
auto numberOfHits = event.getHits().size();
getStatistics().getHisto<TH1I>("number_of_events").Fill(numberOfHits);
if (numberOfHits <= 1)
continue;
else {
auto hits = event.getHits();
for (unsigned int i = 0; i < hits.size() - 1; i++) {
if (!checkConditions(hits[i], hits[i + 1]))
continue;
calculateReconstructedPosition(hits[i], hits[i + 1]);
}
}
}
} else {
ERROR("Returned event is not TimeWindow");
return false;
}
return true;
}
bool ImageReco::terminate()
{
return true;
}
bool ImageReco::checkConditions(const JPetHit& first, const JPetHit& second)
{
if (!cutOnZ(first, second)) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on Z", 1);
return false;
}
if (!cutOnLORDistanceFromCenter(first, second)) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on LOR distance", 1);
return false;
}
if (angleDelta(first, second) < ANGLE_DELTA_MIN_VALUE) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on delta angle", 1);
return false;
}
double totOfFirstHit = calculateSumOfTOTsOfHit(first);
if (totOfFirstHit < TOT_MIN_VALUE_IN_NS || totOfFirstHit > TOT_MAX_VALUE_IN_NS) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on first hit TOT", 1);
return false;
}
double totOfSecondHit = calculateSumOfTOTsOfHit(second);
if (totOfSecondHit < TOT_MIN_VALUE_IN_NS || totOfSecondHit > TOT_MAX_VALUE_IN_NS) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on second hit TOT", 1);
return false;
}
return true;
}
bool ImageReco::cutOnZ(const JPetHit& first, const JPetHit& second)
{
return (std::fabs(first.getPosZ()) < CUT_ON_Z_VALUE) && (fabs(second.getPosZ()) < CUT_ON_Z_VALUE);
}
bool ImageReco::cutOnLORDistanceFromCenter(const JPetHit& first, const JPetHit& second)
{
double x_a = first.getPosX();
double x_b = second.getPosX();
double y_a = first.getPosY();
double y_b = second.getPosY();
double a = (y_a - y_b) / (x_a - x_b);
double c = y_a - ((y_a - y_b) / (x_a - x_b)) * x_a;
return (std::fabs(c) / std::sqrt(a * a + 1)) < CUT_ON_LOR_DISTANCE_FROM_CENTER; //b is 1 and b*b is 1
}
float ImageReco::angleDelta(const JPetHit& first, const JPetHit& second)
{
float delta = fabs(first.getBarrelSlot().getTheta() - second.getBarrelSlot().getTheta());
return std::min(delta, (float)360 - delta);
}
double ImageReco::calculateSumOfTOTsOfHit(const JPetHit& hit)
{
return calculateSumOfTOTs(hit.getSignalA()) + calculateSumOfTOTs(hit.getSignalB());
}
double ImageReco::calculateSumOfTOTs(const JPetPhysSignal& signal)
{
double tot = 0.;
std::map<int, double> leadingPoints, trailingPoints;
leadingPoints = signal.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);
trailingPoints = signal.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);
for (int i = 1; i < 5; i++) {
auto leadSearch = leadingPoints.find(i);
auto trailSearch = trailingPoints.find(i);
if (leadSearch != leadingPoints.end() && trailSearch != trailingPoints.end())
tot += (trailSearch->second - leadSearch->second);
}
return tot / 1000.;
}
bool ImageReco::calculateReconstructedPosition(const JPetHit& firstHit, const JPetHit& secondHit)
{
double s1_a = static_cast<double>(firstHit.getSignalA().getTime());
double s1_b = static_cast<double>(firstHit.getSignalB().getTime());
double s2_a = static_cast<double>(secondHit.getSignalA().getTime());
double s2_b = static_cast<double>(secondHit.getSignalB().getTime());
double t_s1_ab = s1_a - s1_b;
double t_s2_ab = s2_a - s2_b;
double s1_z = (t_s1_ab * 11) / 2.0;
double s2_z = (t_s2_ab * 11) / 2.0;
double vdx = secondHit.getPosX() - firstHit.getPosX();
double vdz = s2_z - s1_z;
double vdy = secondHit.getPosY() - firstHit.getPosY();
double dd = std::sqrt(vdx * vdx + vdz * vdz + vdy * vdy);
double mtof_a = 0;
if (firstHit.getPosY() > secondHit.getPosY()) {
mtof_a = ((((s1_a + s1_b) / 2.0) - ((s2_a + s2_b) / 2.0)) * 30);
} else {
mtof_a = ((((s2_a + s2_b) / 2.0) - ((s1_a + s1_b) / 2.0)) * 30);
}
double x, y, z;
x = firstHit.getPosX() + ((vdx / 2.0) + (vdx / dd * mtof_a));
y = firstHit.getPosY() + ((vdy / 2.0) + (vdy / dd * mtof_a));
z = s1_z + ((vdz / 2.0) + (vdz / dd * mtof_a));
//x > -xRange && x < xRange && y > -yRange && y < yRange &&
if (z > -ANNIHILATION_POINT_Z && z < ANNIHILATION_POINT_Z) {
getStatistics().getHisto<TH3D>("hits_pos").Fill(x, y, z);
return true;
} else {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on annihilation point Z", 1);
}
return false;
}
<commit_msg>Add control histograms<commit_after>
/**
* @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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.
*
* @file ImageReco.cpp
*/
#include "ImageReco.h"
#include <TH3D.h>
#include <TH1I.h>
#include "./JPetOptionsTools/JPetOptionsTools.h"
using namespace jpet_options_tools;
const int numberOfBins = 100;
const int xRange = 100;
const int yRange = 100;
const int zRange = 50;
const int numberOfHitsInEventHisto = 10;
const int numberOfConditions = 6;
int CUT_ON_Z_VALUE = 23;
int CUT_ON_LOR_DISTANCE_FROM_CENTER = 25;
int ANNIHILATION_POINT_Z = 23;
int TOT_MIN_VALUE_IN_NS = 15;
int TOT_MAX_VALUE_IN_NS = 25;
int ANGLE_DELTA_MIN_VALUE = 20;
ImageReco::ImageReco(const char* name) : JPetUserTask(name) {}
ImageReco::~ImageReco() {}
bool ImageReco::init()
{
auto opts = getOptions();
CUT_ON_Z_VALUE = getOptionAsInt(opts, "ImageReco_CUT_ON_Z_VALUE_int");
CUT_ON_LOR_DISTANCE_FROM_CENTER = getOptionAsInt(opts, "ImageReco_CUT_ON_LOR_DISTANCE_FROM_CENTER_int");
ANNIHILATION_POINT_Z = getOptionAsInt(opts, "ImageReco_ANNIHILATION_POINT_Z_int");
TOT_MIN_VALUE_IN_NS = getOptionAsInt(opts, "ImageReco_TOT_MIN_VALUE_IN_NS_int");
TOT_MAX_VALUE_IN_NS = getOptionAsInt(opts, "ImageReco_TOT_MAX_VALUE_IN_NS_int");
ANGLE_DELTA_MIN_VALUE = getOptionAsInt(opts, "ImageReco_ANGLE_DELTA_MIN_VALUE_int");
fOutputEvents = new JPetTimeWindow("JPetEvent");
getStatistics().createHistogram(new TH3D("hits_pos",
"Reconstructed hit pos",
numberOfBins, -xRange, xRange,
numberOfBins, -yRange, yRange,
numberOfBins, -zRange, zRange));
getStatistics().createHistogram(new TH1I("number_of_events",
"Number of events with n hits",
numberOfHitsInEventHisto, 0, numberOfHitsInEventHisto));
getStatistics().createHistogram(new TH1I("number_of_hits_filtered_by_condition",
"Number of hits filtered by condition",
numberOfConditions, 0, numberOfConditions));
getStatistics().createHistogram(new TH1D("distance_from_center",
"Distance from center",
zRange, -zRange, zRange));
getStatistics().createHistogram(new TH1D("cut_on_Z",
"Cut on Z",
zRange, -zRange, zRange));
getStatistics().createHistogram(new TH1D("angle_delta",
"Angle delta",
360, 0, 360));
getStatistics().createHistogram(new TH1D("first_hit_TOT",
"Cut on first hit TOT",
100, 0, 100));
getStatistics().createHistogram(new TH1D("second_hit_TOT",
"Cut on second hit TOT",
100, 0, 100));
getStatistics().createHistogram(new TH1D("annihilation_point_z",
"Annihilation point Z",
zRange, -zRange, zRange));
//it is not really nessesery, but it is creating labels in given order
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on Z", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on LOR distance", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on delta angle", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on first hit TOT", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on second hit TOT", 1);
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on annihilation point Z", 1);
return true;
}
bool ImageReco::exec()
{
if (auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {
unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();
for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {
auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));
auto numberOfHits = event.getHits().size();
getStatistics().getHisto<TH1I>("number_of_events").Fill(numberOfHits);
if (numberOfHits <= 1)
continue;
else {
auto hits = event.getHits();
for (unsigned int i = 0; i < hits.size() - 1; i++) {
if (!checkConditions(hits[i], hits[i + 1]))
continue;
calculateReconstructedPosition(hits[i], hits[i + 1]);
}
}
}
} else {
ERROR("Returned event is not TimeWindow");
return false;
}
return true;
}
bool ImageReco::terminate()
{
return true;
}
bool ImageReco::checkConditions(const JPetHit& first, const JPetHit& second)
{
if (!cutOnZ(first, second)) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on Z", 1);
return false;
}
if (!cutOnLORDistanceFromCenter(first, second)) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on LOR distance", 1);
return false;
}
if (angleDelta(first, second) < ANGLE_DELTA_MIN_VALUE) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on delta angle", 1);
return false;
}
double totOfFirstHit = calculateSumOfTOTsOfHit(first);
getStatistics().getHisto<TH1D>("first_hit_TOT").Fill(totOfFirstHit);
if (totOfFirstHit < TOT_MIN_VALUE_IN_NS || totOfFirstHit > TOT_MAX_VALUE_IN_NS) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on first hit TOT", 1);
return false;
}
double totOfSecondHit = calculateSumOfTOTsOfHit(second);
getStatistics().getHisto<TH1D>("second_hit_TOT").Fill(totOfSecondHit);
if (totOfSecondHit < TOT_MIN_VALUE_IN_NS || totOfSecondHit > TOT_MAX_VALUE_IN_NS) {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on second hit TOT", 1);
return false;
}
return true;
}
bool ImageReco::cutOnZ(const JPetHit& first, const JPetHit& second)
{
getStatistics().getHisto<TH1D>("cut_on_Z").Fill(std::fabs(first.getPosZ()));
getStatistics().getHisto<TH1D>("cut_on_Z").Fill(std::fabs(second.getPosZ()));
return (std::fabs(first.getPosZ()) < CUT_ON_Z_VALUE) && (fabs(second.getPosZ()) < CUT_ON_Z_VALUE);
}
bool ImageReco::cutOnLORDistanceFromCenter(const JPetHit& first, const JPetHit& second)
{
double x_a = first.getPosX();
double x_b = second.getPosX();
double y_a = first.getPosY();
double y_b = second.getPosY();
double a = (y_a - y_b) / (x_a - x_b);
double c = y_a - ((y_a - y_b) / (x_a - x_b)) * x_a;
getStatistics().getHisto<TH1D>("distance_from_center").Fill((std::fabs(c) / std::sqrt(a * a + 1)));
return (std::fabs(c) / std::sqrt(a * a + 1)) < CUT_ON_LOR_DISTANCE_FROM_CENTER; //b is 1 and b*b is 1
}
float ImageReco::angleDelta(const JPetHit& first, const JPetHit& second)
{
float delta = fabs(first.getBarrelSlot().getTheta() - second.getBarrelSlot().getTheta());
getStatistics().getHisto<TH1D>("angle_delta").Fill(std::min(delta, (float)360 - delta));
return std::min(delta, (float)360 - delta);
}
double ImageReco::calculateSumOfTOTsOfHit(const JPetHit& hit)
{
return calculateSumOfTOTs(hit.getSignalA()) + calculateSumOfTOTs(hit.getSignalB());
}
double ImageReco::calculateSumOfTOTs(const JPetPhysSignal& signal)
{
double tot = 0.;
std::map<int, double> leadingPoints, trailingPoints;
leadingPoints = signal.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);
trailingPoints = signal.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);
for (int i = 1; i < 5; i++) {
auto leadSearch = leadingPoints.find(i);
auto trailSearch = trailingPoints.find(i);
if (leadSearch != leadingPoints.end() && trailSearch != trailingPoints.end())
tot += (trailSearch->second - leadSearch->second);
}
return tot / 1000.;
}
bool ImageReco::calculateReconstructedPosition(const JPetHit& firstHit, const JPetHit& secondHit)
{
double s1_a = static_cast<double>(firstHit.getSignalA().getTime());
double s1_b = static_cast<double>(firstHit.getSignalB().getTime());
double s2_a = static_cast<double>(secondHit.getSignalA().getTime());
double s2_b = static_cast<double>(secondHit.getSignalB().getTime());
double t_s1_ab = s1_a - s1_b;
double t_s2_ab = s2_a - s2_b;
double s1_z = (t_s1_ab * 11) / 2.0;
double s2_z = (t_s2_ab * 11) / 2.0;
double vdx = secondHit.getPosX() - firstHit.getPosX();
double vdz = s2_z - s1_z;
double vdy = secondHit.getPosY() - firstHit.getPosY();
double dd = std::sqrt(vdx * vdx + vdz * vdz + vdy * vdy);
double mtof_a = 0;
if (firstHit.getPosY() > secondHit.getPosY()) {
mtof_a = ((((s1_a + s1_b) / 2.0) - ((s2_a + s2_b) / 2.0)) * 30);
} else {
mtof_a = ((((s2_a + s2_b) / 2.0) - ((s1_a + s1_b) / 2.0)) * 30);
}
double x, y, z;
x = firstHit.getPosX() + ((vdx / 2.0) + (vdx / dd * mtof_a));
y = firstHit.getPosY() + ((vdy / 2.0) + (vdy / dd * mtof_a));
z = s1_z + ((vdz / 2.0) + (vdz / dd * mtof_a));
//x > -xRange && x < xRange && y > -yRange && y < yRange &&
getStatistics().getHisto<TH1D>("annihilation_point_z").Fill(z);
if (z > -ANNIHILATION_POINT_Z && z < ANNIHILATION_POINT_Z) {
getStatistics().getHisto<TH3D>("hits_pos").Fill(x, y, z);
return true;
} else {
getStatistics().getHisto<TH1I>("number_of_hits_filtered_by_condition").Fill("Cut on annihilation point Z", 1);
}
return false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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/chromeos/drive/sync_client.h"
#include <vector>
#include "base/bind.h"
#include "base/message_loop/message_loop_proxy.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system/download_operation.h"
#include "chrome/browser/chromeos/drive/file_system/operation_observer.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/sync/entry_update_performer.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/drive/task_util.h"
using content::BrowserThread;
namespace drive {
namespace internal {
namespace {
// The delay constant is used to delay processing a sync task. We should not
// process SyncTasks immediately for the following reasons:
//
// 1) For fetching, the user may accidentally click on "Make available
// offline" checkbox on a file, and immediately cancel it in a second.
// It's a waste to fetch the file in this case.
//
// 2) For uploading, file writing via HTML5 file system API is performed in
// two steps: 1) truncate a file to 0 bytes, 2) write contents. We
// shouldn't start uploading right after the step 1). Besides, the user
// may edit the same file repeatedly in a short period of time.
//
// TODO(satorux): We should find a way to handle the upload case more nicely,
// and shorten the delay. crbug.com/134774
const int kDelaySeconds = 5;
// The delay constant is used to delay retrying a sync task on server errors.
const int kLongDelaySeconds = 600;
// Iterates entries and appends IDs to |to_fetch| if the file is pinned but not
// fetched (not present locally), to |to_update| if the file needs update.
void CollectBacklog(ResourceMetadata* metadata,
std::vector<std::string>* to_fetch,
std::vector<std::string>* to_update) {
DCHECK(to_fetch);
DCHECK(to_update);
scoped_ptr<ResourceMetadata::Iterator> it = metadata->GetIterator();
for (; !it->IsAtEnd(); it->Advance()) {
const std::string& local_id = it->GetID();
const ResourceEntry& entry = it->GetValue();
if (entry.parent_local_id() == util::kDriveTrashDirLocalId) {
to_update->push_back(local_id);
continue;
}
bool should_update = false;
switch (entry.metadata_edit_state()) {
case ResourceEntry::CLEAN:
break;
case ResourceEntry::SYNCING:
case ResourceEntry::DIRTY:
should_update = true;
break;
}
FileCacheEntry cache_entry;
if (it->GetCacheEntry(&cache_entry)) {
if (cache_entry.is_pinned() && !cache_entry.is_present())
to_fetch->push_back(local_id);
if (cache_entry.is_dirty())
should_update = true;
}
if (should_update)
to_update->push_back(local_id);
}
DCHECK(!it->HasError());
}
// Iterates cache entries and collects IDs of ones with obsolete cache files.
void CheckExistingPinnedFiles(ResourceMetadata* metadata,
FileCache* cache,
std::vector<std::string>* local_ids) {
scoped_ptr<FileCache::Iterator> it = cache->GetIterator();
for (; !it->IsAtEnd(); it->Advance()) {
const FileCacheEntry& cache_entry = it->GetValue();
const std::string& local_id = it->GetID();
if (!cache_entry.is_pinned() || !cache_entry.is_present())
continue;
ResourceEntry entry;
FileError error = metadata->GetResourceEntryById(local_id, &entry);
if (error != FILE_ERROR_OK) {
LOG(WARNING) << "Entry not found: " << local_id;
continue;
}
// If MD5s don't match, it indicates the local cache file is stale, unless
// the file is dirty (the MD5 is "local"). We should never re-fetch the
// file when we have a locally modified version.
if (entry.file_specific_info().md5() == cache_entry.md5() ||
cache_entry.is_dirty())
continue;
error = cache->Remove(local_id);
if (error != FILE_ERROR_OK) {
LOG(WARNING) << "Failed to remove cache entry: " << local_id;
continue;
}
error = cache->Pin(local_id);
if (error != FILE_ERROR_OK) {
LOG(WARNING) << "Failed to pin cache entry: " << local_id;
continue;
}
local_ids->push_back(local_id);
}
DCHECK(!it->HasError());
}
} // namespace
SyncClient::SyncTask::SyncTask() : state(PENDING), should_run_again(false) {}
SyncClient::SyncTask::~SyncTask() {}
SyncClient::SyncClient(base::SequencedTaskRunner* blocking_task_runner,
file_system::OperationObserver* observer,
JobScheduler* scheduler,
ResourceMetadata* metadata,
FileCache* cache,
ChangeListLoader* change_list_loader,
const base::FilePath& temporary_file_directory)
: blocking_task_runner_(blocking_task_runner),
operation_observer_(observer),
metadata_(metadata),
cache_(cache),
download_operation_(new file_system::DownloadOperation(
blocking_task_runner,
observer,
scheduler,
metadata,
cache,
temporary_file_directory)),
entry_update_performer_(new EntryUpdatePerformer(blocking_task_runner,
observer,
scheduler,
metadata,
cache,
change_list_loader)),
delay_(base::TimeDelta::FromSeconds(kDelaySeconds)),
long_delay_(base::TimeDelta::FromSeconds(kLongDelaySeconds)),
weak_ptr_factory_(this) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
SyncClient::~SyncClient() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void SyncClient::StartProcessingBacklog() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::vector<std::string>* to_fetch = new std::vector<std::string>;
std::vector<std::string>* to_update = new std::vector<std::string>;
blocking_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&CollectBacklog, metadata_, to_fetch, to_update),
base::Bind(&SyncClient::OnGetLocalIdsOfBacklog,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(to_fetch),
base::Owned(to_update)));
}
void SyncClient::StartCheckingExistingPinnedFiles() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::vector<std::string>* local_ids = new std::vector<std::string>;
blocking_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&CheckExistingPinnedFiles,
metadata_,
cache_,
local_ids),
base::Bind(&SyncClient::AddFetchTasks,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(local_ids)));
}
void SyncClient::AddFetchTask(const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
AddFetchTaskInternal(local_id, delay_);
}
void SyncClient::RemoveFetchTask(const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SyncTasks::iterator it = tasks_.find(SyncTasks::key_type(FETCH, local_id));
if (it == tasks_.end())
return;
SyncTask* task = &it->second;
switch (task->state) {
case PENDING:
tasks_.erase(it);
break;
case RUNNING:
// TODO(kinaba): Cancel tasks in JobScheduler as well. crbug.com/248856
break;
}
}
void SyncClient::AddUpdateTask(const ClientContext& context,
const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
AddUpdateTaskInternal(context, local_id, delay_);
}
void SyncClient::AddFetchTaskInternal(const std::string& local_id,
const base::TimeDelta& delay) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SyncTask task;
task.task = base::Bind(
&file_system::DownloadOperation::EnsureFileDownloadedByLocalId,
base::Unretained(download_operation_.get()),
local_id,
ClientContext(BACKGROUND),
GetFileContentInitializedCallback(),
google_apis::GetContentCallback(),
base::Bind(&SyncClient::OnFetchFileComplete,
weak_ptr_factory_.GetWeakPtr(),
local_id));
AddTask(SyncTasks::key_type(FETCH, local_id), task, delay);
}
void SyncClient::AddUpdateTaskInternal(const ClientContext& context,
const std::string& local_id,
const base::TimeDelta& delay) {
SyncTask task;
task.task = base::Bind(
&EntryUpdatePerformer::UpdateEntry,
base::Unretained(entry_update_performer_.get()),
local_id,
context,
base::Bind(&SyncClient::OnUpdateComplete,
weak_ptr_factory_.GetWeakPtr(),
local_id));
AddTask(SyncTasks::key_type(UPDATE, local_id), task, delay);
}
void SyncClient::AddTask(const SyncTasks::key_type& key,
const SyncTask& task,
const base::TimeDelta& delay) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SyncTasks::iterator it = tasks_.find(key);
if (it != tasks_.end()) {
switch (it->second.state) {
case PENDING:
// The same task will run, do nothing.
break;
case RUNNING:
// Something has changed since the task started. Schedule rerun.
it->second.should_run_again = true;
break;
}
return;
}
DCHECK_EQ(PENDING, task.state);
tasks_[key] = task;
base::MessageLoopProxy::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&SyncClient::StartTask, weak_ptr_factory_.GetWeakPtr(), key),
delay);
}
void SyncClient::StartTask(const SyncTasks::key_type& key) {
SyncTasks::iterator it = tasks_.find(key);
if (it == tasks_.end())
return;
SyncTask* task = &it->second;
switch (task->state) {
case PENDING:
task->state = RUNNING;
task->task.Run();
break;
case RUNNING: // Do nothing.
break;
}
}
void SyncClient::OnGetLocalIdsOfBacklog(
const std::vector<std::string>* to_fetch,
const std::vector<std::string>* to_update) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Give priority to upload tasks over fetch tasks, so that dirty files are
// uploaded as soon as possible.
for (size_t i = 0; i < to_update->size(); ++i) {
const std::string& local_id = (*to_update)[i];
DVLOG(1) << "Queuing to update: " << local_id;
AddUpdateTask(ClientContext(BACKGROUND), local_id);
}
for (size_t i = 0; i < to_fetch->size(); ++i) {
const std::string& local_id = (*to_fetch)[i];
DVLOG(1) << "Queuing to fetch: " << local_id;
AddFetchTaskInternal(local_id, delay_);
}
}
void SyncClient::AddFetchTasks(const std::vector<std::string>* local_ids) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (size_t i = 0; i < local_ids->size(); ++i)
AddFetchTask((*local_ids)[i]);
}
bool SyncClient::OnTaskComplete(SyncType type, const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const SyncTasks::key_type key(type, local_id);
SyncTasks::iterator it = tasks_.find(key);
DCHECK(it != tasks_.end());
if (it->second.should_run_again) {
DVLOG(1) << "Running again: type = " << type << ", id = " << local_id;
it->second.should_run_again = false;
it->second.task.Run();
return false;
}
tasks_.erase(it);
return true;
}
void SyncClient::OnFetchFileComplete(const std::string& local_id,
FileError error,
const base::FilePath& local_path,
scoped_ptr<ResourceEntry> entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!OnTaskComplete(FETCH, local_id))
return;
if (error == FILE_ERROR_OK) {
DVLOG(1) << "Fetched " << local_id << ": " << local_path.value();
} else {
switch (error) {
case FILE_ERROR_ABORT:
// If user cancels download, unpin the file so that we do not sync the
// file again.
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&FileCache::Unpin, base::Unretained(cache_), local_id),
base::Bind(&util::EmptyFileOperationCallback));
break;
case FILE_ERROR_NO_CONNECTION:
// Add the task again so that we'll retry once the connection is back.
AddFetchTaskInternal(local_id, delay_);
break;
case FILE_ERROR_SERVICE_UNAVAILABLE:
// Add the task again so that we'll retry once the service is back.
AddFetchTaskInternal(local_id, long_delay_);
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_SERVICE_UNAVAILABLE,
local_id);
break;
default:
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_MISC,
local_id);
LOG(WARNING) << "Failed to fetch " << local_id
<< ": " << FileErrorToString(error);
}
}
}
void SyncClient::OnUpdateComplete(const std::string& local_id,
FileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!OnTaskComplete(UPDATE, local_id))
return;
if (error == FILE_ERROR_OK) {
DVLOG(1) << "Updated " << local_id;
} else {
switch (error) {
case FILE_ERROR_NO_CONNECTION:
// Add the task again so that we'll retry once the connection is back.
AddUpdateTaskInternal(ClientContext(BACKGROUND), local_id,
base::TimeDelta::FromSeconds(0));
break;
case FILE_ERROR_SERVICE_UNAVAILABLE:
// Add the task again so that we'll retry once the service is back.
AddUpdateTaskInternal(ClientContext(BACKGROUND), local_id, long_delay_);
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_SERVICE_UNAVAILABLE,
local_id);
break;
default:
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_MISC,
local_id);
LOG(WARNING) << "Failed to update " << local_id << ": "
<< FileErrorToString(error);
}
}
}
} // namespace internal
} // namespace drive
<commit_msg>Files.app: Ignore FILE_ERROR_ABORT error when sync update.<commit_after>// Copyright (c) 2012 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/chromeos/drive/sync_client.h"
#include <vector>
#include "base/bind.h"
#include "base/message_loop/message_loop_proxy.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system/download_operation.h"
#include "chrome/browser/chromeos/drive/file_system/operation_observer.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/sync/entry_update_performer.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/drive/task_util.h"
using content::BrowserThread;
namespace drive {
namespace internal {
namespace {
// The delay constant is used to delay processing a sync task. We should not
// process SyncTasks immediately for the following reasons:
//
// 1) For fetching, the user may accidentally click on "Make available
// offline" checkbox on a file, and immediately cancel it in a second.
// It's a waste to fetch the file in this case.
//
// 2) For uploading, file writing via HTML5 file system API is performed in
// two steps: 1) truncate a file to 0 bytes, 2) write contents. We
// shouldn't start uploading right after the step 1). Besides, the user
// may edit the same file repeatedly in a short period of time.
//
// TODO(satorux): We should find a way to handle the upload case more nicely,
// and shorten the delay. crbug.com/134774
const int kDelaySeconds = 5;
// The delay constant is used to delay retrying a sync task on server errors.
const int kLongDelaySeconds = 600;
// Iterates entries and appends IDs to |to_fetch| if the file is pinned but not
// fetched (not present locally), to |to_update| if the file needs update.
void CollectBacklog(ResourceMetadata* metadata,
std::vector<std::string>* to_fetch,
std::vector<std::string>* to_update) {
DCHECK(to_fetch);
DCHECK(to_update);
scoped_ptr<ResourceMetadata::Iterator> it = metadata->GetIterator();
for (; !it->IsAtEnd(); it->Advance()) {
const std::string& local_id = it->GetID();
const ResourceEntry& entry = it->GetValue();
if (entry.parent_local_id() == util::kDriveTrashDirLocalId) {
to_update->push_back(local_id);
continue;
}
bool should_update = false;
switch (entry.metadata_edit_state()) {
case ResourceEntry::CLEAN:
break;
case ResourceEntry::SYNCING:
case ResourceEntry::DIRTY:
should_update = true;
break;
}
FileCacheEntry cache_entry;
if (it->GetCacheEntry(&cache_entry)) {
if (cache_entry.is_pinned() && !cache_entry.is_present())
to_fetch->push_back(local_id);
if (cache_entry.is_dirty())
should_update = true;
}
if (should_update)
to_update->push_back(local_id);
}
DCHECK(!it->HasError());
}
// Iterates cache entries and collects IDs of ones with obsolete cache files.
void CheckExistingPinnedFiles(ResourceMetadata* metadata,
FileCache* cache,
std::vector<std::string>* local_ids) {
scoped_ptr<FileCache::Iterator> it = cache->GetIterator();
for (; !it->IsAtEnd(); it->Advance()) {
const FileCacheEntry& cache_entry = it->GetValue();
const std::string& local_id = it->GetID();
if (!cache_entry.is_pinned() || !cache_entry.is_present())
continue;
ResourceEntry entry;
FileError error = metadata->GetResourceEntryById(local_id, &entry);
if (error != FILE_ERROR_OK) {
LOG(WARNING) << "Entry not found: " << local_id;
continue;
}
// If MD5s don't match, it indicates the local cache file is stale, unless
// the file is dirty (the MD5 is "local"). We should never re-fetch the
// file when we have a locally modified version.
if (entry.file_specific_info().md5() == cache_entry.md5() ||
cache_entry.is_dirty())
continue;
error = cache->Remove(local_id);
if (error != FILE_ERROR_OK) {
LOG(WARNING) << "Failed to remove cache entry: " << local_id;
continue;
}
error = cache->Pin(local_id);
if (error != FILE_ERROR_OK) {
LOG(WARNING) << "Failed to pin cache entry: " << local_id;
continue;
}
local_ids->push_back(local_id);
}
DCHECK(!it->HasError());
}
} // namespace
SyncClient::SyncTask::SyncTask() : state(PENDING), should_run_again(false) {}
SyncClient::SyncTask::~SyncTask() {}
SyncClient::SyncClient(base::SequencedTaskRunner* blocking_task_runner,
file_system::OperationObserver* observer,
JobScheduler* scheduler,
ResourceMetadata* metadata,
FileCache* cache,
ChangeListLoader* change_list_loader,
const base::FilePath& temporary_file_directory)
: blocking_task_runner_(blocking_task_runner),
operation_observer_(observer),
metadata_(metadata),
cache_(cache),
download_operation_(new file_system::DownloadOperation(
blocking_task_runner,
observer,
scheduler,
metadata,
cache,
temporary_file_directory)),
entry_update_performer_(new EntryUpdatePerformer(blocking_task_runner,
observer,
scheduler,
metadata,
cache,
change_list_loader)),
delay_(base::TimeDelta::FromSeconds(kDelaySeconds)),
long_delay_(base::TimeDelta::FromSeconds(kLongDelaySeconds)),
weak_ptr_factory_(this) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
SyncClient::~SyncClient() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void SyncClient::StartProcessingBacklog() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::vector<std::string>* to_fetch = new std::vector<std::string>;
std::vector<std::string>* to_update = new std::vector<std::string>;
blocking_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&CollectBacklog, metadata_, to_fetch, to_update),
base::Bind(&SyncClient::OnGetLocalIdsOfBacklog,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(to_fetch),
base::Owned(to_update)));
}
void SyncClient::StartCheckingExistingPinnedFiles() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::vector<std::string>* local_ids = new std::vector<std::string>;
blocking_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&CheckExistingPinnedFiles,
metadata_,
cache_,
local_ids),
base::Bind(&SyncClient::AddFetchTasks,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(local_ids)));
}
void SyncClient::AddFetchTask(const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
AddFetchTaskInternal(local_id, delay_);
}
void SyncClient::RemoveFetchTask(const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SyncTasks::iterator it = tasks_.find(SyncTasks::key_type(FETCH, local_id));
if (it == tasks_.end())
return;
SyncTask* task = &it->second;
switch (task->state) {
case PENDING:
tasks_.erase(it);
break;
case RUNNING:
// TODO(kinaba): Cancel tasks in JobScheduler as well. crbug.com/248856
break;
}
}
void SyncClient::AddUpdateTask(const ClientContext& context,
const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
AddUpdateTaskInternal(context, local_id, delay_);
}
void SyncClient::AddFetchTaskInternal(const std::string& local_id,
const base::TimeDelta& delay) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SyncTask task;
task.task = base::Bind(
&file_system::DownloadOperation::EnsureFileDownloadedByLocalId,
base::Unretained(download_operation_.get()),
local_id,
ClientContext(BACKGROUND),
GetFileContentInitializedCallback(),
google_apis::GetContentCallback(),
base::Bind(&SyncClient::OnFetchFileComplete,
weak_ptr_factory_.GetWeakPtr(),
local_id));
AddTask(SyncTasks::key_type(FETCH, local_id), task, delay);
}
void SyncClient::AddUpdateTaskInternal(const ClientContext& context,
const std::string& local_id,
const base::TimeDelta& delay) {
SyncTask task;
task.task = base::Bind(
&EntryUpdatePerformer::UpdateEntry,
base::Unretained(entry_update_performer_.get()),
local_id,
context,
base::Bind(&SyncClient::OnUpdateComplete,
weak_ptr_factory_.GetWeakPtr(),
local_id));
AddTask(SyncTasks::key_type(UPDATE, local_id), task, delay);
}
void SyncClient::AddTask(const SyncTasks::key_type& key,
const SyncTask& task,
const base::TimeDelta& delay) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
SyncTasks::iterator it = tasks_.find(key);
if (it != tasks_.end()) {
switch (it->second.state) {
case PENDING:
// The same task will run, do nothing.
break;
case RUNNING:
// Something has changed since the task started. Schedule rerun.
it->second.should_run_again = true;
break;
}
return;
}
DCHECK_EQ(PENDING, task.state);
tasks_[key] = task;
base::MessageLoopProxy::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&SyncClient::StartTask, weak_ptr_factory_.GetWeakPtr(), key),
delay);
}
void SyncClient::StartTask(const SyncTasks::key_type& key) {
SyncTasks::iterator it = tasks_.find(key);
if (it == tasks_.end())
return;
SyncTask* task = &it->second;
switch (task->state) {
case PENDING:
task->state = RUNNING;
task->task.Run();
break;
case RUNNING: // Do nothing.
break;
}
}
void SyncClient::OnGetLocalIdsOfBacklog(
const std::vector<std::string>* to_fetch,
const std::vector<std::string>* to_update) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Give priority to upload tasks over fetch tasks, so that dirty files are
// uploaded as soon as possible.
for (size_t i = 0; i < to_update->size(); ++i) {
const std::string& local_id = (*to_update)[i];
DVLOG(1) << "Queuing to update: " << local_id;
AddUpdateTask(ClientContext(BACKGROUND), local_id);
}
for (size_t i = 0; i < to_fetch->size(); ++i) {
const std::string& local_id = (*to_fetch)[i];
DVLOG(1) << "Queuing to fetch: " << local_id;
AddFetchTaskInternal(local_id, delay_);
}
}
void SyncClient::AddFetchTasks(const std::vector<std::string>* local_ids) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (size_t i = 0; i < local_ids->size(); ++i)
AddFetchTask((*local_ids)[i]);
}
bool SyncClient::OnTaskComplete(SyncType type, const std::string& local_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const SyncTasks::key_type key(type, local_id);
SyncTasks::iterator it = tasks_.find(key);
DCHECK(it != tasks_.end());
if (it->second.should_run_again) {
DVLOG(1) << "Running again: type = " << type << ", id = " << local_id;
it->second.should_run_again = false;
it->second.task.Run();
return false;
}
tasks_.erase(it);
return true;
}
void SyncClient::OnFetchFileComplete(const std::string& local_id,
FileError error,
const base::FilePath& local_path,
scoped_ptr<ResourceEntry> entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!OnTaskComplete(FETCH, local_id))
return;
if (error == FILE_ERROR_OK) {
DVLOG(1) << "Fetched " << local_id << ": " << local_path.value();
} else {
switch (error) {
case FILE_ERROR_ABORT:
// If user cancels download, unpin the file so that we do not sync the
// file again.
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&FileCache::Unpin, base::Unretained(cache_), local_id),
base::Bind(&util::EmptyFileOperationCallback));
break;
case FILE_ERROR_NO_CONNECTION:
// Add the task again so that we'll retry once the connection is back.
AddFetchTaskInternal(local_id, delay_);
break;
case FILE_ERROR_SERVICE_UNAVAILABLE:
// Add the task again so that we'll retry once the service is back.
AddFetchTaskInternal(local_id, long_delay_);
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_SERVICE_UNAVAILABLE,
local_id);
break;
default:
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_MISC,
local_id);
LOG(WARNING) << "Failed to fetch " << local_id
<< ": " << FileErrorToString(error);
}
}
}
void SyncClient::OnUpdateComplete(const std::string& local_id,
FileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!OnTaskComplete(UPDATE, local_id))
return;
if (error == FILE_ERROR_OK) {
DVLOG(1) << "Updated " << local_id;
} else {
switch (error) {
case FILE_ERROR_ABORT:
// Ignore it because this is caused by user's cancel operations.
break;
case FILE_ERROR_NO_CONNECTION:
// Add the task again so that we'll retry once the connection is back.
AddUpdateTaskInternal(ClientContext(BACKGROUND), local_id,
base::TimeDelta::FromSeconds(0));
break;
case FILE_ERROR_SERVICE_UNAVAILABLE:
// Add the task again so that we'll retry once the service is back.
AddUpdateTaskInternal(ClientContext(BACKGROUND), local_id, long_delay_);
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_SERVICE_UNAVAILABLE,
local_id);
break;
default:
operation_observer_->OnDriveSyncError(
file_system::DRIVE_SYNC_ERROR_MISC,
local_id);
LOG(WARNING) << "Failed to update " << local_id << ": "
<< FileErrorToString(error);
}
}
}
} // namespace internal
} // namespace drive
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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/performance_monitor/metric.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "chrome/browser/performance_monitor/constants.h"
namespace performance_monitor {
namespace {
// For certain metrics (for instance, bytes read), it is possible that there is
// no maximum value which we can safely assume.
const double kNoMaximum = -1.0;
// These constants are designed to keep metrics reasonable. However, due to the
// variety of system configurations which can run chrome, these values may not
// catch *all* erroneous values. For instance, on a one-CPU machine, any CPU
// usage > 100 is erroneous, but on a 16-CPU machine, it's perfectly normal.
// These are "best-guesses" in order to weed out obviously-false values. A
// metric is valid if it is greater than or equal to the minimum and less than
// the maximum, i.e. if it falls in the range [min, max).
const double kMinUndefined = 0.0;
const double kMaxUndefined = 0.0; // No undefined metric is valid.
const double kMinCpuUsage = 0.0;
const double kMaxCpuUsage = 100000.0; // 100% on a 1000-CPU machine.
const double kMinPrivateMemoryUsage = 0.0;
const double kMaxPrivateMemoryUsage = kBytesPerTerabyte;
const double kMinSharedMemoryUsage = 0.0;
const double kMaxSharedMemoryUsage = kBytesPerTerabyte;
const double kMinStartupTime = 0.0;
const double kMaxStartupTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinTestStartupTime = 0.0;
const double kMaxTestStartupTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinSessionRestoreTime = 0.0;
const double kMaxSessionRestoreTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinPageLoadTime = 0.0;
const double kMaxPageLoadTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinNetworkBytesRead = 0.0;
const double kMaxNetworkBytesRead = kNoMaximum;
struct MetricBound {
double min;
double max;
};
const MetricBound kMetricBounds[] = {
{ kMinUndefined, kMaxUndefined },
{ kMinCpuUsage, kMaxCpuUsage },
{ kMinPrivateMemoryUsage, kMaxPrivateMemoryUsage },
{ kMinSharedMemoryUsage, kMaxSharedMemoryUsage },
{ kMinStartupTime, kMaxStartupTime },
{ kMinTestStartupTime, kMaxTestStartupTime },
{ kMinSessionRestoreTime, kMaxSessionRestoreTime },
{ kMinPageLoadTime, kMaxPageLoadTime },
{ kMinNetworkBytesRead, kMaxNetworkBytesRead },
};
COMPILE_ASSERT(ARRAYSIZE_UNSAFE(kMetricBounds) == METRIC_NUMBER_OF_METRICS,
metric_bounds_size_doesnt_match_metric_count);
} // namespace
Metric::Metric() {
value = 0.0;
}
Metric::Metric(MetricType metric_type,
const base::Time& metric_time,
const double metric_value)
: type(metric_type), time(metric_time), value(metric_value) {
}
Metric::Metric(MetricType metric_type,
const std::string& metric_time,
const std::string& metric_value) : type(metric_type) {
int64 conversion = 0;
base::StringToInt64(metric_time, &conversion);
time = base::Time::FromInternalValue(conversion);
CHECK(base::StringToDouble(metric_value, &value));
}
Metric::~Metric() {
}
bool Metric::IsValid() const {
return type < METRIC_NUMBER_OF_METRICS &&
(value < kMetricBounds[type].max ||
kMetricBounds[type].max == kNoMaximum) &&
value >= kMetricBounds[type].min;
}
std::string Metric::ValueAsString() const {
return base::DoubleToString(value);
}
} // namespace performance_monitor
<commit_msg>[Coverity] Fix uninitialized member variable.<commit_after>// Copyright (c) 2012 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/performance_monitor/metric.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "chrome/browser/performance_monitor/constants.h"
namespace performance_monitor {
namespace {
// For certain metrics (for instance, bytes read), it is possible that there is
// no maximum value which we can safely assume.
const double kNoMaximum = -1.0;
// These constants are designed to keep metrics reasonable. However, due to the
// variety of system configurations which can run chrome, these values may not
// catch *all* erroneous values. For instance, on a one-CPU machine, any CPU
// usage > 100 is erroneous, but on a 16-CPU machine, it's perfectly normal.
// These are "best-guesses" in order to weed out obviously-false values. A
// metric is valid if it is greater than or equal to the minimum and less than
// the maximum, i.e. if it falls in the range [min, max).
const double kMinUndefined = 0.0;
const double kMaxUndefined = 0.0; // No undefined metric is valid.
const double kMinCpuUsage = 0.0;
const double kMaxCpuUsage = 100000.0; // 100% on a 1000-CPU machine.
const double kMinPrivateMemoryUsage = 0.0;
const double kMaxPrivateMemoryUsage = kBytesPerTerabyte;
const double kMinSharedMemoryUsage = 0.0;
const double kMaxSharedMemoryUsage = kBytesPerTerabyte;
const double kMinStartupTime = 0.0;
const double kMaxStartupTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinTestStartupTime = 0.0;
const double kMaxTestStartupTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinSessionRestoreTime = 0.0;
const double kMaxSessionRestoreTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinPageLoadTime = 0.0;
const double kMaxPageLoadTime = base::Time::kMicrosecondsPerMinute * 15.0;
const double kMinNetworkBytesRead = 0.0;
const double kMaxNetworkBytesRead = kNoMaximum;
struct MetricBound {
double min;
double max;
};
const MetricBound kMetricBounds[] = {
{ kMinUndefined, kMaxUndefined },
{ kMinCpuUsage, kMaxCpuUsage },
{ kMinPrivateMemoryUsage, kMaxPrivateMemoryUsage },
{ kMinSharedMemoryUsage, kMaxSharedMemoryUsage },
{ kMinStartupTime, kMaxStartupTime },
{ kMinTestStartupTime, kMaxTestStartupTime },
{ kMinSessionRestoreTime, kMaxSessionRestoreTime },
{ kMinPageLoadTime, kMaxPageLoadTime },
{ kMinNetworkBytesRead, kMaxNetworkBytesRead },
};
COMPILE_ASSERT(ARRAYSIZE_UNSAFE(kMetricBounds) == METRIC_NUMBER_OF_METRICS,
metric_bounds_size_doesnt_match_metric_count);
} // namespace
Metric::Metric() : type(METRIC_UNDEFINED), value(0.0) {
}
Metric::Metric(MetricType metric_type,
const base::Time& metric_time,
const double metric_value)
: type(metric_type), time(metric_time), value(metric_value) {
}
Metric::Metric(MetricType metric_type,
const std::string& metric_time,
const std::string& metric_value) : type(metric_type) {
int64 conversion = 0;
base::StringToInt64(metric_time, &conversion);
time = base::Time::FromInternalValue(conversion);
CHECK(base::StringToDouble(metric_value, &value));
}
Metric::~Metric() {
}
bool Metric::IsValid() const {
return type < METRIC_NUMBER_OF_METRICS &&
(value < kMetricBounds[type].max ||
kMetricBounds[type].max == kNoMaximum) &&
value >= kMetricBounds[type].min;
}
std::string Metric::ValueAsString() const {
return base::DoubleToString(value);
}
} // namespace performance_monitor
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
namespace {
// Provides a UI Test that lets us take the browser to a url, and
// wait for a cookie value to be set or a JavaScript expression to evaluate
// true before closing the page. It is undefined what happens if you specify
// both a cookie and a JS expression.
class UrlFetchTest : public UITest {
public:
UrlFetchTest() {
show_window_ = true;
dom_automation_enabled_ = true;
}
struct UrlFetchTestResult {
std::string cookie_value;
std::string javascript_variable;
};
void SetUp() {
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (cmd_line->HasSwitch("reference_build")) {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
}
UITest::SetUp();
}
void RunTest(const GURL& url,
const char* wait_cookie_name,
const char* wait_cookie_value,
const char* var_to_fetch,
const std::wstring& wait_js_expr,
const std::wstring& wait_js_frame_xpath,
int wait_js_timeout_ms,
UrlFetchTestResult* result) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
if (wait_cookie_name) {
if (wait_cookie_value) {
bool completed = WaitUntilCookieValue(
tab.get(), url, wait_cookie_name,
TestTimeouts::huge_test_timeout_ms(),
wait_cookie_value);
ASSERT_TRUE(completed);
} else {
result->cookie_value = WaitUntilCookieNonEmpty(
tab.get(), url, wait_cookie_name,
TestTimeouts::huge_test_timeout_ms());
ASSERT_TRUE(result->cookie_value.length());
}
} else if (!wait_js_expr.empty()) {
bool completed = WaitUntilJavaScriptCondition(tab.get(),
wait_js_frame_xpath,
wait_js_expr,
wait_js_timeout_ms);
ASSERT_TRUE(completed);
}
if (var_to_fetch) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s);", var_to_fetch);
std::wstring value;
bool success = tab->ExecuteAndExtractString(L"", ASCIIToWide(script),
&value);
ASSERT_TRUE(success);
result->javascript_variable = WideToUTF8(value);
}
}
};
bool WriteValueToFile(std::string value, const FilePath& path) {
int retval = file_util::WriteFile(path, value.c_str(), value.length());
return retval == static_cast<int>(value.length());
}
// To actually do anything useful, this test should have a url
// passed on the command line, eg.
//
// --url=http://foo.bar.com
//
// Additional arguments:
//
// --wait_cookie_name=<name>
// Waits for a cookie named <name> to be set before exiting successfully.
//
// --wait_cookie_value=<value>
// In conjunction with --wait_cookie_name, this waits for a specific value
// to be set. (Incompatible with --wait_cookie_output)
//
// --wait_cookie_output=<filepath>
// In conjunction with --wait_cookie_name, this saves the cookie value to
// a file at the given path. (Incompatible with --wait_cookie_value)
//
// --wait_js_expr=<jscript_expr>
// Waits for a javascript expression to evaluate true before exiting
// successfully.
//
// --wait_js_timeout=<timeout_ms>
// In conjunction with --wait_js_condition, this sets the timeout in ms
// that we are prepared to wait. If this timeout is exceeded, we will exit
// with failure. Note that a timeout greater than the gtest timeout will not
// be honored.
//
// --wait_js_frame_xpath=<xpath>
// In conjuction with --wait_js_condition, the JavaScript expression is
// executed in the context of the frame that matches the provided xpath.
// If this is not specified (or empty string), then the main frame is used.
//
// --jsvar=<name>
// At the end of the test, fetch the named javascript variable from the page.
//
// --jsvar_output=<filepath>
// Write the value of the variable named by '--jsvar' to a file at the given
// path.
//
// --reference_build
// Use the reference build of chrome for the test.
TEST_F(UrlFetchTest, UrlFetch) {
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch("url"))
return;
std::string cookie_name =
cmd_line->GetSwitchValueASCII("wait_cookie_name");
std::string cookie_value =
cmd_line->GetSwitchValueASCII("wait_cookie_value");
std::wstring js_expr =
UTF8ToWide(cmd_line->GetSwitchValueASCII("wait_js_expr"));
std::wstring js_frame_xpath =
UTF8ToWide(cmd_line->GetSwitchValueASCII("wait_js_frame_xpath"));
std::string js_timeout_ms_str =
cmd_line->GetSwitchValueASCII("wait_js_timeout");
std::string jsvar = cmd_line->GetSwitchValueASCII("jsvar");
int js_timeout_ms = -1; // no timeout, wait forever
if (!js_timeout_ms_str.empty())
base::StringToInt(js_timeout_ms_str, &js_timeout_ms);
UrlFetchTestResult result;
RunTest(GURL(cmd_line->GetSwitchValueASCII("url")),
cookie_name.length() > 0 ? cookie_name.c_str() : NULL,
cookie_value.length() > 0 ? cookie_value.c_str() : NULL,
jsvar.length() > 0 ? jsvar.c_str() : NULL,
js_expr,
js_frame_xpath,
js_timeout_ms,
&result);
// Write out the cookie if requested
FilePath cookie_output_path =
cmd_line->GetSwitchValuePath("wait_cookie_output");
if (cookie_output_path.value().size() > 0) {
ASSERT_TRUE(WriteValueToFile(result.cookie_value, cookie_output_path));
}
// Write out the JS Variable if requested
FilePath jsvar_output_path = cmd_line->GetSwitchValuePath("jsvar_output");
if (jsvar_output_path.value().size() > 0) {
ASSERT_TRUE(WriteValueToFile(result.javascript_variable,
jsvar_output_path));
}
}
} // namespace
<commit_msg>Convert to std::wstring as late as possible.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
namespace {
// Provides a UI Test that lets us take the browser to a url, and
// wait for a cookie value to be set or a JavaScript expression to evaluate
// true before closing the page. It is undefined what happens if you specify
// both a cookie and a JS expression.
class UrlFetchTest : public UITest {
public:
UrlFetchTest() {
show_window_ = true;
dom_automation_enabled_ = true;
}
struct UrlFetchTestResult {
std::string cookie_value;
std::string javascript_variable;
};
void SetUp() {
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (cmd_line->HasSwitch("reference_build")) {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
}
UITest::SetUp();
}
void RunTest(const GURL& url,
const char* wait_cookie_name,
const char* wait_cookie_value,
const char* var_to_fetch,
const std::string& wait_js_expr,
const std::string& wait_js_frame_xpath,
int wait_js_timeout_ms,
UrlFetchTestResult* result) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
if (wait_cookie_name) {
if (wait_cookie_value) {
bool completed = WaitUntilCookieValue(
tab.get(), url, wait_cookie_name,
TestTimeouts::huge_test_timeout_ms(),
wait_cookie_value);
ASSERT_TRUE(completed);
} else {
result->cookie_value = WaitUntilCookieNonEmpty(
tab.get(), url, wait_cookie_name,
TestTimeouts::huge_test_timeout_ms());
ASSERT_TRUE(result->cookie_value.length());
}
} else if (!wait_js_expr.empty()) {
bool completed = WaitUntilJavaScriptCondition(
tab.get(),
UTF8ToWide(wait_js_frame_xpath),
UTF8ToWide(wait_js_expr),
wait_js_timeout_ms);
ASSERT_TRUE(completed);
}
if (var_to_fetch) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s);", var_to_fetch);
std::wstring value;
bool success = tab->ExecuteAndExtractString(L"", ASCIIToWide(script),
&value);
ASSERT_TRUE(success);
result->javascript_variable = WideToUTF8(value);
}
}
};
bool WriteValueToFile(std::string value, const FilePath& path) {
int retval = file_util::WriteFile(path, value.c_str(), value.length());
return retval == static_cast<int>(value.length());
}
// To actually do anything useful, this test should have a url
// passed on the command line, eg.
//
// --url=http://foo.bar.com
//
// Additional arguments:
//
// --wait_cookie_name=<name>
// Waits for a cookie named <name> to be set before exiting successfully.
//
// --wait_cookie_value=<value>
// In conjunction with --wait_cookie_name, this waits for a specific value
// to be set. (Incompatible with --wait_cookie_output)
//
// --wait_cookie_output=<filepath>
// In conjunction with --wait_cookie_name, this saves the cookie value to
// a file at the given path. (Incompatible with --wait_cookie_value)
//
// --wait_js_expr=<jscript_expr>
// Waits for a javascript expression to evaluate true before exiting
// successfully.
//
// --wait_js_timeout=<timeout_ms>
// In conjunction with --wait_js_condition, this sets the timeout in ms
// that we are prepared to wait. If this timeout is exceeded, we will exit
// with failure. Note that a timeout greater than the gtest timeout will not
// be honored.
//
// --wait_js_frame_xpath=<xpath>
// In conjuction with --wait_js_condition, the JavaScript expression is
// executed in the context of the frame that matches the provided xpath.
// If this is not specified (or empty string), then the main frame is used.
//
// --jsvar=<name>
// At the end of the test, fetch the named javascript variable from the page.
//
// --jsvar_output=<filepath>
// Write the value of the variable named by '--jsvar' to a file at the given
// path.
//
// --reference_build
// Use the reference build of chrome for the test.
TEST_F(UrlFetchTest, UrlFetch) {
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch("url"))
return;
std::string cookie_name =
cmd_line->GetSwitchValueASCII("wait_cookie_name");
std::string cookie_value =
cmd_line->GetSwitchValueASCII("wait_cookie_value");
std::string js_expr =
cmd_line->GetSwitchValueASCII("wait_js_expr");
std::string js_frame_xpath =
cmd_line->GetSwitchValueASCII("wait_js_frame_xpath");
std::string js_timeout_ms_str =
cmd_line->GetSwitchValueASCII("wait_js_timeout");
std::string jsvar = cmd_line->GetSwitchValueASCII("jsvar");
int js_timeout_ms = -1; // no timeout, wait forever
if (!js_timeout_ms_str.empty())
base::StringToInt(js_timeout_ms_str, &js_timeout_ms);
UrlFetchTestResult result;
RunTest(GURL(cmd_line->GetSwitchValueASCII("url")),
cookie_name.length() > 0 ? cookie_name.c_str() : NULL,
cookie_value.length() > 0 ? cookie_value.c_str() : NULL,
jsvar.length() > 0 ? jsvar.c_str() : NULL,
js_expr,
js_frame_xpath,
js_timeout_ms,
&result);
// Write out the cookie if requested
FilePath cookie_output_path =
cmd_line->GetSwitchValuePath("wait_cookie_output");
if (cookie_output_path.value().size() > 0) {
ASSERT_TRUE(WriteValueToFile(result.cookie_value, cookie_output_path));
}
// Write out the JS Variable if requested
FilePath jsvar_output_path = cmd_line->GetSwitchValuePath("jsvar_output");
if (jsvar_output_path.value().size() > 0) {
ASSERT_TRUE(WriteValueToFile(result.javascript_variable,
jsvar_output_path));
}
}
} // namespace
<|endoftext|> |
<commit_before>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/net/config.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <QDir>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares"),
_settings("BitShares", BTS_BLOCKCHAIN_NAME)
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::handle_crash()
{
auto response = QMessageBox::question(nullptr,
tr("Crash Detected"),
tr("It appears that %1 crashed last time it was running. "
"If this is happening frequently, it could be caused by a "
"corrupted database. Would you like "
"to reset the database (this will take several minutes) or "
"to continue normally? Resetting the database will "
"NOT lose any of your information or funds.").arg(qApp->applicationName()),
tr("Reset Database"),
tr("Continue Normally"),
QString(), 1);
if (response == 0)
QDir((get_data_dir() + "/chain").c_str()).removeRecursively();
}
std::string ClientWrapper::get_data_dir()
{
auto data_dir = bts::client::get_data_dir(boost::program_options::variables_map()).to_native_ansi_path();
if (_settings.contains("data_dir"))
data_dir = _settings.value("data_dir").toString().toStdString();
int data_dir_index = qApp->arguments().indexOf("--data-dir");
if (data_dir_index != -1 && qApp->arguments().size() > data_dir_index+1)
data_dir = qApp->arguments()[data_dir_index+1].toStdString();
return data_dir;
}
void ClientWrapper::initialize(INotifier* notifier)
{
bool upnp = _settings.value( "network/p2p/use_upnp", true ).toBool();
#ifdef BTS_TEST_NETWORK
uint32_t default_port = BTS_NET_TEST_P2P_PORT + BTS_TEST_NETWORK_VERSION;
#else
uint32_t default_port = BTS_NET_DEFAULT_P2P_PORT;
#endif
uint32_t p2pport = _settings.value( "network/p2p/port", default_port ).toInt();
std::string default_wallet_name = _settings.value("client/default_wallet_name", "default").toString().toStdString();
_settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = get_data_dir();
wlog("Starting client with data-dir: ${ddir}", ("ddir", data_dir));
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name, notifier](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir, fc::optional<fc::path>(), [=](uint32_t blocks_processed) {
if( blocks_processed % 1000 == 0 )
main_thread->async( [&]{ Q_EMIT status_update(tr("Reindexing database; please wait... This may take several minutes.").arg(blocks_processed)); } );
} );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading...")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
const bts::client::config& loadedCfg = _client->configure( data_dir );
if(notifier != nullptr)
notifier->on_config_loaded(loadedCfg);
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->wallet_close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::set_data_dir(QString data_dir)
{
QSettings ("BitShares", BTS_BLOCKCHAIN_NAME).setValue("data_dir", data_dir);
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<commit_msg>Remove every 1000 blocks check from reindexing status update<commit_after>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/net/config.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <QDir>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares"),
_settings("BitShares", BTS_BLOCKCHAIN_NAME)
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::handle_crash()
{
auto response = QMessageBox::question(nullptr,
tr("Crash Detected"),
tr("It appears that %1 crashed last time it was running. "
"If this is happening frequently, it could be caused by a "
"corrupted database. Would you like "
"to reset the database (this will take several minutes) or "
"to continue normally? Resetting the database will "
"NOT lose any of your information or funds.").arg(qApp->applicationName()),
tr("Reset Database"),
tr("Continue Normally"),
QString(), 1);
if (response == 0)
QDir((get_data_dir() + "/chain").c_str()).removeRecursively();
}
std::string ClientWrapper::get_data_dir()
{
auto data_dir = bts::client::get_data_dir(boost::program_options::variables_map()).to_native_ansi_path();
if (_settings.contains("data_dir"))
data_dir = _settings.value("data_dir").toString().toStdString();
int data_dir_index = qApp->arguments().indexOf("--data-dir");
if (data_dir_index != -1 && qApp->arguments().size() > data_dir_index+1)
data_dir = qApp->arguments()[data_dir_index+1].toStdString();
return data_dir;
}
void ClientWrapper::initialize(INotifier* notifier)
{
bool upnp = _settings.value( "network/p2p/use_upnp", true ).toBool();
#ifdef BTS_TEST_NETWORK
uint32_t default_port = BTS_NET_TEST_P2P_PORT + BTS_TEST_NETWORK_VERSION;
#else
uint32_t default_port = BTS_NET_DEFAULT_P2P_PORT;
#endif
uint32_t p2pport = _settings.value( "network/p2p/port", default_port ).toInt();
std::string default_wallet_name = _settings.value("client/default_wallet_name", "default").toString().toStdString();
_settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = get_data_dir();
wlog("Starting client with data-dir: ${ddir}", ("ddir", data_dir));
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name, notifier](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir, fc::optional<fc::path>(), [=](uint32_t blocks_processed) {
main_thread->async( [&]{ Q_EMIT status_update(tr("Reindexing database; please wait... This may take several minutes.").arg(blocks_processed)); } );
} );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading...")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
const bts::client::config& loadedCfg = _client->configure( data_dir );
if(notifier != nullptr)
notifier->on_config_loaded(loadedCfg);
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->wallet_close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::set_data_dir(QString data_dir)
{
QSettings ("BitShares", BTS_BLOCKCHAIN_NAME).setValue("data_dir", data_dir);
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<|endoftext|> |
<commit_before>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
//project
#include "add-account-page.h"
#include "service-selection-page.h"
#include "service-model.h"
#include "service-helper.h"
#include "sort-service-model.h"
#include "provider-plugin-process.h"
#include "account-sync-handler.h"
#include "genericaccountsetupform.h"
//Accounts
#include <Accounts/Account>
#include <Accounts/Manager>
//Meegotouch
#include <MLocale>
#include <MLabel>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MImageWidget>
#include <MButton>
#include <MWidgetCreator>
//Qt
#include <QString>
#include <QSortFilterProxyModel>
#include <QRegExp>
#include <QDebug>
using namespace Accounts;
M_REGISTER_WIDGET_NO_CREATE(AccountsUI::AddAccountPage)
namespace AccountsUI {
class AddAccountPagePrivate
{
public:
AddAccountPagePrivate()
: context(0),
syncHandler(0)
{}
~AddAccountPagePrivate()
{
qDeleteAll(serviceContextList);
}
AbstractAccountSetupContext *context;
QList<AbstractServiceSetupContext*> serviceContextList;
AccountSyncHandler *syncHandler;
QList<AbstractSetupContext*> abstractContexts;
QString serviceType;
Accounts::ServiceList hiddenServiceList;
};
AddAccountPage::AddAccountPage(AbstractAccountSetupContext *context,
QGraphicsItem *parent)
: MApplicationPage(parent)
, d_ptr(new AddAccountPagePrivate())
{
Q_D(AddAccountPage);
Q_ASSERT(context);
setStyleName("AccountsUiPage");
setEscapeMode(MApplicationPageModel::EscapeAuto);
d->context = context;
d->serviceType = context->serviceType();
}
AddAccountPage::~AddAccountPage()
{
Q_D(AddAccountPage);
delete d;
}
void AddAccountPage::createContent()
{
Q_D(AddAccountPage);
Q_ASSERT(centralWidget());
//% "Add new account"
setTitle(qtTrId("qtn_acc_add_new_account_title"));
// layout
MLayout *layout = new MLayout(centralWidget());
MLinearLayoutPolicy *layoutPolicy =
new MLinearLayoutPolicy( layout, Qt::Vertical );
// plugin widget has the provider info and credentials widget
QGraphicsLayoutItem *pluginWidget = d->context->widget();
layoutPolicy->addItem(pluginWidget);
// TODO : this part is just for testing purposes, to jump to service selection page, without going through authentication
if (!qgetenv("ACCOUNTSUI_SKIP_VALIDATION").isEmpty()) {
MButton *nextButton = new MButton("Skip Validation");
connect(nextButton, SIGNAL(clicked()), this, SLOT(navigateToServiceSelectionPage()));
layoutPolicy->addItem(nextButton);
}
// login Ok, go to next page
connect(d->context, SIGNAL(validated()), SLOT(navigateToServiceSelectionPage()));
connect(d->context, SIGNAL(validated()), SLOT(showMenuBar()));
//process indicator
connect(d->context, SIGNAL(validating()), SLOT(hideMenuBar()));
connect(d->context, SIGNAL(error(AccountsUI::ErrorCode, const QString &)),
this, SLOT(onError(AccountsUI::ErrorCode, const QString &)));
//cancelling
connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
d->context, SLOT(stopAuthSession()));
connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
d->context, SLOT(showMenuBar()));
}
void AddAccountPage::setHiddenServices(const Accounts::ServiceList &hiddenServices)
{
Q_D(AddAccountPage);
d->hiddenServiceList = hiddenServices;
}
void AddAccountPage::navigateToServiceSelectionPage()
{
Q_D(AddAccountPage);
disconnect(d->context, SIGNAL(validated()), this, SLOT(navigateToServiceSelectionPage()));
ServiceModel *serviceModel = new ServiceModel(d->context->account(), this);
SortServiceModel *sortModel = new SortServiceModel(this);
sortModel->setSourceModel(serviceModel);
sortModel->setHiddenServices(d->hiddenServiceList);
sortModel->sort(ServiceModel::ServiceNameColumn);
d->serviceContextList = ServiceModel::createServiceContexts(sortModel, d->context, this);
if (d->serviceContextList.count() == 0 ||
(d->serviceContextList.count() == 1 &&
!d->serviceContextList.at(0)->hasMandatorySettings())) {
d->syncHandler = new AccountSyncHandler(this);
connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
this, SLOT(onSyncStateChanged(const SyncState&)));
d->context->account()->selectService(NULL);
d->context->account()->setEnabled(true);
d->abstractContexts.append(d->context);
if (d->serviceContextList.count() == 1)
d->abstractContexts.append(d->serviceContextList.at(0));
setProgressIndicatorVisible(true);
qDebug() << Q_FUNC_INFO;
d->syncHandler->validate(d->abstractContexts);
return;
}
openServiceSelectionPage(d->context, d->serviceContextList);
}
void AddAccountPage::openServiceSelectionPage(AccountsUI::AbstractAccountSetupContext *context,
QList<AccountsUI::AbstractServiceSetupContext *> &serviceContextList)
{
ServiceSelectionPage *serviceSelectionPage =
new ServiceSelectionPage(context, serviceContextList);
connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
this,SLOT(appear()));
connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
this, SLOT(clearServiceContextList()));
connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
serviceSelectionPage,SLOT(deleteLater()));
serviceSelectionPage->appear();
}
void AddAccountPage::onSyncStateChanged(const SyncState &state)
{
qDebug() << Q_FUNC_INFO;
Q_D(AddAccountPage);
switch (state) {
case NotValidated:
qDebug() << Q_FUNC_INFO << __LINE__;
showMenuBar();
break;
case NotStored:
qDebug() << Q_FUNC_INFO << __LINE__;
showMenuBar();
break;
case Validated:
d->syncHandler->store(d->abstractContexts);
break;
case Stored:
connect(d->context->account(), SIGNAL(synced()),
ProviderPluginProcess::instance(), SLOT(quit()));
d->context->account()->sync();
showMenuBar();
break;
default:
return;
}
}
void AddAccountPage::clearServiceContextList()
{
Q_D(AddAccountPage);
d->serviceContextList.clear();
}
void AddAccountPage::hideMenuBar()
{
setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Hide);
}
void AddAccountPage::showMenuBar()
{
setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Show);
}
void AddAccountPage::onError(AccountsUI::ErrorCode, const QString &)
{
showMenuBar();
}
} //namespace
<commit_msg>Fixing 225464 - Simple accounts are configured with disabled state<commit_after>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
//project
#include "add-account-page.h"
#include "service-selection-page.h"
#include "service-model.h"
#include "service-helper.h"
#include "sort-service-model.h"
#include "provider-plugin-process.h"
#include "account-sync-handler.h"
#include "genericaccountsetupform.h"
//Accounts
#include <Accounts/Account>
#include <Accounts/Manager>
//Meegotouch
#include <MLocale>
#include <MLabel>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MImageWidget>
#include <MButton>
#include <MWidgetCreator>
//Qt
#include <QString>
#include <QSortFilterProxyModel>
#include <QRegExp>
#include <QDebug>
using namespace Accounts;
M_REGISTER_WIDGET_NO_CREATE(AccountsUI::AddAccountPage)
namespace AccountsUI {
class AddAccountPagePrivate
{
public:
AddAccountPagePrivate()
: context(0),
syncHandler(0)
{}
~AddAccountPagePrivate()
{
qDeleteAll(serviceContextList);
}
AbstractAccountSetupContext *context;
QList<AbstractServiceSetupContext*> serviceContextList;
AccountSyncHandler *syncHandler;
QList<AbstractSetupContext*> abstractContexts;
QString serviceType;
Accounts::ServiceList hiddenServiceList;
};
AddAccountPage::AddAccountPage(AbstractAccountSetupContext *context,
QGraphicsItem *parent)
: MApplicationPage(parent)
, d_ptr(new AddAccountPagePrivate())
{
Q_D(AddAccountPage);
Q_ASSERT(context);
setStyleName("AccountsUiPage");
setEscapeMode(MApplicationPageModel::EscapeAuto);
d->context = context;
d->serviceType = context->serviceType();
}
AddAccountPage::~AddAccountPage()
{
Q_D(AddAccountPage);
delete d;
}
void AddAccountPage::createContent()
{
Q_D(AddAccountPage);
Q_ASSERT(centralWidget());
//% "Add new account"
setTitle(qtTrId("qtn_acc_add_new_account_title"));
// layout
MLayout *layout = new MLayout(centralWidget());
MLinearLayoutPolicy *layoutPolicy =
new MLinearLayoutPolicy( layout, Qt::Vertical );
// plugin widget has the provider info and credentials widget
QGraphicsLayoutItem *pluginWidget = d->context->widget();
layoutPolicy->addItem(pluginWidget);
// TODO : this part is just for testing purposes, to jump to service selection page, without going through authentication
if (!qgetenv("ACCOUNTSUI_SKIP_VALIDATION").isEmpty()) {
MButton *nextButton = new MButton("Skip Validation");
connect(nextButton, SIGNAL(clicked()), this, SLOT(navigateToServiceSelectionPage()));
layoutPolicy->addItem(nextButton);
}
// login Ok, go to next page
connect(d->context, SIGNAL(validated()), SLOT(navigateToServiceSelectionPage()));
connect(d->context, SIGNAL(validated()), SLOT(showMenuBar()));
//process indicator
connect(d->context, SIGNAL(validating()), SLOT(hideMenuBar()));
connect(d->context, SIGNAL(error(AccountsUI::ErrorCode, const QString &)),
this, SLOT(onError(AccountsUI::ErrorCode, const QString &)));
//cancelling
connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
d->context, SLOT(stopAuthSession()));
connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
d->context, SLOT(showMenuBar()));
}
void AddAccountPage::setHiddenServices(const Accounts::ServiceList &hiddenServices)
{
Q_D(AddAccountPage);
d->hiddenServiceList = hiddenServices;
}
void AddAccountPage::navigateToServiceSelectionPage()
{
Q_D(AddAccountPage);
disconnect(d->context, SIGNAL(validated()), this, SLOT(navigateToServiceSelectionPage()));
ServiceModel *serviceModel = new ServiceModel(d->context->account(), this);
SortServiceModel *sortModel = new SortServiceModel(this);
sortModel->setSourceModel(serviceModel);
sortModel->setHiddenServices(d->hiddenServiceList);
sortModel->sort(ServiceModel::ServiceNameColumn);
d->serviceContextList = ServiceModel::createServiceContexts(sortModel, d->context, this);
if (d->serviceContextList.count() == 0 ||
(d->serviceContextList.count() == 1 &&
!d->serviceContextList.at(0)->hasMandatorySettings())) {
d->syncHandler = new AccountSyncHandler(this);
connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
this, SLOT(onSyncStateChanged(const SyncState&)));
d->context->account()->selectService(NULL);
d->context->account()->setEnabled(true);
d->abstractContexts.append(d->context);
if (d->serviceContextList.count() == 1) {
d->context->account()->selectService(d->serviceContextList.at(0)->service());
d->context->account()->setEnabled(true);
d->abstractContexts.append(d->serviceContextList.at(0));
}
setProgressIndicatorVisible(true);
qDebug() << Q_FUNC_INFO;
d->syncHandler->validate(d->abstractContexts);
return;
}
openServiceSelectionPage(d->context, d->serviceContextList);
}
void AddAccountPage::openServiceSelectionPage(AccountsUI::AbstractAccountSetupContext *context,
QList<AccountsUI::AbstractServiceSetupContext *> &serviceContextList)
{
ServiceSelectionPage *serviceSelectionPage =
new ServiceSelectionPage(context, serviceContextList);
connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
this,SLOT(appear()));
connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
this, SLOT(clearServiceContextList()));
connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
serviceSelectionPage,SLOT(deleteLater()));
serviceSelectionPage->appear();
}
void AddAccountPage::onSyncStateChanged(const SyncState &state)
{
qDebug() << Q_FUNC_INFO;
Q_D(AddAccountPage);
switch (state) {
case NotValidated:
qDebug() << Q_FUNC_INFO << __LINE__;
showMenuBar();
break;
case NotStored:
qDebug() << Q_FUNC_INFO << __LINE__;
showMenuBar();
break;
case Validated:
d->syncHandler->store(d->abstractContexts);
break;
case Stored:
connect(d->context->account(), SIGNAL(synced()),
ProviderPluginProcess::instance(), SLOT(quit()));
d->context->account()->sync();
showMenuBar();
break;
default:
return;
}
}
void AddAccountPage::clearServiceContextList()
{
Q_D(AddAccountPage);
d->serviceContextList.clear();
}
void AddAccountPage::hideMenuBar()
{
setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Hide);
}
void AddAccountPage::showMenuBar()
{
setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Show);
}
void AddAccountPage::onError(AccountsUI::ErrorCode, const QString &)
{
showMenuBar();
}
} //namespace
<|endoftext|> |
<commit_before>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares")
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::initialize()
{
QSettings settings("BitShares", BTS_BLOCKCHAIN_NAME);
bool upnp = settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t p2pport = settings.value( "network/p2p/port", BTS_NETWORK_DEFAULT_P2P_PORT ).toInt();
std::string default_wallet_name = settings.value("client/default_wallet_name", "default").toString().toStdString();
settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
Q_UNUSED(p2pport);
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = fc::app_path() / BTS_BLOCKCHAIN_NAME;
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1 client").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading interface")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
_client->configure( data_dir );
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
main_thread->async( [&]{ Q_EMIT status_update(tr("Forwarding port")); });
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->get_wallet()->close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<commit_msg>Fix weird build error...<commit_after>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares")
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::initialize()
{
QSettings settings("BitShares", BTS_BLOCKCHAIN_NAME);
bool upnp = settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t p2pport = settings.value( "network/p2p/port", BTS_NETWORK_DEFAULT_P2P_PORT ).toInt();
std::string default_wallet_name = settings.value("client/default_wallet_name", "default").toString().toStdString();
settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
Q_UNUSED(p2pport);
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = fc::app_path() / BTS_BLOCKCHAIN_NAME;
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1 client").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading interface")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
_client->configure( data_dir );
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
main_thread->async( [&]{ Q_EMIT status_update(tr("Forwarding port")); });
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->get_wallet()->close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<|endoftext|> |
<commit_before>#include "viewer.h"
#include <cstdlib>
#include <ctime>
#include <GL/gl.h>
#include <SDL.h>
#include "base/Log.h"
#include "base/Guard.h"
namespace viewer {
int Viewer::run() {
typedef base::PtrGuard<SDL_Surface, SDL_FreeSurface> SurfaceGuard;
typedef base::RunGuard<SDL_Quit> SDLQuitGuard;
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) != 0) {
VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END;
return 1;
}
SDLQuitGuard sdlQuitGuard;
SDL_WM_SetCaption("viewer", "viewer");
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SurfaceGuard screen(SDL_SetVideoMode(1024, 600, 24, SDL_OPENGL));
if (!screen) {
VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END;
return 1;
}
#if 0
SDL_WM_ToggleFullScreen(screen.get());
#endif
try {
m_driver = new video::Driver(screen->w, screen->h);
} catch (const video::TextException& e) {
VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END;
return 1;
}
m_width = screen->w;
m_height = screen->h;
// Seed random number generator
srand(time(NULL));
Uint32 last_time;
Uint32 fps = 120;
// Initialize time difference counter
last_time = SDL_GetTicks();
// Main loop
for (;;) {
Uint32 this_time = SDL_GetTicks();
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
goto end;
break;
default:
break;
}
}
try {
// TODO Fix wraparound for time difference
tick(this_time - last_time);
} catch (const std::exception& e) {
VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END;
return 1;
}
m_driver->beginScene();
draw();
m_driver->endScene();
last_time = this_time;
Sint32 sleep_time = (1000 / fps) - (SDL_GetTicks() - last_time);
if (sleep_time > 0) {
SDL_Delay(sleep_time);
}
}
end:
return 0;
}
void Viewer::draw()
{
std::lock_guard<std::mutex> lockGuard(mutex());
const float minNote = 50;
const float maxNote = 300;
const double noteWidth = 2;
// const double noteHeight = 20;
double position = 0;
for (auto note : cb()) {
if (note != 0) { // TODO float compare
double ypos = (note - minNote) * (m_height / (maxNote - minNote));
m_driver->draw2DRectangle(position, ypos - 1, position + noteWidth,
ypos + 1, video::Color(255, 255, 255, 255));
}
position += noteWidth;
}
// G3
{
double ypos = (196 - minNote) * (m_height / (maxNote - minNote));
m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(255, 0, 0, 255));
}
// A3
{
double ypos = (220 - minNote) * (m_height / (maxNote - minNote));
m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(100, 0, 0, 255));
}
}
}
<commit_msg>change some pitch settings and lines<commit_after>#include "viewer.h"
#include <cstdlib>
#include <ctime>
#include <GL/gl.h>
#include <SDL.h>
#include "base/Log.h"
#include "base/Guard.h"
namespace viewer {
namespace {
const float MINNOTE = 100;
const float MAXNOTE = 300;
}
int Viewer::run() {
typedef base::PtrGuard<SDL_Surface, SDL_FreeSurface> SurfaceGuard;
typedef base::RunGuard<SDL_Quit> SDLQuitGuard;
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) != 0) {
VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END;
return 1;
}
SDLQuitGuard sdlQuitGuard;
SDL_WM_SetCaption("viewer", "viewer");
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SurfaceGuard screen(SDL_SetVideoMode(1024, 600, 24, SDL_OPENGL));
if (!screen) {
VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END;
return 1;
}
#if 0
SDL_WM_ToggleFullScreen(screen.get());
#endif
try {
m_driver = new video::Driver(screen->w, screen->h);
} catch (const video::TextException& e) {
VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END;
return 1;
}
m_width = screen->w;
m_height = screen->h;
// Seed random number generator
srand(time(NULL));
Uint32 last_time;
Uint32 fps = 120;
// Initialize time difference counter
last_time = SDL_GetTicks();
// Main loop
for (;;) {
Uint32 this_time = SDL_GetTicks();
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
goto end;
break;
case SDL_MOUSEBUTTONDOWN: {
double ypos = m_height - event.button.y;
double note = ypos / (m_height / (MAXNOTE - MINNOTE)) + MINNOTE;
std::cerr << "note = " << note << std::endl;
} break;
default:
break;
}
}
try {
// TODO Fix wraparound for time difference
tick(this_time - last_time);
} catch (const std::exception& e) {
VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END;
return 1;
}
m_driver->beginScene();
draw();
m_driver->endScene();
last_time = this_time;
Sint32 sleep_time = (1000 / fps) - (SDL_GetTicks() - last_time);
if (sleep_time > 0) {
SDL_Delay(sleep_time);
}
}
end:
return 0;
}
void Viewer::draw()
{
std::lock_guard<std::mutex> lockGuard(mutex());
const double noteWidth = 2;
// const double noteHeight = 20;
double position = 0;
for (auto note : cb()) {
if (note != 0) { // TODO float compare
double ypos = (note - MINNOTE) * (m_height / (MAXNOTE - MINNOTE));
m_driver->draw2DRectangle(position, ypos - 1, position + noteWidth,
ypos + 1, video::Color(255, 255, 255, 255));
}
position += noteWidth;
}
// G3
{
double ypos = (196 - MINNOTE) * (m_height / (MAXNOTE - MINNOTE));
m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(255, 0, 0, 255));
}
// A3 - reach
{
double ypos = (220 - MINNOTE) * (m_height / (MAXNOTE - MINNOTE));
m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(100, 0, 0, 255));
}
// C3 - don't go here
{
double ypos = (131 - MINNOTE) * (m_height / (MAXNOTE - MINNOTE));
m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(100, 0, 0, 255));
}
}
}
<|endoftext|> |
<commit_before>/* -*- C++ -*-
This file is part of ThreadWeaver.
$ Author: Mirko Boehm $
$ Copyright: (C) 2004-2013 Mirko Boehm $
$ Contact: mirko@kde.org
http://www.kde.org
http://creative-destruction.me $
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "managedjobpointer.h"
#include "debuggingaids.h"
#include "queueapi.h"
#include "collection_p.h"
#include "collection.h"
namespace ThreadWeaver {
namespace Private {
Collection_Private::Collection_Private()
: api(0)
, jobCounter(0)
, selfIsExecuting(false)
{
}
Collection_Private::~Collection_Private()
{
}
void Collection_Private::finalCleanup(Collection *collection)
{
Q_ASSERT(!self.isNull());
Q_ASSERT(!mutex.tryLock());
freeQueuePolicyResources(self);
if (collection->status() < Job::Status_Success) {
collection->setStatus(Job::Status_Success);
}
api = 0;
}
void Collection_Private::enqueueElements()
{
Q_ASSERT(!mutex.tryLock());
prepareToEnqueueElements();
jobCounter.fetchAndStoreOrdered(elements.count() + 1); //including self
api->enqueue(elements);
}
void Collection_Private::elementStarted(Collection*, JobPointer job, Thread*)
{
QMutexLocker l(&mutex); Q_UNUSED(l);
Q_UNUSED(job) // except in Q_ASSERT
Q_ASSERT(!self.isNull());
if (jobsStarted.fetchAndAddOrdered(1) == 0) {
//emit started() signal on beginning of first job execution
selfExecuteWrapper.callBegin();
}
}
namespace {
struct MutexUnlocker {
QMutexLocker* locker;
MutexUnlocker(QMutexLocker* l) : locker(l) { locker->unlock(); }
~MutexUnlocker() { locker->relock(); }
};
}
void Collection_Private::elementFinished(Collection *collection, JobPointer job, Thread *thread)
{
QMutexLocker l(&mutex); Q_UNUSED(l);
Q_ASSERT(!self.isNull());
Q_UNUSED(job) // except in Q_ASSERT
if (selfIsExecuting) {
// the element that is finished is the collection itself
// the collection is always executed first
// queue the collection elements:
enqueueElements();
selfIsExecuting = false;
}
const int started = jobsStarted.loadAcquire();
Q_ASSERT(started >= 0); Q_UNUSED(started);
processCompletedElement(collection, job, thread);
const int remainingJobs = jobCounter.fetchAndAddOrdered(-1) - 1;
TWDEBUG(4, "Collection_Private::elementFinished: %i\n", remainingJobs);
if (remainingJobs <= -1) {
//its no use to count, the elements have been dequeued, now the threads call back that have been processing jobs in the meantime
} else {
Q_ASSERT(remainingJobs >= 0);
if (remainingJobs == 0) {
// all elements can only be done if self has been executed:
// there is a small chance that (this) has been dequeued in the
// meantime, in this case, there is nothing left to clean up
finalCleanup(collection);
{
MutexUnlocker u(&l); Q_UNUSED(u);
selfExecuteWrapper.callEnd();
}
self.clear();
}
}
}
void Collection_Private::prepareToEnqueueElements()
{
//empty in Collection
}
void Collection_Private::processCompletedElement(Collection*, JobPointer, Thread*)
{
//empty in Collection
}
void Collection_Private::stop_locked(Collection *collection)
{
Q_ASSERT(!mutex.tryLock());
if (api != 0) {
TWDEBUG(4, "Collection::stop: dequeueing %p.\n", collection);
if (!api->dequeue(ManagedJobPointer<Collection>(collection))) {
dequeueElements(collection, false);
}
}
}
void Collection_Private::dequeueElements(Collection* collection, bool queueApiIsLocked)
{
// dequeue everything:
Q_ASSERT(!mutex.tryLock());
if (api == 0) {
return; //not queued
}
for (int index = 0; index < elements.size(); ++index) {
bool result;
if (queueApiIsLocked) {
result = api->dequeue_p(elements.at(index));
} else {
result = api->dequeue(elements.at(index));
}
if (result) {
jobCounter.fetchAndAddOrdered(-1);
}
TWDEBUG(0, "Collection::Private::dequeueElements: dequeueing %p (%s, %i jobs left).\n",
(void *)elements.at(index).data(),
result ? "found" : "not found",
jobCounter.loadAcquire());
// if (jobCounter.loadAcquire() == 1) {
// // last job
// TWDEBUG(0, "Break here");
// }
elementDequeued(elements.at(index));
}
if (jobCounter.loadAcquire() == 1) {
finalCleanup(collection);
}
}
void CollectionSelfExecuteWrapper::begin(const JobPointer &job, Thread *thread)
{
job_ = job;
thread_ = thread;
}
void CollectionSelfExecuteWrapper::end(const JobPointer &job, Thread *thread)
{
Q_ASSERT(job_ == job && thread_ == thread);
Q_UNUSED(job); Q_UNUSED(thread); //except in assert
}
void CollectionSelfExecuteWrapper::callBegin()
{
ExecuteWrapper::begin(job_, thread_);
}
void CollectionSelfExecuteWrapper::callEnd()
{
ExecuteWrapper::end(job_, thread_);
job_.clear();
}
}
}
<commit_msg>Adjust debug levels.<commit_after>/* -*- C++ -*-
This file is part of ThreadWeaver.
$ Author: Mirko Boehm $
$ Copyright: (C) 2004-2013 Mirko Boehm $
$ Contact: mirko@kde.org
http://www.kde.org
http://creative-destruction.me $
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "managedjobpointer.h"
#include "debuggingaids.h"
#include "queueapi.h"
#include "collection_p.h"
#include "collection.h"
namespace ThreadWeaver {
namespace Private {
Collection_Private::Collection_Private()
: api(0)
, jobCounter(0)
, selfIsExecuting(false)
{
}
Collection_Private::~Collection_Private()
{
}
void Collection_Private::finalCleanup(Collection *collection)
{
Q_ASSERT(!self.isNull());
Q_ASSERT(!mutex.tryLock());
freeQueuePolicyResources(self);
if (collection->status() < Job::Status_Success) {
collection->setStatus(Job::Status_Success);
}
api = 0;
}
void Collection_Private::enqueueElements()
{
Q_ASSERT(!mutex.tryLock());
prepareToEnqueueElements();
jobCounter.fetchAndStoreOrdered(elements.count() + 1); //including self
api->enqueue(elements);
}
void Collection_Private::elementStarted(Collection*, JobPointer job, Thread*)
{
QMutexLocker l(&mutex); Q_UNUSED(l);
Q_UNUSED(job) // except in Q_ASSERT
Q_ASSERT(!self.isNull());
if (jobsStarted.fetchAndAddOrdered(1) == 0) {
//emit started() signal on beginning of first job execution
selfExecuteWrapper.callBegin();
}
}
namespace {
struct MutexUnlocker {
QMutexLocker* locker;
MutexUnlocker(QMutexLocker* l) : locker(l) { locker->unlock(); }
~MutexUnlocker() { locker->relock(); }
};
}
void Collection_Private::elementFinished(Collection *collection, JobPointer job, Thread *thread)
{
QMutexLocker l(&mutex); Q_UNUSED(l);
Q_ASSERT(!self.isNull());
Q_UNUSED(job) // except in Q_ASSERT
if (selfIsExecuting) {
// the element that is finished is the collection itself
// the collection is always executed first
// queue the collection elements:
enqueueElements();
selfIsExecuting = false;
}
const int started = jobsStarted.loadAcquire();
Q_ASSERT(started >= 0); Q_UNUSED(started);
processCompletedElement(collection, job, thread);
const int remainingJobs = jobCounter.fetchAndAddOrdered(-1) - 1;
TWDEBUG(4, "Collection_Private::elementFinished: %i\n", remainingJobs);
if (remainingJobs <= -1) {
//its no use to count, the elements have been dequeued, now the threads call back that have been processing jobs in the meantime
} else {
Q_ASSERT(remainingJobs >= 0);
if (remainingJobs == 0) {
// all elements can only be done if self has been executed:
// there is a small chance that (this) has been dequeued in the
// meantime, in this case, there is nothing left to clean up
finalCleanup(collection);
{
MutexUnlocker u(&l); Q_UNUSED(u);
selfExecuteWrapper.callEnd();
}
self.clear();
}
}
}
void Collection_Private::prepareToEnqueueElements()
{
//empty in Collection
}
void Collection_Private::processCompletedElement(Collection*, JobPointer, Thread*)
{
//empty in Collection
}
void Collection_Private::stop_locked(Collection *collection)
{
Q_ASSERT(!mutex.tryLock());
if (api != 0) {
TWDEBUG(4, "Collection::stop: dequeueing %p.\n", collection);
if (!api->dequeue(ManagedJobPointer<Collection>(collection))) {
dequeueElements(collection, false);
}
}
}
void Collection_Private::dequeueElements(Collection* collection, bool queueApiIsLocked)
{
// dequeue everything:
Q_ASSERT(!mutex.tryLock());
if (api == 0) {
return; //not queued
}
for (int index = 0; index < elements.size(); ++index) {
bool result;
if (queueApiIsLocked) {
result = api->dequeue_p(elements.at(index));
} else {
result = api->dequeue(elements.at(index));
}
if (result) {
jobCounter.fetchAndAddOrdered(-1);
}
TWDEBUG(3, "Collection::Private::dequeueElements: dequeueing %p (%s, %i jobs left).\n",
(void *)elements.at(index).data(),
result ? "found" : "not found",
jobCounter.loadAcquire());
elementDequeued(elements.at(index));
}
if (jobCounter.loadAcquire() == 1) {
finalCleanup(collection);
}
}
void CollectionSelfExecuteWrapper::begin(const JobPointer &job, Thread *thread)
{
job_ = job;
thread_ = thread;
}
void CollectionSelfExecuteWrapper::end(const JobPointer &job, Thread *thread)
{
Q_ASSERT(job_ == job && thread_ == thread);
Q_UNUSED(job); Q_UNUSED(thread); //except in assert
}
void CollectionSelfExecuteWrapper::callBegin()
{
ExecuteWrapper::begin(job_, thread_);
}
void CollectionSelfExecuteWrapper::callEnd()
{
ExecuteWrapper::end(job_, thread_);
job_.clear();
}
}
}
<|endoftext|> |
<commit_before>#ifndef ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/topology/Conversions.hh>
#include <aleph/topology/Intersections.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <initializer_list>
#include <map>
#include <ostream>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace aleph
{
/**
Partitions a simplicial complex according to its $\phi$-persistence
values. This follows the persistent intersection homology algorithm
in:
Persistent Intersection Homology\n
Paul Bendich and John Harer\n
The function uses a simplicial complex \f$K\f$ and a function \f$\phi\f$
that determines whether a simplex is proper or not. The function is
going to create a new simplicial complex. This complex contains all
proper simplices (in their original order) followed by all improper
ones.
*/
template <class Simplex, class Function> std::pair<topology::SimplicialComplex<Simplex>, std::size_t> partition( const topology::SimplicialComplex<Simplex>& K, Function phi )
{
topology::SimplicialComplex<Simplex> L;
for( auto&& simplex : K )
{
if( phi(simplex) )
L.push_back( simplex );
}
auto s = L.size();
for( auto&& simplex : K )
{
if( !phi(simplex) )
L.push_back( simplex );
}
return std::make_pair( L, s );
}
/**
@class Perversity
@brief Perversity model in the sense of persistent intersection homology
Models a perversity in the sense of persistent intersection homology,
following the definitions of Bendich. The class ensures that all
values satisfy
\f
-1 \leq p_k \leq k-1
\f
*/
class Perversity
{
public:
/**
Creates a new perversity from a range of values. The values must be
at least implicitly convertible to integers.
*/
template <class InputIterator> Perversity( InputIterator begin, InputIterator end )
: _values( begin, end )
{
for( std::size_t k = 0; k < _values.size(); k++ )
{
if( _values[k] < -1 )
_values[k] = -1;
// There is an index shift going on here: since $k$ runs from $0$
// to $d-1$, there is no need to shift the upper bound.
else if( _values[k] > static_cast<int>( k ) )
_values[k] = static_cast<int>( k );
}
}
/** Creates a new perversity from an initializer list of values */
Perversity( std::initializer_list<int> values )
: Perversity( values.begin(), values.end() )
{
}
/**
Queries the perversity value in a given dimension $d$. Invalid
dimension values only cause the function to return a zero.
*/
int operator()( std::size_t d ) const noexcept
{
if( d < _values.size() + 1 )
return _values[ static_cast<std::size_t>( d-1 ) ];
else
return 0;
}
using const_iterator = typename std::vector<int>::const_iterator;
const_iterator begin() const noexcept { return _values.begin(); }
const_iterator end() const noexcept { return _values.end(); }
private:
std::vector<int> _values;
};
/**
@class PerversityGM
@brief Perversity model in the sense of intersection homology
Models a perversity in the sense of intersection homology, following
Goresky and MacPherson. The class ensures that all values satisfy
\f
p_{k+1} = p_k \mathrm{ or } p_{k+1} = p_k + 1
\f
and \f$p_2 = 0\f$.
*/
class PerversityGM
{
public:
/**
Creates a new perversity from a range of values. The values must be
at least implicitly convertible to integers.
*/
template <class InputIterator> PerversityGM( InputIterator begin, InputIterator end )
: _values( begin, end )
{
for( std::size_t k = 1; k < _values.size(); k++ )
{
if( _values[k] != _values[k-1] && _values[k] != _values[k-1] + 1 )
_values[k] = _values[k-1] + 1;
}
}
/** Creates a new perversity from an initializer list of values */
PerversityGM( std::initializer_list<int> values )
: PerversityGM( values.begin(), values.end() )
{
}
/**
Queries the perversity value in a given dimension \p d. Invalid
dimension values only cause the function to return a zero.
*/
unsigned operator()( std::size_t d ) const noexcept
{
if( d < _values.size() + 2 )
return _values[ static_cast<std::size_t>( d-2 ) ];
else
return 0;
}
using const_iterator = typename std::vector<unsigned>::const_iterator;
const_iterator begin() const noexcept { return _values.begin(); }
const_iterator end() const noexcept { return _values.end(); }
private:
std::vector<unsigned> _values;
};
// Provide a simple form of tag dispatching in order to detect whether
// a perversity uses the 'original' intersection homology framework as
// described by Goresky and MacPherson.
template <typename> struct is_goresky_macpherson_perversity_base : std::false_type {};
template <> struct is_goresky_macpherson_perversity_base<PerversityGM>: std::true_type {};
template <typename T> struct is_goresky_macpherson_perversity : is_goresky_macpherson_perversity_base<typename std::decay<T>::type> {};
std::ostream& operator<<( std::ostream& o, const Perversity p )
{
o << "[";
for( auto it = p.begin(); it != p.end(); ++it )
{
if( it != p.begin() )
o << ",";
o << *it;
}
o << "]";
return o;
}
/**
Given a simplicial complex, a stratification (a filtration), and
a perversity function, this function calculates the persistent
intersection homology of the data set.
Depending on the selected perversity, the stratification is set
up differently and needs to satisfy certain constraints. Hence,
if a Goresky--MacPherson perversity is being used, we have
\f[
X_{n-1} = X_{n-2}
\f]
and
\f[
X_n = K.
\f]
The function does *not* check the last condition, though, since one
can also use it with a barycentric subdivision of a given complex.
@param K Simplicial complex
@param X Stratification/filtration (sequence of simplicial complexes)
@param p Perversity function
@returns Persistent intersection homology diagram
*/
template <class Simplex, class Perversity>
auto calculateIntersectionHomology( const aleph::topology::SimplicialComplex<Simplex>& K,
const std::vector< aleph::topology::SimplicialComplex<Simplex> >& X,
const Perversity& p ) -> std::vector< PersistenceDiagram<typename Simplex::DataType> >
{
// The use of Goresky--MacPherson perversities requires using the
// original indexing, starting from k=2.
bool useOriginalIndexing = is_goresky_macpherson_perversity<Perversity>::value;
if( useOriginalIndexing )
{
// Consistency check: The stratification must have sufficiently many
// simplicial complexes.
if( X.size() <= 2 )
throw std::runtime_error( "Insufficient number of simplicial complexes for stratification" );
// Consistency check: The strata need to satisfy $X_{n-1} = X_{n-2}$
// for a proper Goresky--MacPherson stratification.
if( *(X.rbegin()+1) != *(X.rbegin()+2) )
throw std::runtime_error( "Stratification must satisfy requirements by Goresky & MacPherson" );
}
// Check consistency of filtration -----------------------------------
//
// The maximum dimension of each complex in the filtration has to
// match the dimension of the simplicial complex.
{
std::size_t minDimension = K.dimension();
std::size_t maxDimension = 0;
for( auto&& x : X )
{
if( !K.empty() )
{
minDimension = std::min( minDimension, x.dimension() );
maxDimension = std::max( maxDimension, x.dimension() );
}
}
if( maxDimension != K.dimension() )
throw std::runtime_error( "Invalid filtration" );
}
// Check whether simplex is allowable --------------------------------
std::map<Simplex, bool> phi;
{
auto d = K.dimension();
for( auto&& s : K )
{
bool admissible = true;
// Note that I am letting the index start at $k = 2$ because this
// is in consistent with the original definition given by Goresky
// and MacPherson. By default, this behaviour is *not* active.
for( std::size_t k = useOriginalIndexing ? 2 : 1; k <= d; k++ )
{
// The notation follows Bendich and Harer, so $i$ is actually
// referring to a dimension instead of an index. Beware!
auto i = s.dimension();
auto intersection = aleph::topology::lastLexicographicalIntersection( X.at( d - k ), s );
auto dimension = intersection.empty() ? -1 : static_cast<long>( intersection.dimension() );
admissible = admissible && intersection.empty() ? true : static_cast<long>( dimension ) <= ( long(i) - long(k) + long( p(k) ) );
}
phi[s] = admissible;
}
}
// Partition according to allowable simplices ------------------------
aleph::topology::SimplicialComplex<Simplex> L;
std::size_t s = 0;
std::tie( L, s ) =
aleph::partition( K, [&phi] ( const Simplex& s )
{
return phi.at(s);
} );
// Calculate persistent intersection homology ------------------------
auto boundaryMatrix = aleph::topology::makeBoundaryMatrix( L, s );
using IndexType = typename decltype(boundaryMatrix)::Index;
bool includeAllUnpairedCreators = true;
auto pairing = aleph::calculatePersistencePairing( boundaryMatrix, includeAllUnpairedCreators, static_cast<IndexType>(s) );
auto persistenceDiagrams = aleph::makePersistenceDiagrams( pairing, L );
return persistenceDiagrams;
}
} // namespace aleph
#endif
<commit_msg>Improved performance of $\phi$-persistence admissibility check<commit_after>#ifndef ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_PHI_PERSISTENCE_HH__
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/topology/Conversions.hh>
#include <aleph/topology/Intersections.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <initializer_list>
#include <map>
#include <ostream>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace aleph
{
/**
Partitions a simplicial complex according to its $\phi$-persistence
values. This follows the persistent intersection homology algorithm
in:
Persistent Intersection Homology\n
Paul Bendich and John Harer\n
The function uses a simplicial complex \f$K\f$ and a function \f$\phi\f$
that determines whether a simplex is proper or not. The function is
going to create a new simplicial complex. This complex contains all
proper simplices (in their original order) followed by all improper
ones.
*/
template <class Simplex, class Function> std::pair<topology::SimplicialComplex<Simplex>, std::size_t> partition( const topology::SimplicialComplex<Simplex>& K, Function phi )
{
topology::SimplicialComplex<Simplex> L;
for( auto&& simplex : K )
{
if( phi(simplex) )
L.push_back( simplex );
}
auto s = L.size();
for( auto&& simplex : K )
{
if( !phi(simplex) )
L.push_back( simplex );
}
return std::make_pair( L, s );
}
/**
@class Perversity
@brief Perversity model in the sense of persistent intersection homology
Models a perversity in the sense of persistent intersection homology,
following the definitions of Bendich. The class ensures that all
values satisfy
\f
-1 \leq p_k \leq k-1
\f
*/
class Perversity
{
public:
/**
Creates a new perversity from a range of values. The values must be
at least implicitly convertible to integers.
*/
template <class InputIterator> Perversity( InputIterator begin, InputIterator end )
: _values( begin, end )
{
for( std::size_t k = 0; k < _values.size(); k++ )
{
if( _values[k] < -1 )
_values[k] = -1;
// There is an index shift going on here: since $k$ runs from $0$
// to $d-1$, there is no need to shift the upper bound.
else if( _values[k] > static_cast<int>( k ) )
_values[k] = static_cast<int>( k );
}
}
/** Creates a new perversity from an initializer list of values */
Perversity( std::initializer_list<int> values )
: Perversity( values.begin(), values.end() )
{
}
/**
Queries the perversity value in a given dimension $d$. Invalid
dimension values only cause the function to return a zero.
*/
int operator()( std::size_t d ) const noexcept
{
if( d < _values.size() + 1 )
return _values[ static_cast<std::size_t>( d-1 ) ];
else
return 0;
}
using const_iterator = typename std::vector<int>::const_iterator;
const_iterator begin() const noexcept { return _values.begin(); }
const_iterator end() const noexcept { return _values.end(); }
private:
std::vector<int> _values;
};
/**
@class PerversityGM
@brief Perversity model in the sense of intersection homology
Models a perversity in the sense of intersection homology, following
Goresky and MacPherson. The class ensures that all values satisfy
\f
p_{k+1} = p_k \mathrm{ or } p_{k+1} = p_k + 1
\f
and \f$p_2 = 0\f$.
*/
class PerversityGM
{
public:
/**
Creates a new perversity from a range of values. The values must be
at least implicitly convertible to integers.
*/
template <class InputIterator> PerversityGM( InputIterator begin, InputIterator end )
: _values( begin, end )
{
for( std::size_t k = 1; k < _values.size(); k++ )
{
if( _values[k] != _values[k-1] && _values[k] != _values[k-1] + 1 )
_values[k] = _values[k-1] + 1;
}
}
/** Creates a new perversity from an initializer list of values */
PerversityGM( std::initializer_list<int> values )
: PerversityGM( values.begin(), values.end() )
{
}
/**
Queries the perversity value in a given dimension \p d. Invalid
dimension values only cause the function to return a zero.
*/
unsigned operator()( std::size_t d ) const noexcept
{
if( d < _values.size() + 2 )
return _values[ static_cast<std::size_t>( d-2 ) ];
else
return 0;
}
using const_iterator = typename std::vector<unsigned>::const_iterator;
const_iterator begin() const noexcept { return _values.begin(); }
const_iterator end() const noexcept { return _values.end(); }
private:
std::vector<unsigned> _values;
};
// Provide a simple form of tag dispatching in order to detect whether
// a perversity uses the 'original' intersection homology framework as
// described by Goresky and MacPherson.
template <typename> struct is_goresky_macpherson_perversity_base : std::false_type {};
template <> struct is_goresky_macpherson_perversity_base<PerversityGM>: std::true_type {};
template <typename T> struct is_goresky_macpherson_perversity : is_goresky_macpherson_perversity_base<typename std::decay<T>::type> {};
std::ostream& operator<<( std::ostream& o, const Perversity p )
{
o << "[";
for( auto it = p.begin(); it != p.end(); ++it )
{
if( it != p.begin() )
o << ",";
o << *it;
}
o << "]";
return o;
}
/**
Given a simplicial complex, a stratification (a filtration), and
a perversity function, this function calculates the persistent
intersection homology of the data set.
Depending on the selected perversity, the stratification is set
up differently and needs to satisfy certain constraints. Hence,
if a Goresky--MacPherson perversity is being used, we have
\f[
X_{n-1} = X_{n-2}
\f]
and
\f[
X_n = K.
\f]
The function does *not* check the last condition, though, since one
can also use it with a barycentric subdivision of a given complex.
@param K Simplicial complex
@param X Stratification/filtration (sequence of simplicial complexes)
@param p Perversity function
@returns Persistent intersection homology diagram
*/
template <class Simplex, class Perversity>
auto calculateIntersectionHomology( const aleph::topology::SimplicialComplex<Simplex>& K,
const std::vector< aleph::topology::SimplicialComplex<Simplex> >& X,
const Perversity& p ) -> std::vector< PersistenceDiagram<typename Simplex::DataType> >
{
// The use of Goresky--MacPherson perversities requires using the
// original indexing, starting from k=2.
bool useOriginalIndexing = is_goresky_macpherson_perversity<Perversity>::value;
if( useOriginalIndexing )
{
// Consistency check: The stratification must have sufficiently many
// simplicial complexes.
if( X.size() <= 2 )
throw std::runtime_error( "Insufficient number of simplicial complexes for stratification" );
// Consistency check: The strata need to satisfy $X_{n-1} = X_{n-2}$
// for a proper Goresky--MacPherson stratification.
if( *(X.rbegin()+1) != *(X.rbegin()+2) )
throw std::runtime_error( "Stratification must satisfy requirements by Goresky & MacPherson" );
}
// Check consistency of filtration -----------------------------------
//
// The maximum dimension of each complex in the filtration has to
// match the dimension of the simplicial complex.
{
std::size_t minDimension = K.dimension();
std::size_t maxDimension = 0;
for( auto&& x : X )
{
if( !K.empty() )
{
minDimension = std::min( minDimension, x.dimension() );
maxDimension = std::max( maxDimension, x.dimension() );
}
}
if( maxDimension != K.dimension() )
throw std::runtime_error( "Invalid filtration" );
}
// Check whether simplex is allowable --------------------------------
std::map<Simplex, bool> phi;
{
auto d = K.dimension();
for( auto&& s : K )
{
bool admissible = true;
// Note that I am letting the index start at $k = 2$ because this
// is in consistent with the original definition given by Goresky
// and MacPherson. By default, this behaviour is *not* active.
for( std::size_t k = useOriginalIndexing ? 2 : 1; k <= d; k++ )
{
// The notation follows Bendich and Harer, so $i$ is actually
// referring to a dimension instead of an index. Beware!
auto i = s.dimension();
auto intersection = aleph::topology::lastLexicographicalIntersection( X.at( d - k ), s );
auto dimension = intersection.empty() ? -1 : static_cast<long>( intersection.dimension() );
admissible = admissible && intersection.empty() ? true : static_cast<long>( dimension ) <= ( long(i) - long(k) + long( p(k) ) );
// Early abort as soon as we are sure that the simplex cannot
// become admissible again.
if( !admissible )
break;
}
phi[s] = admissible;
}
}
// Partition according to allowable simplices ------------------------
aleph::topology::SimplicialComplex<Simplex> L;
std::size_t s = 0;
std::tie( L, s ) =
aleph::partition( K, [&phi] ( const Simplex& s )
{
return phi.at(s);
} );
// Calculate persistent intersection homology ------------------------
auto boundaryMatrix = aleph::topology::makeBoundaryMatrix( L, s );
using IndexType = typename decltype(boundaryMatrix)::Index;
bool includeAllUnpairedCreators = true;
auto pairing = aleph::calculatePersistencePairing( boundaryMatrix, includeAllUnpairedCreators, static_cast<IndexType>(s) );
auto persistenceDiagrams = aleph::makePersistenceDiagrams( pairing, L );
return persistenceDiagrams;
}
} // namespace aleph
#endif
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : implements compiler like Log formatter
// ***************************************************************************
#ifndef BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER
#define BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER
// Boost.Test
#include <boost/test/output/compiler_log_formatter.hpp>
#include <boost/test/unit_test_suite_impl.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/utils/basic_cstring/io.hpp>
// Boost
#include <boost/version.hpp>
// STL
#include <iostream>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
namespace output {
// ************************************************************************** //
// ************** compiler_log_formatter ************** //
// ************************************************************************** //
void
compiler_log_formatter::log_start( std::ostream& output, counter_t test_cases_amount )
{
if( test_cases_amount > 0 )
output << "Running " << test_cases_amount << " test "
<< (test_cases_amount > 1 ? "cases" : "case") << "...\n";
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_finish( std::ostream& )
{
// do nothing
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_build_info( std::ostream& output )
{
output << "Platform: " << BOOST_PLATFORM << '\n'
<< "Compiler: " << BOOST_COMPILER << '\n'
<< "STL : " << BOOST_STDLIB << '\n'
<< "Boost : " << BOOST_VERSION/100000 << "."
<< BOOST_VERSION/100 % 1000 << "."
<< BOOST_VERSION % 100 << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::test_unit_start( std::ostream& output, test_unit const& tu )
{
output << "Entering test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed )
{
output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\"";
if( elapsed > 0 ) {
output << "; testing time: ";
if( elapsed % 1000 == 0 )
output << elapsed/1000 << "ms";
else
output << elapsed << "mks";
}
output << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::test_unit_skipped( std::ostream& output, test_unit const& tu )
{
output << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_exception( std::ostream& output, log_checkpoint_data const& checkpoint_data, const_string explanation )
{
print_prefix( output, BOOST_TEST_L( "unknown location" ), 0 );
output << "fatal error in \"" << framework::current_test_case().p_name << "\": ";
if( !explanation.is_empty() )
output << explanation;
else
output << "uncaught exception, system error or abort requested";
if( !checkpoint_data.m_file_name.is_empty() ) {
output << '\n';
print_prefix( output, checkpoint_data.m_file_name, checkpoint_data.m_line_num );
output << "last checkpoint";
if( !checkpoint_data.m_message.empty() )
output << ": " << checkpoint_data.m_message;
}
output << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_entry_start( std::ostream& output, log_entry_data const& entry_data, log_entry_types let )
{
switch( let ) {
case BOOST_UTL_ET_INFO:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "info: ";
break;
case BOOST_UTL_ET_MESSAGE:
break;
case BOOST_UTL_ET_WARNING:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "warning in \"" << framework::current_test_case().p_name << "\": ";
break;
case BOOST_UTL_ET_ERROR:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "error in \"" << framework::current_test_case().p_name << "\": ";
break;
case BOOST_UTL_ET_FATAL_ERROR:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "fatal error in \"" << framework::current_test_case().p_name << "\": ";
break;
}
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_entry_value( std::ostream& output, const_string value )
{
output << value;
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_entry_finish( std::ostream& output )
{
output << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::print_prefix( std::ostream& output, const_string file, std::size_t line )
{
output << file << '(' << line << "): ";
}
//____________________________________________________________________________//
} // namespace ouptut
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.4 2005/12/14 05:26:32 rogeeff
// report aborted test units
//
// Revision 1.3 2005/02/21 10:09:26 rogeeff
// exception logging changes so that it produce a string recognizable by compiler as an error
//
// Revision 1.2 2005/02/20 08:27:06 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// Revision 1.1 2005/02/01 08:59:38 rogeeff
// supplied_log_formatters split
// change formatters interface to simplify result interface
//
// ***************************************************************************
#endif // BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER
<commit_msg>flush log stream on exit<commit_after>// (C) Copyright Gennadiy Rozental 2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : implements compiler like Log formatter
// ***************************************************************************
#ifndef BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER
#define BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER
// Boost.Test
#include <boost/test/output/compiler_log_formatter.hpp>
#include <boost/test/unit_test_suite_impl.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/utils/basic_cstring/io.hpp>
// Boost
#include <boost/version.hpp>
// STL
#include <iostream>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
namespace output {
// ************************************************************************** //
// ************** compiler_log_formatter ************** //
// ************************************************************************** //
void
compiler_log_formatter::log_start( std::ostream& output, counter_t test_cases_amount )
{
if( test_cases_amount > 0 )
output << "Running " << test_cases_amount << " test "
<< (test_cases_amount > 1 ? "cases" : "case") << "...\n";
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_finish( std::ostream& ostr )
{
ostr.flush();
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_build_info( std::ostream& output )
{
output << "Platform: " << BOOST_PLATFORM << '\n'
<< "Compiler: " << BOOST_COMPILER << '\n'
<< "STL : " << BOOST_STDLIB << '\n'
<< "Boost : " << BOOST_VERSION/100000 << "."
<< BOOST_VERSION/100 % 1000 << "."
<< BOOST_VERSION % 100 << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::test_unit_start( std::ostream& output, test_unit const& tu )
{
output << "Entering test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed )
{
output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\"";
if( elapsed > 0 ) {
output << "; testing time: ";
if( elapsed % 1000 == 0 )
output << elapsed/1000 << "ms";
else
output << elapsed << "mks";
}
output << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::test_unit_skipped( std::ostream& output, test_unit const& tu )
{
output << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_exception( std::ostream& output, log_checkpoint_data const& checkpoint_data, const_string explanation )
{
print_prefix( output, BOOST_TEST_L( "unknown location" ), 0 );
output << "fatal error in \"" << framework::current_test_case().p_name << "\": ";
if( !explanation.is_empty() )
output << explanation;
else
output << "uncaught exception, system error or abort requested";
if( !checkpoint_data.m_file_name.is_empty() ) {
output << '\n';
print_prefix( output, checkpoint_data.m_file_name, checkpoint_data.m_line_num );
output << "last checkpoint";
if( !checkpoint_data.m_message.empty() )
output << ": " << checkpoint_data.m_message;
}
output << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_entry_start( std::ostream& output, log_entry_data const& entry_data, log_entry_types let )
{
switch( let ) {
case BOOST_UTL_ET_INFO:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "info: ";
break;
case BOOST_UTL_ET_MESSAGE:
break;
case BOOST_UTL_ET_WARNING:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "warning in \"" << framework::current_test_case().p_name << "\": ";
break;
case BOOST_UTL_ET_ERROR:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "error in \"" << framework::current_test_case().p_name << "\": ";
break;
case BOOST_UTL_ET_FATAL_ERROR:
print_prefix( output, entry_data.m_file_name, entry_data.m_line_num );
output << "fatal error in \"" << framework::current_test_case().p_name << "\": ";
break;
}
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_entry_value( std::ostream& output, const_string value )
{
output << value;
}
//____________________________________________________________________________//
void
compiler_log_formatter::log_entry_finish( std::ostream& output )
{
output << std::endl;
}
//____________________________________________________________________________//
void
compiler_log_formatter::print_prefix( std::ostream& output, const_string file, std::size_t line )
{
output << file << '(' << line << "): ";
}
//____________________________________________________________________________//
} // namespace ouptut
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.5 2006/07/28 15:01:59 rogeeff
// flush log stream on exit
//
// Revision 1.4 2005/12/14 05:26:32 rogeeff
// report aborted test units
//
// Revision 1.3 2005/02/21 10:09:26 rogeeff
// exception logging changes so that it produce a string recognizable by compiler as an error
//
// Revision 1.2 2005/02/20 08:27:06 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// Revision 1.1 2005/02/01 08:59:38 rogeeff
// supplied_log_formatters split
// change formatters interface to simplify result interface
//
// ***************************************************************************
#endif // BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER
<|endoftext|> |
<commit_before>/**
* \file
* \brief ThreadControlBlock class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2014-10-23
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/architecture/Stack.hpp"
namespace distortos
{
namespace scheduler
{
class ThreadControlBlockList;
/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:
/// state of the thread
enum class State : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is terminated
Terminated,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
};
/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
*/
ThreadControlBlock(void* buffer, size_t size, uint8_t priority);
/**
* \return iterator to the element on the list, valid only when list_ != nullptr
*/
ThreadControlBlockListIterator getIterator() const
{
return iterator_;
}
/**
* \return reference to internal storage for list link
*/
Link& getLink()
{
return link_;
}
/**
* \return const reference to internal storage for list link
*/
const Link& getLink() const
{
return link_;
}
/**
* \return pointer to list that has this object
*/
ThreadControlBlockList* getList() const
{
return list_;
}
/**
* \return priority of ThreadControlBlock
*/
uint8_t getPriority() const
{
return priority_;
}
/**
* \return reference to internal RoundRobinQuantum object
*/
RoundRobinQuantum& getRoundRobinQuantum()
{
return roundRobinQuantum_;
}
/**
* \return const reference to internal RoundRobinQuantum object
*/
const RoundRobinQuantum& getRoundRobinQuantum() const
{
return roundRobinQuantum_;
}
/**
* \return reference to internal Stack object
*/
architecture::Stack& getStack()
{
return stack_;
}
/**
* \return const reference to internal Stack object
*/
const architecture::Stack& getStack() const
{
return stack_;
}
/**
* \return current state of object
*/
State getState() const
{
return state_;
}
/**
* \brief Sets the iterator to the element on the list.
*
* \param [in] iterator is an iterator to the element on the list
*/
void setIterator(const ThreadControlBlockListIterator iterator)
{
iterator_ = iterator;
}
/**
* \brief Sets the list that has this object.
*
* \param [in] list is a pointer to list that has this object
*/
void setList(ThreadControlBlockList* const list)
{
list_ = list;
}
/**
* Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(uint8_t priority, bool alwaysBehind = {});
/**
* \param [in] state is the new state of object
*/
void setState(const State state)
{
state_ = state;
}
/**
* \brief Termination hook function of thread
*
* \attention This function should be called only by Scheduler::remove().
*/
void terminationHook()
{
terminationHook_();
}
protected:
/**
* \brief ThreadControlBlock constructor.
*
* This constructor is meant for MainThreadControlBlock.
*
* \param [in] stack is an rvalue reference to stack of main()
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
*/
ThreadControlBlock(architecture::Stack&& stack, uint8_t priority);
/**
* \brief ThreadControlBlock's destructor
*
* \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
*/
~ThreadControlBlock()
{
}
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
*/
static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes.
*
* This should be overridden by derived classes.
*/
virtual void terminationHook_() = 0;
/// internal stack object
architecture::Stack stack_;
/// storage for list link
Link link_;
/// pointer to list that has this object
ThreadControlBlockList* list_;
/// iterator to the element on the list, valid only when list_ != nullptr
ThreadControlBlockListIterator iterator_;
/// thread's priority, 0 - lowest, UINT8_MAX - highest
uint8_t priority_;
/// thread's boosted priority, 0 - no boosting
uint8_t boostedPriority_;
/// round-robin quantum
RoundRobinQuantum roundRobinQuantum_;
/// current state of object
State state_;
};
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
<commit_msg>ThreadControlBlock: add ThreadControlBlock::getEffectivePriority()<commit_after>/**
* \file
* \brief ThreadControlBlock class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2014-10-23
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/architecture/Stack.hpp"
namespace distortos
{
namespace scheduler
{
class ThreadControlBlockList;
/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:
/// state of the thread
enum class State : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is terminated
Terminated,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
};
/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
*/
ThreadControlBlock(void* buffer, size_t size, uint8_t priority);
/**
* \return effective priority of ThreadControlBlock
*/
uint8_t getEffectivePriority() const
{
return std::max(priority_, boostedPriority_);
}
/**
* \return iterator to the element on the list, valid only when list_ != nullptr
*/
ThreadControlBlockListIterator getIterator() const
{
return iterator_;
}
/**
* \return reference to internal storage for list link
*/
Link& getLink()
{
return link_;
}
/**
* \return const reference to internal storage for list link
*/
const Link& getLink() const
{
return link_;
}
/**
* \return pointer to list that has this object
*/
ThreadControlBlockList* getList() const
{
return list_;
}
/**
* \return priority of ThreadControlBlock
*/
uint8_t getPriority() const
{
return priority_;
}
/**
* \return reference to internal RoundRobinQuantum object
*/
RoundRobinQuantum& getRoundRobinQuantum()
{
return roundRobinQuantum_;
}
/**
* \return const reference to internal RoundRobinQuantum object
*/
const RoundRobinQuantum& getRoundRobinQuantum() const
{
return roundRobinQuantum_;
}
/**
* \return reference to internal Stack object
*/
architecture::Stack& getStack()
{
return stack_;
}
/**
* \return const reference to internal Stack object
*/
const architecture::Stack& getStack() const
{
return stack_;
}
/**
* \return current state of object
*/
State getState() const
{
return state_;
}
/**
* \brief Sets the iterator to the element on the list.
*
* \param [in] iterator is an iterator to the element on the list
*/
void setIterator(const ThreadControlBlockListIterator iterator)
{
iterator_ = iterator;
}
/**
* \brief Sets the list that has this object.
*
* \param [in] list is a pointer to list that has this object
*/
void setList(ThreadControlBlockList* const list)
{
list_ = list;
}
/**
* Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(uint8_t priority, bool alwaysBehind = {});
/**
* \param [in] state is the new state of object
*/
void setState(const State state)
{
state_ = state;
}
/**
* \brief Termination hook function of thread
*
* \attention This function should be called only by Scheduler::remove().
*/
void terminationHook()
{
terminationHook_();
}
protected:
/**
* \brief ThreadControlBlock constructor.
*
* This constructor is meant for MainThreadControlBlock.
*
* \param [in] stack is an rvalue reference to stack of main()
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
*/
ThreadControlBlock(architecture::Stack&& stack, uint8_t priority);
/**
* \brief ThreadControlBlock's destructor
*
* \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
*/
~ThreadControlBlock()
{
}
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
*/
static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes.
*
* This should be overridden by derived classes.
*/
virtual void terminationHook_() = 0;
/// internal stack object
architecture::Stack stack_;
/// storage for list link
Link link_;
/// pointer to list that has this object
ThreadControlBlockList* list_;
/// iterator to the element on the list, valid only when list_ != nullptr
ThreadControlBlockListIterator iterator_;
/// thread's priority, 0 - lowest, UINT8_MAX - highest
uint8_t priority_;
/// thread's boosted priority, 0 - no boosting
uint8_t boostedPriority_;
/// round-robin quantum
RoundRobinQuantum roundRobinQuantum_;
/// current state of object
State state_;
};
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
<|endoftext|> |
<commit_before>// Joint work by Rob Mill & J B Coe
#include <iostream>
#include <functional>
class A;
class B;
class C;
class AbstractVisitor
{
public:
virtual void Visit(A& a) = 0;
virtual void Visit(B& b) = 0;
virtual void Visit(C& c) = 0;
protected:
~AbstractVisitor() {}
};
class Visitable
{
public:
virtual void Accept(AbstractVisitor& v) = 0;
protected:
~Visitable() {}
};
class A : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class B : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class C : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
template <typename T, typename F, typename BaseInnerVisitor, typename ArgsT>
class ComposeVisitor
{
public:
class InnerVisitor : public BaseInnerVisitor
{
public:
using BaseInnerVisitor::Visit;
InnerVisitor(ArgsT&& args) : BaseInnerVisitor(std::move(args.second)), m_f(std::move(args.first)) {}
void Visit(T& t) final override { m_f(t); }
private:
F m_f;
};
ComposeVisitor(ArgsT&& args) : m_args(std::move(args)) {}
template <typename Tadd, typename Fadd>
ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, ArgsT>> on(Fadd&& f) &&
{
return ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, ArgsT>>(
std::make_pair(std::move(f), std::move(m_args)));
}
InnerVisitor end_visitor() && { return InnerVisitor(std::move(m_args)); }
ArgsT m_args;
};
template <typename TVisitorBase>
class EmptyVisitor
{
public:
class InnerVisitor : public TVisitorBase
{
public:
using TVisitorBase::Visit;
InnerVisitor(std::nullptr_t) {}
};
template <typename Tadd, typename Fadd>
ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, std::nullptr_t>> on(Fadd&& f) &&
{
return ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, std::nullptr_t>>(
std::make_pair(std::move(f), nullptr));
}
};
template <typename TVisitorBase>
EmptyVisitor<TVisitorBase> begin_visitor()
{
return EmptyVisitor<TVisitorBase>();
}
int main()
{
A a;
B b;
C c;
int iCounter = 0;
#ifdef USE_CLASS
struct CVisitor : public AbstractVisitor
{
CVisitor(int& i) : iCounter_(i) {}
int& iCounter_;
void Visit(A& a) override final
{
std::cout << "I'm an A" << std::endl;
iCounter_ += 1;
}
void Visit(B& a) override final
{
std::cout << "I'm a B" << std::endl;
iCounter_ += 2;
}
void Visit(C& a) override final
{
std::cout << "I'm a C" << std::endl;
iCounter_ += 3;
}
} visitor(iCounter);
#else
auto visitor = begin_visitor<AbstractVisitor>()
.on<A>([&iCounter](A& a)
{
std::cout << "I'm an A" << std::endl;
iCounter += 1;
})
.on<B>([&iCounter](B& a)
{
std::cout << "I'm a B" << std::endl;
iCounter += 2;
})
.on<C>([&iCounter](C& c)
{
std::cout << "I'm a C" << std::endl;
iCounter += 3;
})
.end_visitor();
#endif
a.Accept(visitor);
b.Accept(visitor);
c.Accept(visitor);
std::cout << "Count is " << iCounter << std::endl;
return 0;
}
<commit_msg>appease gcc<commit_after>// Joint work by Rob Mill & J B Coe
#include <iostream>
#include <functional>
class A;
class B;
class C;
class AbstractVisitor
{
public:
virtual void Visit(A& a) = 0;
virtual void Visit(B& b) = 0;
virtual void Visit(C& c) = 0;
protected:
~AbstractVisitor() {}
};
class Visitable
{
public:
virtual void Accept(AbstractVisitor& v) = 0;
protected:
~Visitable() {}
};
class A : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class B : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
class C : public Visitable
{
public:
void Accept(AbstractVisitor& v) override { v.Visit(*this); }
};
template <typename T, typename F, typename BaseInnerVisitor, typename ArgsT>
class ComposeVisitor
{
public:
class InnerVisitor : public BaseInnerVisitor
{
public:
using BaseInnerVisitor::Visit;
InnerVisitor(ArgsT&& args) : BaseInnerVisitor(std::move(args.second)), m_f(std::move(args.first)) {}
void Visit(T& t) final override { m_f(t); }
private:
F m_f;
};
ComposeVisitor(ArgsT&& args) : m_args(std::move(args)) {}
template <typename Tadd, typename Fadd>
ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, ArgsT>> on(Fadd&& f) &&
{
return ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, ArgsT>>(
std::make_pair(std::move(f), std::move(m_args)));
}
typename std::enable_if< ! std::is_abstract<InnerVisitor>::value, InnerVisitor>::type
end_visitor() && { return InnerVisitor(std::move(m_args)); }
ArgsT m_args;
};
template <typename TVisitorBase>
class EmptyVisitor
{
public:
class InnerVisitor : public TVisitorBase
{
public:
using TVisitorBase::Visit;
InnerVisitor(std::nullptr_t) {}
};
template <typename Tadd, typename Fadd>
ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, std::nullptr_t>> on(Fadd&& f) &&
{
return ComposeVisitor<Tadd, Fadd, InnerVisitor, std::pair<Fadd, std::nullptr_t>>(
std::make_pair(std::move(f), nullptr));
}
};
template <typename TVisitorBase>
EmptyVisitor<TVisitorBase> begin_visitor()
{
return EmptyVisitor<TVisitorBase>();
}
int main()
{
A a;
B b;
C c;
int iCounter = 0;
#ifdef USE_CLASS
struct CVisitor : public AbstractVisitor
{
CVisitor(int& i) : iCounter_(i) {}
int& iCounter_;
void Visit(A& a) override final
{
std::cout << "I'm an A" << std::endl;
iCounter_ += 1;
}
void Visit(B& a) override final
{
std::cout << "I'm a B" << std::endl;
iCounter_ += 2;
}
void Visit(C& a) override final
{
std::cout << "I'm a C" << std::endl;
iCounter_ += 3;
}
} visitor(iCounter);
#else
auto visitor = begin_visitor<AbstractVisitor>()
.on<A>([&iCounter](A& a)
{
std::cout << "I'm an A" << std::endl;
iCounter += 1;
})
.on<B>([&iCounter](B& a)
{
std::cout << "I'm a B" << std::endl;
iCounter += 2;
})
.on<C>([&iCounter](C& c)
{
std::cout << "I'm a C" << std::endl;
iCounter += 3;
})
.end_visitor();
#endif
a.Accept(visitor);
b.Accept(visitor);
c.Accept(visitor);
std::cout << "Count is " << iCounter << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file joint_distribution_iid.hpp
* \date Febuary 2015
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__DISTRIBUTION__JOINT_DISTRIBUTION_IID_HPP
#define FL__DISTRIBUTION__JOINT_DISTRIBUTION_IID_HPP
#include <Eigen/Dense>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/distribution/interface/moments.hpp>
namespace fl
{
// Forward declaration
template <typename...Distributions> class JointDistribution;
/**
* Traits of JointDistribution<Distribution, Count>
*/
template <typename Distribution, int Count>
struct Traits<
JointDistribution<MultipleOf<Distribution, Count>>
>
{
typedef typename Traits<Distribution>::Variate MarginalVariate;
enum : signed int
{
MarginalCount = Count,
Dimension = ExpandSizes<MarginalVariate::SizeAtCompileTime, Count>::Size
};
typedef typename MarginalVariate::Scalar Scalar;
typedef Eigen::Matrix<Scalar, Dimension, 1> Variate;
typedef Eigen::Matrix<Scalar, Dimension, Dimension> SecondMoment;
typedef Eigen::Matrix<Distribution, Count, 1> MarginalDistributions;
typedef Moments<Variate, SecondMoment> MomentsInterface;
};
/**
* \ingroup distributions
*/
template <typename MarginalDistribution, int Count>
class JointDistribution<MultipleOf<MarginalDistribution, Count>>
: public Traits<
JointDistribution<
MultipleOf<MarginalDistribution, Count>
>
>::MomentsInterface
{
public:
typedef JointDistribution<MultipleOf<MarginalDistribution, Count>> This;
typedef typename Traits<This>::Variate Variate;
typedef typename Traits<This>::SecondMoment SecondMoment;
typedef typename Traits<This>::MarginalDistributions MarginalDistributions;
public:
JointDistribution(MarginalDistribution marginal,
int count = ToDimension<Count>::Value)
: distributions_(MarginalDistributions(count, 1))
{
assert(count > 0);
for (int i = 0; i < distributions_.rows(); ++i)
{
distributions_(i) = marginal;
}
dimension_ = marginal.dimension() * count;
}
/**
* \brief Overridable default destructor
*/
virtual ~JointDistribution() { }
virtual Variate mean() const
{
Variate mu = Variate(dimension(), 1);
int offset = 0;
for (int i = 0; i < Traits<This>::MarginalCount; ++i)
{
const MarginalDistribution& marginal = distributions_(i);
int dim = marginal.dimension();
mu.middleRows(offset, dim) = marginal.mean();
offset += dim;
}
return mu;
}
virtual SecondMoment covariance() const
{
SecondMoment cov = SecondMoment::Zero(dimension(), dimension());
int offset = 0;
for (int i = 0; i < distributions_.rows(); ++i)
{
const MarginalDistribution& marginal = distributions_(i);
int dim = marginal.dimension();
cov.block(offset, offset, dim, dim) = marginal.covariance();
offset += dim;
}
return cov;
}
virtual int dimension() const
{
return dimension_;
}
MarginalDistributions& distributions()
{
return distributions_;
}
protected:
MarginalDistributions distributions_;
int dimension_;
};
}
#endif
<commit_msg>provided access to distributions_<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file joint_distribution_iid.hpp
* \date Febuary 2015
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__DISTRIBUTION__JOINT_DISTRIBUTION_IID_HPP
#define FL__DISTRIBUTION__JOINT_DISTRIBUTION_IID_HPP
#include <Eigen/Dense>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/distribution/interface/moments.hpp>
namespace fl
{
// Forward declaration
template <typename...Distributions> class JointDistribution;
/**
* Traits of JointDistribution<Distribution, Count>
*/
template <typename Distribution, int Count>
struct Traits<
JointDistribution<MultipleOf<Distribution, Count>>
>
{
typedef typename Traits<Distribution>::Variate MarginalVariate;
enum : signed int
{
MarginalCount = Count,
Dimension = ExpandSizes<MarginalVariate::SizeAtCompileTime, Count>::Size
};
typedef typename MarginalVariate::Scalar Scalar;
typedef Eigen::Matrix<Scalar, Dimension, 1> Variate;
typedef Eigen::Matrix<Scalar, Dimension, Dimension> SecondMoment;
typedef Eigen::Matrix<Distribution, Count, 1> MarginalDistributions;
typedef Moments<Variate, SecondMoment> MomentsInterface;
};
/**
* \ingroup distributions
*/
template <typename MarginalDistribution, int Count>
class JointDistribution<MultipleOf<MarginalDistribution, Count>>
: public Traits<
JointDistribution<
MultipleOf<MarginalDistribution, Count>
>
>::MomentsInterface
{
public:
typedef JointDistribution This;
typedef from_traits(Variate);
typedef from_traits(SecondMoment);
typedef from_traits(MarginalDistributions);
public:
JointDistribution(MarginalDistribution marginal,
int count = ToDimension<Count>::Value)
: distributions_(MarginalDistributions(count, 1))
{
assert(count > 0);
for (int i = 0; i < distributions_.rows(); ++i)
{
distributions_(i) = marginal;
}
dimension_ = marginal.dimension() * count;
}
/**
* \brief Overridable default destructor
*/
virtual ~JointDistribution() { }
virtual Variate mean() const
{
Variate mu = Variate(dimension(), 1);
int offset = 0;
for (int i = 0; i < Traits<This>::MarginalCount; ++i)
{
const MarginalDistribution& marginal = distributions_(i);
int dim = marginal.dimension();
mu.middleRows(offset, dim) = marginal.mean();
offset += dim;
}
return mu;
}
virtual SecondMoment covariance() const
{
SecondMoment cov = SecondMoment::Zero(dimension(), dimension());
int offset = 0;
for (int i = 0; i < distributions_.rows(); ++i)
{
const MarginalDistribution& marginal = distributions_(i);
int dim = marginal.dimension();
cov.block(offset, offset, dim, dim) = marginal.covariance();
offset += dim;
}
return cov;
}
virtual int dimension() const
{
return dimension_;
}
MarginalDistributions& distributions()
{
return distributions_;
}
const MarginalDistributions& distributions() const
{
return distributions_;
}
MarginalDistribution& distribution(int index)
{
assert(index < distributions_.size());
return distributions_(index);
}
const MarginalDistribution& distribution(int index) const
{
assert(index < distributions_.size());
return distributions_(index);
}
protected:
MarginalDistributions distributions_;
int dimension_;
};
}
#endif
<|endoftext|> |
<commit_before>/*
* structs.h
*
* Created on: 28.01.2015
* Author: fnolden
*/
#include <assert.h>
#ifndef INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
#define INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
namespace search
{
struct Value{
float min;
float max;
int steps_max;
float step_width;
Value(){
init_range(0, 0, 1);
};
Value( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_range( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_min_max(float min, float max, int steps_max = 3){
assert(min <= max);
assert(steps_max > 0);
this->min = min;
this->max = max;
this->steps_max = steps_max;
if(steps_max != 1){
step_width = (max - min)/(steps_max-1); // First step = min, last step = max
}
else{
step_width = 0;
}
}
float at(int step){
assert(step < steps_max);
return min + (step_width*step);
}
std::string to_string(){
std::stringstream ss;
ss << "min: " << min << " max: " << max << " steps: " << steps_max << " step_width: " << step_width << "\n";
return ss.str();
}
};
struct Search_setup{
Value x;
Value y;
Value z;
Value roll;
Value pitch;
Value yaw;
std::string to_string(){
std::stringstream ss;
ss << "x: " << x.to_string();
ss << "y: " << y.to_string();
ss << "z: " << z.to_string();
ss << "roll: " << roll.to_string();
ss << "pitch: " << pitch.to_string();
ss << "yaw: " << yaw.to_string();
return ss.str();
}
};
struct Search_value{
Search_value(){
init(0, 0, 0, 0, 0, 0, 0);
}
Search_value( float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0){
init(x, y, z, roll, pitch, yaw, result);
}
void init(float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0)
{
this->x = x;
this->y = y;
this->z = z;
this->roll = roll;
this->pitch = pitch;
this->yaw = yaw;
this->result = result;
}
std::string to_string(){
std::stringstream ss;
ss << "x: " << x << " y: " << y <<" z: " << z;
ss << " roll: " << roll << " pitch: " << pitch << " yaw: " << yaw;
ss << " result: " << result << "\n";
return ss.str();
}
float x;
float y;
float z;
float roll;
float pitch;
float yaw;
long unsigned int result;
};
}
#endif /* INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_ */
<commit_msg>added helper functions for tf handeling<commit_after>/*
* structs.h
*
* Created on: 28.01.2015
* Author: fnolden
*/
#include <assert.h>
#ifndef INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
#define INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
namespace search
{
struct Value{
float min;
float max;
int steps_max;
float step_width;
Value(){
init_range(0, 0, 1);
};
Value( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_range( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_min_max(float min, float max, int steps_max = 3){
assert(min <= max);
assert(steps_max > 0);
this->min = min;
this->max = max;
this->steps_max = steps_max;
if(steps_max != 1){
step_width = (max - min)/(steps_max-1); // First step = min, last step = max
}
else{
step_width = 0;
}
}
float at(int step){
assert(step < steps_max);
return min + (step_width*step);
}
std::string to_string(){
std::stringstream ss;
ss << "min: " << min << " max: " << max << " steps: " << steps_max << " step_width: " << step_width << "\n";
return ss.str();
}
};
struct Search_setup{
Value x;
Value y;
Value z;
Value roll;
Value pitch;
Value yaw;
std::string to_string(){
std::stringstream ss;
ss << "x: " << x.to_string();
ss << "y: " << y.to_string();
ss << "z: " << z.to_string();
ss << "roll: " << roll.to_string();
ss << "pitch: " << pitch.to_string();
ss << "yaw: " << yaw.to_string();
return ss.str();
}
};
struct Search_value{
Search_value(){
init(0, 0, 0, 0, 0, 0, 0);
}
Search_value(tf::Transform tf, long unsigned int result = 0){
init(tf, result);
}
Search_value( float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0){
init(x, y, z, roll, pitch, yaw, result);
}
void init(float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0)
{
this->x = x;
this->y = y;
this->z = z;
this->roll = roll;
this->pitch = pitch;
this->yaw = yaw;
this->result = result;
}
void init(tf::Transform tf, long unsigned int result = 0)
{
this->x = tf.getOrigin()[0];
this->y = tf.getOrigin()[1];
this->z = tf.getOrigin()[2];
double r,p,y;
tf.getBasis().getRPY(r, p, y);
this->roll = r;
this->pitch = p;
this->yaw = y;
this->result = result;
}
std::string to_string(){
std::stringstream ss;
ss << "x: " << x << " y: " << y <<" z: " << z;
ss << " roll: " << roll << " pitch: " << pitch << " yaw: " << yaw;
ss << " result: " << result << "\n";
return ss.str();
}
void get_transform(tf::Transform &tf){
tf.setOrigin( tf::Vector3( x, y, z ) );
tf::Quaternion q;
q.setRPY(roll, pitch, yaw );
tf.setRotation( q );
}
float x;
float y;
float z;
float roll;
float pitch;
float yaw;
long unsigned int result;
};
}
#endif /* INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_ */
<|endoftext|> |
<commit_before>#ifndef VIGRA_MULTI_ARRAY_MAP_HXX
#define VIGRA_MULTI_ARRAY_MAP_HXX
/* boost */
#include <boost/function.hpp>
/* vigra */
#include <vigra/multi_array.hxx>
#include <vigra/accumulator.hxx>
/* vigra - merge graph */
#include <vigra/merge_graph/min_indexed_pq.hxx>
namespace vigra{
namespace view_maps {
template<unsigned int DIM,class T>
class SumMap;
template<class T>
class SumMap<0,T> : public MultiArrayView<1,T> {
private:
SumMap(); // non empty-construction
SumMap( const SumMap& other ); // non construction-copyable
SumMap& operator=( const SumMap& ); // non copyable
public:
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
//const value_type & operator[](const IdType label)const{
// return this->operator(label);
//}
void merge(const IdType a,const IdType b){
this->operator()(a)+=this->operator()(b);
}
template<class CB>
CB mergeCallback(){
CB cb;
cb = boost::bind(boost::mem_fn(&SumMap<0,T>::merge), this , _1,_2);
return cb;
}
SumMap(ArrayViewType & array)
: ArrayViewType(array){
}
};
template<unsigned int DIM, class T>
class SumMap : public MultiArrayView<DIM+1,T> {
private:
SumMap(); // non empty-construction
SumMap( const SumMap& other ); // non construction-copyable
SumMap& operator=( const SumMap& ); // non copyable
public:
typedef MultiArrayView<DIM+1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
//const value_type & operator[](const IdType label)const{
// return this->operator(label);
//}
void merge(const IdType a,const IdType b){
this->bindInner(a)+=this->bindInner(b);
}
template<class CB>
CB mergeCallback(){
CB cb;
cb = boost::bind(boost::mem_fn(&SumMap<DIM,T>::merge), this , _1,_2);
return cb;
}
SumMap(ArrayViewType & array)
: ArrayViewType(array){
}
};
template<unsigned int DIM,class T,class WEIGHT_MAP>
class WeightedMeanMap;
template<class T,class WEIGHT_MAP>
class WeightedMeanMap<0,T,WEIGHT_MAP> : public MultiArrayView<1,T> {
private:
WeightedMeanMap(); // non empty-construction
WeightedMeanMap( const WeightedMeanMap& other ); // non construction-copyable
WeightedMeanMap& operator=( const WeightedMeanMap& ); // non copyable
public:
typedef WEIGHT_MAP WeightMapType;
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void merge(const IdType a,const IdType b){
const T va=this->operator()(a);
const T vb=this->operator()(b);
const T wa=weightMap_(a);
const T wb=weightMap_(b);
this->operator()(a)=(va*wa + vb*wb)/(wa+wb);
}
template<class CB>
CB mergeCallback(){
return boost::bind(boost::mem_fn(&WeightedMeanMap<0,T,WEIGHT_MAP>::merge), this , _1,_2);
}
WeightedMeanMap(ArrayViewType & array,const WeightMapType & weightMap)
: ArrayViewType(array),
weightMap_(weightMap){
}
private:
const WeightMapType & weightMap_;
};
template<unsigned int DIM,class T,class WEIGHT_MAP>
class WeightedMeanMap : public MultiArrayView<DIM+1,T> {
private:
WeightedMeanMap(); // non empty-construction
WeightedMeanMap( const WeightedMeanMap& other ); // non construction-copyable
WeightedMeanMap& operator=( const WeightedMeanMap& ); // non copyable
public:
typedef WEIGHT_MAP WeightMapType;
typedef MultiArrayView<DIM+1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void merge(const IdType a,const IdType b){
const T wa=weightMap_(a);
const T wb=weightMap_(b);
vigra::MultiArrayView<DIM,T> va = this->bindInner(a);
vigra::MultiArray<DIM,T> vb = this->bindInner(b);
va=(va*wa+vb*wb);
//va*=wa;
//vb*=wb;
//va+=vb;
//va/=(wa+wb);
//vb/=wb;
}
template<class CB>
CB mergeCallback(){
return boost::bind(boost::mem_fn(&WeightedMeanMap<DIM,T,WEIGHT_MAP>::merge), this , _1,_2);
}
WeightedMeanMap(ArrayViewType & array,const WeightMapType & weightMap)
: ArrayViewType(array),
weightMap_(weightMap){
}
private:
const WeightMapType & weightMap_;
};
template<class T,class MERGE_GRAPH>
class MinWeightEdgeMapSimple : public MultiArrayView<1,T> {
private:
MinWeightEdgeMapSimple(); // non empty-construction
MinWeightEdgeMapSimple( const MinWeightEdgeMapSimple& other ); // non construction-copyable
MinWeightEdgeMapSimple& operator=( const MinWeightEdgeMapSimple& ); // non copyable
public:
typedef MERGE_GRAPH MergeGraphType;
typedef typename MergeGraphType::Edge Edge;
typedef typename MergeGraphType::EdgeIt EdgeIt;
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void operator[](const Edge edge)const{
return MultiArrayView<1,T>::operator()(mergeGraph_.id(edge));
}
void mergeEdges(const IdType a,const IdType b){
pq_.deleteValue(b);
changePqWeight(a,this->operator()(a));
}
void eraseEdge(const IdType label){
pq_.deleteValue(label);
}
template<class CB>
CB eraseEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMapSimple<T,MERGE_GRAPH>::eraseEdge), this , _1);
}
template<class CB>
CB mergeEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMapSimple<T,MERGE_GRAPH>::mergeEdges), this , _1,_2);
}
MinWeightEdgeMapSimple(const MergeGraphType & mergeGraph,ArrayViewType & array)
: ArrayViewType(array),
mergeGraph_(mergeGraph),
pq_(mergeGraph.maxEdgeId()+1){
for(EdgeIt e(mergeGraph);e!=lemon::INVALID;++e){
const Edge edge = *e;
const IdType edgeId = mergeGraph_.id(edge);
pq_.insert(edgeId,this->operator()(edgeId));
}
}
IdType minWeightEdgeLabel(){
IdType minLabel = pq_.minIndex();
while(mergeGraph_.hasEdgeId(minLabel)==false){
pq_.deleteValue(minLabel);
IdType minLabel = pq_.minIndex();
}
return minLabel;
}
private:
void changePqWeight(const IdType l,const T newWeigt){
pq_.changeValue(l,newWeigt);
}
const MergeGraphType & mergeGraph_;
vigra::MinIndexedPQ<T> pq_;
};
template<class T,class MERGE_GRAPH,class EDGE_MAP,class NODE_MAP>
class MinWeightEdgeMap : public MultiArrayView<1,T> {
private:
MinWeightEdgeMap(); // non empty-construction
MinWeightEdgeMap( const MinWeightEdgeMap& other ); // non construction-copyable
MinWeightEdgeMap& operator=( const MinWeightEdgeMap& ); // non copyable
public:
typedef MERGE_GRAPH MergeGraphType;
typedef typename MergeGraphType::Edge Edge;
typedef EDGE_MAP EdgeMapType;
typedef NODE_MAP NodeMapType;
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void operator[](const Edge edge)const{
return MultiArrayView<1,T>::operator()(mergeGraph_.id(edge));
}
void mergeEdges(const IdType a,const IdType b){
this->operator()(a)=getMixedWeight(a);
pq_.deleteValue(b);
}
void eraseEdge(const IdType label){
pq_.deleteValue(label);
}
template<class CB>
CB eraseEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMap<T,MERGE_GRAPH,EDGE_MAP,NODE_MAP>::eraseEdge), this , _1);
}
template<class CB>
CB mergeEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMap<T,MERGE_GRAPH,EDGE_MAP,NODE_MAP>::mergeEdges), this , _1,_2);
}
MinWeightEdgeMap(const MergeGraphType & mergeGraph,ArrayViewType & array,const EdgeMapType & edgeMap,const NodeMapType & nodeMap)
: ArrayViewType(array),
mergeGraph_(mergeGraph),
edgeMap_(edgeMap),
nodeMap_(nodeMap),
pq_(mergeGraph.initNumberOfEdges()){
// initalize mixed weights and initalize pq
for(IdType l=0;l<mergeGraph_.initNumberOfEdges();++l){
const T mixedWeight = getMixedWeight(l);
this->operator()(l)=mixedWeight;
pq_.insert(l,mixedWeight);
}
}
IdType minWeightEdgeLabel(){
IdType minLabel = pq_.minIndex();
while(mergeGraph_.hasEdgeId(minLabel)==false){
pq_.deleteValue(minLabel);
IdType minLabel = pq_.minIndex();
}
return minLabel;
}
private:
T getMixedWeight(const IdType label)const{
return edgeMap_(label);
}
void changePqWeight(const IdType l,const T newWeigt){
pq_.changeValue(l,newWeigt);
}
const MergeGraphType & mergeGraph_;
const EdgeMapType & edgeMap_;
const NodeMapType & nodeMap_;
vigra::MinIndexedPQ<T> pq_;
};
} // end namespace view_maps
} // end namespace vigra
#endif // VIGRA_MULTI_ARRAY_MAP_HXX<commit_msg>BROKEN<commit_after>#ifndef VIGRA_MULTI_ARRAY_MAP_HXX
#define VIGRA_MULTI_ARRAY_MAP_HXX
/* boost */
#include <boost/function.hpp>
/* vigra */
#include <vigra/multi_array.hxx>
#include <vigra/accumulator.hxx>
/* vigra - merge graph */
#include <vigra/merge_graph/min_indexed_pq.hxx>
namespace vigra{
namespace view_maps {
template<unsigned int DIM,class T>
class SumMap;
template<class T>
class SumMap<0,T> : public MultiArrayView<1,T> {
private:
SumMap(); // non empty-construction
SumMap( const SumMap& other ); // non construction-copyable
SumMap& operator=( const SumMap& ); // non copyable
public:
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
//const value_type & operator[](const IdType label)const{
// return this->operator(label);
//}
void merge(const IdType a,const IdType b){
this->operator()(a)+=this->operator()(b);
}
template<class CB>
CB mergeCallback(){
CB cb;
cb = boost::bind(boost::mem_fn(&SumMap<0,T>::merge), this , _1,_2);
return cb;
}
SumMap(ArrayViewType & array)
: ArrayViewType(array){
}
};
template<unsigned int DIM, class T>
class SumMap : public MultiArrayView<DIM+1,T> {
private:
SumMap(); // non empty-construction
SumMap( const SumMap& other ); // non construction-copyable
SumMap& operator=( const SumMap& ); // non copyable
public:
typedef MultiArrayView<DIM+1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
//const value_type & operator[](const IdType label)const{
// return this->operator(label);
//}
void merge(const IdType a,const IdType b){
this->bindInner(a)+=this->bindInner(b);
}
template<class CB>
CB mergeCallback(){
CB cb;
cb = boost::bind(boost::mem_fn(&SumMap<DIM,T>::merge), this , _1,_2);
return cb;
}
SumMap(ArrayViewType & array)
: ArrayViewType(array){
}
};
template<unsigned int DIM,class T,class WEIGHT_MAP>
class WeightedMeanMap;
template<class T,class WEIGHT_MAP>
class WeightedMeanMap<0,T,WEIGHT_MAP> : public MultiArrayView<1,T> {
private:
WeightedMeanMap(); // non empty-construction
WeightedMeanMap( const WeightedMeanMap& other ); // non construction-copyable
WeightedMeanMap& operator=( const WeightedMeanMap& ); // non copyable
public:
typedef WEIGHT_MAP WeightMapType;
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void merge(const IdType a,const IdType b){
const T va=this->operator()(a);
const T vb=this->operator()(b);
const T wa=weightMap_(a);
const T wb=weightMap_(b);
this->operator()(a)=(va*wa + vb*wb)/(wa+wb);
}
template<class CB>
CB mergeCallback(){
return boost::bind(boost::mem_fn(&WeightedMeanMap<0,T,WEIGHT_MAP>::merge), this , _1,_2);
}
WeightedMeanMap(ArrayViewType & array,const WeightMapType & weightMap)
: ArrayViewType(array),
weightMap_(weightMap){
}
private:
const WeightMapType & weightMap_;
};
template<unsigned int DIM,class T,class WEIGHT_MAP>
class WeightedMeanMap : public MultiArrayView<DIM+1,T> {
private:
WeightedMeanMap(); // non empty-construction
WeightedMeanMap( const WeightedMeanMap& other ); // non construction-copyable
WeightedMeanMap& operator=( const WeightedMeanMap& ); // non copyable
public:
typedef WEIGHT_MAP WeightMapType;
typedef MultiArrayView<DIM+1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void merge(const IdType a,const IdType b){
const T wa=weightMap_(a);
const T wb=weightMap_(b);
vigra::MultiArrayView<DIM,T> va = this->bindInner(a);
vigra::MultiArray<DIM,T> vb = this->bindInner(b);
va=(va*wa+vb*wb);
//va*=wa;
//vb*=wb;
//va+=vb;
//va/=(wa+wb);
//vb/=wb;
}
template<class CB>
CB mergeCallback(){
return boost::bind(boost::mem_fn(&WeightedMeanMap<DIM,T,WEIGHT_MAP>::merge), this , _1,_2);
}
WeightedMeanMap(ArrayViewType & array,const WeightMapType & weightMap)
: ArrayViewType(array),
weightMap_(weightMap){
}
private:
const WeightMapType & weightMap_;
};
template<class T,class MERGE_GRAPH>
class MinWeightEdgeMapSimple : public MultiArrayView<1,T> {
private:
MinWeightEdgeMapSimple(); // non empty-construction
MinWeightEdgeMapSimple( const MinWeightEdgeMapSimple& other ); // non construction-copyable
MinWeightEdgeMapSimple& operator=( const MinWeightEdgeMapSimple& ); // non copyable
public:
typedef MERGE_GRAPH MergeGraphType;
typedef typename MergeGraphType::Edge Edge;
typedef typename MergeGraphType::EdgeIt EdgeIt;
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void operator[](const Edge edge)const{
return MultiArrayView<1,T>::operator()(mergeGraph_.id(edge));
}
void mergeEdges(const IdType a,const IdType b){
pq_.deleteValue(b);
changePqWeight(a,this->operator()(a));
}
void eraseEdge(const IdType label){
pq_.deleteValue(label);
}
template<class CB>
CB eraseEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMapSimple<T,MERGE_GRAPH>::eraseEdge), this , _1);
}
template<class CB>
CB mergeEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMapSimple<T,MERGE_GRAPH>::mergeEdges), this , _1,_2);
}
MinWeightEdgeMapSimple(const MergeGraphType & mergeGraph,ArrayViewType & array)
: ArrayViewType(array),
mergeGraph_(mergeGraph),
pq_(mergeGraph.maxEdgeId()+1){
for(EdgeIt e(mergeGraph);e!=lemon::INVALID;++e){
const Edge edge = *e;
const IdType edgeId = mergeGraph_.id(edge);
pq_.insert(edgeId,this->operator()(edgeId));
}
}
IdType minWeightEdgeLabel(){
IdType minLabel = pq_.minIndex();
while(mergeGraph_.hasEdgeId(minLabel)==false){
pq_.deleteValue(minLabel);
IdType minLabel = pq_.minIndex();
}
return minLabel;
}
private:
void changePqWeight(const IdType l,const T newWeigt){
pq_.changeValue(l,newWeigt);
}
const MergeGraphType & mergeGraph_;
vigra::MinIndexedPQ<T> pq_;
};
template<class T,class MERGE_GRAPH,class EDGE_MAP,class NODE_MAP>
class MinWeightEdgeMap : public MultiArrayView<1,T> {
private:
MinWeightEdgeMap(); // non empty-construction
MinWeightEdgeMap( const MinWeightEdgeMap& other ); // non construction-copyable
MinWeightEdgeMap& operator=( const MinWeightEdgeMap& ); // non copyable
public:
typedef MERGE_GRAPH MergeGraphType;
typedef typename MergeGraphType::Edge Edge;
typedef EDGE_MAP EdgeMapType;
typedef NODE_MAP NodeMapType;
typedef MultiArrayView<1,T> ArrayViewType;
typedef Int32 IdType;
typedef T value_type;
void operator[](const Edge edge)const{
return MultiArrayView<1,T>::operator()(mergeGraph_.id(edge));
}
void mergeEdges(const IdType a,const IdType b){
this->operator()(a)=getMixedWeight(a);
pq_.deleteValue(b);
}
void eraseEdge(const IdType label){
pq_.deleteValue(label);
}
template<class CB>
CB eraseEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMap<T,MERGE_GRAPH,EDGE_MAP,NODE_MAP>::eraseEdge), this , _1);
}
template<class CB>
CB mergeEdgeCallback(){
return boost::bind(boost::mem_fn(&MinWeightEdgeMap<T,MERGE_GRAPH,EDGE_MAP,NODE_MAP>::mergeEdges), this , _1,_2);
}
MinWeightEdgeMap(const MergeGraphType & mergeGraph,ArrayViewType & array,const EdgeMapType & edgeMap,const NodeMapType & nodeMap)
: ArrayViewType(array),
mergeGraph_(mergeGraph),
edgeMap_(edgeMap),
nodeMap_(nodeMap),
pq_(mergeGraph.initNumberOfEdges()){
// initalize mixed weights and initalize pq
for(IdType l=0;l<mergeGraph_.initNumberOfEdges();++l){
const T mixedWeight = getMixedWeight(l);
this->operator()(l)=mixedWeight;
pq_.insert(l,mixedWeight);
}
}
IdType minWeightEdgeLabel(){
IdType minLabel = pq_.minIndex();
while(mergeGraph_.hasEdgeId(minLabel)==false){
pq_.deleteValue(minLabel);
IdType minLabel = pq_.minIndex();
}
return minLabel;
}
private:
T getMixedWeight(const IdType label)const{
return edgeMap_(label);
}
void changePqWeight(const IdType l,const T newWeigt){
pq_.changeValue(l,newWeigt);
}
const MergeGraphType & mergeGraph_;
const EdgeMapType & edgeMap_;
const NodeMapType & nodeMap_;
vigra::MinIndexedPQ<T> pq_;
};
} // end namespace view_maps
} // end namespace vigra
#endif // VIGRA_MULTI_ARRAY_MAP_HXX<|endoftext|> |
<commit_before>#include <Percolation_Sim.h>
int main() {
// Construct Network
Network net("name", false);
net.populate(10001);
net.erdos_renyi(5);
for (int i = 0; i < 10001; i++){
// Choose and run simulation
Percolation_Sim sim(&net);
sim.set_transmissibility(0.2);
sim.rand_infect(10);
sim.run_simulation();
cout << sim.epidemic_size() << endl;
sim.reset();
}
return 0;
}
<commit_msg>minor change to header<commit_after>//example code
#include <Percolation_Sim.h>
int main() {
// Construct Network
Network net("name", false);
net.populate(10001);
net.erdos_renyi(5);
for (int i = 0; i < 10001; i++){
// Choose and run simulation
Percolation_Sim sim(&net);
sim.set_transmissibility(0.2);
sim.rand_infect(10);
sim.run_simulation();
cout << sim.epidemic_size() << endl;
sim.reset();
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file
* NearestNeighborFLANN.cpp
*
* @date: Jan 5, 2010
* @author: sblume
*/
#include "NearestNeighborFLANN.h"
#include <assert.h>
#include <stdexcept>
#include <cmath>
using std::runtime_error;
namespace BRICS_3D {
NearestNeighborFLANN::NearestNeighborFLANN() {
this->dimension = -1;
this->maxDistance = -1; //default = disable
this->dataMatrix = NULL;
this->index_id = NULL;
this->parameters.log_level = LOG_NONE;
this->parameters.log_destination = NULL;
this->parameters.algorithm = KDTREE;
this->parameters.checks = 32;
this->parameters.trees = 8;
this->parameters.branching = 32;
this->parameters.iterations = 7;
this->parameters.target_precision = -1;
}
NearestNeighborFLANN::~NearestNeighborFLANN() {
flann_free_index(index_id, ¶meters);
}
void NearestNeighborFLANN::setData(vector<vector<float> >* data) {
assert(false); //TODO: implement
}
void NearestNeighborFLANN::setData(vector<vector<double> >* data) {
assert(data != 0);
if (index_id != 0) { // clean up if previous versions exist
flann_free_index(index_id, ¶meters);
}
dimension = (*data)[0].size();
rows = data->size();
cols = dimension;
dataMatrix = new float[rows * cols];
// convert data
int matrixIndex = 0;
for (int rowIndex = 0; rowIndex < rows; ++rowIndex) {
for (int j = 0; j < dimension; ++j) {
dataMatrix[matrixIndex + j] = static_cast<float> ( (*data)[rowIndex][j] );
}
matrixIndex += dimension;
}
// create underlying data structure
index_id = flann_build_index(dataMatrix, rows, cols, &speedup, ¶meters);
}
void NearestNeighborFLANN::setData(PointCloud3D* data) {
assert(data != 0);
if (index_id != 0) { // clean up if previous versions exist
flann_free_index(index_id, ¶meters);
}
dimension = 3; //we work with a 3D points...
rows = data->getSize();
cols = dimension;
dataMatrix = new float[rows * cols];
// convert data
int matrixIndex = 0;
for (int rowIndex = 0; rowIndex < rows; ++rowIndex) {
dataMatrix[matrixIndex + 0] = static_cast<float> ((*data->getPointCloud())[rowIndex].getX());
dataMatrix[matrixIndex + 1] = static_cast<float> ((*data->getPointCloud())[rowIndex].getY());
dataMatrix[matrixIndex + 2] = static_cast<float> ((*data->getPointCloud())[rowIndex].getZ());
matrixIndex += 3;
}
// create underlying data structure
index_id = flann_build_index(dataMatrix, rows, cols, &speedup, ¶meters);
}
void NearestNeighborFLANN::findNearestNeighbors(vector<float>* query, std::vector<int>* resultIndices, unsigned int k) {
assert(false); //TODO: implement
}
void NearestNeighborFLANN::findNearestNeighbors(vector<double>* query, std::vector<int>* resultIndices, unsigned int k) {
assert (query != 0);
assert (resultIndices != 0);
// assert (static_cast<int>(query->size()) == dimension);
if (static_cast<int>(query->size()) != dimension) {
throw runtime_error("Mismatch of query and data dimension.");
}
if (static_cast<int>(k) > this->rows) {
throw runtime_error("Number of neighbors k is bigger than the amount of data points.");
}
resultIndices->clear();
int nn = static_cast<int>(k);
const int f = 3;
int tcount = 1;
int result[f];
float dists[f]; //TODO dynamic array (should be nn)
float* queryData = new float[dimension]; //TODO: is there also a double version?!?
for (int i = 0; i < dimension; ++i) {
queryData[i] = static_cast<float>( (*query)[i] );
}
flann_find_nearest_neighbors_index(index_id, queryData, tcount, result, dists, nn, parameters.checks, ¶meters);
BRICS_3D::Coordinate resultDistance; //distance has same data-type as Coordinate, although the meaning is different TODO: global distance typedef?
int resultIndex;
for (int i = 0; i < nn; i++) {
resultDistance = static_cast<BRICS_3D::Coordinate>(sqrt(dists[i])); //seems to return squared distance (although documentation does not suggest)
resultIndex = result[i];
if (resultDistance <= maxDistance || maxDistance < 0.0) { //if max distance is < 0 then the distance should have no influence
resultIndices->push_back(resultIndex);
}
}
delete[] queryData;
}
void NearestNeighborFLANN::findNearestNeighbors(Point3D* query, std::vector<int>* resultIndices, unsigned int k) {
assert (query != 0);
assert (resultIndices != 0);
assert (dimension == 3);
if (static_cast<int>(k) > this->rows) {
throw runtime_error("Number of neighbors k is bigger than the amount of data points.");
}
resultIndices->clear();
int nn = static_cast<int>(k);
int tcount = 1;
int result[21];
float dists[21]; //TODO dynamic array
float* queryData = new float[dimension];
queryData[0] = static_cast<float> (query->getX());
queryData[1] = static_cast<float> (query->getY());
queryData[2] = static_cast<float> (query->getZ());
flann_find_nearest_neighbors_index(index_id, queryData, tcount, result, dists, nn, parameters.checks, ¶meters);
BRICS_3D::Coordinate resultDistance; //distance has same data-type as Coordinate, although the meaning is different TODO: global distance typedef?
int resultIndex;
for (int i = 0; i < nn; i++) {
resultDistance = static_cast<BRICS_3D::Coordinate>(sqrt(dists[i])); //seems to return squared distance (although documentation does not suggest)
resultIndex = result[i];
if (resultDistance <= maxDistance || maxDistance < 0.0) { //if max distance is < 0 then the distance should have no influence
resultIndices->push_back(resultIndex);
}
}
delete[] queryData;
}
FLANNParameters NearestNeighborFLANN::getParameters() const {
return parameters;
}
void NearestNeighborFLANN::setParameters(FLANNParameters p) {
this->parameters = p;
}
float NearestNeighborFLANN::getSpeedup() const {
return speedup;
}
}
/* EOF */
<commit_msg>Bugfix for FLANN Wrapper.<commit_after>/**
* @file
* NearestNeighborFLANN.cpp
*
* @date: Jan 5, 2010
* @author: sblume
*/
#include "NearestNeighborFLANN.h"
#include <assert.h>
#include <stdexcept>
#include <cmath>
using std::runtime_error;
namespace BRICS_3D {
NearestNeighborFLANN::NearestNeighborFLANN() {
this->dimension = -1;
this->maxDistance = -1; //default = disable
this->dataMatrix = NULL;
this->index_id = NULL;
this->parameters.log_level = LOG_NONE;
this->parameters.log_destination = NULL;
this->parameters.algorithm = KDTREE;
this->parameters.checks = 32;
this->parameters.trees = 8;
this->parameters.branching = 32;
this->parameters.iterations = 7;
this->parameters.target_precision = -1;
}
NearestNeighborFLANN::~NearestNeighborFLANN() {
flann_free_index(index_id, ¶meters);
}
void NearestNeighborFLANN::setData(vector<vector<float> >* data) {
assert(false); //TODO: implement
}
void NearestNeighborFLANN::setData(vector<vector<double> >* data) {
assert(data != 0);
if (index_id != 0) { // clean up if previous versions exist
flann_free_index(index_id, ¶meters);
}
dimension = (*data)[0].size();
rows = data->size();
cols = dimension;
dataMatrix = new float[rows * cols];
// convert data
int matrixIndex = 0;
for (int rowIndex = 0; rowIndex < rows; ++rowIndex) {
for (int j = 0; j < dimension; ++j) {
dataMatrix[matrixIndex + j] = static_cast<float> ( (*data)[rowIndex][j] );
}
matrixIndex += dimension;
}
// create underlying data structure
index_id = flann_build_index(dataMatrix, rows, cols, &speedup, ¶meters);
}
void NearestNeighborFLANN::setData(PointCloud3D* data) {
assert(data != 0);
if (index_id != 0) { // clean up if previous versions exist
flann_free_index(index_id, ¶meters);
}
dimension = 3; //we work with a 3D points...
rows = data->getSize();
cols = dimension;
dataMatrix = new float[rows * cols];
// convert data
int matrixIndex = 0;
for (int rowIndex = 0; rowIndex < rows; ++rowIndex) {
dataMatrix[matrixIndex + 0] = static_cast<float> ((*data->getPointCloud())[rowIndex].getX());
dataMatrix[matrixIndex + 1] = static_cast<float> ((*data->getPointCloud())[rowIndex].getY());
dataMatrix[matrixIndex + 2] = static_cast<float> ((*data->getPointCloud())[rowIndex].getZ());
matrixIndex += 3;
}
// create underlying data structure
index_id = flann_build_index(dataMatrix, rows, cols, &speedup, ¶meters);
}
void NearestNeighborFLANN::findNearestNeighbors(vector<float>* query, std::vector<int>* resultIndices, unsigned int k) {
assert(false); //TODO: implement
}
void NearestNeighborFLANN::findNearestNeighbors(vector<double>* query, std::vector<int>* resultIndices, unsigned int k) {
assert (query != 0);
assert (resultIndices != 0);
// assert (static_cast<int>(query->size()) == dimension);
if (static_cast<int>(query->size()) != dimension) {
throw runtime_error("Mismatch of query and data dimension.");
}
if (static_cast<int>(k) > this->rows) {
throw runtime_error("Number of neighbors k is bigger than the amount of data points.");
}
resultIndices->clear();
int nn = static_cast<int>(k);
int tcount = 1;
int* result = new int[nn];
float* dists = new float[nn];
float* queryData = new float[dimension]; //TODO: is there also a double version?!?
for (int i = 0; i < dimension; ++i) {
queryData[i] = static_cast<float>( (*query)[i] );
}
flann_find_nearest_neighbors_index(index_id, queryData, tcount, result, dists, nn, parameters.checks, ¶meters);
BRICS_3D::Coordinate resultDistance; //distance has same data-type as Coordinate, although the meaning is different TODO: global distance typedef?
int resultIndex;
for (int i = 0; i < nn; i++) {
resultDistance = static_cast<BRICS_3D::Coordinate>(sqrt(dists[i])); //seems to return squared distance (although documentation does not suggest)
resultIndex = result[i];
if (resultDistance <= maxDistance || maxDistance < 0.0) { //if max distance is < 0 then the distance should have no influence
resultIndices->push_back(resultIndex);
}
}
delete[] queryData;
delete[] dists;
delete[] result;
}
void NearestNeighborFLANN::findNearestNeighbors(Point3D* query, std::vector<int>* resultIndices, unsigned int k) {
assert (query != 0);
assert (resultIndices != 0);
assert (dimension == 3);
if (static_cast<int>(k) > this->rows) {
throw runtime_error("Number of neighbors k is bigger than the amount of data points.");
}
resultIndices->clear();
int nn = static_cast<int>(k);
int tcount = 1;
int* result = new int[nn];
float* dists = new float[nn];
float* queryData = new float[dimension];
queryData[0] = static_cast<float> (query->getX());
queryData[1] = static_cast<float> (query->getY());
queryData[2] = static_cast<float> (query->getZ());
flann_find_nearest_neighbors_index(index_id, queryData, tcount, result, dists, nn, parameters.checks, ¶meters);
BRICS_3D::Coordinate resultDistance; //distance has same data-type as Coordinate, although the meaning is different TODO: global distance typedef?
int resultIndex;
for (int i = 0; i < nn; i++) {
resultDistance = static_cast<BRICS_3D::Coordinate>(sqrt(dists[i])); //seems to return squared distance (although documentation does not suggest)
resultIndex = result[i];
if (resultDistance <= maxDistance || maxDistance < 0.0) { //if max distance is < 0 then the distance should have no influence
resultIndices->push_back(resultIndex);
}
}
delete[] queryData;
delete[] dists;
delete[] result;
}
FLANNParameters NearestNeighborFLANN::getParameters() const {
return parameters;
}
void NearestNeighborFLANN::setParameters(FLANNParameters p) {
this->parameters = p;
}
float NearestNeighborFLANN::getSpeedup() const {
return speedup;
}
}
/* EOF */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef URBI_SOCKET_HH
# define URBI_SOCKET_HH
#include <libport/asio.hh>
#include <urbi/uobject.hh>
namespace urbi
{
/** Use this class instead of libport::Socket when you need an UObject which
* is also a Socket.
*/
class UObjectSocket: public libport::Socket
{
public:
UObjectSocket(boost::asio::io_service& io = libport::get_io_service())
: libport::Socket(io)
{
}
~UObjectSocket()
{
while (!checkDestructionPermission())
getCurrentContext()->yield_until(
libport::utime() + (libport::utime_t)1000);
}
};
}
#endif
<commit_msg>uobject: close our socket in UObjectSocket destructor to avoid deadlock.<commit_after>/*
* Copyright (C) 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef URBI_SOCKET_HH
# define URBI_SOCKET_HH
#include <libport/asio.hh>
#include <urbi/uobject.hh>
namespace urbi
{
/** Use this class instead of libport::Socket when you need an UObject which
* is also a Socket.
*/
class UObjectSocket: public libport::Socket
{
public:
UObjectSocket(boost::asio::io_service& io = libport::get_io_service())
: libport::Socket(io)
{
}
~UObjectSocket()
{
close();
wasDestroyed();
while (!checkDestructionPermission())
getCurrentContext()->yield_until(
libport::utime() + (libport::utime_t)1000);
}
};
}
#endif
<|endoftext|> |
<commit_before>#include "platform/chunks_download_strategy.hpp"
#include "coding/file_writer.hpp"
#include "coding/file_reader.hpp"
#include "coding/varint.hpp"
#include "base/logging.hpp"
#include "std/algorithm.hpp"
namespace downloader
{
ChunksDownloadStrategy::ChunksDownloadStrategy(vector<string> const & urls)
{
// init servers list
for (size_t i = 0; i < urls.size(); ++i)
m_servers.push_back(ServerT(urls[i], SERVER_READY));
}
pair<ChunksDownloadStrategy::ChunkT *, int>
ChunksDownloadStrategy::GetChunk(RangeT const & range)
{
vector<ChunkT>::iterator i = lower_bound(m_chunks.begin(), m_chunks.end(), range.first, LessChunks());
if (i != m_chunks.end() && i->m_pos == range.first)
{
ASSERT_EQUAL ( (i+1)->m_pos, range.second + 1, () );
return pair<ChunkT *, int>(&(*i), distance(m_chunks.begin(), i));
}
else
{
LOG(LERROR, ("Downloader error. Invalid chunk range: ", range));
return pair<ChunkT *, int>(static_cast<ChunkT *>(0), -1);
}
}
void ChunksDownloadStrategy::InitChunks(int64_t fileSize, int64_t chunkSize, ChunkStatusT status)
{
m_chunks.reserve(fileSize / chunkSize + 2);
for (int64_t i = 0; i < fileSize; i += chunkSize)
m_chunks.push_back(ChunkT(i, status));
m_chunks.push_back(ChunkT(fileSize, CHUNK_AUX));
}
void ChunksDownloadStrategy::AddChunk(RangeT const & range, ChunkStatusT status)
{
ASSERT_LESS_OR_EQUAL ( range.first, range.second, () );
if (m_chunks.empty())
{
ASSERT_EQUAL ( range.first, 0, () );
m_chunks.push_back(ChunkT(range.first, status));
}
else
{
ASSERT_EQUAL ( m_chunks.back().m_pos, range.first, () );
m_chunks.back().m_status = status;
}
m_chunks.push_back(ChunkT(range.second + 1, CHUNK_AUX));
}
void ChunksDownloadStrategy::SaveChunks(int64_t fileSize, string const & fName)
{
if (!m_chunks.empty())
{
try
{
FileWriter w(fName);
WriteVarInt(w, fileSize);
w.Write(&m_chunks[0], sizeof(ChunkT) * m_chunks.size());
return;
}
catch (FileWriter::Exception const & e)
{
LOG(LWARNING, ("Can't save chunks to file", e.Msg()));
}
}
// Delete if no chunks or some error occured.
(void)FileWriter::DeleteFileX(fName);
}
int64_t ChunksDownloadStrategy::LoadOrInitChunks(string const & fName, int64_t fileSize,
int64_t chunkSize)
{
ASSERT ( fileSize > 0, () );
ASSERT ( chunkSize > 0, () );
try
{
FileReader r(fName, true /* with exceptions */);
ReaderSource<FileReader> src(r);
int64_t const readedSize = ReadVarInt<int64_t>(src);
if (readedSize == fileSize)
{
// Load chunks.
uint64_t const size = src.Size();
int const stSize = sizeof(ChunkT);
size_t const count = size / stSize;
ASSERT_EQUAL(size, stSize * count, ());
m_chunks.resize(count);
src.Read(&m_chunks[0], stSize * count);
// Reset status "downloading" to "free".
int64_t downloadedSize = 0;
for (size_t i = 0; i < count-1; ++i)
{
if (m_chunks[i].m_status != CHUNK_COMPLETE)
m_chunks[i].m_status = CHUNK_FREE;
else
downloadedSize += (m_chunks[i+1].m_pos - m_chunks[i].m_pos);
}
return downloadedSize;
}
}
catch (RootException const & e)
{
// Usually - file not exists or Reader::Exception.
LOG(LDEBUG, (e.Msg()));
}
InitChunks(fileSize, chunkSize);
return 0;
}
string ChunksDownloadStrategy::ChunkFinished(bool success, RangeT const & range)
{
pair<ChunkT *, int> res = GetChunk(range);
string url;
// find server which was downloading this chunk
if (res.first)
{
for (size_t s = 0; s < m_servers.size(); ++s)
{
if (m_servers[s].m_chunkIndex == res.second)
{
url = m_servers[s].m_url;
if (success)
{
// mark server as free and chunk as ready
m_servers[s].m_chunkIndex = SERVER_READY;
res.first->m_status = CHUNK_COMPLETE;
}
else
{
LOG(LINFO, ("Thread for url", m_servers[s].m_url,
"failed to download chunk number", m_servers[s].m_chunkIndex));
// remove failed server and mark chunk as free
m_servers.erase(m_servers.begin() + s);
res.first->m_status = CHUNK_FREE;
}
break;
}
}
}
return url;
}
ChunksDownloadStrategy::ResultT
ChunksDownloadStrategy::NextChunk(string & outUrl, RangeT & range)
{
// If no servers at all.
if (m_servers.empty())
return EDownloadFailed;
// Find first free server.
ServerT * server = 0;
for (size_t i = 0; i < m_servers.size(); ++i)
{
if (m_servers[i].m_chunkIndex == SERVER_READY)
{
server = &m_servers[i];
break;
}
}
if (server == 0)
return ENoFreeServers;
bool allChunksDownloaded = true;
// Find first free chunk.
for (size_t i = 0; i < m_chunks.size()-1; ++i)
{
switch (m_chunks[i].m_status)
{
case CHUNK_FREE:
server->m_chunkIndex = static_cast<int>(i);
outUrl = server->m_url;
range.first = m_chunks[i].m_pos;
range.second = m_chunks[i+1].m_pos - 1;
m_chunks[i].m_status = CHUNK_DOWNLOADING;
return ENextChunk;
case CHUNK_DOWNLOADING:
allChunksDownloaded = false;
break;
}
}
return (allChunksDownloaded ? EDownloadSucceeded : ENoFreeServers);
}
} // namespace downloader
<commit_msg>Review fixes.<commit_after>#include "platform/chunks_download_strategy.hpp"
#include "coding/file_writer.hpp"
#include "coding/file_reader.hpp"
#include "coding/varint.hpp"
#include "base/logging.hpp"
#include "std/algorithm.hpp"
namespace downloader
{
ChunksDownloadStrategy::ChunksDownloadStrategy(vector<string> const & urls)
{
// init servers list
for (size_t i = 0; i < urls.size(); ++i)
m_servers.push_back(ServerT(urls[i], SERVER_READY));
}
pair<ChunksDownloadStrategy::ChunkT *, int>
ChunksDownloadStrategy::GetChunk(RangeT const & range)
{
vector<ChunkT>::iterator i = lower_bound(m_chunks.begin(), m_chunks.end(), range.first, LessChunks());
if (i != m_chunks.end() && i->m_pos == range.first)
{
ASSERT_EQUAL ( (i+1)->m_pos, range.second + 1, () );
return pair<ChunkT *, int>(&(*i), distance(m_chunks.begin(), i));
}
else
{
LOG(LERROR, ("Downloader error. Invalid chunk range: ", range));
return pair<ChunkT *, int>(static_cast<ChunkT *>(0), -1);
}
}
void ChunksDownloadStrategy::InitChunks(int64_t fileSize, int64_t chunkSize, ChunkStatusT status)
{
m_chunks.reserve(fileSize / chunkSize + 2);
for (int64_t i = 0; i < fileSize; i += chunkSize)
m_chunks.push_back(ChunkT(i, status));
m_chunks.push_back(ChunkT(fileSize, CHUNK_AUX));
}
void ChunksDownloadStrategy::AddChunk(RangeT const & range, ChunkStatusT status)
{
ASSERT_LESS_OR_EQUAL ( range.first, range.second, () );
if (m_chunks.empty())
{
ASSERT_EQUAL ( range.first, 0, () );
m_chunks.push_back(ChunkT(range.first, status));
}
else
{
ASSERT_EQUAL ( m_chunks.back().m_pos, range.first, () );
m_chunks.back().m_status = status;
}
m_chunks.push_back(ChunkT(range.second + 1, CHUNK_AUX));
}
void ChunksDownloadStrategy::SaveChunks(int64_t fileSize, string const & fName)
{
if (!m_chunks.empty())
{
try
{
FileWriter w(fName);
WriteVarInt(w, fileSize);
w.Write(&m_chunks[0], sizeof(ChunkT) * m_chunks.size());
return;
}
catch (FileWriter::Exception const & e)
{
LOG(LWARNING, ("Can't save chunks to file", e.Msg()));
}
}
// Delete if no chunks or some error occured.
(void)FileWriter::DeleteFileX(fName);
}
int64_t ChunksDownloadStrategy::LoadOrInitChunks(string const & fName, int64_t fileSize,
int64_t chunkSize)
{
ASSERT ( fileSize > 0, () );
ASSERT ( chunkSize > 0, () );
try
{
FileReader r(fName, true /* with exceptions */);
ReaderSource<FileReader> src(r);
int64_t const readSize = ReadVarInt<int64_t>(src);
if (readSize == fileSize)
{
// Load chunks.
uint64_t const size = src.Size();
int const stSize = sizeof(ChunkT);
size_t const count = size / stSize;
ASSERT_EQUAL(size, stSize * count, ());
m_chunks.resize(count);
src.Read(&m_chunks[0], stSize * count);
// Reset status "downloading" to "free".
int64_t downloadedSize = 0;
for (size_t i = 0; i < count-1; ++i)
{
if (m_chunks[i].m_status != CHUNK_COMPLETE)
m_chunks[i].m_status = CHUNK_FREE;
else
downloadedSize += (m_chunks[i+1].m_pos - m_chunks[i].m_pos);
}
return downloadedSize;
}
}
catch (FileReader::Exception const & e)
{
// Usually - file not exists or Reader::Exception.
LOG(LDEBUG, (e.Msg()));
}
InitChunks(fileSize, chunkSize);
return 0;
}
string ChunksDownloadStrategy::ChunkFinished(bool success, RangeT const & range)
{
pair<ChunkT *, int> res = GetChunk(range);
string url;
// find server which was downloading this chunk
if (res.first)
{
for (size_t s = 0; s < m_servers.size(); ++s)
{
if (m_servers[s].m_chunkIndex == res.second)
{
url = m_servers[s].m_url;
if (success)
{
// mark server as free and chunk as ready
m_servers[s].m_chunkIndex = SERVER_READY;
res.first->m_status = CHUNK_COMPLETE;
}
else
{
LOG(LINFO, ("Thread for url", m_servers[s].m_url,
"failed to download chunk number", m_servers[s].m_chunkIndex));
// remove failed server and mark chunk as free
m_servers.erase(m_servers.begin() + s);
res.first->m_status = CHUNK_FREE;
}
break;
}
}
}
return url;
}
ChunksDownloadStrategy::ResultT
ChunksDownloadStrategy::NextChunk(string & outUrl, RangeT & range)
{
// If no servers at all.
if (m_servers.empty())
return EDownloadFailed;
// Find first free server.
ServerT * server = 0;
for (size_t i = 0; i < m_servers.size(); ++i)
{
if (m_servers[i].m_chunkIndex == SERVER_READY)
{
server = &m_servers[i];
break;
}
}
if (server == 0)
return ENoFreeServers;
bool allChunksDownloaded = true;
// Find first free chunk.
for (size_t i = 0; i < m_chunks.size()-1; ++i)
{
switch (m_chunks[i].m_status)
{
case CHUNK_FREE:
server->m_chunkIndex = static_cast<int>(i);
outUrl = server->m_url;
range.first = m_chunks[i].m_pos;
range.second = m_chunks[i+1].m_pos - 1;
m_chunks[i].m_status = CHUNK_DOWNLOADING;
return ENextChunk;
case CHUNK_DOWNLOADING:
allChunksDownloaded = false;
break;
}
}
return (allChunksDownloaded ? EDownloadSucceeded : ENoFreeServers);
}
} // namespace downloader
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.