text
stringlengths 54
60.6k
|
---|
<commit_before>/***************************************************************************/
/* Copyright (c) 2014 Linas Vepstas */
/* All rights reserved */
/* */
/* Use of the link grammar parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software. */
/* This license allows free redistribution and use in source and binary */
/* forms, with or without modification, subject to certain conditions. */
/* */
/***************************************************************************/
// This implements a very simple-minded multi-threaded unit test.
// All it does is to make sure the system doesn't crash e.g. due to
// memory allocation conflicts.
#include <thread>
#include <vector>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include "link-grammar/link-includes.h"
static void parse_one_sent(Dictionary dict, Parse_Options opts, const char *sent_str)
{
Sentence sent = sentence_create(sent_str, dict);
if (!sent) {
fprintf (stderr, "Fatal error: Unable to create parser\n");
exit(2);
}
sentence_split(sent, opts);
int num_linkages = sentence_parse(sent, opts);
#if 0
if (num_linkages <= 0) {
fprintf (stderr, "Fatal error: Unable to parse sentence\n");
exit(3);
}
#endif
if (0 < num_linkages)
{
if (10 < num_linkages) num_linkages = 10;
for (int li = 0; li<num_linkages; li++)
{
Linkage linkage = linkage_create(li, sent, opts);
// Short diagram, it wraps.
char * str = linkage_print_diagram(linkage, true, 50);
linkage_free_diagram(str);
str = linkage_print_links_and_domains(linkage);
linkage_free_links_and_domains(str);
str = linkage_print_disjuncts(linkage);
linkage_free_disjuncts(str);
str = linkage_print_constituent_tree(linkage, SINGLE_LINE);
linkage_free_constituent_tree_str(str);
linkage_delete(linkage);
}
}
sentence_delete(sent);
}
static void parse_sents(Dictionary dict, Parse_Options opts, int thread_id, int niter)
{
const char *sents[] = {
"Frank felt vindicated when his long time friend Bill revealed that he was the winner of the competition.",
"Logorrhea, or excessive and often incoherent talkativeness or wordiness, is a social disease.",
"It was covered with bites.",
"I have no idea what that is.",
"His shout had been involuntary, something anybody might have done.",
"Trump, Ryan and McConnell are using the budget process to pay for the GOP’s $1.5 trillion tax scam.",
"We ate popcorn and watched movies on TV for three days.",
"Sweat stood on his brow, fury was bright in his one good eye.",
"One of the things you do when you stop your bicycle is apply the brake.",
"The line extends 10 miles offshore.",
// The English parser will choke on this.
"под броню боевого робота устремились потоки энергии.",
"через четверть часа здесь будет полно полицейских.",
// Rabindranath Tagore
"習近平: 堅守 實體經濟落實高品 質發展",
"文在寅希望半島對話氛 圍在平昌冬奧會後能延續",
"土耳其出兵 搶先機 美土俄棋局怎麼走?",
"默克爾努力獲突破 德社民黨同意開展組閣談判"
};
int nsents = sizeof(sents) / sizeof(const char *);
#define WID 120
#define LIN 4
char junk[LIN*WID];
for (int ln=0; ln<LIN; ln++)
{
char *line = &junk[ln*WID];
for (int w = 0; w < WID; w++)
{
// Ugly junk including stuff that should be
// bad/invalid UTF-8 character sequences.
line[w] = (5*w+1)%30 + (31*ln ^ 0x66);
if (30<w) line[w] += 0x7f;
if (60<w) line[w] += 0x50;
if (90<w) line[w] = line[w-90] ^ line[w-30];
if (0 == w%25) line[w] = ' ';
if (0 == w%23) line[w] = ' ';
if (0 == w%15) line[w] = ' ';
if (0 == w%11) line[w] = ' ';
}
line[WID-1] = 0x0;
}
for (int j=0; j<niter; j += nsents)
{
for (int i=0; i < nsents; ++i)
{
parse_one_sent(dict, opts, sents[i]);
}
for (int ln=0; ln<LIN; ln++)
{
char *line = &junk[ln*WID];
parse_one_sent(dict, opts, line);
}
}
}
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "en_US.UTF-8");
Parse_Options opts = parse_options_create();
dictionary_set_data_dir(DICTIONARY_DIR "/data");
// Dictionary dict = dictionary_create_lang("ru");
Dictionary dict = dictionary_create_lang("en");
if (!dict) {
fprintf (stderr, "Fatal error: Unable to open the dictionary\n");
exit(1);
}
int n_threads = 10;
int niter = 100;
printf("Creating %d threads, each parsing %d sentences\n",
n_threads, niter);
std::vector<std::thread> thread_pool;
for (int i=0; i < n_threads; i++) {
thread_pool.push_back(std::thread(parse_sents, dict, opts, i, niter));
}
// Wait for all threads to complete
for (std::thread& t : thread_pool) t.join();
printf("Done with multi-threaded parsing\n");
dictionary_delete(dict);
parse_options_delete(opts);
return 0;
}
<commit_msg>Disable spell-guessing on bad sentences<commit_after>/***************************************************************************/
/* Copyright (c) 2014 Linas Vepstas */
/* All rights reserved */
/* */
/* Use of the link grammar parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software. */
/* This license allows free redistribution and use in source and binary */
/* forms, with or without modification, subject to certain conditions. */
/* */
/***************************************************************************/
// This implements a very simple-minded multi-threaded unit test.
// All it does is to make sure the system doesn't crash e.g. due to
// memory allocation conflicts.
#include <thread>
#include <vector>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include "link-grammar/link-includes.h"
static void parse_one_sent(Dictionary dict, Parse_Options opts, const char *sent_str)
{
Sentence sent = sentence_create(sent_str, dict);
if (!sent) {
fprintf (stderr, "Fatal error: Unable to create parser\n");
exit(2);
}
sentence_split(sent, opts);
int num_linkages = sentence_parse(sent, opts);
#if 0
if (num_linkages <= 0) {
fprintf (stderr, "Fatal error: Unable to parse sentence\n");
exit(3);
}
#endif
if (0 < num_linkages)
{
if (10 < num_linkages) num_linkages = 10;
for (int li = 0; li<num_linkages; li++)
{
Linkage linkage = linkage_create(li, sent, opts);
// Short diagram, it wraps.
char * str = linkage_print_diagram(linkage, true, 50);
linkage_free_diagram(str);
str = linkage_print_links_and_domains(linkage);
linkage_free_links_and_domains(str);
str = linkage_print_disjuncts(linkage);
linkage_free_disjuncts(str);
str = linkage_print_constituent_tree(linkage, SINGLE_LINE);
linkage_free_constituent_tree_str(str);
linkage_delete(linkage);
}
}
sentence_delete(sent);
}
static void parse_sents(Dictionary dict, Parse_Options opts, int thread_id, int niter)
{
const char *sents[] = {
"Frank felt vindicated when his long time friend Bill revealed that he was the winner of the competition.",
"Logorrhea, or excessive and often incoherent talkativeness or wordiness, is a social disease.",
"It was covered with bites.",
"I have no idea what that is.",
"His shout had been involuntary, something anybody might have done.",
"Trump, Ryan and McConnell are using the budget process to pay for the GOP’s $1.5 trillion tax scam.",
"We ate popcorn and watched movies on TV for three days.",
"Sweat stood on his brow, fury was bright in his one good eye.",
"One of the things you do when you stop your bicycle is apply the brake.",
"The line extends 10 miles offshore.",
// The English parser will choke on this.
"под броню боевого робота устремились потоки энергии.",
"через четверть часа здесь будет полно полицейских.",
// Rabindranath Tagore
"習近平: 堅守 實體經濟落實高品 質發展",
"文在寅希望半島對話氛 圍在平昌冬奧會後能延續",
"土耳其出兵 搶先機 美土俄棋局怎麼走?",
"默克爾努力獲突破 德社民黨同意開展組閣談判"
};
int nsents = sizeof(sents) / sizeof(const char *);
#define WID 120
#define LIN 4
char junk[LIN*WID];
for (int ln=0; ln<LIN; ln++)
{
char *line = &junk[ln*WID];
for (int w = 0; w < WID; w++)
{
// Ugly junk including stuff that should be
// bad/invalid UTF-8 character sequences.
line[w] = ((thread_id+1)*w+1)%30 + (31*ln ^ 0x66);
if (30<w) line[w] += 0x7f;
if (60<w) line[w] += 0x50;
if (90<w) line[w] = line[w-90] ^ line[w-30];
if (0 == w%25) line[w] = ' ';
if (0 == w%23) line[w] = ' ';
if (0 == w%15) line[w] = ' ';
if (0 == w%11) line[w] = ' ';
}
line[WID-1] = 0x0;
}
for (int j=0; j<niter; j += (nsents+LIN))
{
for (int i=0; i < nsents; ++i)
{
parse_one_sent(dict, opts, sents[i]);
}
for (int ln=0; ln<LIN; ln++)
{
char *line = &junk[ln*WID];
parse_one_sent(dict, opts, line);
}
}
}
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "en_US.UTF-8");
Parse_Options opts = parse_options_create();
parse_options_set_spell_guess(opts, 0);
dictionary_set_data_dir(DICTIONARY_DIR "/data");
// Dictionary dict = dictionary_create_lang("ru");
Dictionary dict = dictionary_create_lang("en");
if (!dict) {
fprintf (stderr, "Fatal error: Unable to open the dictionary\n");
exit(1);
}
int n_threads = 10;
int niter = 300;
printf("Creating %d threads, each parsing %d sentences\n",
n_threads, niter);
std::vector<std::thread> thread_pool;
for (int i=0; i < n_threads; i++) {
thread_pool.push_back(std::thread(parse_sents, dict, opts, i, niter));
}
// Wait for all threads to complete
for (std::thread& t : thread_pool) t.join();
printf("Done with multi-threaded parsing\n");
dictionary_delete(dict);
parse_options_delete(opts);
return 0;
}
<|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 "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
namespace prerender {
namespace {
int omnibox_exact_group_id = 0;
int omnibox_exact_full_group_id = 0;
const char* kOmniboxHeuristicNames[] = {
"Exact",
"Exact_Full"
};
COMPILE_ASSERT(arraysize(kOmniboxHeuristicNames) == OMNIBOX_HEURISTIC_MAX,
OmniboxHeuristic_name_count_mismatch);
const char kPrerenderFromOmniboxTrialName[] = "PrerenderFromOmnibox";
const char kPrerenderFromOmniboxHeuristicTrialName[] =
"PrerenderFromOmniboxHeuristic";
const char* NameFromOmniboxHeuristic(OmniboxHeuristic heuristic) {
DCHECK_LT(static_cast<unsigned int>(heuristic),
arraysize(kOmniboxHeuristicNames));
return kOmniboxHeuristicNames[heuristic];
}
} // end namespace
void ConfigurePrerenderFromOmnibox();
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerenderMode)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerenderMode);
if (switch_value == switches::kPrerenderModeSwitchValueAuto) {
prerender_option = PRERENDER_OPTION_AUTO;
} else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderModeSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value ==
switches::kPrerenderModeSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO: {
base::FieldTrial::Probability divisor = 1000;
base::FieldTrial::Probability exp1_probability = 200;
base::FieldTrial::Probability control1_probability = 200;
base::FieldTrial::Probability no_use1_probability = 100;
base::FieldTrial::Probability exp2_probability = 200;
base::FieldTrial::Probability control2_probability = 200;
base::FieldTrial::Probability no_use2_probability = 100;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
exp1_probability = 495;
control1_probability = 5;
no_use1_probability = 0;
exp2_probability = 495;
control2_probability = 5;
no_use2_probability = 0;
}
CHECK_EQ(divisor, exp1_probability + control1_probability +
no_use1_probability + exp2_probability +
control2_probability + no_use2_probability);
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prefetch", divisor,
"ContentPrefetchPrerender1", 2012, 6, 30));
const int kPrerenderExperiment1Group = trial->kDefaultGroupNumber;
const int kPrerenderControl1Group =
trial->AppendGroup("ContentPrefetchPrerenderControl1",
control1_probability);
const int kPrerenderNoUse1Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse1",
no_use1_probability);
const int kPrerenderExperiment2Group =
trial->AppendGroup("ContentPrefetchPrerender2",
exp2_probability);
const int kPrerenderControl2Group =
trial->AppendGroup("ContentPrefetchPrerenderControl2",
control2_probability);
const int kPrerenderNoUse2Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse2",
no_use2_probability);
const int trial_group = trial->group();
if (trial_group == kPrerenderExperiment1Group ||
trial_group == kPrerenderExperiment2Group) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == kPrerenderControl1Group ||
trial_group == kPrerenderControl2Group) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else if (trial_group == kPrerenderNoUse1Group ||
trial_group == kPrerenderNoUse2Group) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);
} else {
NOTREACHED();
}
break;
}
case PRERENDER_OPTION_DISABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
ConfigurePrerenderFromOmnibox();
}
void ConfigurePrerenderFromOmnibox() {
// Field trial to see if we're enabled.
const base::FieldTrial::Probability kDivisor = 100;
const base::FieldTrial::Probability kEnabledProbability = 40;
scoped_refptr<base::FieldTrial> enabled_trial(
new base::FieldTrial(kPrerenderFromOmniboxTrialName, kDivisor,
"OmniboxPrerenderDisabled", 2012, 8, 30));
enabled_trial->AppendGroup("OmniboxPrerenderEnabled", kEnabledProbability);
// Field trial to see which heuristic to use.
const base::FieldTrial::Probability kExactFullProbability = 50;
scoped_refptr<base::FieldTrial> heuristic_trial(
new base::FieldTrial(kPrerenderFromOmniboxHeuristicTrialName, kDivisor,
"OriginalAlgorithm", 2012, 8, 30));
omnibox_exact_group_id = base::FieldTrial::kDefaultGroupNumber;
omnibox_exact_full_group_id =
heuristic_trial->AppendGroup("ExactFullAlgorithm", kExactFullProbability);
}
bool IsOmniboxEnabled(Profile* profile) {
if (!profile || profile->IsOffTheRecord())
return false;
if (!PrerenderManager::IsPrerenderingPossible())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrerenderFromOmnibox)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPrerenderFromOmnibox);
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)
return true;
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)
return false;
DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);
}
if (!MetricsServiceHelper::IsMetricsReportingEnabled())
return false;
const int group =
base::FieldTrialList::FindValue(kPrerenderFromOmniboxTrialName);
return group != base::FieldTrial::kNotFinalized &&
group != base::FieldTrial::kDefaultGroupNumber;
}
OmniboxHeuristic GetOmniboxHeuristicToUse() {
const int group =
base::FieldTrialList::FindValue(kPrerenderFromOmniboxHeuristicTrialName);
if (group == omnibox_exact_group_id)
return OMNIBOX_HEURISTIC_EXACT;
if (group == omnibox_exact_full_group_id)
return OMNIBOX_HEURISTIC_EXACT_FULL;
// If we don't have a group just return the exact heuristic.
return OMNIBOX_HEURISTIC_EXACT;
}
std::string GetOmniboxHistogramSuffix() {
return NameFromOmniboxHeuristic(prerender::GetOmniboxHeuristicToUse());
}
} // namespace prerender
<commit_msg>Increase omnibox prerender field trial opt-in from 40% to 90%.<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 "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
namespace prerender {
namespace {
int omnibox_exact_group_id = 0;
int omnibox_exact_full_group_id = 0;
const char* kOmniboxHeuristicNames[] = {
"Exact",
"Exact_Full"
};
COMPILE_ASSERT(arraysize(kOmniboxHeuristicNames) == OMNIBOX_HEURISTIC_MAX,
OmniboxHeuristic_name_count_mismatch);
const char kPrerenderFromOmniboxTrialName[] = "PrerenderFromOmnibox";
const char kPrerenderFromOmniboxHeuristicTrialName[] =
"PrerenderFromOmniboxHeuristic";
const char* NameFromOmniboxHeuristic(OmniboxHeuristic heuristic) {
DCHECK_LT(static_cast<unsigned int>(heuristic),
arraysize(kOmniboxHeuristicNames));
return kOmniboxHeuristicNames[heuristic];
}
} // end namespace
void ConfigurePrerenderFromOmnibox();
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerenderMode)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerenderMode);
if (switch_value == switches::kPrerenderModeSwitchValueAuto) {
prerender_option = PRERENDER_OPTION_AUTO;
} else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderModeSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value ==
switches::kPrerenderModeSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO: {
base::FieldTrial::Probability divisor = 1000;
base::FieldTrial::Probability exp1_probability = 200;
base::FieldTrial::Probability control1_probability = 200;
base::FieldTrial::Probability no_use1_probability = 100;
base::FieldTrial::Probability exp2_probability = 200;
base::FieldTrial::Probability control2_probability = 200;
base::FieldTrial::Probability no_use2_probability = 100;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
exp1_probability = 495;
control1_probability = 5;
no_use1_probability = 0;
exp2_probability = 495;
control2_probability = 5;
no_use2_probability = 0;
}
CHECK_EQ(divisor, exp1_probability + control1_probability +
no_use1_probability + exp2_probability +
control2_probability + no_use2_probability);
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prefetch", divisor,
"ContentPrefetchPrerender1", 2012, 6, 30));
const int kPrerenderExperiment1Group = trial->kDefaultGroupNumber;
const int kPrerenderControl1Group =
trial->AppendGroup("ContentPrefetchPrerenderControl1",
control1_probability);
const int kPrerenderNoUse1Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse1",
no_use1_probability);
const int kPrerenderExperiment2Group =
trial->AppendGroup("ContentPrefetchPrerender2",
exp2_probability);
const int kPrerenderControl2Group =
trial->AppendGroup("ContentPrefetchPrerenderControl2",
control2_probability);
const int kPrerenderNoUse2Group =
trial->AppendGroup("ContentPrefetchPrerenderNoUse2",
no_use2_probability);
const int trial_group = trial->group();
if (trial_group == kPrerenderExperiment1Group ||
trial_group == kPrerenderExperiment2Group) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == kPrerenderControl1Group ||
trial_group == kPrerenderControl2Group) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else if (trial_group == kPrerenderNoUse1Group ||
trial_group == kPrerenderNoUse2Group) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);
} else {
NOTREACHED();
}
break;
}
case PRERENDER_OPTION_DISABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
ConfigurePrerenderFromOmnibox();
}
void ConfigurePrerenderFromOmnibox() {
// Field trial to see if we're enabled.
const base::FieldTrial::Probability kDivisor = 100;
const base::FieldTrial::Probability kEnabledProbability = 90;
scoped_refptr<base::FieldTrial> enabled_trial(
new base::FieldTrial(kPrerenderFromOmniboxTrialName, kDivisor,
"OmniboxPrerenderDisabled", 2012, 8, 30));
enabled_trial->AppendGroup("OmniboxPrerenderEnabled", kEnabledProbability);
// Field trial to see which heuristic to use.
const base::FieldTrial::Probability kExactFullProbability = 50;
scoped_refptr<base::FieldTrial> heuristic_trial(
new base::FieldTrial(kPrerenderFromOmniboxHeuristicTrialName, kDivisor,
"OriginalAlgorithm", 2012, 8, 30));
omnibox_exact_group_id = base::FieldTrial::kDefaultGroupNumber;
omnibox_exact_full_group_id =
heuristic_trial->AppendGroup("ExactFullAlgorithm", kExactFullProbability);
}
bool IsOmniboxEnabled(Profile* profile) {
if (!profile || profile->IsOffTheRecord())
return false;
if (!PrerenderManager::IsPrerenderingPossible())
return false;
// Override any field trial groups if the user has set a command line flag.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrerenderFromOmnibox)) {
const std::string switch_value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPrerenderFromOmnibox);
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)
return true;
if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)
return false;
DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);
}
if (!MetricsServiceHelper::IsMetricsReportingEnabled())
return false;
const int group =
base::FieldTrialList::FindValue(kPrerenderFromOmniboxTrialName);
return group != base::FieldTrial::kNotFinalized &&
group != base::FieldTrial::kDefaultGroupNumber;
}
OmniboxHeuristic GetOmniboxHeuristicToUse() {
const int group =
base::FieldTrialList::FindValue(kPrerenderFromOmniboxHeuristicTrialName);
if (group == omnibox_exact_group_id)
return OMNIBOX_HEURISTIC_EXACT;
if (group == omnibox_exact_full_group_id)
return OMNIBOX_HEURISTIC_EXACT_FULL;
// If we don't have a group just return the exact heuristic.
return OMNIBOX_HEURISTIC_EXACT;
}
std::string GetOmniboxHistogramSuffix() {
return NameFromOmniboxHeuristic(prerender::GetOmniboxHeuristicToUse());
}
} // namespace prerender
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This example is free, and not covered by the LGPL license. There is no
* restriction applied to their modification, redistribution, using and so on.
* You can study them, modify them, use them in your own program - either
* completely or partially.
*/
#include "settingspage.h"
#include "textdocument.h"
#include "textbrowser.h"
#include "themeloader.h"
#include "treewidget.h"
#include "bufferview.h"
#include "themeinfo.h"
#include "splitview.h"
#include "chatpage.h"
#include <IrcBufferModel>
#include <IrcConnection>
#include <QPushButton>
#include <IrcChannel>
#include <IrcMessage>
#include <QShortcut>
#include <IrcBuffer>
#include <QPainter>
#include <QPixmap>
#include <QBuffer>
class Channel : public IrcChannel
{
public:
Channel(QObject* parent = 0) : IrcChannel(parent) { }
bool isActive() const { return true; }
};
class Server : public IrcBuffer
{
public:
Server(QObject* parent = 0) : IrcBuffer(parent) { }
bool isActive() const { return true; }
};
static void receiveMessages(TextDocument* doc)
{
QString title = doc->buffer()->title();
IrcConnection* connection = doc->buffer()->connection();
doc->receiveMessage(IrcMessage::fromParameters("Lorem", "JOIN", QStringList() << title, connection));
doc->receiveMessage(IrcMessage::fromParameters("Morbi", "PRIVMSG", QStringList() << title << "nullam eget commodo diam. sit amet ornare leo.", connection));
doc->receiveMessage(IrcMessage::fromParameters("nulla", "PRIVMSG", QStringList() << title << "...", connection));
doc->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection));
doc->receiveMessage(IrcMessage::fromParameters("rhoncus", "PRIVMSG", QStringList() << title << "vivamus!", connection));
doc->receiveMessage(IrcMessage::fromParameters("Etiam", "PRIVMSG", QStringList() << title << "Ut volutpat nibh nec enim elementum, sed placerat erat gravida.", connection));
doc->receiveMessage(IrcMessage::fromParameters("Ipsum", "QUIT", QStringList() << "Nulla facilisi.", connection));
doc->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection));
doc->receiveMessage(IrcMessage::fromParameters("nunc", "PRIVMSG", QStringList() << title << ":)", connection));
doc->receiveMessage(IrcMessage::fromParameters("gravida", "PRIVMSG", QStringList() << title << "etiam augue purus, pharetra vel neque a, fringilla hendrerit orci", connection));
doc->receiveMessage(IrcMessage::fromParameters("Proin", "PRIVMSG", QStringList() << title << "enim ante?", connection));
doc->receiveMessage(IrcMessage::fromParameters("Cras", "PRIVMSG", QStringList() << title << "quisque vel lacus eu odio pretium adipiscing...", connection));
}
static IrcBuffer* createChannel(const QString& name, QObject* parent)
{
IrcChannel* channel = new Channel(parent);
channel->setPrefix("#");
channel->setName(name);
return channel;
}
static IrcBufferModel* createBufferModel(QObject* parent)
{
IrcConnection* connection = new IrcConnection(parent);
connection->setNickName("communi");
IrcBufferModel* model = new IrcBufferModel(connection);
IrcBuffer* server = new Server(model);
server->setName("Lorem Ipsum");
server->setSticky(true);
model->add(server);
model->add(createChannel("donec", model));
model->add(createChannel("convallis", model));
model->add(createChannel("sagittis", model));
model->add(createChannel("magna", model));
model->add(createChannel("tincidunt", model));
model->add(createChannel("phasellus ", model));
model->add(createChannel("tellus", model));
model->add(createChannel("fermentum", model));
model->add(createChannel("pharetra", model));
model->add(createChannel("vehicula", model));
model->add(createChannel("aliquam", model));
model->add(createChannel("bibendum", model));
model->add(createChannel("semper", model));
model->add(createChannel("dictum", model));
model->add(createChannel("rhoncus", model));
return model;
}
static ChatPage* createChatPage(QWidget* parent = 0)
{
ChatPage* page = new ChatPage(parent);
IrcBufferModel* model = createBufferModel(page);
foreach (IrcBuffer* buffer, model->buffers())
page->treeWidget()->addBuffer(buffer);
IrcBuffer* buffer = model->find("#magna");
page->addBuffer(buffer);
page->splitView()->setCurrentBuffer(buffer);
page->treeWidget()->setCurrentBuffer(buffer);
page->treeWidget()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
page->currentView()->textBrowser()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
receiveMessages(page->currentView()->textDocument());
return page;
}
SettingsPage::SettingsPage(QWidget* parent) : QWidget(parent)
{
ui.setupUi(this);
connect(ui.buttonBox, SIGNAL(accepted()), this, SIGNAL(accepted()));
connect(ui.buttonBox, SIGNAL(rejected()), this, SIGNAL(rejected()));
QShortcut* shortcut = new QShortcut(Qt::Key_Return, this);
connect(shortcut, SIGNAL(activated()), ui.buttonBox->button(QDialogButtonBox::Ok), SLOT(click()));
shortcut = new QShortcut(Qt::Key_Escape, this);
connect(shortcut, SIGNAL(activated()), ui.buttonBox->button(QDialogButtonBox::Cancel), SLOT(click()));
ChatPage* page = createChatPage();
page->resize(640, 400);
foreach (const QString& name, ThemeLoader::instance()->themes()) {
ThemeInfo theme = ThemeLoader::instance()->theme(name);
QPixmap pixmap(640, 400);
QPainter painter(&pixmap);
page->setTheme(theme.name());
page->render(&painter);
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
pixmap.scaled(320, 200).save(&buffer, "PNG");
QLabel* label = new QLabel(ui.content);
label->setTextFormat(Qt::RichText);
label->setText(tr("<table><tr>"
"<td>"
"<img src='data:image/png;base64,%5'/>"
"</td>"
"<td>"
"<h1>%1</h1>"
"<p><b>Version</b>: %2</p>"
"<p><b>Author</b>: %3</p>"
"<p>%4</p>"
"</td>"
"</tr></table>").arg(theme.name(), theme.version(), theme.author(), theme.description(), ba.toBase64()));
ui.content->layout()->addWidget(label);
}
delete page;
}
SettingsPage::~SettingsPage()
{
}
QString SettingsPage::theme() const
{
//return ui.comboBox->currentText();
return "Cute";
}
/*
void SettingsPage::setThemes(const QStringList& themes)
{
//ui.comboBox->clear();
//ui.comboBox->addItems(themes);
}
*/
<commit_msg>Improve theme preview<commit_after>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This example is free, and not covered by the LGPL license. There is no
* restriction applied to their modification, redistribution, using and so on.
* You can study them, modify them, use them in your own program - either
* completely or partially.
*/
#include "settingspage.h"
#include "textdocument.h"
#include "textbrowser.h"
#include "themeloader.h"
#include "treewidget.h"
#include "bufferview.h"
#include "themeinfo.h"
#include "splitview.h"
#include "chatpage.h"
#include <IrcBufferModel>
#include <IrcConnection>
#include <QPushButton>
#include <IrcChannel>
#include <IrcMessage>
#include <QShortcut>
#include <IrcBuffer>
#include <QPainter>
#include <QPixmap>
#include <QBuffer>
class Channel : public IrcChannel
{
public:
Channel(QObject* parent = 0) : IrcChannel(parent) { }
bool isActive() const { return true; }
};
class Server : public IrcBuffer
{
public:
Server(QObject* parent = 0) : IrcBuffer(parent) { }
bool isActive() const { return true; }
};
static void receiveMessages(IrcBufferModel* model, IrcBuffer* buffer)
{
QString title = buffer->title();
IrcConnection* connection = buffer->connection();
model->receiveMessage(IrcMessage::fromParameters("Lorem", "JOIN", QStringList() << title, connection));
IrcNamesMessage* names = new IrcNamesMessage(connection);
names->setParameters(QStringList() << title << "Lorem" << "Morbi" << "nulla" << "rhoncus" << "Etiam" << "nunc" << "gravida" << "Proin" << "Cras");
model->receiveMessage(names);
model->receiveMessage(IrcMessage::fromParameters("Morbi", "PRIVMSG", QStringList() << title << "nullam eget commodo diam. sit amet ornare leo.", connection));
model->receiveMessage(IrcMessage::fromParameters("nulla", "PRIVMSG", QStringList() << title << "...", connection));
model->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection));
model->receiveMessage(IrcMessage::fromParameters("rhoncus", "PRIVMSG", QStringList() << title << "vivamus!", connection));
model->receiveMessage(IrcMessage::fromParameters("Etiam", "PRIVMSG", QStringList() << title << "Ut volutpat nibh nec enim elementum, sed placerat erat gravida.", connection));
model->receiveMessage(IrcMessage::fromParameters("Ipsum", "QUIT", QStringList() << "Nulla facilisi.", connection));
model->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection));
model->receiveMessage(IrcMessage::fromParameters("nunc", "PRIVMSG", QStringList() << title << ":)", connection));
model->receiveMessage(IrcMessage::fromParameters("gravida", "PRIVMSG", QStringList() << title << "etiam augue purus, pharetra vel neque a, fringilla hendrerit orci", connection));
model->receiveMessage(IrcMessage::fromParameters("Proin", "PRIVMSG", QStringList() << title << "enim ante?", connection));
model->receiveMessage(IrcMessage::fromParameters("Cras", "PRIVMSG", QStringList() << title << "quisque vel lacus eu odio pretium adipiscing...", connection));
}
static IrcBuffer* createChannel(const QString& name, QObject* parent)
{
IrcChannel* channel = new Channel(parent);
channel->setPrefix("#");
channel->setName(name);
return channel;
}
static IrcBufferModel* createBufferModel(QObject* parent)
{
IrcConnection* connection = new IrcConnection(parent);
connection->setNickName("communi");
IrcBufferModel* model = new IrcBufferModel(connection);
IrcBuffer* server = new Server(model);
server->setName("Lorem Ipsum");
server->setSticky(true);
model->add(server);
model->add(createChannel("donec", model));
model->add(createChannel("convallis", model));
model->add(createChannel("sagittis", model));
model->add(createChannel("magna", model));
model->add(createChannel("tincidunt", model));
model->add(createChannel("phasellus ", model));
model->add(createChannel("tellus", model));
model->add(createChannel("fermentum", model));
model->add(createChannel("pharetra", model));
model->add(createChannel("vehicula", model));
model->add(createChannel("aliquam", model));
model->add(createChannel("bibendum", model));
model->add(createChannel("semper", model));
model->add(createChannel("dictum", model));
model->add(createChannel("rhoncus", model));
return model;
}
static ChatPage* createChatPage(QWidget* parent = 0)
{
ChatPage* page = new ChatPage(parent);
IrcBufferModel* model = createBufferModel(page);
foreach (IrcBuffer* buffer, model->buffers())
page->treeWidget()->addBuffer(buffer);
IrcBuffer* buffer = model->find("#magna");
page->addBuffer(buffer);
page->splitView()->setCurrentBuffer(buffer);
page->treeWidget()->setCurrentBuffer(buffer);
page->treeWidget()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
page->currentView()->textBrowser()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
receiveMessages(model, buffer);
return page;
}
SettingsPage::SettingsPage(QWidget* parent) : QWidget(parent)
{
ui.setupUi(this);
connect(ui.buttonBox, SIGNAL(accepted()), this, SIGNAL(accepted()));
connect(ui.buttonBox, SIGNAL(rejected()), this, SIGNAL(rejected()));
QShortcut* shortcut = new QShortcut(Qt::Key_Return, this);
connect(shortcut, SIGNAL(activated()), ui.buttonBox->button(QDialogButtonBox::Ok), SLOT(click()));
shortcut = new QShortcut(Qt::Key_Escape, this);
connect(shortcut, SIGNAL(activated()), ui.buttonBox->button(QDialogButtonBox::Cancel), SLOT(click()));
ChatPage* page = createChatPage();
page->resize(640, 400);
foreach (const QString& name, ThemeLoader::instance()->themes()) {
ThemeInfo theme = ThemeLoader::instance()->theme(name);
QPixmap pixmap(640, 400);
QPainter painter(&pixmap);
page->setTheme(theme.name());
page->render(&painter);
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
pixmap.scaled(320, 200).save(&buffer, "PNG");
QLabel* label = new QLabel(ui.content);
label->setTextFormat(Qt::RichText);
label->setText(tr("<table><tr>"
"<td>"
"<img src='data:image/png;base64,%5'/>"
"</td>"
"<td>"
"<h1>%1</h1>"
"<p><b>Version</b>: %2</p>"
"<p><b>Author</b>: %3</p>"
"<p>%4</p>"
"</td>"
"</tr></table>").arg(theme.name(), theme.version(), theme.author(), theme.description(), ba.toBase64()));
ui.content->layout()->addWidget(label);
}
delete page;
}
SettingsPage::~SettingsPage()
{
}
QString SettingsPage::theme() const
{
//return ui.comboBox->currentText();
return "Cute";
}
/*
void SettingsPage::setThemes(const QStringList& themes)
{
//ui.comboBox->clear();
//ui.comboBox->addItems(themes);
}
*/
<|endoftext|> |
<commit_before>//
// complex2record
//
// This pass changes the primitive complex type to a record. As an
// optimization, unimplemented, it can be turned off to take advantage
// of C99 support of complex types.
//
#include "astutil.h"
#include "build.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "symscope.h"
static ClassType*
buildComplexRecord(const char* name, Type* real) {
ClassType* ct = new ClassType(CLASS_RECORD);
TypeSymbol* ts = new TypeSymbol(name, ct);
ct->fields.insertAtTail(new DefExpr(new VarSymbol("re", real)));
ct->fields.insertAtTail(new DefExpr(new VarSymbol("im", real)));
rootModule->block->insertAtTail(new DefExpr(ts));
return ct;
}
#define complex2rec(t) \
((t == dtComplex[COMPLEX_SIZE_64]) ? complex64 : \
((t == dtComplex[COMPLEX_SIZE_128]) ? complex128 : 0))
#define complex2real(t) \
((t == dtComplex[COMPLEX_SIZE_64]) ? dtReal[FLOAT_SIZE_32] : \
((t == dtComplex[COMPLEX_SIZE_128]) ? dtReal[FLOAT_SIZE_64] : 0))
void
complex2record() {
ClassType* complex64 = buildComplexRecord("_complex64", dtReal[FLOAT_SIZE_32]);
ClassType* complex128 = buildComplexRecord("_complex128", dtReal[FLOAT_SIZE_64]);
complex64->refType = dtComplex[COMPLEX_SIZE_64]->refType;
complex128->refType = dtComplex[COMPLEX_SIZE_128]->refType;
dtComplex[COMPLEX_SIZE_64]->refType = NULL;
dtComplex[COMPLEX_SIZE_128]->refType = NULL;
dtComplex[COMPLEX_SIZE_64]->symbol->defPoint->remove();
dtComplex[COMPLEX_SIZE_128]->symbol->defPoint->remove();
forv_Vec(BaseAST, ast, gAsts) {
if (DefExpr* def = toDefExpr(ast)) {
if (def->parentExpr != rootModule->block)
if (!isTypeSymbol(def->sym))
if (is_complex_type(def->sym->type))
def->sym->type = complex2rec(def->sym->type);
if (FnSymbol* fn = toFnSymbol(def->sym))
if (is_complex_type(fn->retType))
fn->retType = complex2rec(fn->retType);
} else if (SymExpr* se = toSymExpr(ast)) {
if (VarSymbol* var = toVarSymbol(se->var)) {
if (is_complex_type(var->type)) {
if (var->immediate) {
ClassType* ct = complex2rec(se->var->type);
VarSymbol* tmp = new VarSymbol("_tmp", ct);
se->getStmtExpr()->insertBefore(new DefExpr(tmp));
se->getStmtExpr()->insertBefore(new CallExpr(PRIMITIVE_SET_MEMBER, tmp, ct->getField(1), complex2real(se->var->type)->defaultValue));
se->getStmtExpr()->insertBefore(new CallExpr(PRIMITIVE_SET_MEMBER, tmp, ct->getField(2), complex2real(se->var->type)->defaultValue));
se->replace(new SymExpr(tmp));
}
}
} else if (TypeSymbol* ts = toTypeSymbol(se->var)) {
if (is_complex_type(ts->type)) {
se->var = complex2rec(ts->type)->symbol;
}
}
}
}
forv_Vec(BaseAST, ast, gAsts) {
if (CallExpr* call = toCallExpr(ast)) {
if (call->isPrimitive(PRIMITIVE_GET_REAL)) {
call->primitive = primitives[PRIMITIVE_GET_MEMBER];
ClassType* ct = toClassType(call->get(1)->typeInfo());
if (isReference(ct))
ct = toClassType(getValueType(ct));
call->insertAtTail(ct->getField(1));
} else if (call->isPrimitive(PRIMITIVE_GET_IMAG)) {
call->primitive = primitives[PRIMITIVE_GET_MEMBER];
ClassType* ct = toClassType(call->get(1)->typeInfo());
if (isReference(ct))
ct = toClassType(getValueType(ct));
call->insertAtTail(ct->getField(2));
}
}
}
//
// change arrays of complexes into arrays of new complex records
//
forv_Vec(TypeSymbol, ts, gTypes) {
if (ts->hasPragma("data class")) {
if (Type* nt = toType(ts->type->substitutions.v[0].value)) {
if (is_complex_type(nt)) {
ts->type->substitutions.v[0].value = complex2rec(nt);
}
}
}
}
}
<commit_msg>fixed valgrind regression due to complex type bug<commit_after>//
// complex2record
//
// This pass changes the primitive complex type to a record. As an
// optimization, unimplemented, it can be turned off to take advantage
// of C99 support of complex types.
//
#include "astutil.h"
#include "build.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "symscope.h"
static ClassType*
buildComplexRecord(const char* name, Type* real) {
ClassType* ct = new ClassType(CLASS_RECORD);
TypeSymbol* ts = new TypeSymbol(name, ct);
ct->fields.insertAtTail(new DefExpr(new VarSymbol("re", real)));
ct->fields.insertAtTail(new DefExpr(new VarSymbol("im", real)));
rootModule->block->insertAtTail(new DefExpr(ts));
return ct;
}
#define complex2rec(t) \
((t == dtComplex[COMPLEX_SIZE_64]) ? complex64 : \
((t == dtComplex[COMPLEX_SIZE_128]) ? complex128 : 0))
#define complex2real(t) \
((t == dtComplex[COMPLEX_SIZE_64]) ? dtReal[FLOAT_SIZE_32] : \
((t == dtComplex[COMPLEX_SIZE_128]) ? dtReal[FLOAT_SIZE_64] : 0))
void
complex2record() {
ClassType* complex64 = buildComplexRecord("_complex64", dtReal[FLOAT_SIZE_32]);
ClassType* complex128 = buildComplexRecord("_complex128", dtReal[FLOAT_SIZE_64]);
complex64->refType = dtComplex[COMPLEX_SIZE_64]->refType;
complex128->refType = dtComplex[COMPLEX_SIZE_128]->refType;
dtComplex[COMPLEX_SIZE_64]->refType = NULL;
dtComplex[COMPLEX_SIZE_128]->refType = NULL;
dtComplex[COMPLEX_SIZE_64]->symbol->defPoint->remove();
dtComplex[COMPLEX_SIZE_128]->symbol->defPoint->remove();
forv_Vec(BaseAST, ast, gAsts) {
if (SymExpr* se = toSymExpr(ast)) {
if (VarSymbol* var = toVarSymbol(se->var)) {
if (is_complex_type(var->type)) {
if (var->immediate) {
ClassType* ct = complex2rec(se->var->type);
VarSymbol* tmp = new VarSymbol("_tmp", ct);
se->getStmtExpr()->insertBefore(new DefExpr(tmp));
se->getStmtExpr()->insertBefore(new CallExpr(PRIMITIVE_SET_MEMBER, tmp, ct->getField(1), complex2real(se->var->type)->defaultValue));
se->getStmtExpr()->insertBefore(new CallExpr(PRIMITIVE_SET_MEMBER, tmp, ct->getField(2), complex2real(se->var->type)->defaultValue));
se->replace(new SymExpr(tmp));
}
}
} else if (TypeSymbol* ts = toTypeSymbol(se->var)) {
if (is_complex_type(ts->type)) {
se->var = complex2rec(ts->type)->symbol;
}
}
}
}
forv_Vec(BaseAST, ast, gAsts) {
if (DefExpr* def = toDefExpr(ast)) {
if (!isTypeSymbol(def->sym))
if (is_complex_type(def->sym->type))
def->sym->type = complex2rec(def->sym->type);
if (FnSymbol* fn = toFnSymbol(def->sym))
if (is_complex_type(fn->retType))
fn->retType = complex2rec(fn->retType);
}
}
forv_Vec(BaseAST, ast, gAsts) {
if (CallExpr* call = toCallExpr(ast)) {
if (call->isPrimitive(PRIMITIVE_GET_REAL)) {
call->primitive = primitives[PRIMITIVE_GET_MEMBER];
ClassType* ct = toClassType(call->get(1)->typeInfo());
if (isReference(ct))
ct = toClassType(getValueType(ct));
call->insertAtTail(ct->getField(1));
} else if (call->isPrimitive(PRIMITIVE_GET_IMAG)) {
call->primitive = primitives[PRIMITIVE_GET_MEMBER];
ClassType* ct = toClassType(call->get(1)->typeInfo());
if (isReference(ct))
ct = toClassType(getValueType(ct));
call->insertAtTail(ct->getField(2));
}
}
}
//
// change arrays of complexes into arrays of new complex records
//
forv_Vec(TypeSymbol, ts, gTypes) {
if (ts->hasPragma("data class")) {
if (Type* nt = toType(ts->type->substitutions.v[0].value)) {
if (is_complex_type(nt)) {
ts->type->substitutions.v[0].value = complex2rec(nt);
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "proto_converter.h"
#include <vespa/searchlib/common/mapnames.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/vespalib/data/slime/binary_format.h>
#include <vespa/vespalib/data/smart_buffer.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.engine.proto_converter");
namespace search::engine {
namespace {
template <typename T>
vespalib::string make_sort_spec(const T &sorting) {
vespalib::string spec;
for (const auto &field_spec: sorting) {
if (!spec.empty()) {
spec.push_back(' ');
}
if (field_spec.ascending()) {
spec.push_back('+');
} else {
spec.push_back('-');
}
spec.append(field_spec.field());
}
return spec;
}
template <typename T>
void add_single_props(fef::Properties &dst, const T &src) {
for (const auto &entry: src) {
dst.add(entry.name(), entry.value());
}
}
template <typename T>
void add_multi_props(fef::Properties &dst, const T &src) {
for (const auto &entry: src) {
for (int i = 0; i < entry.values_size(); ++i) {
dst.add(entry.name(), entry.values(i));
}
}
}
}
//-----------------------------------------------------------------------------
void
ProtoConverter::search_request_from_proto(const ProtoSearchRequest &proto, SearchRequest &request)
{
request.offset = proto.offset();
request.maxhits = proto.hits();
request.setTimeout(1ms * proto.timeout());
request.setTraceLevel(proto.trace_level());
request.sortSpec = make_sort_spec(proto.sorting());
request.sessionId.assign(proto.session_key().begin(), proto.session_key().end());
request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type());
if (proto.cache_grouping()) {
request.propertiesMap.lookupCreate(MapNames::CACHES).add("grouping", "true");
}
if (proto.cache_query()) {
request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true");
}
request.ranking = proto.rank_profile();
if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) {
auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE);
add_multi_props(feature_overrides, proto.feature_overrides());
add_single_props(feature_overrides, proto.tensor_feature_overrides());
}
if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) {
auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK);
add_multi_props(rank_props, proto.rank_properties());
add_single_props(rank_props, proto.tensor_rank_properties());
}
request.groupSpec.assign(proto.grouping_blob().begin(), proto.grouping_blob().end());
request.location = proto.geo_location();
request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end());
}
void
ProtoConverter::search_reply_to_proto(const SearchReply &reply, ProtoSearchReply &proto)
{
proto.set_total_hit_count(reply.totalHitCount);
proto.set_coverage_docs(reply.coverage.getCovered());
proto.set_active_docs(reply.coverage.getActive());
proto.set_soon_active_docs(reply.coverage.getSoonActive());
proto.set_degraded_by_match_phase(reply.coverage.wasDegradedByMatchPhase());
proto.set_degraded_by_soft_timeout(reply.coverage.wasDegradedByTimeout());
bool has_sort_data = (reply.sortIndex.size() > 0);
assert(!has_sort_data || (reply.sortIndex.size() == (reply.hits.size() + 1)));
if (reply.request) {
uint32_t asked_offset = reply.request->offset;
uint32_t asked_hits = reply.request->maxhits;
size_t got_hits = reply.hits.size();
if (got_hits < asked_hits && asked_offset + got_hits < reply.totalHitCount) {
LOG(warning, "asked for %u hits [at offset %u] but only returning %zu hits from %" PRIu64 " available",
asked_hits, asked_offset, got_hits, reply.totalHitCount);
}
}
for (size_t i = 0; i < reply.hits.size(); ++i) {
auto *hit = proto.add_hits();
hit->set_global_id(reply.hits[i].gid.get(), document::GlobalId::LENGTH);
hit->set_relevance(reply.hits[i].metric);
if (has_sort_data) {
size_t sort_data_offset = reply.sortIndex[i];
size_t sort_data_size = (reply.sortIndex[i + 1] - reply.sortIndex[i]);
assert((sort_data_offset + sort_data_size) <= reply.sortData.size());
hit->set_sort_data(&reply.sortData[sort_data_offset], sort_data_size);
}
}
proto.set_grouping_blob(&reply.groupResult[0], reply.groupResult.size());
const auto &slime_trace = reply.propertiesMap.trace().lookup("slime");
proto.set_slime_trace(slime_trace.get().data(), slime_trace.get().size());
if (reply.my_issues) {
reply.my_issues->for_each_message([&](const vespalib::string &err_msg)
{
auto *err_obj = proto.add_errors();
err_obj->set_message(err_msg);
});
}
}
//-----------------------------------------------------------------------------
void
ProtoConverter::docsum_request_from_proto(const ProtoDocsumRequest &proto, DocsumRequest &request)
{
request.setTimeout(1ms * proto.timeout());
request.sessionId.assign(proto.session_key().begin(), proto.session_key().end());
request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type());
request.resultClassName = proto.summary_class();
if (proto.cache_query()) {
request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true");
}
request.dumpFeatures = proto.dump_features();
request.ranking = proto.rank_profile();
if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) {
auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE);
add_multi_props(feature_overrides, proto.feature_overrides());
add_single_props(feature_overrides, proto.tensor_feature_overrides());
}
if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) {
auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK);
add_multi_props(rank_props, proto.rank_properties());
add_single_props(rank_props, proto.tensor_rank_properties());
}
if(proto.highlight_terms_size() > 0) {
auto &highlight_terms = request.propertiesMap.lookupCreate(MapNames::HIGHLIGHTTERMS);
add_multi_props(highlight_terms, proto.highlight_terms());
}
request.location = proto.geo_location();
request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end());
request.hits.resize(proto.global_ids_size());
for (int i = 0; i < proto.global_ids_size(); ++i) {
const auto &gid = proto.global_ids(i);
if (gid.size() == document::GlobalId::LENGTH) {
request.hits[i].gid = document::GlobalId(gid.data());
}
}
}
void
ProtoConverter::docsum_reply_to_proto(const DocsumReply &reply, ProtoDocsumReply &proto)
{
if (reply.hasResult()) {
vespalib::SmartBuffer buf(4_Ki);
vespalib::slime::BinaryFormat::encode(reply.slime(), buf);
proto.set_slime_summaries(buf.obtain().data, buf.obtain().size);
}
if (reply.hasIssues()) {
reply.issues().for_each_message([&](const vespalib::string &err_msg)
{
auto *err_obj = proto.add_errors();
err_obj->set_message(err_msg);
});
}
}
//-----------------------------------------------------------------------------
void
ProtoConverter::monitor_request_from_proto(const ProtoMonitorRequest &, MonitorRequest &)
{
}
void
ProtoConverter::monitor_reply_to_proto(const MonitorReply &reply, ProtoMonitorReply &proto)
{
proto.set_online(reply.timestamp != 0);
proto.set_active_docs(reply.activeDocs);
proto.set_distribution_key(reply.distribution_key);
proto.set_is_blocking_writes(reply.is_blocking_writes);
}
//-----------------------------------------------------------------------------
}
<commit_msg>feature values in SearchReply -> protobuf<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "proto_converter.h"
#include <vespa/searchlib/common/mapnames.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/vespalib/data/slime/binary_format.h>
#include <vespa/vespalib/data/smart_buffer.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.engine.proto_converter");
namespace search::engine {
namespace {
template <typename T>
vespalib::string make_sort_spec(const T &sorting) {
vespalib::string spec;
for (const auto &field_spec: sorting) {
if (!spec.empty()) {
spec.push_back(' ');
}
if (field_spec.ascending()) {
spec.push_back('+');
} else {
spec.push_back('-');
}
spec.append(field_spec.field());
}
return spec;
}
template <typename T>
void add_single_props(fef::Properties &dst, const T &src) {
for (const auto &entry: src) {
dst.add(entry.name(), entry.value());
}
}
template <typename T>
void add_multi_props(fef::Properties &dst, const T &src) {
for (const auto &entry: src) {
for (int i = 0; i < entry.values_size(); ++i) {
dst.add(entry.name(), entry.values(i));
}
}
}
}
//-----------------------------------------------------------------------------
void
ProtoConverter::search_request_from_proto(const ProtoSearchRequest &proto, SearchRequest &request)
{
request.offset = proto.offset();
request.maxhits = proto.hits();
request.setTimeout(1ms * proto.timeout());
request.setTraceLevel(proto.trace_level());
request.sortSpec = make_sort_spec(proto.sorting());
request.sessionId.assign(proto.session_key().begin(), proto.session_key().end());
request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type());
if (proto.cache_grouping()) {
request.propertiesMap.lookupCreate(MapNames::CACHES).add("grouping", "true");
}
if (proto.cache_query()) {
request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true");
}
request.ranking = proto.rank_profile();
if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) {
auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE);
add_multi_props(feature_overrides, proto.feature_overrides());
add_single_props(feature_overrides, proto.tensor_feature_overrides());
}
if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) {
auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK);
add_multi_props(rank_props, proto.rank_properties());
add_single_props(rank_props, proto.tensor_rank_properties());
}
request.groupSpec.assign(proto.grouping_blob().begin(), proto.grouping_blob().end());
request.location = proto.geo_location();
request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end());
}
void
ProtoConverter::search_reply_to_proto(const SearchReply &reply, ProtoSearchReply &proto)
{
proto.set_total_hit_count(reply.totalHitCount);
proto.set_coverage_docs(reply.coverage.getCovered());
proto.set_active_docs(reply.coverage.getActive());
proto.set_soon_active_docs(reply.coverage.getSoonActive());
proto.set_degraded_by_match_phase(reply.coverage.wasDegradedByMatchPhase());
proto.set_degraded_by_soft_timeout(reply.coverage.wasDegradedByTimeout());
bool has_sort_data = (reply.sortIndex.size() > 0);
assert(!has_sort_data || (reply.sortIndex.size() == (reply.hits.size() + 1)));
if (reply.request) {
uint32_t asked_offset = reply.request->offset;
uint32_t asked_hits = reply.request->maxhits;
size_t got_hits = reply.hits.size();
if (got_hits < asked_hits && asked_offset + got_hits < reply.totalHitCount) {
LOG(warning, "asked for %u hits [at offset %u] but only returning %zu hits from %" PRIu64 " available",
asked_hits, asked_offset, got_hits, reply.totalHitCount);
}
}
size_t num_match_features = reply.match_features.names.size();
using FeatureValuesIterator = std::vector<search::FeatureValues::Value>::const_iterator;
FeatureValuesIterator mfv_iter;
bool has_match_features = (num_match_features > 0 && reply.hits.size() > 0);
if (has_match_features) {
size_t num_match_feature_values = reply.match_features.values.size();
fprintf(stderr, "reply with %zu hits has %zu match features, total %zu/%zu\n",
reply.hits.size(), num_match_features,
num_match_feature_values, reply.hits.size() * num_match_features);
assert(num_match_feature_values == reply.hits.size() * num_match_features);
for (const auto & name : reply.match_features.names) {
*proto.add_match_feature_names() = name;
}
mfv_iter = reply.match_features.values.begin();
}
for (size_t i = 0; i < reply.hits.size(); ++i) {
auto *hit = proto.add_hits();
hit->set_global_id(reply.hits[i].gid.get(), document::GlobalId::LENGTH);
hit->set_relevance(reply.hits[i].metric);
if (has_sort_data) {
size_t sort_data_offset = reply.sortIndex[i];
size_t sort_data_size = (reply.sortIndex[i + 1] - reply.sortIndex[i]);
assert((sort_data_offset + sort_data_size) <= reply.sortData.size());
hit->set_sort_data(&reply.sortData[sort_data_offset], sort_data_size);
}
if (has_match_features) {
for (size_t j = 0; j < num_match_features; ++j) {
auto * obj = hit->add_match_features();
const auto & feature_value = *mfv_iter++;
if (feature_value.is_data()) {
auto mem = feature_value.as_data();
obj->set_tensor(mem.data, mem.size);
} else if (feature_value.is_double()) {
obj->set_number(feature_value.as_double());
}
}
}
}
if (has_match_features) {
assert(mfv_iter == reply.match_features.values.end());
}
proto.set_grouping_blob(&reply.groupResult[0], reply.groupResult.size());
const auto &slime_trace = reply.propertiesMap.trace().lookup("slime");
proto.set_slime_trace(slime_trace.get().data(), slime_trace.get().size());
if (reply.my_issues) {
reply.my_issues->for_each_message([&](const vespalib::string &err_msg)
{
auto *err_obj = proto.add_errors();
err_obj->set_message(err_msg);
});
}
}
//-----------------------------------------------------------------------------
void
ProtoConverter::docsum_request_from_proto(const ProtoDocsumRequest &proto, DocsumRequest &request)
{
request.setTimeout(1ms * proto.timeout());
request.sessionId.assign(proto.session_key().begin(), proto.session_key().end());
request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type());
request.resultClassName = proto.summary_class();
if (proto.cache_query()) {
request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true");
}
request.dumpFeatures = proto.dump_features();
request.ranking = proto.rank_profile();
if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) {
auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE);
add_multi_props(feature_overrides, proto.feature_overrides());
add_single_props(feature_overrides, proto.tensor_feature_overrides());
}
if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) {
auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK);
add_multi_props(rank_props, proto.rank_properties());
add_single_props(rank_props, proto.tensor_rank_properties());
}
if(proto.highlight_terms_size() > 0) {
auto &highlight_terms = request.propertiesMap.lookupCreate(MapNames::HIGHLIGHTTERMS);
add_multi_props(highlight_terms, proto.highlight_terms());
}
request.location = proto.geo_location();
request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end());
request.hits.resize(proto.global_ids_size());
for (int i = 0; i < proto.global_ids_size(); ++i) {
const auto &gid = proto.global_ids(i);
if (gid.size() == document::GlobalId::LENGTH) {
request.hits[i].gid = document::GlobalId(gid.data());
}
}
}
void
ProtoConverter::docsum_reply_to_proto(const DocsumReply &reply, ProtoDocsumReply &proto)
{
if (reply.hasResult()) {
vespalib::SmartBuffer buf(4_Ki);
vespalib::slime::BinaryFormat::encode(reply.slime(), buf);
proto.set_slime_summaries(buf.obtain().data, buf.obtain().size);
}
if (reply.hasIssues()) {
reply.issues().for_each_message([&](const vespalib::string &err_msg)
{
auto *err_obj = proto.add_errors();
err_obj->set_message(err_msg);
});
}
}
//-----------------------------------------------------------------------------
void
ProtoConverter::monitor_request_from_proto(const ProtoMonitorRequest &, MonitorRequest &)
{
}
void
ProtoConverter::monitor_reply_to_proto(const MonitorReply &reply, ProtoMonitorReply &proto)
{
proto.set_online(reply.timestamp != 0);
proto.set_active_docs(reply.activeDocs);
proto.set_distribution_key(reply.distribution_key);
proto.set_is_blocking_writes(reply.is_blocking_writes);
}
//-----------------------------------------------------------------------------
}
<|endoftext|> |
<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 "remoting/host/simple_host.h"
#include "base/stl_util-inl.h"
#include "build/build_config.h"
#include "remoting/base/constants.h"
#include "remoting/base/protocol_decoder.h"
#include "remoting/host/session_manager.h"
#include "remoting/jingle_glue/jingle_channel.h"
namespace remoting {
SimpleHost::SimpleHost(const std::string& username,
const std::string& auth_token,
Capturer* capturer,
Encoder* encoder,
EventExecutor* executor)
: capture_thread_("CaptureThread"),
encode_thread_("EncodeThread"),
username_(username),
auth_token_(auth_token),
capturer_(capturer),
encoder_(encoder),
executor_(executor) {
}
void SimpleHost::Run() {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Submit a task to perform host registration. We'll also start
// listening to connection if registration is done.
RegisterHost();
// Run the main message loop. This is the main loop of this host
// object.
main_loop_.Run();
}
// This method is called when we need to the host process.
void SimpleHost::DestroySession() {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// First we tell the session to pause and then we wait until all
// the tasks are done.
if (session_.get()) {
session_->Pause();
// TODO(hclam): Revise the order.
DCHECK(encode_thread_.IsRunning());
encode_thread_.Stop();
DCHECK(capture_thread_.IsRunning());
capture_thread_.Stop();
}
}
// This method talks to the cloud to register the host process. If
// successful we will start listening to network requests.
void SimpleHost::RegisterHost() {
DCHECK_EQ(&main_loop_, MessageLoop::current());
DCHECK(!jingle_client_);
// Connect to the talk network with a JingleClient.
jingle_client_ = new JingleClient();
jingle_client_->Init(username_, auth_token_,
kChromotingTokenServiceName, this);
}
// This method is called if a client is connected to this object.
void SimpleHost::OnClientConnected(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Create a new RecordSession if there was none.
if (!session_.get()) {
// The first we need to make sure capture and encode thread are
// running.
capture_thread_.Start();
encode_thread_.Start();
// Then we create a SessionManager passing the message loops that
// it should run on.
// Note that we pass the ownership of the capturer and encoder to
// the session manager.
DCHECK(capturer_.get());
DCHECK(encoder_.get());
session_ = new SessionManager(capture_thread_.message_loop(),
encode_thread_.message_loop(),
&main_loop_,
capturer_.release(),
encoder_.release());
// Immediately add the client and start the session.
session_->AddClient(client);
session_->Start();
LOG(INFO) << "Session manager started";
} else {
// If a session manager already exists we simply add the new client.
session_->AddClient(client);
}
}
void SimpleHost::OnClientDisconnected(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Remove the client from the session manager.
if (session_.get())
session_->RemoveClient(client);
// Also remove reference to ClientConnection from this object.
client_ = NULL;
// TODO(hclam): If the last client has disconnected we need destroy
// the session manager and shutdown the capture and encode threads.
// Right now we assume there's only one client.
DestroySession();
}
////////////////////////////////////////////////////////////////////////////
// ClientConnection::EventHandler implementations
void SimpleHost::HandleMessages(ClientConnection* client,
ClientMessageList* messages) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Delegate the messages to EventExecutor and delete the unhandled
// messages.
DCHECK(executor_.get());
executor_->HandleInputEvents(messages);
STLDeleteElements<ClientMessageList>(messages);
}
void SimpleHost::OnConnectionOpened(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Completes the client connection.
LOG(INFO) << "Connection to client established.";
OnClientConnected(client_.get());
}
void SimpleHost::OnConnectionClosed(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Completes the client connection.
LOG(INFO) << "Connection to client closed.";
OnClientDisconnected(client_.get());
}
void SimpleHost::OnConnectionFailed(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// The client has disconnected.
LOG(ERROR) << "Connection failed unexpectedly.";
OnClientDisconnected(client_.get());
}
////////////////////////////////////////////////////////////////////////////
// JingleClient::Callback implementations
void SimpleHost::OnStateChange(JingleClient* jingle_client,
JingleClient::State state) {
DCHECK_EQ(jingle_client_.get(), jingle_client);
if (state == JingleClient::CONNECTED) {
LOG(INFO) << "Host connected as "
<< jingle_client->GetFullJid() << "." << std::endl;
// Start heartbeating after we connected
heartbeat_sender_ = new HeartbeatSender();
// TODO(sergeyu): where do we get host id?
heartbeat_sender_->Start(jingle_client_.get(), "HostID");
} else if (state == JingleClient::CLOSED) {
LOG(INFO) << "Host disconnected from talk network." << std::endl;
heartbeat_sender_ = NULL;
// Quit the message loop if disconected.
main_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
}
bool SimpleHost::OnAcceptConnection(
JingleClient* jingle_client, const std::string& jid,
JingleChannel::Callback** channel_callback) {
DCHECK_EQ(jingle_client_.get(), jingle_client);
// TODO(hclam): Allow multiple clients to connect to the host.
if (client_.get())
return false;
LOG(INFO) << "Client connected: " << jid << std::endl;
// If we accept the connected then create a client object and set the
// callback.
client_ = new ClientConnection(&main_loop_, new ProtocolDecoder(), this);
*channel_callback = client_.get();
return true;
}
void SimpleHost::OnNewConnection(JingleClient* jingle_client,
scoped_refptr<JingleChannel> channel) {
DCHECK_EQ(jingle_client_.get(), jingle_client);
// Since the session manager has not started, it is still safe to access
// the client directly. Note that we give the ownership of the channel
// to the client.
client_->set_jingle_channel(channel);
}
} // namespace remoting
<commit_msg>Set up the message loop of the mac host to be UI based so that it can pick up the system callbacks about screen changes. Also clean up some comments.<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 "remoting/host/simple_host.h"
#include "base/stl_util-inl.h"
#include "build/build_config.h"
#include "remoting/base/constants.h"
#include "remoting/base/protocol_decoder.h"
#include "remoting/host/session_manager.h"
#include "remoting/jingle_glue/jingle_channel.h"
namespace remoting {
#if defined (OS_MACOSX)
// The Mac depends on system callbacks to tell it what rectangles need to
// be updated, so we need to use the system message loop.
const MessageLoop::Type kSimpleHostMessageLoopType = MessageLoop::TYPE_UI;
#else
const MessageLoop::Type kSimpleHostMessageLoopType = MessageLoop::TYPE_DEFAULT;
#endif // defined (OS_MACOSX)
SimpleHost::SimpleHost(const std::string& username,
const std::string& auth_token,
Capturer* capturer,
Encoder* encoder,
EventExecutor* executor)
: main_loop_(kSimpleHostMessageLoopType),
capture_thread_("CaptureThread"),
encode_thread_("EncodeThread"),
username_(username),
auth_token_(auth_token),
capturer_(capturer),
encoder_(encoder),
executor_(executor) {
}
void SimpleHost::Run() {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Submit a task to perform host registration. We'll also start
// listening to connection if registration is done.
RegisterHost();
// Run the main message loop. This is the main loop of this host
// object.
main_loop_.Run();
}
// This method is called when we need to destroy the host process.
void SimpleHost::DestroySession() {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// First we tell the session to pause and then we wait until all
// the tasks are done.
if (session_.get()) {
session_->Pause();
// TODO(hclam): Revise the order.
DCHECK(encode_thread_.IsRunning());
encode_thread_.Stop();
DCHECK(capture_thread_.IsRunning());
capture_thread_.Stop();
}
}
// This method talks to the cloud to register the host process. If
// successful we will start listening to network requests.
void SimpleHost::RegisterHost() {
DCHECK_EQ(&main_loop_, MessageLoop::current());
DCHECK(!jingle_client_);
// Connect to the talk network with a JingleClient.
jingle_client_ = new JingleClient();
jingle_client_->Init(username_, auth_token_,
kChromotingTokenServiceName, this);
}
// This method is called if a client is connected to this object.
void SimpleHost::OnClientConnected(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Create a new RecordSession if there was none.
if (!session_.get()) {
// The first we need to make sure capture and encode thread are
// running.
capture_thread_.Start();
encode_thread_.Start();
// Then we create a SessionManager passing the message loops that
// it should run on.
// Note that we pass the ownership of the capturer and encoder to
// the session manager.
DCHECK(capturer_.get());
DCHECK(encoder_.get());
session_ = new SessionManager(capture_thread_.message_loop(),
encode_thread_.message_loop(),
&main_loop_,
capturer_.release(),
encoder_.release());
// Immediately add the client and start the session.
session_->AddClient(client);
session_->Start();
LOG(INFO) << "Session manager started";
} else {
// If a session manager already exists we simply add the new client.
session_->AddClient(client);
}
}
void SimpleHost::OnClientDisconnected(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Remove the client from the session manager.
if (session_.get())
session_->RemoveClient(client);
// Also remove reference to ClientConnection from this object.
client_ = NULL;
// TODO(hclam): If the last client has disconnected we need to destroy
// the session manager and shutdown the capture and encode threads.
// Right now we assume that there's only one client.
DestroySession();
}
////////////////////////////////////////////////////////////////////////////
// ClientConnection::EventHandler implementations
void SimpleHost::HandleMessages(ClientConnection* client,
ClientMessageList* messages) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Delegate the messages to EventExecutor and delete the unhandled
// messages.
DCHECK(executor_.get());
executor_->HandleInputEvents(messages);
STLDeleteElements<ClientMessageList>(messages);
}
void SimpleHost::OnConnectionOpened(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Completes the client connection.
LOG(INFO) << "Connection to client established.";
OnClientConnected(client_.get());
}
void SimpleHost::OnConnectionClosed(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// Completes the client connection.
LOG(INFO) << "Connection to client closed.";
OnClientDisconnected(client_.get());
}
void SimpleHost::OnConnectionFailed(ClientConnection* client) {
DCHECK_EQ(&main_loop_, MessageLoop::current());
// The client has disconnected.
LOG(ERROR) << "Connection failed unexpectedly.";
OnClientDisconnected(client_.get());
}
////////////////////////////////////////////////////////////////////////////
// JingleClient::Callback implementations
void SimpleHost::OnStateChange(JingleClient* jingle_client,
JingleClient::State state) {
DCHECK_EQ(jingle_client_.get(), jingle_client);
if (state == JingleClient::CONNECTED) {
LOG(INFO) << "Host connected as "
<< jingle_client->GetFullJid() << "." << std::endl;
// Start heartbeating after we connected
heartbeat_sender_ = new HeartbeatSender();
// TODO(sergeyu): where do we get host id?
heartbeat_sender_->Start(jingle_client_.get(), "HostID");
} else if (state == JingleClient::CLOSED) {
LOG(INFO) << "Host disconnected from talk network." << std::endl;
heartbeat_sender_ = NULL;
// Quit the message loop if disconected.
main_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
}
bool SimpleHost::OnAcceptConnection(
JingleClient* jingle_client, const std::string& jid,
JingleChannel::Callback** channel_callback) {
DCHECK_EQ(jingle_client_.get(), jingle_client);
// TODO(hclam): Allow multiple clients to connect to the host.
if (client_.get())
return false;
LOG(INFO) << "Client connected: " << jid << std::endl;
// If we accept the connected then create a client object and set the
// callback.
client_ = new ClientConnection(&main_loop_, new ProtocolDecoder(), this);
*channel_callback = client_.get();
return true;
}
void SimpleHost::OnNewConnection(JingleClient* jingle_client,
scoped_refptr<JingleChannel> channel) {
DCHECK_EQ(jingle_client_.get(), jingle_client);
// Since the session manager has not started, it is still safe to access
// the client directly. Note that we give the ownership of the channel
// to the client.
client_->set_jingle_channel(channel);
}
} // namespace remoting
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include <iostream>
#include "db/test/Test.h"
#include "db/test/Tester.h"
#include "db/test/TestRunner.h"
#include "db/rt/Runnable.h"
#include "db/rt/System.h"
using namespace std;
using namespace db::test;
using namespace db::rt;
void runDynoIterTest1(TestRunner& tr, const char* name, int size, int iter)
{
tr.test(name);
{
DynamicObject d1;
for(int i = 0; i < size; i++)
{
d1[i] = i;
}
uint64_t start = System::getCurrentMilliseconds();
for(int j = 0; j < iter; j++)
{
DynamicObjectIterator i = d1.getIterator();
while(i->hasNext())
{
DynamicObject next = i->next();
}
}
uint64_t stop = System::getCurrentMilliseconds();
cout << "[dt:" << stop-start << "]";
}
tr.passIfNoException();
}
void runDynoIterTest(TestRunner& tr)
{
tr.group("DynamicObject iter perf");
runDynoIterTest1(tr, "array (10k * 1k)", 10000, 1000);
runDynoIterTest1(tr, "array (1k * 10k)", 1000, 10000);
runDynoIterTest1(tr, "array (100 * 100k)", 100, 100000);
runDynoIterTest1(tr, "array (10 * 1M)", 10, 1000000);
tr.ungroup();
}
class DbDynoPerfTester : public db::test::Tester
{
public:
DbDynoPerfTester()
{
setName("dyno-perf");
}
/**
* Run automatic unit tests.
*/
virtual int runAutomaticTests(TestRunner& tr)
{
return 0;
}
/**
* Runs interactive unit tests.
*/
virtual int runInteractiveTests(TestRunner& tr)
{
runDynoIterTest(tr);
return 0;
}
};
#ifndef DB_TEST_NO_MAIN
DB_TEST_MAIN(DbDynoPerfTester)
#endif
<commit_msg>Expand dyno perf test.<commit_after>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include <iostream>
#include "db/test/Test.h"
#include "db/test/Tester.h"
#include "db/test/TestRunner.h"
#include "db/rt/Runnable.h"
#include "db/rt/System.h"
using namespace std;
using namespace db::config;
using namespace db::test;
using namespace db::rt;
static bool header = true;
static void runDynoIterTest1(
TestRunner& tr, const char* name, int dynos, int iter)
{
tr.test(name);
{
uint64_t start_init = System::getCurrentMilliseconds();
DynamicObject d1;
d1->setType(Array);
for(int i = 0; i < dynos; i++)
{
d1[i] = i;
}
uint64_t start_iter = System::getCurrentMilliseconds();
for(int j = 0; j < iter; j++)
{
DynamicObjectIterator i = d1.getIterator();
while(i->hasNext())
{
DynamicObject next = i->next();
}
}
uint64_t iter_dt = System::getCurrentMilliseconds() - start_iter;
uint64_t init_dt = start_iter - start_init;
if(header)
{
printf(
"%9s %9s "
"%8s %9s "
"%8s %10s %9s "
"%9s\n",
"dynos", "iter",
"init (s)", "d/ms",
"iter (s)", "i/s", "(d*i)/ms",
"total (s)");
header = false;
}
printf(
"%9d %9d "
"%8.3f %9.3f "
"%8.3f %10.3f %9.3f "
"%9.3f\n",
dynos, iter,
init_dt/1000.0, dynos/(double)init_dt,
iter_dt/1000.0, iter/(iter_dt/1000.0), (dynos*iter)/(double)iter_dt,
(init_dt + iter_dt)/1000.0);
}
tr.passIfNoException();
}
void runDynoIterTest(TestRunner& tr)
{
tr.group("DynamicObject iter perf");
bool all = false;
Config& cfg = tr.getApp()->getConfig();
if(cfg->hasMember("all"))
{
all = cfg["all"]->getBoolean();
}
if(all)
{
//runDynoIterTest1(tr, "array s:10M i:1 ", 10000000, 1);
runDynoIterTest1(tr, "array s:1M i:1 ", 1000000, 1);
runDynoIterTest1(tr, "array s:1M i:2 ", 1000000, 2);
runDynoIterTest1(tr, "array s:1M i:5 ", 1000000, 5);
runDynoIterTest1(tr, "array s:1M i:10 ", 1000000, 10);
}
runDynoIterTest1(tr, "array s:100K i:100 ", 100000, 100);
runDynoIterTest1(tr, "array s:10K i:1K ", 10000, 1000);
runDynoIterTest1(tr, "array s:1K i:10K ", 1000, 10000);
runDynoIterTest1(tr, "array s:100 i:100K ", 100, 100000);
runDynoIterTest1(tr, "array s:10 i:1M ", 10, 1000000);
if(all)
{
runDynoIterTest1(tr, "array s:5 i:1M ", 5, 1000000);
runDynoIterTest1(tr, "array s:2 i:1M ", 2, 1000000);
runDynoIterTest1(tr, "array s:1 i:1M ", 1, 1000000);
runDynoIterTest1(tr, "array s:0 i:1M ", 0, 1000000);
//runDynoIterTest1(tr, "array s:5 i:2M ", 5, 2000000);
//runDynoIterTest1(tr, "array s:2 i:5M ", 2, 5000000);
//runDynoIterTest1(tr, "array s:1 i:10M ", 1, 10000000);
}
tr.ungroup();
}
class DbDynoPerfTester : public db::test::Tester
{
public:
DbDynoPerfTester()
{
setName("dyno-perf");
}
/**
* Run automatic unit tests.
*/
virtual int runAutomaticTests(TestRunner& tr)
{
return 0;
}
/**
* Runs interactive unit tests.
*/
virtual int runInteractiveTests(TestRunner& tr)
{
runDynoIterTest(tr);
return 0;
}
};
#ifndef DB_TEST_NO_MAIN
DB_TEST_MAIN(DbDynoPerfTester)
#endif
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* 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.
*/
#ifdef CLEVER_DEBUG
#include <stdio.h>
#include "core/opcode.h"
#endif
#include "core/cstring.h"
#include "core/scope.h"
#include "core/value.h"
#include "types/type.h"
#include "core/vm.h"
namespace clever {
// VM initialization phase
inline void VM::init()
{
// Opcode handler mapping
m_handlers[OP_RET] = &VM::ret;
m_handlers[OP_ASSIGN] = &VM::assignment;
m_handlers[OP_ADD] = &VM::add;
m_handlers[OP_SUB] = &VM::sub;
m_handlers[OP_MUL] = &VM::mul;
m_handlers[OP_DIV] = &VM::div;
m_handlers[OP_MOD] = &VM::sub;
m_handlers[OP_JMP] = &VM::jmp;
m_handlers[OP_FCALL] = &VM::fcall;
m_handlers[OP_LEAVE] = &VM::leave;
m_handlers[OP_SEND_VAL] = &VM::send_val;
m_handlers[OP_JMPZ] = &VM::jmpz;
m_handlers[OP_PRE_INC] = &VM::inc;
m_handlers[OP_POS_INC] = &VM::inc;
m_handlers[OP_PRE_DEC] = &VM::dec;
m_handlers[OP_POS_DEC] = &VM::dec;
}
inline Value* VM::getValue(size_t scope_id, size_t value_id) const
{
return (*m_scope_pool)[scope_id]->getValue(value_id);
}
#ifdef CLEVER_DEBUG
void VM::dumpOpcodes() const
{
const char *op_type[] = {
"UNUSED", "FETCH_VAL", "JMP_ADDR"
};
for (size_t i = 0, j = m_inst.size(); i < j; ++i) {
IR& ir = m_inst[i];
::printf("[%03ld] %-12s | %3ld:%3ld (%-9s) | %3ld:%3ld (%-9s) | %p\n",
i,
get_opcode_name(ir.opcode),
ir.op1, ir.op1_scope, op_type[ir.op1_type],
ir.op2, ir.op2_scope, op_type[ir.op2_type],
ir.result);
}
}
#endif
// Return operation
VM_HANDLER(ret)
{
if (m_call_stack.size()) {
const StackFrame& frame = m_call_stack.top();
const Value* val = getValue(op.op1_scope, op.op1);
if (val) {
m_call_stack.top().ret_val->copy(getValue(op.op1_scope, op.op1));
}
m_call_stack.pop();
// Go back to the caller
VM_GOTO(frame.ret_addr);
} else {
// Terminates the execution
VM_GOTO(m_inst.size());
}
}
// JMP operation
VM_HANDLER(jmp)
{
VM_GOTO(op.op1);
}
// JMPZ operation
VM_HANDLER(jmpz)
{
Value* value = getValue(op.op1_scope, op.op1);
if (!value->getInt()) {
VM_GOTO(op.op2);
}
VM_NEXT();
}
// Assignment operation
VM_HANDLER(assignment)
{
Value* var = getValue(op.op1_scope, op.op1);
Value* value = getValue(op.op2_scope, op.op2);
var->copy(value);
VM_NEXT();
}
// Math sum operation
VM_HANDLER(add)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() + rhs->getInt());
}
VM_NEXT();
}
// Math subtraction operation
VM_HANDLER(sub)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() - rhs->getInt());
}
VM_NEXT();
}
// Math multiplication operation
VM_HANDLER(mul)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() * rhs->getInt());
}
VM_NEXT();
}
// Math division operation
VM_HANDLER(div)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() / rhs->getInt());
}
VM_NEXT();
}
// Math modulus operation
VM_HANDLER(mod)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() % rhs->getInt());
}
VM_NEXT();
}
// Receives values to be used in the next function call
VM_HANDLER(send_val)
{
m_call_args.push_back(getValue(op.op1_scope, op.op1));
VM_NEXT();
}
// Saves function argument and local variables
void VM::saveVars()
{/*
Scope* arg_vars = m_call_stack.top().arg_vars;
Scope* local_vars = m_call_stack.top().local_vars;
if (arg_vars) {
// Save the function argument values
for (size_t i = 0, j = arg_vars->size(); i < j; ++i) {
Value* tmp = new Value();
tmp->copy(getValue(arg_vars->at(i).value_id));
m_call_stack.top().vars.push_back(
std::pair<size_t, Value*>(
arg_vars->at(i).value_id, tmp));
}
}
if (EXPECTED(local_vars != NULL)) {
// Save the local variables
for (size_t i = 0, j = local_vars->size(); i < j; ++i) {
Value* tmp = new Value();
tmp->copy(getValue(local_vars->at(i).value_id));
m_call_stack.top().vars.push_back(
std::pair<size_t, Value*>(
local_vars->at(i).value_id, tmp));
}
}*/
}
// Restore the argument and local variables values
void VM::restoreVars() const
{/*
FuncVars::const_iterator it = m_call_stack.top().vars.begin(),
end = m_call_stack.top().vars.end();
while (EXPECTED(it != end)) {
Value* var = getValue((*it).first);
var->copy((*it).second);
++it;
}*/
}
// Function call operation
VM_HANDLER(fcall)
{
Value* func = getValue(op.op1_scope, op.op1);
Function* fdata = static_cast<Function*>(func->getObj());
if (fdata->isUserDefined()) {
// Save arguments and local vars on possible recursion
if (m_call_stack.size()) {
saveVars();
}
// Pushs a new stack frame for the user function call on the call stack
m_call_stack.push(StackFrame());
// Sets the return address to the next instruction
m_call_stack.top().ret_addr = m_pc + 1;
// Save the function return value address
m_call_stack.top().ret_val = op.result;
// Function argument value binding
if (fdata->hasArgs()) {
Scope* arg_scope = fdata->getArgVars();
m_call_stack.top().arg_vars = arg_scope;
for (size_t i = 0, j = arg_scope->size(); i < j; ++i) {
Value* arg_val = getValue(
arg_scope->at(i).scope->getId(), arg_scope->at(i).value_id);
arg_val->copy(m_call_args[i]);
}
m_call_args.clear();
}
VM_GOTO(fdata->getAddr());
} else {
fdata->getPtr()(m_call_args);
m_call_args.clear();
VM_NEXT();
}
}
// Leave operation
VM_HANDLER(leave)
{
const StackFrame& frame = m_call_stack.top();
if (m_call_stack.size() > 1) {
restoreVars();
}
m_call_stack.pop();
// Go back to the next instruction after the caller
VM_GOTO(frame.ret_addr);
}
// Increment operation
VM_HANDLER(inc)
{
Value* value = getValue(op.op1_scope, op.op1);
if (op.opcode == OP_PRE_INC) {
value->getType()->increment(value);
op.result->copy(value);
} else {
op.result->copy(value);
value->getType()->increment(value);
}
VM_NEXT();
}
// Decrement operation
VM_HANDLER(dec)
{
Value* value = getValue(op.op1_scope, op.op1);
if (op.opcode == OP_PRE_DEC) {
value->getType()->decrement(value);
op.result->copy(value);
} else {
op.result->copy(value);
value->getType()->decrement(value);
}
VM_NEXT();
}
// Executes the VM opcodes in a continuation-passing style
void VM::run()
{
// Loads the opcode handlers
init();
for (size_t n = m_inst.size(); m_pc < n;) {
(this->*m_handlers[m_inst[m_pc].opcode])(m_inst[m_pc]);
}
}
} // clever
<commit_msg>- Removed some uneeded comments on VM<commit_after>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* 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.
*/
#ifdef CLEVER_DEBUG
#include <stdio.h>
#include "core/opcode.h"
#endif
#include "core/cstring.h"
#include "core/scope.h"
#include "core/value.h"
#include "types/type.h"
#include "core/vm.h"
namespace clever {
// VM initialization phase
inline void VM::init()
{
// Opcode handler mapping
m_handlers[OP_RET] = &VM::ret;
m_handlers[OP_ASSIGN] = &VM::assignment;
m_handlers[OP_ADD] = &VM::add;
m_handlers[OP_SUB] = &VM::sub;
m_handlers[OP_MUL] = &VM::mul;
m_handlers[OP_DIV] = &VM::div;
m_handlers[OP_MOD] = &VM::sub;
m_handlers[OP_JMP] = &VM::jmp;
m_handlers[OP_FCALL] = &VM::fcall;
m_handlers[OP_LEAVE] = &VM::leave;
m_handlers[OP_SEND_VAL] = &VM::send_val;
m_handlers[OP_JMPZ] = &VM::jmpz;
m_handlers[OP_PRE_INC] = &VM::inc;
m_handlers[OP_POS_INC] = &VM::inc;
m_handlers[OP_PRE_DEC] = &VM::dec;
m_handlers[OP_POS_DEC] = &VM::dec;
}
inline Value* VM::getValue(size_t scope_id, size_t value_id) const
{
return (*m_scope_pool)[scope_id]->getValue(value_id);
}
#ifdef CLEVER_DEBUG
void VM::dumpOpcodes() const
{
const char *op_type[] = {
"UNUSED", "FETCH_VAL", "JMP_ADDR"
};
for (size_t i = 0, j = m_inst.size(); i < j; ++i) {
IR& ir = m_inst[i];
::printf("[%03ld] %-12s | %3ld:%3ld (%-9s) | %3ld:%3ld (%-9s) | %p\n",
i,
get_opcode_name(ir.opcode),
ir.op1, ir.op1_scope, op_type[ir.op1_type],
ir.op2, ir.op2_scope, op_type[ir.op2_type],
ir.result);
}
}
#endif
// Return operation
VM_HANDLER(ret)
{
if (m_call_stack.size()) {
const StackFrame& frame = m_call_stack.top();
const Value* val = getValue(op.op1_scope, op.op1);
if (val) {
m_call_stack.top().ret_val->copy(getValue(op.op1_scope, op.op1));
}
m_call_stack.pop();
// Go back to the caller
VM_GOTO(frame.ret_addr);
} else {
// Terminates the execution
VM_GOTO(m_inst.size());
}
}
// JMP operation
VM_HANDLER(jmp)
{
VM_GOTO(op.op1);
}
// JMPZ operation
VM_HANDLER(jmpz)
{
Value* value = getValue(op.op1_scope, op.op1);
if (!value->getInt()) {
VM_GOTO(op.op2);
}
VM_NEXT();
}
// Assignment operation
VM_HANDLER(assignment)
{
Value* var = getValue(op.op1_scope, op.op1);
Value* value = getValue(op.op2_scope, op.op2);
var->copy(value);
VM_NEXT();
}
// Math sum operation
VM_HANDLER(add)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() + rhs->getInt());
}
VM_NEXT();
}
// Math subtraction operation
VM_HANDLER(sub)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() - rhs->getInt());
}
VM_NEXT();
}
// Math multiplication operation
VM_HANDLER(mul)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() * rhs->getInt());
}
VM_NEXT();
}
// Math division operation
VM_HANDLER(div)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() / rhs->getInt());
}
VM_NEXT();
}
// Math modulus operation
VM_HANDLER(mod)
{
Value* lhs = getValue(op.op1_scope, op.op1);
Value* rhs = getValue(op.op2_scope, op.op2);
if (lhs->getType() == CLEVER_INT_TYPE
&& rhs->getType() == CLEVER_INT_TYPE) {
op.result->setInt(lhs->getInt() % rhs->getInt());
}
VM_NEXT();
}
// Receives values to be used in the next function call
VM_HANDLER(send_val)
{
m_call_args.push_back(getValue(op.op1_scope, op.op1));
VM_NEXT();
}
// Saves function argument and local variables
void VM::saveVars()
{/*
Scope* arg_vars = m_call_stack.top().arg_vars;
Scope* local_vars = m_call_stack.top().local_vars;
if (arg_vars) {
// Save the function argument values
for (size_t i = 0, j = arg_vars->size(); i < j; ++i) {
Value* tmp = new Value();
tmp->copy(getValue(arg_vars->at(i).value_id));
m_call_stack.top().vars.push_back(
std::pair<size_t, Value*>(
arg_vars->at(i).value_id, tmp));
}
}
if (EXPECTED(local_vars != NULL)) {
// Save the local variables
for (size_t i = 0, j = local_vars->size(); i < j; ++i) {
Value* tmp = new Value();
tmp->copy(getValue(local_vars->at(i).value_id));
m_call_stack.top().vars.push_back(
std::pair<size_t, Value*>(
local_vars->at(i).value_id, tmp));
}
}*/
}
// Restore the argument and local variables values
void VM::restoreVars() const
{/*
FuncVars::const_iterator it = m_call_stack.top().vars.begin(),
end = m_call_stack.top().vars.end();
while (EXPECTED(it != end)) {
Value* var = getValue((*it).first);
var->copy((*it).second);
++it;
}*/
}
// Function call operation
VM_HANDLER(fcall)
{
Value* func = getValue(op.op1_scope, op.op1);
Function* fdata = static_cast<Function*>(func->getObj());
if (fdata->isUserDefined()) {
if (m_call_stack.size()) {
saveVars();
}
m_call_stack.push(StackFrame());
m_call_stack.top().ret_addr = m_pc + 1;
m_call_stack.top().ret_val = op.result;
// Function argument value binding
if (fdata->hasArgs()) {
Scope* arg_scope = fdata->getArgVars();
m_call_stack.top().arg_vars = arg_scope;
for (size_t i = 0, j = arg_scope->size(); i < j; ++i) {
Value* arg_val = getValue(
arg_scope->at(i).scope->getId(),
arg_scope->at(i).value_id);
arg_val->copy(m_call_args[i]);
}
m_call_args.clear();
}
VM_GOTO(fdata->getAddr());
} else {
fdata->getPtr()(m_call_args);
m_call_args.clear();
VM_NEXT();
}
}
// Leave operation
VM_HANDLER(leave)
{
const StackFrame& frame = m_call_stack.top();
if (m_call_stack.size() > 1) {
restoreVars();
}
m_call_stack.pop();
// Go back to the next instruction after the caller
VM_GOTO(frame.ret_addr);
}
// Increment operation
VM_HANDLER(inc)
{
Value* value = getValue(op.op1_scope, op.op1);
if (op.opcode == OP_PRE_INC) {
value->getType()->increment(value);
op.result->copy(value);
} else {
op.result->copy(value);
value->getType()->increment(value);
}
VM_NEXT();
}
// Decrement operation
VM_HANDLER(dec)
{
Value* value = getValue(op.op1_scope, op.op1);
if (op.opcode == OP_PRE_DEC) {
value->getType()->decrement(value);
op.result->copy(value);
} else {
op.result->copy(value);
value->getType()->decrement(value);
}
VM_NEXT();
}
// Executes the VM opcodes in a continuation-passing style
void VM::run()
{
// Loads the opcode handlers
init();
for (size_t n = m_inst.size(); m_pc < n;) {
(this->*m_handlers[m_inst[m_pc].opcode])(m_inst[m_pc]);
}
}
} // clever
<|endoftext|> |
<commit_before>#include <boost/program_options.hpp>
#include <boost/optional.hpp>
#include <iostream>
#include <boost/thread.hpp>
#include <silicium/http/receive_request.hpp>
#include <silicium/asio/tcp_acceptor.hpp>
#include <silicium/asio/writing_observable.hpp>
#include <silicium/observable/spawn_coroutine.hpp>
#include <silicium/observable/spawn_observable.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <silicium/http/generate_response.hpp>
#include <silicium/observable/total_consumer.hpp>
#include <silicium/boost_threading.hpp>
#include <silicium/run_process.hpp>
#include <functional>
#include "server/find_cmake.hpp"
#include "server/find_gcc.hpp"
#include "server/find_executable.hpp"
#include "server/cmake.hpp"
namespace
{
template <class AsyncWriteStream, class YieldContext, class Status, class StatusText>
void quick_final_response(AsyncWriteStream &client, YieldContext &&yield, Status &&status, StatusText &&status_text, std::string const &content)
{
std::vector<char> response;
{
auto response_writer = Si::make_container_sink(response);
Si::http::generate_status_line(response_writer, "HTTP/1.0", std::forward<Status>(status), std::forward<StatusText>(status_text));
Si::http::generate_header(response_writer, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size()));
Si::append(response_writer, "\r\n");
Si::append(response_writer, content);
}
//you can handle the error if you want
boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield);
//ignore shutdown failures, they do not matter here
client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
}
struct notification
{
};
struct notification_server
{
typedef notification element_type;
notification_server(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint endpoint, Si::noexcept_string secret)
: m_server(
Si::erase_unique(
Si::transform(
Si::asio::make_tcp_acceptor(boost::asio::ip::tcp::acceptor(io, endpoint)),
[this](Si::asio::tcp_acceptor_result maybe_client) -> Si::nothing
{
auto client = maybe_client.get();
Si::spawn_coroutine([this, client](Si::spawn_context yield)
{
serve_client(*client, yield);
});
return{};
}
)
)
)
, m_is_running(false)
, m_secret(std::move(secret))
{
}
void async_get_one(Si::ptr_observer<Si::observer<element_type>> observer)
{
if (!m_is_running)
{
m_server.start();
m_is_running = true;
}
return Si::visit<void>(
m_observer_or_notification,
[this, observer](Si::observer<element_type> * &my_observer)
{
assert(!my_observer);
my_observer = observer.get();
},
[this, observer](notification)
{
m_observer_or_notification = static_cast<Si::observer<element_type> *>(nullptr);
observer.got_element(notification());
}
);
}
private:
Si::total_consumer<Si::unique_observable<Si::nothing>> m_server;
bool m_is_running;
Si::noexcept_string m_secret;
Si::fast_variant<Si::observer<element_type> *, notification> m_observer_or_notification;
template <class YieldContext>
void serve_client(boost::asio::ip::tcp::socket &client, YieldContext &&yield)
{
Si::error_or<boost::optional<Si::http::request>> maybe_request = Si::http::receive_request(client, yield);
if (maybe_request.is_error())
{
std::cerr << client.remote_endpoint().address() << ": " << maybe_request.error() << '\n';
return;
}
if (!maybe_request.get())
{
return;
}
Si::http::request const &request = *maybe_request.get();
if (std::string::npos == request.path.find(m_secret))
{
quick_final_response(client, yield, "403", "Forbidden", "the path does not contain the correct secret");
return;
}
Si::visit<void>(
m_observer_or_notification,
[](Si::observer<element_type> * &observer)
{
Si::exchange(observer, nullptr)->got_element(notification());
},
[](notification const &)
{
}
);
quick_final_response(client, yield, "200", "OK", "the server has been successfully notified");
}
};
struct options
{
std::string repository;
boost::uint16_t port;
Si::noexcept_string secret;
};
boost::optional<options> parse_options(int argc, char **argv)
{
options result;
result.port = 8080;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("repository,r", boost::program_options::value(&result.repository), "the URI for git cloning the code")
("port,p", boost::program_options::value(&result.port), "port to listen on for POSTed push notifications")
("secret,s", boost::program_options::value(&result.secret), "a string that needs to be in the query for the notification to be accepted")
;
boost::program_options::positional_options_description positional;
positional.add("repository", 1);
positional.add("port", 1);
positional.add("secret", 1);
boost::program_options::variables_map vm;
try
{
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);
}
catch (boost::program_options::error const &ex)
{
std::cerr
<< ex.what() << '\n'
<< desc << "\n";
return boost::none;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cerr << desc << "\n";
return boost::none;
}
if (result.repository.empty())
{
std::cerr << "Missing option value --repository\n";
std::cerr << desc << "\n";
return boost::none;
}
return std::move(result);
}
enum class build_result
{
success,
failure,
missing_dependency
};
Si::error_or<boost::optional<boost::filesystem::path>> find_git()
{
return buildserver::find_executable_unix("git", {});
}
void git_clone(std::string const &repository, boost::filesystem::path const &destination, boost::filesystem::path const &git_exe)
{
Si::process_parameters parameters;
parameters.executable = git_exe;
parameters.current_path = destination.parent_path();
parameters.arguments = {"clone", repository, destination.string()};
if (Si::run_process(parameters) != 0)
{
throw std::runtime_error("git-clone failed");
}
}
build_result build(std::string const &repository, boost::filesystem::path const &workspace)
{
boost::optional<boost::filesystem::path> maybe_git = find_git().get();
if (!maybe_git)
{
return build_result::missing_dependency;
}
boost::optional<boost::filesystem::path> maybe_cmake = buildserver::find_cmake().get();
if (!maybe_cmake)
{
return build_result::missing_dependency;
}
boost::filesystem::path const source = workspace / "source.git";
git_clone(repository, source, *maybe_git);
boost::filesystem::path const build = workspace / "build";
boost::filesystem::create_directories(build);
buildserver::cmake_exe cmake(*maybe_cmake);
boost::system::error_code error = cmake.generate(source, build, {});
if (error)
{
boost::throw_exception(boost::system::system_error(error));
}
error = cmake.build(build, boost::thread::hardware_concurrency());
if (error)
{
boost::throw_exception(boost::system::system_error(error));
}
return build_result::success;
}
}
namespace Si
{
template <class Element, class ThreadingAPI>
struct thread_observable2
{
typedef Element element_type;
explicit thread_observable2(std::function<element_type ()> action)
: m_action(std::move(action))
{
}
template <class Observer>
void async_get_one(Observer &&observer)
{
assert(m_action);
auto action = std::move(m_action);
m_worker = ThreadingAPI::launch_async([
observer
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
= std::forward<Observer>(observer)
#endif
,
action
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
= std::move(action)
#endif
]() mutable
{
std::forward<Observer>(observer).got_element(action());
});
}
private:
std::function<element_type ()> m_action;
typename ThreadingAPI::template future<void>::type m_worker;
};
template <class ThreadingAPI, class Action>
auto make_thread_observable2(Action &&action)
{
return thread_observable2<decltype(action()), ThreadingAPI>(std::forward<Action>(action));
}
template <class Next>
struct posting_observable : private observer<typename Next::element_type>
{
typedef typename Next::element_type element_type;
explicit posting_observable(boost::asio::io_service &io, Next next)
: m_io(&io)
, m_observer(nullptr)
, m_next(std::move(next))
{
}
template <class Observer>
void async_get_one(Observer &&observer_)
{
m_observer = observer_.get();
m_next.async_get_one(extend(std::forward<Observer>(observer_), observe_by_ref(static_cast<observer<element_type> &>(*this))));
}
private:
boost::asio::io_service *m_io;
observer<element_type> *m_observer;
Next m_next;
virtual void got_element(element_type value) SILICIUM_OVERRIDE
{
auto observer_ = Si::exchange(m_observer, nullptr);
m_io->post([observer_, value = std::move(value)]() mutable
{
observer_->got_element(std::move(value));
});
}
virtual void ended() SILICIUM_OVERRIDE
{
auto observer_ = Si::exchange(m_observer, nullptr);
m_io->post([observer_]() mutable
{
observer_->ended();
});
}
};
template <class Next>
auto make_posting_observable(boost::asio::io_service &io, Next &&next)
{
return posting_observable<typename std::decay<Next>::type>(io, std::forward<Next>(next));
}
}
int main(int argc, char **argv)
{
auto parsed_options = parse_options(argc, argv);
if (!parsed_options)
{
return 1;
}
//TODO: make the workspace configurable
boost::filesystem::path const &workspace = boost::filesystem::current_path();
boost::asio::io_service io;
notification_server notifications(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::any(), parsed_options->port), parsed_options->secret);
auto all_done = Si::make_total_consumer(
Si::transform(
Si::ref(notifications),
[&](boost::optional<notification> element)
{
assert(element);
std::cerr << "Received a notification\n";
try
{
Si::spawn_observable(
Si::transform(
Si::make_posting_observable(
io,
Si::make_thread_observable2<Si::boost_threading>([&]()
{
boost::filesystem::remove_all(workspace);
boost::filesystem::create_directories(workspace);
return build(parsed_options->repository, workspace);
})
),
[](build_result result)
{
switch (result)
{
case build_result::success:
std::cerr << "Build success\n";
break;
case build_result::failure:
std::cerr << "Build failure\n";
break;
case build_result::missing_dependency:
std::cerr << "Build dependency missing\n";
break;
}
return Si::nothing();
}
)
);
}
catch (std::exception const &ex)
{
std::cerr << "Exception: " << ex.what() << '\n';
}
return Si::nothing();
}
)
);
all_done.start();
io.run();
}
<commit_msg>thread_observable2 calls ended() when finished<commit_after>#include <boost/program_options.hpp>
#include <boost/optional.hpp>
#include <iostream>
#include <boost/thread.hpp>
#include <silicium/http/receive_request.hpp>
#include <silicium/asio/tcp_acceptor.hpp>
#include <silicium/asio/writing_observable.hpp>
#include <silicium/observable/spawn_coroutine.hpp>
#include <silicium/observable/spawn_observable.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <silicium/http/generate_response.hpp>
#include <silicium/observable/total_consumer.hpp>
#include <silicium/boost_threading.hpp>
#include <silicium/run_process.hpp>
#include <functional>
#include "server/find_cmake.hpp"
#include "server/find_gcc.hpp"
#include "server/find_executable.hpp"
#include "server/cmake.hpp"
namespace
{
template <class AsyncWriteStream, class YieldContext, class Status, class StatusText>
void quick_final_response(AsyncWriteStream &client, YieldContext &&yield, Status &&status, StatusText &&status_text, std::string const &content)
{
std::vector<char> response;
{
auto response_writer = Si::make_container_sink(response);
Si::http::generate_status_line(response_writer, "HTTP/1.0", std::forward<Status>(status), std::forward<StatusText>(status_text));
Si::http::generate_header(response_writer, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size()));
Si::append(response_writer, "\r\n");
Si::append(response_writer, content);
}
//you can handle the error if you want
boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield);
//ignore shutdown failures, they do not matter here
client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
}
struct notification
{
};
template <class Observer>
struct notification_server
{
typedef notification element_type;
notification_server(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint endpoint, Si::noexcept_string secret)
: m_server(
Si::erase_unique(
Si::transform(
Si::asio::make_tcp_acceptor(boost::asio::ip::tcp::acceptor(io, endpoint)),
[this](Si::asio::tcp_acceptor_result maybe_client) -> Si::nothing
{
auto client = maybe_client.get();
Si::spawn_coroutine([this, client](Si::spawn_context yield)
{
serve_client(*client, yield);
});
return{};
}
)
)
)
, m_is_running(false)
, m_secret(std::move(secret))
{
}
void async_get_one(Observer observer)
{
if (!m_is_running)
{
m_server.start();
m_is_running = true;
}
return Si::visit<void>(
m_observer_or_notification,
[this, &observer](Observer &my_observer) mutable
{
assert(!my_observer.get());
my_observer = std::move(observer);
},
[this, &observer](notification)
{
m_observer_or_notification = Observer();
std::move(observer).got_element(notification());
}
);
}
private:
Si::total_consumer<Si::unique_observable<Si::nothing>> m_server;
bool m_is_running;
Si::noexcept_string m_secret;
Si::fast_variant<Observer, notification> m_observer_or_notification;
template <class YieldContext>
void serve_client(boost::asio::ip::tcp::socket &client, YieldContext &&yield)
{
Si::error_or<boost::optional<Si::http::request>> maybe_request = Si::http::receive_request(client, yield);
if (maybe_request.is_error())
{
std::cerr << client.remote_endpoint().address() << ": " << maybe_request.error() << '\n';
return;
}
if (!maybe_request.get())
{
return;
}
Si::http::request const &request = *maybe_request.get();
if (std::string::npos == request.path.find(m_secret))
{
quick_final_response(client, yield, "403", "Forbidden", "the path does not contain the correct secret");
return;
}
Si::visit<void>(
m_observer_or_notification,
[](Observer &observer)
{
Si::exchange(observer, Observer()).got_element(notification());
},
[](notification const &)
{
}
);
quick_final_response(client, yield, "200", "OK", "the server has been successfully notified");
}
};
struct options
{
std::string repository;
boost::uint16_t port;
Si::noexcept_string secret;
};
boost::optional<options> parse_options(int argc, char **argv)
{
options result;
result.port = 8080;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("repository,r", boost::program_options::value(&result.repository), "the URI for git cloning the code")
("port,p", boost::program_options::value(&result.port), "port to listen on for POSTed push notifications")
("secret,s", boost::program_options::value(&result.secret), "a string that needs to be in the query for the notification to be accepted")
;
boost::program_options::positional_options_description positional;
positional.add("repository", 1);
positional.add("port", 1);
positional.add("secret", 1);
boost::program_options::variables_map vm;
try
{
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);
}
catch (boost::program_options::error const &ex)
{
std::cerr
<< ex.what() << '\n'
<< desc << "\n";
return boost::none;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cerr << desc << "\n";
return boost::none;
}
if (result.repository.empty())
{
std::cerr << "Missing option value --repository\n";
std::cerr << desc << "\n";
return boost::none;
}
return std::move(result);
}
enum class build_result
{
success,
failure,
missing_dependency
};
Si::error_or<boost::optional<boost::filesystem::path>> find_git()
{
return buildserver::find_executable_unix("git", {});
}
void git_clone(std::string const &repository, boost::filesystem::path const &destination, boost::filesystem::path const &git_exe)
{
Si::process_parameters parameters;
parameters.executable = git_exe;
parameters.current_path = destination.parent_path();
parameters.arguments = {"clone", repository, destination.string()};
if (Si::run_process(parameters) != 0)
{
throw std::runtime_error("git-clone failed");
}
}
build_result build(std::string const &repository, boost::filesystem::path const &workspace)
{
boost::optional<boost::filesystem::path> maybe_git = find_git().get();
if (!maybe_git)
{
return build_result::missing_dependency;
}
boost::optional<boost::filesystem::path> maybe_cmake = buildserver::find_cmake().get();
if (!maybe_cmake)
{
return build_result::missing_dependency;
}
boost::filesystem::path const source = workspace / "source.git";
git_clone(repository, source, *maybe_git);
boost::filesystem::path const build = workspace / "build";
boost::filesystem::create_directories(build);
buildserver::cmake_exe cmake(*maybe_cmake);
boost::system::error_code error = cmake.generate(source, build, {});
if (error)
{
boost::throw_exception(boost::system::system_error(error));
}
error = cmake.build(build, boost::thread::hardware_concurrency());
if (error)
{
boost::throw_exception(boost::system::system_error(error));
}
return build_result::success;
}
}
namespace Si
{
template <class Element, class ThreadingAPI>
struct thread_observable2
{
typedef Element element_type;
explicit thread_observable2(std::function<element_type ()> action)
: m_action(std::move(action))
, m_has_finished(false)
{
}
template <class Observer>
void async_get_one(Observer &&observer)
{
if (m_has_finished)
{
return std::forward<Observer>(observer).ended();
}
assert(m_action);
auto action = std::move(m_action);
m_worker = ThreadingAPI::launch_async([
this,
observer
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
= std::forward<Observer>(observer)
#endif
,
action
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
= std::move(action)
#endif
]() mutable
{
m_has_finished = true;
std::forward<Observer>(observer).got_element(action());
});
}
private:
std::function<element_type ()> m_action;
typename ThreadingAPI::template future<void>::type m_worker;
bool m_has_finished;
};
template <class ThreadingAPI, class Action>
auto make_thread_observable2(Action &&action)
{
return thread_observable2<decltype(action()), ThreadingAPI>(std::forward<Action>(action));
}
template <class Next>
struct posting_observable : private observer<typename Next::element_type>
{
typedef typename Next::element_type element_type;
explicit posting_observable(boost::asio::io_service &io, Next next)
: m_io(&io)
, m_observer(nullptr)
, m_next(std::move(next))
{
}
template <class Observer>
void async_get_one(Observer &&observer_)
{
m_observer = observer_.get();
m_next.async_get_one(extend(std::forward<Observer>(observer_), observe_by_ref(static_cast<observer<element_type> &>(*this))));
}
private:
boost::asio::io_service *m_io;
observer<element_type> *m_observer;
Next m_next;
virtual void got_element(element_type value) SILICIUM_OVERRIDE
{
auto observer_ = Si::exchange(m_observer, nullptr);
m_io->post([observer_, value = std::move(value)]() mutable
{
observer_->got_element(std::move(value));
});
}
virtual void ended() SILICIUM_OVERRIDE
{
auto observer_ = Si::exchange(m_observer, nullptr);
m_io->post([observer_]() mutable
{
observer_->ended();
});
}
};
template <class Next>
auto make_posting_observable(boost::asio::io_service &io, Next &&next)
{
return posting_observable<typename std::decay<Next>::type>(io, std::forward<Next>(next));
}
}
int main(int argc, char **argv)
{
auto parsed_options = parse_options(argc, argv);
if (!parsed_options)
{
return 1;
}
//TODO: make the workspace configurable
boost::filesystem::path const &workspace = boost::filesystem::current_path();
boost::asio::io_service io;
notification_server<Si::ptr_observer<Si::observer<notification>>> notifications(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::any(), parsed_options->port), parsed_options->secret);
auto all_done = Si::make_total_consumer(
Si::transform(
Si::ref(notifications),
[&](boost::optional<notification> element)
{
assert(element);
std::cerr << "Received a notification\n";
try
{
Si::spawn_observable(
Si::transform(
Si::make_posting_observable(
io,
Si::make_thread_observable2<Si::boost_threading>([&]()
{
boost::filesystem::remove_all(workspace);
boost::filesystem::create_directories(workspace);
return build(parsed_options->repository, workspace);
})
),
[](build_result result)
{
switch (result)
{
case build_result::success:
std::cerr << "Build success\n";
break;
case build_result::failure:
std::cerr << "Build failure\n";
break;
case build_result::missing_dependency:
std::cerr << "Build dependency missing\n";
break;
}
return Si::nothing();
}
)
);
}
catch (std::exception const &ex)
{
std::cerr << "Exception: " << ex.what() << '\n';
}
return Si::nothing();
}
)
);
all_done.start();
io.run();
}
<|endoftext|> |
<commit_before>// Frame.cpp
#include "Frame.h"
#include "Application.h"
#include "Puzzle.h"
#include "Canvas.h"
#include <wx/menu.h>
#include <wx/aboutdlg.h>
#include <wx/msgdlg.h>
#include <wx/sizer.h>
Frame::Frame( void ) : wxFrame( 0, wxID_ANY, "Symmetry Group Madness" ), timer( this, ID_Timer )
{
wxMenu* gameMenu = new wxMenu();
wxMenuItem* newGameMenuItem = new wxMenuItem( gameMenu, ID_NewGame, "New Game", "Start a new game at level 1." );
wxMenuItem* saveGameMenuItem = new wxMenuItem( gameMenu, ID_SaveGame, "Save Game", "Save your current game to disk." );
wxMenuItem* loadGameMenuItem = new wxMenuItem( gameMenu, ID_LoadGame, "Load Game", "Load a previously saved game from disk." );
wxMenuItem* exitMenuItem = new wxMenuItem( gameMenu, ID_Exit, "Exit", "Exit this program." );
gameMenu->Append( newGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( saveGameMenuItem );
gameMenu->Append( loadGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( exitMenuItem );
wxMenu* helpMenu = new wxMenu();
wxMenuItem* solveMenuItem = new wxMenuItem( helpMenu, ID_Solve, "Solve", "Let the computer attempt to find a solution to the puzzle." );
wxMenuItem* aboutMenuItem = new wxMenuItem( helpMenu, ID_About, "About", "Show the about-box." );
helpMenu->Append( solveMenuItem );
helpMenu->AppendSeparator();
helpMenu->Append( aboutMenuItem );
wxMenuBar* menuBar = new wxMenuBar();
menuBar->Append( gameMenu, "Game" );
menuBar->Append( helpMenu, "Help" );
SetMenuBar( menuBar );
wxStatusBar* statusBar = new wxStatusBar( this );
SetStatusBar( statusBar );
Bind( wxEVT_MENU, &Frame::OnNewGame, this, ID_NewGame );
Bind( wxEVT_MENU, &Frame::OnSaveGame, this, ID_SaveGame );
Bind( wxEVT_MENU, &Frame::OnLoadGame, this, ID_LoadGame );
Bind( wxEVT_MENU, &Frame::OnSolve, this, ID_Solve );
Bind( wxEVT_MENU, &Frame::OnExit, this, ID_Exit );
Bind( wxEVT_MENU, &Frame::OnAbout, this, ID_About );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_NewGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_SaveGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_LoadGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_Solve );
Bind( wxEVT_TIMER, &Frame::OnTimer, this, ID_Timer );
canvas = new Canvas( this );
wxBoxSizer* boxSizer = new wxBoxSizer( wxVERTICAL );
boxSizer->Add( canvas, 1, wxGROW );
SetSizer( boxSizer );
timer.Start(1);
}
/*virtual*/ Frame::~Frame( void )
{
}
void Frame::OnExit( wxCommandEvent& event )
{
if( wxGetApp().SetPuzzle( nullptr ) )
Close( true );
}
void Frame::OnAbout( wxCommandEvent& event )
{
wxAboutDialogInfo aboutDialogInfo;
aboutDialogInfo.SetName( "Symmetry Group Madness" );
aboutDialogInfo.SetVersion( "1.0" );
aboutDialogInfo.SetDescription( "This program is free software and distributed under the MIT license." );
aboutDialogInfo.SetCopyright( "Copyright (C) 2016 Spencer T. Parkin <[email protected]>" );
//aboutDialogInfo.SetWebSite( "http://spencerparkin.github.io/SymmetryGroupMadness" );
wxAboutBox( aboutDialogInfo );
}
void Frame::OnTimer( wxTimerEvent& event )
{
canvas->Refresh();
}
void Frame::OnSolve( wxCommandEvent& event )
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
if( puzzle )
{
timer.Stop();
if( puzzle->EnqueueSolution() )
{
int solutionSize = ( int )puzzle->autoRotationQueue.size();
if( wxYES != wxMessageBox( wxString::Format( "A solution was found with %d moves. Run solution?", solutionSize ), "Solution found!", wxICON_EXCLAMATION | wxYES_NO, this ) )
puzzle->autoRotationQueue.clear();
}
else
{
wxMessageBox( "Failed to find a solution. I suck.", "Solution not found.", wxICON_ERROR, this );
}
timer.Start(1);
}
}
void Frame::OnNewGame( wxCommandEvent& event )
{
if( wxGetApp().SetPuzzle( nullptr ) )
{
Puzzle* puzzle = new Puzzle();
puzzle->SetupLevel(1);
wxGetApp().SetPuzzle( puzzle );
canvas->Refresh();
}
}
void Frame::OnSaveGame( wxCommandEvent& event )
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
if( puzzle )
puzzle->Save();
}
void Frame::OnLoadGame( wxCommandEvent& event )
{
wxGetApp().SetPuzzle( nullptr );
Puzzle* puzzle = new Puzzle();
if( !puzzle->Load() )
delete puzzle;
else
wxGetApp().SetPuzzle( puzzle );
canvas->Refresh();
}
void Frame::OnUpdateMenuItemUI( wxUpdateUIEvent& event )
{
switch( event.GetId() )
{
case ID_NewGame:
{
event.Enable( true );
break;
}
case ID_SaveGame:
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
event.Enable( ( puzzle && puzzle->modified ) ? true : false );
break;
}
case ID_LoadGame:
{
event.Enable( true );
break;
}
case ID_Solve:
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
event.Enable( puzzle && !puzzle->GetPermutation().IsIdentity() );
break;
}
}
}
// Frame.cpp
<commit_msg>unfortunate bug<commit_after>// Frame.cpp
#include "Frame.h"
#include "Application.h"
#include "Puzzle.h"
#include "Canvas.h"
#include <wx/menu.h>
#include <wx/aboutdlg.h>
#include <wx/msgdlg.h>
#include <wx/sizer.h>
// BUG: The "percent solved" thing as not only a bit dumb, but, due probably to round-off error,
// it is also not always accurate enough to detect when the puzzle is actually solved. If every
// puzzle had its permutation group encoded, then we could use that as a possibly fool-proof way
// to know when the puzzle is in the solved state.
Frame::Frame( void ) : wxFrame( 0, wxID_ANY, "Symmetry Group Madness" ), timer( this, ID_Timer )
{
wxMenu* gameMenu = new wxMenu();
wxMenuItem* newGameMenuItem = new wxMenuItem( gameMenu, ID_NewGame, "New Game", "Start a new game at level 1." );
wxMenuItem* saveGameMenuItem = new wxMenuItem( gameMenu, ID_SaveGame, "Save Game", "Save your current game to disk." );
wxMenuItem* loadGameMenuItem = new wxMenuItem( gameMenu, ID_LoadGame, "Load Game", "Load a previously saved game from disk." );
wxMenuItem* exitMenuItem = new wxMenuItem( gameMenu, ID_Exit, "Exit", "Exit this program." );
gameMenu->Append( newGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( saveGameMenuItem );
gameMenu->Append( loadGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( exitMenuItem );
wxMenu* helpMenu = new wxMenu();
wxMenuItem* solveMenuItem = new wxMenuItem( helpMenu, ID_Solve, "Solve", "Let the computer attempt to find a solution to the puzzle." );
wxMenuItem* aboutMenuItem = new wxMenuItem( helpMenu, ID_About, "About", "Show the about-box." );
helpMenu->Append( solveMenuItem );
helpMenu->AppendSeparator();
helpMenu->Append( aboutMenuItem );
wxMenuBar* menuBar = new wxMenuBar();
menuBar->Append( gameMenu, "Game" );
menuBar->Append( helpMenu, "Help" );
SetMenuBar( menuBar );
wxStatusBar* statusBar = new wxStatusBar( this );
SetStatusBar( statusBar );
Bind( wxEVT_MENU, &Frame::OnNewGame, this, ID_NewGame );
Bind( wxEVT_MENU, &Frame::OnSaveGame, this, ID_SaveGame );
Bind( wxEVT_MENU, &Frame::OnLoadGame, this, ID_LoadGame );
Bind( wxEVT_MENU, &Frame::OnSolve, this, ID_Solve );
Bind( wxEVT_MENU, &Frame::OnExit, this, ID_Exit );
Bind( wxEVT_MENU, &Frame::OnAbout, this, ID_About );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_NewGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_SaveGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_LoadGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_Solve );
Bind( wxEVT_TIMER, &Frame::OnTimer, this, ID_Timer );
canvas = new Canvas( this );
wxBoxSizer* boxSizer = new wxBoxSizer( wxVERTICAL );
boxSizer->Add( canvas, 1, wxGROW );
SetSizer( boxSizer );
timer.Start(1);
}
/*virtual*/ Frame::~Frame( void )
{
}
void Frame::OnExit( wxCommandEvent& event )
{
if( wxGetApp().SetPuzzle( nullptr ) )
Close( true );
}
void Frame::OnAbout( wxCommandEvent& event )
{
wxAboutDialogInfo aboutDialogInfo;
aboutDialogInfo.SetName( "Symmetry Group Madness" );
aboutDialogInfo.SetVersion( "1.0" );
aboutDialogInfo.SetDescription( "This program is free software and distributed under the MIT license." );
aboutDialogInfo.SetCopyright( "Copyright (C) 2016 Spencer T. Parkin <[email protected]>" );
//aboutDialogInfo.SetWebSite( "http://spencerparkin.github.io/SymmetryGroupMadness" );
wxAboutBox( aboutDialogInfo );
}
void Frame::OnTimer( wxTimerEvent& event )
{
canvas->Refresh();
}
void Frame::OnSolve( wxCommandEvent& event )
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
if( puzzle )
{
timer.Stop();
if( puzzle->EnqueueSolution() )
{
int solutionSize = ( int )puzzle->autoRotationQueue.size();
if( wxYES != wxMessageBox( wxString::Format( "A solution was found with %d moves. Run solution?", solutionSize ), "Solution found!", wxICON_EXCLAMATION | wxYES_NO, this ) )
puzzle->autoRotationQueue.clear();
}
else
{
wxMessageBox( "Failed to find a solution. I suck.", "Solution not found.", wxICON_ERROR, this );
}
timer.Start(1);
}
}
void Frame::OnNewGame( wxCommandEvent& event )
{
if( wxGetApp().SetPuzzle( nullptr ) )
{
Puzzle* puzzle = new Puzzle();
puzzle->SetupLevel(1);
wxGetApp().SetPuzzle( puzzle );
canvas->Refresh();
}
}
void Frame::OnSaveGame( wxCommandEvent& event )
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
if( puzzle )
puzzle->Save();
}
void Frame::OnLoadGame( wxCommandEvent& event )
{
wxGetApp().SetPuzzle( nullptr );
Puzzle* puzzle = new Puzzle();
if( !puzzle->Load() )
delete puzzle;
else
wxGetApp().SetPuzzle( puzzle );
canvas->Refresh();
}
void Frame::OnUpdateMenuItemUI( wxUpdateUIEvent& event )
{
switch( event.GetId() )
{
case ID_NewGame:
{
event.Enable( true );
break;
}
case ID_SaveGame:
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
event.Enable( ( puzzle && puzzle->modified ) ? true : false );
break;
}
case ID_LoadGame:
{
event.Enable( true );
break;
}
case ID_Solve:
{
Puzzle* puzzle = wxGetApp().GetPuzzle();
event.Enable( puzzle && !puzzle->GetPermutation().IsIdentity() );
break;
}
}
}
// Frame.cpp
<|endoftext|> |
<commit_before>//===-- buffer_queue_test.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a function call tracing system.
//
//===----------------------------------------------------------------------===//
#include "xray_buffer_queue.h"
#include "gtest/gtest.h"
#include <future>
#include <system_error>
#include <unistd.h>
namespace __xray {
static constexpr size_t kSize = 4096;
TEST(BufferQueueTest, API) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
}
TEST(BufferQueueTest, GetAndRelease) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf;
ASSERT_EQ(Buffers.getBuffer(Buf), std::error_code());
ASSERT_NE(nullptr, Buf.Buffer);
ASSERT_EQ(Buffers.releaseBuffer(Buf), std::error_code());
ASSERT_EQ(nullptr, Buf.Buffer);
}
TEST(BufferQueueTest, GetUntilFailed) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf0;
EXPECT_EQ(Buffers.getBuffer(Buf0), std::error_code());
BufferQueue::Buffer Buf1;
EXPECT_EQ(std::errc::not_enough_memory, Buffers.getBuffer(Buf1));
EXPECT_EQ(Buffers.releaseBuffer(Buf0), std::error_code());
}
TEST(BufferQueueTest, ReleaseUnknown) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf;
Buf.Buffer = reinterpret_cast<void *>(0xdeadbeef);
Buf.Size = kSize;
EXPECT_EQ(std::errc::argument_out_of_domain, Buffers.releaseBuffer(Buf));
}
TEST(BufferQueueTest, ErrorsWhenFinalising) {
bool Success = false;
BufferQueue Buffers(kSize, 2, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf;
ASSERT_EQ(Buffers.getBuffer(Buf), std::error_code());
ASSERT_NE(nullptr, Buf.Buffer);
ASSERT_EQ(Buffers.finalize(), std::error_code());
BufferQueue::Buffer OtherBuf;
ASSERT_EQ(std::errc::state_not_recoverable, Buffers.getBuffer(OtherBuf));
ASSERT_EQ(std::errc::state_not_recoverable, Buffers.finalize());
ASSERT_EQ(Buffers.releaseBuffer(Buf), std::error_code());
}
TEST(BufferQueueTest, MultiThreaded) {
bool Success = false;
BufferQueue Buffers(kSize, 100, Success);
ASSERT_TRUE(Success);
auto F = [&] {
BufferQueue::Buffer B;
while (!Buffers.getBuffer(B)) {
Buffers.releaseBuffer(B);
}
};
auto T0 = std::async(std::launch::async, F);
auto T1 = std::async(std::launch::async, F);
auto T2 = std::async(std::launch::async, [&] {
while (!Buffers.finalize())
;
});
F();
}
TEST(BufferQueueTest, Apply) {
bool Success = false;
BufferQueue Buffers(kSize, 10, Success);
ASSERT_TRUE(Success);
auto Count = 0;
BufferQueue::Buffer B;
for (int I = 0; I < 10; ++I) {
ASSERT_FALSE(Buffers.getBuffer(B));
ASSERT_FALSE(Buffers.releaseBuffer(B));
}
Buffers.apply([&](const BufferQueue::Buffer &B) { ++Count; });
ASSERT_EQ(Count, 10);
}
} // namespace __xray
<commit_msg>[XRay] Fix gtest error code comparison. NFC.<commit_after>//===-- buffer_queue_test.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a function call tracing system.
//
//===----------------------------------------------------------------------===//
#include "xray_buffer_queue.h"
#include "gtest/gtest.h"
#include <future>
#include <system_error>
#include <unistd.h>
namespace __xray {
static constexpr size_t kSize = 4096;
TEST(BufferQueueTest, API) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
}
TEST(BufferQueueTest, GetAndRelease) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf;
ASSERT_EQ(Buffers.getBuffer(Buf), std::error_code());
ASSERT_NE(nullptr, Buf.Buffer);
ASSERT_EQ(Buffers.releaseBuffer(Buf), std::error_code());
ASSERT_EQ(nullptr, Buf.Buffer);
}
TEST(BufferQueueTest, GetUntilFailed) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf0;
EXPECT_EQ(Buffers.getBuffer(Buf0), std::error_code());
BufferQueue::Buffer Buf1;
EXPECT_EQ(std::make_error_code(std::errc::not_enough_memory),
Buffers.getBuffer(Buf1));
EXPECT_EQ(Buffers.releaseBuffer(Buf0), std::error_code());
}
TEST(BufferQueueTest, ReleaseUnknown) {
bool Success = false;
BufferQueue Buffers(kSize, 1, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf;
Buf.Buffer = reinterpret_cast<void *>(0xdeadbeef);
Buf.Size = kSize;
EXPECT_EQ(std::make_error_code(std::errc::argument_out_of_domain),
Buffers.releaseBuffer(Buf));
}
TEST(BufferQueueTest, ErrorsWhenFinalising) {
bool Success = false;
BufferQueue Buffers(kSize, 2, Success);
ASSERT_TRUE(Success);
BufferQueue::Buffer Buf;
ASSERT_EQ(Buffers.getBuffer(Buf), std::error_code());
ASSERT_NE(nullptr, Buf.Buffer);
ASSERT_EQ(Buffers.finalize(), std::error_code());
BufferQueue::Buffer OtherBuf;
ASSERT_EQ(std::make_error_code(std::errc::state_not_recoverable),
Buffers.getBuffer(OtherBuf));
ASSERT_EQ(std::make_error_code(std::errc::state_not_recoverable),
Buffers.finalize());
ASSERT_EQ(Buffers.releaseBuffer(Buf), std::error_code());
}
TEST(BufferQueueTest, MultiThreaded) {
bool Success = false;
BufferQueue Buffers(kSize, 100, Success);
ASSERT_TRUE(Success);
auto F = [&] {
BufferQueue::Buffer B;
while (!Buffers.getBuffer(B)) {
Buffers.releaseBuffer(B);
}
};
auto T0 = std::async(std::launch::async, F);
auto T1 = std::async(std::launch::async, F);
auto T2 = std::async(std::launch::async, [&] {
while (!Buffers.finalize())
;
});
F();
}
TEST(BufferQueueTest, Apply) {
bool Success = false;
BufferQueue Buffers(kSize, 10, Success);
ASSERT_TRUE(Success);
auto Count = 0;
BufferQueue::Buffer B;
for (int I = 0; I < 10; ++I) {
ASSERT_FALSE(Buffers.getBuffer(B));
ASSERT_FALSE(Buffers.releaseBuffer(B));
}
Buffers.apply([&](const BufferQueue::Buffer &B) { ++Count; });
ASSERT_EQ(Count, 10);
}
} // namespace __xray
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "routablefactories60.h"
#include "routingpolicyfactories.h"
#include "routablerepository.h"
#include "routingpolicyrepository.h"
#include "replymerger.h"
#include <vespa/document/util/stringutil.h>
#include <vespa/documentapi/documentapi.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/messagebus/error.h>
#include <sstream>
#include <cassert>
#include <vespa/log/log.h>
LOG_SETUP(".documentprotocol");
using document::DocumentTypeRepo;
namespace documentapi {
const mbus::string DocumentProtocol::NAME = "document";
DocumentProtocol::DocumentProtocol(std::shared_ptr<const DocumentTypeRepo> repo, const string &configId) :
_routingPolicyRepository(std::make_unique<RoutingPolicyRepository>()),
_routableRepository(std::make_unique<RoutableRepository>()),
_repo(std::move(repo))
{
// Prepare config string for routing policy factories.
string cfg = (configId.empty() ? "client" : configId);
// When adding factories to this list, please KEEP THEM ORDERED alphabetically like they are now.
putRoutingPolicyFactory("AND", std::make_shared<RoutingPolicyFactories::AndPolicyFactory>());
putRoutingPolicyFactory("Content", std::make_shared<RoutingPolicyFactories::ContentPolicyFactory>());
putRoutingPolicyFactory("Storage", std::make_shared<RoutingPolicyFactories::ContentPolicyFactory>()); // TODO Vespa 8: remove
putRoutingPolicyFactory("DocumentRouteSelector", std::make_shared<RoutingPolicyFactories::DocumentRouteSelectorPolicyFactory>(*_repo, cfg));
putRoutingPolicyFactory("Extern", std::make_shared<RoutingPolicyFactories::ExternPolicyFactory>());
putRoutingPolicyFactory("LoadBalancer", std::make_shared<RoutingPolicyFactories::LoadBalancerPolicyFactory>());
putRoutingPolicyFactory("LocalService", std::make_shared<RoutingPolicyFactories::LocalServicePolicyFactory>());
putRoutingPolicyFactory("MessageType", std::make_shared<RoutingPolicyFactories::MessageTypePolicyFactory>());
putRoutingPolicyFactory("RoundRobin", std::make_shared<RoutingPolicyFactories::RoundRobinPolicyFactory>());
putRoutingPolicyFactory("SubsetService", std::make_shared<RoutingPolicyFactories::SubsetServicePolicyFactory>());
// Prepare version specifications to use when adding routable factories.
vespalib::VersionSpecification version6(6, 221);
std::vector<vespalib::VersionSpecification> from6 = { version6 };
// Add 6.x serialization
putRoutableFactory(MESSAGE_CREATEVISITOR, std::make_shared<RoutableFactories60::CreateVisitorMessageFactory>(), from6);
putRoutableFactory(MESSAGE_DESTROYVISITOR, std::make_shared<RoutableFactories60::DestroyVisitorMessageFactory>(), from6);
putRoutableFactory(MESSAGE_DOCUMENTLIST, std::make_shared<RoutableFactories60::DocumentListMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_DOCUMENTSUMMARY, std::make_shared<RoutableFactories60::DocumentSummaryMessageFactory>(), from6);
putRoutableFactory(MESSAGE_EMPTYBUCKETS, std::make_shared<RoutableFactories60::EmptyBucketsMessageFactory>(), from6);
putRoutableFactory(MESSAGE_GETBUCKETLIST, std::make_shared<RoutableFactories60::GetBucketListMessageFactory>(), from6);
putRoutableFactory(MESSAGE_GETBUCKETSTATE, std::make_shared<RoutableFactories60::GetBucketStateMessageFactory>(), from6);
putRoutableFactory(MESSAGE_GETDOCUMENT, std::make_shared<RoutableFactories60::GetDocumentMessageFactory>(), from6);
putRoutableFactory(MESSAGE_MAPVISITOR, std::make_shared<RoutableFactories60::MapVisitorMessageFactory>(), from6);
putRoutableFactory(MESSAGE_PUTDOCUMENT, std::make_shared<RoutableFactories60::PutDocumentMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_QUERYRESULT, std::make_shared<RoutableFactories60::QueryResultMessageFactory>(), from6);
putRoutableFactory(MESSAGE_REMOVEDOCUMENT, std::make_shared<RoutableFactories60::RemoveDocumentMessageFactory>(), from6);
putRoutableFactory(MESSAGE_REMOVELOCATION, std::make_shared<RoutableFactories60::RemoveLocationMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_SEARCHRESULT, std::make_shared<RoutableFactories60::SearchResultMessageFactory>(), from6);
putRoutableFactory(MESSAGE_STATBUCKET, std::make_shared<RoutableFactories60::StatBucketMessageFactory>(), from6);
putRoutableFactory(MESSAGE_UPDATEDOCUMENT, std::make_shared<RoutableFactories60::UpdateDocumentMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_VISITORINFO, std::make_shared<RoutableFactories60::VisitorInfoMessageFactory>(), from6);
putRoutableFactory(REPLY_CREATEVISITOR, std::make_shared<RoutableFactories60::CreateVisitorReplyFactory>(), from6);
putRoutableFactory(REPLY_DESTROYVISITOR, std::make_shared<RoutableFactories60::DestroyVisitorReplyFactory>(), from6);
putRoutableFactory(REPLY_DOCUMENTIGNORED, std::make_shared<RoutableFactories60::DocumentIgnoredReplyFactory>(), from6);
putRoutableFactory(REPLY_DOCUMENTLIST, std::make_shared<RoutableFactories60::DocumentListReplyFactory>(), from6);
putRoutableFactory(REPLY_DOCUMENTSUMMARY, std::make_shared<RoutableFactories60::DocumentSummaryReplyFactory>(), from6);
putRoutableFactory(REPLY_EMPTYBUCKETS, std::make_shared<RoutableFactories60::EmptyBucketsReplyFactory>(), from6);
putRoutableFactory(REPLY_GETBUCKETLIST, std::make_shared<RoutableFactories60::GetBucketListReplyFactory>(), from6);
putRoutableFactory(REPLY_GETBUCKETSTATE, std::make_shared<RoutableFactories60::GetBucketStateReplyFactory>(), from6);
putRoutableFactory(REPLY_GETDOCUMENT, std::make_shared<RoutableFactories60::GetDocumentReplyFactory>(*_repo), from6);
putRoutableFactory(REPLY_MAPVISITOR, std::make_shared<RoutableFactories60::MapVisitorReplyFactory>(), from6);
putRoutableFactory(REPLY_PUTDOCUMENT, std::make_shared<RoutableFactories60::PutDocumentReplyFactory>(), from6);
putRoutableFactory(REPLY_QUERYRESULT, std::make_shared<RoutableFactories60::QueryResultReplyFactory>(), from6);
putRoutableFactory(REPLY_REMOVEDOCUMENT, std::make_shared<RoutableFactories60::RemoveDocumentReplyFactory>(), from6);
putRoutableFactory(REPLY_REMOVELOCATION, std::make_shared<RoutableFactories60::RemoveLocationReplyFactory>(), from6);
putRoutableFactory(REPLY_SEARCHRESULT, std::make_shared<RoutableFactories60::SearchResultReplyFactory>(), from6);
putRoutableFactory(REPLY_STATBUCKET, std::make_shared<RoutableFactories60::StatBucketReplyFactory>(), from6);
putRoutableFactory(REPLY_UPDATEDOCUMENT, std::make_shared<RoutableFactories60::UpdateDocumentReplyFactory>(), from6);
putRoutableFactory(REPLY_VISITORINFO, std::make_shared<RoutableFactories60::VisitorInfoReplyFactory>(), from6);
putRoutableFactory(REPLY_WRONGDISTRIBUTION, std::make_shared<RoutableFactories60::WrongDistributionReplyFactory>(), from6);
}
DocumentProtocol::~DocumentProtocol() = default;
mbus::IRoutingPolicy::UP
DocumentProtocol::createPolicy(const mbus::string &name, const mbus::string ¶m) const
{
return _routingPolicyRepository->createPolicy(name, param);
}
DocumentProtocol &
DocumentProtocol::putRoutingPolicyFactory(const string &name, IRoutingPolicyFactory::SP factory)
{
_routingPolicyRepository->putFactory(name, std::move(factory));
return *this;
}
mbus::Blob
DocumentProtocol::encode(const vespalib::Version &version, const mbus::Routable &routable) const
{
mbus::Blob blob(_routableRepository->encode(version, routable));
// When valgrind reports errors of uninitialized data being written to
// the network, it is useful to be able to see the serialized data to
// try to identify what bits are uninitialized.
if (LOG_WOULD_LOG(spam)) {
std::ostringstream message;
document::StringUtil::printAsHex(
message, blob.data(), blob.size());
LOG(spam, "Encoded message of protocol %s type %u using version %s serialization:\n%s",
routable.getProtocol().c_str(), routable.getType(),
version.toString().c_str(), message.str().c_str());
}
return blob;
}
mbus::Routable::UP
DocumentProtocol::decode(const vespalib::Version &version, mbus::BlobRef data) const
{
try {
return _routableRepository->decode(version, data);
} catch (vespalib::Exception &e) {
LOG(warning, "%s", e.getMessage().c_str());
return mbus::Routable::UP();
}
}
uint32_t
DocumentProtocol::getRoutableTypes(const vespalib::Version &version, std::vector<uint32_t> &out) const
{
return _routableRepository->getRoutableTypes(version, out);
}
DocumentProtocol &
DocumentProtocol::putRoutableFactory(uint32_t type, IRoutableFactory::SP factory,
const vespalib::VersionSpecification &version)
{
_routableRepository->putFactory(version, type, std::move(factory));
return *this;
}
DocumentProtocol &
DocumentProtocol::putRoutableFactory(uint32_t type, IRoutableFactory::SP factory,
const std::vector<vespalib::VersionSpecification> &versions)
{
for (const auto & version : versions) {
putRoutableFactory(type, factory, version);
}
return *this;
}
string
DocumentProtocol::getErrorName(uint32_t errorCode) {
switch (errorCode) {
case ERROR_MESSAGE_IGNORED: return "MESSAGE_IGNORED";
case ERROR_POLICY_FAILURE: return "POLICY_FAILURE";
case ERROR_DOCUMENT_NOT_FOUND: return "DOCUMENT_NOT_FOUND";
case ERROR_EXISTS: return "EXISTS";
case ERROR_BUCKET_NOT_FOUND: return "BUCKET_NOT_FOUND";
case ERROR_BUCKET_DELETED: return "BUCKET_DELETED";
case ERROR_NOT_IMPLEMENTED: return "NOT_IMPLEMENTED";
case ERROR_ILLEGAL_PARAMETERS: return "ILLEGAL_PARAMETERS";
case ERROR_IGNORED: return "IGNORED";
case ERROR_UNKNOWN_COMMAND: return "UNKNOWN_COMMAND";
case ERROR_UNPARSEABLE: return "UNPARSEABLE";
case ERROR_NO_SPACE: return "NO_SPACE";
case ERROR_INTERNAL_FAILURE: return "INTERNAL_FAILURE";
case ERROR_PROCESSING_FAILURE: return "PROCESSING_FAILURE";
case ERROR_TIMESTAMP_EXIST: return "TIMESTAMP_EXIST";
case ERROR_STALE_TIMESTAMP: return "STALE_TIMESTAMP";
case ERROR_NODE_NOT_READY: return "NODE_NOT_READY";
case ERROR_WRONG_DISTRIBUTION: return "WRONG_DISTRIBUTION";
case ERROR_REJECTED: return "REJECTED";
case ERROR_ABORTED: return "ABORTED";
case ERROR_BUSY: return "BUSY";
case ERROR_NOT_CONNECTED: return "NOT_CONNECTED";
case ERROR_DISK_FAILURE: return "DISK_FAILURE";
case ERROR_IO_FAILURE: return "IO_FAILURE";
case ERROR_SUSPENDED: return "SUSPENDED";
case ERROR_TEST_AND_SET_CONDITION_FAILED: return "TEST_AND_SET_CONDITION_FAILED";
}
return mbus::ErrorCode::getName(errorCode);
}
void
DocumentProtocol::merge(mbus::RoutingContext &ctx)
{
std::set<uint32_t> mask;
merge(ctx, mask);
}
void
DocumentProtocol::merge(mbus::RoutingContext& ctx,
const std::set<uint32_t>& mask)
{
ReplyMerger rm;
uint32_t idx = 0;
for (mbus::RoutingNodeIterator it = ctx.getChildIterator();
it.isValid(); it.next(), ++idx)
{
if (mask.find(idx) != mask.end()) {
continue;
}
rm.merge(idx, it.getReplyRef());
}
assert(idx != 0);
ReplyMerger::Result res(rm.mergedReply());
if (res.isSuccessful()) {
const uint32_t okIdx = res.getSuccessfulReplyIndex();
ctx.setReply(ctx.getChildIterator().skip(okIdx).removeReply());
} else {
assert(res.hasGeneratedReply());
ctx.setReply(res.releaseGeneratedReply());
}
}
bool
DocumentProtocol::hasOnlyErrorsOfType(const mbus::Reply &reply, uint32_t errCode)
{
for (uint32_t i = 0; i < reply.getNumErrors(); ++i) {
if (reply.getError(i).getCode() != errCode) {
return false;
}
}
return true;
}
}
<commit_msg>remove 'Storage' protocol<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "routablefactories60.h"
#include "routingpolicyfactories.h"
#include "routablerepository.h"
#include "routingpolicyrepository.h"
#include "replymerger.h"
#include <vespa/document/util/stringutil.h>
#include <vespa/documentapi/documentapi.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/messagebus/error.h>
#include <sstream>
#include <cassert>
#include <vespa/log/log.h>
LOG_SETUP(".documentprotocol");
using document::DocumentTypeRepo;
namespace documentapi {
const mbus::string DocumentProtocol::NAME = "document";
DocumentProtocol::DocumentProtocol(std::shared_ptr<const DocumentTypeRepo> repo, const string &configId) :
_routingPolicyRepository(std::make_unique<RoutingPolicyRepository>()),
_routableRepository(std::make_unique<RoutableRepository>()),
_repo(std::move(repo))
{
// Prepare config string for routing policy factories.
string cfg = (configId.empty() ? "client" : configId);
// When adding factories to this list, please KEEP THEM ORDERED alphabetically like they are now.
putRoutingPolicyFactory("AND", std::make_shared<RoutingPolicyFactories::AndPolicyFactory>());
putRoutingPolicyFactory("Content", std::make_shared<RoutingPolicyFactories::ContentPolicyFactory>());
putRoutingPolicyFactory("DocumentRouteSelector", std::make_shared<RoutingPolicyFactories::DocumentRouteSelectorPolicyFactory>(*_repo, cfg));
putRoutingPolicyFactory("Extern", std::make_shared<RoutingPolicyFactories::ExternPolicyFactory>());
putRoutingPolicyFactory("LoadBalancer", std::make_shared<RoutingPolicyFactories::LoadBalancerPolicyFactory>());
putRoutingPolicyFactory("LocalService", std::make_shared<RoutingPolicyFactories::LocalServicePolicyFactory>());
putRoutingPolicyFactory("MessageType", std::make_shared<RoutingPolicyFactories::MessageTypePolicyFactory>());
putRoutingPolicyFactory("RoundRobin", std::make_shared<RoutingPolicyFactories::RoundRobinPolicyFactory>());
putRoutingPolicyFactory("SubsetService", std::make_shared<RoutingPolicyFactories::SubsetServicePolicyFactory>());
// Prepare version specifications to use when adding routable factories.
vespalib::VersionSpecification version6(6, 221);
std::vector<vespalib::VersionSpecification> from6 = { version6 };
// Add 6.x serialization
putRoutableFactory(MESSAGE_CREATEVISITOR, std::make_shared<RoutableFactories60::CreateVisitorMessageFactory>(), from6);
putRoutableFactory(MESSAGE_DESTROYVISITOR, std::make_shared<RoutableFactories60::DestroyVisitorMessageFactory>(), from6);
putRoutableFactory(MESSAGE_DOCUMENTLIST, std::make_shared<RoutableFactories60::DocumentListMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_DOCUMENTSUMMARY, std::make_shared<RoutableFactories60::DocumentSummaryMessageFactory>(), from6);
putRoutableFactory(MESSAGE_EMPTYBUCKETS, std::make_shared<RoutableFactories60::EmptyBucketsMessageFactory>(), from6);
putRoutableFactory(MESSAGE_GETBUCKETLIST, std::make_shared<RoutableFactories60::GetBucketListMessageFactory>(), from6);
putRoutableFactory(MESSAGE_GETBUCKETSTATE, std::make_shared<RoutableFactories60::GetBucketStateMessageFactory>(), from6);
putRoutableFactory(MESSAGE_GETDOCUMENT, std::make_shared<RoutableFactories60::GetDocumentMessageFactory>(), from6);
putRoutableFactory(MESSAGE_MAPVISITOR, std::make_shared<RoutableFactories60::MapVisitorMessageFactory>(), from6);
putRoutableFactory(MESSAGE_PUTDOCUMENT, std::make_shared<RoutableFactories60::PutDocumentMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_QUERYRESULT, std::make_shared<RoutableFactories60::QueryResultMessageFactory>(), from6);
putRoutableFactory(MESSAGE_REMOVEDOCUMENT, std::make_shared<RoutableFactories60::RemoveDocumentMessageFactory>(), from6);
putRoutableFactory(MESSAGE_REMOVELOCATION, std::make_shared<RoutableFactories60::RemoveLocationMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_SEARCHRESULT, std::make_shared<RoutableFactories60::SearchResultMessageFactory>(), from6);
putRoutableFactory(MESSAGE_STATBUCKET, std::make_shared<RoutableFactories60::StatBucketMessageFactory>(), from6);
putRoutableFactory(MESSAGE_UPDATEDOCUMENT, std::make_shared<RoutableFactories60::UpdateDocumentMessageFactory>(*_repo), from6);
putRoutableFactory(MESSAGE_VISITORINFO, std::make_shared<RoutableFactories60::VisitorInfoMessageFactory>(), from6);
putRoutableFactory(REPLY_CREATEVISITOR, std::make_shared<RoutableFactories60::CreateVisitorReplyFactory>(), from6);
putRoutableFactory(REPLY_DESTROYVISITOR, std::make_shared<RoutableFactories60::DestroyVisitorReplyFactory>(), from6);
putRoutableFactory(REPLY_DOCUMENTIGNORED, std::make_shared<RoutableFactories60::DocumentIgnoredReplyFactory>(), from6);
putRoutableFactory(REPLY_DOCUMENTLIST, std::make_shared<RoutableFactories60::DocumentListReplyFactory>(), from6);
putRoutableFactory(REPLY_DOCUMENTSUMMARY, std::make_shared<RoutableFactories60::DocumentSummaryReplyFactory>(), from6);
putRoutableFactory(REPLY_EMPTYBUCKETS, std::make_shared<RoutableFactories60::EmptyBucketsReplyFactory>(), from6);
putRoutableFactory(REPLY_GETBUCKETLIST, std::make_shared<RoutableFactories60::GetBucketListReplyFactory>(), from6);
putRoutableFactory(REPLY_GETBUCKETSTATE, std::make_shared<RoutableFactories60::GetBucketStateReplyFactory>(), from6);
putRoutableFactory(REPLY_GETDOCUMENT, std::make_shared<RoutableFactories60::GetDocumentReplyFactory>(*_repo), from6);
putRoutableFactory(REPLY_MAPVISITOR, std::make_shared<RoutableFactories60::MapVisitorReplyFactory>(), from6);
putRoutableFactory(REPLY_PUTDOCUMENT, std::make_shared<RoutableFactories60::PutDocumentReplyFactory>(), from6);
putRoutableFactory(REPLY_QUERYRESULT, std::make_shared<RoutableFactories60::QueryResultReplyFactory>(), from6);
putRoutableFactory(REPLY_REMOVEDOCUMENT, std::make_shared<RoutableFactories60::RemoveDocumentReplyFactory>(), from6);
putRoutableFactory(REPLY_REMOVELOCATION, std::make_shared<RoutableFactories60::RemoveLocationReplyFactory>(), from6);
putRoutableFactory(REPLY_SEARCHRESULT, std::make_shared<RoutableFactories60::SearchResultReplyFactory>(), from6);
putRoutableFactory(REPLY_STATBUCKET, std::make_shared<RoutableFactories60::StatBucketReplyFactory>(), from6);
putRoutableFactory(REPLY_UPDATEDOCUMENT, std::make_shared<RoutableFactories60::UpdateDocumentReplyFactory>(), from6);
putRoutableFactory(REPLY_VISITORINFO, std::make_shared<RoutableFactories60::VisitorInfoReplyFactory>(), from6);
putRoutableFactory(REPLY_WRONGDISTRIBUTION, std::make_shared<RoutableFactories60::WrongDistributionReplyFactory>(), from6);
}
DocumentProtocol::~DocumentProtocol() = default;
mbus::IRoutingPolicy::UP
DocumentProtocol::createPolicy(const mbus::string &name, const mbus::string ¶m) const
{
return _routingPolicyRepository->createPolicy(name, param);
}
DocumentProtocol &
DocumentProtocol::putRoutingPolicyFactory(const string &name, IRoutingPolicyFactory::SP factory)
{
_routingPolicyRepository->putFactory(name, std::move(factory));
return *this;
}
mbus::Blob
DocumentProtocol::encode(const vespalib::Version &version, const mbus::Routable &routable) const
{
mbus::Blob blob(_routableRepository->encode(version, routable));
// When valgrind reports errors of uninitialized data being written to
// the network, it is useful to be able to see the serialized data to
// try to identify what bits are uninitialized.
if (LOG_WOULD_LOG(spam)) {
std::ostringstream message;
document::StringUtil::printAsHex(
message, blob.data(), blob.size());
LOG(spam, "Encoded message of protocol %s type %u using version %s serialization:\n%s",
routable.getProtocol().c_str(), routable.getType(),
version.toString().c_str(), message.str().c_str());
}
return blob;
}
mbus::Routable::UP
DocumentProtocol::decode(const vespalib::Version &version, mbus::BlobRef data) const
{
try {
return _routableRepository->decode(version, data);
} catch (vespalib::Exception &e) {
LOG(warning, "%s", e.getMessage().c_str());
return mbus::Routable::UP();
}
}
uint32_t
DocumentProtocol::getRoutableTypes(const vespalib::Version &version, std::vector<uint32_t> &out) const
{
return _routableRepository->getRoutableTypes(version, out);
}
DocumentProtocol &
DocumentProtocol::putRoutableFactory(uint32_t type, IRoutableFactory::SP factory,
const vespalib::VersionSpecification &version)
{
_routableRepository->putFactory(version, type, std::move(factory));
return *this;
}
DocumentProtocol &
DocumentProtocol::putRoutableFactory(uint32_t type, IRoutableFactory::SP factory,
const std::vector<vespalib::VersionSpecification> &versions)
{
for (const auto & version : versions) {
putRoutableFactory(type, factory, version);
}
return *this;
}
string
DocumentProtocol::getErrorName(uint32_t errorCode) {
switch (errorCode) {
case ERROR_MESSAGE_IGNORED: return "MESSAGE_IGNORED";
case ERROR_POLICY_FAILURE: return "POLICY_FAILURE";
case ERROR_DOCUMENT_NOT_FOUND: return "DOCUMENT_NOT_FOUND";
case ERROR_EXISTS: return "EXISTS";
case ERROR_BUCKET_NOT_FOUND: return "BUCKET_NOT_FOUND";
case ERROR_BUCKET_DELETED: return "BUCKET_DELETED";
case ERROR_NOT_IMPLEMENTED: return "NOT_IMPLEMENTED";
case ERROR_ILLEGAL_PARAMETERS: return "ILLEGAL_PARAMETERS";
case ERROR_IGNORED: return "IGNORED";
case ERROR_UNKNOWN_COMMAND: return "UNKNOWN_COMMAND";
case ERROR_UNPARSEABLE: return "UNPARSEABLE";
case ERROR_NO_SPACE: return "NO_SPACE";
case ERROR_INTERNAL_FAILURE: return "INTERNAL_FAILURE";
case ERROR_PROCESSING_FAILURE: return "PROCESSING_FAILURE";
case ERROR_TIMESTAMP_EXIST: return "TIMESTAMP_EXIST";
case ERROR_STALE_TIMESTAMP: return "STALE_TIMESTAMP";
case ERROR_NODE_NOT_READY: return "NODE_NOT_READY";
case ERROR_WRONG_DISTRIBUTION: return "WRONG_DISTRIBUTION";
case ERROR_REJECTED: return "REJECTED";
case ERROR_ABORTED: return "ABORTED";
case ERROR_BUSY: return "BUSY";
case ERROR_NOT_CONNECTED: return "NOT_CONNECTED";
case ERROR_DISK_FAILURE: return "DISK_FAILURE";
case ERROR_IO_FAILURE: return "IO_FAILURE";
case ERROR_SUSPENDED: return "SUSPENDED";
case ERROR_TEST_AND_SET_CONDITION_FAILED: return "TEST_AND_SET_CONDITION_FAILED";
}
return mbus::ErrorCode::getName(errorCode);
}
void
DocumentProtocol::merge(mbus::RoutingContext &ctx)
{
std::set<uint32_t> mask;
merge(ctx, mask);
}
void
DocumentProtocol::merge(mbus::RoutingContext& ctx,
const std::set<uint32_t>& mask)
{
ReplyMerger rm;
uint32_t idx = 0;
for (mbus::RoutingNodeIterator it = ctx.getChildIterator();
it.isValid(); it.next(), ++idx)
{
if (mask.find(idx) != mask.end()) {
continue;
}
rm.merge(idx, it.getReplyRef());
}
assert(idx != 0);
ReplyMerger::Result res(rm.mergedReply());
if (res.isSuccessful()) {
const uint32_t okIdx = res.getSuccessfulReplyIndex();
ctx.setReply(ctx.getChildIterator().skip(okIdx).removeReply());
} else {
assert(res.hasGeneratedReply());
ctx.setReply(res.releaseGeneratedReply());
}
}
bool
DocumentProtocol::hasOnlyErrorsOfType(const mbus::Reply &reply, uint32_t errCode)
{
for (uint32_t i = 0; i < reply.getNumErrors(); ++i) {
if (reply.getError(i).getCode() != errCode) {
return false;
}
}
return true;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_INTRUSIVE_LIFO_INBOX_HPP
#define CAF_INTRUSIVE_LIFO_INBOX_HPP
#include <atomic>
#include <condition_variable>
#include <mutex>
#include "caf/config.hpp"
#include "caf/intrusive/inbox_result.hpp"
namespace caf {
namespace intrusive {
/// An intrusive, thread-safe LIFO queue implementation for a single reader
/// with any number of writers.
template <class Policy>
class lifo_inbox {
public:
using policy_type = Policy;
using value_type = typename policy_type::mapped_type;
using pointer = value_type*;
using node_type = typename value_type::node_type;
using node_pointer = node_type*;
using unique_pointer = typename policy_type::unique_pointer;
using deleter_type = typename unique_pointer::deleter_type;
/// Tries to enqueue a new element to the inbox.
/// @threadsafe
inbox_result push_front(pointer new_element) noexcept {
CAF_ASSERT(new_element != nullptr);
pointer e = stack_.load();
auto eof = stack_closed_tag();
auto blk = reader_blocked_tag();
while (e != eof) {
// A tag is never part of a non-empty list.
new_element->next = e != blk ? e : nullptr;
if (stack_.compare_exchange_strong(e, new_element))
return e == reader_blocked_tag() ? inbox_result::unblocked_reader
: inbox_result::success;
// Continue with new value of `e`.
}
// The queue has been closed, drop messages.
deleter_type d;
d(new_element);
return inbox_result::queue_closed;
}
/// Tries to enqueue a new element to the inbox.
/// @threadsafe
inbox_result push_front(unique_pointer x) noexcept {
return push_front(x.release());
}
/// Tries to enqueue a new element to the mailbox.
/// @threadsafe
template <class... Ts>
inbox_result emplace_front(Ts&&... xs) {
return push_front(new value_type(std::forward<Ts>(xs)...));
}
/// Queries whether this queue is empty.
/// @pre `!closed() && !blocked()`
bool empty() const noexcept {
CAF_ASSERT(!closed());
CAF_ASSERT(!blocked());
return stack_.load() == stack_empty_tag();
}
/// Queries whether this has been closed.
bool closed() const noexcept {
return stack_.load() == stack_closed_tag();
}
/// Queries whether this has been marked as blocked, i.e.,
/// the owner of the list is waiting for new data.
bool blocked() const noexcept {
return stack_.load() == reader_blocked_tag();
}
/// Tries to set this queue from `empty` to `blocked`.
bool try_block() noexcept {
auto e = stack_empty_tag();
return stack_.compare_exchange_strong(e, reader_blocked_tag());
}
/// Tries to set this queue from `blocked` to `empty`.
bool try_unblock() noexcept {
auto e = reader_blocked_tag();
return stack_.compare_exchange_strong(e, stack_empty_tag());
}
/// Sets the head to `new_head` and returns the previous head if the queue
/// was not empty.
pointer take_head(pointer new_head) noexcept {
// This member function should only be used to transition to closed or
// empty.
CAF_ASSERT(new_head == stack_closed_tag()
|| new_head == stack_empty_tag());
// Must not be called on a closed queue.
pointer e = stack_.load();
CAF_ASSERT(e != stack_closed_tag());
// We don't assert these conditions again since only the owner is allowed
// to call this member function, i.e., there's never a race on `take_head`.
while (e != new_head) {
if (stack_.compare_exchange_weak(e, new_head)) {
CAF_ASSERT(e != stack_closed_tag());
if (is_empty_or_blocked_tag(e)) {
// Sanity check: going from empty/blocked to closed.
CAF_ASSERT(new_head == stack_closed_tag());
return nullptr;
}
return e;
}
// Next iteration.
}
return nullptr;
}
/// Sets the head to `stack_empty_tag()` and returns the previous head if
/// the queue was not empty.
pointer take_head() noexcept {
return take_head(stack_empty_tag());
}
/// Closes this queue and deletes all remaining elements.
/// @warning Call only from the reader (owner).
void close() noexcept {
deleter_type d;
static_assert(noexcept(d(std::declval<pointer>())),
"deleter is not noexcept");
close(d);
}
/// Closes this queue and applies `f` to each pointer. The function object
/// `f` must take ownership of the passed pointer.
/// @warning Call only from the reader (owner).
template <class F>
void close(F& f) noexcept(noexcept(f(std::declval<pointer>()))) {
node_pointer ptr = take_head(stack_closed_tag());
while (ptr != nullptr) {
auto next = ptr->next;
f(promote(ptr));
ptr = next;
}
}
lifo_inbox() noexcept {
stack_ = stack_empty_tag();
}
~lifo_inbox() noexcept {
if (!closed())
close();
}
// -- synchronized access ---------------------------------------------------
template <class Mutex, class CondVar>
bool synchronized_push_front(Mutex& mtx, CondVar& cv, pointer ptr) {
switch (push_front(ptr)) {
default:
// enqueued message to a running actor's mailbox
return true;
case inbox_result::unblocked_reader: {
std::unique_lock<Mutex> guard(mtx);
cv.notify_one();
return true;
}
case inbox_result::queue_closed:
// actor no longer alive
return false;
}
}
template <class Mutex, class CondVar>
bool synchronized_push_front(Mutex& mtx, CondVar& cv, unique_pointer ptr) {
return synchronized_push_front(mtx, cv, ptr.relase());
}
template <class Mutex, class CondVar, class... Ts>
bool synchronized_emplace_front(Mutex& mtx, CondVar& cv, Ts&&... xs) {
return synchronized_push_front(mtx, cv,
new value_type(std::forward<Ts>(xs)...));
}
template <class Mutex, class CondVar>
void synchronized_await(Mutex& mtx, CondVar& cv) {
CAF_ASSERT(!closed());
if (try_block()) {
std::unique_lock<Mutex> guard(mtx);
while (blocked())
cv.wait(guard);
}
}
template <class Mutex, class CondVar, class TimePoint>
bool synchronized_await(Mutex& mtx, CondVar& cv, const TimePoint& timeout) {
CAF_ASSERT(!closed());
if (try_block()) {
std::unique_lock<Mutex> guard(mtx);
while (blocked()) {
if (cv.wait_until(guard, timeout) == std::cv_status::timeout) {
// if we're unable to set the queue from blocked to empty,
// than there's a new element in the list
return !try_unblock();
}
}
}
return true;
}
private:
static constexpr pointer stack_empty_tag() {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator wheter this queue is empty or not.
return static_cast<pointer>(nullptr);
}
pointer stack_closed_tag() const noexcept {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator wheter this queue is closed or not.
return reinterpret_cast<pointer>(reinterpret_cast<intptr_t>(this) + 1);
}
pointer reader_blocked_tag() const noexcept {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator wheter the owner of the queue is currently waiting for
// new messages.
return reinterpret_cast<pointer>(const_cast<lifo_inbox*>(this));
}
bool is_empty_or_blocked_tag(pointer x) const noexcept {
return x == stack_empty_tag() || x == reader_blocked_tag();
}
// -- member variables ------------------------------------------------------
std::atomic<pointer> stack_;
};
} // namespace intrusive
} // namespace caf
#endif // CAF_INTRUSIVE_LIFO_INBOX_HPP
<commit_msg>Improve assertions in LIFO inbox<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_INTRUSIVE_LIFO_INBOX_HPP
#define CAF_INTRUSIVE_LIFO_INBOX_HPP
#include <atomic>
#include <condition_variable>
#include <mutex>
#include "caf/config.hpp"
#include "caf/intrusive/inbox_result.hpp"
namespace caf {
namespace intrusive {
/// An intrusive, thread-safe LIFO queue implementation for a single reader
/// with any number of writers.
template <class Policy>
class lifo_inbox {
public:
using policy_type = Policy;
using value_type = typename policy_type::mapped_type;
using pointer = value_type*;
using node_type = typename value_type::node_type;
using node_pointer = node_type*;
using unique_pointer = typename policy_type::unique_pointer;
using deleter_type = typename unique_pointer::deleter_type;
/// Tries to enqueue a new element to the inbox.
/// @threadsafe
inbox_result push_front(pointer new_element) noexcept {
CAF_ASSERT(new_element != nullptr);
pointer e = stack_.load();
auto eof = stack_closed_tag();
auto blk = reader_blocked_tag();
while (e != eof) {
// A tag is never part of a non-empty list.
new_element->next = e != blk ? e : nullptr;
if (stack_.compare_exchange_strong(e, new_element))
return e == reader_blocked_tag() ? inbox_result::unblocked_reader
: inbox_result::success;
// Continue with new value of `e`.
}
// The queue has been closed, drop messages.
deleter_type d;
d(new_element);
return inbox_result::queue_closed;
}
/// Tries to enqueue a new element to the inbox.
/// @threadsafe
inbox_result push_front(unique_pointer x) noexcept {
return push_front(x.release());
}
/// Tries to enqueue a new element to the mailbox.
/// @threadsafe
template <class... Ts>
inbox_result emplace_front(Ts&&... xs) {
return push_front(new value_type(std::forward<Ts>(xs)...));
}
/// Queries whether this queue is empty.
/// @pre `!closed() && !blocked()`
bool empty() const noexcept {
CAF_ASSERT(!closed());
CAF_ASSERT(!blocked());
return stack_.load() == stack_empty_tag();
}
/// Queries whether this has been closed.
bool closed() const noexcept {
return stack_.load() == stack_closed_tag();
}
/// Queries whether this has been marked as blocked, i.e.,
/// the owner of the list is waiting for new data.
bool blocked() const noexcept {
return stack_.load() == reader_blocked_tag();
}
/// Tries to set this queue from `empty` to `blocked`.
bool try_block() noexcept {
auto e = stack_empty_tag();
return stack_.compare_exchange_strong(e, reader_blocked_tag());
}
/// Tries to set this queue from `blocked` to `empty`.
bool try_unblock() noexcept {
auto e = reader_blocked_tag();
return stack_.compare_exchange_strong(e, stack_empty_tag());
}
/// Sets the head to `new_head` and returns the previous head if the queue
/// was not empty.
pointer take_head(pointer new_head) noexcept {
// This member function should only be used to transition to closed or
// empty.
CAF_ASSERT(new_head == stack_closed_tag()
|| new_head == stack_empty_tag());
pointer e = stack_.load();
// Must not be called on a closed queue.
CAF_ASSERT(e != stack_closed_tag());
// Must not be called on a blocked queue unless for setting it to closed,
// because that would mean an actor accesses its mailbox after blocking its
// mailbox but before receiving anything.
CAF_ASSERT(e != reader_blocked_tag() || new_head == stack_closed_tag());
// We don't assert these conditions again since only the owner is allowed
// to call this member function, i.e., there's never a race on `take_head`.
while (e != new_head) {
if (stack_.compare_exchange_weak(e, new_head)) {
CAF_ASSERT(e != stack_closed_tag());
if (is_empty_or_blocked_tag(e)) {
// Sanity check: going from empty/blocked to closed.
CAF_ASSERT(new_head == stack_closed_tag());
return nullptr;
}
return e;
}
// Next iteration.
}
return nullptr;
}
/// Sets the head to `stack_empty_tag()` and returns the previous head if
/// the queue was not empty.
pointer take_head() noexcept {
return take_head(stack_empty_tag());
}
/// Closes this queue and deletes all remaining elements.
/// @warning Call only from the reader (owner).
void close() noexcept {
deleter_type d;
static_assert(noexcept(d(std::declval<pointer>())),
"deleter is not noexcept");
close(d);
}
/// Closes this queue and applies `f` to each pointer. The function object
/// `f` must take ownership of the passed pointer.
/// @warning Call only from the reader (owner).
template <class F>
void close(F& f) noexcept(noexcept(f(std::declval<pointer>()))) {
node_pointer ptr = take_head(stack_closed_tag());
while (ptr != nullptr) {
auto next = ptr->next;
f(promote(ptr));
ptr = next;
}
}
lifo_inbox() noexcept {
stack_ = stack_empty_tag();
}
~lifo_inbox() noexcept {
if (!closed())
close();
}
// -- synchronized access ---------------------------------------------------
template <class Mutex, class CondVar>
bool synchronized_push_front(Mutex& mtx, CondVar& cv, pointer ptr) {
switch (push_front(ptr)) {
default:
// enqueued message to a running actor's mailbox
return true;
case inbox_result::unblocked_reader: {
std::unique_lock<Mutex> guard(mtx);
cv.notify_one();
return true;
}
case inbox_result::queue_closed:
// actor no longer alive
return false;
}
}
template <class Mutex, class CondVar>
bool synchronized_push_front(Mutex& mtx, CondVar& cv, unique_pointer ptr) {
return synchronized_push_front(mtx, cv, ptr.relase());
}
template <class Mutex, class CondVar, class... Ts>
bool synchronized_emplace_front(Mutex& mtx, CondVar& cv, Ts&&... xs) {
return synchronized_push_front(mtx, cv,
new value_type(std::forward<Ts>(xs)...));
}
template <class Mutex, class CondVar>
void synchronized_await(Mutex& mtx, CondVar& cv) {
CAF_ASSERT(!closed());
if (try_block()) {
std::unique_lock<Mutex> guard(mtx);
while (blocked())
cv.wait(guard);
}
}
template <class Mutex, class CondVar, class TimePoint>
bool synchronized_await(Mutex& mtx, CondVar& cv, const TimePoint& timeout) {
CAF_ASSERT(!closed());
if (try_block()) {
std::unique_lock<Mutex> guard(mtx);
while (blocked()) {
if (cv.wait_until(guard, timeout) == std::cv_status::timeout) {
// if we're unable to set the queue from blocked to empty,
// than there's a new element in the list
return !try_unblock();
}
}
}
return true;
}
private:
static constexpr pointer stack_empty_tag() {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator wheter this queue is empty or not.
return static_cast<pointer>(nullptr);
}
pointer stack_closed_tag() const noexcept {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator wheter this queue is closed or not.
return reinterpret_cast<pointer>(reinterpret_cast<intptr_t>(this) + 1);
}
pointer reader_blocked_tag() const noexcept {
// We are *never* going to dereference the returned pointer. It is only
// used as indicator wheter the owner of the queue is currently waiting for
// new messages.
return reinterpret_cast<pointer>(const_cast<lifo_inbox*>(this));
}
bool is_empty_or_blocked_tag(pointer x) const noexcept {
return x == stack_empty_tag() || x == reader_blocked_tag();
}
// -- member variables ------------------------------------------------------
std::atomic<pointer> stack_;
};
} // namespace intrusive
} // namespace caf
#endif // CAF_INTRUSIVE_LIFO_INBOX_HPP
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "OgreVolumeGridSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"
namespace Ogre {
namespace Volume {
Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const
{
AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
// Inside the grid
if (box.intersects(ray.getOrigin()))
{
return ray.getOrigin();
}
// Outside the grid, ray intersects it
std::pair<bool, Real> intersection = ray.intersects(box);
if (intersection.first)
{
Vector3 direction = ray.getDirection().normalisedCopy();
return ray.getOrigin() + direction * intersection.second;
}
// Outside the grid, ray doesn't intersect it
return ray.getOrigin();
}
//-----------------------------------------------------------------------
Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const
{
AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
Vector3 direction = ray.getDirection().normalisedCopy();
Vector3 invertedDirection = (Real)-1.0 * direction;
Vector3 origin = ray.getOrigin() + direction * box.getSize().length();
Ray inverted(origin, invertedDirection);
std::pair<bool, Real> intersection = inverted.intersects(box);
if (intersection.first)
{
return origin + invertedDirection * intersection.second;
}
return ray.getOrigin() + direction * maxDistance;
}
//-----------------------------------------------------------------------
GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) :
mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient)
{
}
//-----------------------------------------------------------------------
GridSource::~GridSource(void)
{
}
//-----------------------------------------------------------------------
Vector4 GridSource::getValueAndGradient(const Vector3 &position) const
{
Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
Vector3 normal;
if (mTrilinearGradient)
{
size_t x0 = (size_t)scaledPosition.x;
size_t x1 = (size_t)ceil(scaledPosition.x);
size_t y0 = (size_t)scaledPosition.y;
size_t y1 = (size_t)ceil(scaledPosition.y);
size_t z0 = (size_t)scaledPosition.z;
size_t z1 = (size_t)ceil(scaledPosition.z);
Real dX = scaledPosition.x - (Real)x0;
Real dY = scaledPosition.y - (Real)y0;
Real dZ = scaledPosition.z - (Real)z0;
Vector3 f000 = getGradient(x0, y0, z0);
Vector3 f100 = getGradient(x1, y0, z0);
Vector3 f010 = getGradient(x0, y1, z0);
Vector3 f001 = getGradient(x0, y0, z1);
Vector3 f101 = getGradient(x1, y0, z1);
Vector3 f011 = getGradient(x0, y1, z1);
Vector3 f110 = getGradient(x1, y1, z0);
Vector3 f111 = getGradient(x1, y1, z1);
Real oneMinX = (Real)1.0 - dX;
Real oneMinY = (Real)1.0 - dY;
Real oneMinZ = (Real)1.0 - dZ;
Real oneMinXoneMinY = oneMinX * oneMinY;
Real dXOneMinY = dX * oneMinY;
normal = oneMinZ * (f000 * oneMinXoneMinY
+ f100 * dXOneMinY
+ f010 * oneMinX * dY)
+ dZ * (f001 * oneMinXoneMinY
+ f101 * dXOneMinY
+ f011 * oneMinX * dY)
+ dX * dY * (f110 * oneMinZ
+ f111 * dZ);
normal *= (Real)-1.0;
}
else
{
normal = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5));
normal *= (Real)-1.0;
}
return Vector4(normal.x, normal.y, normal.z, getValue(position));
}
//-----------------------------------------------------------------------
Real GridSource::getValue(const Vector3 &position) const
{
Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
Real value;
if (mTrilinearValue)
{
size_t x0 = (size_t)scaledPosition.x;
size_t x1 = (size_t)ceil(scaledPosition.x);
size_t y0 = (size_t)scaledPosition.y;
size_t y1 = (size_t)ceil(scaledPosition.y);
size_t z0 = (size_t)scaledPosition.z;
size_t z1 = (size_t)ceil(scaledPosition.z);
Real dX = scaledPosition.x - (Real)x0;
Real dY = scaledPosition.y - (Real)y0;
Real dZ = scaledPosition.z - (Real)z0;
Real f000 = getVolumeGridValue(x0, y0, z0);
Real f100 = getVolumeGridValue(x1, y0, z0);
Real f010 = getVolumeGridValue(x0, y1, z0);
Real f001 = getVolumeGridValue(x0, y0, z1);
Real f101 = getVolumeGridValue(x1, y0, z1);
Real f011 = getVolumeGridValue(x0, y1, z1);
Real f110 = getVolumeGridValue(x1, y1, z0);
Real f111 = getVolumeGridValue(x1, y1, z1);
Real oneMinX = (Real)1.0 - dX;
Real oneMinY = (Real)1.0 - dY;
Real oneMinZ = (Real)1.0 - dZ;
Real oneMinXoneMinY = oneMinX * oneMinY;
Real dXOneMinY = dX * oneMinY;
value = oneMinZ * (f000 * oneMinXoneMinY
+ f100 * dXOneMinY
+ f010 * oneMinX * dY)
+ dZ * (f001 * oneMinXoneMinY
+ f101 * dXOneMinY
+ f011 * oneMinX * dY)
+ dX * dY * (f110 * oneMinZ
+ f111 * dZ);
}
else
{
// Nearest neighbour else
size_t x = (size_t)(scaledPosition.x + (Real)0.5);
size_t y = (size_t)(scaledPosition.y + (Real)0.5);
size_t z = (size_t)(scaledPosition.z + (Real)0.5);
value = (Real)getVolumeGridValue(x, y, z);
}
return value;
}
//-----------------------------------------------------------------------
size_t GridSource::getWidth(void) const
{
return mWidth;
}
//-----------------------------------------------------------------------
size_t GridSource::getHeight(void) const
{
return mHeight;
}
//-----------------------------------------------------------------------
size_t GridSource::getDepth(void) const
{
return mDepth;
}
//-----------------------------------------------------------------------
void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 ¢er, Real radius)
{
Real worldWidthScale = (Real)1.0 / mPosXScale;
Real worldHeightScale = (Real)1.0 / mPosYScale;
Real worldDepthScale = (Real)1.0 / mPosZScale;
operation->setSourceA(this);
operation->setSourceB(source);
// No need for trilineaer interpolation here as we iterate over the
// cells anyway.
bool oldTrilinearValue = mTrilinearValue;
mTrilinearValue = false;
float value;
int x, y;
Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale);
int xStart = Math::Clamp((size_t)(scaledCenter.x - radius * mPosXScale), (size_t)0, mWidth);
int xEnd = Math::Clamp((size_t)(scaledCenter.x + radius * mPosXScale), (size_t)0, mWidth);
int yStart = Math::Clamp((size_t)(scaledCenter.y - radius * mPosYScale), (size_t)0, mHeight);
int yEnd = Math::Clamp((size_t)(scaledCenter.y + radius * mPosYScale), (size_t)0, mHeight);
int zStart = Math::Clamp((size_t)(scaledCenter.z - radius * mPosZScale), (size_t)0, mDepth);
int zEnd = Math::Clamp((size_t)(scaledCenter.z + radius * mPosZScale), (size_t)0, mDepth);
Vector3 pos;
for (int z = zStart; z < zEnd; ++z)
{
for (y = yStart; y < yEnd; ++y)
{
for (x = xStart; x < xEnd; ++x)
{
pos.x = x * worldWidthScale;
pos.y = y * worldHeightScale;
pos.z = z * worldDepthScale;
value = operation->getValue(pos);
setVolumeGridValue(x, y, z, value);
}
}
}
mTrilinearValue = oldTrilinearValue;
}
//-----------------------------------------------------------------------
Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const
{
return mVolumeSpaceToWorldSpaceFactor;
}
}
}<commit_msg>Volume Rendering: Better variable name<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "OgreVolumeGridSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"
namespace Ogre {
namespace Volume {
Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const
{
AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
// Inside the grid
if (box.intersects(ray.getOrigin()))
{
return ray.getOrigin();
}
// Outside the grid, ray intersects it
std::pair<bool, Real> intersection = ray.intersects(box);
if (intersection.first)
{
Vector3 direction = ray.getDirection().normalisedCopy();
return ray.getOrigin() + direction * intersection.second;
}
// Outside the grid, ray doesn't intersect it
return ray.getOrigin();
}
//-----------------------------------------------------------------------
Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const
{
AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
Vector3 direction = ray.getDirection().normalisedCopy();
Vector3 invertedDirection = (Real)-1.0 * direction;
Vector3 origin = ray.getOrigin() + direction * box.getSize().length();
Ray inverted(origin, invertedDirection);
std::pair<bool, Real> intersection = inverted.intersects(box);
if (intersection.first)
{
return origin + invertedDirection * intersection.second;
}
return ray.getOrigin() + direction * maxDistance;
}
//-----------------------------------------------------------------------
GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) :
mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient)
{
}
//-----------------------------------------------------------------------
GridSource::~GridSource(void)
{
}
//-----------------------------------------------------------------------
Vector4 GridSource::getValueAndGradient(const Vector3 &position) const
{
Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
Vector3 gradient;
if (mTrilinearGradient)
{
size_t x0 = (size_t)scaledPosition.x;
size_t x1 = (size_t)ceil(scaledPosition.x);
size_t y0 = (size_t)scaledPosition.y;
size_t y1 = (size_t)ceil(scaledPosition.y);
size_t z0 = (size_t)scaledPosition.z;
size_t z1 = (size_t)ceil(scaledPosition.z);
Real dX = scaledPosition.x - (Real)x0;
Real dY = scaledPosition.y - (Real)y0;
Real dZ = scaledPosition.z - (Real)z0;
Vector3 f000 = getGradient(x0, y0, z0);
Vector3 f100 = getGradient(x1, y0, z0);
Vector3 f010 = getGradient(x0, y1, z0);
Vector3 f001 = getGradient(x0, y0, z1);
Vector3 f101 = getGradient(x1, y0, z1);
Vector3 f011 = getGradient(x0, y1, z1);
Vector3 f110 = getGradient(x1, y1, z0);
Vector3 f111 = getGradient(x1, y1, z1);
Real oneMinX = (Real)1.0 - dX;
Real oneMinY = (Real)1.0 - dY;
Real oneMinZ = (Real)1.0 - dZ;
Real oneMinXoneMinY = oneMinX * oneMinY;
Real dXOneMinY = dX * oneMinY;
gradient = oneMinZ * (f000 * oneMinXoneMinY
+ f100 * dXOneMinY
+ f010 * oneMinX * dY)
+ dZ * (f001 * oneMinXoneMinY
+ f101 * dXOneMinY
+ f011 * oneMinX * dY)
+ dX * dY * (f110 * oneMinZ
+ f111 * dZ);
gradient *= (Real)-1.0;
}
else
{
gradient = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5));
gradient *= (Real)-1.0;
}
return Vector4(gradient.x, gradient.y, gradient.z, getValue(position));
}
//-----------------------------------------------------------------------
Real GridSource::getValue(const Vector3 &position) const
{
Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
Real value;
if (mTrilinearValue)
{
size_t x0 = (size_t)scaledPosition.x;
size_t x1 = (size_t)ceil(scaledPosition.x);
size_t y0 = (size_t)scaledPosition.y;
size_t y1 = (size_t)ceil(scaledPosition.y);
size_t z0 = (size_t)scaledPosition.z;
size_t z1 = (size_t)ceil(scaledPosition.z);
Real dX = scaledPosition.x - (Real)x0;
Real dY = scaledPosition.y - (Real)y0;
Real dZ = scaledPosition.z - (Real)z0;
Real f000 = getVolumeGridValue(x0, y0, z0);
Real f100 = getVolumeGridValue(x1, y0, z0);
Real f010 = getVolumeGridValue(x0, y1, z0);
Real f001 = getVolumeGridValue(x0, y0, z1);
Real f101 = getVolumeGridValue(x1, y0, z1);
Real f011 = getVolumeGridValue(x0, y1, z1);
Real f110 = getVolumeGridValue(x1, y1, z0);
Real f111 = getVolumeGridValue(x1, y1, z1);
Real oneMinX = (Real)1.0 - dX;
Real oneMinY = (Real)1.0 - dY;
Real oneMinZ = (Real)1.0 - dZ;
Real oneMinXoneMinY = oneMinX * oneMinY;
Real dXOneMinY = dX * oneMinY;
value = oneMinZ * (f000 * oneMinXoneMinY
+ f100 * dXOneMinY
+ f010 * oneMinX * dY)
+ dZ * (f001 * oneMinXoneMinY
+ f101 * dXOneMinY
+ f011 * oneMinX * dY)
+ dX * dY * (f110 * oneMinZ
+ f111 * dZ);
}
else
{
// Nearest neighbour else
size_t x = (size_t)(scaledPosition.x + (Real)0.5);
size_t y = (size_t)(scaledPosition.y + (Real)0.5);
size_t z = (size_t)(scaledPosition.z + (Real)0.5);
value = (Real)getVolumeGridValue(x, y, z);
}
return value;
}
//-----------------------------------------------------------------------
size_t GridSource::getWidth(void) const
{
return mWidth;
}
//-----------------------------------------------------------------------
size_t GridSource::getHeight(void) const
{
return mHeight;
}
//-----------------------------------------------------------------------
size_t GridSource::getDepth(void) const
{
return mDepth;
}
//-----------------------------------------------------------------------
void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 ¢er, Real radius)
{
Real worldWidthScale = (Real)1.0 / mPosXScale;
Real worldHeightScale = (Real)1.0 / mPosYScale;
Real worldDepthScale = (Real)1.0 / mPosZScale;
operation->setSourceA(this);
operation->setSourceB(source);
// No need for trilineaer interpolation here as we iterate over the
// cells anyway.
bool oldTrilinearValue = mTrilinearValue;
mTrilinearValue = false;
float value;
int x, y;
Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale);
int xStart = Math::Clamp((size_t)(scaledCenter.x - radius * mPosXScale), (size_t)0, mWidth);
int xEnd = Math::Clamp((size_t)(scaledCenter.x + radius * mPosXScale), (size_t)0, mWidth);
int yStart = Math::Clamp((size_t)(scaledCenter.y - radius * mPosYScale), (size_t)0, mHeight);
int yEnd = Math::Clamp((size_t)(scaledCenter.y + radius * mPosYScale), (size_t)0, mHeight);
int zStart = Math::Clamp((size_t)(scaledCenter.z - radius * mPosZScale), (size_t)0, mDepth);
int zEnd = Math::Clamp((size_t)(scaledCenter.z + radius * mPosZScale), (size_t)0, mDepth);
Vector3 pos;
for (int z = zStart; z < zEnd; ++z)
{
for (y = yStart; y < yEnd; ++y)
{
for (x = xStart; x < xEnd; ++x)
{
pos.x = x * worldWidthScale;
pos.y = y * worldHeightScale;
pos.z = z * worldDepthScale;
value = operation->getValue(pos);
setVolumeGridValue(x, y, z, value);
}
}
}
mTrilinearValue = oldTrilinearValue;
}
//-----------------------------------------------------------------------
Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const
{
return mVolumeSpaceToWorldSpaceFactor;
}
}
}<|endoftext|> |
<commit_before>#include "../base/SRC_FIRST.hpp"
#include "overlay_element.hpp"
namespace graphics
{
OverlayElement::~OverlayElement()
{}
OverlayElement::Params::Params()
: m_pivot(0, 0),
m_position(EPosAboveRight),
m_depth(maxDepth),
m_userInfo()
{}
OverlayElement::OverlayElement(Params const & p)
: m_pivot(p.m_pivot),
m_position(p.m_position),
m_depth(p.m_depth),
m_isNeedRedraw(true),
m_isFrozen(false),
m_isVisible(true),
m_isValid(true),
m_isDirtyRect(true),
m_isDirtyLayout(true),
m_isDirtyRoughRect(true),
m_userInfo(p.m_userInfo)
{}
m2::PointD const OverlayElement::computeTopLeft(m2::PointD const & sz,
m2::PointD const & pv,
EPosition pos)
{
m2::PointD res;
if (pos & EPosLeft)
res.x = pv.x - sz.x;
else if (pos & EPosRight)
res.x = pv.x;
else
res.x = pv.x - sz.x / 2;
if (pos & EPosAbove)
res.y = pv.y - sz.y;
else if (pos & EPosUnder)
res.y = pv.y;
else
res.y = pv.y - sz.y / 2;
return res;
}
void OverlayElement::offset(m2::PointD const & offs)
{
setPivot(pivot() + offs);
setIsDirtyRect(true);
}
m2::PointD const & OverlayElement::pivot() const
{
return m_pivot;
}
void OverlayElement::setPivot(m2::PointD const & pivot)
{
m_pivot = pivot;
setIsDirtyRect(true);
}
graphics::EPosition OverlayElement::position() const
{
return m_position;
}
void OverlayElement::setPosition(graphics::EPosition pos)
{
m_position = pos;
setIsDirtyRect(true);
}
double OverlayElement::depth() const
{
return m_depth;
}
void OverlayElement::setDepth(double depth)
{
m_depth = depth;
}
bool OverlayElement::isFrozen() const
{
return m_isFrozen;
}
void OverlayElement::setIsFrozen(bool flag)
{
m_isFrozen = flag;
}
bool OverlayElement::isNeedRedraw() const
{
return m_isNeedRedraw;
}
void OverlayElement::setIsNeedRedraw(bool flag)
{
m_isNeedRedraw = flag;
}
bool OverlayElement::isVisible() const
{
return m_isVisible;
}
void OverlayElement::setIsVisible(bool flag)
{
m_isVisible = flag;
}
bool OverlayElement::isDirtyLayout() const
{
return m_isDirtyLayout;
}
void OverlayElement::setIsDirtyLayout(bool flag) const
{
m_isDirtyLayout = flag;
if (flag)
setIsDirtyRect(true);
}
bool OverlayElement::isDirtyRect() const
{
return m_isDirtyRect;
}
void OverlayElement::setIsDirtyRect(bool flag) const
{
if (flag)
m_isDirtyRoughRect = true;
m_isDirtyRect = flag;
}
m2::RectD const & OverlayElement::roughBoundRect() const
{
if (m_isDirtyRoughRect)
{
for (int i = 0; i < boundRects().size(); ++i)
if (i == 0)
m_roughBoundRect = boundRects()[i].GetGlobalRect();
else
m_roughBoundRect.Add(boundRects()[i].GetGlobalRect());
m_isDirtyRoughRect = false;
}
return m_roughBoundRect;
}
bool OverlayElement::hitTest(m2::PointD const & pt) const
{
vector<m2::AnyRectD> const & rects = boundRects();
for (vector<m2::AnyRectD>::const_iterator it = rects.begin(); it != rects.end(); ++it)
if (it->IsPointInside(pt))
return true;
return false;
}
bool OverlayElement::isValid() const
{
return m_isValid;
}
void OverlayElement::setIsValid(bool flag)
{
m_isValid = flag;
}
bool OverlayElement::roughHitTest(m2::PointD const & pt) const
{
return roughBoundRect().IsPointInside(pt);
}
OverlayElement::UserInfo const & OverlayElement::userInfo() const
{
return m_userInfo;
}
m2::PointD const OverlayElement::point(EPosition pos) const
{
/// @todo It's better to call roughBoundRect(), or place ASSERT(!m_isDirtyRoughRect, ()) here.
/// In general there is no need to store m_roughBoundRect at all.
/// It's calculating time is fast, because elements already cache vector<m2::AnyRectD>.
m2::PointD res = m_roughBoundRect.Center();
if (pos & EPosLeft)
res.x = m_roughBoundRect.minX();
if (pos & EPosRight)
res.x = m_roughBoundRect.maxX();
if (pos & EPosAbove)
res.y = m_roughBoundRect.minY();
if (pos & EPosUnder)
res.y = m_roughBoundRect.maxY();
return res;
}
bool OverlayElement::hasSharpGeometry() const
{
return false;
}
double OverlayElement::priority() const
{
return m_depth;
}
}
<commit_msg>default value for OverlayElement was made zero.<commit_after>#include "../base/SRC_FIRST.hpp"
#include "overlay_element.hpp"
namespace graphics
{
OverlayElement::~OverlayElement()
{}
OverlayElement::Params::Params()
: m_pivot(0, 0),
m_position(EPosAboveRight),
m_depth(0),
m_userInfo()
{}
OverlayElement::OverlayElement(Params const & p)
: m_pivot(p.m_pivot),
m_position(p.m_position),
m_depth(p.m_depth),
m_isNeedRedraw(true),
m_isFrozen(false),
m_isVisible(true),
m_isValid(true),
m_isDirtyRect(true),
m_isDirtyLayout(true),
m_isDirtyRoughRect(true),
m_userInfo(p.m_userInfo)
{}
m2::PointD const OverlayElement::computeTopLeft(m2::PointD const & sz,
m2::PointD const & pv,
EPosition pos)
{
m2::PointD res;
if (pos & EPosLeft)
res.x = pv.x - sz.x;
else if (pos & EPosRight)
res.x = pv.x;
else
res.x = pv.x - sz.x / 2;
if (pos & EPosAbove)
res.y = pv.y - sz.y;
else if (pos & EPosUnder)
res.y = pv.y;
else
res.y = pv.y - sz.y / 2;
return res;
}
void OverlayElement::offset(m2::PointD const & offs)
{
setPivot(pivot() + offs);
setIsDirtyRect(true);
}
m2::PointD const & OverlayElement::pivot() const
{
return m_pivot;
}
void OverlayElement::setPivot(m2::PointD const & pivot)
{
m_pivot = pivot;
setIsDirtyRect(true);
}
graphics::EPosition OverlayElement::position() const
{
return m_position;
}
void OverlayElement::setPosition(graphics::EPosition pos)
{
m_position = pos;
setIsDirtyRect(true);
}
double OverlayElement::depth() const
{
return m_depth;
}
void OverlayElement::setDepth(double depth)
{
m_depth = depth;
}
bool OverlayElement::isFrozen() const
{
return m_isFrozen;
}
void OverlayElement::setIsFrozen(bool flag)
{
m_isFrozen = flag;
}
bool OverlayElement::isNeedRedraw() const
{
return m_isNeedRedraw;
}
void OverlayElement::setIsNeedRedraw(bool flag)
{
m_isNeedRedraw = flag;
}
bool OverlayElement::isVisible() const
{
return m_isVisible;
}
void OverlayElement::setIsVisible(bool flag)
{
m_isVisible = flag;
}
bool OverlayElement::isDirtyLayout() const
{
return m_isDirtyLayout;
}
void OverlayElement::setIsDirtyLayout(bool flag) const
{
m_isDirtyLayout = flag;
if (flag)
setIsDirtyRect(true);
}
bool OverlayElement::isDirtyRect() const
{
return m_isDirtyRect;
}
void OverlayElement::setIsDirtyRect(bool flag) const
{
if (flag)
m_isDirtyRoughRect = true;
m_isDirtyRect = flag;
}
m2::RectD const & OverlayElement::roughBoundRect() const
{
if (m_isDirtyRoughRect)
{
for (int i = 0; i < boundRects().size(); ++i)
if (i == 0)
m_roughBoundRect = boundRects()[i].GetGlobalRect();
else
m_roughBoundRect.Add(boundRects()[i].GetGlobalRect());
m_isDirtyRoughRect = false;
}
return m_roughBoundRect;
}
bool OverlayElement::hitTest(m2::PointD const & pt) const
{
vector<m2::AnyRectD> const & rects = boundRects();
for (vector<m2::AnyRectD>::const_iterator it = rects.begin(); it != rects.end(); ++it)
if (it->IsPointInside(pt))
return true;
return false;
}
bool OverlayElement::isValid() const
{
return m_isValid;
}
void OverlayElement::setIsValid(bool flag)
{
m_isValid = flag;
}
bool OverlayElement::roughHitTest(m2::PointD const & pt) const
{
return roughBoundRect().IsPointInside(pt);
}
OverlayElement::UserInfo const & OverlayElement::userInfo() const
{
return m_userInfo;
}
m2::PointD const OverlayElement::point(EPosition pos) const
{
/// @todo It's better to call roughBoundRect(), or place ASSERT(!m_isDirtyRoughRect, ()) here.
/// In general there is no need to store m_roughBoundRect at all.
/// It's calculating time is fast, because elements already cache vector<m2::AnyRectD>.
m2::PointD res = m_roughBoundRect.Center();
if (pos & EPosLeft)
res.x = m_roughBoundRect.minX();
if (pos & EPosRight)
res.x = m_roughBoundRect.maxX();
if (pos & EPosAbove)
res.y = m_roughBoundRect.minY();
if (pos & EPosUnder)
res.y = m_roughBoundRect.maxY();
return res;
}
bool OverlayElement::hasSharpGeometry() const
{
return false;
}
double OverlayElement::priority() const
{
return m_depth;
}
}
<|endoftext|> |
<commit_before>/*
* tests/wobbly_test.cpp
*
* Tests for the "wobbly" spring model.
*
* See LICENCE.md for Copyright information.
*/
#include <array> // for array
#include <functional> // for function, __base
#include <memory> // for unique_ptr
#include <sstream> // for char_traits, etc
#include <type_traits> // for move
#include <stdlib.h> // for exit
#include <boost/test/utils/wrap_stringstream.hpp> // for operator<<
#include <gmock/gmock-matchers.h> // for EXPECT_THAT, etc
#include <gtest/gtest-death-test.h> // for DeathTest, ExitedWithCode, etc
#include <gtest/gtest.h> // for AssertHelper, TEST_F, etc
#include <gmock/gmock.h> // IWYU pragma: keep
#include <wobbly/wobbly.h> // for PointView, Point, Vector
#include <wobbly_internal.h> // for Spring, etc
#include "boost_geometry.h" // IWYU pragma: keep
#include <mathematical_model_matcher.h> // for Eq, EqDispatchHelper, etc
#include <ostream_point_operator.h> // for operator<<
using ::testing::ExitedWithCode;
using ::testing::Not;
using ::testing::Test;
using ::wobbly::matchers::Eq;
using ::wobbly::matchers::SatisfiesModel;
using ::wobbly::models::Linear;
namespace bg = boost::geometry;
namespace
{
class SingleObjectStorage
{
public:
SingleObjectStorage ()
{
storage.fill (0);
}
wobbly::PointView <double> Position ()
{
return wobbly::PointView <double> (storage, 0);
}
wobbly::PointView <double> Velocity ()
{
return wobbly::PointView <double> (storage, 1);
}
wobbly::PointView <double> Force ()
{
return wobbly::PointView <double> (storage, 2);
}
private:
std::array <double, 6> storage;
};
class SingleObjectStorageView
{
public:
SingleObjectStorageView (SingleObjectStorage &storage) :
position (storage.Position ()),
velocity (storage.Velocity ()),
force (storage.Force ())
{
}
wobbly::PointView <double> position;
wobbly::PointView <double> velocity;
wobbly::PointView <double> force;
};
constexpr double FirstPositionX = 50.0f;
constexpr double FirstPositionY = 50.0f;
constexpr double SecondPositionX = 100.0f;
constexpr double SecondPositionY = 100.0f;
constexpr double SpringConstant = 0.5f;
TEST (Spring, MoveConstructorNoExcept)
{
SingleObjectStorage storageA, storageB;
EXPECT_NO_THROW ({
wobbly::Spring a (storageA.Force (),
storageB.Force (),
storageA.Position (),
storageB.Position (),
wobbly::Vector (0, 0));
wobbly::Spring b (std::move (a));
});
}
TEST (Spring, MoveAssignToSelf)
{
SingleObjectStorage storageA, storageB;
EXPECT_EXIT ({
wobbly::Spring a (storageA.Force (),
storageB.Force (),
storageA.Position (),
storageB.Position (),
wobbly::Vector (0, 0));
a = std::move (a);
exit (0);
}, ExitedWithCode (0), "");
}
class Springs :
public ::testing::Test
{
public:
Springs ():
desiredDistance (SecondPositionX - FirstPositionX,
SecondPositionY - FirstPositionY),
first (firstStorage),
second (secondStorage),
spring (firstStorage.Force (),
secondStorage.Force (),
firstStorage.Position (),
secondStorage.Position (),
desiredDistance)
{
bg::assign_point (first.position,
wobbly::Point (FirstPositionX,
FirstPositionY));
bg::assign_point (second.position,
wobbly::Point (SecondPositionX,
SecondPositionY));
}
protected:
wobbly::Vector desiredDistance;
private:
SingleObjectStorage firstStorage;
SingleObjectStorage secondStorage;
protected:
SingleObjectStorageView first;
SingleObjectStorageView second;
wobbly::Spring spring;
};
TEST_F (Springs, NoForceAppliedWhenNoDeltaFromDesired)
{
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force,
Eq (wobbly::Vector (0, 0)));
EXPECT_THAT (second.force,
Eq (wobbly::Vector (0, 0)));
}
template <typename Position>
wobbly::Vector
ForceForSpring (Position const &first,
Position const &second,
wobbly::Vector const &desired)
{
wobbly::Vector expectedForce;
bg::assign (expectedForce, second);
bg::subtract_point (expectedForce, first);
bg::subtract_point (expectedForce, desired);
bg::multiply_value (expectedForce, SpringConstant);
bg::divide_value (expectedForce, 2);
return expectedForce;
}
TEST_F (Springs, ForceAppliedToFirstObjectProportianalToPositiveDistanceSK)
{
bg::assign (first.position,
wobbly::Vector (FirstPositionX - 10.0f,
FirstPositionY - 10.0f));
wobbly::Vector expectedForce (ForceForSpring (first.position,
second.position,
desiredDistance));
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force, Eq (expectedForce));
}
TEST_F (Springs, ForceAppliedToSecondObjectProportionalToNegativeDistanceSK)
{
bg::assign (first.position, wobbly::Vector (FirstPositionX - 10.0f,
FirstPositionY - 10.0f));
wobbly::Vector negativeDistance (desiredDistance);
bg::multiply_value (negativeDistance, -1.0f);
wobbly::Vector expectedForce (ForceForSpring (second.position,
first.position,
negativeDistance));
spring.ApplyForces (SpringConstant);
EXPECT_THAT (second.force, Eq (expectedForce));
}
TEST_F (Springs, ForceAccumulatesWithApplications)
{
bg::assign (first.position,
wobbly::Vector (FirstPositionX - 10.0f,
FirstPositionY - 10.0f));
wobbly::Vector expectedForce (ForceForSpring (first.position,
second.position,
desiredDistance));
/* Scalar for single spring */
unsigned int const nApplications = 3;
bg::multiply_value (expectedForce, nApplications);
for (unsigned int i = 0; i < nApplications; ++i)
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force, Eq (expectedForce));
}
TEST_F (Springs, ForceRelationshipIsLinearlyRelatedToDistance)
{
std::function <double (int)> forceByDistanceFunction =
[this](int delta) -> double {
bg::assign (first.force, wobbly::Vector (0, 0));
bg::assign (second.force, wobbly::Vector (0, 0));
bg::assign (first.position,
wobbly::Vector (FirstPositionX - delta,
FirstPositionY));
bg::assign (second.position,
wobbly::Vector (SecondPositionX + delta,
SecondPositionY));
spring.ApplyForces (SpringConstant);
return bg::get <0> (first.force);
};
EXPECT_THAT (forceByDistanceFunction,
SatisfiesModel (Linear <double> ()));
}
TEST_F (Springs, ForceClippedWithVerySmallDelta)
{
double const justBelowThreshold = FirstPositionX -
wobbly::Spring::ClipThreshold * 1.1;
bg::assign (first.position,
wobbly::Vector (justBelowThreshold, FirstPositionY));
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force, Eq (wobbly::Vector (0, 0)));
}
TEST_F (Springs, ApplyForcesReturnsTrueIfForceRemaining)
{
/* Change the position of one object, that will cause forces
* to be exerted
*/
bg::assign (first.position, wobbly::Vector (FirstPositionX - 10,
FirstPositionY));
EXPECT_TRUE (spring.ApplyForces (SpringConstant));
}
TEST_F (Springs, ApplyForcesReturnsFalseIfNoForceRemaining)
{
/* Where there is no delta, there is no force */
EXPECT_FALSE (spring.ApplyForces (0.0f));
}
double const SpringScaleFactor = 2.0f;
TEST_F (Springs, ForceExistsAfterLengthScaled)
{
spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
SpringScaleFactor));
EXPECT_TRUE (spring.ApplyForces (SpringConstant));
}
TEST_F (Springs, NoForceAfterLengthScaledAndObjectsMoved)
{
/* Calculate distance between first and second, then adjust
* second object's position to be distance * scaleFactor */
wobbly::Vector distance;
bg::assign (distance, second.position);
bg::subtract_point (distance, first.position);
bg::subtract_point (second.position, distance);
bg::multiply_value (distance, SpringScaleFactor);
bg::add_point (second.position, distance);
spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
SpringScaleFactor));
EXPECT_FALSE (spring.ApplyForces (SpringConstant));
}
}
<commit_msg>spring_test: Remove MoveAssignToSelf<commit_after>/*
* tests/wobbly_test.cpp
*
* Tests for the "wobbly" spring model.
*
* See LICENCE.md for Copyright information.
*/
#include <array> // for array
#include <functional> // for function, __base
#include <memory> // for unique_ptr
#include <sstream> // for char_traits, etc
#include <type_traits> // for move
#include <stdlib.h> // for exit
#include <boost/test/utils/wrap_stringstream.hpp> // for operator<<
#include <gmock/gmock-matchers.h> // for EXPECT_THAT, etc
#include <gtest/gtest-death-test.h> // for DeathTest, ExitedWithCode, etc
#include <gtest/gtest.h> // for AssertHelper, TEST_F, etc
#include <gmock/gmock.h> // IWYU pragma: keep
#include <wobbly/wobbly.h> // for PointView, Point, Vector
#include <wobbly_internal.h> // for Spring, etc
#include "boost_geometry.h" // IWYU pragma: keep
#include <mathematical_model_matcher.h> // for Eq, EqDispatchHelper, etc
#include <ostream_point_operator.h> // for operator<<
using ::testing::ExitedWithCode;
using ::testing::Not;
using ::testing::Test;
using ::wobbly::matchers::Eq;
using ::wobbly::matchers::SatisfiesModel;
using ::wobbly::models::Linear;
namespace bg = boost::geometry;
namespace
{
class SingleObjectStorage
{
public:
SingleObjectStorage ()
{
storage.fill (0);
}
wobbly::PointView <double> Position ()
{
return wobbly::PointView <double> (storage, 0);
}
wobbly::PointView <double> Velocity ()
{
return wobbly::PointView <double> (storage, 1);
}
wobbly::PointView <double> Force ()
{
return wobbly::PointView <double> (storage, 2);
}
private:
std::array <double, 6> storage;
};
class SingleObjectStorageView
{
public:
SingleObjectStorageView (SingleObjectStorage &storage) :
position (storage.Position ()),
velocity (storage.Velocity ()),
force (storage.Force ())
{
}
wobbly::PointView <double> position;
wobbly::PointView <double> velocity;
wobbly::PointView <double> force;
};
constexpr double FirstPositionX = 50.0f;
constexpr double FirstPositionY = 50.0f;
constexpr double SecondPositionX = 100.0f;
constexpr double SecondPositionY = 100.0f;
constexpr double SpringConstant = 0.5f;
TEST (Spring, MoveConstructorNoExcept)
{
SingleObjectStorage storageA, storageB;
EXPECT_NO_THROW ({
wobbly::Spring a (storageA.Force (),
storageB.Force (),
storageA.Position (),
storageB.Position (),
wobbly::Vector (0, 0));
wobbly::Spring b (std::move (a));
});
}
class Springs :
public ::testing::Test
{
public:
Springs ():
desiredDistance (SecondPositionX - FirstPositionX,
SecondPositionY - FirstPositionY),
first (firstStorage),
second (secondStorage),
spring (firstStorage.Force (),
secondStorage.Force (),
firstStorage.Position (),
secondStorage.Position (),
desiredDistance)
{
bg::assign_point (first.position,
wobbly::Point (FirstPositionX,
FirstPositionY));
bg::assign_point (second.position,
wobbly::Point (SecondPositionX,
SecondPositionY));
}
protected:
wobbly::Vector desiredDistance;
private:
SingleObjectStorage firstStorage;
SingleObjectStorage secondStorage;
protected:
SingleObjectStorageView first;
SingleObjectStorageView second;
wobbly::Spring spring;
};
TEST_F (Springs, NoForceAppliedWhenNoDeltaFromDesired)
{
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force,
Eq (wobbly::Vector (0, 0)));
EXPECT_THAT (second.force,
Eq (wobbly::Vector (0, 0)));
}
template <typename Position>
wobbly::Vector
ForceForSpring (Position const &first,
Position const &second,
wobbly::Vector const &desired)
{
wobbly::Vector expectedForce;
bg::assign (expectedForce, second);
bg::subtract_point (expectedForce, first);
bg::subtract_point (expectedForce, desired);
bg::multiply_value (expectedForce, SpringConstant);
bg::divide_value (expectedForce, 2);
return expectedForce;
}
TEST_F (Springs, ForceAppliedToFirstObjectProportianalToPositiveDistanceSK)
{
bg::assign (first.position,
wobbly::Vector (FirstPositionX - 10.0f,
FirstPositionY - 10.0f));
wobbly::Vector expectedForce (ForceForSpring (first.position,
second.position,
desiredDistance));
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force, Eq (expectedForce));
}
TEST_F (Springs, ForceAppliedToSecondObjectProportionalToNegativeDistanceSK)
{
bg::assign (first.position, wobbly::Vector (FirstPositionX - 10.0f,
FirstPositionY - 10.0f));
wobbly::Vector negativeDistance (desiredDistance);
bg::multiply_value (negativeDistance, -1.0f);
wobbly::Vector expectedForce (ForceForSpring (second.position,
first.position,
negativeDistance));
spring.ApplyForces (SpringConstant);
EXPECT_THAT (second.force, Eq (expectedForce));
}
TEST_F (Springs, ForceAccumulatesWithApplications)
{
bg::assign (first.position,
wobbly::Vector (FirstPositionX - 10.0f,
FirstPositionY - 10.0f));
wobbly::Vector expectedForce (ForceForSpring (first.position,
second.position,
desiredDistance));
/* Scalar for single spring */
unsigned int const nApplications = 3;
bg::multiply_value (expectedForce, nApplications);
for (unsigned int i = 0; i < nApplications; ++i)
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force, Eq (expectedForce));
}
TEST_F (Springs, ForceRelationshipIsLinearlyRelatedToDistance)
{
std::function <double (int)> forceByDistanceFunction =
[this](int delta) -> double {
bg::assign (first.force, wobbly::Vector (0, 0));
bg::assign (second.force, wobbly::Vector (0, 0));
bg::assign (first.position,
wobbly::Vector (FirstPositionX - delta,
FirstPositionY));
bg::assign (second.position,
wobbly::Vector (SecondPositionX + delta,
SecondPositionY));
spring.ApplyForces (SpringConstant);
return bg::get <0> (first.force);
};
EXPECT_THAT (forceByDistanceFunction,
SatisfiesModel (Linear <double> ()));
}
TEST_F (Springs, ForceClippedWithVerySmallDelta)
{
double const justBelowThreshold = FirstPositionX -
wobbly::Spring::ClipThreshold * 1.1;
bg::assign (first.position,
wobbly::Vector (justBelowThreshold, FirstPositionY));
spring.ApplyForces (SpringConstant);
EXPECT_THAT (first.force, Eq (wobbly::Vector (0, 0)));
}
TEST_F (Springs, ApplyForcesReturnsTrueIfForceRemaining)
{
/* Change the position of one object, that will cause forces
* to be exerted
*/
bg::assign (first.position, wobbly::Vector (FirstPositionX - 10,
FirstPositionY));
EXPECT_TRUE (spring.ApplyForces (SpringConstant));
}
TEST_F (Springs, ApplyForcesReturnsFalseIfNoForceRemaining)
{
/* Where there is no delta, there is no force */
EXPECT_FALSE (spring.ApplyForces (0.0f));
}
double const SpringScaleFactor = 2.0f;
TEST_F (Springs, ForceExistsAfterLengthScaled)
{
spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
SpringScaleFactor));
EXPECT_TRUE (spring.ApplyForces (SpringConstant));
}
TEST_F (Springs, NoForceAfterLengthScaledAndObjectsMoved)
{
/* Calculate distance between first and second, then adjust
* second object's position to be distance * scaleFactor */
wobbly::Vector distance;
bg::assign (distance, second.position);
bg::subtract_point (distance, first.position);
bg::subtract_point (second.position, distance);
bg::multiply_value (distance, SpringScaleFactor);
bg::add_point (second.position, distance);
spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
SpringScaleFactor));
EXPECT_FALSE (spring.ApplyForces (SpringConstant));
}
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
struct UnionFind {
vector<int> p, rank, setSize;
int numSets;
UnionFind(int N) {
setSize.assign(N, 1);
numSets = N;
rank.assign(N, 0);
p.assign(N, 0);
for (int i = 0; i < N; i++) p[i] = i;
}
int findSet(int i) {
return (p[i] == i) ? i : (p[i] = findSet(p[i]));
}
bool isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void unionSet(int i, int j) {
if (!isSameSet(i, j)) {
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x; setSize[x] += setSize[y];
} else {
p[x] = y; setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
}
}
}
int numDisjointSets() {
return numSets;
}
int sizeOfSet(int i) {
return setSize[findSet(i)];
}
};
int main() {
}<commit_msg>Reindent UnionFind<commit_after>#include <bits/stdc++.h>
using namespace std;
struct UnionFind {
vector<int> p, rank, setSize;
int numSets;
UnionFind(int N) {
setSize.assign(N, 1);
numSets = N;
rank.assign(N, 0);
p.assign(N, 0);
for (int i = 0; i < N; i++) p[i] = i;
}
int findSet(int i) {
return (p[i] == i) ? i : (p[i] = findSet(p[i]));
}
bool isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void unionSet(int i, int j) {
if (!isSameSet(i, j)) {
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x; setSize[x] += setSize[y];
} else {
p[x] = y; setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
}
}
}
int numDisjointSets() {
return numSets;
}
int sizeOfSet(int i) {
return setSize[findSet(i)];
}
};
int main() {
}<|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 "chrome/browser/chromeos/system/touchpad_settings.h"
#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace {
const char kLockOnIdleSuspendPath[] =
"/var/lib/power_manager/lock_on_idle_suspend";
void EnableScreenLockOnFileThread(bool enable) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
std::string config = base::StringPrintf("%d", enable);
file_util::WriteFile(FilePath(kLockOnIdleSuspendPath),
config.c_str(),
config.size());
}
}
} // namespace
namespace chromeos {
namespace system {
namespace screen_locker_settings {
void EnableScreenLock(bool enable) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Run this on the FILE thread.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&EnableScreenLockOnFileThread, enable));
}
} // namespace screen_locker_settings
} // namespace system
} // namespace chromeos
<commit_msg>Fix erroneous include in screen_locker_settings.<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 "chrome/browser/chromeos/system/screen_locker_settings.h"
#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace {
const char kLockOnIdleSuspendPath[] =
"/var/lib/power_manager/lock_on_idle_suspend";
void EnableScreenLockOnFileThread(bool enable) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
std::string config = base::StringPrintf("%d", enable);
file_util::WriteFile(FilePath(kLockOnIdleSuspendPath),
config.c_str(),
config.size());
}
}
} // namespace
namespace chromeos {
namespace system {
namespace screen_locker_settings {
void EnableScreenLock(bool enable) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Run this on the FILE thread.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&EnableScreenLockOnFileThread, enable));
}
} // namespace screen_locker_settings
} // namespace system
} // namespace chromeos
<|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 "chrome/browser/ui/browser_dialogs.h"
#include <gtk/gtk.h>
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/logging_chrome.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/result_codes.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/base/gtk/gtk_signal.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/gtk_util.h"
#include "ui/gfx/image/image.h"
namespace {
// A wrapper class that represents the Gtk dialog.
class HungRendererDialogGtk {
public:
HungRendererDialogGtk();
virtual ~HungRendererDialogGtk() {}
void ShowForTabContents(TabContents* hung_contents);
void EndForTabContents(TabContents* hung_contents);
private:
// The GtkTreeView column ids.
enum {
COL_FAVICON,
COL_TITLE,
COL_COUNT,
};
// Create the gtk dialog and add the widgets.
void Init();
CHROMEGTK_CALLBACK_1(HungRendererDialogGtk, void, OnResponse, int);
GtkDialog* dialog_;
GtkListStore* model_;
TabContents* contents_;
DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);
};
// We only support showing one of these at a time per app.
HungRendererDialogGtk* g_instance = NULL;
// The response ID for the "Kill pages" button. Anything positive should be
// fine (the built in GtkResponseTypes are negative numbers).
const int kKillPagesButtonResponse = 1;
HungRendererDialogGtk::HungRendererDialogGtk()
: dialog_(NULL), model_(NULL), contents_(NULL) {
Init();
}
void HungRendererDialogGtk::Init() {
dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),
NULL, // No parent because tabs can span multiple windows.
GTK_DIALOG_NO_SEPARATOR,
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),
kKillPagesButtonResponse,
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),
GTK_RESPONSE_OK,
NULL));
gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);
g_signal_connect(dialog_, "delete-event",
G_CALLBACK(gtk_widget_hide_on_delete), NULL);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);
// We have an hbox with the frozen icon on the left. On the right,
// we have a vbox with the unresponsive text on top and a table of
// tabs on bottom.
// ·-----------------------------------·
// |·---------------------------------·|
// ||·----·|·------------------------·||
// |||icon||| |||
// ||·----·|| The folowing page(s).. |||
// || || |||
// || ||------------------------|||
// || || table of tabs |||
// || |·------------------------·||
// |·---------------------------------·|
// | |
// | kill button wait button|
// ·-----------------------------------·
GtkWidget* content_area = gtk_dialog_get_content_area(dialog_);
gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing);
GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
// Wrap the icon in a vbox so it stays top aligned.
GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
GdkPixbuf* icon_pixbuf = rb.GetNativeImageNamed(IDR_FROZEN_TAB_ICON);
GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);
gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);
GtkWidget* vbox = gtk_vbox_new(FALSE, ui::kControlSpacing);
gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
GtkWidget* text = gtk_label_new(
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());
gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);
GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),
GTK_SHADOW_ETCHED_IN);
gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);
// The list of hung tabs is GtkTreeView with a GtkListStore as the model.
model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
GtkWidget* tree_view = gtk_tree_view_new_with_model(
GTK_TREE_MODEL(model_));
g_object_unref(model_);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);
GtkTreeViewColumn* column = gtk_tree_view_column_new();
GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start(column, renderer, FALSE);
gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(column, renderer, TRUE);
gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);
gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);
gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);
}
void HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {
DCHECK(hung_contents && dialog_);
contents_ = hung_contents;
gtk_list_store_clear(model_);
GtkTreeIter tree_iter;
for (TabContentsIterator it; !it.done(); ++it) {
if (it->tab_contents()->GetRenderProcessHost() ==
hung_contents->GetRenderProcessHost()) {
gtk_list_store_append(model_, &tree_iter);
std::string title = UTF16ToUTF8(it->tab_contents()->GetTitle());
if (title.empty())
title = UTF16ToUTF8(TabContentsWrapper::GetDefaultTitle());
SkBitmap favicon = it->favicon_tab_helper()->GetFavicon();
GdkPixbuf* pixbuf = NULL;
if (favicon.width() > 0)
pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);
gtk_list_store_set(model_, &tree_iter,
COL_FAVICON, pixbuf,
COL_TITLE, title.c_str(),
-1);
if (pixbuf)
g_object_unref(pixbuf);
}
}
gtk_util::ShowDialog(GTK_WIDGET(dialog_));
}
void HungRendererDialogGtk::EndForTabContents(TabContents* contents) {
DCHECK(contents);
if (contents_ && contents_->GetRenderProcessHost() ==
contents->GetRenderProcessHost()) {
gtk_widget_hide(GTK_WIDGET(dialog_));
// Since we're closing, we no longer need this TabContents.
contents_ = NULL;
}
}
// When the user clicks a button on the dialog or closes the dialog, this
// callback is called.
void HungRendererDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
DCHECK(g_instance == this);
switch (response_id) {
case kKillPagesButtonResponse:
// Kill the process.
if (contents_ && contents_->GetRenderProcessHost()) {
base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),
content::RESULT_CODE_HUNG, false);
}
break;
case GTK_RESPONSE_OK:
case GTK_RESPONSE_DELETE_EVENT:
// Start waiting again for responsiveness.
if (contents_ && contents_->render_view_host())
contents_->render_view_host()->RestartHangMonitorTimeout();
break;
default:
NOTREACHED();
}
gtk_widget_destroy(GTK_WIDGET(dialog_));
delete g_instance;
g_instance = NULL;
}
} // namespace
namespace browser {
void ShowHungRendererDialog(TabContents* contents) {
if (!logging::DialogsAreSuppressed()) {
if (!g_instance)
g_instance = new HungRendererDialogGtk();
g_instance->ShowForTabContents(contents);
}
}
void HideHungRendererDialog(TabContents* contents) {
if (!logging::DialogsAreSuppressed() && g_instance)
g_instance->EndForTabContents(contents);
}
} // namespace browser
<commit_msg>[Linux] Observer initiating tab for destruction in hung-renderer dialog.<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 "chrome/browser/ui/browser_dialogs.h"
#include <gtk/gtk.h>
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/logging_chrome.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/result_codes.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/base/gtk/gtk_signal.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/gtk_util.h"
#include "ui/gfx/image/image.h"
namespace {
// A wrapper class that represents the Gtk dialog.
class HungRendererDialogGtk {
public:
HungRendererDialogGtk();
virtual ~HungRendererDialogGtk() {}
void ShowForTabContents(TabContents* hung_contents);
void Hide();
void EndForTabContents(TabContents* hung_contents);
private:
// Dismiss the panel if |contents_| is closed or its renderer exits.
class TabContentsObserverImpl : public TabContentsObserver {
public:
TabContentsObserverImpl(HungRendererDialogGtk* dialog,
TabContents* contents)
: TabContentsObserver(contents),
dialog_(dialog) {
}
// TabContentsObserver overrides:
virtual void RenderViewGone() OVERRIDE {
dialog_->Hide();
}
virtual void TabContentsDestroyed(TabContents* tab) OVERRIDE {
dialog_->Hide();
}
private:
HungRendererDialogGtk* dialog_; // weak
DISALLOW_COPY_AND_ASSIGN(TabContentsObserverImpl);
};
// The GtkTreeView column ids.
enum {
COL_FAVICON,
COL_TITLE,
COL_COUNT,
};
// Create the gtk dialog and add the widgets.
void Init();
CHROMEGTK_CALLBACK_1(HungRendererDialogGtk, void, OnResponse, int);
GtkDialog* dialog_;
GtkListStore* model_;
TabContents* contents_;
scoped_ptr<TabContentsObserverImpl> contents_observer_;
DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);
};
// We only support showing one of these at a time per app.
HungRendererDialogGtk* g_instance = NULL;
// The response ID for the "Kill pages" button. Anything positive should be
// fine (the built in GtkResponseTypes are negative numbers).
const int kKillPagesButtonResponse = 1;
HungRendererDialogGtk::HungRendererDialogGtk()
: dialog_(NULL), model_(NULL), contents_(NULL) {
Init();
}
void HungRendererDialogGtk::Init() {
dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),
NULL, // No parent because tabs can span multiple windows.
GTK_DIALOG_NO_SEPARATOR,
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),
kKillPagesButtonResponse,
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),
GTK_RESPONSE_OK,
NULL));
gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);
g_signal_connect(dialog_, "delete-event",
G_CALLBACK(gtk_widget_hide_on_delete), NULL);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);
// We have an hbox with the frozen icon on the left. On the right,
// we have a vbox with the unresponsive text on top and a table of
// tabs on bottom.
// ·-----------------------------------·
// |·---------------------------------·|
// ||·----·|·------------------------·||
// |||icon||| |||
// ||·----·|| The folowing page(s).. |||
// || || |||
// || ||------------------------|||
// || || table of tabs |||
// || |·------------------------·||
// |·---------------------------------·|
// | |
// | kill button wait button|
// ·-----------------------------------·
GtkWidget* content_area = gtk_dialog_get_content_area(dialog_);
gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing);
GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
// Wrap the icon in a vbox so it stays top aligned.
GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
GdkPixbuf* icon_pixbuf = rb.GetNativeImageNamed(IDR_FROZEN_TAB_ICON);
GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);
gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);
GtkWidget* vbox = gtk_vbox_new(FALSE, ui::kControlSpacing);
gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
GtkWidget* text = gtk_label_new(
l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());
gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);
GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),
GTK_SHADOW_ETCHED_IN);
gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);
// The list of hung tabs is GtkTreeView with a GtkListStore as the model.
model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
GtkWidget* tree_view = gtk_tree_view_new_with_model(
GTK_TREE_MODEL(model_));
g_object_unref(model_);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);
GtkTreeViewColumn* column = gtk_tree_view_column_new();
GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start(column, renderer, FALSE);
gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(column, renderer, TRUE);
gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);
gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);
gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);
}
void HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {
DCHECK(hung_contents && dialog_);
contents_ = hung_contents;
contents_observer_.reset(new TabContentsObserverImpl(this, contents_));
gtk_list_store_clear(model_);
GtkTreeIter tree_iter;
for (TabContentsIterator it; !it.done(); ++it) {
if (it->tab_contents()->GetRenderProcessHost() ==
hung_contents->GetRenderProcessHost()) {
gtk_list_store_append(model_, &tree_iter);
std::string title = UTF16ToUTF8(it->tab_contents()->GetTitle());
if (title.empty())
title = UTF16ToUTF8(TabContentsWrapper::GetDefaultTitle());
SkBitmap favicon = it->favicon_tab_helper()->GetFavicon();
GdkPixbuf* pixbuf = NULL;
if (favicon.width() > 0)
pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);
gtk_list_store_set(model_, &tree_iter,
COL_FAVICON, pixbuf,
COL_TITLE, title.c_str(),
-1);
if (pixbuf)
g_object_unref(pixbuf);
}
}
gtk_util::ShowDialog(GTK_WIDGET(dialog_));
}
void HungRendererDialogGtk::Hide() {
gtk_widget_hide(GTK_WIDGET(dialog_));
// Since we're closing, we no longer need this TabContents.
contents_observer_.reset();
contents_ = NULL;
}
void HungRendererDialogGtk::EndForTabContents(TabContents* contents) {
DCHECK(contents);
if (contents_ && contents_->GetRenderProcessHost() ==
contents->GetRenderProcessHost()) {
Hide();
}
}
// When the user clicks a button on the dialog or closes the dialog, this
// callback is called.
void HungRendererDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
DCHECK(g_instance == this);
switch (response_id) {
case kKillPagesButtonResponse:
// Kill the process.
if (contents_ && contents_->GetRenderProcessHost()) {
base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),
content::RESULT_CODE_HUNG, false);
}
break;
case GTK_RESPONSE_OK:
case GTK_RESPONSE_DELETE_EVENT:
// Start waiting again for responsiveness.
if (contents_ && contents_->render_view_host())
contents_->render_view_host()->RestartHangMonitorTimeout();
break;
default:
NOTREACHED();
}
gtk_widget_destroy(GTK_WIDGET(dialog_));
delete g_instance;
g_instance = NULL;
}
} // namespace
namespace browser {
void ShowHungRendererDialog(TabContents* contents) {
if (!logging::DialogsAreSuppressed()) {
if (!g_instance)
g_instance = new HungRendererDialogGtk();
g_instance->ShowForTabContents(contents);
}
}
void HideHungRendererDialog(TabContents* contents) {
if (!logging::DialogsAreSuppressed() && g_instance)
g_instance->EndForTabContents(contents);
}
} // namespace browser
<|endoftext|> |
<commit_before>#pragma once
#include <depthai-shared/common/EepromData.hpp>
#include <depthai-shared/common/optional.hpp>
#include <nlohmann/json.hpp>
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/datatype/RawStereoDepthConfig.hpp"
namespace dai {
/**
* Specify properties for StereoDepth
*/
struct StereoDepthProperties {
struct RectificationMesh {
/**
* Uri which points to the mesh array for 'left' input rectification
*/
std::string meshLeftUri;
/**
* Uri which points to the mesh array for 'right' input rectification
*/
std::string meshRightUri;
/**
* Mesh array size in bytes, for each of 'left' and 'right' (need to match)
*/
tl::optional<std::uint32_t> meshSize;
/**
* Distance between mesh points, in the horizontal direction
*/
uint16_t stepWidth = 16;
/**
* Distance between mesh points, in the vertical direction
*/
uint16_t stepHeight = 16;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RectificationMesh, meshLeftUri, meshRightUri, meshSize, stepWidth, stepHeight);
};
/// Initial stereo config
RawStereoDepthConfig initialConfig;
/// Whether to wait for config at 'inputConfig' IO
bool inputConfigSync = false;
using MedianFilter = dai::MedianFilter;
/**
* Align the disparity/depth to the perspective of a rectified output, or center it
*/
enum class DepthAlign : int32_t { RECTIFIED_RIGHT, RECTIFIED_LEFT, CENTER };
/**
* Set the disparity/depth alignment to the perspective of a rectified output, or center it
*/
DepthAlign depthAlign = DepthAlign::RECTIFIED_RIGHT;
/**
* Which camera to align disparity/depth to.
* When configured (not AUTO), takes precedence over 'depthAlign'
*/
CameraBoardSocket depthAlignCamera = CameraBoardSocket::AUTO;
bool enableRectification = true;
/**
* Disparity range increased from 96 to 192, combined from full resolution and downscaled images.
* Suitable for short range objects
*/
bool enableExtendedDisparity = false;
/**
* Fill color for missing data at frame edges: grayscale 0..255, or -1 to replicate pixels
*/
std::int32_t rectifyEdgeFillColor = -1;
/**
* Input frame width. Optional (taken from MonoCamera nodes if they exist)
*/
tl::optional<std::int32_t> width;
/**
* Input frame height. Optional (taken from MonoCamera nodes if they exist)
*/
tl::optional<std::int32_t> height;
/**
* Output disparity/depth width. Currently only used when aligning to RGB
*/
tl::optional<std::int32_t> outWidth;
/**
* Output disparity/depth height. Currently only used when aligning to RGB
*/
tl::optional<std::int32_t> outHeight;
/**
* Whether to keep aspect ratio of the input (rectified) or not
*/
bool outKeepAspectRatio = true;
/**
* Specify a direct warp mesh to be used for rectification,
* instead of intrinsics + extrinsic matrices
*/
RectificationMesh mesh;
/**
* Whether to enable switching stereo modes at runtime or not.
* E.g. standard to subpixel, standard+LR-check to subpixel + LR-check.
* Note: It will allocate resources for worst cases scenario,
* should be enabled only if dynamic mode switch is required.
* Default value: false.
*/
bool enableRuntimeStereoModeSwitch = false;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(StereoDepthProperties,
initialConfig,
inputConfigSync,
depthAlign,
depthAlignCamera,
enableRectification,
enableExtendedDisparity,
rectifyEdgeFillColor,
width,
height,
outWidth,
outHeight,
outKeepAspectRatio,
mesh,
enableRuntimeStereoModeSwitch);
} // namespace dai
<commit_msg>Add numFramePools to properties<commit_after>#pragma once
#include <depthai-shared/common/EepromData.hpp>
#include <depthai-shared/common/optional.hpp>
#include <nlohmann/json.hpp>
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/datatype/RawStereoDepthConfig.hpp"
namespace dai {
/**
* Specify properties for StereoDepth
*/
struct StereoDepthProperties {
struct RectificationMesh {
/**
* Uri which points to the mesh array for 'left' input rectification
*/
std::string meshLeftUri;
/**
* Uri which points to the mesh array for 'right' input rectification
*/
std::string meshRightUri;
/**
* Mesh array size in bytes, for each of 'left' and 'right' (need to match)
*/
tl::optional<std::uint32_t> meshSize;
/**
* Distance between mesh points, in the horizontal direction
*/
uint16_t stepWidth = 16;
/**
* Distance between mesh points, in the vertical direction
*/
uint16_t stepHeight = 16;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RectificationMesh, meshLeftUri, meshRightUri, meshSize, stepWidth, stepHeight);
};
/// Initial stereo config
RawStereoDepthConfig initialConfig;
/// Whether to wait for config at 'inputConfig' IO
bool inputConfigSync = false;
using MedianFilter = dai::MedianFilter;
/**
* Align the disparity/depth to the perspective of a rectified output, or center it
*/
enum class DepthAlign : int32_t { RECTIFIED_RIGHT, RECTIFIED_LEFT, CENTER };
/**
* Set the disparity/depth alignment to the perspective of a rectified output, or center it
*/
DepthAlign depthAlign = DepthAlign::RECTIFIED_RIGHT;
/**
* Which camera to align disparity/depth to.
* When configured (not AUTO), takes precedence over 'depthAlign'
*/
CameraBoardSocket depthAlignCamera = CameraBoardSocket::AUTO;
bool enableRectification = true;
/**
* Disparity range increased from 96 to 192, combined from full resolution and downscaled images.
* Suitable for short range objects
*/
bool enableExtendedDisparity = false;
/**
* Fill color for missing data at frame edges: grayscale 0..255, or -1 to replicate pixels
*/
std::int32_t rectifyEdgeFillColor = -1;
/**
* Input frame width. Optional (taken from MonoCamera nodes if they exist)
*/
tl::optional<std::int32_t> width;
/**
* Input frame height. Optional (taken from MonoCamera nodes if they exist)
*/
tl::optional<std::int32_t> height;
/**
* Output disparity/depth width. Currently only used when aligning to RGB
*/
tl::optional<std::int32_t> outWidth;
/**
* Output disparity/depth height. Currently only used when aligning to RGB
*/
tl::optional<std::int32_t> outHeight;
/**
* Whether to keep aspect ratio of the input (rectified) or not
*/
bool outKeepAspectRatio = true;
/**
* Specify a direct warp mesh to be used for rectification,
* instead of intrinsics + extrinsic matrices
*/
RectificationMesh mesh;
/**
* Whether to enable switching stereo modes at runtime or not.
* E.g. standard to subpixel, standard+LR-check to subpixel + LR-check.
* Note: It will allocate resources for worst cases scenario,
* should be enabled only if dynamic mode switch is required.
* Default value: false.
*/
bool enableRuntimeStereoModeSwitch = false;
/// Num frames in output pool
int numFramesPool = 3;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(StereoDepthProperties,
initialConfig,
inputConfigSync,
depthAlign,
depthAlignCamera,
enableRectification,
enableExtendedDisparity,
rectifyEdgeFillColor,
width,
height,
outWidth,
outHeight,
outKeepAspectRatio,
mesh,
enableRuntimeStereoModeSwitch,
numFramesPool);
} // namespace dai
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: %M%
Language: C++
Date: %D%
Version: %V%
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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 "vtkMCubesWriter.h"
#include "vtkByteSwap.h"
#include "vtkNormals.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkMCubesWriter* vtkMCubesWriter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMCubesWriter");
if(ret)
{
return (vtkMCubesWriter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkMCubesWriter;
}
// Create object.
vtkMCubesWriter::vtkMCubesWriter()
{
this->LimitsFileName = NULL;
}
vtkMCubesWriter::~vtkMCubesWriter()
{
if ( this->LimitsFileName )
{
delete [] this->LimitsFileName;
}
}
static void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys);
static void WriteLimits(FILE *fp, float *bounds);
// Write out data in MOVIE.BYU format.
void vtkMCubesWriter::WriteData()
{
vtkPoints *pts;
vtkNormals *normals;
vtkCellArray *polys;
vtkPolyData *input=this->GetInput();
polys = input->GetPolys();
pts = input->GetPoints();
if (pts == NULL || polys == NULL )
{
vtkErrorMacro(<<"No data to write!");
return;
}
normals = input->GetPointData()->GetNormals();
if (normals == NULL )
{
vtkErrorMacro(<<"No normals to write!: use vtkPolyDataNormals to generate them");
return;
}
if ( this->FileName == NULL)
{
vtkErrorMacro(<< "Please specify FileName to write");
return;
}
vtkDebugMacro("Writing MCubes tri file");
FILE *fp;
if ((fp = fopen(this->FileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open file: " << this->FileName);
return;
}
WriteMCubes (fp, pts, normals, polys);
fclose (fp);
if (this->LimitsFileName) {
vtkDebugMacro("Writing MCubes limits file");
if ((fp = fopen(this->LimitsFileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open file: " << this->LimitsFileName);
return;
}
WriteLimits (fp, input->GetBounds ());
fclose (fp);
}
}
void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys)
{
typedef struct {float x[3], n[3];} pointType;
pointType point;
int i;
int npts, *indx;
//
// Write out triangle polygons. In not a triangle polygon, create triangles.
//
for (polys->InitTraversal(); polys->GetNextCell(npts,indx); )
{
for (i=0; i < 3; i++)
{
pts->GetPoint(indx[i],&point.x[0]);
normals->GetNormal(indx[i],&point.n[0]);
vtkByteSwap::SwapWrite4BERange((float *) (&point),6,fp);
}
}
}
void WriteLimits(FILE *fp, float *bounds)
{
vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
}
void vtkMCubesWriter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataWriter::PrintSelf(os,indent);
os << indent << "Limits File Name: "
<< (this->LimitsFileName ? this->LimitsFileName : "(none)") << "\n";
}
<commit_msg>ENH:Minor formatting tweaks<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMCubesWriter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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 "vtkMCubesWriter.h"
#include "vtkByteSwap.h"
#include "vtkNormals.h"
#include "vtkObjectFactory.h"
//--------------------------------------------------------------------------
vtkMCubesWriter* vtkMCubesWriter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMCubesWriter");
if(ret)
{
return (vtkMCubesWriter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkMCubesWriter;
}
// Create object.
vtkMCubesWriter::vtkMCubesWriter()
{
this->LimitsFileName = NULL;
}
vtkMCubesWriter::~vtkMCubesWriter()
{
if ( this->LimitsFileName )
{
delete [] this->LimitsFileName;
}
}
static void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys);
static void WriteLimits(FILE *fp, float *bounds);
// Write out data in MOVIE.BYU format.
void vtkMCubesWriter::WriteData()
{
vtkPoints *pts;
vtkNormals *normals;
vtkCellArray *polys;
vtkPolyData *input=this->GetInput();
polys = input->GetPolys();
pts = input->GetPoints();
if (pts == NULL || polys == NULL )
{
vtkErrorMacro(<<"No data to write!");
return;
}
normals = input->GetPointData()->GetNormals();
if (normals == NULL )
{
vtkErrorMacro(<<"No normals to write!: use vtkPolyDataNormals to generate them");
return;
}
if ( this->FileName == NULL)
{
vtkErrorMacro(<< "Please specify FileName to write");
return;
}
vtkDebugMacro("Writing MCubes tri file");
FILE *fp;
if ((fp = fopen(this->FileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open file: " << this->FileName);
return;
}
WriteMCubes (fp, pts, normals, polys);
fclose (fp);
if (this->LimitsFileName)
{
vtkDebugMacro("Writing MCubes limits file");
if ((fp = fopen(this->LimitsFileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open file: " << this->LimitsFileName);
return;
}
WriteLimits (fp, input->GetBounds ());
fclose (fp);
}
}
void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys)
{
typedef struct {float x[3], n[3];} pointType;
pointType point;
int i;
int npts, *indx;
// Write out triangle polygons. In not a triangle polygon, create triangles.
//
for (polys->InitTraversal(); polys->GetNextCell(npts,indx); )
{
for (i=0; i < 3; i++)
{
pts->GetPoint(indx[i],&point.x[0]);
normals->GetNormal(indx[i],&point.n[0]);
vtkByteSwap::SwapWrite4BERange((float *) (&point),6,fp);
}
}
}
void WriteLimits(FILE *fp, float *bounds)
{
vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
}
void vtkMCubesWriter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataWriter::PrintSelf(os,indent);
os << indent << "Limits File Name: "
<< (this->LimitsFileName ? this->LimitsFileName : "(none)") << "\n";
}
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2017 Chris McArthur, prince.chrismc(at)gmail(dot)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 <string>
#include <iostream>
#include "GL/glew.h" // include GL Extension Wrangler
#include "glm/gtc/matrix_transform.hpp" //glm::lookAt
#include "CImg.h"
#include "GlfwWindow.h"
#include "Shader.h"
using cimg_library::CImg;
using cimg_library::CImgDisplay;
int main()
{
std::cout << "Welcome to Image Height Map Generator!" << std::endl;
// Create a GLFWwindow
GlfwWindow window("Image Height Map by Christopher McArthur", GlfwWindow::DEFAULT_WIDTH, GlfwWindow::DEFAULT_HEIGHT);
if (!window()) // Make sure it exists
{
return -1;
}
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Build and compile our shader program
VertexShader vertexShader("shaders/vertex.shader");
FragmentShader fragmentShader("shaders/fragment.shader");
// make sure they are ready to use
if (!vertexShader() || !fragmentShader())
{
return -1;
}
ShaderLinker* shaderProgram = &ShaderLinker::GetInstance();
if (!shaderProgram->Link(&vertexShader, &fragmentShader))
{
return -1;
}
// Constant vectors
const glm::vec3 center(0.0f, 0.0f, 0.0f);
const glm::vec3 up(0.0f, 0.0f, 1.0f);
const glm::vec3 eye(0.0f, -5.0f, 3.0f);
CImg<unsigned char> image("assets/depth.bmp"); // load the image
CImgDisplay display(image, "Image"); // create window displaying image
// Game loop
while (! ~window)
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.05f, 0.075f, 0.075f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glm::mat4 view_matrix;
view_matrix = glm::lookAt(eye, center, up);
shaderProgram->SetShaderMat4("view_matrix", view_matrix);
shaderProgram->SetShaderMat4("projection_matrix", window.GetProjectionMatrix());
++window; // swap buffers
}
return 0;
}
<commit_msg>now loading all the points and displaying them in gl window<commit_after>/*
MIT License
Copyright (c) 2017 Chris McArthur, prince.chrismc(at)gmail(dot)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 <string>
#include <iostream>
#include <vector>
#include "GL/glew.h" // include GL Extension Wrangler
#include "glm/gtc/matrix_transform.hpp" //glm::lookAt
#include "CImg.h"
#include "GlfwWindow.h"
#include "Shader.h"
using cimg_library::CImg;
using cimg_library::CImgDisplay;
enum class ObjectColors { RED, GREEN, BLUE, GREY, YELLOW, TEAL };
int main()
{
std::cout << "Welcome to Image Height Map Generator!" << std::endl;
// Create a GLFWwindow
GlfwWindow window("Image Height Map by Christopher McArthur", GlfwWindow::DEFAULT_WIDTH, GlfwWindow::DEFAULT_HEIGHT);
if (!window()) // Make sure it exists
{
return -1;
}
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Build and compile our shader program
VertexShader vertexShader("shaders/vertex.shader");
FragmentShader fragmentShader("shaders/fragment.shader");
if (!vertexShader() || !fragmentShader()) // make sure they are ready to use
{
return -1;
}
ShaderLinker* shaderProgram = &ShaderLinker::GetInstance();
if (!shaderProgram->Link(&vertexShader, &fragmentShader))
{
return -1;
}
// Constant vectors
const glm::vec3 center(0.0f, 0.0f, 0.0f);
const glm::vec3 up(0.0f, 1.0f, 0.0f);
const glm::vec3 eye(0.0f, 50.0f, -50.0f);
// ---------------------------------------------------------------------------------------------
std::cout << "Processing image....";
CImg<float> image("assets/depth.bmp"); // load the image
CImgDisplay display(image, "Image"); // create window displaying image
int x = (0 - image.width()/2), z = (0 - image.height() / 2);
std::vector<glm::vec3> verticies_all;
for (CImg<float>::iterator it = image.begin(); it < image.end(); ++it)
{
verticies_all.emplace_back(glm::vec3(x++, *it, z));
if(x == image.width()) {x = (0 - image.width() / 2); z += 1; }
}
std::cout << " Completed!" <<std::endl;
GLuint VAO_all_pts, VBO_all_pts;
glGenVertexArrays(1, &VAO_all_pts);
glBindVertexArray(VAO_all_pts);
glGenBuffers(1, &VBO_all_pts);
glBindBuffer(GL_ARRAY_BUFFER, VBO_all_pts);
glBufferData(GL_ARRAY_BUFFER, verticies_all.size() * sizeof(glm::vec3), &verticies_all.front(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// ---------------------------------------------------------------------------------------------
// Game loop
while (! ~window)
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.05f, 0.075f, 0.075f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glm::mat4 view_matrix;
view_matrix = glm::lookAt(eye, center, up);
shaderProgram->SetShaderMat4("view_matrix", view_matrix);
shaderProgram->SetShaderMat4("projection_matrix", window.GetProjectionMatrix());
glm::mat4 model_matrix = glm::scale(glm::mat4(), glm::vec3(0.05f));
shaderProgram->SetShaderMat4("model_matrix", model_matrix);
shaderProgram->SetShaderInt("object_color", (GLint)ObjectColors::GREY);
glBindVertexArray(VAO_all_pts);
glDrawArrays(GL_POINTS, 0, (GLsizei)verticies_all.size());
glBindVertexArray(0);
++window; // swap buffers
}
return 0;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkNavigationDataSequentialPlayer.h>
#include <mitkStandardFileLocations.h>
#include "mitkTestingMacros.h"
#include <mitkTestFixture.h>
#include "mitkNavigationDataReaderXML.h"
#include <iostream>
#include <sstream>
//foe exceptions
#include "mitkIGTException.h"
#include "mitkIGTIOException.h"
class mitkNavigationDataSequentialPlayerTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkNavigationDataSequentialPlayerTestSuite);
MITK_TEST(TestStandardWorkflow);
MITK_TEST(TestRestartWithNewNavigationDataSet);
MITK_TEST(TestSetFileNameException);
MITK_TEST(TestGoToSnapshotException);
MITK_TEST(TestSetXMLStringException);
MITK_TEST(TestDoubleUpdate);
CPPUNIT_TEST_SUITE_END();
private:
/** Members used inside the different test methods. All members are initialized via setUp().*/
vnl_vector<mitk::ScalarType> tTool0Snapshot1;
vnl_vector<mitk::ScalarType> tTool1Snapshot2;
mitk::Quaternion qTool0Snapshot0;
mitk::Quaternion qTool1Snapshot1;
mitk::NavigationDataSet::Pointer NavigationDataSet;
mitk::NavigationDataSequentialPlayer::Pointer player;
public:
void setUp(){
tTool0Snapshot1 = vnl_vector<mitk::ScalarType>(3);
tTool1Snapshot2 = vnl_vector<mitk::ScalarType>(3);
mitk::Quaternion qTool0Snapshot0;
mitk::Quaternion qTool1Snapshot1;
player = mitk::NavigationDataSequentialPlayer::New();
std::string file = GetTestDataFilePath("IGT-Data/NavigationDataTestData_2ToolsDouble.xml");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
NavigationDataSet =reader->Read(file);
}
void tearDown()
{
}
bool runLoop()
{
player->Update();
mitk::NavigationData::Pointer nd0;
mitk::NavigationData::Pointer nd1;
for(unsigned int i=0; i<player->GetNumberOfSnapshots(); ++i)
{
nd0 = player->GetOutput(0);
nd1 = player->GetOutput(1);
// test some values
if(nd0.IsNull() || nd1.IsNull()) return false;
if(i==0)
{
mitk::NavigationData::Pointer ref0 = NavigationDataSet->GetNavigationDataForIndex(0,0);
mitk::NavigationData::Pointer ref1 = NavigationDataSet->GetNavigationDataForIndex(1,0);
if (!(ref0->GetOrientation().as_vector() == nd0->GetOrientation().as_vector())) {return false;}
if (!(ref1->GetOrientation().as_vector() == nd1->GetOrientation().as_vector())) {return false;}
if (!(ref0->GetPosition().GetVnlVector() == nd0->GetPosition().GetVnlVector())) {return false;}
if (!(ref1->GetPosition().GetVnlVector() == nd1->GetPosition().GetVnlVector())) {return false;}
}
else if(i==1)
{
if (!(tTool0Snapshot1 == nd0->GetPosition().GetVnlVector())) {return false;}
else if (!(qTool1Snapshot1.as_vector() == nd1->GetOrientation().as_vector())) {return false;}
}
else if(i==2) // should be repeated
{
if (!(tTool1Snapshot2 == nd1->GetPosition().GetVnlVector())) {return false;}
}
// Goto next Snapshot
player->GoToNextSnapshot();
player->Update();
}
return true;
}
void TestStandardWorkflow()
{
// create test values valid for the xml data above
tTool0Snapshot1[0] = -336.65;
tTool0Snapshot1[1] = 138.5;
tTool0Snapshot1[2]= -2061.07;
tTool1Snapshot2[0] = -56.93;
tTool1Snapshot2[1] = 233.79;
tTool1Snapshot2[2]= -2042.6;
vnl_vector_fixed<mitk::ScalarType,4> qVec;
qVec[0] = 0.0085;
qVec[1] = -0.0576;
qVec[2]= -0.0022;
qVec[3]= 0.9982;
qTool0Snapshot0 = mitk::Quaternion(qVec);
qVec[0] = 0.4683;
qVec[1] = 0.0188;
qVec[2]= -0.8805;
qVec[3]= 0.0696;
qTool1Snapshot1 = mitk::Quaternion(qVec);
//test SetXMLString()
player->SetNavigationDataSet(NavigationDataSet);
MITK_TEST_CONDITION(player->GetNumberOfSnapshots() == 3,"Testing method SetXMLString with 3 navigation datas.");
MITK_TEST_CONDITION(player->GetNumberOfIndexedOutputs() == 2,"Testing number of outputs");
//rest repeat
player->SetRepeat(true);
MITK_TEST_CONDITION(runLoop(),"Testing first run.");
MITK_TEST_CONDITION(runLoop(),"Testing second run."); //repeat is on should work a second time
// now test the go to snapshot function
player->GoToSnapshot(2);
mitk::NavigationData::Pointer nd1 = player->GetOutput(1);
MITK_TEST_CONDITION(tTool1Snapshot2 == nd1->GetPosition().GetVnlVector(),
"Testing GoToSnapshot() [1]");
MITK_TEST_OUTPUT( << tTool1Snapshot2 << "\t" << nd1->GetPosition().GetVnlVector());
player->GoToSnapshot(0);
mitk::NavigationData::Pointer nd0 = player->GetOutput();
MITK_TEST_CONDITION(qTool0Snapshot0.as_vector() == nd0->GetOrientation().as_vector(),
"Testing GoToSnapshot() [2]");
MITK_TEST_OUTPUT( << qTool0Snapshot0.as_vector() << "\t" <<nd0->GetOrientation().as_vector() );
player->GoToSnapshot(2);
// and a third time
MITK_TEST_CONDITION(runLoop(),"Tested if repeat works again.");
}
void TestRestartWithNewNavigationDataSet()
{
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
mitk::NavigationDataSequentialPlayer::Pointer player(mitk::NavigationDataSequentialPlayer::New());
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData_2ToolsDouble.xml", "Modules/IGT/Testing/Data");
player->SetNavigationDataSet(reader->Read(file));
mitk::NavigationData::PositionType nd1 = player->GetOutput(0)->GetPosition();
player->SetNavigationDataSet(reader->Read(file));
player->Update();
mitk::NavigationData::PositionType nd2 = player->GetOutput(0)->GetPosition();
MITK_TEST_CONDITION(nd1 == nd2, "First output must be the same after setting same navigation data again.");
// setting new NavigationDataSet with different tool count should result in an exception
file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");
MITK_TEST_FOR_EXCEPTION(mitk::IGTException, player->SetNavigationDataSet(reader->Read(file)));
}
void TestSetFileNameException()
{ //testing exception if file name hasnt been set
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer = mitk::NavigationDataSequentialPlayer::New();
bool exceptionThrown=false;
try
{
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer->SetNavigationDataSet(reader->Read(""));
}
catch(mitk::IGTIOException)
{
exceptionThrown=true;
MITK_TEST_OUTPUT(<<"Tested exception for the case when file version is wrong in SetFileName. Application should not crash.");
}
MITK_TEST_CONDITION(exceptionThrown, "Testing SetFileName method if exception (if file name hasnt been set) was thrown.");
//testing ReInItXML method if data element is not found
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer1 = mitk::NavigationDataSequentialPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestDataInvalidTags.xml", "Modules/IGT/Testing/Data");
bool exceptionThrown1=false;
try
{
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer1->SetNavigationDataSet(reader->Read(file));
}
catch(mitk::IGTException)
{
exceptionThrown1=true;
}
MITK_TEST_CONDITION(exceptionThrown1, "Testing SetFileName method if exception (if data element not found) was thrown.");
}
void TestGoToSnapshotException()
{
//testing GoToSnapShot for exception
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer2 = mitk::NavigationDataSequentialPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData_2Tools.xml", "Modules/IGT/Testing/Data");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer2->SetNavigationDataSet(reader->Read(file));
bool exceptionThrown2=false;
try
{
unsigned int invalidSnapshot = 1000;
myTestPlayer2->GoToSnapshot(invalidSnapshot);
}
catch(mitk::IGTException)
{
exceptionThrown2=true;
}
MITK_TEST_CONDITION(exceptionThrown2, "Testing if exception is thrown when GoToSnapShot method is called with an index that doesn't exist.");
}
void TestSetXMLStringException()
{
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer3 = mitk::NavigationDataSequentialPlayer::New();
bool exceptionThrown3=false;
//The string above XML_INVALID_TESTSTRING is a wrong string, some element were deleted in above
try
{
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidVersionNavigationDataTestData.xml", "Modules/IGT/Testing/Data");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer3->SetNavigationDataSet(reader->Read(file));
}
catch(mitk::IGTIOException)
{
exceptionThrown3=true;
}
MITK_TEST_CONDITION(exceptionThrown3, "Testing SetXMLString method with an invalid XML string.");
}
void TestDoubleUpdate()
{
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData_2Tools.xml", "Modules/IGT/Testing/Data");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
player->SetNavigationDataSet(reader->Read(file));
player->Update();
mitk::Quaternion nd1Orientation = player->GetOutput()->GetOrientation();
player->Update();
mitk::Quaternion nd2Orientation = player->GetOutput()->GetOrientation();
MITK_TEST_CONDITION(nd1Orientation.as_vector() == nd2Orientation.as_vector(), "Output must be the same no matter if Update() was called between.");
MITK_TEST_CONDITION(player->GoToNextSnapshot(), "There must be a next snapshot available.");
player->Update();
mitk::Quaternion nd3Orientation = player->GetOutput()->GetOrientation();
MITK_TEST_CONDITION(nd1Orientation.as_vector() != nd3Orientation.as_vector(), "Output must be different if GoToNextSnapshot() was called between.");
}
};
MITK_TEST_SUITE_REGISTRATION(mitkNavigationDataSequentialPlayer)<commit_msg>SequentialDataPlayerTest now correctly tests order of retrieved navigation Datas<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkNavigationDataSequentialPlayer.h>
#include <mitkStandardFileLocations.h>
#include "mitkTestingMacros.h"
#include <mitkTestFixture.h>
#include "mitkNavigationDataReaderXML.h"
#include <iostream>
#include <sstream>
//foe exceptions
#include "mitkIGTException.h"
#include "mitkIGTIOException.h"
class mitkNavigationDataSequentialPlayerTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkNavigationDataSequentialPlayerTestSuite);
MITK_TEST(TestStandardWorkflow);
MITK_TEST(TestRestartWithNewNavigationDataSet);
MITK_TEST(TestSetFileNameException);
MITK_TEST(TestGoToSnapshotException);
MITK_TEST(TestSetXMLStringException);
MITK_TEST(TestDoubleUpdate);
CPPUNIT_TEST_SUITE_END();
private:
/** Members used inside the different test methods. All members are initialized via setUp().*/
vnl_vector<mitk::ScalarType> tTool0Snapshot1;
vnl_vector<mitk::ScalarType> tTool1Snapshot2;
mitk::Quaternion qTool0Snapshot0;
mitk::Quaternion qTool1Snapshot1;
mitk::NavigationDataSet::Pointer NavigationDataSet;
mitk::NavigationDataSequentialPlayer::Pointer player;
public:
void setUp(){
tTool0Snapshot1 = vnl_vector<mitk::ScalarType>(3);
tTool1Snapshot2 = vnl_vector<mitk::ScalarType>(3);
mitk::Quaternion qTool0Snapshot0;
mitk::Quaternion qTool1Snapshot1;
player = mitk::NavigationDataSequentialPlayer::New();
std::string file = GetTestDataFilePath("IGT-Data/NavigationDataTestData_2ToolsDouble.xml");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
NavigationDataSet =reader->Read(file);
}
void tearDown()
{
}
bool runLoop()
{
player->Update();
mitk::NavigationData::Pointer nd0;
mitk::NavigationData::Pointer nd1;
for(unsigned int i=0; i<player->GetNumberOfSnapshots(); ++i)
{
nd0 = player->GetOutput(0);
nd1 = player->GetOutput(1);
// test some values
if(nd0.IsNull() || nd1.IsNull()) return false;
if(i==0)
{
mitk::NavigationData::Pointer ref0 = NavigationDataSet->GetNavigationDataForIndex(0,0);
mitk::NavigationData::Pointer ref1 = NavigationDataSet->GetNavigationDataForIndex(0,1);
if (!(ref0->GetOrientation().as_vector() == nd0->GetOrientation().as_vector())) {return false;}
if (!(ref1->GetOrientation().as_vector() == nd1->GetOrientation().as_vector())) {return false;}
if (!(ref0->GetPosition().GetVnlVector() == nd0->GetPosition().GetVnlVector())) {return false;}
if (!(ref1->GetPosition().GetVnlVector() == nd1->GetPosition().GetVnlVector())) {return false;}
}
else if(i==1)
{
mitk::NavigationData::Pointer ref0 = NavigationDataSet->GetNavigationDataForIndex(1,0);
mitk::NavigationData::Pointer ref1 = NavigationDataSet->GetNavigationDataForIndex(1,1);
if (!(ref0->GetOrientation().as_vector() == nd0->GetOrientation().as_vector())) {return false;}
if (!(ref1->GetOrientation().as_vector() == nd1->GetOrientation().as_vector())) {return false;}
if (!(ref0->GetPosition().GetVnlVector() == nd0->GetPosition().GetVnlVector())) {return false;}
if (!(ref1->GetPosition().GetVnlVector() == nd1->GetPosition().GetVnlVector())) {return false;}
}
else if(i==2) // should be repeated
{
mitk::NavigationData::Pointer ref0 = NavigationDataSet->GetNavigationDataForIndex(2,0);
mitk::NavigationData::Pointer ref1 = NavigationDataSet->GetNavigationDataForIndex(2,1);
if (!(ref0->GetOrientation().as_vector() == nd0->GetOrientation().as_vector())) {return false;}
if (!(ref1->GetOrientation().as_vector() == nd1->GetOrientation().as_vector())) {return false;}
if (!(ref0->GetPosition().GetVnlVector() == nd0->GetPosition().GetVnlVector())) {return false;}
if (!(ref1->GetPosition().GetVnlVector() == nd1->GetPosition().GetVnlVector())) {return false;}
}
// Goto next Snapshot
player->GoToNextSnapshot();
player->Update();
}
return true;
}
void TestStandardWorkflow()
{
// create test values valid for the xml data above
tTool0Snapshot1[0] = -336.65;
tTool0Snapshot1[1] = 138.5;
tTool0Snapshot1[2]= -2061.07;
tTool1Snapshot2[0] = -56.93;
tTool1Snapshot2[1] = 233.79;
tTool1Snapshot2[2]= -2042.6;
vnl_vector_fixed<mitk::ScalarType,4> qVec;
qVec[0] = 0.0085;
qVec[1] = -0.0576;
qVec[2]= -0.0022;
qVec[3]= 0.9982;
qTool0Snapshot0 = mitk::Quaternion(qVec);
qVec[0] = 0.4683;
qVec[1] = 0.0188;
qVec[2]= -0.8805;
qVec[3]= 0.0696;
qTool1Snapshot1 = mitk::Quaternion(qVec);
//test SetXMLString()
player->SetNavigationDataSet(NavigationDataSet);
MITK_TEST_CONDITION(player->GetNumberOfSnapshots() == 3,"Testing method SetXMLString with 3 navigation datas.");
MITK_TEST_CONDITION(player->GetNumberOfIndexedOutputs() == 2,"Testing number of outputs");
//rest repeat
player->SetRepeat(true);
MITK_TEST_CONDITION(runLoop(),"Testing first run.");
MITK_TEST_CONDITION(runLoop(),"Testing second run."); //repeat is on should work a second time
// now test the go to snapshot function
player->GoToSnapshot(2);
mitk::NavigationData::Pointer nd1 = player->GetOutput(1);
MITK_TEST_CONDITION(tTool1Snapshot2 == nd1->GetPosition().GetVnlVector(),
"Testing GoToSnapshot() [1]");
MITK_TEST_OUTPUT( << tTool1Snapshot2 << "\t" << nd1->GetPosition().GetVnlVector());
player->GoToSnapshot(0);
mitk::NavigationData::Pointer nd0 = player->GetOutput();
MITK_TEST_CONDITION(qTool0Snapshot0.as_vector() == nd0->GetOrientation().as_vector(),
"Testing GoToSnapshot() [2]");
MITK_TEST_OUTPUT( << qTool0Snapshot0.as_vector() << "\t" <<nd0->GetOrientation().as_vector() );
player->GoToSnapshot(2);
// and a third time
MITK_TEST_CONDITION(runLoop(),"Tested if repeat works again.");
}
void TestRestartWithNewNavigationDataSet()
{
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
mitk::NavigationDataSequentialPlayer::Pointer player(mitk::NavigationDataSequentialPlayer::New());
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData_2ToolsDouble.xml", "Modules/IGT/Testing/Data");
player->SetNavigationDataSet(reader->Read(file));
mitk::NavigationData::PositionType nd1 = player->GetOutput(0)->GetPosition();
player->SetNavigationDataSet(reader->Read(file));
player->Update();
mitk::NavigationData::PositionType nd2 = player->GetOutput(0)->GetPosition();
MITK_TEST_CONDITION(nd1 == nd2, "First output must be the same after setting same navigation data again.");
// setting new NavigationDataSet with different tool count should result in an exception
file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");
MITK_TEST_FOR_EXCEPTION(mitk::IGTException, player->SetNavigationDataSet(reader->Read(file)));
}
void TestSetFileNameException()
{ //testing exception if file name hasnt been set
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer = mitk::NavigationDataSequentialPlayer::New();
bool exceptionThrown=false;
try
{
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer->SetNavigationDataSet(reader->Read(""));
}
catch(mitk::IGTIOException)
{
exceptionThrown=true;
MITK_TEST_OUTPUT(<<"Tested exception for the case when file version is wrong in SetFileName. Application should not crash.");
}
MITK_TEST_CONDITION(exceptionThrown, "Testing SetFileName method if exception (if file name hasnt been set) was thrown.");
//testing ReInItXML method if data element is not found
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer1 = mitk::NavigationDataSequentialPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestDataInvalidTags.xml", "Modules/IGT/Testing/Data");
bool exceptionThrown1=false;
try
{
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer1->SetNavigationDataSet(reader->Read(file));
}
catch(mitk::IGTException)
{
exceptionThrown1=true;
}
MITK_TEST_CONDITION(exceptionThrown1, "Testing SetFileName method if exception (if data element not found) was thrown.");
}
void TestGoToSnapshotException()
{
//testing GoToSnapShot for exception
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer2 = mitk::NavigationDataSequentialPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData_2Tools.xml", "Modules/IGT/Testing/Data");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer2->SetNavigationDataSet(reader->Read(file));
bool exceptionThrown2=false;
try
{
unsigned int invalidSnapshot = 1000;
myTestPlayer2->GoToSnapshot(invalidSnapshot);
}
catch(mitk::IGTException)
{
exceptionThrown2=true;
}
MITK_TEST_CONDITION(exceptionThrown2, "Testing if exception is thrown when GoToSnapShot method is called with an index that doesn't exist.");
}
void TestSetXMLStringException()
{
mitk::NavigationDataSequentialPlayer::Pointer myTestPlayer3 = mitk::NavigationDataSequentialPlayer::New();
bool exceptionThrown3=false;
//The string above XML_INVALID_TESTSTRING is a wrong string, some element were deleted in above
try
{
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidVersionNavigationDataTestData.xml", "Modules/IGT/Testing/Data");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
myTestPlayer3->SetNavigationDataSet(reader->Read(file));
}
catch(mitk::IGTIOException)
{
exceptionThrown3=true;
}
MITK_TEST_CONDITION(exceptionThrown3, "Testing SetXMLString method with an invalid XML string.");
}
void TestDoubleUpdate()
{
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData_2Tools.xml", "Modules/IGT/Testing/Data");
mitk::NavigationDataReaderXML::Pointer reader = mitk::NavigationDataReaderXML::New();
player->SetNavigationDataSet(reader->Read(file));
player->Update();
mitk::Quaternion nd1Orientation = player->GetOutput()->GetOrientation();
player->Update();
mitk::Quaternion nd2Orientation = player->GetOutput()->GetOrientation();
MITK_TEST_CONDITION(nd1Orientation.as_vector() == nd2Orientation.as_vector(), "Output must be the same no matter if Update() was called between.");
MITK_TEST_CONDITION(player->GoToNextSnapshot(), "There must be a next snapshot available.");
player->Update();
mitk::Quaternion nd3Orientation = player->GetOutput()->GetOrientation();
MITK_TEST_CONDITION(nd1Orientation.as_vector() != nd3Orientation.as_vector(), "Output must be different if GoToNextSnapshot() was called between.");
}
};
MITK_TEST_SUITE_REGISTRATION(mitkNavigationDataSequentialPlayer)<|endoftext|> |
<commit_before>//====================================================================================================================//
// File: qcan_socket.cpp //
// Description: CAN socket class //
// //
// Copyright (C) MicroControl GmbH & Co. KG //
// 53844 Troisdorf - Germany //
// www.microcontrol.net //
// //
//--------------------------------------------------------------------------------------------------------------------//
// 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, the following //
// disclaimer and the referenced file 'LICENSE'. //
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the //
// following disclaimer in the documentation and/or other materials provided with the distribution. //
// 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products //
// derived from this software without specific prior written permission. //
// //
// 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 files **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
#include "qcan_socket.hpp"
#include <QtCore/QDebug>
#include <QtNetwork/QNetworkInterface>
/*--------------------------------------------------------------------------------------------------------------------*\
** Definitions **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------*\
** Class methods **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket() //
// //
//--------------------------------------------------------------------------------------------------------------------//
QCanSocket::QCanSocket(QObject * pclParentV)
{
if (pclParentV != Q_NULLPTR)
{
this->setParent(pclParentV);
}
//---------------------------------------------------------------------------------------------------
// set default values for host address and port
//
clServerHostAddrP = QHostAddress(QHostAddress::LocalHost);
uwServerPortP = QCAN_WEB_SOCKET_DEFAULT_PORT;
//---------------------------------------------------------------------------------------------------
// create a local and a WebSocket by default, the selection which one is used will be done in
// setHostAddress().
//
pclLocalSocketP = new QLocalSocket(this);
pclWebSocketP = new QWebSocket("", QWebSocketProtocol::VersionLatest, this);
//---------------------------------------------------------------------------------------------------
// the socket is not connected yet and the default connection method is "local"
//
btIsLocalConnectionP = true;
btIsConnectedP = false;
//---------------------------------------------------------------------------------------------------
// No socket errors available yet
//
slSocketErrorP = 0;
clUuidP = QUuid::createUuid();
teCanStateP = eCAN_STATE_BUS_ACTIVE;
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket() //
// destructor //
//--------------------------------------------------------------------------------------------------------------------//
QCanSocket::~QCanSocket()
{
delete (pclLocalSocketP);
delete (pclWebSocketP);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::connectNetwork() //
// //
//--------------------------------------------------------------------------------------------------------------------//
bool QCanSocket::connectNetwork(const CAN_Channel_e & teChannelR)
{
bool btResultT = false;
//---------------------------------------------------------------------------------------------------
// create a new socket
//
if (btIsConnectedP == false)
{
if (btIsLocalConnectionP == false)
{
qDebug() << "QCanSocket::connectNetwork(" << teChannelR << "- WebSocket";
//----------------------------------------------------------------------------------------
// create new WebSocket
//
pclWebSocketP->abort();
QString clSocketUrlT = QString("ws://") + clServerHostAddrP.toString() + QString(":%1").arg(uwServerPortP);
clSocketUrlT += QString("/%1").arg(teChannelR);
qDebug() << "QCanSocket::connectNetwork(" << teChannelR << ") -" << clSocketUrlT;
pclWebSocketP->open(clSocketUrlT);
//----------------------------------------------------------------------------------------
// make signal / slot connection for WebSocket
//
connect( pclWebSocketP, &QWebSocket::connected, this, &QCanSocket::onSocketConnect);
connect( pclWebSocketP, &QWebSocket::disconnected, this, &QCanSocket::onSocketDisconnect);
connect( pclWebSocketP, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
this, &QCanSocket::onSocketErrorWeb);
connect( pclWebSocketP, &QWebSocket::binaryMessageReceived, this, &QCanSocket::onSocketReceiveWeb);
btResultT = true;
}
else
{
qDebug() << "QCanSocket::connectNetwork(" << teChannelR << ") - LocalSocket";
//----------------------------------------------------------------------------------------
// create new local socket
//
pclLocalSocketP->abort();
//----------------------------------------------------------------------------------------
// make signal / slot connection for local socket
//
connect( pclLocalSocketP, &QLocalSocket::connected, this, &QCanSocket::onSocketConnect);
connect( pclLocalSocketP, &QLocalSocket::disconnected, this, &QCanSocket::onSocketDisconnect);
connect( pclLocalSocketP, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
this, &QCanSocket::onSocketErrorLocal);
connect( pclLocalSocketP, &QLocalSocket::readyRead, this, &QCanSocket::onSocketReceiveLocal);
//----------------------------------------------------------------------------------------
// connect to local server
//
pclLocalSocketP->connectToServer(QString("CANpieServerChannel%1").arg(teChannelR));
qDebug() << "QCanSocket::connectNetwork() -" << pclLocalSocketP->fullServerName();
btResultT = true;
}
}
return(btResultT);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::disconnectNetwork() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::disconnectNetwork(void)
{
qDebug() << "QCanSocket::disconnectNetwork() ";
if (btIsLocalConnectionP == false)
{
pclWebSocketP->disconnect();
}
else
{
disconnect(pclLocalSocketP, 0, 0, 0);
pclLocalSocketP->disconnectFromServer();
}
btIsConnectedP = false;
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::error() //
// //
//--------------------------------------------------------------------------------------------------------------------//
QAbstractSocket::SocketError QCanSocket::error() const
{
return((QAbstractSocket::SocketError) slSocketErrorP);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::errorString() //
// //
//--------------------------------------------------------------------------------------------------------------------//
QString QCanSocket::errorString() const
{
QString clErrorT;
switch (slSocketErrorP)
{
case QAbstractSocket::ConnectionRefusedError:
clErrorT = qPrintable(tr("connection refused or timed out.") );
break;
case QAbstractSocket::RemoteHostClosedError:
clErrorT = qPrintable(tr("server closed the connection.") );
break;
case QAbstractSocket::HostNotFoundError:
clErrorT = qPrintable(tr("server address was not found.") );
break;
case QAbstractSocket::SocketAccessError:
clErrorT = qPrintable(tr("application lacked the required privileges.") );
break;
case QAbstractSocket::SocketResourceError:
clErrorT = qPrintable(tr("local system ran out of resources.") );
break;
case QAbstractSocket::SocketTimeoutError:
clErrorT = qPrintable(tr("operation timed out.") );
break;
case QAbstractSocket::NetworkError:
clErrorT = qPrintable(tr("error occurred with the network (e.g. cable plugged out.") );
break;
case QAbstractSocket::AddressInUseError:
clErrorT = qPrintable(tr("address is already in use.") );
break;
default:
clErrorT = qPrintable(tr("unknown reason") );
break;
}
return (clErrorT);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::framesAvailable() //
// //
//--------------------------------------------------------------------------------------------------------------------//
int32_t QCanSocket::framesAvailable(void) const
{
return (clReceiveFifoP.size());
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketConnect() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketConnect(void)
{
qDebug() << "QCanSocket::onSocketConnect() ";
//---------------------------------------------------------------------------------------------------
// send signal about connection state and keep it in local variable
//
btIsConnectedP = true;
emit connected();
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketDisconnect() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketDisconnect(void)
{
qDebug() << "QCanSocket::onSocketDisconnect() ";
//---------------------------------------------------------------------------------------------------
// send signal about connection state and keep it in local variable
//
btIsConnectedP = false;
emit disconnected();
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketErrorLocal() //
// handle error conditions of local socket //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketErrorLocal(QLocalSocket::LocalSocketError teSocketErrorV)
{
qDebug() << "QCanSocket::onSocketErrorLocal() " << teSocketErrorV;
qDebug() << pclLocalSocketP->errorString();
switch(teSocketErrorV)
{
//-------------------------------------------------------------------------------------------
// abort all operations and disconnect socket
//
case QLocalSocket::PeerClosedError:
case QLocalSocket::ConnectionError:
pclLocalSocketP->abort();
btIsConnectedP = false;
emit disconnected();
break;
default:
break;
}
//---------------------------------------------------------------------------------------------------
// Store socket error and send signal:
// Since the enumeration values for LocalSocketError are derived from QAbstractSocket::SocketError
// inside the header file QtNetwork/qlocalsocket.h we can simply cast it.
//
slSocketErrorP = teSocketErrorV;
emit error( (QAbstractSocket::SocketError) teSocketErrorV);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketErrorWeb() //
// handle error conditions of WebSocket //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketErrorWeb(QAbstractSocket::SocketError teSocketErrorV)
{
qDebug() << "QCanSocket::onSocketErrorWeb() -" << teSocketErrorV;
switch(teSocketErrorV)
{
//-------------------------------------------------------------
// abort all operations and disconnect socket
//
case QAbstractSocket::RemoteHostClosedError:
case QAbstractSocket::NetworkError:
pclWebSocketP->abort();
btIsConnectedP = false;
emit disconnected();
break;
default:
break;
}
//----------------------------------------------------------------
// store socket error and send signal
//
slSocketErrorP = teSocketErrorV;
emit error(teSocketErrorV);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketReceiveLocal() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketReceiveLocal(void)
{
uint32_t ulFrameCountT;
bool btValidFrameT = false;
bool btSignalNewFrameT = false;
ulFrameCountT = pclLocalSocketP->bytesAvailable() / QCAN_FRAME_ARRAY_SIZE;
while (ulFrameCountT)
{
clReceiveDataP = pclLocalSocketP->read(QCAN_FRAME_ARRAY_SIZE);
btValidFrameT = clReceiveFrameP.fromByteArray(clReceiveDataP);
if (btValidFrameT)
{
//-----------------------------------------------------------------------------------
// Store frame in FIFO
//
clReceiveMutexP.lock();
clReceiveFifoP.enqueue(clReceiveFrameP);
btSignalNewFrameT = true;
clReceiveMutexP.unlock();
//-----------------------------------------------------------------------------------
// If the frame type is an error frame, store the for the actual CAN state
//
if (clReceiveFrameP.frameType() == QCanFrame::eFRAME_TYPE_ERROR)
{
teCanStateP = clReceiveFrameP.errorState();
}
}
ulFrameCountT--;
}
//---------------------------------------------------------------------------------------------------
// Emit signal only once when new data arrived. The flag 'btReceiveSignalSendP' is cleared inside
// the read() method.
//
if (btSignalNewFrameT == true)
{
emit readyRead();
}
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketReceiveWeb() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketReceiveWeb(const QByteArray &clMessageR)
{
bool btValidFrameT = false;
bool btSignalNewFrameT = false;
btValidFrameT = clReceiveFrameP.fromByteArray(clMessageR);
if (btValidFrameT)
{
//-----------------------------------------------------------------------------------
// Store frame in FIFO
//
clReceiveMutexP.lock();
clReceiveFifoP.enqueue(clReceiveFrameP);
btSignalNewFrameT = true;
clReceiveMutexP.unlock();
//-----------------------------------------------------------------------------------
// If the frame type is an error frame, store the for the actual CAN state
//
if (clReceiveFrameP.frameType() == QCanFrame::eFRAME_TYPE_ERROR)
{
teCanStateP = clReceiveFrameP.errorState();
}
}
//---------------------------------------------------------------------------------------------------
// Emit signal only once when new data arrived. The flag 'btReceiveSignalSendP' is cleared inside
// the read() method.
//
if (btSignalNewFrameT == true)
{
emit readyRead();
}
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::read() //
// //
//--------------------------------------------------------------------------------------------------------------------//
bool QCanSocket::read(QCanFrame & clFrameR)
{
bool btResultT = false;
clReceiveMutexP.lock();
if (clReceiveFifoP.size() > 0)
{
clFrameR = clReceiveFifoP.dequeue(); // read message from queue
btResultT = true; // message has been updated
}
clReceiveMutexP.unlock();
return (btResultT);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::setHostAddress() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::setHostAddress(QHostAddress clHostAddressV, uint16_t uwPortV)
{
if(btIsConnectedP == false)
{
clServerHostAddrP = clHostAddressV;
uwServerPortP = uwPortV;
if (clHostAddressV == QHostAddress::LocalHost)
{
btIsLocalConnectionP = true;
}
else
{
btIsLocalConnectionP = false;
}
}
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::write() //
// //
//--------------------------------------------------------------------------------------------------------------------//
bool QCanSocket::write(const QCanFrame & clFrameR)
{
bool btResultT = false;
if (btIsConnectedP == true)
{
QByteArray clDatagramT = clFrameR.toByteArray();
if (btIsLocalConnectionP == false)
{
if (pclWebSocketP->sendBinaryMessage(clDatagramT) == QCAN_FRAME_ARRAY_SIZE)
{
pclWebSocketP->flush();
btResultT = true;
}
}
else
{
if (pclLocalSocketP->write(clDatagramT) == QCAN_FRAME_ARRAY_SIZE)
{
pclLocalSocketP->flush();
btResultT = true;
}
}
}
return(btResultT);
}
<commit_msg>Fix error string<commit_after>//====================================================================================================================//
// File: qcan_socket.cpp //
// Description: CAN socket class //
// //
// Copyright (C) MicroControl GmbH & Co. KG //
// 53844 Troisdorf - Germany //
// www.microcontrol.net //
// //
//--------------------------------------------------------------------------------------------------------------------//
// 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, the following //
// disclaimer and the referenced file 'LICENSE'. //
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the //
// following disclaimer in the documentation and/or other materials provided with the distribution. //
// 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products //
// derived from this software without specific prior written permission. //
// //
// 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 files **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
#include "qcan_socket.hpp"
#include <QtCore/QDebug>
#include <QtNetwork/QNetworkInterface>
/*--------------------------------------------------------------------------------------------------------------------*\
** Definitions **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------*\
** Class methods **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket() //
// //
//--------------------------------------------------------------------------------------------------------------------//
QCanSocket::QCanSocket(QObject * pclParentV)
{
if (pclParentV != Q_NULLPTR)
{
this->setParent(pclParentV);
}
//---------------------------------------------------------------------------------------------------
// set default values for host address and port
//
clServerHostAddrP = QHostAddress(QHostAddress::LocalHost);
uwServerPortP = QCAN_WEB_SOCKET_DEFAULT_PORT;
//---------------------------------------------------------------------------------------------------
// create a local and a WebSocket by default, the selection which one is used will be done in
// setHostAddress().
//
pclLocalSocketP = new QLocalSocket(this);
pclWebSocketP = new QWebSocket("", QWebSocketProtocol::VersionLatest, this);
//---------------------------------------------------------------------------------------------------
// the socket is not connected yet and the default connection method is "local"
//
btIsLocalConnectionP = true;
btIsConnectedP = false;
//---------------------------------------------------------------------------------------------------
// No socket errors available yet
//
slSocketErrorP = 0;
clUuidP = QUuid::createUuid();
teCanStateP = eCAN_STATE_BUS_ACTIVE;
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket() //
// destructor //
//--------------------------------------------------------------------------------------------------------------------//
QCanSocket::~QCanSocket()
{
delete (pclLocalSocketP);
delete (pclWebSocketP);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::connectNetwork() //
// //
//--------------------------------------------------------------------------------------------------------------------//
bool QCanSocket::connectNetwork(const CAN_Channel_e & teChannelR)
{
bool btResultT = false;
//---------------------------------------------------------------------------------------------------
// create a new socket
//
if (btIsConnectedP == false)
{
if (btIsLocalConnectionP == false)
{
qDebug() << "QCanSocket::connectNetwork(" << teChannelR << "- WebSocket";
//----------------------------------------------------------------------------------------
// create new WebSocket
//
pclWebSocketP->abort();
QString clSocketUrlT = QString("ws://") + clServerHostAddrP.toString() + QString(":%1").arg(uwServerPortP);
clSocketUrlT += QString("/%1").arg(teChannelR);
qDebug() << "QCanSocket::connectNetwork(" << teChannelR << ") -" << clSocketUrlT;
pclWebSocketP->open(clSocketUrlT);
//----------------------------------------------------------------------------------------
// make signal / slot connection for WebSocket
//
connect( pclWebSocketP, &QWebSocket::connected, this, &QCanSocket::onSocketConnect);
connect( pclWebSocketP, &QWebSocket::disconnected, this, &QCanSocket::onSocketDisconnect);
connect( pclWebSocketP, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
this, &QCanSocket::onSocketErrorWeb);
connect( pclWebSocketP, &QWebSocket::binaryMessageReceived, this, &QCanSocket::onSocketReceiveWeb);
btResultT = true;
}
else
{
qDebug() << "QCanSocket::connectNetwork(" << teChannelR << ") - LocalSocket";
//----------------------------------------------------------------------------------------
// create new local socket
//
pclLocalSocketP->abort();
//----------------------------------------------------------------------------------------
// make signal / slot connection for local socket
//
connect( pclLocalSocketP, &QLocalSocket::connected, this, &QCanSocket::onSocketConnect);
connect( pclLocalSocketP, &QLocalSocket::disconnected, this, &QCanSocket::onSocketDisconnect);
connect( pclLocalSocketP, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
this, &QCanSocket::onSocketErrorLocal);
connect( pclLocalSocketP, &QLocalSocket::readyRead, this, &QCanSocket::onSocketReceiveLocal);
//----------------------------------------------------------------------------------------
// connect to local server
//
pclLocalSocketP->connectToServer(QString("CANpieServerChannel%1").arg(teChannelR));
qDebug() << "QCanSocket::connectNetwork() -" << pclLocalSocketP->fullServerName();
btResultT = true;
}
}
return(btResultT);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::disconnectNetwork() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::disconnectNetwork(void)
{
qDebug() << "QCanSocket::disconnectNetwork() ";
if (btIsLocalConnectionP == false)
{
pclWebSocketP->disconnect();
}
else
{
disconnect(pclLocalSocketP, 0, 0, 0);
pclLocalSocketP->disconnectFromServer();
}
btIsConnectedP = false;
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::error() //
// //
//--------------------------------------------------------------------------------------------------------------------//
QAbstractSocket::SocketError QCanSocket::error() const
{
return((QAbstractSocket::SocketError) slSocketErrorP);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::errorString() //
// //
//--------------------------------------------------------------------------------------------------------------------//
QString QCanSocket::errorString() const
{
QString clErrorT;
switch (slSocketErrorP)
{
case QAbstractSocket::ConnectionRefusedError:
clErrorT = qPrintable(tr("connection refused or timed out.") );
break;
case QAbstractSocket::RemoteHostClosedError:
clErrorT = qPrintable(tr("server closed the connection.") );
break;
case QAbstractSocket::HostNotFoundError:
clErrorT = qPrintable(tr("server address was not found.") );
break;
case QAbstractSocket::SocketAccessError:
clErrorT = qPrintable(tr("application lacked the required privileges.") );
break;
case QAbstractSocket::SocketResourceError:
clErrorT = qPrintable(tr("local system ran out of resources.") );
break;
case QAbstractSocket::SocketTimeoutError:
clErrorT = qPrintable(tr("operation timed out.") );
break;
case QAbstractSocket::NetworkError:
clErrorT = qPrintable(tr("error occurred with the network (e.g. cable plugged out).") );
break;
case QAbstractSocket::AddressInUseError:
clErrorT = qPrintable(tr("address is already in use.") );
break;
default:
clErrorT = qPrintable(tr("unknown reason") );
break;
}
return (clErrorT);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::framesAvailable() //
// //
//--------------------------------------------------------------------------------------------------------------------//
int32_t QCanSocket::framesAvailable(void) const
{
return (clReceiveFifoP.size());
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketConnect() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketConnect(void)
{
qDebug() << "QCanSocket::onSocketConnect() ";
//---------------------------------------------------------------------------------------------------
// send signal about connection state and keep it in local variable
//
btIsConnectedP = true;
emit connected();
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketDisconnect() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketDisconnect(void)
{
qDebug() << "QCanSocket::onSocketDisconnect() ";
//---------------------------------------------------------------------------------------------------
// send signal about connection state and keep it in local variable
//
btIsConnectedP = false;
emit disconnected();
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketErrorLocal() //
// handle error conditions of local socket //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketErrorLocal(QLocalSocket::LocalSocketError teSocketErrorV)
{
qDebug() << "QCanSocket::onSocketErrorLocal() " << teSocketErrorV;
qDebug() << pclLocalSocketP->errorString();
switch(teSocketErrorV)
{
//-------------------------------------------------------------------------------------------
// abort all operations and disconnect socket
//
case QLocalSocket::PeerClosedError:
case QLocalSocket::ConnectionError:
pclLocalSocketP->abort();
btIsConnectedP = false;
emit disconnected();
break;
default:
break;
}
//---------------------------------------------------------------------------------------------------
// Store socket error and send signal:
// Since the enumeration values for LocalSocketError are derived from QAbstractSocket::SocketError
// inside the header file QtNetwork/qlocalsocket.h we can simply cast it.
//
slSocketErrorP = teSocketErrorV;
emit error( (QAbstractSocket::SocketError) teSocketErrorV);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketErrorWeb() //
// handle error conditions of WebSocket //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketErrorWeb(QAbstractSocket::SocketError teSocketErrorV)
{
qDebug() << "QCanSocket::onSocketErrorWeb() -" << teSocketErrorV;
switch(teSocketErrorV)
{
//-------------------------------------------------------------
// abort all operations and disconnect socket
//
case QAbstractSocket::RemoteHostClosedError:
case QAbstractSocket::NetworkError:
pclWebSocketP->abort();
btIsConnectedP = false;
emit disconnected();
break;
default:
break;
}
//----------------------------------------------------------------
// store socket error and send signal
//
slSocketErrorP = teSocketErrorV;
emit error(teSocketErrorV);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketReceiveLocal() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketReceiveLocal(void)
{
uint32_t ulFrameCountT;
bool btValidFrameT = false;
bool btSignalNewFrameT = false;
ulFrameCountT = pclLocalSocketP->bytesAvailable() / QCAN_FRAME_ARRAY_SIZE;
while (ulFrameCountT)
{
clReceiveDataP = pclLocalSocketP->read(QCAN_FRAME_ARRAY_SIZE);
btValidFrameT = clReceiveFrameP.fromByteArray(clReceiveDataP);
if (btValidFrameT)
{
//-----------------------------------------------------------------------------------
// Store frame in FIFO
//
clReceiveMutexP.lock();
clReceiveFifoP.enqueue(clReceiveFrameP);
btSignalNewFrameT = true;
clReceiveMutexP.unlock();
//-----------------------------------------------------------------------------------
// If the frame type is an error frame, store the for the actual CAN state
//
if (clReceiveFrameP.frameType() == QCanFrame::eFRAME_TYPE_ERROR)
{
teCanStateP = clReceiveFrameP.errorState();
}
}
ulFrameCountT--;
}
//---------------------------------------------------------------------------------------------------
// Emit signal only once when new data arrived. The flag 'btReceiveSignalSendP' is cleared inside
// the read() method.
//
if (btSignalNewFrameT == true)
{
emit readyRead();
}
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::onSocketReceiveWeb() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::onSocketReceiveWeb(const QByteArray &clMessageR)
{
bool btValidFrameT = false;
bool btSignalNewFrameT = false;
btValidFrameT = clReceiveFrameP.fromByteArray(clMessageR);
if (btValidFrameT)
{
//-----------------------------------------------------------------------------------
// Store frame in FIFO
//
clReceiveMutexP.lock();
clReceiveFifoP.enqueue(clReceiveFrameP);
btSignalNewFrameT = true;
clReceiveMutexP.unlock();
//-----------------------------------------------------------------------------------
// If the frame type is an error frame, store the for the actual CAN state
//
if (clReceiveFrameP.frameType() == QCanFrame::eFRAME_TYPE_ERROR)
{
teCanStateP = clReceiveFrameP.errorState();
}
}
//---------------------------------------------------------------------------------------------------
// Emit signal only once when new data arrived. The flag 'btReceiveSignalSendP' is cleared inside
// the read() method.
//
if (btSignalNewFrameT == true)
{
emit readyRead();
}
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::read() //
// //
//--------------------------------------------------------------------------------------------------------------------//
bool QCanSocket::read(QCanFrame & clFrameR)
{
bool btResultT = false;
clReceiveMutexP.lock();
if (clReceiveFifoP.size() > 0)
{
clFrameR = clReceiveFifoP.dequeue(); // read message from queue
btResultT = true; // message has been updated
}
clReceiveMutexP.unlock();
return (btResultT);
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::setHostAddress() //
// //
//--------------------------------------------------------------------------------------------------------------------//
void QCanSocket::setHostAddress(QHostAddress clHostAddressV, uint16_t uwPortV)
{
if(btIsConnectedP == false)
{
clServerHostAddrP = clHostAddressV;
uwServerPortP = uwPortV;
if (clHostAddressV == QHostAddress::LocalHost)
{
btIsLocalConnectionP = true;
}
else
{
btIsLocalConnectionP = false;
}
}
}
//--------------------------------------------------------------------------------------------------------------------//
// QCanSocket::write() //
// //
//--------------------------------------------------------------------------------------------------------------------//
bool QCanSocket::write(const QCanFrame & clFrameR)
{
bool btResultT = false;
if (btIsConnectedP == true)
{
QByteArray clDatagramT = clFrameR.toByteArray();
if (btIsLocalConnectionP == false)
{
if (pclWebSocketP->sendBinaryMessage(clDatagramT) == QCAN_FRAME_ARRAY_SIZE)
{
pclWebSocketP->flush();
btResultT = true;
}
}
else
{
if (pclLocalSocketP->write(clDatagramT) == QCAN_FRAME_ARRAY_SIZE)
{
pclLocalSocketP->flush();
btResultT = true;
}
}
}
return(btResultT);
}
<|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: joaander
#include "TwoStepLangevinBase.h"
#include <boost/python.hpp>
using namespace boost::python;
using namespace std;
/*! \file TwoStepLangevinBase.h
\brief Contains code for the TwoStepLangevinBase class
*/
/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
\param group The group of particles this integration method is to work on
\param T Temperature set point as a function of time
\param seed Random seed to use in generating random numbers
\param use_lambda If true, gamma=lambda*diameter, otherwise use a per-type gamma via setGamma()
\param lambda Scale factor to convert diameter to gamma
*/
TwoStepLangevinBase::TwoStepLangevinBase(boost::shared_ptr<SystemDefinition> sysdef,
boost::shared_ptr<ParticleGroup> group,
boost::shared_ptr<Variant> T,
unsigned int seed,
bool use_lambda,
Scalar lambda)
: IntegrationMethodTwoStep(sysdef, group), m_T(T), m_seed(seed), m_use_lambda(use_lambda), m_lambda(lambda), m_warned_aniso(false)
{
m_exec_conf->msg->notice(5) << "Constructing TwoStepLangevinBase" << endl;
if (use_lambda)
m_exec_conf->msg->notice(2) << "integrate.langevin/bd is determining gamma from particle diameters" << endl;
else
m_exec_conf->msg->notice(2) << "integrate.langevin/bd is using specified gamma values" << endl;
// Hash the User's Seed to make it less likely to be a low positive integer
m_seed = m_seed*0x12345677 + 0x12345 ; m_seed^=(m_seed>>16); m_seed*= 0x45679;
// allocate memory for the per-type gamma storage and initialize them to 1.0
GPUVector<Scalar> gamma(m_pdata->getNTypes(), m_exec_conf);
m_gamma.swap(gamma);
ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::overwrite);
for (unsigned int i = 0; i < m_gamma.size(); i++)
h_gamma.data[i] = Scalar(1.0);
// allocate memory for the per-type gamma_r storage and initialize them to 0.0 (no rotational noise by default)
GPUVector<Scalar> gamma_r(m_pdata->getNTypes(), m_exec_conf);
m_gamma_r.swap(gamma_r);
ArrayHandle<Scalar> h_gamma_r(m_gamma_r, access_location::host, access_mode::overwrite);
for (unsigned int i = 0; i < m_gamma_r.size(); i++)
h_gamma_r.data[i] = Scalar(0.0);
// connect to the ParticleData to receive notifications when the maximum number of particles changes
m_num_type_change_connection = m_pdata->connectNumTypesChange(boost::bind(&TwoStepLangevinBase::slotNumTypesChange, this));
}
TwoStepLangevinBase::~TwoStepLangevinBase()
{
m_exec_conf->msg->notice(5) << "Destroying TwoStepLangevinBase" << endl;
m_num_type_change_connection.disconnect();
}
void TwoStepLangevinBase::slotNumTypesChange()
{
// skip the reallocation if the number of types does not change
// this keeps old parameters when restoring a snapshot
// it will result in invalid coefficients if the snapshot has a different type id -> name mapping
if (m_pdata->getNTypes() == m_gamma.size())
return;
// re-allocate memory for the per-type gamma storage and initialize them to 1.0
unsigned int old_ntypes = m_gamma.size();
m_gamma.resize(m_pdata->getNTypes());
m_gamma_r.resize(m_pdata->getNTypes());
ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::readwrite);
ArrayHandle<Scalar> h_gamma_r(m_gamma_r, access_location::host, access_mode::readwrite);
for (unsigned int i = old_ntypes; i < m_gamma.size(); i++)
{
h_gamma.data[i] = Scalar(1.0);
h_gamma_r.data[i] = Scalar(1.0);
}
}
/*! \param typ Particle type to set gamma for
\param gamma The gamma value to set
*/
void TwoStepLangevinBase::setGamma(unsigned int typ, Scalar gamma)
{
// check for user errors
if (m_use_lambda)
{
m_exec_conf->msg->error() << "Trying to set gamma when it is set to be the diameter! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
if (typ >= m_pdata->getNTypes())
{
m_exec_conf->msg->error() << "Trying to set gamma for a non existent type! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::readwrite);
h_gamma.data[typ] = gamma;
}
/*! \param typ Particle type to set gamma_r (2D rotational noise) for
\param gamma The gamma_r value to set
*/
void TwoStepLangevinBase::setGamma_r(unsigned int typ, Scalar gamma_r)
{
// check for user errors
if (gamma_r < 0)
{
m_exec_conf->msg->error() << "gamma_r should be positive or 0! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
if (typ >= m_pdata->getNTypes())
{
m_exec_conf->msg->error() << "Trying to set gamma for a non existent type! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
ArrayHandle<Scalar> h_gamma_r(m_gamma_r, access_location::host, access_mode::readwrite);
h_gamma_r.data[typ] = gamma_r;
}
void export_TwoStepLangevinBase()
{
class_<TwoStepLangevinBase, boost::shared_ptr<TwoStepLangevinBase>, bases<IntegrationMethodTwoStep>, boost::noncopyable>
("TwoStepLangevinBase", init< boost::shared_ptr<SystemDefinition>,
boost::shared_ptr<ParticleGroup>,
boost::shared_ptr<Variant>,
unsigned int,
bool,
Scalar
>())
.def("setT", &TwoStepLangevinBase::setT)
.def("setGamma", &TwoStepLangevinBase::setGamma)
;
}
<commit_msg>minor_bug_fixes<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: joaander
#include "TwoStepLangevinBase.h"
#include <boost/python.hpp>
using namespace boost::python;
using namespace std;
/*! \file TwoStepLangevinBase.h
\brief Contains code for the TwoStepLangevinBase class
*/
/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
\param group The group of particles this integration method is to work on
\param T Temperature set point as a function of time
\param seed Random seed to use in generating random numbers
\param use_lambda If true, gamma=lambda*diameter, otherwise use a per-type gamma via setGamma()
\param lambda Scale factor to convert diameter to gamma
*/
TwoStepLangevinBase::TwoStepLangevinBase(boost::shared_ptr<SystemDefinition> sysdef,
boost::shared_ptr<ParticleGroup> group,
boost::shared_ptr<Variant> T,
unsigned int seed,
bool use_lambda,
Scalar lambda)
: IntegrationMethodTwoStep(sysdef, group), m_T(T), m_seed(seed), m_use_lambda(use_lambda), m_lambda(lambda), m_warned_aniso(false)
{
m_exec_conf->msg->notice(5) << "Constructing TwoStepLangevinBase" << endl;
if (use_lambda)
m_exec_conf->msg->notice(2) << "integrate.langevin/bd is determining gamma from particle diameters" << endl;
else
m_exec_conf->msg->notice(2) << "integrate.langevin/bd is using specified gamma values" << endl;
// Hash the User's Seed to make it less likely to be a low positive integer
m_seed = m_seed*0x12345677 + 0x12345 ; m_seed^=(m_seed>>16); m_seed*= 0x45679;
// allocate memory for the per-type gamma storage and initialize them to 1.0
GPUVector<Scalar> gamma(m_pdata->getNTypes(), m_exec_conf);
m_gamma.swap(gamma);
ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::overwrite);
for (unsigned int i = 0; i < m_gamma.size(); i++)
h_gamma.data[i] = Scalar(1.0);
// allocate memory for the per-type gamma_r storage and initialize them to 0.0 (no rotational noise by default)
GPUVector<Scalar> gamma_r(m_pdata->getNTypes(), m_exec_conf);
m_gamma_r.swap(gamma_r);
ArrayHandle<Scalar> h_gamma_r(m_gamma_r, access_location::host, access_mode::overwrite);
for (unsigned int i = 0; i < m_gamma_r.size(); i++)
h_gamma_r.data[i] = Scalar(0.0);
// connect to the ParticleData to receive notifications when the maximum number of particles changes
m_num_type_change_connection = m_pdata->connectNumTypesChange(boost::bind(&TwoStepLangevinBase::slotNumTypesChange, this));
}
TwoStepLangevinBase::~TwoStepLangevinBase()
{
m_exec_conf->msg->notice(5) << "Destroying TwoStepLangevinBase" << endl;
m_num_type_change_connection.disconnect();
}
void TwoStepLangevinBase::slotNumTypesChange()
{
// skip the reallocation if the number of types does not change
// this keeps old parameters when restoring a snapshot
// it will result in invalid coefficients if the snapshot has a different type id -> name mapping
if (m_pdata->getNTypes() == m_gamma.size())
return;
// re-allocate memory for the per-type gamma storage and initialize them to 1.0
unsigned int old_ntypes = m_gamma.size();
m_gamma.resize(m_pdata->getNTypes());
m_gamma_r.resize(m_pdata->getNTypes());
ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::readwrite);
ArrayHandle<Scalar> h_gamma_r(m_gamma_r, access_location::host, access_mode::readwrite);
for (unsigned int i = old_ntypes; i < m_gamma.size(); i++)
{
h_gamma.data[i] = Scalar(1.0);
h_gamma_r.data[i] = Scalar(1.0);
}
}
/*! \param typ Particle type to set gamma for
\param gamma The gamma value to set
*/
void TwoStepLangevinBase::setGamma(unsigned int typ, Scalar gamma)
{
// check for user errors
if (m_use_lambda)
{
m_exec_conf->msg->error() << "Trying to set gamma when it is set to be the diameter! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
if (typ >= m_pdata->getNTypes())
{
m_exec_conf->msg->error() << "Trying to set gamma for a non existent type! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::readwrite);
h_gamma.data[typ] = gamma;
}
/*! \param typ Particle type to set gamma_r (2D rotational noise) for
\param gamma The gamma_r value to set
*/
void TwoStepLangevinBase::setGamma_r(unsigned int typ, Scalar gamma_r)
{
// check for user errors
if (gamma_r < 0)
{
m_exec_conf->msg->error() << "gamma_r should be positive or 0! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
if (typ >= m_pdata->getNTypes())
{
m_exec_conf->msg->error() << "Trying to set gamma for a non existent type! " << typ << endl;
throw runtime_error("Error setting params in TwoStepLangevinBase");
}
ArrayHandle<Scalar> h_gamma_r(m_gamma_r, access_location::host, access_mode::readwrite);
h_gamma_r.data[typ] = gamma_r;
}
void export_TwoStepLangevinBase()
{
class_<TwoStepLangevinBase, boost::shared_ptr<TwoStepLangevinBase>, bases<IntegrationMethodTwoStep>, boost::noncopyable>
("TwoStepLangevinBase", init< boost::shared_ptr<SystemDefinition>,
boost::shared_ptr<ParticleGroup>,
boost::shared_ptr<Variant>,
unsigned int,
bool,
Scalar
>())
.def("setT", &TwoStepLangevinBase::setT)
.def("setGamma", &TwoStepLangevinBase::setGamma)
.def("setGamma_r", &TwoStepLangevinBase::setGamma_r)
;
}
<|endoftext|> |
<commit_before>/* This source file must have a .cpp extension so that all C++ compilers
recognize the extension without flags. Borland does not know .cxx for
example. */
#ifndef __cplusplus
# error "A C compiler has been selected for C++."
#endif
/* Version number components: V=Version, R=Revision, P=Patch
Version date components: YYYY=Year, MM=Month, DD=Day */
#if defined(__COMO__)
# define COMPILER_ID "Comeau"
/* __COMO_VERSION__ = VRR */
# define COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100)
# define COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100)
#elif defined(__INTEL_COMPILER) || defined(__ICC)
# define COMPILER_ID "Intel"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
/* __INTEL_COMPILER = VRP */
# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
# if defined(__INTEL_COMPILER_UPDATE)
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)
# else
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10)
# endif
# if defined(__INTEL_COMPILER_BUILD_DATE)
/* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
# endif
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
#elif defined(__PATHCC__)
# define COMPILER_ID "PathScale"
# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)
# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
# if defined(__PATHCC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
# endif
#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)
# define COMPILER_ID "Embarcadero"
# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF)
#elif defined(__BORLANDC__)
# define COMPILER_ID "Borland"
/* __BORLANDC__ = 0xVRR */
# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)
#elif defined(__WATCOMC__) && __WATCOMC__ < 1200
# define COMPILER_ID "Watcom"
/* __WATCOMC__ = VVRR */
# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif
#elif defined(__WATCOMC__)
# define COMPILER_ID "OpenWatcom"
/* __WATCOMC__ = VVRP + 1100 */
# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif
#elif defined(__SUNPRO_CC)
# define COMPILER_ID "SunPro"
# if __SUNPRO_CC >= 0x5100
/* __SUNPRO_CC = 0xVRRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF)
# else
/* __SUNPRO_CC = 0xVRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF)
# endif
#elif defined(__HP_aCC)
# define COMPILER_ID "HP"
/* __HP_aCC = VVRRPP */
# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000)
# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100)
# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100)
#elif defined(__DECCXX)
# define COMPILER_ID "Compaq"
/* __DECCXX_VER = VVRRTPPPP */
# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000)
# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100)
# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000)
#elif defined(__IBMCPP__) && defined(__COMPILER_VER__)
# define COMPILER_ID "zOS"
/* __IBMCPP__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)
#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800
# define COMPILER_ID "XL"
/* __IBMCPP__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)
#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800
# define COMPILER_ID "VisualAge"
/* __IBMCPP__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)
#elif defined(__PGI)
# define COMPILER_ID "PGI"
# define COMPILER_VERSION_MAJOR DEC(__PGIC__)
# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__)
# if defined(__PGIC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)
# endif
#elif defined(_CRAYC)
# define COMPILER_ID "Cray"
# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR)
# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR)
#elif defined(__TI_COMPILER_VERSION__)
# define COMPILER_ID "TI"
/* __TI_COMPILER_VERSION__ = VVVRRRPPP */
# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000)
# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000)
# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000)
#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version)
# define COMPILER_ID "Fujitsu"
#elif defined(__SCO_VERSION__)
# define COMPILER_ID "SCO"
#elif defined(__clang__) && defined(__apple_build_version__)
# define COMPILER_ID "AppleClang"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__)
#elif defined(__clang__)
# define COMPILER_ID "Clang"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
#elif defined(__GNUC__) || defined(__GNUG__)
# define COMPILER_ID "GNU"
# if defined(__GNUC__)
# define COMPILER_VERSION_MAJOR DEC(__GNUC__)
# else
# define COMPILER_VERSION_MAJOR DEC(__GNUG__)
# endif
# if defined(__GNUC_MINOR__)
# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__)
# endif
# if defined(__GNUC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
# endif
#elif defined(_MSC_VER)
# define COMPILER_ID "MSVC"
/* _MSC_VER = VVRR */
# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100)
# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100)
# if defined(_MSC_FULL_VER)
# if _MSC_VER >= 1400
/* _MSC_FULL_VER = VVRRPPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000)
# else
/* _MSC_FULL_VER = VVRRPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000)
# endif
# endif
# if defined(_MSC_BUILD)
# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD)
# endif
#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)
# define COMPILER_ID "ADSP"
#if defined(__VISUALDSPVERSION__)
/* __VISUALDSPVERSION__ = 0xVVRRPP00 */
# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24)
# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF)
#endif
#elif defined(__IAR_SYSTEMS_ICC__ ) || defined(__IAR_SYSTEMS_ICC)
# define COMPILER_ID "IAR"
#elif defined(__ARMCC_VERSION)
# define COMPILER_ID "ARMCC"
#if __ARMCC_VERSION >= 1000000
/* __ARMCC_VERSION = VRRPPPP */
# define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000)
# define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100)
# define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)
#else
/* __ARMCC_VERSION = VRPPPP */
# define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000)
# define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10)
# define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)
#endif
#elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION)
# define COMPILER_ID "MIPSpro"
# if defined(_SGI_COMPILER_VERSION)
/* _SGI_COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_SGI_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_SGI_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_SGI_COMPILER_VERSION % 10)
# else
/* _COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_COMPILER_VERSION % 10)
# endif
/* These compilers are either not known or too old to define an
identification macro. Try to identify the platform and guess that
it is the native compiler. */
#elif defined(__sgi)
# define COMPILER_ID "MIPSpro"
#elif defined(__hpux) || defined(__hpua)
# define COMPILER_ID "HP"
#else /* unknown compiler */
# define COMPILER_ID ""
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]";
#ifdef SIMULATE_ID
char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]";
#endif
#ifdef __QNXNTO__
char const* qnxnto = "INFO" ":" "qnxnto[]";
#endif
#if defined(__CRAYXE) || defined(__CRAYXC)
char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]";
#endif
#define STRINGIFY_HELPER(X) #X
#define STRINGIFY(X) STRINGIFY_HELPER(X)
/* Identify known platforms by name. */
#if defined(__linux) || defined(__linux__) || defined(linux)
# define PLATFORM_ID "Linux"
#elif defined(__CYGWIN__)
# define PLATFORM_ID "Cygwin"
#elif defined(__MINGW32__)
# define PLATFORM_ID "MinGW"
#elif defined(__APPLE__)
# define PLATFORM_ID "Darwin"
#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
# define PLATFORM_ID "Windows"
#elif defined(__FreeBSD__) || defined(__FreeBSD)
# define PLATFORM_ID "FreeBSD"
#elif defined(__NetBSD__) || defined(__NetBSD)
# define PLATFORM_ID "NetBSD"
#elif defined(__OpenBSD__) || defined(__OPENBSD)
# define PLATFORM_ID "OpenBSD"
#elif defined(__sun) || defined(sun)
# define PLATFORM_ID "SunOS"
#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__)
# define PLATFORM_ID "AIX"
#elif defined(__sgi) || defined(__sgi__) || defined(_SGI)
# define PLATFORM_ID "IRIX"
#elif defined(__hpux) || defined(__hpux__)
# define PLATFORM_ID "HP-UX"
#elif defined(__HAIKU__)
# define PLATFORM_ID "Haiku"
#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS)
# define PLATFORM_ID "BeOS"
#elif defined(__QNX__) || defined(__QNXNTO__)
# define PLATFORM_ID "QNX"
#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__)
# define PLATFORM_ID "Tru64"
#elif defined(__riscos) || defined(__riscos__)
# define PLATFORM_ID "RISCos"
#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__)
# define PLATFORM_ID "SINIX"
#elif defined(__UNIX_SV__)
# define PLATFORM_ID "UNIX_SV"
#elif defined(__bsdos__)
# define PLATFORM_ID "BSDOS"
#elif defined(_MPRAS) || defined(MPRAS)
# define PLATFORM_ID "MP-RAS"
#elif defined(__osf) || defined(__osf__)
# define PLATFORM_ID "OSF1"
#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv)
# define PLATFORM_ID "SCO_SV"
#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX)
# define PLATFORM_ID "ULTRIX"
#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX)
# define PLATFORM_ID "Xenix"
#elif defined(__WATCOMC__)
# if defined(__LINUX__)
# define PLATFORM_ID "Linux"
# elif defined(__DOS__)
# define PLATFORM_ID "DOS"
# elif defined(__OS2__)
# define PLATFORM_ID "OS2"
# elif defined(__WINDOWS__)
# define PLATFORM_ID "Windows3x"
# else /* unknown platform */
# define PLATFORM_ID
# endif
#else /* unknown platform */
# define PLATFORM_ID
#endif
/* For windows compilers MSVC and Intel we can determine
the architecture of the compiler being used. This is because
the compilers do not have flags that can change the architecture,
but rather depend on which compiler is being used
*/
#if defined(_WIN32) && defined(_MSC_VER)
# if defined(_M_IA64)
# define ARCHITECTURE_ID "IA64"
# elif defined(_M_X64) || defined(_M_AMD64)
# define ARCHITECTURE_ID "x64"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# elif defined(_M_ARM)
# if _M_ARM == 4
# define ARCHITECTURE_ID "ARMV4I"
# elif _M_ARM == 5
# define ARCHITECTURE_ID "ARMV5I"
# else
# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM)
# endif
# elif defined(_M_MIPS)
# define ARCHITECTURE_ID "MIPS"
# elif defined(_M_SH)
# define ARCHITECTURE_ID "SHx"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#elif defined(__WATCOMC__)
# if defined(_M_I86)
# define ARCHITECTURE_ID "I86"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#else
# define ARCHITECTURE_ID
#endif
/* Convert integer to decimal digit literals. */
#define DEC(n) \
('0' + (((n) / 10000000)%10)), \
('0' + (((n) / 1000000)%10)), \
('0' + (((n) / 100000)%10)), \
('0' + (((n) / 10000)%10)), \
('0' + (((n) / 1000)%10)), \
('0' + (((n) / 100)%10)), \
('0' + (((n) / 10)%10)), \
('0' + ((n) % 10))
/* Convert integer to hex digit literals. */
#define HEX(n) \
('0' + ((n)>>28 & 0xF)), \
('0' + ((n)>>24 & 0xF)), \
('0' + ((n)>>20 & 0xF)), \
('0' + ((n)>>16 & 0xF)), \
('0' + ((n)>>12 & 0xF)), \
('0' + ((n)>>8 & 0xF)), \
('0' + ((n)>>4 & 0xF)), \
('0' + ((n) & 0xF))
/* Construct a string literal encoding the version number components. */
#ifdef COMPILER_VERSION_MAJOR
char const info_version[] = {
'I', 'N', 'F', 'O', ':',
'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[',
COMPILER_VERSION_MAJOR,
# ifdef COMPILER_VERSION_MINOR
'.', COMPILER_VERSION_MINOR,
# ifdef COMPILER_VERSION_PATCH
'.', COMPILER_VERSION_PATCH,
# ifdef COMPILER_VERSION_TWEAK
'.', COMPILER_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct a string literal encoding the version number components. */
#ifdef SIMULATE_VERSION_MAJOR
char const info_simulate_version[] = {
'I', 'N', 'F', 'O', ':',
's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[',
SIMULATE_VERSION_MAJOR,
# ifdef SIMULATE_VERSION_MINOR
'.', SIMULATE_VERSION_MINOR,
# ifdef SIMULATE_VERSION_PATCH
'.', SIMULATE_VERSION_PATCH,
# ifdef SIMULATE_VERSION_TWEAK
'.', SIMULATE_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]";
char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]";
const char* info_language_dialect_default = "INFO" ":" "dialect_default["
#if __cplusplus > 201402L
"17"
#elif __cplusplus >= 201402L
"14"
#elif __cplusplus >= 201103L
"11"
#else
"98"
#endif
"]";
/*--------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
int require = 0;
require += info_compiler[argc];
require += info_platform[argc];
#ifdef COMPILER_VERSION_MAJOR
require += info_version[argc];
#endif
#ifdef SIMULATE_ID
require += info_simulate[argc];
#endif
#ifdef SIMULATE_VERSION_MAJOR
require += info_simulate_version[argc];
#endif
#if defined(__CRAYXE) || defined(__CRAYXC)
require += info_cray[argc];
#endif
require += info_language_dialect_default[argc];
(void)argv;
return require;
}
<commit_msg>forget CMake cpp file<commit_after><|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/extensions/app_host/binaries_installer.h"
#include "base/logging.h"
#include "base/threading/platform_thread.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "google_update/google_update_idl.h"
using base::win::ScopedBstr;
using base::win::ScopedComPtr;
namespace app_host {
namespace {
const wchar_t kAppHostAppId[] = L"{FDA71E6F-AC4C-4a00-8B70-9958A68906BF}";
const wchar_t kBinariesAppId[] = L"{4DC8B4CA-1BDA-483e-B5FA-D3C12E15B62D}";
const int kInstallationPollingIntervalMs = 50;
HRESULT CreateInstalledApp(IAppBundle* app_bundle,
const wchar_t* app_guid,
IApp** app) {
ScopedComPtr<IApp> temp_app;
ScopedComPtr<IDispatch> idispatch;
HRESULT hr = app_bundle->createInstalledApp(ScopedBstr(app_guid),
idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to configure App Bundle: " << hr;
} else {
hr = temp_app.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying IApp from "
<< "IAppBundle->createInstalledApp return value: " << hr;
} else {
*app = temp_app.Detach();
}
}
return hr;
}
HRESULT GetCurrentState(IApp* app,
ICurrentState** current_state,
CurrentState* state_value) {
HRESULT hr = S_OK;
ScopedComPtr<ICurrentState> temp_current_state;
{
ScopedComPtr<IDispatch> idispatch;
hr = app->get_currentState(idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get App Bundle state: " << hr;
} else {
hr = temp_current_state.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying ICurrentState from "
<< "IApp::get_currentState return value: " << hr;
}
}
}
if (SUCCEEDED(hr)) {
LONG long_state_value;
hr = temp_current_state->get_stateValue(&long_state_value);
if (FAILED(hr))
LOG(ERROR) << "Failed to get App Bundle state value: " << hr;
*state_value = static_cast<CurrentState>(long_state_value);
*current_state = temp_current_state.Detach();
}
return hr;
}
HRESULT CheckIsBusy(IAppBundle* app_bundle, bool* is_busy) {
VARIANT_BOOL variant_is_busy = VARIANT_TRUE;
HRESULT hr = app_bundle->isBusy(&variant_is_busy);
if (FAILED(hr))
LOG(ERROR) << "Failed to check app_bundle->isBusy: " << hr;
else
*is_busy = (variant_is_busy == VARIANT_TRUE);
return hr;
}
HRESULT OnUpdateAvailable(IAppBundle* app_bundle) {
// If the app bundle is busy we will just wait some more.
bool is_busy = false;
HRESULT hr = CheckIsBusy(app_bundle, &is_busy);
if (SUCCEEDED(hr) && !is_busy) {
hr = app_bundle->download();
if (FAILED(hr))
LOG(ERROR) << "Failed to initiate bundle download: " << hr;
}
return hr;
}
HRESULT OnReadyToInstall(IAppBundle* app_bundle) {
// If the app bundle is busy we will just wait some more.
bool is_busy = false;
HRESULT hr = CheckIsBusy(app_bundle, &is_busy);
if (SUCCEEDED(hr) && !is_busy) {
hr = app_bundle->install();
if (FAILED(hr))
LOG(ERROR) << "Failed to initiate bundle install: " << hr;
}
return hr;
}
HRESULT OnError(ICurrentState* current_state) {
LONG error_code;
HRESULT hr = current_state->get_errorCode(&error_code);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to retrieve bundle error code: " << hr;
} else {
hr = error_code;
ScopedBstr completion_message;
HRESULT completion_message_hr =
current_state->get_completionMessage(completion_message.Receive());
if (FAILED(completion_message_hr)) {
LOG(ERROR) << "Bundle installation failed with error " << hr
<< ". Error message retrieval failed with error: "
<< completion_message_hr;
} else {
LOG(ERROR) << "Bundle installation failed with error " << hr << ": "
<< completion_message;
}
}
return hr;
}
HRESULT CreateGoogleUpdate3(IGoogleUpdate3** update3) {
ScopedComPtr<IGoogleUpdate3> temp_update3;
HRESULT hr = temp_update3.CreateInstance(CLSID_GoogleUpdate3UserClass);
if (SUCCEEDED(hr)) {
*update3 = temp_update3.Detach();
} else {
// TODO(erikwright): Try in-proc to support running elevated? According
// to update3_utils.cc (CreateGoogleUpdate3UserClass):
// The primary reason for the LocalServer activation failing on Vista/Win7
// is that COM does not look at HKCU registration when the code is running
// elevated. We fall back to an in-proc mode. The in-proc mode is limited to
// one install at a time, so we use it only as a backup mechanism.
LOG(ERROR) << "Failed to instantiate GoogleUpdate3: " << hr;
}
return hr;
}
HRESULT CreateAppBundle(IGoogleUpdate3* update3, IAppBundle** app_bundle) {
HRESULT hr = S_OK;
ScopedComPtr<IAppBundle> temp_app_bundle;
{
ScopedComPtr<IDispatch> idispatch;
hr = update3->createAppBundle(idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to createAppBundle: " << hr;
} else {
hr = temp_app_bundle.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying IAppBundle from "
<< "IGoogleUpdate3->createAppBundle return value: " << hr;
}
}
}
if (SUCCEEDED(hr)) {
hr = temp_app_bundle->initialize();
if (FAILED(hr))
LOG(ERROR) << "Failed to initialize App Bundle: " << hr;
else
*app_bundle = temp_app_bundle.Detach();
}
return hr;
}
HRESULT GetAppHostApValue(IGoogleUpdate3* update3, BSTR* ap_value) {
ScopedComPtr<IAppBundle> app_bundle;
HRESULT hr = CreateAppBundle(update3, app_bundle.Receive());
if (SUCCEEDED(hr)) {
ScopedComPtr<IApp> app;
hr = CreateInstalledApp(app_bundle, kAppHostAppId, app.Receive());
if (SUCCEEDED(hr)) {
hr = app->get_ap(ap_value);
if (FAILED(hr))
LOG(ERROR) << "Failed to get the App Host AP value.";
}
}
return hr;
}
HRESULT SelectBinariesApValue(IGoogleUpdate3* update3, BSTR* ap_value) {
HRESULT hr = GetAppHostApValue(update3, ap_value);
if (FAILED(hr)) {
// TODO(erikwright): distinguish between AppHost not installed and an
// error in GetAppHostApValue.
// TODO(erikwright): Use stable by default when App Host support is in
// stable.
ScopedBstr temp_ap_value;
if (NULL == temp_ap_value.Allocate(L"2.0-dev-multi-apphost")) {
LOG(ERROR) << "Unexpected error in ScopedBstr::Allocate.";
hr = E_FAIL;
} else {
*ap_value = temp_ap_value.Release();
hr = S_OK;
}
}
return hr;
}
HRESULT CreateBinariesIApp(IAppBundle* app_bundle, BSTR ap, IApp** app) {
HRESULT hr = S_OK;
ScopedComPtr<IApp> temp_app;
{
ScopedComPtr<IDispatch> idispatch;
hr = app_bundle->createApp(ScopedBstr(kBinariesAppId), idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to configure App Bundle: " << hr;
} else {
hr = temp_app.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying IApp from "
<< "IAppBundle->createApp return value: " << hr;
}
}
}
if (SUCCEEDED(hr)) {
hr = temp_app->put_isEulaAccepted(VARIANT_TRUE);
if (FAILED(hr))
LOG(ERROR) << "Failed to set 'EULA Accepted': " << hr;
}
if (SUCCEEDED(hr)) {
hr = temp_app->put_ap(ap);
if (FAILED(hr))
LOG(ERROR) << "Failed to set AP value: " << hr;
}
if (SUCCEEDED(hr))
*app = temp_app.Detach();
return hr;
}
bool CheckIfDone(IAppBundle* app_bundle, IApp* app, HRESULT* hr) {
ScopedComPtr<ICurrentState> current_state;
CurrentState state_value;
*hr = GetCurrentState(app, current_state.Receive(), &state_value);
bool complete = false;
if (SUCCEEDED(hr)) {
switch (state_value) {
case STATE_WAITING_TO_CHECK_FOR_UPDATE:
case STATE_CHECKING_FOR_UPDATE:
case STATE_WAITING_TO_DOWNLOAD:
case STATE_RETRYING_DOWNLOAD:
case STATE_DOWNLOADING:
case STATE_WAITING_TO_INSTALL:
case STATE_INSTALLING:
case STATE_DOWNLOAD_COMPLETE:
case STATE_EXTRACTING:
case STATE_APPLYING_DIFFERENTIAL_PATCH:
// These states will all transition on their own.
break;
case STATE_UPDATE_AVAILABLE:
*hr = OnUpdateAvailable(app_bundle);
break;
case STATE_READY_TO_INSTALL:
*hr = OnReadyToInstall(app_bundle);
break;
case STATE_NO_UPDATE:
LOG(INFO) << "Google Update reports that the binaries are already "
<< "installed and up-to-date.";
complete = true;
break;
case STATE_INSTALL_COMPLETE:
complete = true;
break;
case STATE_ERROR:
*hr = OnError(current_state);
break;
case STATE_INIT:
case STATE_PAUSED:
default:
LOG(ERROR) << "Unexpected bundle state: " << state_value << ".";
*hr = E_FAIL;
break;
}
}
return FAILED(*hr) || complete;
}
} // namespace
// Attempts to install the Chrome Binaries using the IGoogleUpdate3 interface.
// Blocks until the installation process completes, without message pumping.
HRESULT InstallBinaries() {
base::win::ScopedCOMInitializer initialize_com;
HRESULT hr = S_OK;
if (!initialize_com.succeeded()) {
LOG(ERROR) << "COM initialization failed";
hr = E_FAIL;
}
ScopedComPtr<IGoogleUpdate3> update3;
if (SUCCEEDED(hr)) {
hr = CreateGoogleUpdate3(update3.Receive());
}
ScopedBstr ap_value;
if (SUCCEEDED(hr)) {
hr = SelectBinariesApValue(update3, ap_value.Receive());
}
ScopedComPtr<IAppBundle> app_bundle;
if (SUCCEEDED(hr)) {
hr = CreateAppBundle(update3, app_bundle.Receive());
}
ScopedComPtr<IApp> app;
if (SUCCEEDED(hr)) {
hr = CreateBinariesIApp(app_bundle, ap_value, app.Receive());
}
if (SUCCEEDED(hr)) {
hr = app_bundle->checkForUpdate();
if (FAILED(hr)) {
LOG(ERROR) << "Failed to initiate update check: " << hr;
}
}
if (SUCCEEDED(hr)) {
// We rely upon Omaha to eventually time out and transition to a failure
// state.
while (!CheckIfDone(app_bundle, app, &hr)) {
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
kInstallationPollingIntervalMs));
}
}
return hr;
}
} // namespace app_host
<commit_msg>Mostly cleanup.<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/extensions/app_host/binaries_installer.h"
#include "base/logging.h"
#include "base/threading/platform_thread.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "google_update/google_update_idl.h"
namespace app_host {
// Helpers --------------------------------------------------------------------
namespace {
const wchar_t kAppHostAppId[] = L"{FDA71E6F-AC4C-4a00-8B70-9958A68906BF}";
const wchar_t kBinariesAppId[] = L"{4DC8B4CA-1BDA-483e-B5FA-D3C12E15B62D}";
const int kInstallationPollingIntervalMs = 50;
HRESULT CreateInstalledApp(IAppBundle* app_bundle,
const wchar_t* app_guid,
IApp** app) {
base::win::ScopedComPtr<IDispatch> idispatch;
HRESULT hr = app_bundle->createInstalledApp(base::win::ScopedBstr(app_guid),
idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to configure App Bundle: " << hr;
return hr;
}
base::win::ScopedComPtr<IApp> temp_app;
hr = temp_app.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying IApp from "
<< "IAppBundle->createInstalledApp return value: " << hr;
} else {
*app = temp_app.Detach();
}
return hr;
}
HRESULT GetAppHostApValue(IGoogleUpdate3* update3,
IAppBundle* app_bundle,
BSTR* ap_value) {
base::win::ScopedComPtr<IApp> app;
HRESULT hr = CreateInstalledApp(app_bundle, kAppHostAppId, app.Receive());
if (FAILED(hr))
return hr;
hr = app->get_ap(ap_value);
if (FAILED(hr))
LOG(ERROR) << "Failed to get the App Host AP value.";
return hr;
}
HRESULT GetCurrentState(IApp* app,
ICurrentState** current_state,
CurrentState* state_value) {
base::win::ScopedComPtr<IDispatch> idispatch;
HRESULT hr = app->get_currentState(idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get App Bundle state: " << hr;
return hr;
}
base::win::ScopedComPtr<ICurrentState> temp_current_state;
hr = temp_current_state.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying ICurrentState from "
<< "IApp::get_currentState return value: " << hr;
return hr;
}
LONG long_state_value;
hr = temp_current_state->get_stateValue(&long_state_value);
if (SUCCEEDED(hr)) {
*state_value = static_cast<CurrentState>(long_state_value);
*current_state = temp_current_state.Detach();
} else {
LOG(ERROR) << "Failed to get App Bundle state value: " << hr;
}
return hr;
}
bool CheckIsBusy(IAppBundle* app_bundle, HRESULT* hr) {
VARIANT_BOOL variant_is_busy = VARIANT_TRUE;
*hr = app_bundle->isBusy(&variant_is_busy);
if (FAILED(*hr))
LOG(ERROR) << "Failed to check app_bundle->isBusy: " << *hr;
return (variant_is_busy == VARIANT_TRUE);
}
void OnUpdateAvailable(IAppBundle* app_bundle, HRESULT* hr) {
// If the app bundle is busy we will just wait some more.
if (CheckIsBusy(app_bundle, hr) || FAILED(*hr))
return;
*hr = app_bundle->download();
if (FAILED(*hr))
LOG(ERROR) << "Failed to initiate bundle download: " << *hr;
}
void OnReadyToInstall(IAppBundle* app_bundle, HRESULT* hr) {
// If the app bundle is busy we will just wait some more.
if (CheckIsBusy(app_bundle, hr) || FAILED(*hr))
return;
*hr = app_bundle->install();
if (FAILED(*hr))
LOG(ERROR) << "Failed to initiate bundle install: " << *hr;
}
HRESULT OnError(ICurrentState* current_state) {
LONG error_code;
HRESULT hr = current_state->get_errorCode(&error_code);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to retrieve bundle error code: " << hr;
return hr;
}
base::win::ScopedBstr completion_message;
HRESULT completion_message_hr =
current_state->get_completionMessage(completion_message.Receive());
if (FAILED(completion_message_hr)) {
LOG(ERROR) << "Bundle installation failed with error " << error_code
<< ". Error message retrieval failed with error: "
<< completion_message_hr;
} else {
LOG(ERROR) << "Bundle installation failed with error " << error_code << ": "
<< completion_message;
}
return error_code;
}
HRESULT CreateGoogleUpdate3(IGoogleUpdate3** update3) {
base::win::ScopedComPtr<IGoogleUpdate3> temp_update3;
HRESULT hr = temp_update3.CreateInstance(CLSID_GoogleUpdate3UserClass);
if (SUCCEEDED(hr)) {
*update3 = temp_update3.Detach();
} else {
// TODO(erikwright): Try in-proc to support running elevated? According
// to update3_utils.cc (CreateGoogleUpdate3UserClass):
// The primary reason for the LocalServer activation failing on Vista/Win7
// is that COM does not look at HKCU registration when the code is running
// elevated. We fall back to an in-proc mode. The in-proc mode is limited to
// one install at a time, so we use it only as a backup mechanism.
LOG(ERROR) << "Failed to instantiate GoogleUpdate3: " << hr;
}
return hr;
}
HRESULT CreateAppBundle(IGoogleUpdate3* update3, IAppBundle** app_bundle) {
base::win::ScopedComPtr<IDispatch> idispatch;
HRESULT hr = update3->createAppBundle(idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to createAppBundle: " << hr;
return hr;
}
base::win::ScopedComPtr<IAppBundle> temp_app_bundle;
hr = temp_app_bundle.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying IAppBundle from "
<< "IGoogleUpdate3->createAppBundle return value: " << hr;
return hr;
}
hr = temp_app_bundle->initialize();
if (FAILED(hr))
LOG(ERROR) << "Failed to initialize App Bundle: " << hr;
else
*app_bundle = temp_app_bundle.Detach();
return hr;
}
HRESULT SelectBinariesApValue(IGoogleUpdate3* update3,
IAppBundle* app_bundle,
BSTR* ap_value) {
HRESULT hr = GetAppHostApValue(update3, app_bundle, ap_value);
if (SUCCEEDED(hr))
return hr;
// TODO(erikwright): distinguish between AppHost not installed and an
// error in GetAppHostApValue.
// TODO(erikwright): Use stable by default when App Host support is in
// stable.
base::win::ScopedBstr temp_ap_value;
if (temp_ap_value.Allocate(L"2.0-dev-multi-apphost") == NULL) {
LOG(ERROR) << "Unexpected error in ScopedBstr::Allocate.";
return E_FAIL;
}
*ap_value = temp_ap_value.Release();
return S_OK;
}
HRESULT CreateBinariesIApp(IAppBundle* app_bundle, BSTR ap, IApp** app) {
base::win::ScopedComPtr<IDispatch> idispatch;
HRESULT hr = app_bundle->createApp(base::win::ScopedBstr(kBinariesAppId),
idispatch.Receive());
if (FAILED(hr)) {
LOG(ERROR) << "Failed to configure App Bundle: " << hr;
return hr;
}
base::win::ScopedComPtr<IApp> temp_app;
hr = temp_app.QueryFrom(idispatch);
if (FAILED(hr)) {
LOG(ERROR) << "Unexpected error querying IApp from "
<< "IAppBundle->createApp return value: " << hr;
return hr;
}
hr = temp_app->put_isEulaAccepted(VARIANT_TRUE);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to set 'EULA Accepted': " << hr;
return hr;
}
hr = temp_app->put_ap(ap);
if (FAILED(hr))
LOG(ERROR) << "Failed to set AP value: " << hr;
else
*app = temp_app.Detach();
return hr;
}
bool CheckIfDone(IAppBundle* app_bundle, IApp* app, HRESULT* hr) {
base::win::ScopedComPtr<ICurrentState> current_state;
CurrentState state_value;
*hr = GetCurrentState(app, current_state.Receive(), &state_value);
if (FAILED(*hr))
return true;
switch (state_value) {
case STATE_WAITING_TO_CHECK_FOR_UPDATE:
case STATE_CHECKING_FOR_UPDATE:
case STATE_WAITING_TO_DOWNLOAD:
case STATE_RETRYING_DOWNLOAD:
case STATE_DOWNLOADING:
case STATE_WAITING_TO_INSTALL:
case STATE_INSTALLING:
case STATE_DOWNLOAD_COMPLETE:
case STATE_EXTRACTING:
case STATE_APPLYING_DIFFERENTIAL_PATCH:
// These states will all transition on their own.
return false;
case STATE_UPDATE_AVAILABLE:
OnUpdateAvailable(app_bundle, hr);
return FAILED(*hr);
case STATE_READY_TO_INSTALL:
OnReadyToInstall(app_bundle, hr);
return FAILED(*hr);
case STATE_NO_UPDATE:
LOG(INFO) << "Google Update reports that the binaries are already "
<< "installed and up-to-date.";
return true;
case STATE_INSTALL_COMPLETE:
return true;
case STATE_ERROR:
*hr = OnError(current_state);
return FAILED(*hr);
case STATE_INIT:
case STATE_PAUSED:
default:
LOG(ERROR) << "Unexpected bundle state: " << state_value << ".";
*hr = E_FAIL;
return true;
}
}
} // namespace
// Globals --------------------------------------------------------------------
HRESULT InstallBinaries() {
base::win::ScopedCOMInitializer initialize_com;
if (!initialize_com.succeeded()) {
LOG(ERROR) << "COM initialization failed";
return E_FAIL;
}
base::win::ScopedComPtr<IGoogleUpdate3> update3;
HRESULT hr = CreateGoogleUpdate3(update3.Receive());
if (FAILED(hr))
return hr;
base::win::ScopedComPtr<IAppBundle> app_bundle;
hr = CreateAppBundle(update3, app_bundle.Receive());
if (FAILED(hr))
return hr;
base::win::ScopedBstr ap_value;
hr = SelectBinariesApValue(update3, app_bundle, ap_value.Receive());
if (FAILED(hr))
return hr;
base::win::ScopedComPtr<IApp> app;
hr = CreateBinariesIApp(app_bundle, ap_value, app.Receive());
if (FAILED(hr))
return hr;
hr = app_bundle->checkForUpdate();
if (FAILED(hr)) {
LOG(ERROR) << "Failed to initiate update check: " << hr;
return hr;
}
// We rely upon Omaha to eventually time out and transition to a failure
// state.
while (!CheckIfDone(app_bundle, app, &hr)) {
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
kInstallationPollingIntervalMs));
}
return hr;
}
} // namespace app_host
<|endoftext|> |
<commit_before>/*
FILNAMN: server.cc
PROGRAMMERARE: hanel742, eriek984, jened502, tobgr602, niker917, davha227
SKAPAD DATUM: 2013-11-18
BESKRIVNING:
*/
#include "thread.h"
using namespace std;
// ---------------------------------------
// Helper functions
void Thread::handleMessage(QString inData){
int i;
QString from;
i = inData.indexOf(compare);
from = inData.left(i);
string stdFrom = from.toStdString();
inData = inData.mid(i+1);
QString to;
i = inData.indexOf(compare);
to = inData.left(i);
string stdTo = to.toStdString();
inData = inData.mid(i+1);
QString contents;
i = inData.indexOf(compare);
contents = inData.left(i);
string stdContents = contents.toStdString();
inData = inData.mid(i+1);
Message message(stdContents, stdFrom, stdTo);
userPointer->sendMessage(message);
}
// ----------------------
void Thread::handleInitiate(string stdInData) {
try
{
userPointer = masterPointer->createUser(stdInData);
userPointer->setThread(this);
requestStruct();
userPointer->sendHistory();
}
catch (...)
{
reinitiate();
}
}
// ----------------------
void Thread::handleStructure() {
vector<string> structure = userPointer->getStruct();
QByteArray sendData;
sendData += "/structure";
sendData += compare;
unsigned int i;
for (i = 0; i+1 < structure.size() ; i++) {
sendData += QString::fromStdString(structure.at(i));
sendData += compare;
}
i++;
sendData += QString::fromStdString(structure.at(i));
sendData += breaker;
TcpSocket->write(sendData);
}
// ---------------------------------------
Thread::Thread(qintptr ID, Master* masterptr, QObject *parent) : QThread(parent)
{
masterPointer=masterptr;
this->socketDescriptor = ID;
compare += 0x1F;
breaker += 0x1E;
}
// ---------------------------------------
void Thread::run()
{
//thread starts here
cout << socketDescriptor << " starting thread"<<endl;
TcpSocket = new QTcpSocket();
if(!TcpSocket->setSocketDescriptor(this->socketDescriptor))
{
emit error(TcpSocket->error());
return;
}
connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
cout << socketDescriptor << " client connected"<<endl;
//creates a messageloop
exec();
}
// ---------------------------------------
// ---------------------------
void Thread::readyRead()
{
QByteArray Data = TcpSocket->readAll();
int i;
int n;
QString commandName;
QString inData = Data;
QString rest;
while ( !inData.isEmpty() ) {
i = inData.indexOf(compare);
commandName = inData.left(i);
inData = inData.mid(i+1);
n = inData.indexOf(breaker);
if (inData.size() < 2) {
break;
}
rest = inData.mid(n+1);
inData = inData.left(n);
QString temp = inData;
string stdInData = temp.toStdString();
// Check which command that's supposed to run
if (commandName == "/initiate") {
handleInitiate(stdInData);
}
else if (commandName == "/message") {
handleMessage(inData);
}
else if ( commandName == "/structure" ) {
handleStructure();
}
else {
qDebug() << commandName;
TcpSocket->write("Ej giltigt kommando");
cout << socketDescriptor << "Data in: "<< stdInData<<endl;
}
inData = rest;
}
}
// ---------------------------------------
void Thread::disconnected()
{
cout << socketDescriptor << "Disconnected"<<endl;
try {
masterPointer->removeUser(userPointer->getName());
} catch (...) {
}
TcpSocket->deleteLater();
//exits the thread
exit(0);
}
// -----------------------------------------
//svarar klienten
void Thread::sendMessage(Message messageObject){
QByteArray array = "/message";
array += 0x1F; //unit separator
array += QString::fromStdString(messageObject.getFrom());
array += 0x1F;
array += QString::fromStdString(messageObject.getTo());
array += 0x1F;
array += QString::fromStdString(messageObject.getMessage());
array += 0x1F;
array += QString::fromStdString(messageObject.getServerTime());
array += 0x1E;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// -----------------------------------------
void Thread::sendHistory(){
QByteArray array = "/history";
array += 0x1F; //unit separator
for (unsigned int i=0; i < userPointer->getParentRoom()->log.size(); i++)
{
Message tempMessage = userPointer->getParentRoom()->log.at(i);
array += QString::fromStdString(tempMessage.getFrom());
array += 0x1F; //unit separator
array += QString::fromStdString(tempMessage.getTo());
array += 0x1F; //unit separator
array += QString::fromStdString(tempMessage.getMessage());
array += 0x1F; //unit separator
array += QString::fromStdString(tempMessage.getServerTime());
array += 0x1E; //unit separator
}
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// -----------------------------------------
void Thread::reinitiate(){
QByteArray array = "/reinitiate";
array += 0x1E; //unit separator
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// -----------------------------------------
void Thread::requestStruct() {
QByteArray array = "/structure";
array += 0x1E;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
<commit_msg>Worked on sending several commands at start, fixed a couple, but structure crashes.<commit_after>/*
FILNAMN: server.cc
PROGRAMMERARE: hanel742, eriek984, jened502, tobgr602, niker917, davha227
SKAPAD DATUM: 2013-11-18
BESKRIVNING:
*/
#include "thread.h"
using namespace std;
// ---------------------------------------
// Helper functions
void Thread::handleMessage(QString inData){
int i;
QString from;
i = inData.indexOf(compare);
from = inData.left(i);
string stdFrom = from.toStdString();
inData = inData.mid(i+1);
QString to;
i = inData.indexOf(compare);
to = inData.left(i);
string stdTo = to.toStdString();
inData = inData.mid(i+1);
QString contents;
i = inData.indexOf(compare);
contents = inData.left(i);
string stdContents = contents.toStdString();
inData = inData.mid(i+1);
Message message(stdContents, stdFrom, stdTo);
userPointer->sendMessage(message);
}
// ----------------------
void Thread::handleInitiate(string stdInData) {
try
{
userPointer = masterPointer->createUser(stdInData);
userPointer->setThread(this);
requestStruct();
userPointer->sendHistory();
}
catch (...)
{
reinitiate();
}
}
// ----------------------
void Thread::handleStructure() {
vector<string> structure = userPointer->getStruct();
QByteArray sendData;
sendData += "/structure";
sendData += compare;
unsigned int i;
for (i = 0; i+1 < structure.size() ; i++) {
sendData += QString::fromStdString(structure.at(i));
sendData += compare;
}
i++;
sendData += QString::fromStdString(structure.at(i));
sendData += breaker;
TcpSocket->write(sendData);
}
// ---------------------------------------
Thread::Thread(qintptr ID, Master* masterptr, QObject *parent) : QThread(parent)
{
masterPointer=masterptr;
this->socketDescriptor = ID;
compare += 0x1F;
breaker += 0x1E;
}
// ---------------------------------------
void Thread::run()
{
//thread starts here
cout << socketDescriptor << " starting thread"<<endl;
TcpSocket = new QTcpSocket();
if(!TcpSocket->setSocketDescriptor(this->socketDescriptor))
{
emit error(TcpSocket->error());
return;
}
connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
cout << socketDescriptor << " client connected"<<endl;
//creates a messageloop
exec();
}
// ---------------------------------------
// ---------------------------
void Thread::readyRead()
{
QByteArray Data = TcpSocket->readAll();
int i;
int n;
QString commandName;
QString inData = Data;
QString rest;
while ( !inData.isEmpty() ) {
i = inData.indexOf(compare);
commandName = inData.left(i);
inData = inData.mid(i+1);
n = inData.indexOf(breaker);
if (inData.size() < 2) {
break;
}
rest = inData.mid(n+1);
inData = inData.left(n);
QString temp = inData;
string stdInData = temp.toStdString();
// Check which command that's supposed to run
if (commandName == "/initiate") {
cout <<"Initiate. " << stdInData << endl;
handleInitiate(stdInData);
}
else if (commandName == "/message") {
qDebug() << "/message thread";
handleMessage(inData);
}
else if ( commandName == "/structure" ) {
//handleStructure();
cout << "Handled structure, but not really" << endl;
}
else {
cout << "Ej giltigt kommando" << commandName.toStdString() << endl;
TcpSocket->write("Ej giltigt kommando");
cout << socketDescriptor << "Data in: "<< stdInData<<endl;
}
inData = rest;
}
}
// ---------------------------------------
void Thread::disconnected()
{
cout << socketDescriptor << "Disconnected"<<endl;
try {
masterPointer->removeUser(userPointer->getName());
} catch (...) {
}
TcpSocket->deleteLater();
//exits the thread
exit(0);
}
// -----------------------------------------
//svarar klienten
void Thread::sendMessage(Message messageObject){
QByteArray array = "/message";
array += 0x1F; //unit separator
array += QString::fromStdString(messageObject.getFrom());
array += 0x1F;
array += QString::fromStdString(messageObject.getTo());
array += 0x1F;
array += QString::fromStdString(messageObject.getMessage());
array += 0x1F;
array += QString::fromStdString(messageObject.getServerTime());
array += 0x1E;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// -----------------------------------------
void Thread::sendHistory(){
QByteArray array = "/history";
array += 0x1F; //unit separator
unsigned int logSize = userPointer->getParentRoom()->log.size();
for (unsigned int i = 0; i < logSize; i++){
Message tempMessage = userPointer->getParentRoom()->log.at(i);
array += QString::fromStdString(tempMessage.getFrom());
array += 0x1F; //unit separator
array += QString::fromStdString(tempMessage.getTo());
array += 0x1F; //unit separator
array += QString::fromStdString(tempMessage.getMessage());
array += 0x1F; //unit separator
array += QString::fromStdString(tempMessage.getServerTime());
if ( i+1 == logSize ){
cout << "0x1E" << endl;
array += 0x1E;
break;
}
array += 0x1F; //unit separator
}
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// -----------------------------------------
void Thread::reinitiate(){
QByteArray array = "/reinitiate";
array += 0x1F;
array += 0x1E; //unit separator
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// -----------------------------------------
void Thread::requestStruct() {
QByteArray array = "/structure";
array += 0x1F;
array += 0x1E;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <fnord-base/application.h>
#include <fnord-base/cli/flagparser.h>
#include <fnord-base/exception.h>
#include <fnord-base/exceptionhandler.h>
#include <fnord-base/inspect.h>
#include <fnord-base/random.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/inputstream.h>
#include <fnord-base/io/outputstream.h>
#include <fnord-base/logging.h>
#include <fnord-base/net/udpserver.h>
#include <fnord-base/stats/statsd.h>
#include <fnord-base/stdtypes.h>
#include <fnord-base/thread/threadpool.h>
#include <fnord-http/httpserver.h>
#include <fnord-metricdb/metricservice.h>
#include <environment.h>
using fnord::metric_service::MetricService;
using namespace fnordmetric;
static const char kCrashErrorMsg[] =
"FnordMetric crashed :( -- Please report a bug at "
"github.com/paulasmuth/fnordmetric";
static MetricService makeMetricService(
const std::string& backend_type,
TaskScheduler* backend_scheduler) {
/* open inmemory backend */
if (backend_type == "inmemory") {
fnord::logInfo("fnordmetric-server", "Opening new inmemory backend");
return MetricService::newWithInMemoryBackend();
}
/* open disk backend */
if (backend_type == "disk") {
if (!env()->flags()->isSet("datadir")) {
RAISE(
kUsageError,
"the --datadir flag must be set when using the disk backend");
}
auto datadir = env()->flags()->getString("datadir");
if (!fnord::FileUtil::exists(datadir)) {
RAISEF(kIOError, "File $0 does not exist", datadir);
}
if (!fnord::FileUtil::isDirectory(datadir)) {
RAISEF(kIOError, "File $0 is not a directory", datadir);
}
fnord::logInfo("fnordmetric-server", "Opening disk backend at $0", datadir);
return MetricService::newWithDiskBackend(datadir, backend_scheduler);
}
RAISEF(kUsageError, "unknown backend type: $0", backend_type);
}
static int startServer() {
fnord::thread::ThreadPool server_pool;
fnord::thread::ThreadPool worker_pool;
/* setup MetricService */
auto metric_service = makeMetricService(
env()->flags()->getString("storage_backend"),
&server_pool);
/* Setup statsd server */
/*if (env()->flags()->isSet("statsd_port")) {
auto port = env()->flags()->getInt("statsd_port");
fnord::logInfo("Starting statsd server on port $0", port);
auto statsd_server = new StatsdServer(&server_pool, &worker_pool);
statsd_server->onSample([&metric_service] (
const std::string& key,
double value,
const std::vector<std::pair<std::string, std::string>>& labels) {
if (env()->verbose()) {
fnord::logDebug(
"statsd sample: $0=$1 $2",
key.c_str(),
value,
fnord::inspect(labels).c_str());
}
metric_service.insertSample(key, value, labels);
});
statsd_server->listen(port);
}*/
/* Setup http server */
/*if (env()->flags()->isSet("http_port")) {
auto port = env()->flags()->getInt("http_port");
env()->logger()->printf(
"INFO",
"Starting HTTP server on port %i",
port);
auto http_api = new HTTPAPI(metric_service.metricRepository());
auto http_server = new fnord::http::HTTPServer(
&server_pool,
&worker_pool);
http_server->addHandler(AdminUI::getHandler());
http_server->addHandler(JSONRPCHTTPAdapter::make(&json_rpc));
http_server->addHandler(std::unique_ptr<http::HTTPHandler>(http_api));
http_server->listen(port);
}*/
return 0;
}
static void printUsage() {
auto err_stream = fnord::OutputStream::getStderr();
err_stream->printf("usage: fnordmetric-server [options]\n");
err_stream->printf("\noptions:\n");
env()->flags()->printUsage(err_stream.get());
err_stream->printf("\nexamples:\n");
err_stream->printf(" $ fnordmetric-server --http_port 8080 --statsd_port 8125 --datadir /tmp/fnordmetric-data\n");
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
env()->flags()->defineFlag(
"http_port",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8080",
"Start the web interface on this port",
"<port>");
env()->flags()->defineFlag(
"statsd_port",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8125",
"Start the statsd interface on this port",
"<port>");
env()->flags()->defineFlag(
"storage_backend",
cli::FlagParser::T_STRING,
false,
NULL,
"disk",
"One of 'disk', 'inmemory', 'mysql' or 'hbase'. Default: 'disk'",
"<name>");
env()->flags()->defineFlag(
"datadir",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"Store the database in this directory (disk backend only)",
"<path>");
env()->flags()->defineFlag(
"disable_external_sources",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"Disable queries against external data sources like CSV files or MySQL");
env()->flags()->defineFlag(
"verbose",
cli::FlagParser::T_SWITCH,
false,
NULL,
"Be verbose");
env()->flags()->defineFlag(
"help",
cli::FlagParser::T_SWITCH,
false,
"h",
NULL,
"You are reading it...");
env()->flags()->parseArgv(argc, argv);
env()->setVerbose(env()->flags()->isSet("verbose"));
if (env()->flags()->isSet("help")) {
printUsage();
return 0;
}
try {
return startServer();
} catch (const fnord::Exception& e) {
fnord::logError("fnordmetric-server", e, "FATAL ERROR");
if (e.getTypeName() == kUsageError) {
printUsage();
}
return 1;
}
return 0;
}
<commit_msg>start new http, statsd server<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <fnord-base/application.h>
#include <fnord-base/cli/flagparser.h>
#include <fnord-base/exception.h>
#include <fnord-base/exceptionhandler.h>
#include <fnord-base/inspect.h>
#include <fnord-base/random.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/inputstream.h>
#include <fnord-base/io/outputstream.h>
#include <fnord-base/logging.h>
#include <fnord-base/net/udpserver.h>
#include <fnord-base/stats/statsd.h>
#include <fnord-base/stdtypes.h>
#include <fnord-base/thread/threadpool.h>
#include <fnord-base/thread/eventloop.h>
#include <fnord-http/httpserver.h>
#include <fnord-http/httprouter.h>
#include <fnord-json/json.h>
#include <fnord-json/jsonrpc.h>
#include <fnord-metricdb/metricservice.h>
#include <fnord-metricdb/httpapiservlet.h>
#include <environment.h>
using fnord::metric_service::MetricService;
using namespace fnordmetric;
static const char kCrashErrorMsg[] =
"FnordMetric crashed :( -- Please report a bug at "
"github.com/paulasmuth/fnordmetric";
static MetricService makeMetricService(
const std::string& backend_type,
TaskScheduler* backend_scheduler) {
/* open inmemory backend */
if (backend_type == "inmemory") {
fnord::logInfo("fnordmetric-server", "Opening new inmemory backend");
return MetricService::newWithInMemoryBackend();
}
/* open disk backend */
if (backend_type == "disk") {
if (!env()->flags()->isSet("datadir")) {
RAISE(
kUsageError,
"the --datadir flag must be set when using the disk backend");
}
auto datadir = env()->flags()->getString("datadir");
if (!fnord::FileUtil::exists(datadir)) {
RAISEF(kIOError, "File $0 does not exist", datadir);
}
if (!fnord::FileUtil::isDirectory(datadir)) {
RAISEF(kIOError, "File $0 is not a directory", datadir);
}
fnord::logInfo("fnordmetric-server", "Opening disk backend at $0", datadir);
return MetricService::newWithDiskBackend(datadir, backend_scheduler);
}
RAISEF(kUsageError, "unknown backend type: $0", backend_type);
}
static int startServer() {
/* Setup statsd server */
return 0;
}
static void printUsage() {
auto err_stream = fnord::OutputStream::getStderr();
err_stream->printf("usage: fnordmetric-server [options]\n");
err_stream->printf("\noptions:\n");
env()->flags()->printUsage(err_stream.get());
err_stream->printf("\nexamples:\n");
err_stream->printf(" $ fnordmetric-server --http_port 8080 --statsd_port 8125 --datadir /tmp/fnordmetric-data\n");
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
env()->flags()->defineFlag(
"http_port",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8080",
"Start the web interface on this port",
"<port>");
env()->flags()->defineFlag(
"statsd_port",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8125",
"Start the statsd interface on this port",
"<port>");
env()->flags()->defineFlag(
"storage_backend",
cli::FlagParser::T_STRING,
false,
NULL,
"disk",
"One of 'disk', 'inmemory', 'mysql' or 'hbase'. Default: 'disk'",
"<name>");
env()->flags()->defineFlag(
"datadir",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"Store the database in this directory (disk backend only)",
"<path>");
env()->flags()->defineFlag(
"disable_external_sources",
cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"Disable queries against external data sources like CSV files or MySQL");
env()->flags()->defineFlag(
"verbose",
cli::FlagParser::T_SWITCH,
false,
NULL,
"Be verbose");
env()->flags()->defineFlag(
"help",
cli::FlagParser::T_SWITCH,
false,
"h",
NULL,
"You are reading it...");
env()->flags()->parseArgv(argc, argv);
env()->setVerbose(env()->flags()->isSet("verbose"));
if (env()->flags()->isSet("help")) {
printUsage();
return 0;
}
fnord::thread::EventLoop evloop;
fnord::thread::ThreadPool server_pool;
fnord::thread::ThreadPool worker_pool;
fnord::json::JSONRPC rpc;
fnord::json::JSONRPCHTTPAdapter rpc_http(&rpc);
try {
/* setup MetricService */
auto metric_service = makeMetricService(
env()->flags()->getString("storage_backend"),
&server_pool);
/* start http server */
auto http_port = env()->flags()->getInt("http_port");
fnord::logInfo(
"fnordmeric-server",
"Starting HTTP server on port $0",
http_port);
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &evloop);
http_server.listen(http_port);
fnord::metric_service::HTTPAPIServlet metrics_api(&metric_service);
http_router.addRouteByPrefixMatch("/metrics", &metrics_api);
http_router.addRouteByPrefixMatch("/rpc", &rpc_http);
//auto http_api = new HTTPAPI(metric_service.metricRepository());
//http_server->addHandler(AdminUI::getHandler());
//http_server->addHandler(std::unique_ptr<http::HTTPHandler>(http_api));
/* set up statsd server */
fnord::statsd::StatsdServer statsd_server(&evloop, &evloop);
statsd_server.onSample([&metric_service] (
const std::string& key,
double value,
const std::vector<std::pair<std::string, std::string>>& labels) {
if (env()->verbose()) {
fnord::logDebug(
"statsd sample: $0=$1 $2",
key,
value,
fnord::inspect(labels).c_str());
}
metric_service.insertSample(key, value, labels);
});
/* start statsd server */
if (env()->flags()->isSet("statsd_port")) {
auto statsd_port = env()->flags()->getInt("statsd_port");
fnord::logInfo(
"fnordmetric-server",
"Starting StatsD server on port $0",
statsd_port);
statsd_server.listen(statsd_port);
}
/* start event loop */
evloop.run();
} catch (const fnord::Exception& e) {
fnord::logError("fnordmetric-server", e, "FATAL ERROR");
if (e.getTypeName() == kUsageError) {
printUsage();
}
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2020 The QXmpp developers
*
* Authors:
* Manjeet Dahiya
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppStream.h"
#include "QXmppConstants_p.h"
#include "QXmppLogger.h"
#include "QXmppStanza.h"
#include "QXmppStreamManagement_p.h"
#include "QXmppUtils.h"
#include <QBuffer>
#include <QDomDocument>
#include <QHostAddress>
#include <QMap>
#include <QRegExp>
#include <QSslSocket>
#include <QStringList>
#include <QTime>
#include <QXmlStreamWriter>
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
static bool randomSeeded = false;
#endif
static const QByteArray streamRootElementEnd = QByteArrayLiteral("</stream:stream>");
class QXmppStreamPrivate
{
public:
QXmppStreamPrivate();
QByteArray dataBuffer;
QSslSocket *socket;
// incoming stream state
QByteArray streamStart;
bool streamManagementEnabled;
QMap<unsigned, QByteArray> unacknowledgedStanzas;
unsigned lastOutgoingSequenceNumber;
unsigned lastIncomingSequenceNumber;
};
QXmppStreamPrivate::QXmppStreamPrivate()
: socket(nullptr), streamManagementEnabled(false), lastOutgoingSequenceNumber(0), lastIncomingSequenceNumber(0)
{
}
///
/// Constructs a base XMPP stream.
///
/// \param parent
///
QXmppStream::QXmppStream(QObject *parent)
: QXmppLoggable(parent),
d(new QXmppStreamPrivate)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
// Make sure the random number generator is seeded
if (!randomSeeded) {
qsrand(QTime(0, 0, 0).msecsTo(QTime::currentTime()) ^ reinterpret_cast<quintptr>(this));
randomSeeded = true;
}
#endif
}
///
/// Destroys a base XMPP stream.
///
QXmppStream::~QXmppStream()
{
delete d;
}
///
/// Disconnects from the remote host.
///
void QXmppStream::disconnectFromHost()
{
d->streamManagementEnabled = false;
if (d->socket) {
if (d->socket->state() == QAbstractSocket::ConnectedState) {
sendData(streamRootElementEnd);
d->socket->flush();
}
// FIXME: according to RFC 6120 section 4.4, we should wait for
// the incoming stream to end before closing the socket
d->socket->disconnectFromHost();
}
}
///
/// Handles a stream start event, which occurs when the underlying transport
/// becomes ready (socket connected, encryption started).
///
/// If you redefine handleStart(), make sure to call the base class's method.
///
void QXmppStream::handleStart()
{
d->streamManagementEnabled = false;
d->dataBuffer.clear();
d->streamStart.clear();
}
///
/// Returns true if the stream is connected.
///
bool QXmppStream::isConnected() const
{
return d->socket &&
d->socket->state() == QAbstractSocket::ConnectedState;
}
///
/// Sends raw data to the peer.
///
/// \param data
///
bool QXmppStream::sendData(const QByteArray &data)
{
logSent(QString::fromUtf8(data));
if (!d->socket || d->socket->state() != QAbstractSocket::ConnectedState)
return false;
return d->socket->write(data) == data.size();
}
///
/// Sends an XMPP packet to the peer.
///
/// \param packet
///
bool QXmppStream::sendPacket(const QXmppStanza &packet)
{
// prepare packet
QByteArray data;
QXmlStreamWriter xmlStream(&data);
packet.toXml(&xmlStream);
bool isXmppStanza = packet.isXmppStanza();
if (isXmppStanza && d->streamManagementEnabled)
d->unacknowledgedStanzas[++d->lastOutgoingSequenceNumber] = data;
// send packet
bool success = sendData(data);
if (isXmppStanza)
sendAcknowledgementRequest();
return success;
}
///
/// Returns the QSslSocket used for this stream.
///
QSslSocket *QXmppStream::socket() const
{
return d->socket;
}
///
/// Sets the QSslSocket used for this stream.
///
void QXmppStream::setSocket(QSslSocket *socket)
{
d->socket = socket;
if (!d->socket)
return;
// socket events
connect(socket, &QAbstractSocket::connected, this, &QXmppStream::_q_socketConnected);
connect(socket, &QSslSocket::encrypted, this, &QXmppStream::_q_socketEncrypted);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(socket, &QSslSocket::errorOccurred, this, &QXmppStream::_q_socketError);
#else
connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QSslSocket::error), this, &QXmppStream::_q_socketError);
#endif
connect(socket, &QIODevice::readyRead, this, &QXmppStream::_q_socketReadyRead);
}
void QXmppStream::_q_socketConnected()
{
info(QStringLiteral("Socket connected to %1 %2").arg(d->socket->peerAddress().toString(), QString::number(d->socket->peerPort())));
handleStart();
}
void QXmppStream::_q_socketEncrypted()
{
debug("Socket encrypted");
handleStart();
}
void QXmppStream::_q_socketError(QAbstractSocket::SocketError socketError)
{
Q_UNUSED(socketError);
warning(QStringLiteral("Socket error: ") + socket()->errorString());
}
void QXmppStream::_q_socketReadyRead()
{
d->dataBuffer.append(d->socket->readAll());
// handle whitespace pings
if (!d->dataBuffer.isEmpty() && d->dataBuffer.trimmed().isEmpty()) {
d->dataBuffer.clear();
handleStanza(QDomElement());
}
// FIXME : maybe these QRegExps could be static?
QRegExp startStreamRegex(R"(^(<\?xml.*\?>)?\s*<stream:stream.*>)");
startStreamRegex.setMinimal(true);
QRegExp endStreamRegex("</stream:stream>$");
endStreamRegex.setMinimal(true);
// check whether we need to add stream start / end elements
//
// NOTE: as we may only have partial XML content, do not alter the stream's
// state until we have a valid XML document!
QByteArray completeXml = d->dataBuffer;
const QString strData = QString::fromUtf8(d->dataBuffer);
bool streamStart = false;
if (d->streamStart.isEmpty() && startStreamRegex.indexIn(strData) != -1)
streamStart = true;
else
completeXml.prepend(d->streamStart);
bool streamEnd = false;
if (endStreamRegex.indexIn(strData) != -1)
streamEnd = true;
else
completeXml.append(streamRootElementEnd);
// check whether we have a valid XML document
QDomDocument doc;
if (!doc.setContent(completeXml, true))
return;
// remove data from buffer
logReceived(strData);
d->dataBuffer.clear();
// process stream start
if (streamStart) {
d->streamStart = startStreamRegex.cap(0).toUtf8();
handleStream(doc.documentElement());
}
// process stanzas
QDomElement nodeRecv = doc.documentElement().firstChildElement();
while (!nodeRecv.isNull()) {
if (QXmppStreamManagementAck::isStreamManagementAck(nodeRecv))
handleAcknowledgement(nodeRecv);
else if (QXmppStreamManagementReq::isStreamManagementReq(nodeRecv))
sendAcknowledgement();
else {
handleStanza(nodeRecv);
if (nodeRecv.tagName() == QLatin1String("message") ||
nodeRecv.tagName() == QLatin1String("presence") ||
nodeRecv.tagName() == QLatin1String("iq"))
++d->lastIncomingSequenceNumber;
}
nodeRecv = nodeRecv.nextSiblingElement();
}
// process stream end
if (streamEnd)
disconnectFromHost();
}
///
/// Enables Stream Management acks / reqs (\xep{0198}).
///
/// \param resetSequenceNumber Indicates if the sequence numbers should be
/// reset. This must be done if the stream is not resumed.
///
/// \since QXmpp 1.0
///
void QXmppStream::enableStreamManagement(bool resetSequenceNumber)
{
d->streamManagementEnabled = true;
if (resetSequenceNumber) {
d->lastOutgoingSequenceNumber = 0;
d->lastIncomingSequenceNumber = 0;
// resend unacked stanzas
if (!d->unacknowledgedStanzas.empty()) {
QMap<unsigned, QByteArray> oldUnackedStanzas = d->unacknowledgedStanzas;
d->unacknowledgedStanzas.clear();
for (QMap<unsigned, QByteArray>::iterator it = oldUnackedStanzas.begin(); it != oldUnackedStanzas.end(); ++it) {
d->unacknowledgedStanzas[++d->lastOutgoingSequenceNumber] = it.value();
sendData(it.value());
}
sendAcknowledgementRequest();
}
} else {
// resend unacked stanzas
if (!d->unacknowledgedStanzas.empty()) {
for (QMap<unsigned, QByteArray>::iterator it = d->unacknowledgedStanzas.begin(); it != d->unacknowledgedStanzas.end(); ++it)
sendData(it.value());
sendAcknowledgementRequest();
}
}
}
///
/// Returns the sequence number of the last incoming stanza (\xep{0198}).
///
/// \since QXmpp 1.0
///
unsigned QXmppStream::lastIncomingSequenceNumber() const
{
return d->lastIncomingSequenceNumber;
}
///
/// Sets the last acknowledged sequence number for outgoing stanzas
/// (\xep{0198}).
///
/// \since QXmpp 1.0
///
void QXmppStream::setAcknowledgedSequenceNumber(unsigned sequenceNumber)
{
for (QMap<unsigned, QByteArray>::iterator it = d->unacknowledgedStanzas.begin(); it != d->unacknowledgedStanzas.end();) {
if (it.key() <= sequenceNumber)
it = d->unacknowledgedStanzas.erase(it);
else
++it;
}
}
///
/// Handles an incoming acknowledgement from \xep{0198}.
///
/// \param element
///
/// \since QXmpp 1.0
///
void QXmppStream::handleAcknowledgement(QDomElement &element)
{
if (!d->streamManagementEnabled)
return;
QXmppStreamManagementAck ack;
ack.parse(element);
setAcknowledgedSequenceNumber(ack.seqNo());
}
///
/// Sends an acknowledgement as defined in \xep{0198}.
///
/// \since QXmpp 1.0
///
void QXmppStream::sendAcknowledgement()
{
if (!d->streamManagementEnabled)
return;
// prepare packet
QByteArray data;
QXmlStreamWriter xmlStream(&data);
QXmppStreamManagementAck ack(d->lastIncomingSequenceNumber);
ack.toXml(&xmlStream);
// send packet
sendData(data);
}
///
/// Sends an acknowledgement request as defined in \xep{0198}.
///
/// \since QXmpp 1.0
///
void QXmppStream::sendAcknowledgementRequest()
{
if (!d->streamManagementEnabled)
return;
// prepare packet
QByteArray data;
QXmlStreamWriter xmlStream(&data);
QXmppStreamManagementReq::toXml(&xmlStream);
// send packet
sendData(data);
}
<commit_msg>QXmppStream: Refactor XML parsing, Replace deprecated QRegExp<commit_after>/*
* Copyright (C) 2008-2020 The QXmpp developers
*
* Authors:
* Manjeet Dahiya
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppStream.h"
#include "QXmppConstants_p.h"
#include "QXmppLogger.h"
#include "QXmppStanza.h"
#include "QXmppStreamManagement_p.h"
#include "QXmppUtils.h"
#include <QBuffer>
#include <QDomDocument>
#include <QHostAddress>
#include <QMap>
#include <QRegularExpression>
#include <QSslSocket>
#include <QStringList>
#include <QTime>
#include <QXmlStreamWriter>
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
static bool randomSeeded = false;
#endif
class QXmppStreamPrivate
{
public:
QXmppStreamPrivate();
QString dataBuffer;
QSslSocket *socket;
// incoming stream state
QString streamOpenElement;
bool streamManagementEnabled;
QMap<unsigned, QByteArray> unacknowledgedStanzas;
unsigned lastOutgoingSequenceNumber;
unsigned lastIncomingSequenceNumber;
};
QXmppStreamPrivate::QXmppStreamPrivate()
: socket(nullptr), streamManagementEnabled(false), lastOutgoingSequenceNumber(0), lastIncomingSequenceNumber(0)
{
}
///
/// Constructs a base XMPP stream.
///
/// \param parent
///
QXmppStream::QXmppStream(QObject *parent)
: QXmppLoggable(parent),
d(new QXmppStreamPrivate)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
// Make sure the random number generator is seeded
if (!randomSeeded) {
qsrand(QTime(0, 0, 0).msecsTo(QTime::currentTime()) ^ reinterpret_cast<quintptr>(this));
randomSeeded = true;
}
#endif
}
///
/// Destroys a base XMPP stream.
///
QXmppStream::~QXmppStream()
{
delete d;
}
///
/// Disconnects from the remote host.
///
void QXmppStream::disconnectFromHost()
{
d->streamManagementEnabled = false;
if (d->socket) {
if (d->socket->state() == QAbstractSocket::ConnectedState) {
sendData(QByteArrayLiteral("</stream:stream>"));
d->socket->flush();
}
// FIXME: according to RFC 6120 section 4.4, we should wait for
// the incoming stream to end before closing the socket
d->socket->disconnectFromHost();
}
}
///
/// Handles a stream start event, which occurs when the underlying transport
/// becomes ready (socket connected, encryption started).
///
/// If you redefine handleStart(), make sure to call the base class's method.
///
void QXmppStream::handleStart()
{
d->streamManagementEnabled = false;
d->dataBuffer.clear();
d->streamOpenElement.clear();
}
///
/// Returns true if the stream is connected.
///
bool QXmppStream::isConnected() const
{
return d->socket &&
d->socket->state() == QAbstractSocket::ConnectedState;
}
///
/// Sends raw data to the peer.
///
/// \param data
///
bool QXmppStream::sendData(const QByteArray &data)
{
logSent(QString::fromUtf8(data));
if (!d->socket || d->socket->state() != QAbstractSocket::ConnectedState)
return false;
return d->socket->write(data) == data.size();
}
///
/// Sends an XMPP packet to the peer.
///
/// \param packet
///
bool QXmppStream::sendPacket(const QXmppStanza &packet)
{
// prepare packet
QByteArray data;
QXmlStreamWriter xmlStream(&data);
packet.toXml(&xmlStream);
bool isXmppStanza = packet.isXmppStanza();
if (isXmppStanza && d->streamManagementEnabled)
d->unacknowledgedStanzas[++d->lastOutgoingSequenceNumber] = data;
// send packet
bool success = sendData(data);
if (isXmppStanza)
sendAcknowledgementRequest();
return success;
}
///
/// Returns the QSslSocket used for this stream.
///
QSslSocket *QXmppStream::socket() const
{
return d->socket;
}
///
/// Sets the QSslSocket used for this stream.
///
void QXmppStream::setSocket(QSslSocket *socket)
{
d->socket = socket;
if (!d->socket)
return;
// socket events
connect(socket, &QAbstractSocket::connected, this, &QXmppStream::_q_socketConnected);
connect(socket, &QSslSocket::encrypted, this, &QXmppStream::_q_socketEncrypted);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(socket, &QSslSocket::errorOccurred, this, &QXmppStream::_q_socketError);
#else
connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QSslSocket::error), this, &QXmppStream::_q_socketError);
#endif
connect(socket, &QIODevice::readyRead, this, &QXmppStream::_q_socketReadyRead);
}
void QXmppStream::_q_socketConnected()
{
info(QStringLiteral("Socket connected to %1 %2").arg(d->socket->peerAddress().toString(), QString::number(d->socket->peerPort())));
handleStart();
}
void QXmppStream::_q_socketEncrypted()
{
debug("Socket encrypted");
handleStart();
}
void QXmppStream::_q_socketError(QAbstractSocket::SocketError socketError)
{
Q_UNUSED(socketError);
warning(QStringLiteral("Socket error: ") + socket()->errorString());
}
void QXmppStream::_q_socketReadyRead()
{
// As we may only have partial XML content, we need to cache the received
// data until it has been successfully parsed. In case it can't be parsed,
//
// There are only two small problems with the current strategy:
// * When we receive a full stanza + a partial one, we can't parse the
// first stanza until another stanza arrives that is complete.
// * We don't know when we received invalid XML (would cause a growing
// cache and a timeout after some time).
// However, both issues could only be solved using an XML stream reader
// which would cause many other problems since we don't actually use it for
// parsing the content.
d->dataBuffer.append(QString::fromUtf8(d->socket->readAll()));
//
// Check for whitespace pings
//
if (d->dataBuffer.isEmpty() || d->dataBuffer.trimmed().isEmpty()) {
d->dataBuffer.clear();
logReceived({});
handleStanza({});
return;
}
//
// Check whether we received a stream open or closing tag
//
static const QRegularExpression streamStartRegex(R"(^(<\?xml.*\?>)?\s*<stream:stream[^>]*>)");
static const QRegularExpression streamEndRegex("</stream:stream>$");
QRegularExpressionMatch streamOpenMatch;
bool hasStreamOpen = d->streamOpenElement.isEmpty() &&
(streamOpenMatch = streamStartRegex.match(d->dataBuffer)).hasMatch();
bool hasStreamClose = streamEndRegex.match(d->dataBuffer).hasMatch();
//
// The stream start/end and stanza packets can't be parsed without any
// modifications with QDomDocument. This is because of multiple reasons:
// * The <stream:stream> open element is not considered valid without the
// closing tag.
// * Only the closing tag is of course not valid too.
// * Stanzas/Nonzas need to have the correct stream namespaces set:
// * For being able to parse <stream:features/>
// * For having the correct namespace (e.g. 'jabber:client') set to
// stanzas and their child elements (e.g. <body/> of a message).
//
// The wrapping strategy looks like this:
// * The stream open tag is cached once it arrives, for later access
// * Incoming XML that has no <stream> open tag will be prepended by the
// cached <stream> tag.
// * Incoming XML that has no <stream> close tag will be appended by a
// generic string "</stream:stream>"
//
// The result is parsed by QDomDocument and the child elements of the stream
// are processed. In case the received data contained a stream open tag,
// the stream is processed (before the stanzas are processed). In case we
// received a </stream> closing tag, the connection is closed.
//
auto wrappedStanzas = d->dataBuffer;
if (!hasStreamOpen) {
wrappedStanzas.prepend(d->streamOpenElement);
}
if (!hasStreamClose) {
wrappedStanzas.append(QStringLiteral("</stream:stream>"));
}
//
// Try to parse the wrapped XML
//
QDomDocument doc;
if (!doc.setContent(wrappedStanzas, true))
return;
//
// Success: We can clear the buffer and send a 'received' log message
//
d->dataBuffer.clear();
logReceived(d->dataBuffer);
// process stream start
if (hasStreamOpen) {
d->streamOpenElement = streamOpenMatch.captured();
handleStream(doc.documentElement());
}
// process stanzas
QDomElement nodeRecv = doc.documentElement().firstChildElement();
while (!nodeRecv.isNull()) {
if (QXmppStreamManagementAck::isStreamManagementAck(nodeRecv))
handleAcknowledgement(nodeRecv);
else if (QXmppStreamManagementReq::isStreamManagementReq(nodeRecv))
sendAcknowledgement();
else {
handleStanza(nodeRecv);
if (nodeRecv.tagName() == QLatin1String("message") ||
nodeRecv.tagName() == QLatin1String("presence") ||
nodeRecv.tagName() == QLatin1String("iq"))
++d->lastIncomingSequenceNumber;
}
nodeRecv = nodeRecv.nextSiblingElement();
}
// process stream end
if (hasStreamClose) {
disconnectFromHost();
}
}
///
/// Enables Stream Management acks / reqs (\xep{0198}).
///
/// \param resetSequenceNumber Indicates if the sequence numbers should be
/// reset. This must be done if the stream is not resumed.
///
/// \since QXmpp 1.0
///
void QXmppStream::enableStreamManagement(bool resetSequenceNumber)
{
d->streamManagementEnabled = true;
if (resetSequenceNumber) {
d->lastOutgoingSequenceNumber = 0;
d->lastIncomingSequenceNumber = 0;
// resend unacked stanzas
if (!d->unacknowledgedStanzas.empty()) {
QMap<unsigned, QByteArray> oldUnackedStanzas = d->unacknowledgedStanzas;
d->unacknowledgedStanzas.clear();
for (QMap<unsigned, QByteArray>::iterator it = oldUnackedStanzas.begin(); it != oldUnackedStanzas.end(); ++it) {
d->unacknowledgedStanzas[++d->lastOutgoingSequenceNumber] = it.value();
sendData(it.value());
}
sendAcknowledgementRequest();
}
} else {
// resend unacked stanzas
if (!d->unacknowledgedStanzas.empty()) {
for (QMap<unsigned, QByteArray>::iterator it = d->unacknowledgedStanzas.begin(); it != d->unacknowledgedStanzas.end(); ++it)
sendData(it.value());
sendAcknowledgementRequest();
}
}
}
///
/// Returns the sequence number of the last incoming stanza (\xep{0198}).
///
/// \since QXmpp 1.0
///
unsigned QXmppStream::lastIncomingSequenceNumber() const
{
return d->lastIncomingSequenceNumber;
}
///
/// Sets the last acknowledged sequence number for outgoing stanzas
/// (\xep{0198}).
///
/// \since QXmpp 1.0
///
void QXmppStream::setAcknowledgedSequenceNumber(unsigned sequenceNumber)
{
for (QMap<unsigned, QByteArray>::iterator it = d->unacknowledgedStanzas.begin(); it != d->unacknowledgedStanzas.end();) {
if (it.key() <= sequenceNumber)
it = d->unacknowledgedStanzas.erase(it);
else
++it;
}
}
///
/// Handles an incoming acknowledgement from \xep{0198}.
///
/// \param element
///
/// \since QXmpp 1.0
///
void QXmppStream::handleAcknowledgement(QDomElement &element)
{
if (!d->streamManagementEnabled)
return;
QXmppStreamManagementAck ack;
ack.parse(element);
setAcknowledgedSequenceNumber(ack.seqNo());
}
///
/// Sends an acknowledgement as defined in \xep{0198}.
///
/// \since QXmpp 1.0
///
void QXmppStream::sendAcknowledgement()
{
if (!d->streamManagementEnabled)
return;
// prepare packet
QByteArray data;
QXmlStreamWriter xmlStream(&data);
QXmppStreamManagementAck ack(d->lastIncomingSequenceNumber);
ack.toXml(&xmlStream);
// send packet
sendData(data);
}
///
/// Sends an acknowledgement request as defined in \xep{0198}.
///
/// \since QXmpp 1.0
///
void QXmppStream::sendAcknowledgementRequest()
{
if (!d->streamManagementEnabled)
return;
// prepare packet
QByteArray data;
QXmlStreamWriter xmlStream(&data);
QXmppStreamManagementReq::toXml(&xmlStream);
// send packet
sendData(data);
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <fstream>
// Local includes
#include "mesh_data.h"
#include "mesh_base.h"
#include "xdr_cxx.h"
#include "elem.h"
namespace libMesh
{
//------------------------------------------------------
// MeshData functions
void MeshData::read_xdr (const std::string& name,
const XdrMODE mode)
{
/**
* This code implements the output of the MeshData
* object in XDR format. This warrants some documentation.
* The output consists of 8 sections:
*
* 1.) The name of the data stored, if provided (string)
*
* 2.) A switch whether real or complex data is stored (string)
*
* 3.) The number of nodes for which values are stored
* (unsigned int)
*
* 4.) The number of elements for which values are stored
* (unsigned int)
*
* for each node
*
* 5.) The foreign node id (unsigned int)
*
* 6.) The actual values (vector of real/complex)
*
* end node loop
*
* for each element
*
* 7.) The foreign element id (unsigned int)
*
* 8.) The actual values (vector of real/complex)
*
* end node loop
*
* Note that the actual IO is handled through the Xdr class
* (to be renamed later?) which provides a uniform interface to
* both the XDR (eXternal Data Representation) interface and standard
* ASCII output. Thus this one section of code will write XDR or ASCII
* files with no changes.
*/
// we should better be active or in compatibility mode
libmesh_assert (_active || _compatibility_mode);
// make sure the id maps are ready
libmesh_assert (_node_id_map_closed);
libmesh_assert (_elem_id_map_closed);
/**
* clear the data, but keep the id maps
*/
this->clear();
Xdr io(name, mode);
/*
* all processors read the data in the same format,
* but only the processor that owns the element stores
* element-associated data. For nodes, i haven't come
* up with such asmart idea, yet... :-P
*/
const unsigned int proc_id = _mesh.processor_id();
/**
* 1.)
*
* Read the descriptive name
*/
{
std::string desc = "";
io.data (desc);
this->_data_descriptor = desc;
}
/**
* 2.)
*
* Read: either real or complex
*/
{
std::string vtype="";
io.data (vtype);
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
if (vtype != "COMPLEX")
{
libMesh::err << "ERROR: File does not contain complex-valued data!"
<< std::endl;
libmesh_error();
}
#elif LIBMESH_USE_REAL_NUMBERS
if (vtype != "REAL")
{
libMesh::err << "ERROR: File does not contain real-valued data!"
<< std::endl;
libmesh_error();
}
#else
/*
* What number type is this?
*/
libmesh_error();
#endif
}
/**
* 3.)
*
* Read the number of nodes for which data is there
*/
unsigned int n_node = 0;
io.data (n_node);
/**
* 4.)
*
* Read the number of elements for which data is there
*/
unsigned int n_elem = 0;
io.data (n_elem);
unsigned int previous_values_size = 0;
for (unsigned int n_cnt=0; n_cnt < n_node; n_cnt++)
{
/**
* 5.)
*
* Read the foreign node id, locate the
* Node* associated with this foreign id
*/
unsigned int f_id = 0;
io.data (f_id);
const Node* node = foreign_id_to_node(f_id);
/**
* 6.)
*
* the actual values for this node, Xdr knows
* the length
*/
{
std::vector<Number> values;
io.data (values);
#ifdef DEBUG
/*
* make sure the size of the values vectors
* are identical for all nodes
*/
if (n_cnt == 0)
previous_values_size = values.size();
else
{
if (previous_values_size != values.size())
{
libMesh::err << "ERROR: Size mismatch for n_cnt = " << n_cnt << std::endl;
libmesh_error();
}
}
#endif
/**
* insert this node and the values in the _node_data
*/
_node_data.insert (std::make_pair(node, values));
}
}
previous_values_size = 0;
for (unsigned int n_cnt=0; n_cnt < n_elem; n_cnt++)
{
/**
* 7.)
*
* Read the foreign elem id, locate the Elem*
*/
unsigned int f_id = 0;
io.data (f_id);
const Elem* elem = foreign_id_to_elem(f_id);
/**
* 8.)
*
* the actual values for this elem, Xdr knows
* how many
*/
{
std::vector<Number> values;
io.data (values);
#ifdef DEBUG
/*
* make sure the size of the values vectors
* are identical for all elements
*/
if (n_cnt == 0)
previous_values_size = values.size();
else
{
if (previous_values_size != values.size())
{
libMesh::err << "ERROR: Size mismatch for n_cnt = " << n_cnt << std::endl;
libmesh_error();
}
}
#endif
/**
* insert this elem and the values in our _elem_data
* @e only when we own this element!
*/
if (elem->processor_id() == proc_id)
_elem_data.insert (std::make_pair(elem, values));
}
}
/*
* finished reading. Now ready for use, provided
* there was any data contained in the file.
*/
libmesh_assert ((this->_node_data.size() != 0) || (this->_elem_data.size() != 0));
this->_node_data_closed = true;
this->_elem_data_closed = true;
}
void MeshData::write_xdr (const std::string& name,
const XdrMODE mode)
{
/**
* This code implements the output of the MeshData
* object in XDR format. This warrants some documentation.
* The output consists of 8 sections:
*
* 1.) The name of the data stored, if provided (string)
*
* 2.) A switch whether real or complex data is stored (string)
*
* 3.) The number of nodes for which values are stored
* (unsigned int)
*
* 4.) The number of elements for which values are stored
* (unsigned int)
*
* for each node
*
* 5.) The foreign node id (unsigned int)
*
* 6.) The actual values (vector of real/complex)
*
* end node loop
*
* for each element
*
* 7.) The foreign element id (unsigned int)
*
* 8.) The actual values (vector of real/complex)
*
* end node loop
*
* Note that the actual IO is handled through the Xdr class
* (to be renamed later?) which provides a uniform interface to
* both the XDR (eXternal Data Representation) interface and standard
* ASCII output. Thus this one section of code will write XDR or ASCII
* files with no changes.
*/
/*
* make sure the id maps are ready
* and that we have data to write
*/
libmesh_assert (_node_id_map_closed);
libmesh_assert (_elem_id_map_closed);
libmesh_assert (_node_data_closed);
libmesh_assert (_elem_data_closed);
Xdr io(name, mode);
// all processors write the data in the same format
//const unsigned int proc_id = _mesh.processor_id();
/**
* 1.)
*
* Write the descriptive name
*/
{
std::string desc = this->_data_descriptor;
io.data (desc, "# Data description");
}
/**
* 2.)
*
* Write: either real or complex
*/
{
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
std::string desc = "COMPLEX";
#elif LIBMESH_USE_REAL_NUMBERS
std::string desc = "REAL";
#else
better_you_choke_this...
#endif
io.data (desc, "# type of values");
}
/**
* 3.)
*
* Write the number of nodes for which data is there
*/
{
unsigned int n_node = this->_node_data.size();
io.data (n_node, "# No. of nodes for which data is stored");
}
/**
* 4.)
*
* Write the number of elements for which data is there
*/
{
unsigned int n_elem = this->_elem_data.size();
io.data (n_elem, "# No. of elements for which data is stored");
}
std::map<const Node*,
std::vector<Number> >::const_iterator nit = _node_data.begin ();
for (; nit != _node_data.end(); ++nit)
{
const Node* node = (*nit).first;
/**
* 5.)
*
* Write the foreign node id
*/
{
unsigned int f_id = node_to_foreign_id (node);
io.data (f_id, "# Foreign node id");
}
/**
* 6.)
*
* the actual values for this node
*/
{
/*
* since we are iterating over our @e own
* map, this libmesh_assert should never break...
*/
libmesh_assert (this->has_data(node));
const std::vector<Number>& values = this->get_data(node);
/*
* copy the data to a local buf, since
* the Xdr class needs write access, even
* when only reading data
*/
std::vector<Number> buf = values;
io.data (buf, "# Values");
}
}
std::map<const Elem*,
std::vector<Number> >::const_iterator eit = _elem_data.begin ();
for (; eit != _elem_data.end(); ++eit)
{
const Elem* elem = (*eit).first;
/**
* 7.)
*
* Write the foreign element id
*/
{
unsigned int f_id = elem_to_foreign_id (elem);
io.data (f_id, "# Foreign element id");
}
/**
* 8.)
*
* the actual values for this element
*/
{
/*
* since we are iterating over our @e own
* map, this libmesh_assert should never break...
*/
libmesh_assert (this->has_data(elem));
const std::vector<Number>& values = this->get_data(elem);
/*
* copy the data to a local buf, since
* the Xdr class needs write access, even
* when only reading data
*/
std::vector<Number> buf = values;
io.data (buf, "# Values");
}
}
}
} // namespace libMesh
<commit_msg>Avoid "unused variables" warnings in non-debug modes<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <fstream>
// Local includes
#include "mesh_data.h"
#include "mesh_base.h"
#include "xdr_cxx.h"
#include "elem.h"
namespace libMesh
{
//------------------------------------------------------
// MeshData functions
void MeshData::read_xdr (const std::string& name,
const XdrMODE mode)
{
/**
* This code implements the output of the MeshData
* object in XDR format. This warrants some documentation.
* The output consists of 8 sections:
*
* 1.) The name of the data stored, if provided (string)
*
* 2.) A switch whether real or complex data is stored (string)
*
* 3.) The number of nodes for which values are stored
* (unsigned int)
*
* 4.) The number of elements for which values are stored
* (unsigned int)
*
* for each node
*
* 5.) The foreign node id (unsigned int)
*
* 6.) The actual values (vector of real/complex)
*
* end node loop
*
* for each element
*
* 7.) The foreign element id (unsigned int)
*
* 8.) The actual values (vector of real/complex)
*
* end node loop
*
* Note that the actual IO is handled through the Xdr class
* (to be renamed later?) which provides a uniform interface to
* both the XDR (eXternal Data Representation) interface and standard
* ASCII output. Thus this one section of code will write XDR or ASCII
* files with no changes.
*/
// we should better be active or in compatibility mode
libmesh_assert (_active || _compatibility_mode);
// make sure the id maps are ready
libmesh_assert (_node_id_map_closed);
libmesh_assert (_elem_id_map_closed);
/**
* clear the data, but keep the id maps
*/
this->clear();
Xdr io(name, mode);
/*
* all processors read the data in the same format,
* but only the processor that owns the element stores
* element-associated data. For nodes, i haven't come
* up with such asmart idea, yet... :-P
*/
const unsigned int proc_id = _mesh.processor_id();
/**
* 1.)
*
* Read the descriptive name
*/
{
std::string desc = "";
io.data (desc);
this->_data_descriptor = desc;
}
/**
* 2.)
*
* Read: either real or complex
*/
{
std::string vtype="";
io.data (vtype);
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
if (vtype != "COMPLEX")
{
libMesh::err << "ERROR: File does not contain complex-valued data!"
<< std::endl;
libmesh_error();
}
#elif LIBMESH_USE_REAL_NUMBERS
if (vtype != "REAL")
{
libMesh::err << "ERROR: File does not contain real-valued data!"
<< std::endl;
libmesh_error();
}
#else
/*
* What number type is this?
*/
libmesh_error();
#endif
}
/**
* 3.)
*
* Read the number of nodes for which data is there
*/
unsigned int n_node = 0;
io.data (n_node);
/**
* 4.)
*
* Read the number of elements for which data is there
*/
unsigned int n_elem = 0;
io.data (n_elem);
#ifdef DEBUG
unsigned int previous_values_size = 0;
#endif
for (unsigned int n_cnt=0; n_cnt < n_node; n_cnt++)
{
/**
* 5.)
*
* Read the foreign node id, locate the
* Node* associated with this foreign id
*/
unsigned int f_id = 0;
io.data (f_id);
const Node* node = foreign_id_to_node(f_id);
/**
* 6.)
*
* the actual values for this node, Xdr knows
* the length
*/
{
std::vector<Number> values;
io.data (values);
#ifdef DEBUG
/*
* make sure the size of the values vectors
* are identical for all nodes
*/
if (n_cnt == 0)
previous_values_size = values.size();
else
{
if (previous_values_size != values.size())
{
libMesh::err << "ERROR: Size mismatch for n_cnt = " << n_cnt << std::endl;
libmesh_error();
}
}
#endif
/**
* insert this node and the values in the _node_data
*/
_node_data.insert (std::make_pair(node, values));
}
}
#ifdef DEBUG
previous_values_size = 0;
#endif
for (unsigned int n_cnt=0; n_cnt < n_elem; n_cnt++)
{
/**
* 7.)
*
* Read the foreign elem id, locate the Elem*
*/
unsigned int f_id = 0;
io.data (f_id);
const Elem* elem = foreign_id_to_elem(f_id);
/**
* 8.)
*
* the actual values for this elem, Xdr knows
* how many
*/
{
std::vector<Number> values;
io.data (values);
#ifdef DEBUG
/*
* make sure the size of the values vectors
* are identical for all elements
*/
if (n_cnt == 0)
previous_values_size = values.size();
else
{
if (previous_values_size != values.size())
{
libMesh::err << "ERROR: Size mismatch for n_cnt = " << n_cnt << std::endl;
libmesh_error();
}
}
#endif
/**
* insert this elem and the values in our _elem_data
* @e only when we own this element!
*/
if (elem->processor_id() == proc_id)
_elem_data.insert (std::make_pair(elem, values));
}
}
/*
* finished reading. Now ready for use, provided
* there was any data contained in the file.
*/
libmesh_assert ((this->_node_data.size() != 0) || (this->_elem_data.size() != 0));
this->_node_data_closed = true;
this->_elem_data_closed = true;
}
void MeshData::write_xdr (const std::string& name,
const XdrMODE mode)
{
/**
* This code implements the output of the MeshData
* object in XDR format. This warrants some documentation.
* The output consists of 8 sections:
*
* 1.) The name of the data stored, if provided (string)
*
* 2.) A switch whether real or complex data is stored (string)
*
* 3.) The number of nodes for which values are stored
* (unsigned int)
*
* 4.) The number of elements for which values are stored
* (unsigned int)
*
* for each node
*
* 5.) The foreign node id (unsigned int)
*
* 6.) The actual values (vector of real/complex)
*
* end node loop
*
* for each element
*
* 7.) The foreign element id (unsigned int)
*
* 8.) The actual values (vector of real/complex)
*
* end node loop
*
* Note that the actual IO is handled through the Xdr class
* (to be renamed later?) which provides a uniform interface to
* both the XDR (eXternal Data Representation) interface and standard
* ASCII output. Thus this one section of code will write XDR or ASCII
* files with no changes.
*/
/*
* make sure the id maps are ready
* and that we have data to write
*/
libmesh_assert (_node_id_map_closed);
libmesh_assert (_elem_id_map_closed);
libmesh_assert (_node_data_closed);
libmesh_assert (_elem_data_closed);
Xdr io(name, mode);
// all processors write the data in the same format
//const unsigned int proc_id = _mesh.processor_id();
/**
* 1.)
*
* Write the descriptive name
*/
{
std::string desc = this->_data_descriptor;
io.data (desc, "# Data description");
}
/**
* 2.)
*
* Write: either real or complex
*/
{
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
std::string desc = "COMPLEX";
#elif LIBMESH_USE_REAL_NUMBERS
std::string desc = "REAL";
#else
better_you_choke_this...
#endif
io.data (desc, "# type of values");
}
/**
* 3.)
*
* Write the number of nodes for which data is there
*/
{
unsigned int n_node = this->_node_data.size();
io.data (n_node, "# No. of nodes for which data is stored");
}
/**
* 4.)
*
* Write the number of elements for which data is there
*/
{
unsigned int n_elem = this->_elem_data.size();
io.data (n_elem, "# No. of elements for which data is stored");
}
std::map<const Node*,
std::vector<Number> >::const_iterator nit = _node_data.begin ();
for (; nit != _node_data.end(); ++nit)
{
const Node* node = (*nit).first;
/**
* 5.)
*
* Write the foreign node id
*/
{
unsigned int f_id = node_to_foreign_id (node);
io.data (f_id, "# Foreign node id");
}
/**
* 6.)
*
* the actual values for this node
*/
{
/*
* since we are iterating over our @e own
* map, this libmesh_assert should never break...
*/
libmesh_assert (this->has_data(node));
const std::vector<Number>& values = this->get_data(node);
/*
* copy the data to a local buf, since
* the Xdr class needs write access, even
* when only reading data
*/
std::vector<Number> buf = values;
io.data (buf, "# Values");
}
}
std::map<const Elem*,
std::vector<Number> >::const_iterator eit = _elem_data.begin ();
for (; eit != _elem_data.end(); ++eit)
{
const Elem* elem = (*eit).first;
/**
* 7.)
*
* Write the foreign element id
*/
{
unsigned int f_id = elem_to_foreign_id (elem);
io.data (f_id, "# Foreign element id");
}
/**
* 8.)
*
* the actual values for this element
*/
{
/*
* since we are iterating over our @e own
* map, this libmesh_assert should never break...
*/
libmesh_assert (this->has_data(elem));
const std::vector<Number>& values = this->get_data(elem);
/*
* copy the data to a local buf, since
* the Xdr class needs write access, even
* when only reading data
*/
std::vector<Number> buf = values;
io.data (buf, "# Values");
}
}
}
} // namespace libMesh
<|endoftext|> |
<commit_before>// Copyright 2014 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 "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
static const char kMainWebrtcTestHtmlPage[] =
"/webrtc/webrtc_jsep01_test.html";
// These tests runs on real webcams and ensure WebRTC can acquire webcams
// correctly. They will do nothing if there are no webcams on the system.
// The webcam on the system must support up to 1080p, or the test will fail.
class WebRtcWebcamBrowserTest : public WebRtcTestBase {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
EXPECT_FALSE(command_line->HasSwitch(
switches::kUseFakeDeviceForMediaStream));
EXPECT_FALSE(command_line->HasSwitch(
switches::kUseFakeUIForMediaStream));
}
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
DetectErrorsInJavaScript(); // Look for errors in our rather complex js.
}
};
IN_PROC_BROWSER_TEST_F(WebRtcWebcamBrowserTest,
TestAcquiringAndReacquiringWebcam) {
ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
GURL url(embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
ui_test_utils::NavigateToURL(browser(), url);
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
if (!HasWebcamAvailableOnSystem(tab)) {
LOG(INFO) << "No webcam found on bot: skipping...";
return;
}
GetUserMediaWithSpecificConstraintsAndAccept(tab,
kAudioVideoCallConstraintsVGA);
StartDetectingVideo(tab, "local-view");
WaitForVideoToPlay(tab);
EXPECT_EQ("640x480", GetStreamSize(tab, "local-view"));
CloseLastLocalStream(tab);
GetUserMediaWithSpecificConstraintsAndAccept(tab,
kAudioVideoCallConstraintsQVGA);
StartDetectingVideo(tab, "local-view");
WaitForVideoToPlay(tab);
EXPECT_EQ("320x240", GetStreamSize(tab, "local-view"));
CloseLastLocalStream(tab);
GetUserMediaWithSpecificConstraintsAndAccept(tab,
kAudioVideoCallConstraints360p);
StartDetectingVideo(tab, "local-view");
WaitForVideoToPlay(tab);
EXPECT_EQ("640x360", GetStreamSize(tab, "local-view"));
CloseLastLocalStream(tab);
// Broken on all platforms for C920 webcams: see http://crbug.com/360512.
// GetUserMediaWithSpecificConstraintsAndAccept(tab,
// kAudioVideoCallConstraints720p);
// StartDetectingVideo(tab, "local-view");
// WaitForVideoToPlay(tab);
// EXPECT_EQ("1280x720", GetStreamSize(tab, "local-view"));
// CloseLastLocalStream(tab);
// GetUserMediaWithSpecificConstraintsAndAccept(tab,
// kAudioVideoCallConstraints1080p);
// StartDetectingVideo(tab, "local-view");
// WaitForVideoToPlay(tab);
// EXPECT_EQ("1920x1080", GetStreamSize(tab, "local-view"));
// CloseLastLocalStream(tab);
}
<commit_msg>Re-enabling WebRTC HD cam tests after Logitech C920 fix.<commit_after>// Copyright 2014 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 "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
static const char kMainWebrtcTestHtmlPage[] =
"/webrtc/webrtc_jsep01_test.html";
// These tests runs on real webcams and ensure WebRTC can acquire webcams
// correctly. They will do nothing if there are no webcams on the system.
// The webcam on the system must support up to 1080p, or the test will fail.
class WebRtcWebcamBrowserTest : public WebRtcTestBase {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
EXPECT_FALSE(command_line->HasSwitch(
switches::kUseFakeDeviceForMediaStream));
EXPECT_FALSE(command_line->HasSwitch(
switches::kUseFakeUIForMediaStream));
}
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
DetectErrorsInJavaScript(); // Look for errors in our rather complex js.
}
protected:
std::string GetUserMediaAndGetStreamSize(content::WebContents* tab,
const std::string& constraints) {
GetUserMediaWithSpecificConstraintsAndAccept(tab, constraints);
StartDetectingVideo(tab, "local-view");
WaitForVideoToPlay(tab);
std::string actual_stream_size = GetStreamSize(tab, "local-view");
CloseLastLocalStream(tab);
return actual_stream_size;
}
};
IN_PROC_BROWSER_TEST_F(WebRtcWebcamBrowserTest,
TestAcquiringAndReacquiringWebcam) {
ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
GURL url(embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage));
ui_test_utils::NavigateToURL(browser(), url);
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
if (!HasWebcamAvailableOnSystem(tab)) {
LOG(INFO) << "No webcam found on bot: skipping...";
return;
}
EXPECT_EQ("640x480",
GetUserMediaAndGetStreamSize(tab, kAudioVideoCallConstraintsVGA));
EXPECT_EQ("320x240",
GetUserMediaAndGetStreamSize(tab, kAudioVideoCallConstraintsQVGA));
EXPECT_EQ("640x360",
GetUserMediaAndGetStreamSize(tab, kAudioVideoCallConstraints360p));
EXPECT_EQ("1280x720",
GetUserMediaAndGetStreamSize(tab, kAudioVideoCallConstraints720p));
EXPECT_EQ("1920x1080",
GetUserMediaAndGetStreamSize(tab, kAudioVideoCallConstraints1080p));
}
<|endoftext|> |
<commit_before>#include "ovpCBoxAlgorithmSoundPlayer.h"
#if defined OVP_OS_Windows
#include <windows.h>
#include <mmsystem.h>
#endif
#if defined OVP_OS_Linux
#include <unistd.h>
#endif
#include <string>
#include <cstdlib>
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Stimulation;
using namespace std;
boolean CBoxAlgorithmSoundPlayer::initialize(void)
{
IBox& l_rStaticBoxContext=this->getStaticBoxContext();
m_pStreamDecoder=&getAlgorithmManager().getAlgorithm(getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder));
m_pStreamDecoder->initialize();
for(uint32 i=0; i<l_rStaticBoxContext.getSettingCount(); i+=2)
{
uint64 l_ui64StimulationIdentifier=FSettingValueAutoCast(*this->getBoxAlgorithmContext(), i);
CString l_sSoundFilename=FSettingValueAutoCast(*this->getBoxAlgorithmContext(), i+1);
m_vSoundInfo[l_ui64StimulationIdentifier].push_back(l_sSoundFilename);
}
return true;
}
boolean CBoxAlgorithmSoundPlayer::uninitialize(void)
{
m_pStreamDecoder->uninitialize();
getAlgorithmManager().releaseAlgorithm(*m_pStreamDecoder);
return true;
}
boolean CBoxAlgorithmSoundPlayer::processInput(uint32 ui32InputIndex)
{
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CBoxAlgorithmSoundPlayer::process(void)
{
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
std::map < uint64, std::vector < CString > >::const_iterator it;
std::vector < CString >::const_iterator it2;
for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++)
{
TParameterHandler < const IMemoryBuffer* > l_ipMemoryBuffer(m_pStreamDecoder->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode));
l_ipMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i);
m_pStreamDecoder->process();
if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader))
{
}
if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer))
{
TParameterHandler < IStimulationSet* > l_opStimulationSet(m_pStreamDecoder->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet));
for(uint32 j=0; j<l_opStimulationSet->getStimulationCount(); j++)
{
it=m_vSoundInfo.find(l_opStimulationSet->getStimulationIdentifier(j));
if(it!=m_vSoundInfo.end())
{
for(it2=it->second.begin(); it2!=it->second.end(); it2++)
{
#if defined OVP_OS_Windows
::sndPlaySound(it2->toASCIIString(), SND_NOSTOP | SND_ASYNC );
#elif defined OVP_OS_Linux
string l_sCommand;
l_sCommand+="cat ";
l_sCommand+=it2->toASCIIString();
l_sCommand+=" > /dev/dsp &";
int l_iResult=::system(l_sCommand.c_str());
#else
getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "Sound player not yet implemented for this OS\n";
#endif
}
}
}
}
if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd))
{
}
l_rDynamicBoxContext.markInputAsDeprecated(0, i);
}
return true;
}
<commit_msg><commit_after>#include "ovpCBoxAlgorithmSoundPlayer.h"
#if defined OVP_OS_Windows
#include <windows.h>
#include <mmsystem.h>
#endif
#if defined OVP_OS_Linux
#include <unistd.h>
#endif
#include <string>
#include <cstdlib>
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Stimulation;
using namespace std;
#define boolean OpenViBE::boolean
boolean CBoxAlgorithmSoundPlayer::initialize(void)
{
IBox& l_rStaticBoxContext=this->getStaticBoxContext();
m_pStreamDecoder=&getAlgorithmManager().getAlgorithm(getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder));
m_pStreamDecoder->initialize();
for(uint32 i=0; i<l_rStaticBoxContext.getSettingCount(); i+=2)
{
uint64 l_ui64StimulationIdentifier=FSettingValueAutoCast(*this->getBoxAlgorithmContext(), i);
CString l_sSoundFilename=FSettingValueAutoCast(*this->getBoxAlgorithmContext(), i+1);
m_vSoundInfo[l_ui64StimulationIdentifier].push_back(l_sSoundFilename);
}
return true;
}
boolean CBoxAlgorithmSoundPlayer::uninitialize(void)
{
m_pStreamDecoder->uninitialize();
getAlgorithmManager().releaseAlgorithm(*m_pStreamDecoder);
return true;
}
boolean CBoxAlgorithmSoundPlayer::processInput(uint32 ui32InputIndex)
{
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CBoxAlgorithmSoundPlayer::process(void)
{
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
std::map < uint64, std::vector < CString > >::const_iterator it;
std::vector < CString >::const_iterator it2;
for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++)
{
TParameterHandler < const IMemoryBuffer* > l_ipMemoryBuffer(m_pStreamDecoder->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode));
l_ipMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i);
m_pStreamDecoder->process();
if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader))
{
}
if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer))
{
TParameterHandler < IStimulationSet* > l_opStimulationSet(m_pStreamDecoder->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet));
for(uint32 j=0; j<l_opStimulationSet->getStimulationCount(); j++)
{
it=m_vSoundInfo.find(l_opStimulationSet->getStimulationIdentifier(j));
if(it!=m_vSoundInfo.end())
{
for(it2=it->second.begin(); it2!=it->second.end(); it2++)
{
#if defined OVP_OS_Windows
::sndPlaySound(it2->toASCIIString(), SND_NOSTOP | SND_ASYNC );
#elif defined OVP_OS_Linux
string l_sCommand;
l_sCommand+="cat ";
l_sCommand+=it2->toASCIIString();
l_sCommand+=" > /dev/dsp &";
int l_iResult=::system(l_sCommand.c_str());
#else
getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "Sound player not yet implemented for this OS\n";
#endif
}
}
}
}
if(m_pStreamDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd))
{
}
l_rDynamicBoxContext.markInputAsDeprecated(0, i);
}
return true;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Abhishek Agrawal ([email protected])
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
// This code will convert multiple cartesian state vectors
// into TLE and check where exactly the Atom is failing. The cartesian
// vectors are generated by converting randomly generated keplerian elements.
// The conversion is achieved through the pykep library of ESA.
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <fstream>
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_vector.h>
#include <libsgp4/DateTime.h>
#include <libsgp4/Eci.h>
#include <libsgp4/Globals.h>
#include <libsgp4/SGP4.h>
#include <libsgp4/Tle.h>
#include <Astro/astro.hpp>
#include <SML/sml.hpp>
#include <Atom/printFunctions.hpp>
#include <Astro/orbitalElementConversions.hpp>
#include <Atom/convertCartesianStateToTwoLineElements.hpp>
#include "CppProject/randomKepElem.hpp"
typedef double Real;
typedef std::vector< Real > Vector6;
typedef std::vector< Real > Vector3;
typedef std::vector< Real > Vector2;
typedef std::vector < std::vector < Real > > Vector2D;
int main(void)
{
// some constants
// earth radius
// grav. parameter 'mu' of earth
// value of Pi
// initialize input parameters for the function generating random orbital elements. Description can be
// found in randomKepElem.hpp for each of the following parameters.
const Vector2 range_a = { 0, 1 };
const Vector2 range_e = { 0, 1 };
const Vector2 range_i = { 0, 1 };
const Vector2 range_raan = { 0, 1 };
const Vector2 range_w = { 0, 1 };
const Vector2 range_E = { 0, 1 };
const int limit = 100;
Vector2D randKepElem( limit, std::vector< Real >( 6 ) );
// call the function to generate random keplerian orbital elements. Values are stored in randKepElem in a 2D
// vector format. A single row represents one set of orbital elements, arranged in the same order as the
// input argument order of the elements.
randomKepElem::randomKepElem( range_a, range_e, range_i, range_raan, range_w, range_E, limit, randKepElem );
// test output to check if the random numbers are generated without any errors
std::cout << randKepElem[ 0 ][ 1 ] << std::endl;
//store randomly generated keplerian element sets into a CSV file for easy viewing and use in future debugging of ATOM
std::ofstream RandomKepElemFile;
RandomKepElemFile.open("RandomKepElemFile.csv"); //file will be overwritten each time the code is run unless the name is changed here and the code recompiled
for(int i = 0; i < limit; i++)
{
for(int j = 0; j < 6; j++)
{
RandomKepElemFile << randKepElem[ i ][ j ] << ",";
}
RandomKepElemFile << std::endl;
}
RandomKepElemFile.close();
// generate sets of cartesian elements corresponding to each of the psuedo random orbital element set.
// The conversion from keplerian elements to the cartesian elements is done using the PyKep library from ESA.
// Tle convertedTle = atom::convertCartesianStateToTwoLineElements< Real, Vector6 >( cartesianState, DateTime( ) );
// std::cout << convertedTle << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>added column headings in the CSV file which stores the randomly generated keplerian elements<commit_after>/*
* Copyright (c) 2016 Abhishek Agrawal ([email protected])
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
// This code will convert multiple cartesian state vectors
// into TLE and check where exactly the Atom is failing. The cartesian
// vectors are generated by converting randomly generated keplerian elements.
// The conversion is achieved through the pykep library of ESA.
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <fstream>
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_vector.h>
#include <libsgp4/DateTime.h>
#include <libsgp4/Eci.h>
#include <libsgp4/Globals.h>
#include <libsgp4/SGP4.h>
#include <libsgp4/Tle.h>
#include <Astro/astro.hpp>
#include <SML/sml.hpp>
#include <Atom/printFunctions.hpp>
#include <Astro/orbitalElementConversions.hpp>
#include <Atom/convertCartesianStateToTwoLineElements.hpp>
#include "CppProject/randomKepElem.hpp"
typedef double Real;
typedef std::vector< Real > Vector6;
typedef std::vector< Real > Vector3;
typedef std::vector< Real > Vector2;
typedef std::vector < std::vector < Real > > Vector2D;
int main(void)
{
// some constants values are defined here
// earth radius
// grav. parameter 'mu' of earth
// value of Pi
// initialize input parameters for the function generating random orbital elements. Description can be
// found in randomKepElem.hpp for each of the following parameters.
const Vector2 range_a = { 0, 10 };
const Vector2 range_e = { 20, 30 };
const Vector2 range_i = { 40, 50 };
const Vector2 range_raan = { 60, 70 };
const Vector2 range_w = { 80, 90 };
const Vector2 range_E = { 100, 110 };
const int limit = 100;
Vector2D randKepElem( limit, std::vector< Real >( 6 ) );
// call the function to generate random keplerian orbital elements. Values are stored in randKepElem in a 2D
// vector format. A single row represents one set of orbital elements, arranged in the same order as the
// input argument order of the elements.
randomKepElem::randomKepElem( range_a, range_e, range_i, range_raan, range_w, range_E, limit, randKepElem );
// test output to check if the random numbers are generated without any errors
std::cout << randKepElem[ 0 ][ 1 ] << std::endl;
//store randomly generated keplerian element sets into a CSV file for easy viewing and use in future debugging of ATOM
std::ofstream RandomKepElemFile;
RandomKepElemFile.open("RandomKepElemFile.csv"); //file will be overwritten each time the code is run unless the name is changed here and the code recompiled
RandomKepElemFile << "semi-major axis [km]" << "," << "eccentricity" << ",";
RandomKepElemFile << "Inclination [deg]" << "," << "RAAN [deg]" << ",";
RandomKepElemFile << "AOP [deg]" << "," << "Eccentric Anomaly [deg]" << std::endl;
for(int i = 0; i < limit; i++)
{
for(int j = 0; j < 6; j++)
{
RandomKepElemFile << randKepElem[ i ][ j ] << ",";
}
RandomKepElemFile << std::endl;
}
RandomKepElemFile.close();
// generate sets of cartesian elements corresponding to each of the psuedo random orbital element set.
// The conversion from keplerian elements to the cartesian elements is done using the PyKep library from ESA.
// Tle convertedTle = atom::convertCartesianStateToTwoLineElements< Real, Vector6 >( cartesianState, DateTime( ) );
// std::cout << convertedTle << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>///
/// @file AC_mpi.cpp
/// @brief Implementation of the A + C formulas (from Xavier Gourdon's
/// algorithm) that have been distributed using MPI (Message
/// Passing Interface) and multi-threaded using OpenMP.
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <SegmentedPiTable.hpp>
#include <primecount-internal.hpp>
#include <mpi_reduce_sum.hpp>
#include <fast_div.hpp>
#include <for_atomic.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <print.hpp>
#include <StatusAC.hpp>
#include <stdint.h>
#include <atomic>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
/// Compute the A formula.
/// pi[x_star] < b <= pi[x^(1/3)]
/// x / (primes[b] * primes[i]) < x^(1/2)
///
template <typename T,
typename Primes>
T A(T x,
T xlow,
T xhigh,
uint64_t y,
uint64_t b,
const Primes& primes,
const PiTable& pi,
const SegmentedPiTable& segmentedPi)
{
T sum = 0;
uint64_t prime = primes[b];
T xp = x / prime;
uint64_t sqrt_xp = (uint64_t) isqrt(xp);
uint64_t min_2nd_prime = min(xhigh / prime, sqrt_xp);
uint64_t max_2nd_prime = min(xlow / prime, sqrt_xp);
uint64_t i = pi[max(prime, min_2nd_prime)] + 1;
uint64_t max_i1 = pi[min(xp / y, max_2nd_prime)];
uint64_t max_i2 = pi[max_2nd_prime];
// x / (p * q) >= y
for (; i <= max_i1; i++)
{
uint64_t xpq = fast_div64(xp, primes[i]);
sum += segmentedPi[xpq];
}
// x / (p * q) < y
for (; i <= max_i2; i++)
{
uint64_t xpq = fast_div64(xp, primes[i]);
sum += segmentedPi[xpq] * 2;
}
return sum;
}
/// Compute the 1st part of the C formula.
/// pi[(x/z)^(1/3)] < b <= pi[sqrt(z)]
/// x / (primes[b] * m) <= z
///
/// m may be a prime <= y or a square free number <= z which is
/// coprime to the first b primes and whose largest prime factor <= y.
/// This algorithm recursively iterates over the square free numbers
/// coprime to the first b primes. This algorithm is described in
/// section 2.2 of the paper: Douglas Staple, "The Combinatorial
/// Algorithm For Computing pi(x)", arXiv:1503.01839, 6 March 2015.
///
template <int MU,
typename T,
typename Primes>
T C1(T xp,
uint64_t b,
uint64_t i,
uint64_t pi_y,
uint64_t m,
uint64_t min_m,
uint64_t max_m,
const Primes& primes,
const PiTable& pi)
{
T sum = 0;
for (i++; i <= pi_y; i++)
{
// Calculate next m
T m128 = (T) m * primes[i];
if (m128 > max_m)
return sum;
uint64_t m64 = (uint64_t) m128;
if (m64 > min_m) {
uint64_t xpm = fast_div64(xp, m64);
T phi_xpm = pi[xpm] - b + 2;
sum += phi_xpm * MU;
}
sum += C1<-MU>(xp, b, i, pi_y, m64, min_m, max_m, primes, pi);
}
return sum;
}
/// Compute the 2nd part of the C formula.
/// pi[sqrt(z)] < b <= pi[x_star]
/// x / (primes[b] * primes[i]) < x^(1/2)
///
template <typename T,
typename Primes>
T C2(T x,
T xlow,
T xhigh,
uint64_t y,
uint64_t b,
const Primes& primes,
const PiTable& pi,
const SegmentedPiTable& segmentedPi)
{
T sum = 0;
uint64_t prime = primes[b];
T xp = x / prime;
uint64_t max_m = min3(xlow / prime, xp / prime, y);
T min_m128 = max3(xhigh / prime, xp / (prime * prime), prime);
uint64_t min_m = min(min_m128, max_m);
uint64_t i = pi[max_m];
uint64_t pi_min_m = pi[min_m];
uint64_t min_clustered = (uint64_t) isqrt(xp);
min_clustered = in_between(min_m, min_clustered, max_m);
uint64_t pi_min_clustered = pi[min_clustered];
// Find all clustered easy leaves where
// successive leaves are identical.
// n = primes[b] * primes[i]
// Which satisfy: n > z && primes[i] <= y
while (i > pi_min_clustered)
{
uint64_t xpq = fast_div64(xp, primes[i]);
uint64_t phi_xpq = segmentedPi[xpq] - b + 2;
uint64_t xpq2 = fast_div64(xp, primes[b + phi_xpq - 1]);
uint64_t i2 = segmentedPi[xpq2];
sum += phi_xpq * (i - i2);
i = i2;
}
// Find all sparse easy leaves where
// successive leaves are different.
// n = primes[b] * primes[i]
// Which satisfy: n > z && primes[i] <= y
for (; i > pi_min_m; i--)
{
uint64_t xpq = fast_div64(xp, primes[i]);
sum += segmentedPi[xpq] - b + 2;
}
return sum;
}
/// Compute A + C
template <typename T,
typename Primes>
T AC_OpenMP(T x,
int64_t y,
int64_t z,
int64_t k,
int64_t x_star,
int64_t max_a_prime,
const Primes& primes,
int threads)
{
T sum = 0;
int64_t x13 = iroot<3>(x);
int64_t sqrtx = isqrt(x);
int64_t thread_threshold = 1000;
threads = ideal_num_threads(threads, x13, thread_threshold);
StatusAC status(x);
// PiTable's size >= z because of the C1 formula.
// We could use segmentation for the C1 formula but this
// would not increase overall performance (because C1
// computes very quickly) and the overall memory usage
// would also not much be reduced.
PiTable pi(max(z, max_a_prime), threads);
// SegmentedPiTable's size >= y because of the C2 formula.
// The C2 algorithm can be modified to work with smaller segment
// sizes such as x^(1/3) which improves the cache efficiency.
// However using a segment size < y deteriorates the algorithm's
// runtime complexity by a factor of log(x).
SegmentedPiTable segmentedPi(sqrtx, y, threads);
int64_t pi_y = pi[y];
int64_t pi_sqrtz = pi[isqrt(z)];
int64_t pi_x_star = pi[x_star];
int64_t pi_x13 = pi[x13];
int64_t pi_root3_xy = pi[iroot<3>(x / y)];
int64_t pi_root3_xz = pi[iroot<3>(x / z)];
int64_t min_c1 = max(k, pi_root3_xz) + 1;
int proc_id = mpi_proc_id();
int procs = mpi_num_procs();
atomic<int64_t> atomic_a(-1);
atomic<int64_t> atomic_c1(-1);
atomic<int64_t> atomic_c2(-1);
// In order to reduce the thread creation & destruction
// overhead we reuse the same threads throughout the
// entire computation. The same threads are used for:
//
// 1) Computation of the C1 formula.
// 2) Initialization of the segmentedPi lookup table.
// 3) Computation of the C2 formula.
// 4) Computation of the A formula.
//
#pragma omp parallel num_threads(threads) reduction(+: sum)
{
// C1 formula: pi[(x/z)^(1/3)] < b <= pi[pi_sqrtz]
for_atomic_add(min_c1 + proc_id, b <= pi_sqrtz, procs, atomic_c1)
{
int64_t prime = primes[b];
T xp = x / prime;
int64_t max_m = min(xp / prime, z);
T min_m128 = max(xp / (prime * prime), z / prime);
int64_t min_m = min(min_m128, max_m);
sum -= C1<-1>(xp, b, b, pi_y, 1, min_m, max_m, primes, pi);
status.print(b, pi_x13);
}
// This computes A and the 2nd part of the C formula.
// Find all special leaves of type:
// x / (primes[b] * primes[i]) < x^(1/2)
// where b is bounded by pi[z^(1/2)] < b <= pi[x^(1/3)].
// Since we need to lookup PrimePi[n] values for n < x^(1/2)
// we use a segmented PrimePi[n] table of size y
// (y = O(x^(1/3) * log(x)^3)) to reduce the memory usage.
while (segmentedPi.low() < sqrtx)
{
// Current segment [low, high[
segmentedPi.init();
int64_t low = segmentedPi.low();
int64_t high = segmentedPi.high();
T xlow = x / max(low, 1);
T xhigh = x / high;
int64_t min_c2 = max(k, pi_root3_xy);
min_c2 = max(min_c2, pi_sqrtz);
min_c2 = max(min_c2, pi[isqrt(low)]);
min_c2 = max(min_c2, pi[min(xhigh / y, x_star)]);
min_c2 += 1;
// Upper bound of A & C2 formulas:
// x / (p * q) >= low
// p * next_prime(p) <= x / low
// p <= sqrt(x / low)
T sqrt_xlow = isqrt(xlow);
int64_t max_c2 = pi[min(sqrt_xlow, x_star)];
int64_t max_b = pi[min(sqrt_xlow, x13)];
// C2 formula: pi[sqrt(z)] < b <= pi[x_star]
for_atomic_add(min_c2 + proc_id, b <= max_c2, procs, atomic_c2)
{
sum += C2(x, xlow, xhigh, y, b, primes, pi, segmentedPi);
status.print(b, max_b);
}
// A formula: pi[x_star] < b <= pi[x13]
for_atomic_add(pi_x_star + 1 + proc_id, b <= max_b, procs, atomic_a)
{
sum += A(x, xlow, xhigh, y, b, primes, pi, segmentedPi);
status.print(b, max_b);
}
// Is this the last segment?
if (high >= sqrtx)
break;
// Wait until all threads have finished
// computing the current segment.
#pragma omp barrier
#pragma omp master
{
segmentedPi.next();
status.next();
atomic_a = -1;
atomic_c2 = -1;
}
#pragma omp barrier
}
}
sum = mpi_reduce_sum(sum);
return sum;
}
} // namespace
namespace primecount {
int64_t AC_mpi(int64_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== AC_mpi(x, y) ===");
print_gourdon_vars(x, y, z, k, threads);
double time = get_time();
int64_t x_star = get_x_star_gourdon(x, y);
int64_t max_c_prime = y;
int64_t max_a_prime = (int64_t) isqrt(x / x_star);
int64_t max_prime = max(max_a_prime, max_c_prime);
auto primes = generate_primes<uint32_t>(max_prime);
int64_t sum = AC_OpenMP((uint64_t) x, y, z, k, x_star, max_a_prime, primes, threads);
print("A + C", sum, time);
return sum;
}
#ifdef HAVE_INT128_T
int128_t AC_mpi(int128_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== AC_mpi(x, y) ===");
print_gourdon_vars(x, y, z, k, threads);
double time = get_time();
int64_t x_star = get_x_star_gourdon(x, y);
int64_t max_c_prime = y;
int64_t max_a_prime = (int64_t) isqrt(x / x_star);
int64_t max_prime = max(max_a_prime, max_c_prime);
int128_t sum;
// uses less memory
if (max_prime <= numeric_limits<uint32_t>::max())
{
auto primes = generate_primes<uint32_t>(max_prime);
sum = AC_OpenMP((uint128_t) x, y, z, k, x_star, max_a_prime, primes, threads);
}
else
{
auto primes = generate_primes<uint64_t>(max_prime);
sum = AC_OpenMP((uint128_t) x, y, z, k, x_star, max_a_prime, primes, threads);
}
print("A + C", sum, time);
return sum;
}
#endif
} // namespace
<commit_msg>Update to new algo<commit_after>///
/// @file AC_mpi.cpp
/// @brief Implementation of the A + C formulas (from Xavier Gourdon's
/// algorithm) that have been distributed using MPI (Message
/// Passing Interface) and multi-threaded using OpenMP.
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <SegmentedPiTable.hpp>
#include <primecount-internal.hpp>
#include <LoadBalancerAC.hpp>
#include <mpi_reduce_sum.hpp>
#include <fast_div.hpp>
#include <for_atomic.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <print.hpp>
#include <StatusAC.hpp>
#include <stdint.h>
#include <atomic>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
/// Compute the A formula.
/// pi[x_star] < b <= pi[x^(1/3)]
/// x / (primes[b] * primes[i]) < x^(1/2)
///
template <typename T,
typename Primes>
T A(T x,
T xlow,
T xhigh,
uint64_t y,
uint64_t b,
const Primes& primes,
const PiTable& pi,
const SegmentedPiTable& segmentedPi)
{
T sum = 0;
uint64_t prime = primes[b];
T xp = x / prime;
uint64_t sqrt_xp = (uint64_t) isqrt(xp);
uint64_t min_2nd_prime = min(xhigh / prime, sqrt_xp);
uint64_t max_2nd_prime = min(xlow / prime, sqrt_xp);
uint64_t i = pi[max(prime, min_2nd_prime)] + 1;
uint64_t max_i1 = pi[min(xp / y, max_2nd_prime)];
uint64_t max_i2 = pi[max_2nd_prime];
// x / (p * q) >= y
for (; i <= max_i1; i++)
{
uint64_t xpq = fast_div64(xp, primes[i]);
sum += segmentedPi[xpq];
}
// x / (p * q) < y
for (; i <= max_i2; i++)
{
uint64_t xpq = fast_div64(xp, primes[i]);
sum += segmentedPi[xpq] * 2;
}
return sum;
}
/// Compute the 1st part of the C formula.
/// pi[(x/z)^(1/3)] < b <= pi[sqrt(z)]
/// x / (primes[b] * m) <= z
///
/// m may be a prime <= y or a square free number <= z which is
/// coprime to the first b primes and whose largest prime factor <= y.
/// This algorithm recursively iterates over the square free numbers
/// coprime to the first b primes. This algorithm is described in
/// section 2.2 of the paper: Douglas Staple, "The Combinatorial
/// Algorithm For Computing pi(x)", arXiv:1503.01839, 6 March 2015.
///
template <int MU,
typename T,
typename Primes>
T C1(T xp,
uint64_t b,
uint64_t i,
uint64_t pi_y,
uint64_t m,
uint64_t min_m,
uint64_t max_m,
const Primes& primes,
const PiTable& pi)
{
T sum = 0;
for (i++; i <= pi_y; i++)
{
// Calculate next m
T m128 = (T) m * primes[i];
if (m128 > max_m)
return sum;
uint64_t m64 = (uint64_t) m128;
if (m64 > min_m) {
uint64_t xpm = fast_div64(xp, m64);
T phi_xpm = pi[xpm] - b + 2;
sum += phi_xpm * MU;
}
sum += C1<-MU>(xp, b, i, pi_y, m64, min_m, max_m, primes, pi);
}
return sum;
}
/// Compute the 2nd part of the C formula.
/// pi[sqrt(z)] < b <= pi[x_star]
/// x / (primes[b] * primes[i]) < x^(1/2)
///
template <typename T,
typename Primes>
T C2(T x,
T xlow,
T xhigh,
uint64_t y,
uint64_t b,
const Primes& primes,
const PiTable& pi,
const SegmentedPiTable& segmentedPi)
{
T sum = 0;
uint64_t prime = primes[b];
T xp = x / prime;
uint64_t max_m = min3(xlow / prime, xp / prime, y);
T min_m128 = max3(xhigh / prime, xp / (prime * prime), prime);
uint64_t min_m = min(min_m128, max_m);
uint64_t i = pi[max_m];
uint64_t pi_min_m = pi[min_m];
uint64_t min_clustered = (uint64_t) isqrt(xp);
min_clustered = in_between(min_m, min_clustered, max_m);
uint64_t pi_min_clustered = pi[min_clustered];
// Find all clustered easy leaves where
// successive leaves are identical.
// n = primes[b] * primes[i]
// Which satisfy: n > z && primes[i] <= y
while (i > pi_min_clustered)
{
uint64_t xpq = fast_div64(xp, primes[i]);
uint64_t phi_xpq = segmentedPi[xpq] - b + 2;
uint64_t xpq2 = fast_div64(xp, primes[b + phi_xpq - 1]);
uint64_t i2 = pi[max(xpq2, min_clustered)];
sum += phi_xpq * (i - i2);
i = i2;
}
// Find all sparse easy leaves where
// successive leaves are different.
// n = primes[b] * primes[i]
// Which satisfy: n > z && primes[i] <= y
for (; i > pi_min_m; i--)
{
uint64_t xpq = fast_div64(xp, primes[i]);
sum += segmentedPi[xpq] - b + 2;
}
return sum;
}
/// Compute A + C
template <typename T,
typename Primes>
T AC_OpenMP(T x,
int64_t y,
int64_t z,
int64_t k,
int64_t x_star,
int64_t max_a_prime,
const Primes& primes,
bool is_print,
int threads)
{
T sum = 0;
int64_t x13 = iroot<3>(x);
int64_t sqrtx = isqrt(x);
int64_t thread_threshold = 1000;
threads = ideal_num_threads(threads, x13, thread_threshold);
LoadBalancerAC loadBalancer(sqrtx, x13, y, threads);
StatusAC status(is_print);
// PiTable's size = z because of the C1 formula.
// PiTable is accessed much less frequently than
// SegmentedPiTable, hence it is OK that PiTable's size
// is fairly large and does not fit into the CPU's cache.
PiTable pi(max(z, max_a_prime), threads);
int64_t pi_y = pi[y];
int64_t pi_sqrtz = pi[isqrt(z)];
int64_t pi_root3_xy = pi[iroot<3>(x / y)];
int64_t pi_root3_xz = pi[iroot<3>(x / z)];
int64_t min_c1 = max(k, pi_root3_xz) + 1;
atomic<int64_t> atomic_c1(-1);
int proc_id = mpi_proc_id();
int procs = mpi_num_procs();
// In order to reduce the thread creation & destruction
// overhead we reuse the same threads throughout the
// entire computation. The same threads are used for:
//
// 1) Computation of the C1 formula.
// 2) Computation of the C2 formula.
// 3) Computation of the A formula.
//
#pragma omp parallel num_threads(threads) reduction(+: sum)
{
// SegmentedPiTable is accessed very frequently.
// In order to get good performance it is important that
// SegmentedPiTable fits into the CPU's cache.
// Hence we use a small segment_size of x^(1/4).
SegmentedPiTable segmentedPi;
int64_t low, high;
// C1 formula: pi[(x/z)^(1/3)] < b <= pi[pi_sqrtz]
for_atomic_add(min_c1 + proc_id, b <= pi_sqrtz, procs, atomic_c1)
{
int64_t prime = primes[b];
T xp = x / prime;
int64_t max_m = min(xp / prime, z);
T min_m128 = max(xp / (prime * prime), z / prime);
int64_t min_m = min(min_m128, max_m);
sum -= C1<-1>(xp, b, b, pi_y, 1, min_m, max_m, primes, pi);
}
// for (low = 0; low < sqrt; low += segment_size)
while (loadBalancer.get_work(low, high))
{
// Current segment [low, high[
status.print(low, sqrtx, high - low);
segmentedPi.init(low, high);
T xlow = x / max(low, 1);
T xhigh = x / high;
int64_t min_c2 = max(k, pi_root3_xy);
min_c2 = max(min_c2, pi_sqrtz);
min_c2 = max(min_c2, pi[isqrt(low)]);
min_c2 = max(min_c2, pi[min(xhigh / y, x_star)]);
min_c2 += 1;
int64_t min_a = min(xhigh / high, x13);
min_a = pi[max(x_star, min_a)] + 1;
// Upper bound of A & C2 formulas:
// x / (p * q) >= low
// p * next_prime(p) <= x / low
// p <= sqrt(x / low)
T sqrt_xlow = isqrt(xlow);
int64_t max_c2 = pi[min(sqrt_xlow, x_star)];
int64_t max_a = pi[min(sqrt_xlow, x13)];
// C2 formula: pi[sqrt(z)] < b <= pi[x_star]
for (int64_t b = min_c2 + proc_id; b <= max_c2; b += procs)
sum += C2(x, xlow, xhigh, y, b, primes, pi, segmentedPi);
// A formula: pi[x_star] < b <= pi[x13]
for (int64_t b = min_a + proc_id; b <= max_a; b += procs)
sum += A(x, xlow, xhigh, y, b, primes, pi, segmentedPi);
}
}
sum = mpi_reduce_sum(sum);
return sum;
}
} // namespace
namespace primecount {
int64_t AC_mpi(int64_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== AC_mpi(x, y) ===");
print_gourdon_vars(x, y, z, k, threads);
double time = get_time();
int64_t x_star = get_x_star_gourdon(x, y);
int64_t max_c_prime = y;
int64_t max_a_prime = (int64_t) isqrt(x / x_star);
int64_t max_prime = max(max_a_prime, max_c_prime);
auto primes = generate_primes<uint32_t>(max_prime);
int64_t sum = AC_OpenMP((uint64_t) x, y, z, k, x_star, max_a_prime, primes, is_print(), threads);
print("A + C", sum, time);
return sum;
}
#ifdef HAVE_INT128_T
int128_t AC_mpi(int128_t x,
int64_t y,
int64_t z,
int64_t k,
int threads)
{
print("");
print("=== AC_mpi(x, y) ===");
print_gourdon_vars(x, y, z, k, threads);
double time = get_time();
int64_t x_star = get_x_star_gourdon(x, y);
int64_t max_c_prime = y;
int64_t max_a_prime = (int64_t) isqrt(x / x_star);
int64_t max_prime = max(max_a_prime, max_c_prime);
int128_t sum;
// uses less memory
if (max_prime <= numeric_limits<uint32_t>::max())
{
auto primes = generate_primes<uint32_t>(max_prime);
sum = AC_OpenMP((uint128_t) x, y, z, k, x_star, max_a_prime, primes, is_print(), threads);
}
else
{
auto primes = generate_primes<uint64_t>(max_prime);
sum = AC_OpenMP((uint128_t) x, y, z, k, x_star, max_a_prime, primes, is_print(), threads);
}
print("A + C", sum, time);
return sum;
}
#endif
} // namespace
<|endoftext|> |
<commit_before>/*
====================================================================
Copyright (c) 2011 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_chk_ex.cxx
*/
#include "fct.h"
class err_t {};
class sub_err_t : err_t {};
class other_err_t {};
static void throw_err() {
throw err_t();
}
static void throw_sub_err() {
throw sub_err_t();
}
static void throw_other_err() {
throw other_err_t();
}
static void not_going_to_throw() {
int j = 2+1;
char buf[32];
sprintf(buf, "j=%d", j);
}
FCT_BGN()
{
FCT_QTEST_BGN(throw_err) {
fct_chk_ex(
err_t,
throw_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(throw_and_catch_sub_err) {
fct_chk_ex(
sub_err_t,
throw_sub_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(throw_and_catch_other_err__should_fail) {
/* This is checking for an exception of type "sub_err_t", but
doesn't get it. Should fail! */
fct_chk_ex(
sub_err_t,
throw_other_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(doesnt_throw) {
/* This is expecting the function to throw an error, but it
doesn't. */
fct_chk_ex(
err_t,
not_going_to_throw();
);
} FCT_QTEST_END();
printf("\n***TESTS ARE SUPPOSED TO REPORT FAILURES***\n");
FCT_EXPECTED_FAILURES(2);
}
FCT_END();
<commit_msg>quite warnings with fct_chk_ex and MSVC.<commit_after>/*
====================================================================
Copyright (c) 2011 Ian Blumel. All rights reserved.
This software is licensed as described in the file LICENSE, which
you should have received as part of this distribution.
====================================================================
File: test_chk_ex.cxx
*/
#include "fct.h"
class err_t {};
class sub_err_t : public err_t {};
class other_err_t {};
static void throw_err() {
throw err_t();
}
static void throw_sub_err() {
throw sub_err_t();
}
static void throw_other_err() {
throw other_err_t();
}
static void not_going_to_throw() {
int j = 2+1;
char buf[32];
fct_snprintf(buf, sizeof(buf), "j=%d", j);
}
FCT_BGN()
{
FCT_QTEST_BGN(throw_err) {
fct_chk_ex(
err_t&,
throw_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(throw_and_catch_sub_err) {
fct_chk_ex(
sub_err_t&,
throw_sub_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(throw_and_catch_other_err__should_fail) {
/* This is checking for an exception of type "sub_err_t", but
doesn't get it. Should fail! */
fct_chk_ex(
sub_err_t&,
throw_other_err()
);
} FCT_QTEST_END();
FCT_QTEST_BGN(doesnt_throw) {
/* This is expecting the function to throw an error, but it
doesn't. */
fct_chk_ex(
err_t&,
not_going_to_throw();
);
} FCT_QTEST_END();
printf("\n***TESTS ARE SUPPOSED TO REPORT FAILURES***\n");
FCT_EXPECTED_FAILURES(2);
}
FCT_END();
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Rob Caelers <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <iostream>
#include <string>
#include "loopp/ble/BLEScanner.hpp"
#include "loopp/core/MainLoop.hpp"
#include "loopp/core/Slot.hpp"
#include "loopp/core/Task.hpp"
#include "loopp/http/HttpClient.hpp"
#include "loopp/mqtt/MqttClient.hpp"
#include "loopp/net/Wifi.hpp"
#include "loopp/utils/hexdump.hpp"
#include "loopp/utils/json.hpp"
#include "string.h"
extern "C"
{
#include "esp_heap_trace.h"
}
#include "driver/gpio.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "nvs_flash.h"
#include "user_config.h"
using json = nlohmann::json;
static const char tag[] = "BEACON-SCANNER";
extern const uint8_t ca_start[] asm("_binary_CA_crt_start");
extern const uint8_t ca_end[] asm("_binary_CA_crt_end");
extern const uint8_t certificate_start[] asm("_binary_esp32_crt_start");
extern const uint8_t certificate_end[] asm("_binary_esp32_crt_end");
extern const uint8_t private_key_start[] asm("_binary_esp32_key_start");
extern const uint8_t private_key_end[] asm("_binary_esp32_key_end");
// #define NUM_RECORDS 100
// static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
class Main
{
public:
Main()
: beacon_scanner(loopp::ble::BLEScanner::instance()), wifi(loopp::net::Wifi::instance()),
loop(std::make_shared<loopp::core::MainLoop>()),
mqtt(std::make_shared<loopp::mqtt::MqttClient>(loop, "BLEScanner", MQTT_HOST, MQTT_PORT)),
task("main_task", std::bind(&Main::main_task, this))
{
gpio_pad_select_gpio(LED_GPIO);
gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);
std::string mac = wifi.get_mac();
topic_config = "beaconscanner/config/" + mac;
topic_scan = "beaconscanner/scan/" + mac;
}
private:
// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
static std::string
base64_encode(const std::string &in)
{
std::string out;
int val = 0, valb = -6;
for (char c : in)
{
val = (val << 8) + c;
valb += 8;
while (valb >= 0)
{
out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val << 8) >> (valb + 8)) & 0x3F]);
while (out.size() % 4)
out.push_back('=');
return out;
}
read_body(std::shared_ptr<loopp::http::HttpClient> client)
{
client->read_body_async(1024, loopp::core::make_slot(loop, [this, client](std::error_code, loopp::net::StreamBuffer *buffer) {
if (buffer->consume_size() > 0)
{
std::string s(buffer->consume_data(), buffer->consume_size());
buffer->consume_commit(buffer->consume_size());
ESP_LOGI(tag, "Body: %s", s.c_str());
read_body(client);
}
}));
}
void
test_http()
{
std::shared_ptr<loopp::http::HttpClient> client = std::make_shared<loopp::http::HttpClient>(loop);
client->set_client_certificate(reinterpret_cast<const char *>(certificate_start), reinterpret_cast<const char *>(private_key_start));
client->set_ca_certificate(reinterpret_cast<const char *>(ca_start));
loopp::http::Request request("GET", "https://" MQTT_HOST ":443/");
client->execute(request, loopp::core::make_slot(loop, [this, client](std::error_code, loopp::http::Response) { read_body(client); }));
}
void
on_wifi_system_event(system_event_t event)
{
ESP_LOGI(tag, "-> System event %d", event.event_id);
}
void
on_wifi_timeout()
{
ESP_LOGI(tag, "-> Wifi timer");
wifi_timer = 0;
if (!wifi.connected().get())
{
ESP_LOGI(tag, "-> Wifi failed to connect in time. Reset");
wifi.reconnect();
wifi_timer = loop->add_timer(std::chrono::milliseconds(5000), std::bind(&Main::on_wifi_timeout, this));
}
}
void
on_wifi_connected(bool connected)
{
if (connected)
{
ESP_LOGI(tag, "-> Wifi connected");
loop->cancel_timer(wifi_timer);
#ifdef MQTT_USER
mqtt->set_username(MQTT_USER);
#endif
#ifdef MQTT_PASS
mqtt->set_password(MQTT_PASS);
#endif
#ifdef MQTT_USE_TLS
mqtt->set_client_certificate(reinterpret_cast<const char *>(certificate_start), reinterpret_cast<const char *>(private_key_start));
mqtt->set_ca_certificate(reinterpret_cast<const char *>(ca_start));
#endif
mqtt->set_callback(loopp::core::make_slot(loop, [this](std::string topic, std::string payload) { on_mqtt_data(topic, payload); }));
mqtt->connected().connect(loop, std::bind(&Main::on_mqtt_connected, this, std::placeholders::_1));
mqtt->connect();
test_http();
}
else
{
ESP_LOGI(tag, "-> Wifi disconnected");
}
}
void
on_mqtt_connected(bool connected)
{
if (connected)
{
ESP_LOGI(tag, "-> MQTT connected");
ESP_LOGI(tag, "-> Requesting configuration at %s", topic_config.c_str());
mqtt->subscribe(topic_config);
mqtt->add_filter(topic_config,
loopp::core::make_slot(loop, [this](std::string topic, std::string payload) { on_provisioning(payload); }));
start_beacon_scan();
}
else
{
ESP_LOGI(tag, "-> MQTT disconnected");
stop_beacon_scan();
}
}
void
on_mqtt_data(std::string topic, std::string payload)
{
ESP_LOGI(tag, "-> MQTT %s -> %s (free %d)", topic.c_str(), payload.c_str(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
}
void
on_provisioning(std::string payload)
{
ESP_LOGI(tag, "-> MQTT provisioning-> %s (free %d)", payload.c_str(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
// TODO:
// beacon_scanner.start();
}
void
on_beacon_scanner_scan_result(loopp::ble::BLEScanner::ScanResult result)
{
static int led_state = 0;
led_state ^= 1;
gpio_set_level(LED_GPIO, led_state);
scan_results.push_back(result);
}
void
on_scan_timer()
{
json j;
if (mqtt->connected().get())
{
for (auto r : scan_results)
{
ESP_LOGI(tag, "on_scan_timer %s (free %d)", r.bda_as_string().c_str(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
json jb;
jb["mac"] = r.bda_as_string();
jb["bda"] = base64_encode(std::string(reinterpret_cast<char *>(r.bda), sizeof(r.bda)));
jb["rssi"] = r.rssi;
jb["adv_data"] = base64_encode(r.adv_data);
j.push_back(jb);
}
mqtt->publish(topic_scan, j.dump());
}
scan_results.clear();
}
void
start_beacon_scan()
{
scan_timer = loop->add_periodic_timer(std::chrono::milliseconds(1000), std::bind(&Main::on_scan_timer, this));
beacon_scanner.start();
}
void
stop_beacon_scan()
{
loop->cancel_timer(scan_timer);
scan_timer = 0;
beacon_scanner.stop();
}
void
main_task()
{
wifi.set_ssid(WIFI_SSID);
wifi.set_passphase(WIFI_PASS);
wifi.set_host_name("scan");
wifi.set_auto_connect(true);
wifi.system_event_signal().connect(loop, std::bind(&Main::on_wifi_system_event, this, std::placeholders::_1));
wifi.connected().connect(loop, std::bind(&Main::on_wifi_connected, this, std::placeholders::_1));
beacon_scanner.scan_result_signal().connect(loop, std::bind(&Main::on_beacon_scanner_scan_result, this, std::placeholders::_1));
wifi_timer = loop->add_timer(std::chrono::milliseconds(5000), std::bind(&Main::on_wifi_timeout, this));
wifi.connect();
heap_caps_print_heap_info(MALLOC_CAP_DEFAULT);
// heap_trace_init_standalone(trace_record, NUM_RECORDS);
// ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_ALL) );
loop->run();
}
loopp::ble::BLEScanner &beacon_scanner;
loopp::net::Wifi &wifi;
std::shared_ptr<loopp::core::MainLoop> loop;
std::shared_ptr<loopp::mqtt::MqttClient> mqtt;
loopp::core::Task task;
loopp::core::MainLoop::timer_id wifi_timer = 0;
loopp::core::MainLoop::timer_id scan_timer = 0;
std::list<loopp::ble::BLEScanner::ScanResult> scan_results;
std::string topic_config;
std::string topic_scan;
const static gpio_num_t LED_GPIO = GPIO_NUM_5;
};
extern "C" void
app_main()
{
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(tag, "HEAP: startup");
heap_caps_print_heap_info(MALLOC_CAP_DEFAULT);
new Main();
while (1)
{
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
<commit_msg>Fix compilation error<commit_after>// Copyright (C) 2017 Rob Caelers <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <iostream>
#include <string>
#include "loopp/ble/BLEScanner.hpp"
#include "loopp/core/MainLoop.hpp"
#include "loopp/core/Slot.hpp"
#include "loopp/core/Task.hpp"
#include "loopp/http/HttpClient.hpp"
#include "loopp/mqtt/MqttClient.hpp"
#include "loopp/net/Wifi.hpp"
#include "loopp/utils/hexdump.hpp"
#include "loopp/utils/json.hpp"
#include "string.h"
extern "C"
{
#include "esp_heap_trace.h"
}
#include "driver/gpio.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "nvs_flash.h"
#include "user_config.h"
using json = nlohmann::json;
static const char tag[] = "BEACON-SCANNER";
extern const uint8_t ca_start[] asm("_binary_CA_crt_start");
extern const uint8_t ca_end[] asm("_binary_CA_crt_end");
extern const uint8_t certificate_start[] asm("_binary_esp32_crt_start");
extern const uint8_t certificate_end[] asm("_binary_esp32_crt_end");
extern const uint8_t private_key_start[] asm("_binary_esp32_key_start");
extern const uint8_t private_key_end[] asm("_binary_esp32_key_end");
// #define NUM_RECORDS 100
// static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
class Main
{
public:
Main()
: beacon_scanner(loopp::ble::BLEScanner::instance()), wifi(loopp::net::Wifi::instance()),
loop(std::make_shared<loopp::core::MainLoop>()),
mqtt(std::make_shared<loopp::mqtt::MqttClient>(loop, "BLEScanner", MQTT_HOST, MQTT_PORT)),
task("main_task", std::bind(&Main::main_task, this))
{
gpio_pad_select_gpio(LED_GPIO);
gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);
std::string mac = wifi.get_mac();
topic_config = "beaconscanner/config/" + mac;
topic_scan = "beaconscanner/scan/" + mac;
}
private:
// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
static std::string
base64_encode(const std::string &in)
{
std::string out;
int val = 0, valb = -6;
for (char c : in)
{
val = (val << 8) + c;
valb += 8;
while (valb >= 0)
{
out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val << 8) >> (valb + 8)) & 0x3F]);
while (out.size() % 4)
out.push_back('=');
return out;
}
void
read_body(std::shared_ptr<loopp::http::HttpClient> client)
{
client->read_body_async(1024, loopp::core::make_slot(loop, [this, client](std::error_code, loopp::net::StreamBuffer *buffer) {
if (buffer->consume_size() > 0)
{
std::string s(buffer->consume_data(), buffer->consume_size());
buffer->consume_commit(buffer->consume_size());
ESP_LOGI(tag, "Body: %s", s.c_str());
read_body(client);
}
}));
}
void
test_http()
{
std::shared_ptr<loopp::http::HttpClient> client = std::make_shared<loopp::http::HttpClient>(loop);
client->set_client_certificate(reinterpret_cast<const char *>(certificate_start), reinterpret_cast<const char *>(private_key_start));
client->set_ca_certificate(reinterpret_cast<const char *>(ca_start));
loopp::http::Request request("GET", "https://" MQTT_HOST ":443/");
client->execute(request, loopp::core::make_slot(loop, [this, client](std::error_code, loopp::http::Response) { read_body(client); }));
}
void
on_wifi_system_event(system_event_t event)
{
ESP_LOGI(tag, "-> System event %d", event.event_id);
}
void
on_wifi_timeout()
{
ESP_LOGI(tag, "-> Wifi timer");
wifi_timer = 0;
if (!wifi.connected().get())
{
ESP_LOGI(tag, "-> Wifi failed to connect in time. Reset");
wifi.reconnect();
wifi_timer = loop->add_timer(std::chrono::milliseconds(5000), std::bind(&Main::on_wifi_timeout, this));
}
}
void
on_wifi_connected(bool connected)
{
if (connected)
{
ESP_LOGI(tag, "-> Wifi connected");
loop->cancel_timer(wifi_timer);
#ifdef MQTT_USER
mqtt->set_username(MQTT_USER);
#endif
#ifdef MQTT_PASS
mqtt->set_password(MQTT_PASS);
#endif
#ifdef MQTT_USE_TLS
mqtt->set_client_certificate(reinterpret_cast<const char *>(certificate_start), reinterpret_cast<const char *>(private_key_start));
mqtt->set_ca_certificate(reinterpret_cast<const char *>(ca_start));
#endif
mqtt->set_callback(loopp::core::make_slot(loop, [this](std::string topic, std::string payload) { on_mqtt_data(topic, payload); }));
mqtt->connected().connect(loop, std::bind(&Main::on_mqtt_connected, this, std::placeholders::_1));
mqtt->connect();
test_http();
}
else
{
ESP_LOGI(tag, "-> Wifi disconnected");
}
}
void
on_mqtt_connected(bool connected)
{
if (connected)
{
ESP_LOGI(tag, "-> MQTT connected");
ESP_LOGI(tag, "-> Requesting configuration at %s", topic_config.c_str());
mqtt->subscribe(topic_config);
mqtt->add_filter(topic_config,
loopp::core::make_slot(loop, [this](std::string topic, std::string payload) { on_provisioning(payload); }));
start_beacon_scan();
}
else
{
ESP_LOGI(tag, "-> MQTT disconnected");
stop_beacon_scan();
}
}
void
on_mqtt_data(std::string topic, std::string payload)
{
ESP_LOGI(tag, "-> MQTT %s -> %s (free %d)", topic.c_str(), payload.c_str(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
}
void
on_provisioning(std::string payload)
{
ESP_LOGI(tag, "-> MQTT provisioning-> %s (free %d)", payload.c_str(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
// TODO:
// beacon_scanner.start();
}
void
on_beacon_scanner_scan_result(loopp::ble::BLEScanner::ScanResult result)
{
static int led_state = 0;
led_state ^= 1;
gpio_set_level(LED_GPIO, led_state);
scan_results.push_back(result);
}
void
on_scan_timer()
{
json j;
if (mqtt->connected().get())
{
for (auto r : scan_results)
{
ESP_LOGI(tag, "on_scan_timer %s (free %d)", r.bda_as_string().c_str(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
json jb;
jb["mac"] = r.bda_as_string();
jb["bda"] = base64_encode(std::string(reinterpret_cast<char *>(r.bda), sizeof(r.bda)));
jb["rssi"] = r.rssi;
jb["adv_data"] = base64_encode(r.adv_data);
j.push_back(jb);
}
mqtt->publish(topic_scan, j.dump());
}
scan_results.clear();
}
void
start_beacon_scan()
{
scan_timer = loop->add_periodic_timer(std::chrono::milliseconds(1000), std::bind(&Main::on_scan_timer, this));
beacon_scanner.start();
}
void
stop_beacon_scan()
{
loop->cancel_timer(scan_timer);
scan_timer = 0;
beacon_scanner.stop();
}
void
main_task()
{
wifi.set_ssid(WIFI_SSID);
wifi.set_passphase(WIFI_PASS);
wifi.set_host_name("scan");
wifi.set_auto_connect(true);
wifi.system_event_signal().connect(loop, std::bind(&Main::on_wifi_system_event, this, std::placeholders::_1));
wifi.connected().connect(loop, std::bind(&Main::on_wifi_connected, this, std::placeholders::_1));
beacon_scanner.scan_result_signal().connect(loop, std::bind(&Main::on_beacon_scanner_scan_result, this, std::placeholders::_1));
wifi_timer = loop->add_timer(std::chrono::milliseconds(5000), std::bind(&Main::on_wifi_timeout, this));
wifi.connect();
heap_caps_print_heap_info(MALLOC_CAP_DEFAULT);
// heap_trace_init_standalone(trace_record, NUM_RECORDS);
// ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_ALL) );
loop->run();
}
loopp::ble::BLEScanner &beacon_scanner;
loopp::net::Wifi &wifi;
std::shared_ptr<loopp::core::MainLoop> loop;
std::shared_ptr<loopp::mqtt::MqttClient> mqtt;
loopp::core::Task task;
loopp::core::MainLoop::timer_id wifi_timer = 0;
loopp::core::MainLoop::timer_id scan_timer = 0;
std::list<loopp::ble::BLEScanner::ScanResult> scan_results;
std::string topic_config;
std::string topic_scan;
const static gpio_num_t LED_GPIO = GPIO_NUM_5;
};
extern "C" void
app_main()
{
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(tag, "HEAP: startup");
heap_caps_print_heap_info(MALLOC_CAP_DEFAULT);
new Main();
while (1)
{
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon, Dane Springmeyer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_layer.cc 17 2005-03-08 23:58:43Z pavlenko $
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
// mapnik
#include <mapnik/layer.hpp>
#include <mapnik/datasource.hpp>
using mapnik::Layer;
using mapnik::parameters;
using mapnik::datasource;
struct layer_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const Layer& l)
{
return boost::python::make_tuple(l.name(),l.srs());
}
static boost::python::tuple
getstate(const Layer& l)
{
boost::python::list s;
std::vector<std::string> const& style_names = l.styles();
for (unsigned i = 0; i < style_names.size(); ++i)
{
s.append(style_names[i]);
}
return boost::python::make_tuple(l.abstract(),l.title(),l.clear_label_cache(),l.getMinZoom(),l.getMaxZoom(),l.isQueryable(),l.datasource(),s);
}
static void
setstate (Layer& l, boost::python::tuple state)
{
using namespace boost::python;
if (len(state) != 8)
{
PyErr_SetObject(PyExc_ValueError,
("expected 8-item tuple in call to __setstate__; got %s"
% state).ptr()
);
throw_error_already_set();
}
if (state[0])
{
l.set_abstract(extract<std::string>(state[0]));
}
if (state[1])
{
l.set_title(extract<std::string>(state[1]));
}
if (state[2])
{
l.set_clear_label_cache(extract<bool>(state[2]));
}
if (state[3])
{
l.setMinZoom(extract<double>(state[3]));
}
if (state[4])
{
l.setMaxZoom(extract<double>(state[4]));
}
if (state[5])
{
l.setQueryable(extract<bool>(state[5]));
}
if (state[6])
{
boost::shared_ptr<datasource> ds = extract<boost::shared_ptr<datasource> >(state[6]);
l.set_datasource(ds);
}
boost::python::list s = extract<boost::python::list>(state[7]);
for (int i=0;i<len(s);++i)
{
l.add_style(extract<std::string>(s[i]));
}
}
};
std::vector<std::string> & (mapnik::Layer::*_styles_)() = &mapnik::Layer::styles;
void export_layer()
{
using namespace boost::python;
class_<std::vector<std::string> >("Names")
.def(vector_indexing_suite<std::vector<std::string>,true >())
;
class_<Layer>("Layer", "A Mapnik map layer.", init<std::string const&,optional<std::string const&> >(
"Create a Layer with a named string and, optionally, an srs string either with\n"
"a Proj.4 epsg code ('+init=epsg:<code>') or with a Proj.4 literal ('+proj=<literal>').\n"
"If no srs is specified it will default to '+proj=latlong +datum=WGS84'\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr\n"
"<mapnik._mapnik.Layer object at 0x6a270>"
))
.def_pickle(layer_pickle_suite()
)
.def("envelope",&Layer::envelope,
"Return the geographic envelope/bounding box "
"of the data in the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.envelope()\n"
"Envelope(-1.0,-1.0,0.0,0.0) # default until a datasource is loaded\n"
)
.def("visible", &Layer::isVisible,
"Return True if this layer's data is active and visible at a given scale.\n"
"Otherwise returns False.\n"
"Accepts a scale value as an integer or float input.\n"
"Will return False if:\n"
"\tscale >= minzoom - 1e-6\n"
"\tor:\n"
"\tscale < maxzoom + 1e-6\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.visible(1.0/1000000)\n"
"True\n"
">>> lyr.active = False\n"
">>> lyr.visible(1.0/1000000)\n"
"False\n"
)
.add_property("abstract",
make_function(&Layer::abstract,return_value_policy<copy_const_reference>()),
&Layer::set_abstract,
"Get/Set the abstract of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.abstract\n"
"'' # default is en empty string\n"
">>> lyr.abstract = 'My Shapefile rendered with Mapnik'\n"
">>> lyr.abstract\n"
"'My Shapefile rendered with Mapnik'\n"
)
.add_property("active",
&Layer::isActive,
&Layer::setActive,
"Get/Set whether this layer is active and will be rendered.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.active\n"
"True # Active by default\n"
">>> lyr.active = False # set False to disable layer rendering\n"
">>> lyr.active\n"
"False\n"
)
.add_property("clear_label_cache",
&Layer::clear_label_cache,
&Layer::set_clear_label_cache,
"Get/Set whether this layer's labels are cached."
"\n"
"Usage:\n"
"TODO"
)
.add_property("datasource",
&Layer::datasource,
&Layer::set_datasource,
"The datasource attached to this layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer, Datasource\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.datasource = Datasource(type='shape',file='world_borders')\n"
">>> lyr.datasource\n"
"<mapnik.Datasource object at 0x65470>\n"
)
.add_property("maxzoom",
&Layer::getMaxZoom,
&Layer::setMaxZoom,
"Get/Set the maximum zoom lever of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.maxzoom\n"
"1.7976931348623157e+308 # default is the numerical maximum\n"
">>> lyr.maxzoom = 1.0/1000000\n"
">>> lyr.maxzoom\n"
"9.9999999999999995e-07\n"
)
.add_property("minzoom",
&Layer::getMinZoom,
&Layer::setMinZoom,
"Get/Set the minimum zoom lever of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.minzoom # default is 0\n"
"0.0\n"
">>> lyr.minzoom = 1.0/1000000\n"
">>> lyr.minzoom\n"
"9.9999999999999995e-07\n"
)
.add_property("name",
make_function(&Layer::name, return_value_policy<copy_const_reference>()),
&Layer::set_name,
"Get/Set the name of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.name\n"
"'My Layer'\n"
">>> lyr.name = 'New Name'\n"
">>> lyr.name\n"
"'New Name'\n"
)
.add_property("queryable",
&Layer::isQueryable,
&Layer::setQueryable,
"Get/Set whether this layer is queryable.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.queryable\n"
"False # Not queryable by default\n"
">>> lyr.queryable = True\n"
">>> lyr.queryable\n"
"True\n"
)
.add_property("srs",
make_function(&Layer::srs,return_value_policy<copy_const_reference>()),
&Layer::set_srs,
"Get/Set the SRS of the layer."
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.srs\n"
"'+proj=latlong +datum=WGS84' # The default srs if not initialized with custom srs\n"
">>> # set to google mercator with Proj.4 literal\n"
"... \n"
">>> lyr.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over'\n"
)
.add_property("styles",
make_function(_styles_,return_value_policy<reference_existing_object>()),
"The styles list attached to this layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.styles\n"
"<mapnik._mapnik.Names object at 0x6d3e8>\n"
">>> len(lyr.styles)\n"
"0\n # no styles until you append them"
"lyr.styles.append('My Style') # mapnik uses named styles for flexibility\n"
">>> len(lyr.styles)\n"
"1\n"
">>> lyr.styles[0]\n"
"'My Style'\n"
)
.add_property("title",
make_function(&Layer::title, return_value_policy<copy_const_reference>()),
&Layer::set_title,
"Get/Set the title of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.title\n"
"''\n"
">>> lyr.title = 'My first layer'\n"
">>> lyr.title\n"
"'My first layer'\n"
)
;
}
<commit_msg>slight formatting fixes to docstrings in layer class<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon, Dane Springmeyer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_layer.cc 17 2005-03-08 23:58:43Z pavlenko $
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
// mapnik
#include <mapnik/layer.hpp>
#include <mapnik/datasource.hpp>
using mapnik::Layer;
using mapnik::parameters;
using mapnik::datasource;
struct layer_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const Layer& l)
{
return boost::python::make_tuple(l.name(),l.srs());
}
static boost::python::tuple
getstate(const Layer& l)
{
boost::python::list s;
std::vector<std::string> const& style_names = l.styles();
for (unsigned i = 0; i < style_names.size(); ++i)
{
s.append(style_names[i]);
}
return boost::python::make_tuple(l.abstract(),l.title(),l.clear_label_cache(),l.getMinZoom(),l.getMaxZoom(),l.isQueryable(),l.datasource(),s);
}
static void
setstate (Layer& l, boost::python::tuple state)
{
using namespace boost::python;
if (len(state) != 8)
{
PyErr_SetObject(PyExc_ValueError,
("expected 8-item tuple in call to __setstate__; got %s"
% state).ptr()
);
throw_error_already_set();
}
if (state[0])
{
l.set_abstract(extract<std::string>(state[0]));
}
if (state[1])
{
l.set_title(extract<std::string>(state[1]));
}
if (state[2])
{
l.set_clear_label_cache(extract<bool>(state[2]));
}
if (state[3])
{
l.setMinZoom(extract<double>(state[3]));
}
if (state[4])
{
l.setMaxZoom(extract<double>(state[4]));
}
if (state[5])
{
l.setQueryable(extract<bool>(state[5]));
}
if (state[6])
{
boost::shared_ptr<datasource> ds = extract<boost::shared_ptr<datasource> >(state[6]);
l.set_datasource(ds);
}
boost::python::list s = extract<boost::python::list>(state[7]);
for (int i=0;i<len(s);++i)
{
l.add_style(extract<std::string>(s[i]));
}
}
};
std::vector<std::string> & (mapnik::Layer::*_styles_)() = &mapnik::Layer::styles;
void export_layer()
{
using namespace boost::python;
class_<std::vector<std::string> >("Names")
.def(vector_indexing_suite<std::vector<std::string>,true >())
;
class_<Layer>("Layer", "A Mapnik map layer.", init<std::string const&,optional<std::string const&> >(
"Create a Layer with a named string and, optionally, an srs string.\n"
"\n"
"The srs can be either a Proj.4 epsg code ('+init=epsg:<code>') or\n"
"of a Proj.4 literal ('+proj=<literal>').\n"
"If no srs is specified it will default to '+proj=latlong +datum=WGS84'\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr\n"
"<mapnik._mapnik.Layer object at 0x6a270>\n"
))
.def_pickle(layer_pickle_suite())
.def("envelope",&Layer::envelope,
"Return the geographic envelope/bounding box."
"\n"
"Determined based on the layer datasource.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.envelope()\n"
"Envelope(-1.0,-1.0,0.0,0.0) # default until a datasource is loaded\n"
)
.def("visible", &Layer::isVisible,
"Return True if this layer's data is active and visible at a given scale.\n"
"\n"
"Otherwise returns False.\n"
"Accepts a scale value as an integer or float input.\n"
"Will return False if:\n"
"\tscale >= minzoom - 1e-6\n"
"\tor:\n"
"\tscale < maxzoom + 1e-6\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.visible(1.0/1000000)\n"
"True\n"
">>> lyr.active = False\n"
">>> lyr.visible(1.0/1000000)\n"
"False\n"
)
.add_property("abstract",
make_function(&Layer::abstract,return_value_policy<copy_const_reference>()),
&Layer::set_abstract,
"Get/Set the abstract of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.abstract\n"
"'' # default is en empty string\n"
">>> lyr.abstract = 'My Shapefile rendered with Mapnik'\n"
">>> lyr.abstract\n"
"'My Shapefile rendered with Mapnik'\n"
)
.add_property("active",
&Layer::isActive,
&Layer::setActive,
"Get/Set whether this layer is active and will be rendered.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.active\n"
"True # Active by default\n"
">>> lyr.active = False # set False to disable layer rendering\n"
">>> lyr.active\n"
"False\n"
)
.add_property("clear_label_cache",
&Layer::clear_label_cache,
&Layer::set_clear_label_cache,
"Get/Set whether this layer's labels are cached.\n"
"\n"
"Usage:\n"
"TODO\n"
)
.add_property("datasource",
&Layer::datasource,
&Layer::set_datasource,
"The datasource attached to this layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer, Datasource\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.datasource = Datasource(type='shape',file='world_borders')\n"
">>> lyr.datasource\n"
"<mapnik.Datasource object at 0x65470>\n"
)
.add_property("maxzoom",
&Layer::getMaxZoom,
&Layer::setMaxZoom,
"Get/Set the maximum zoom lever of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.maxzoom\n"
"1.7976931348623157e+308 # default is the numerical maximum\n"
">>> lyr.maxzoom = 1.0/1000000\n"
">>> lyr.maxzoom\n"
"9.9999999999999995e-07\n"
)
.add_property("minzoom",
&Layer::getMinZoom,
&Layer::setMinZoom,
"Get/Set the minimum zoom lever of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.minzoom # default is 0\n"
"0.0\n"
">>> lyr.minzoom = 1.0/1000000\n"
">>> lyr.minzoom\n"
"9.9999999999999995e-07\n"
)
.add_property("name",
make_function(&Layer::name, return_value_policy<copy_const_reference>()),
&Layer::set_name,
"Get/Set the name of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.name\n"
"'My Layer'\n"
">>> lyr.name = 'New Name'\n"
">>> lyr.name\n"
"'New Name'\n"
)
.add_property("queryable",
&Layer::isQueryable,
&Layer::setQueryable,
"Get/Set whether this layer is queryable.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.queryable\n"
"False # Not queryable by default\n"
">>> lyr.queryable = True\n"
">>> lyr.queryable\n"
"True\n"
)
.add_property("srs",
make_function(&Layer::srs,return_value_policy<copy_const_reference>()),
&Layer::set_srs,
"Get/Set the SRS of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.srs\n"
"'+proj=latlong +datum=WGS84' # The default srs if not initialized with custom srs\n"
">>> # set to google mercator with Proj.4 literal\n"
"... \n"
">>> lyr.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over'\n"
)
.add_property("styles",
make_function(_styles_,return_value_policy<reference_existing_object>()),
"The styles list attached to this layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.styles\n"
"<mapnik._mapnik.Names object at 0x6d3e8>\n"
">>> len(lyr.styles)\n"
"0\n # no styles until you append them\n"
"lyr.styles.append('My Style') # mapnik uses named styles for flexibility\n"
">>> len(lyr.styles)\n"
"1\n"
">>> lyr.styles[0]\n"
"'My Style'\n"
)
.add_property("title",
make_function(&Layer::title, return_value_policy<copy_const_reference>()),
&Layer::set_title,
"Get/Set the title of the layer.\n"
"\n"
"Usage:\n"
">>> from mapnik import Layer\n"
">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
">>> lyr.title\n"
"''\n"
">>> lyr.title = 'My first layer'\n"
">>> lyr.title\n"
"'My first layer'\n"
)
;
}
<|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 "chrome/browser/ui/webui/constrained_html_ui.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/gtk/constrained_window_gtk.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/webui/html_dialog_tab_contents_delegate.h"
#include "chrome/browser/ui/webui/html_dialog_ui.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/gfx/rect.h"
#include "views/widget/native_widget_gtk.h"
// ConstrainedHtmlDelegateGtk works with ConstrainedWindowGtk to present
// a TabContents in a ContraintedHtmlUI.
class ConstrainedHtmlDelegateGtk : public views::NativeWidgetGtk,
public ConstrainedHtmlUIDelegate,
public ConstrainedWindowGtkDelegate,
public HtmlDialogTabContentsDelegate {
public:
ConstrainedHtmlDelegateGtk(Profile* profile,
HtmlDialogUIDelegate* delegate);
~ConstrainedHtmlDelegateGtk();
// ConstrainedHtmlUIDelegate interface.
virtual HtmlDialogUIDelegate* GetHtmlDialogUIDelegate() OVERRIDE;
virtual void OnDialogCloseFromWebUI() OVERRIDE;
virtual void ReleaseTabContentsOnDialogClose() OVERRIDE {
release_tab_on_close_ = true;
}
virtual ConstrainedWindow* window() OVERRIDE {
return window_;
}
virtual TabContentsWrapper* tab() OVERRIDE {
return html_tab_contents_.get();
}
// ConstrainedWindowGtkDelegate implementation.
virtual GtkWidget* GetWidgetRoot() OVERRIDE {
return GetNativeView();
}
virtual GtkWidget* GetFocusWidget() OVERRIDE {
return html_tab_contents_->tab_contents()->GetContentNativeView();
}
virtual void DeleteDelegate() OVERRIDE {
if (!closed_via_webui_)
html_delegate_->OnDialogClosed("");
tab_container_->ChangeTabContents(NULL);
}
virtual bool GetBackgroundColor(GdkColor* color) OVERRIDE {
*color = ui::kGdkWhite;
return true;
}
virtual bool ShouldHaveBorderPadding() const OVERRIDE {
return false;
}
// HtmlDialogTabContentsDelegate interface.
void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) OVERRIDE {}
void set_window(ConstrainedWindow* window) {
window_ = window;
}
private:
scoped_ptr<TabContentsWrapper> html_tab_contents_;
TabContentsContainer* tab_container_;
HtmlDialogUIDelegate* html_delegate_;
// The constrained window that owns |this|. Saved so we can close it later.
ConstrainedWindow* window_;
// Was the dialog closed from WebUI (in which case |html_delegate_|'s
// OnDialogClosed() method has already been called)?
bool closed_via_webui_;
// If true, release |tab_| on close instead of destroying it.
bool release_tab_on_close_;
};
ConstrainedHtmlDelegateGtk::ConstrainedHtmlDelegateGtk(
Profile* profile,
HtmlDialogUIDelegate* delegate)
: views::NativeWidgetGtk(new views::Widget),
HtmlDialogTabContentsDelegate(profile),
tab_container_(NULL),
html_delegate_(delegate),
window_(NULL),
closed_via_webui_(false) {
CHECK(delegate);
TabContents* tab_contents =
new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
html_tab_contents_.reset(new TabContentsWrapper(tab_contents));
tab_contents->set_delegate(this);
// Set |this| as a property so the ConstrainedHtmlUI can retrieve it.
ConstrainedHtmlUI::GetPropertyAccessor().SetProperty(
tab_contents->property_bag(), this);
tab_contents->controller().LoadURL(delegate->GetDialogContentURL(), GURL(),
content::PAGE_TRANSITION_START_PAGE,
std::string());
views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
params.native_widget = this;
GetWidget()->Init(params);
tab_container_ = new TabContentsContainer;
GetWidget()->SetContentsView(tab_container_);
tab_container_->ChangeTabContents(html_tab_contents_->tab_contents());
gfx::Size dialog_size;
html_delegate_->GetDialogSize(&dialog_size);
gtk_widget_set_size_request(GetWidgetRoot(),
dialog_size.width(),
dialog_size.height());
}
ConstrainedHtmlDelegateGtk::~ConstrainedHtmlDelegateGtk() {
if (release_tab_on_close_)
ignore_result(html_tab_contents_.release());
}
HtmlDialogUIDelegate* ConstrainedHtmlDelegateGtk::GetHtmlDialogUIDelegate() {
return html_delegate_;
}
void ConstrainedHtmlDelegateGtk::OnDialogCloseFromWebUI() {
closed_via_webui_ = true;
window_->CloseConstrainedWindow();
}
// static
ConstrainedHtmlUIDelegate* ConstrainedHtmlUI::CreateConstrainedHtmlDialog(
Profile* profile,
HtmlDialogUIDelegate* delegate,
TabContentsWrapper* wrapper) {
ConstrainedHtmlDelegateGtk* constrained_delegate =
new ConstrainedHtmlDelegateGtk(profile, delegate);
ConstrainedWindow* constrained_window =
new ConstrainedWindowGtk(wrapper, constrained_delegate);
constrained_delegate->set_window(constrained_window);
return constrained_delegate;
}
<commit_msg>Views: Add missing initializer in the views version of ConstrainedHtmlDelegateGtk.<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 "chrome/browser/ui/webui/constrained_html_ui.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/gtk/constrained_window_gtk.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/webui/html_dialog_tab_contents_delegate.h"
#include "chrome/browser/ui/webui/html_dialog_ui.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/gfx/rect.h"
#include "views/widget/native_widget_gtk.h"
// ConstrainedHtmlDelegateGtk works with ConstrainedWindowGtk to present
// a TabContents in a ContraintedHtmlUI.
class ConstrainedHtmlDelegateGtk : public views::NativeWidgetGtk,
public ConstrainedHtmlUIDelegate,
public ConstrainedWindowGtkDelegate,
public HtmlDialogTabContentsDelegate {
public:
ConstrainedHtmlDelegateGtk(Profile* profile,
HtmlDialogUIDelegate* delegate);
~ConstrainedHtmlDelegateGtk();
// ConstrainedHtmlUIDelegate interface.
virtual HtmlDialogUIDelegate* GetHtmlDialogUIDelegate() OVERRIDE;
virtual void OnDialogCloseFromWebUI() OVERRIDE;
virtual void ReleaseTabContentsOnDialogClose() OVERRIDE {
release_tab_on_close_ = true;
}
virtual ConstrainedWindow* window() OVERRIDE {
return window_;
}
virtual TabContentsWrapper* tab() OVERRIDE {
return html_tab_contents_.get();
}
// ConstrainedWindowGtkDelegate implementation.
virtual GtkWidget* GetWidgetRoot() OVERRIDE {
return GetNativeView();
}
virtual GtkWidget* GetFocusWidget() OVERRIDE {
return html_tab_contents_->tab_contents()->GetContentNativeView();
}
virtual void DeleteDelegate() OVERRIDE {
if (!closed_via_webui_)
html_delegate_->OnDialogClosed("");
tab_container_->ChangeTabContents(NULL);
}
virtual bool GetBackgroundColor(GdkColor* color) OVERRIDE {
*color = ui::kGdkWhite;
return true;
}
virtual bool ShouldHaveBorderPadding() const OVERRIDE {
return false;
}
// HtmlDialogTabContentsDelegate interface.
void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) OVERRIDE {}
void set_window(ConstrainedWindow* window) {
window_ = window;
}
private:
scoped_ptr<TabContentsWrapper> html_tab_contents_;
TabContentsContainer* tab_container_;
HtmlDialogUIDelegate* html_delegate_;
// The constrained window that owns |this|. Saved so we can close it later.
ConstrainedWindow* window_;
// Was the dialog closed from WebUI (in which case |html_delegate_|'s
// OnDialogClosed() method has already been called)?
bool closed_via_webui_;
// If true, release |tab_| on close instead of destroying it.
bool release_tab_on_close_;
};
ConstrainedHtmlDelegateGtk::ConstrainedHtmlDelegateGtk(
Profile* profile,
HtmlDialogUIDelegate* delegate)
: views::NativeWidgetGtk(new views::Widget),
HtmlDialogTabContentsDelegate(profile),
tab_container_(NULL),
html_delegate_(delegate),
window_(NULL),
closed_via_webui_(false),
release_tab_on_close_(false) {
CHECK(delegate);
TabContents* tab_contents =
new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
html_tab_contents_.reset(new TabContentsWrapper(tab_contents));
tab_contents->set_delegate(this);
// Set |this| as a property so the ConstrainedHtmlUI can retrieve it.
ConstrainedHtmlUI::GetPropertyAccessor().SetProperty(
tab_contents->property_bag(), this);
tab_contents->controller().LoadURL(delegate->GetDialogContentURL(), GURL(),
content::PAGE_TRANSITION_START_PAGE,
std::string());
views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
params.native_widget = this;
GetWidget()->Init(params);
tab_container_ = new TabContentsContainer;
GetWidget()->SetContentsView(tab_container_);
tab_container_->ChangeTabContents(html_tab_contents_->tab_contents());
gfx::Size dialog_size;
html_delegate_->GetDialogSize(&dialog_size);
gtk_widget_set_size_request(GetWidgetRoot(),
dialog_size.width(),
dialog_size.height());
}
ConstrainedHtmlDelegateGtk::~ConstrainedHtmlDelegateGtk() {
if (release_tab_on_close_)
ignore_result(html_tab_contents_.release());
}
HtmlDialogUIDelegate* ConstrainedHtmlDelegateGtk::GetHtmlDialogUIDelegate() {
return html_delegate_;
}
void ConstrainedHtmlDelegateGtk::OnDialogCloseFromWebUI() {
closed_via_webui_ = true;
window_->CloseConstrainedWindow();
}
// static
ConstrainedHtmlUIDelegate* ConstrainedHtmlUI::CreateConstrainedHtmlDialog(
Profile* profile,
HtmlDialogUIDelegate* delegate,
TabContentsWrapper* wrapper) {
ConstrainedHtmlDelegateGtk* constrained_delegate =
new ConstrainedHtmlDelegateGtk(profile, delegate);
ConstrainedWindow* constrained_window =
new ConstrainedWindowGtk(wrapper, constrained_delegate);
constrained_delegate->set_window(constrained_window);
return constrained_delegate;
}
<|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/printing/print_job.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/timer/timer.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job_worker.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "printing/printed_document.h"
#include "printing/printed_page.h"
#if defined(OS_WIN)
#include "chrome/browser/printing/pdf_to_emf_converter.h"
#include "printing/pdf_render_settings.h"
#endif
using base::TimeDelta;
namespace {
// Helper function to ensure |owner| is valid until at least |callback| returns.
void HoldRefCallback(const scoped_refptr<printing::PrintJobWorkerOwner>& owner,
const base::Closure& callback) {
callback.Run();
}
} // namespace
namespace printing {
PrintJob::PrintJob()
: source_(NULL),
worker_(),
settings_(),
is_job_pending_(false),
is_canceling_(false),
quit_factory_(this) {
// This is normally a UI message loop, but in unit tests, the message loop is
// of the 'default' type.
DCHECK(base::MessageLoopForUI::IsCurrent() ||
base::MessageLoop::current()->type() ==
base::MessageLoop::TYPE_DEFAULT);
}
PrintJob::~PrintJob() {
// The job should be finished (or at least canceled) when it is destroyed.
DCHECK(!is_job_pending_);
DCHECK(!is_canceling_);
DCHECK(!worker_ || !worker_->IsRunning());
DCHECK(RunsTasksOnCurrentThread());
}
void PrintJob::Initialize(PrintJobWorkerOwner* job,
PrintedPagesSource* source,
int page_count) {
DCHECK(!source_);
DCHECK(!worker_.get());
DCHECK(!is_job_pending_);
DCHECK(!is_canceling_);
DCHECK(!document_.get());
source_ = source;
worker_.reset(job->DetachWorker(this));
settings_ = job->settings();
PrintedDocument* new_doc =
new PrintedDocument(settings_,
source_,
job->cookie(),
content::BrowserThread::GetBlockingPool());
new_doc->set_page_count(page_count);
UpdatePrintedDocument(new_doc);
// Don't forget to register to our own messages.
registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this));
}
void PrintJob::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(RunsTasksOnCurrentThread());
switch (type) {
case chrome::NOTIFICATION_PRINT_JOB_EVENT: {
OnNotifyPrintJobEvent(*content::Details<JobEventDetails>(details).ptr());
break;
}
default: {
break;
}
}
}
void PrintJob::GetSettingsDone(const PrintSettings& new_settings,
PrintingContext::Result result) {
NOTREACHED();
}
PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) {
NOTREACHED();
return NULL;
}
const PrintSettings& PrintJob::settings() const {
return settings_;
}
int PrintJob::cookie() const {
if (!document_.get())
// Always use an invalid cookie in this case.
return 0;
return document_->cookie();
}
void PrintJob::StartPrinting() {
DCHECK(RunsTasksOnCurrentThread());
DCHECK(worker_->IsRunning());
DCHECK(!is_job_pending_);
if (!worker_->IsRunning() || is_job_pending_)
return;
// Real work is done in PrintJobWorker::StartPrinting().
worker_->PostTask(FROM_HERE,
base::Bind(&HoldRefCallback,
make_scoped_refptr(this),
base::Bind(&PrintJobWorker::StartPrinting,
base::Unretained(worker_.get()),
document_)));
// Set the flag right now.
is_job_pending_ = true;
// Tell everyone!
scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL));
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get()));
}
void PrintJob::Stop() {
DCHECK(RunsTasksOnCurrentThread());
if (quit_factory_.HasWeakPtrs()) {
// In case we're running a nested message loop to wait for a job to finish,
// and we finished before the timeout, quit the nested loop right away.
Quit();
quit_factory_.InvalidateWeakPtrs();
}
// Be sure to live long enough.
scoped_refptr<PrintJob> handle(this);
if (worker_->IsRunning()) {
ControlledWorkerShutdown();
} else {
// Flush the cached document.
UpdatePrintedDocument(NULL);
}
}
void PrintJob::Cancel() {
if (is_canceling_)
return;
is_canceling_ = true;
// Be sure to live long enough.
scoped_refptr<PrintJob> handle(this);
DCHECK(RunsTasksOnCurrentThread());
if (worker_ && worker_->IsRunning()) {
// Call this right now so it renders the context invalid. Do not use
// InvokeLater since it would take too much time.
worker_->Cancel();
}
// Make sure a Cancel() is broadcast.
scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::FAILED, NULL, NULL));
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get()));
Stop();
is_canceling_ = false;
}
bool PrintJob::FlushJob(base::TimeDelta timeout) {
// Make sure the object outlive this message loop.
scoped_refptr<PrintJob> handle(this);
base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&PrintJob::Quit, quit_factory_.GetWeakPtr()), timeout);
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
base::MessageLoop::current()->Run();
return true;
}
void PrintJob::DisconnectSource() {
source_ = NULL;
if (document_.get())
document_->DisconnectSource();
}
bool PrintJob::is_job_pending() const {
return is_job_pending_;
}
PrintedDocument* PrintJob::document() const {
return document_.get();
}
void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {
if (document_.get() == new_document)
return;
document_ = new_document;
if (document_.get()) {
settings_ = document_->settings();
}
if (worker_) {
DCHECK(!is_job_pending_);
// Sync the document with the worker.
worker_->PostTask(FROM_HERE,
base::Bind(&HoldRefCallback,
make_scoped_refptr(this),
base::Bind(&PrintJobWorker::OnDocumentChanged,
base::Unretained(worker_.get()),
document_)));
}
}
void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
switch (event_details.type()) {
case JobEventDetails::FAILED: {
settings_.Clear();
// No need to cancel since the worker already canceled itself.
Stop();
break;
}
case JobEventDetails::USER_INIT_DONE:
case JobEventDetails::DEFAULT_INIT_DONE:
case JobEventDetails::USER_INIT_CANCELED: {
DCHECK_EQ(event_details.document(), document_.get());
break;
}
case JobEventDetails::NEW_DOC:
case JobEventDetails::NEW_PAGE:
case JobEventDetails::JOB_DONE:
case JobEventDetails::ALL_PAGES_REQUESTED: {
// Don't care.
break;
}
case JobEventDetails::DOC_DONE: {
// This will call Stop() and broadcast a JOB_DONE message.
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this));
break;
}
case JobEventDetails::PAGE_DONE:
break;
default: {
NOTREACHED();
break;
}
}
}
#if defined(OS_WIN)
class PrintJob::PdfToEmfState {
public:
PdfToEmfState(const gfx::Size& page_size, const gfx::Rect& content_area)
: page_count_(0),
current_page_(0),
pages_in_progress_(0),
page_size_(page_size),
content_area_(content_area),
converter_(PdfToEmfConverter::CreateDefault()) {}
void Start(const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
const PdfToEmfConverter::StartCallback& start_callback) {
converter_->Start(data, conversion_settings, start_callback);
}
void GetMorePages(
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
const int kMaxNumberOfTempFilesPerDocument = 3;
while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
current_page_ < page_count_) {
++pages_in_progress_;
converter_->GetPage(current_page_++, get_page_callback);
}
}
void OnPageProcessed(
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
--pages_in_progress_;
GetMorePages(get_page_callback);
// Release converter if we don't need this any more.
if (!pages_in_progress_ && current_page_ >= page_count_)
converter_.reset();
}
void set_page_count(int page_count) { page_count_ = page_count; }
gfx::Size page_size() const { return page_size_; }
gfx::Rect content_area() const { return content_area_; }
private:
int page_count_;
int current_page_;
int pages_in_progress_;
gfx::Size page_size_;
gfx::Rect content_area_;
scoped_ptr<PdfToEmfConverter> converter_;
};
void PrintJob::StartPdfToEmfConversion(
const scoped_refptr<base::RefCountedMemory>& bytes,
const gfx::Size& page_size,
const gfx::Rect& content_area) {
DCHECK(!ptd_to_emf_state_.get());
ptd_to_emf_state_.reset(new PdfToEmfState(page_size, content_area));
const int kPrinterDpi = settings().dpi();
ptd_to_emf_state_->Start(
bytes,
printing::PdfRenderSettings(content_area, kPrinterDpi, true),
base::Bind(&PrintJob::OnPdfToEmfStarted, this));
}
void PrintJob::OnPdfToEmfStarted(int page_count) {
if (page_count <= 0) {
ptd_to_emf_state_.reset();
Cancel();
return;
}
ptd_to_emf_state_->set_page_count(page_count);
ptd_to_emf_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}
void PrintJob::OnPdfToEmfPageConverted(int page_number,
float scale_factor,
scoped_ptr<MetafilePlayer> emf) {
DCHECK(ptd_to_emf_state_);
if (!document_.get() || !emf) {
ptd_to_emf_state_.reset();
Cancel();
return;
}
// Update the rendered document. It will send notifications to the listener.
document_->SetPage(page_number,
emf.Pass(),
scale_factor,
ptd_to_emf_state_->page_size(),
ptd_to_emf_state_->content_area());
ptd_to_emf_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}
#endif // OS_WIN
void PrintJob::OnDocumentDone() {
// Be sure to live long enough. The instance could be destroyed by the
// JOB_DONE broadcast.
scoped_refptr<PrintJob> handle(this);
// Stop the worker thread.
Stop();
scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL));
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get()));
}
void PrintJob::ControlledWorkerShutdown() {
DCHECK(RunsTasksOnCurrentThread());
// The deadlock this code works around is specific to window messaging on
// Windows, so we aren't likely to need it on any other platforms.
#if defined(OS_WIN)
// We could easily get into a deadlock case if worker_->Stop() is used; the
// printer driver created a window as a child of the browser window. By
// canceling the job, the printer driver initiated dialog box is destroyed,
// which sends a blocking message to its parent window. If the browser window
// thread is not processing messages, a deadlock occurs.
//
// This function ensures that the dialog box will be destroyed in a timely
// manner by the mere fact that the thread will terminate. So the potential
// deadlock is eliminated.
worker_->StopSoon();
// Delay shutdown until the worker terminates. We want this code path
// to wait on the thread to quit before continuing.
if (worker_->IsRunning()) {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PrintJob::ControlledWorkerShutdown, this),
base::TimeDelta::FromMilliseconds(100));
return;
}
#endif
// Now make sure the thread object is cleaned up. Do this on a worker
// thread because it may block.
base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&PrintJobWorker::Stop, base::Unretained(worker_.get())),
base::Bind(&PrintJob::HoldUntilStopIsCalled, this),
false);
is_job_pending_ = false;
registrar_.RemoveAll();
UpdatePrintedDocument(NULL);
}
void PrintJob::HoldUntilStopIsCalled() {
}
void PrintJob::Quit() {
base::MessageLoop::current()->Quit();
}
// Takes settings_ ownership and will be deleted in the receiving thread.
JobEventDetails::JobEventDetails(Type type,
PrintedDocument* document,
PrintedPage* page)
: document_(document),
page_(page),
type_(type) {
}
JobEventDetails::~JobEventDetails() {
}
PrintedDocument* JobEventDetails::document() const { return document_.get(); }
PrintedPage* JobEventDetails::page() const { return page_.get(); }
} // namespace printing
<commit_msg>Fix print spooler hangs when printing more than 3 pages on Windows.<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/printing/print_job.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/timer/timer.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job_worker.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "printing/printed_document.h"
#include "printing/printed_page.h"
#if defined(OS_WIN)
#include "chrome/browser/printing/pdf_to_emf_converter.h"
#include "printing/pdf_render_settings.h"
#endif
using base::TimeDelta;
namespace {
// Helper function to ensure |owner| is valid until at least |callback| returns.
void HoldRefCallback(const scoped_refptr<printing::PrintJobWorkerOwner>& owner,
const base::Closure& callback) {
callback.Run();
}
} // namespace
namespace printing {
PrintJob::PrintJob()
: source_(NULL),
worker_(),
settings_(),
is_job_pending_(false),
is_canceling_(false),
quit_factory_(this) {
// This is normally a UI message loop, but in unit tests, the message loop is
// of the 'default' type.
DCHECK(base::MessageLoopForUI::IsCurrent() ||
base::MessageLoop::current()->type() ==
base::MessageLoop::TYPE_DEFAULT);
}
PrintJob::~PrintJob() {
// The job should be finished (or at least canceled) when it is destroyed.
DCHECK(!is_job_pending_);
DCHECK(!is_canceling_);
DCHECK(!worker_ || !worker_->IsRunning());
DCHECK(RunsTasksOnCurrentThread());
}
void PrintJob::Initialize(PrintJobWorkerOwner* job,
PrintedPagesSource* source,
int page_count) {
DCHECK(!source_);
DCHECK(!worker_.get());
DCHECK(!is_job_pending_);
DCHECK(!is_canceling_);
DCHECK(!document_.get());
source_ = source;
worker_.reset(job->DetachWorker(this));
settings_ = job->settings();
PrintedDocument* new_doc =
new PrintedDocument(settings_,
source_,
job->cookie(),
content::BrowserThread::GetBlockingPool());
new_doc->set_page_count(page_count);
UpdatePrintedDocument(new_doc);
// Don't forget to register to our own messages.
registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this));
}
void PrintJob::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(RunsTasksOnCurrentThread());
switch (type) {
case chrome::NOTIFICATION_PRINT_JOB_EVENT: {
OnNotifyPrintJobEvent(*content::Details<JobEventDetails>(details).ptr());
break;
}
default: {
break;
}
}
}
void PrintJob::GetSettingsDone(const PrintSettings& new_settings,
PrintingContext::Result result) {
NOTREACHED();
}
PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) {
NOTREACHED();
return NULL;
}
const PrintSettings& PrintJob::settings() const {
return settings_;
}
int PrintJob::cookie() const {
if (!document_.get())
// Always use an invalid cookie in this case.
return 0;
return document_->cookie();
}
void PrintJob::StartPrinting() {
DCHECK(RunsTasksOnCurrentThread());
DCHECK(worker_->IsRunning());
DCHECK(!is_job_pending_);
if (!worker_->IsRunning() || is_job_pending_)
return;
// Real work is done in PrintJobWorker::StartPrinting().
worker_->PostTask(FROM_HERE,
base::Bind(&HoldRefCallback,
make_scoped_refptr(this),
base::Bind(&PrintJobWorker::StartPrinting,
base::Unretained(worker_.get()),
document_)));
// Set the flag right now.
is_job_pending_ = true;
// Tell everyone!
scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL));
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get()));
}
void PrintJob::Stop() {
DCHECK(RunsTasksOnCurrentThread());
if (quit_factory_.HasWeakPtrs()) {
// In case we're running a nested message loop to wait for a job to finish,
// and we finished before the timeout, quit the nested loop right away.
Quit();
quit_factory_.InvalidateWeakPtrs();
}
// Be sure to live long enough.
scoped_refptr<PrintJob> handle(this);
if (worker_->IsRunning()) {
ControlledWorkerShutdown();
} else {
// Flush the cached document.
UpdatePrintedDocument(NULL);
}
}
void PrintJob::Cancel() {
if (is_canceling_)
return;
is_canceling_ = true;
// Be sure to live long enough.
scoped_refptr<PrintJob> handle(this);
DCHECK(RunsTasksOnCurrentThread());
if (worker_ && worker_->IsRunning()) {
// Call this right now so it renders the context invalid. Do not use
// InvokeLater since it would take too much time.
worker_->Cancel();
}
// Make sure a Cancel() is broadcast.
scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::FAILED, NULL, NULL));
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get()));
Stop();
is_canceling_ = false;
}
bool PrintJob::FlushJob(base::TimeDelta timeout) {
// Make sure the object outlive this message loop.
scoped_refptr<PrintJob> handle(this);
base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&PrintJob::Quit, quit_factory_.GetWeakPtr()), timeout);
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
base::MessageLoop::current()->Run();
return true;
}
void PrintJob::DisconnectSource() {
source_ = NULL;
if (document_.get())
document_->DisconnectSource();
}
bool PrintJob::is_job_pending() const {
return is_job_pending_;
}
PrintedDocument* PrintJob::document() const {
return document_.get();
}
#if defined(OS_WIN)
class PrintJob::PdfToEmfState {
public:
PdfToEmfState(const gfx::Size& page_size, const gfx::Rect& content_area)
: page_count_(0),
current_page_(0),
pages_in_progress_(0),
page_size_(page_size),
content_area_(content_area),
converter_(PdfToEmfConverter::CreateDefault()) {}
void Start(const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
const PdfToEmfConverter::StartCallback& start_callback) {
converter_->Start(data, conversion_settings, start_callback);
}
void GetMorePages(
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
const int kMaxNumberOfTempFilesPerDocument = 3;
while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
current_page_ < page_count_) {
++pages_in_progress_;
converter_->GetPage(current_page_++, get_page_callback);
}
}
void OnPageProcessed(
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
--pages_in_progress_;
GetMorePages(get_page_callback);
// Release converter if we don't need this any more.
if (!pages_in_progress_ && current_page_ >= page_count_)
converter_.reset();
}
void set_page_count(int page_count) { page_count_ = page_count; }
gfx::Size page_size() const { return page_size_; }
gfx::Rect content_area() const { return content_area_; }
private:
int page_count_;
int current_page_;
int pages_in_progress_;
gfx::Size page_size_;
gfx::Rect content_area_;
scoped_ptr<PdfToEmfConverter> converter_;
};
void PrintJob::StartPdfToEmfConversion(
const scoped_refptr<base::RefCountedMemory>& bytes,
const gfx::Size& page_size,
const gfx::Rect& content_area) {
DCHECK(!ptd_to_emf_state_.get());
ptd_to_emf_state_.reset(new PdfToEmfState(page_size, content_area));
const int kPrinterDpi = settings().dpi();
ptd_to_emf_state_->Start(
bytes,
printing::PdfRenderSettings(content_area, kPrinterDpi, true),
base::Bind(&PrintJob::OnPdfToEmfStarted, this));
}
void PrintJob::OnPdfToEmfStarted(int page_count) {
if (page_count <= 0) {
ptd_to_emf_state_.reset();
Cancel();
return;
}
ptd_to_emf_state_->set_page_count(page_count);
ptd_to_emf_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}
void PrintJob::OnPdfToEmfPageConverted(int page_number,
float scale_factor,
scoped_ptr<MetafilePlayer> emf) {
DCHECK(ptd_to_emf_state_);
if (!document_.get() || !emf) {
ptd_to_emf_state_.reset();
Cancel();
return;
}
// Update the rendered document. It will send notifications to the listener.
document_->SetPage(page_number,
emf.Pass(),
scale_factor,
ptd_to_emf_state_->page_size(),
ptd_to_emf_state_->content_area());
ptd_to_emf_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}
#endif // OS_WIN
void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {
if (document_.get() == new_document)
return;
document_ = new_document;
if (document_.get()) {
settings_ = document_->settings();
}
if (worker_) {
DCHECK(!is_job_pending_);
// Sync the document with the worker.
worker_->PostTask(FROM_HERE,
base::Bind(&HoldRefCallback,
make_scoped_refptr(this),
base::Bind(&PrintJobWorker::OnDocumentChanged,
base::Unretained(worker_.get()),
document_)));
}
}
void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
switch (event_details.type()) {
case JobEventDetails::FAILED: {
settings_.Clear();
// No need to cancel since the worker already canceled itself.
Stop();
break;
}
case JobEventDetails::USER_INIT_DONE:
case JobEventDetails::DEFAULT_INIT_DONE:
case JobEventDetails::USER_INIT_CANCELED: {
DCHECK_EQ(event_details.document(), document_.get());
break;
}
case JobEventDetails::NEW_DOC:
case JobEventDetails::NEW_PAGE:
case JobEventDetails::JOB_DONE:
case JobEventDetails::ALL_PAGES_REQUESTED: {
// Don't care.
break;
}
case JobEventDetails::DOC_DONE: {
// This will call Stop() and broadcast a JOB_DONE message.
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this));
break;
}
case JobEventDetails::PAGE_DONE:
#if defined(OS_WIN)
ptd_to_emf_state_->OnPageProcessed(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
#endif // OS_WIN
break;
default: {
NOTREACHED();
break;
}
}
}
void PrintJob::OnDocumentDone() {
// Be sure to live long enough. The instance could be destroyed by the
// JOB_DONE broadcast.
scoped_refptr<PrintJob> handle(this);
// Stop the worker thread.
Stop();
scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL));
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get()));
}
void PrintJob::ControlledWorkerShutdown() {
DCHECK(RunsTasksOnCurrentThread());
// The deadlock this code works around is specific to window messaging on
// Windows, so we aren't likely to need it on any other platforms.
#if defined(OS_WIN)
// We could easily get into a deadlock case if worker_->Stop() is used; the
// printer driver created a window as a child of the browser window. By
// canceling the job, the printer driver initiated dialog box is destroyed,
// which sends a blocking message to its parent window. If the browser window
// thread is not processing messages, a deadlock occurs.
//
// This function ensures that the dialog box will be destroyed in a timely
// manner by the mere fact that the thread will terminate. So the potential
// deadlock is eliminated.
worker_->StopSoon();
// Delay shutdown until the worker terminates. We want this code path
// to wait on the thread to quit before continuing.
if (worker_->IsRunning()) {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PrintJob::ControlledWorkerShutdown, this),
base::TimeDelta::FromMilliseconds(100));
return;
}
#endif
// Now make sure the thread object is cleaned up. Do this on a worker
// thread because it may block.
base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&PrintJobWorker::Stop, base::Unretained(worker_.get())),
base::Bind(&PrintJob::HoldUntilStopIsCalled, this),
false);
is_job_pending_ = false;
registrar_.RemoveAll();
UpdatePrintedDocument(NULL);
}
void PrintJob::HoldUntilStopIsCalled() {
}
void PrintJob::Quit() {
base::MessageLoop::current()->Quit();
}
// Takes settings_ ownership and will be deleted in the receiving thread.
JobEventDetails::JobEventDetails(Type type,
PrintedDocument* document,
PrintedPage* page)
: document_(document),
page_(page),
type_(type) {
}
JobEventDetails::~JobEventDetails() {
}
PrintedDocument* JobEventDetails::document() const { return document_.get(); }
PrintedPage* JobEventDetails::page() const { return page_.get(); }
} // namespace printing
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE client
#include <boost/test/unit_test.hpp>
#include "client.hpp"
#include "request.hpp"
#include "reply.hpp"
BOOST_AUTO_TEST_CASE(check_readrequest)
{
request r;
BOOST_CHECK (read_request ("b", r) == invalid_request);
BOOST_CHECK (read_request ("open bla", r) == no_error);
}
<commit_msg>improve test case<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE client
#include <boost/test/unit_test.hpp>
#include "client.hpp"
#include "request.hpp"
#include "reply.hpp"
BOOST_AUTO_TEST_CASE(check_readrequest)
{
request r;
BOOST_CHECK (read_request ("aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbb", r) == invalid_request);
BOOST_CHECK (read_request ("b", r) == invalid_request);
BOOST_CHECK (read_request ("open bla", r) == no_error);
BOOST_CHECK (r.getType() == openfile);
BOOST_CHECK (read_request ("close 0", r) == no_error);
BOOST_CHECK (r.getType() == closefile);
BOOST_CHECK (read_request ("read 0 100", r) == no_error);
BOOST_CHECK (r.getType() == readfile);
}
<|endoftext|> |
<commit_before>// USE INF = 1e9!
// w: weight or cost, c : capacity
struct edge {int v, f, w, c; };
int node_count, flw_lmt=INF, src, snk, flw, cst, p[N], d[N], et[N];
vector<edge> e;
vector<int> g[N];
void add_edge(int u, int v, int w, int c) {
int k = e.size();
node_count = max(node_count, u+1);
node_count = max(node_count, v+1);
g[u].push_back(k);
g[v].push_back(k+1);
e.push_back({ v, 0, w, c });
e.push_back({ u, 0, -w, 0 });
}
void clear() {
flw_lmt = INF;
for(int i=0; i<node_count; ++i) g[i].clear();
e.clear();
node_count = 0;
}
void min_cost_max_flow() {
flw = 0, cst = 0;
while (flw < flw_lmt) {
memset(et, 0, sizeof et);
memset(d, 63, sizeof d);
deque<int> q;
q.push_back(src), d[src] = 0;
while (!q.empty()) {
int u = q.front(); q.pop_front();
et[u] = 2;
for(int i : g[u]) {
edge &dir = e[i];
int v = dir.v;
if (dir.f < dir.c and d[u] + dir.w < d[v]) {
d[v] = d[u] + dir.w;
if (et[v] == 0) q.push_back(v);
else if (et[v] == 2) q.push_front(v);
et[v] = 1;
p[v] = i;
}
}
}
if (d[snk] > INF) break;
int inc = flw_lmt - flw;
for (int u=snk; u != src; u = e[p[u]^1].v) {
edge &dir = e[p[u]];
inc = min(inc, dir.c - dir.f);
}
for (int u=snk; u != src; u = e[p[u]^1].v) {
edge &dir = e[p[u]], &rev = e[p[u]^1];
dir.f += inc;
rev.f -= inc;
cst += inc * dir.w;
}
if (!inc) break;
flw += inc;
}
}
<commit_msg>Fix for when graph has |E| = 0<commit_after>// USE INF = 1e9!
// w: weight or cost, c : capacity
struct edge {int v, f, w, c; };
int n, flw_lmt=INF, src, snk, flw, cst, p[N], d[N], et[N];
vector<edge> e;
vector<int> g[N];
void add_edge(int u, int v, int w, int c) {
int k = e.size();
g[u].push_back(k);
g[v].push_back(k+1);
e.push_back({ v, 0, w, c });
e.push_back({ u, 0, -w, 0 });
}
void clear() {
flw_lmt = INF;
for(int i=0; i<=n; ++i) g[i].clear();
e.clear();
}
void min_cost_max_flow() {
flw = 0, cst = 0;
while (flw < flw_lmt) {
memset(et, 0, (n+1) * sizeof(int));
memset(d, 63, (n+1) * sizeof(int));
deque<int> q;
q.push_back(src), d[src] = 0;
while (!q.empty()) {
int u = q.front(); q.pop_front();
et[u] = 2;
for(int i : g[u]) {
edge &dir = e[i];
int v = dir.v;
if (dir.f < dir.c and d[u] + dir.w < d[v]) {
d[v] = d[u] + dir.w;
if (et[v] == 0) q.push_back(v);
else if (et[v] == 2) q.push_front(v);
et[v] = 1;
p[v] = i;
}
}
}
if (d[snk] > INF) break;
int inc = flw_lmt - flw;
for (int u=snk; u != src; u = e[p[u]^1].v) {
edge &dir = e[p[u]];
inc = min(inc, dir.c - dir.f);
}
for (int u=snk; u != src; u = e[p[u]^1].v) {
edge &dir = e[p[u]], &rev = e[p[u]^1];
dir.f += inc;
rev.f -= inc;
cst += inc * dir.w;
}
if (!inc) break;
flw += inc;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: qtITK.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <qapplication.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkQtAdaptor.h"
#include "itkQtProgressBar.h"
int main(int argc, char **argv)
{
typedef itk::Image< float, 2 > ImageType;
typedef itk::DiscreteGaussianImageFilter<
ImageType,
ImageType > FilterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
// Create Qt Application to let Qt get its
// parameters from the command line
QApplication app( argc, argv );
reader->SetFileName( argv[1] );
QVBox qb;
qb.resize(120,200);
QPushButton bb( "Start", &qb );
bb.resize( 100, 30 );
QPushButton cc( "State", &qb );
cc.resize( 100, 30 );
QPushButton qt( "Quit", &qb );
qt.resize( 100, 30 );
itk::QtProgressBar qs( Qt::Horizontal, &qb, "Progress");
qs.resize( 100, 30 );
qs.setRange(0,100);
qs.setValue(0);
// Connect the progress bar to the ITK processObject
qs.Observe( filter.GetPointer() );
qs.Observe( reader.GetPointer() );
typedef itk::QtSlotAdaptor<FilterType> SlotAdaptorType;
SlotAdaptorType slotAdaptor;
// Connect the adaptor to a method of the ITK filter
slotAdaptor.SetCallbackFunction( filter, & FilterType::Update );
// Connect the adaptor's Slot to the Qt Widget Signal
QObject::connect( &bb, SIGNAL(clicked()), &slotAdaptor, SLOT(Slot()) );
typedef itk::QtSignalAdaptor SignalAdaptorType;
SignalAdaptorType signalAdaptor;
// Connect the adaptor as an observer of a Filter's event
filter->AddObserver( itk::StartEvent(), signalAdaptor.GetCommand() );
// Connect the adaptor's Signal to the Qt Widget Slot
QObject::connect( &signalAdaptor, SIGNAL(Signal()), &cc, SLOT(toggle()) );
// Connect the Quit button signal to the quit slot of the application
QObject::connect( &qt, SIGNAL(clicked()), &app, SLOT(quit()) );
app.setMainWidget( &qb );
qb.show();
return app.exec();
}
<commit_msg>ENH: AddImageFilter used to illustrate the progress bar.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: qtITK.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <qapplication.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkAddImageFilter.h"
#include "itkQtAdaptor.h"
#include "itkQtProgressBar.h"
int main(int argc, char **argv)
{
typedef itk::Image< float, 2 > ImageType;
typedef itk::AddImageFilter<
ImageType,
ImageType,
ImageType > FilterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
FilterType::Pointer filter = FilterType::New();
filter->SetInput1( reader->GetOutput() );
filter->SetInput2( reader->GetOutput() );
// Create Qt Application to let Qt get its
// parameters from the command line
QApplication app( argc, argv );
reader->SetFileName( argv[1] );
QVBox qb;
qb.resize(620,200);
QPushButton bb( "Start", &qb );
bb.resize( 100, 30 );
QPushButton cc( "State", &qb );
cc.resize( 100, 30 );
QPushButton qt( "Quit", &qb );
qt.resize( 100, 30 );
itk::QtProgressBar qs( Qt::Horizontal, &qb, "Progress");
qs.resize( 100, 30 );
qs.setRange(0,100);
qs.setValue(0);
// Connect the progress bar to the ITK processObject
qs.Observe( filter.GetPointer() );
qs.Observe( reader.GetPointer() );
typedef itk::QtSlotAdaptor<FilterType> SlotAdaptorType;
SlotAdaptorType slotAdaptor;
// Connect the adaptor to a method of the ITK filter
slotAdaptor.SetCallbackFunction( filter, & FilterType::Update );
// Connect the adaptor's Slot to the Qt Widget Signal
QObject::connect( &bb, SIGNAL(clicked()), &slotAdaptor, SLOT(Slot()) );
typedef itk::QtSignalAdaptor SignalAdaptorType;
SignalAdaptorType signalAdaptor;
// Connect the adaptor as an observer of a Filter's event
filter->AddObserver( itk::StartEvent(), signalAdaptor.GetCommand() );
// Connect the adaptor's Signal to the Qt Widget Slot
QObject::connect( &signalAdaptor, SIGNAL(Signal()), &cc, SLOT(toggle()) );
// Connect the Quit button signal to the quit slot of the application
QObject::connect( &qt, SIGNAL(clicked()), &app, SLOT(quit()) );
app.setMainWidget( &qb );
qb.show();
return app.exec();
}
<|endoftext|> |
<commit_before>AliAnalysisTask *AddTaskHFEnpePbPb5TeV(Bool_t MCthere,
Bool_t isAOD = kTRUE,
Bool_t kNPERef = kTRUE,
Bool_t kNPEkAny = kFALSE,
Bool_t newCentralitySelection = kTRUE, // kTRUE: new framework used; kFALSE: old framework used
Bool_t kNPERefTPConly = kFALSE,
Bool_t kNPETOFITS = kTRUE,
Bool_t kNPETOFlast = kFALSE,
Bool_t kNPEw = kFALSE,
Bool_t kNPEkf = kFALSE)
{
// Default settings (TOF-TPC PbPb)
const int kDefTPCcl = 120; // 100 (Andrea)
const int kDefTPCclPID = 80; // 90 (Andrea)
const int kDefTPCclshared = 1.1;
const int kDefITScl = 4; // 5 (Andrea)
const int kDefITSchi2percluster = -1; // cleanup removes badly matching tracks - effects high pt (cut value = 36) ---> 36 default value for AOD
const double kDefDCAr = 1.; // 2.4 (Andrea)
const double kDefDCAz = 2.; // 3.2 (Andrea)
const double kDefTOFs = 3.;
const double kDefITSs = 2.; // -1,1 up to 1.5, -2,2 up to 3 (Andrea)
const double kDefEtaIncMin = -0.8;
const double kDefEtaIncMax = 0.8;
const Bool_t etacorrection = kFALSE;
const Bool_t multicorrection = kFALSE;
// --- TPC nsigma max and min cut ---
Double_t dEdxhm[12] = {3.11,3.11,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0};
Double_t tpcl1[12] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; // my 46% (mfaggin)
Double_t tpcl2[12] = {-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1}; // my 50% (mfaggin)
Double_t tpcl3[12] = {0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18}; // my 40% (mfaggin)
Double_t tpcl4[12] = {-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38}; // my 60% (mfaggin)
// Default setting for the associated electron for the NonPhotonic Analysis
const double kassETAm = -0.8; // -0.9 (Andrea)
const double kassETAp = 0.8; // 0.9 (Andrea)
const int kassITS = 2; // # cluster
const int kassTPCcl = 60; // 80 (Andrea)
const int kassTPCPIDcl = 60; // not used (Andrea) ---> directly in the filterbit
const double kassDCAr = 1.0; // not used (Andrea) ---> directly in the filterbit 2.4
const double kassDCAz = 2.0; // not used (Andrea) ---> directly in the filterbit 3.2
const double kassTPCSminus = -3.0;
const double kassTPCSplus = 3.0;
// --- Centrality selection ---
const int centrMin = 0;
const int centrMax = 10;
Int_t kWei = -1;
/*
if (MCthere) kWei = 9; // default Pb-Pb
enum {
k11a10abisweiData = 6, // LHC11a10abis weights
k11a10bplusweiData = 7, // LHC11a10b_plus weights
k11a10bpluswei11a10abis = 8, // LHC11a10b_plus weights for LHC11a10abis
k11a10bbisweiData = 9, // LHC11a10bbis weights
};
*/
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_hfe_HFE", "No analysis manager found.");
return 0;
}
//mgr->AddClassDebug("AliAnalysisTaskHFE",12);
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
//@@ 0 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Double_t dEdxaclm[12], dEdxachm[12];
for(int icent = 0; icent < 12; icent++){
dEdxaclm[icent] = kassTPCSminus;
dEdxachm[icent] = kassTPCSplus;
}
const Bool_t isBeauty = kFALSE; // should be false to prevent inclusive analysis
if(kNPERef){
// **************************************************************
//
// Reference task
//
// **************************************************************
// TPC low cut = 0 (tpcl1)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// Additional tasks
// (sma, 6.6.2017) Vary the TOF cut to +-2 sigma)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, 2., 0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// TPC low cut = -0.1 (tpcl2)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// TPC low cut = 0.16 (tpcl3)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl3, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// TPC low cut = -0.38 (tpcl4)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl4, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
}
if(kNPETOFlast){
// **************************************************************
//
// Apply TOF after TPC for mismatch background studies
//
// **************************************************************
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kTRUE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
}
if(kNPEkAny){
// **************************************************************
//
// task for kAny instead of kBoth
//
// **************************************************************
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kAny, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
}
if(kNPEw && MCthere){
// **************************************************************
//
// Reference task
//
// **************************************************************
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE, 0,kWei);
}
if(kNPERefTPConly){
// **************************************************************
//
// Reference task
//
// **************************************************************
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, 0.,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
}
if(kNPETOFITS){
// **************************************************************
//
// Reference task
//
// **************************************************************
// TPC low cut = 0 (tpcl1)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs, kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// Additional tasks
// (sma, 6.6.2017) Vary the ITS cut to +-1
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, kDefTOFs, 1., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// (sma, 6.6.2017) Vary the ITS cut to +-3
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, kDefTOFs, 3., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// TPC low cut = -0.1 (tpcl2)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, kDefTOFs, kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// TPC low cut = 0.16 (tpcl3)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl3, dEdxhm, kDefTOFs, kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
// TPC low cut = -0.38 (tpcl4)
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl4, dEdxhm, kDefTOFs, kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
}
if(kNPEkf){
// **************************************************************
//
// Use KF particle
//
// **************************************************************
RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1,2,kFALSE,kFALSE,kFALSE,kTRUE);
}
return NULL;
}
//===============================================================================
//===============================================================================
AliAnalysisTask *RegisterTaskNPEPbPb(
Int_t centrMin = 0, Int_t centrMax = 100,
Bool_t newCentralitySelection = kTRUE, // kTRUE: new framework used; kFALSE: old framework used
Bool_t useMC, Bool_t isAOD, Bool_t beauty,
Int_t tpcCls=120, Int_t tpcClsPID=80,
Int_t itsCls=4, Double_t dcaxy=1.0, Double_t dcaz=2.0,
Double_t *tpcdEdxcutlow=NULL, Double_t *tpcdEdxcuthigh=NULL,
Double_t tofs=3., Double_t itss=0., Int_t itshitpixel =AliHFEextraCuts::kBoth,
Double_t itschi2percluster = -1, Double_t tpcsharedcluster = 1.1,
Bool_t etacorr=kFALSE, Bool_t multicorr = kFALSE, Bool_t toflast = kFALSE,
Double_t etaIncMin = -0.8, Double_t etaIncMax = 0.8,
Double_t assETAm=-0.8, Double_t assETAp=0.8, Int_t assITS=2, Int_t assTPCcl=100,
Int_t assTPCPIDcl=80, Double_t assDCAr=1.0, Double_t assDCAz=2.0,
Double_t *assTPCSminus = NULL, Double_t *assTPCSplus=NULL,
Bool_t useCat1Tracks = kTRUE, Bool_t useCat2Tracks = kTRUE,
Int_t weightlevelback = -1,Int_t wei = 2,
Bool_t releasemcvx = kFALSE,
Bool_t ipCharge = kFALSE,
Bool_t ipOpp = kFALSE,
Bool_t usekfparticle = kFALSE)
{
//
// Cuts on the inclusive leg
//
Int_t idcaxy = (Int_t)(dcaxy*10.);
Int_t idcaz = (Int_t)(dcaz*10.);
Int_t tpclow = 0;
// ------- to manage containers name with negative TPC low cut --------
bool IsTPClowcutNegative = kFALSE;
if(tpcdEdxcutlow)
{
tpclow = (Int_t) (tpcdEdxcutlow[0]*1000.);
if(tpclow<0)
{
IsTPClowcutNegative = kTRUE;
tpclow = 0 - tpclow; // switched signed (ready to be used in the container name)
}
}
// --------------------------------------------------------------------
Int_t itofs = (Int_t)(tofs*10.);
Int_t iitss = (Int_t)(itss*10.);
Int_t ipixelany = itshitpixel;
Int_t imult = multicorr ? 1 : 0;
Int_t itofpos = toflast ? 1 : 0;
//
// Cuts on the associated leg
//
Int_t iassDCAr = (Int_t)(assDCAr*10);
Int_t iassDCAz = (Int_t)(assDCAz*10);
Int_t iassTPCSplus = assTPCSplus ? (Int_t)(assTPCSplus[0]*1000) : 0;
Int_t icat1 = useCat1Tracks ? 1 : 0;
Int_t icat2 = useCat2Tracks ? 1 : 0;
Bool_t nondefaultcentr = kFALSE;
TString cweightsback("");
if(weightlevelback>=0) {
cweightsback += "Wa";
cweightsback += weightlevelback;
}
TString cmvx("");
if(releasemcvx) {
cmvx += "MCVR";
}
TString kfp("");
if(usekfparticle) {
kfp += "kf";
}
if(beauty) {
if(ipCharge && ipOpp) TString cbeauty("BeautyIPopp");
else if(ipCharge) TString cbeauty("BeautyIPcrg");
else if(!ipCharge) TString cbeauty("Beauty");
else TString cbeauty("BeautyWrong");
}
else TString cbeauty("");
// ------- to manage containers name with negative TPC low cut --------
TString appendix = ""; // letter 'm' added in this point (after TPCs)
if(IsTPClowcutNegative) appendix+=TString::Format("SPD%d_incTPCc%dTPCp%dITS%dDCAr%dz%dTPCsm%dTOFs%dITSs%dm%dt%d_photTPCc%dTPCp%dITS%dDCAr%dDCAz%dTPCs%d%s%s%s%s",ipixelany,tpcCls,tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,iitss,imult,itofpos,assTPCcl,assTPCPIDcl,assITS,iassDCAr,iassDCAz,iassTPCSplus,cweightsback.Data(),cmvx.Data(),cbeauty.Data(),kfp.Data());
else appendix+=TString::Format("SPD%d_incTPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dITSs%dm%dt%d_photTPCc%dTPCp%dITS%dDCAr%dDCAz%dTPCs%d%s%s%s%s",ipixelany,tpcCls,tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,iitss,imult,itofpos,assTPCcl,assTPCPIDcl,assITS,iassDCAr,iassDCAz,iassTPCSplus,cweightsback.Data(),cmvx.Data(),cbeauty.Data(),kfp.Data());
//TString appendix(TString::Format("SPD%d_incTPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dITSs%dm%dt%d_photTPCc%dTPCp%dITS%dDCAr%dDCAz%dTPCs%d%s%s%s%s",ipixelany,tpcCls,tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,iitss,imult,itofpos,assTPCcl,assTPCPIDcl,assITS,iassDCAr,iassDCAz,iassTPCSplus,cweightsback.Data(),cmvx.Data(),cbeauty.Data(),kfp.Data())); // old version
// --------------------------------------------------------------------
printf("Add macro appendix %s\n", appendix.Data());
// --------------------------------------------------------------------
// GRID version
if(useMC&&!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigWeightFactors")) gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/ConfigWeightFactors.C");
if(!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigHFEnpePbPb5TeV"))gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/PbPb/ConfigHFEnpePbPb5TeV.C");
// GSI version
//if(useMC&&!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigWeightFactors")) gROOT->LoadMacro("$TRAIN_ROOT/util/hfe/configs/ConfigWeightFactors.C");
//if(!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigHFEnpePbPb5TeV")) gROOT->LoadMacro("$TRAIN_ROOT/util/hfe/configs/ConfigHFEnpePbPb5TeV.C");
// --------------------------------------------------------------------
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisTaskHFE *task = ConfigHFEnpePbPb5TeV(useMC, isAOD, appendix, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz, tpcdEdxcutlow, tpcdEdxcuthigh, tofs, 0, itss, itshitpixel, itschi2percluster, tpcsharedcluster, etacorr, multicorr, toflast, etaIncMin, etaIncMax,
assETAm, assETAp, assITS, assTPCcl, assTPCPIDcl,
assDCAr, assDCAz, assTPCSminus, assTPCSplus,
useCat1Tracks, useCat2Tracks, weightlevelback,usekfparticle);
// old config file
//AliAnalysisTaskHFE *task = ConfigHFEnpePbPb(useMC, isAOD, appendix, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz, tpcdEdxcutlow, tpcdEdxcuthigh, tofs, 0, itss, itshitpixel, itschi2percluster, tpcsharedcluster, etacorr, multicorr, toflast, etaIncMin, etaIncMax,
// assETAm, assETAp, assITS, assTPCcl, assTPCPIDcl,
// assDCAr, assDCAz, assTPCSminus, assTPCSplus,
// useCat1Tracks, useCat2Tracks, weightlevelback,usekfparticle);
if(isAOD)
task->SetAODAnalysis();
else
task->SetESDAnalysis();
if (useMC) task->SetHasMCData(kTRUE);
else task->SetHasMCData(kFALSE);
if(useMC&&(beauty || (weightlevelback>=0))) ConfigWeightFactors(task,kFALSE,wei);//2;For default PbPb
// ----- centrality selection -----
task->SetCentralityCheck(newCentralitySelection,"V0M");
task->SetCentralityInterval(centrMin,centrMax); // all events outside the desired centrality interval are rejected
// --------------------------------
// ----- trigger selecton ---------
if(!newCentralitySelection) task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral); // old framework
if(newCentralitySelection) task->SelectCollisionCandidates(AliVEvent::kINT7); // new framework
// --------------------------------
TString containerName = mgr->GetCommonFileName();
containerName += ":HFEtask";
containerName += appendix.Data();
printf("container name: %s\n", containerName.Data());
//create data containers
task->ConnectOutput(1, mgr->CreateContainer(Form("HFE_Results_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()));
task->ConnectOutput(2, mgr->CreateContainer(Form("HFE_QA_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()));
mgr->ConnectInput(task, 0, cinput );
mgr->AddTask(task);
return NULL;
}
<commit_msg>remove addtask HFE run2 PbPb<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2018 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.
*/
// Publishes a frozen nav_msgs/OccupancyGrid map from serialized submaps.
#include <map>
#include <string>
#include "cartographer/io/proto_stream.h"
#include "cartographer/io/proto_stream_deserializer.h"
#include "cartographer/io/submap_painter.h"
#include "cartographer/mapping/2d/probability_grid.h"
#include "cartographer/mapping/2d/submap_2d.h"
#include "cartographer/mapping/3d/submap_3d.h"
#include "cartographer_ros/msg_conversion.h"
#include "cartographer_ros/node_constants.h"
#include "cartographer_ros/ros_log_sink.h"
#include "cartographer_ros/ros_map.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "nav_msgs/OccupancyGrid.h"
#include "ros/ros.h"
DEFINE_string(pbstream_filename, "",
"Filename of a pbstream to draw a map from.");
DEFINE_string(map_topic, "map", "Name of the published map topic.");
DEFINE_string(map_frame_id, "map", "Frame ID of the published map.");
DEFINE_double(resolution, 0.05, "Resolution of a grid cell in the drawn map.");
namespace cartographer_ros {
namespace {
std::unique_ptr<nav_msgs::OccupancyGrid> LoadOccupancyGridMsg(
const std::string& pbstream_filename, const double resolution) {
::cartographer::io::ProtoStreamReader reader(pbstream_filename);
::cartographer::io::ProtoStreamDeserializer deserializer(&reader);
LOG(INFO) << "Loading submap slices from serialized data.";
std::map<::cartographer::mapping::SubmapId, ::cartographer::io::SubmapSlice>
submap_slices;
::cartographer::mapping::ValueConversionTables conversion_tables;
::cartographer::io::DeserializeAndFillSubmapSlices(
&deserializer, &submap_slices, &conversion_tables);
CHECK(reader.eof());
LOG(INFO) << "Generating combined map image from submap slices.";
const auto painted_slices =
::cartographer::io::PaintSubmapSlices(submap_slices, resolution);
return CreateOccupancyGridMsg(painted_slices, resolution, FLAGS_map_frame_id,
ros::Time::now());
}
void Run(const std::string& pbstream_filename, const std::string& map_topic,
const std::string& map_frame_id, const double resolution) {
std::unique_ptr<nav_msgs::OccupancyGrid> msg_ptr =
LoadOccupancyGridMsg(pbstream_filename, resolution);
::ros::NodeHandle node_handle("");
::ros::Publisher pub = node_handle.advertise<nav_msgs::OccupancyGrid>(
map_topic, kLatestOnlyPublisherQueueSize, true /*latched */);
LOG(INFO) << "Publishing occupancy grid topic " << map_topic
<< " (frame_id: " << map_frame_id
<< ", resolution:" << std::to_string(resolution) << ").";
pub.publish(*msg_ptr);
::ros::spin();
::ros::shutdown();
}
} // namespace
} // namespace cartographer_ros
int main(int argc, char** argv) {
FLAGS_alsologtostderr = true;
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
CHECK(!FLAGS_pbstream_filename.empty()) << "-pbstream_filename is missing.";
::ros::init(argc, argv, "cartographer_pbstream_map_publisher");
::ros::start();
cartographer_ros::ScopedRosLogSink ros_log_sink;
::cartographer_ros::Run(FLAGS_pbstream_filename, FLAGS_map_topic,
FLAGS_map_frame_id, FLAGS_resolution);
}
<commit_msg>Only use ROS log sink in pbstream_map_publisher_main.cc (#1040)<commit_after>/*
* Copyright 2018 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.
*/
// Publishes a frozen nav_msgs/OccupancyGrid map from serialized submaps.
#include <map>
#include <string>
#include "cartographer/io/proto_stream.h"
#include "cartographer/io/proto_stream_deserializer.h"
#include "cartographer/io/submap_painter.h"
#include "cartographer/mapping/2d/probability_grid.h"
#include "cartographer/mapping/2d/submap_2d.h"
#include "cartographer/mapping/3d/submap_3d.h"
#include "cartographer_ros/msg_conversion.h"
#include "cartographer_ros/node_constants.h"
#include "cartographer_ros/ros_log_sink.h"
#include "cartographer_ros/ros_map.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "nav_msgs/OccupancyGrid.h"
#include "ros/ros.h"
DEFINE_string(pbstream_filename, "",
"Filename of a pbstream to draw a map from.");
DEFINE_string(map_topic, "map", "Name of the published map topic.");
DEFINE_string(map_frame_id, "map", "Frame ID of the published map.");
DEFINE_double(resolution, 0.05, "Resolution of a grid cell in the drawn map.");
namespace cartographer_ros {
namespace {
std::unique_ptr<nav_msgs::OccupancyGrid> LoadOccupancyGridMsg(
const std::string& pbstream_filename, const double resolution) {
::cartographer::io::ProtoStreamReader reader(pbstream_filename);
::cartographer::io::ProtoStreamDeserializer deserializer(&reader);
LOG(INFO) << "Loading submap slices from serialized data.";
std::map<::cartographer::mapping::SubmapId, ::cartographer::io::SubmapSlice>
submap_slices;
::cartographer::mapping::ValueConversionTables conversion_tables;
::cartographer::io::DeserializeAndFillSubmapSlices(
&deserializer, &submap_slices, &conversion_tables);
CHECK(reader.eof());
LOG(INFO) << "Generating combined map image from submap slices.";
const auto painted_slices =
::cartographer::io::PaintSubmapSlices(submap_slices, resolution);
return CreateOccupancyGridMsg(painted_slices, resolution, FLAGS_map_frame_id,
ros::Time::now());
}
void Run(const std::string& pbstream_filename, const std::string& map_topic,
const std::string& map_frame_id, const double resolution) {
std::unique_ptr<nav_msgs::OccupancyGrid> msg_ptr =
LoadOccupancyGridMsg(pbstream_filename, resolution);
::ros::NodeHandle node_handle("");
::ros::Publisher pub = node_handle.advertise<nav_msgs::OccupancyGrid>(
map_topic, kLatestOnlyPublisherQueueSize, true /*latched */);
LOG(INFO) << "Publishing occupancy grid topic " << map_topic
<< " (frame_id: " << map_frame_id
<< ", resolution:" << std::to_string(resolution) << ").";
pub.publish(*msg_ptr);
::ros::spin();
::ros::shutdown();
}
} // namespace
} // namespace cartographer_ros
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
CHECK(!FLAGS_pbstream_filename.empty()) << "-pbstream_filename is missing.";
::ros::init(argc, argv, "cartographer_pbstream_map_publisher");
::ros::start();
cartographer_ros::ScopedRosLogSink ros_log_sink;
::cartographer_ros::Run(FLAGS_pbstream_filename, FLAGS_map_topic,
FLAGS_map_frame_id, FLAGS_resolution);
}
<|endoftext|> |
<commit_before>// AddTaskEmcalJetSpectraQA.C
AliAnalysisHFjetTagHFE* AddTaskHFjetTagHFE(
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *njets = "Jets",
const char *nrho = "Rho",
Double_t jetradius = 0.3,
Double_t jetptcut = 1,
Double_t jetareacut = 0.2,
const char *cutType = "TPCfid",
Int_t leadhadtype = 0,
const char *suffix = "",
Bool_t iMC = kFALSE
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskHFjetTagHFE", "No analysis manager to connect to.");
return 0;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
AliVEventHandler* handler = mgr->GetInputEventHandler();
if (!handler)
{
::Error("AddTaskHFjetTagHFE", "This task requires an input event handler");
return 0;
}
enum EDataType_t {
kUnknown,
kESD,
kAOD
};
EDataType_t dataType = kUnknown;
if (handler->InheritsFrom("AliESDInputHandler")) {
dataType = kESD;
}
else if (handler->InheritsFrom("AliAODInputHandler")) {
dataType = kAOD;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString trackName(ntracks);
TString clusName(nclusters);
if (trackName == "usedefault") {
if (dataType == kESD) {
trackName = "Tracks";
}
else if (dataType == kAOD) {
trackName = "tracks";
}
else {
trackName = "";
}
}
if (clusName == "usedefault") {
if (dataType == kESD) {
clusName = "CaloClusters";
}
else if (dataType == kAOD) {
clusName = "caloClusters";
}
else {
clusName = "";
}
}
TString name("AliAnalysisHFjetTagHFE");
if (strcmp(njets,"")) {
name += "_";
name += njets;
}
if (strcmp(nrho,"")) {
name += "_";
name += nrho;
}
name += "_";
name += cutType;
if (strcmp(suffix,"")) {
name += "_";
name += suffix;
}
AliAnalysisHFjetTagHFE* jetTask = new AliAnalysisHFjetTagHFE(name);
jetTask->SetVzRange(-10,10);
jetTask->SetNeedEmcalGeom(kFALSE);
Double_t JetEta = 0.9-jetradius;
cout << "<----------- JetEta = " << JetEta << endl;
jetTask->SetJetEtaCut(JetEta);
/*
AliParticleContainer *trackCont = jetTask->AddTrackContainer(trackName);
AliClusterContainer *clusterCont = jetTask->AddClusterContainer(clusName);
*/
//if (trackName == "mcparticles") {
//AliMCParticleContainer* mcpartCont = jetTask->AddMCParticleContainer(trackName);
//mcpartCont->SelectPhysicalPrimaries(kTRUE);
//}
//else if (trackName == "tracks" || trackName == "Tracks") {
if (trackName == "tracks" || trackName == "Tracks") {
AliTrackContainer* trackCont = jetTask->AddTrackContainer(trackName);
trackCont->SetFilterHybridTracks(kTRUE);
}
else if (!trackName.IsNull()) {
jetTask->AddParticleContainer(trackName);
}
/*
AliParticleContainer *partCont = jetTask->GetParticleContainer(0);
if (partCont) {
partCont->SetParticlePtCut(trackPtCut);
}
*/
AliClusterContainer *clusterCont = jetTask->AddClusterContainer(clusName);
if (clusterCont) {
clusterCont->SetClusECut(0.);
clusterCont->SetClusPtCut(0.);
clusterCont->SetClusHadCorrEnergyCut(clusECut);
clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
}
//AliJetContainer *jetCont = jetTask->AddJetContainer(njets, cutType, jetradius);
AliJetContainer* jetCont = jetTask->AddJetContainer(AliJetContainer::kChargedJet, AliJetContainer::antikt_algorithm, AliJetContainer::pt_scheme, jetradius, AliJetContainer::kTPCfid, "Jet");
if (jetCont) {
//jetCont->SetRhoName(nrho);
jetCont->SetRhoName("Rho");
cout << "Name of Rho " << jetCont->GetRhoName() << endl;
//if(jetradius==0.3)jetareacut=0.2;
jetareacut = jetradius*jetradius*TMath::Pi()*0.6;
cout << "jetradius = " << jetradius << " ; jetareacut = " << jetareacut << endl;
//+++ jetCont->SetPercAreaCut(jetareacut);
jetCont->SetJetAreaCut(jetareacut);
jetCont->SetJetPtCut(jetptcut);
jetCont->ConnectParticleContainer(trackCont);
jetCont->ConnectClusterContainer(clusterCont);
jetCont->SetLeadingHadronType(leadhadtype);
jetCont->SetMaxTrackPt(1000);
jetCont->SetZLeadingCut(0.98,0.98);
}
if(iMC)
{
//AliTrackContainer* trackContMC = jetTask->AddTrackContainer("mcparticles");
AliMCParticleContainer* trackContMC = jetTask->AddMCParticleContainer("mcparticles");
//AliJetContainer* jetContMC = jetTask->AddJetContainer(AliJetContainer::kChargedJet, AliJetContainer::antikt_algorithm, AliJetContainer::pt_scheme, jetradius, AliJetContainer::kTPCfid, "JetMC");
//AliJetContainer* jetContMC = jetTask->AddJetContainer("JetMC_AKTChargedR030_mcparticles_pT0150_pt_scheme");
AliJetContainer* jetContMC;
if(jetradius==0.3)jetTask->AddJetContainer("JetMC_AKTChargedR030_mcparticles_pT0150_pt_scheme");
if(jetradius==0.2)jetTask->AddJetContainer("JetMC_AKTChargedR020_mcparticles_pT0150_pt_scheme");
if(jetradius==0.4)jetTask->AddJetContainer("JetMC_AKTChargedR040_mcparticles_pT0150_pt_scheme");
if (jetContMC) {
//jetCont->SetRhoName(nrho);
//if(jetradius==0.3)jetareacut=0.2;
jetContMC->SetJetAreaCut(jetareacut);
jetContMC->SetJetPtCut(jetptcut);
jetContMC->ConnectParticleContainer(trackContMC);
jetContMC->ConnectClusterContainer(clusterCont);
jetContMC->SetLeadingHadronType(leadhadtype);
jetContMC->SetMaxTrackPt(1000);
jetContMC->SetZLeadingCut(0.98,0.98);
}
}
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(jetTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ;
TString contname(name);
contname += "_histos";
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contname.Data(),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectInput (jetTask, 0, cinput1 );
mgr->ConnectOutput (jetTask, 1, coutput1 );
return jetTask;
}
<commit_msg>modified to work with root6<commit_after>// AddTaskEmcalJetSpectraQA.C
AliAnalysisHFjetTagHFE* AddTaskHFjetTagHFE(
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *njets = "Jets",
const char *nrho = "Rho",
Double_t jetradius = 0.3,
Double_t jetptcut = 1,
Double_t jetareacut = 0.2,
const char *cutType = "TPCfid",
Int_t leadhadtype = 0,
const char *suffix = "",
Bool_t iMC = kFALSE
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskHFjetTagHFE", "No analysis manager to connect to.");
return 0;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
AliVEventHandler* handler = mgr->GetInputEventHandler();
if (!handler)
{
::Error("AddTaskHFjetTagHFE", "This task requires an input event handler");
return 0;
}
enum EDataType_t {
kUnknown,
kESD,
kAOD
};
EDataType_t dataType = kUnknown;
if (handler->InheritsFrom("AliESDInputHandler")) {
dataType = kESD;
}
else if (handler->InheritsFrom("AliAODInputHandler")) {
dataType = kAOD;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString trackName(ntracks);
TString clusName(nclusters);
if (trackName == "usedefault") {
if (dataType == kESD) {
trackName = "Tracks";
}
else if (dataType == kAOD) {
trackName = "tracks";
}
else {
trackName = "";
}
}
if (clusName == "usedefault") {
if (dataType == kESD) {
clusName = "CaloClusters";
}
else if (dataType == kAOD) {
clusName = "caloClusters";
}
else {
clusName = "";
}
}
TString name("AliAnalysisHFjetTagHFE");
if (strcmp(njets,"")) {
name += "_";
name += njets;
}
if (strcmp(nrho,"")) {
name += "_";
name += nrho;
}
name += "_";
name += cutType;
if (strcmp(suffix,"")) {
name += "_";
name += suffix;
}
AliAnalysisHFjetTagHFE* jetTask = new AliAnalysisHFjetTagHFE(name);
jetTask->SetVzRange(-10,10);
jetTask->SetNeedEmcalGeom(kFALSE);
Double_t JetEta = 0.9-jetradius;
cout << "<----------- JetEta = " << JetEta << endl;
jetTask->SetJetEtaCut(JetEta);
AliTrackContainer* trackCont = 0;
//if (trackName == "mcparticles") {
//AliMCParticleContainer* mcpartCont = jetTask->AddMCParticleContainer(trackName);
//mcpartCont->SelectPhysicalPrimaries(kTRUE);
//}
//else if (trackName == "tracks" || trackName == "Tracks") {
if (trackName == "tracks" || trackName == "Tracks") {
//AliTrackContainer* trackCont = jetTask->AddTrackContainer(trackName);
trackCont = jetTask->AddTrackContainer(trackName);
trackCont->SetFilterHybridTracks(kTRUE);
}
else if (!trackName.IsNull()) {
jetTask->AddParticleContainer(trackName);
}
/*
AliParticleContainer *partCont = jetTask->GetParticleContainer(0);
if (partCont) {
partCont->SetParticlePtCut(trackPtCut);
}
*/
AliClusterContainer *clusterCont = jetTask->AddClusterContainer(clusName);
if (clusterCont) {
clusterCont->SetClusECut(0.);
clusterCont->SetClusPtCut(0.);
clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
}
//AliJetContainer *jetCont = jetTask->AddJetContainer(njets, cutType, jetradius);
AliJetContainer* jetCont = jetTask->AddJetContainer(AliJetContainer::kChargedJet, AliJetContainer::antikt_algorithm, AliJetContainer::pt_scheme, jetradius, AliJetContainer::kTPCfid, "Jet");
if (jetCont) {
//jetCont->SetRhoName(nrho);
jetCont->SetRhoName("Rho");
cout << "Name of Rho " << jetCont->GetRhoName() << endl;
//if(jetradius==0.3)jetareacut=0.2;
jetareacut = jetradius*jetradius*TMath::Pi()*0.6;
cout << "jetradius = " << jetradius << " ; jetareacut = " << jetareacut << endl;
//+++ jetCont->SetPercAreaCut(jetareacut);
jetCont->SetJetAreaCut(jetareacut);
jetCont->SetJetPtCut(jetptcut);
jetCont->ConnectParticleContainer(trackCont);
jetCont->ConnectClusterContainer(clusterCont);
jetCont->SetLeadingHadronType(leadhadtype);
jetCont->SetMaxTrackPt(1000);
jetCont->SetZLeadingCut(0.98,0.98);
}
if(iMC)
{
//AliTrackContainer* trackContMC = jetTask->AddTrackContainer("mcparticles");
AliMCParticleContainer* trackContMC = jetTask->AddMCParticleContainer("mcparticles");
//AliJetContainer* jetContMC = jetTask->AddJetContainer(AliJetContainer::kChargedJet, AliJetContainer::antikt_algorithm, AliJetContainer::pt_scheme, jetradius, AliJetContainer::kTPCfid, "JetMC");
//AliJetContainer* jetContMC = jetTask->AddJetContainer("JetMC_AKTChargedR030_mcparticles_pT0150_pt_scheme");
AliJetContainer* jetContMC;
if(jetradius==0.3)jetContMC = jetTask->AddJetContainer("JetMC_AKTChargedR030_mcparticles_pT0150_pt_scheme");
if(jetradius==0.2)jetContMC = jetTask->AddJetContainer("JetMC_AKTChargedR020_mcparticles_pT0150_pt_scheme");
if(jetradius==0.4)jetContMC = jetTask->AddJetContainer("JetMC_AKTChargedR040_mcparticles_pT0150_pt_scheme");
if (jetContMC) {
//jetCont->SetRhoName(nrho);
//if(jetradius==0.3)jetareacut=0.2;
jetContMC->SetJetAreaCut(jetareacut);
jetContMC->SetJetPtCut(jetptcut);
jetContMC->ConnectParticleContainer(trackContMC);
jetContMC->ConnectClusterContainer(clusterCont);
jetContMC->SetLeadingHadronType(leadhadtype);
jetContMC->SetMaxTrackPt(1000);
jetContMC->SetZLeadingCut(0.98,0.98);
}
}
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(jetTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ;
TString contname(name);
contname += "_histos";
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contname.Data(),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectInput (jetTask, 0, cinput1 );
mgr->ConnectOutput (jetTask, 1, coutput1 );
return jetTask;
}
<|endoftext|> |
<commit_before>#include "acmacs-base/rjson-v3.hh"
#include "acmacs-draw/continent-map.hh"
#include "acmacs-draw/draw-legend.hh"
#include "acmacs-draw/draw-elements.hh"
#include "acmacs-map-draw/map-elements-v1.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/mapi-settings.hh"
// ----------------------------------------------------------------------
void map_elements::Elements::add_basic_elements_v1()
{
add<map_elements::v1::BackgroundBorderGrid>();
} // map_elements::Elements::add_basic_elements_v1
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::BackgroundBorderGrid::draw(acmacs::surface::Surface& aSurface, const ChartDraw&) const
{
const auto& v = aSurface.viewport();
aSurface.rectangle_filled(v.origin, v.size, mBackground, Pixels{0}, mBackground);
aSurface.grid(Scaled{1}, mGridColor, mGridLineWidth);
aSurface.rectangle(v.origin, v.size, mBorderColor, mBorderWidth);
} // map_elements::v1::BackgroundBorderGrid::draw
// ----------------------------------------------------------------------
void map_elements::v1::BackgroundBorderGrid::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.border(mBorderColor, mBorderWidth);
aDrawElements.background(mBackground);
aDrawElements.grid(Scaled{1}, mGridColor, mGridLineWidth);
} // map_elements::v1::BackgroundBorderGrid::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::ContinentMap::draw(acmacs::surface::Surface& aSurface, const ChartDraw&) const
{
acmacs::PointCoordinates origin = mOrigin;
if (origin.x() < 0)
origin.x(origin.x() + aSurface.width_in_pixels() - mWidthInParent.value());
if (origin.y() < 0)
origin.y(origin.y() + aSurface.height_in_pixels() - mWidthInParent.value() / continent_map_aspect());
acmacs::surface::Surface& continent_surface = aSurface.subsurface(origin, mWidthInParent, continent_map_size(), true);
continent_map_draw(continent_surface);
} // map_elements::ContinentMap::draw
// ----------------------------------------------------------------------
void map_elements::v1::ContinentMap::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.continent_map(mOrigin, mWidthInParent);
} // map_elements::v1::ContinentMap::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::LegendPointLabel::draw(acmacs::surface::Surface& aSurface, const ChartDraw&) const
{
if (!mLines.empty()) {
double width = 0, height = 0;
for (const auto& line: mLines) {
const acmacs::Size line_size = aSurface.text_size(line.label, mLabelSize, mLabelStyle);
if (line_size.width > width)
width = line_size.width;
if (line_size.height > height)
height = line_size.height;
}
const acmacs::Size padding = aSurface.text_size("O", mLabelSize, mLabelStyle);
const double scaled_point_size = aSurface.convert(mPointSize).value();
const acmacs::Size legend_surface_size{width + padding.width * 3 + scaled_point_size,
height * static_cast<double>(mLines.size() - 1) * mInterline + height + padding.height * 2};
const acmacs::PointCoordinates legend_surface_origin = subsurface_origin(aSurface, mOrigin, legend_surface_size);
acmacs::surface::Surface& legend_surface = aSurface.subsurface(legend_surface_origin, Scaled{legend_surface_size.width}, legend_surface_size, false);
const auto& legend_v = legend_surface.viewport();
legend_surface.rectangle_filled(legend_v.origin, legend_v.size, mBackground, Pixels{0}, mBackground);
legend_surface.rectangle(legend_v.origin, legend_v.size, mBorderColor, mBorderWidth);
const double point_x = padding.width + scaled_point_size / 2;
const double text_x = padding.width * 2 + scaled_point_size;
double y = padding.height + height;
for (const auto& line: mLines) {
legend_surface.circle_filled({point_x, y - height / 2}, mPointSize, AspectNormal, NoRotation, line.outline, Pixels{1}, acmacs::surface::Dash::NoDash, line.fill);
legend_surface.text({text_x, y}, line.label, mLabelColor, mLabelSize, mLabelStyle);
y += height * mInterline;
}
}
} // map_elements::v1::LegendPointLabel::draw
// ----------------------------------------------------------------------
void map_elements::v1::LegendPointLabel::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
auto& legend = aDrawElements.legend();
legend.origin(mOrigin)
.background(mBackground)
.border_color(mBorderColor)
.border_width(mBorderWidth);
legend.interline(mInterline);
for (const auto& line : mLines) {
legend.add(line.label, mLabelColor, mLabelSize, mLabelStyle, mPointSize, line.outline, line.outline_width, line.fill, acmacs::PointShape::Circle);
}
} // map_elements::v1::LegendPointLabel::draw
// ----------------------------------------------------------------------
void map_elements::v1::Title::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw& chart_draw) const
{
using namespace std::string_view_literals;
if (mShow && (mLines.size() > 1 || (!mLines.empty() && !mLines.front().empty()))) {
// AD_DEBUG("env stress: {}", chart_draw.settings().getenv("stress"sv));
std::vector<std::string> lines(mLines.size());
std::transform(std::begin(mLines), std::end(mLines), std::begin(lines),
[&chart_draw](const auto& line) -> std::string { return chart_draw.settings_present() ? chart_draw.settings().substitute(line) : line; });
aDrawElements.title(lines)
.text_color(mTextColor)
.text_size(mTextSize)
.text_style(mTextStyle)
.interline(mInterline)
.padding(mPadding)
.origin(mOrigin)
.background(mBackground)
.border_color(mBorderColor)
.border_width(mBorderWidth);
}
} // map_elements::v1::Title::draw
// ----------------------------------------------------------------------
// !!! obsolete !!!
void map_elements::v1::Title::draw(acmacs::surface::Surface& aSurface) const
{
// obsolete
try {
if (mShow && (mLines.size() > 1 || (!mLines.empty() && !mLines.front().empty()))) {
double width = 0, height = 0;
for (const auto& line : mLines) {
const acmacs::Size line_size = aSurface.text_size(line, mTextSize, mTextStyle);
if (line_size.width > width)
width = line_size.width;
if (line_size.height > height)
height = line_size.height;
}
const double padding = aSurface.convert(mPadding).value();
if (std::isnan(padding))
throw std::runtime_error("padding is NaN");
const acmacs::Size legend_surface_size{width + padding * 2, height * static_cast<double>(mLines.size() - 1) * mInterline + height + padding * 2};
const acmacs::PointCoordinates legend_surface_origin = subsurface_origin(aSurface, mOrigin, legend_surface_size);
acmacs::surface::Surface& legend_surface = aSurface.subsurface(legend_surface_origin, Scaled{legend_surface_size.width}, legend_surface_size, false);
const auto& legend_v = legend_surface.viewport();
legend_surface.rectangle_filled(legend_v.origin, legend_v.size, mBackground, Pixels{0}, mBackground);
legend_surface.rectangle(legend_v.origin, legend_v.size, mBorderColor, mBorderWidth);
const double text_x = padding;
double y = padding + height;
for (const auto& line : mLines) {
legend_surface.text({text_x, y}, line, mTextColor, mTextSize, mTextStyle);
y += height * mInterline;
}
}
}
catch (std::exception& err) {
AD_ERROR("map_elements::Title::draw(Surface&): {} (ignored)", err);
}
} // map_elements::v1::Title::draw
// ----------------------------------------------------------------------
// !!! obsolete !!!
void map_elements::v1::SerumCircle::draw(acmacs::surface::Surface& aSurface, const ChartDraw& aChartDraw) const
{
if (mSerumNo != static_cast<size_t>(-1)) {
auto transformed_layout = aChartDraw.chart(0).modified_transformed_layout();
const auto& coord = transformed_layout->at(mSerumNo + aChartDraw.chart().number_of_antigens());
if (coord.exists()) {
if (mStart == mEnd) {
aSurface.circle_filled(coord, mRadius * 2.0, AspectNormal, NoRotation, mOutlineColor, mOutlineWidth, mOutlineDash, mFillColor);
}
else {
aSurface.sector_filled(coord, mRadius * 2.0, mStart, mEnd, mOutlineColor, mOutlineWidth, mRadiusColor, mRadiusWidth, mRadiusDash, mFillColor);
}
}
else
AD_WARNING("SerumCircle::draw(surface): cannot draw serum circle, center coordinates: {}", coord);
}
} // map_elements::v1::SerumCircle::draw
// ----------------------------------------------------------------------
void map_elements::v1::SerumCircle::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw& aChartDraw) const
{
if (const auto& coord = aChartDraw.chart(0).modified_layout()->at(mSerumNo + aChartDraw.chart().number_of_antigens()); coord.exists())
aDrawElements.serum_circle(coord, aChartDraw.chart(0).modified_transformation(), mRadius * 2.0, mFillColor, mOutlineColor, mOutlineWidth, mOutlineDash, mRadiusColor, mRadiusWidth, mRadiusDash, mStart, mEnd);
else
AD_WARNING("SerumCircle::draw(draw_elements): cannot draw serum circle, center coordinates: {}", coord);
} // map_elements::v1::SerumCircle::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::LineFromTo::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
aSurface.line(mBegin, mEnd, mLineColor, mLineWidth);
} // map_elements::v1::LineFromTo::draw
// ----------------------------------------------------------------------
void map_elements::v1::LineFromTo::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.line(mBegin, mEnd, mLineColor, mLineWidth);
} // map_elements::v1::LineFromTo::draw
// ----------------------------------------------------------------------
void map_elements::v1::LineSlope::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.line(line_, mLineColor, mLineWidth, apply_map_transformation_);
} // map_elements::v1::Line::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Rectangle::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
const std::vector<acmacs::PointCoordinates> path{mCorner1, {mCorner1.x(), mCorner2.y()}, mCorner2, {mCorner2.x(), mCorner1.y()}};
if (mFilled)
aSurface.path_fill(path.begin(), path.end(), mColor);
else
aSurface.path_outline(path.begin(), path.end(), mColor, mLineWidth, true);
} // map_elements::v1::Rectangle::draw
// ----------------------------------------------------------------------
void map_elements::v1::Rectangle::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.rectangle(mCorner1, mCorner2, mColor, mFilled, mLineWidth);
} // map_elements::v1::Rectangle::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Arrow::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
const bool x_eq = float_equal(mEnd.x(), mBegin.x());
const double sign2 = x_eq ? (mBegin.y() < mEnd.y() ? 1.0 : -1.0) : (mEnd.x() < mBegin.x() ? 1.0 : -1.0);
const double angle = x_eq ? -M_PI_2 : std::atan((mEnd.y() - mBegin.y()) / (mEnd.x() - mBegin.x()));
const auto end = aSurface.arrow_head(mEnd, angle, sign2, mArrowHeadColor, mArrowWidth, mArrowHeadFilled);
aSurface.line(mBegin, end, mLineColor, mLineWidth);
} // map_elements::v1::Arrow::draw
// ----------------------------------------------------------------------
void map_elements::v1::Arrow::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.arrow(mBegin, mEnd, mLineColor, mLineWidth, mArrowHeadColor, mArrowHeadFilled, mArrowWidth);
} // map_elements::v1::Arrow::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Circle::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
aSurface.circle_filled(mCenter, mSize, mAspect, mRotation, mOutlineColor, mOutlineWidth, acmacs::surface::Dash::NoDash, mFillColor);
} // map_elements::v1::Circle::draw
// ----------------------------------------------------------------------
void map_elements::v1::Circle::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.circle(mCenter, mSize, mFillColor, mOutlineColor, mOutlineWidth, mAspect, mRotation);
} // map_elements::v1::Circle::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Path::draw(acmacs::surface::Surface& /*aSurface*/, const ChartDraw& /*aChartDraw*/) const
{
AD_WARNING("map_elements::Path::draw(surface) obsolete and not implemented");
} // map_elements::v1::Path::draw
void map_elements::v1::Path::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw& /*aChartDraw*/) const
{
aDrawElements.path(mPath, mLineColor, mLineWidth, close_and_fill_);
} // map_elements::v1::Path::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Point::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
aSurface.circle_filled(mCenter, mSize, mAspect, mRotation, mOutlineColor, mOutlineWidth, acmacs::surface::Dash::NoDash, mFillColor);
} // map_elements::v1::Point::draw
// ----------------------------------------------------------------------
void map_elements::v1::Point::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.point(mCenter, mSize, mFillColor, mOutlineColor, mOutlineWidth, mAspect, mRotation, mLabel);
} // map_elements::v1::Point::draw
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>point shape in legend<commit_after>#include "acmacs-base/rjson-v3.hh"
#include "acmacs-draw/continent-map.hh"
#include "acmacs-draw/draw-legend.hh"
#include "acmacs-draw/draw-elements.hh"
#include "acmacs-map-draw/map-elements-v1.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/mapi-settings.hh"
// ----------------------------------------------------------------------
void map_elements::Elements::add_basic_elements_v1()
{
add<map_elements::v1::BackgroundBorderGrid>();
} // map_elements::Elements::add_basic_elements_v1
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::BackgroundBorderGrid::draw(acmacs::surface::Surface& aSurface, const ChartDraw&) const
{
const auto& v = aSurface.viewport();
aSurface.rectangle_filled(v.origin, v.size, mBackground, Pixels{0}, mBackground);
aSurface.grid(Scaled{1}, mGridColor, mGridLineWidth);
aSurface.rectangle(v.origin, v.size, mBorderColor, mBorderWidth);
} // map_elements::v1::BackgroundBorderGrid::draw
// ----------------------------------------------------------------------
void map_elements::v1::BackgroundBorderGrid::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.border(mBorderColor, mBorderWidth);
aDrawElements.background(mBackground);
aDrawElements.grid(Scaled{1}, mGridColor, mGridLineWidth);
} // map_elements::v1::BackgroundBorderGrid::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::ContinentMap::draw(acmacs::surface::Surface& aSurface, const ChartDraw&) const
{
acmacs::PointCoordinates origin = mOrigin;
if (origin.x() < 0)
origin.x(origin.x() + aSurface.width_in_pixels() - mWidthInParent.value());
if (origin.y() < 0)
origin.y(origin.y() + aSurface.height_in_pixels() - mWidthInParent.value() / continent_map_aspect());
acmacs::surface::Surface& continent_surface = aSurface.subsurface(origin, mWidthInParent, continent_map_size(), true);
continent_map_draw(continent_surface);
} // map_elements::ContinentMap::draw
// ----------------------------------------------------------------------
void map_elements::v1::ContinentMap::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.continent_map(mOrigin, mWidthInParent);
} // map_elements::v1::ContinentMap::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::LegendPointLabel::draw(acmacs::surface::Surface& aSurface, const ChartDraw&) const
{
if (!mLines.empty()) {
double width = 0, height = 0;
for (const auto& line: mLines) {
const acmacs::Size line_size = aSurface.text_size(line.label, mLabelSize, mLabelStyle);
if (line_size.width > width)
width = line_size.width;
if (line_size.height > height)
height = line_size.height;
}
const acmacs::Size padding = aSurface.text_size("O", mLabelSize, mLabelStyle);
const double scaled_point_size = aSurface.convert(mPointSize).value();
const acmacs::Size legend_surface_size{width + padding.width * 3 + scaled_point_size,
height * static_cast<double>(mLines.size() - 1) * mInterline + height + padding.height * 2};
const acmacs::PointCoordinates legend_surface_origin = subsurface_origin(aSurface, mOrigin, legend_surface_size);
acmacs::surface::Surface& legend_surface = aSurface.subsurface(legend_surface_origin, Scaled{legend_surface_size.width}, legend_surface_size, false);
const auto& legend_v = legend_surface.viewport();
legend_surface.rectangle_filled(legend_v.origin, legend_v.size, mBackground, Pixels{0}, mBackground);
legend_surface.rectangle(legend_v.origin, legend_v.size, mBorderColor, mBorderWidth);
const double point_x = padding.width + scaled_point_size / 2;
const double text_x = padding.width * 2 + scaled_point_size;
double y = padding.height + height;
for (const auto& line: mLines) {
legend_surface.circle_filled({point_x, y - height / 2}, mPointSize, AspectNormal, NoRotation, line.outline, Pixels{1}, acmacs::surface::Dash::NoDash, line.fill);
legend_surface.text({text_x, y}, line.label, mLabelColor, mLabelSize, mLabelStyle);
y += height * mInterline;
}
}
} // map_elements::v1::LegendPointLabel::draw
// ----------------------------------------------------------------------
void map_elements::v1::LegendPointLabel::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
auto& legend = aDrawElements.legend();
legend.origin(mOrigin)
.background(mBackground)
.border_color(mBorderColor)
.border_width(mBorderWidth);
legend.interline(mInterline);
for (const auto& line : mLines)
legend.add(line.label, mLabelColor, mLabelSize, mLabelStyle, mPointSize, line.outline, line.outline_width, line.fill, line.shape_);
} // map_elements::v1::LegendPointLabel::draw
// ----------------------------------------------------------------------
void map_elements::v1::Title::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw& chart_draw) const
{
using namespace std::string_view_literals;
if (mShow && (mLines.size() > 1 || (!mLines.empty() && !mLines.front().empty()))) {
// AD_DEBUG("env stress: {}", chart_draw.settings().getenv("stress"sv));
std::vector<std::string> lines(mLines.size());
std::transform(std::begin(mLines), std::end(mLines), std::begin(lines),
[&chart_draw](const auto& line) -> std::string { return chart_draw.settings_present() ? chart_draw.settings().substitute(line) : line; });
aDrawElements.title(lines)
.text_color(mTextColor)
.text_size(mTextSize)
.text_style(mTextStyle)
.interline(mInterline)
.padding(mPadding)
.origin(mOrigin)
.background(mBackground)
.border_color(mBorderColor)
.border_width(mBorderWidth);
}
} // map_elements::v1::Title::draw
// ----------------------------------------------------------------------
// !!! obsolete !!!
void map_elements::v1::Title::draw(acmacs::surface::Surface& aSurface) const
{
// obsolete
try {
if (mShow && (mLines.size() > 1 || (!mLines.empty() && !mLines.front().empty()))) {
double width = 0, height = 0;
for (const auto& line : mLines) {
const acmacs::Size line_size = aSurface.text_size(line, mTextSize, mTextStyle);
if (line_size.width > width)
width = line_size.width;
if (line_size.height > height)
height = line_size.height;
}
const double padding = aSurface.convert(mPadding).value();
if (std::isnan(padding))
throw std::runtime_error("padding is NaN");
const acmacs::Size legend_surface_size{width + padding * 2, height * static_cast<double>(mLines.size() - 1) * mInterline + height + padding * 2};
const acmacs::PointCoordinates legend_surface_origin = subsurface_origin(aSurface, mOrigin, legend_surface_size);
acmacs::surface::Surface& legend_surface = aSurface.subsurface(legend_surface_origin, Scaled{legend_surface_size.width}, legend_surface_size, false);
const auto& legend_v = legend_surface.viewport();
legend_surface.rectangle_filled(legend_v.origin, legend_v.size, mBackground, Pixels{0}, mBackground);
legend_surface.rectangle(legend_v.origin, legend_v.size, mBorderColor, mBorderWidth);
const double text_x = padding;
double y = padding + height;
for (const auto& line : mLines) {
legend_surface.text({text_x, y}, line, mTextColor, mTextSize, mTextStyle);
y += height * mInterline;
}
}
}
catch (std::exception& err) {
AD_ERROR("map_elements::Title::draw(Surface&): {} (ignored)", err);
}
} // map_elements::v1::Title::draw
// ----------------------------------------------------------------------
// !!! obsolete !!!
void map_elements::v1::SerumCircle::draw(acmacs::surface::Surface& aSurface, const ChartDraw& aChartDraw) const
{
if (mSerumNo != static_cast<size_t>(-1)) {
auto transformed_layout = aChartDraw.chart(0).modified_transformed_layout();
const auto& coord = transformed_layout->at(mSerumNo + aChartDraw.chart().number_of_antigens());
if (coord.exists()) {
if (mStart == mEnd) {
aSurface.circle_filled(coord, mRadius * 2.0, AspectNormal, NoRotation, mOutlineColor, mOutlineWidth, mOutlineDash, mFillColor);
}
else {
aSurface.sector_filled(coord, mRadius * 2.0, mStart, mEnd, mOutlineColor, mOutlineWidth, mRadiusColor, mRadiusWidth, mRadiusDash, mFillColor);
}
}
else
AD_WARNING("SerumCircle::draw(surface): cannot draw serum circle, center coordinates: {}", coord);
}
} // map_elements::v1::SerumCircle::draw
// ----------------------------------------------------------------------
void map_elements::v1::SerumCircle::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw& aChartDraw) const
{
if (const auto& coord = aChartDraw.chart(0).modified_layout()->at(mSerumNo + aChartDraw.chart().number_of_antigens()); coord.exists())
aDrawElements.serum_circle(coord, aChartDraw.chart(0).modified_transformation(), mRadius * 2.0, mFillColor, mOutlineColor, mOutlineWidth, mOutlineDash, mRadiusColor, mRadiusWidth, mRadiusDash, mStart, mEnd);
else
AD_WARNING("SerumCircle::draw(draw_elements): cannot draw serum circle, center coordinates: {}", coord);
} // map_elements::v1::SerumCircle::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::LineFromTo::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
aSurface.line(mBegin, mEnd, mLineColor, mLineWidth);
} // map_elements::v1::LineFromTo::draw
// ----------------------------------------------------------------------
void map_elements::v1::LineFromTo::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.line(mBegin, mEnd, mLineColor, mLineWidth);
} // map_elements::v1::LineFromTo::draw
// ----------------------------------------------------------------------
void map_elements::v1::LineSlope::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.line(line_, mLineColor, mLineWidth, apply_map_transformation_);
} // map_elements::v1::Line::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Rectangle::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
const std::vector<acmacs::PointCoordinates> path{mCorner1, {mCorner1.x(), mCorner2.y()}, mCorner2, {mCorner2.x(), mCorner1.y()}};
if (mFilled)
aSurface.path_fill(path.begin(), path.end(), mColor);
else
aSurface.path_outline(path.begin(), path.end(), mColor, mLineWidth, true);
} // map_elements::v1::Rectangle::draw
// ----------------------------------------------------------------------
void map_elements::v1::Rectangle::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.rectangle(mCorner1, mCorner2, mColor, mFilled, mLineWidth);
} // map_elements::v1::Rectangle::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Arrow::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
const bool x_eq = float_equal(mEnd.x(), mBegin.x());
const double sign2 = x_eq ? (mBegin.y() < mEnd.y() ? 1.0 : -1.0) : (mEnd.x() < mBegin.x() ? 1.0 : -1.0);
const double angle = x_eq ? -M_PI_2 : std::atan((mEnd.y() - mBegin.y()) / (mEnd.x() - mBegin.x()));
const auto end = aSurface.arrow_head(mEnd, angle, sign2, mArrowHeadColor, mArrowWidth, mArrowHeadFilled);
aSurface.line(mBegin, end, mLineColor, mLineWidth);
} // map_elements::v1::Arrow::draw
// ----------------------------------------------------------------------
void map_elements::v1::Arrow::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.arrow(mBegin, mEnd, mLineColor, mLineWidth, mArrowHeadColor, mArrowHeadFilled, mArrowWidth);
} // map_elements::v1::Arrow::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Circle::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
aSurface.circle_filled(mCenter, mSize, mAspect, mRotation, mOutlineColor, mOutlineWidth, acmacs::surface::Dash::NoDash, mFillColor);
} // map_elements::v1::Circle::draw
// ----------------------------------------------------------------------
void map_elements::v1::Circle::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.circle(mCenter, mSize, mFillColor, mOutlineColor, mOutlineWidth, mAspect, mRotation);
} // map_elements::v1::Circle::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Path::draw(acmacs::surface::Surface& /*aSurface*/, const ChartDraw& /*aChartDraw*/) const
{
AD_WARNING("map_elements::Path::draw(surface) obsolete and not implemented");
} // map_elements::v1::Path::draw
void map_elements::v1::Path::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw& /*aChartDraw*/) const
{
aDrawElements.path(mPath, mLineColor, mLineWidth, close_and_fill_);
} // map_elements::v1::Path::draw
// ----------------------------------------------------------------------
// obsolete
void map_elements::v1::Point::draw(acmacs::surface::Surface& aSurface, const ChartDraw& /*aChartDraw*/) const
{
aSurface.circle_filled(mCenter, mSize, mAspect, mRotation, mOutlineColor, mOutlineWidth, acmacs::surface::Dash::NoDash, mFillColor);
} // map_elements::v1::Point::draw
// ----------------------------------------------------------------------
void map_elements::v1::Point::draw(acmacs::draw::DrawElements& aDrawElements, const ChartDraw&) const
{
aDrawElements.point(mCenter, mSize, mFillColor, mOutlineColor, mOutlineWidth, mAspect, mRotation, mLabel);
} // map_elements::v1::Point::draw
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before><commit_msg>Create Range Sum Query - Mutable.cpp<commit_after><|endoftext|> |
<commit_before>// this file defines the SegmentationExamples for the test driver
// and all it expects is that you have a function called RegisterTests
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(CannySegmentationLevelSetImageFilterTest);
REGISTER_TEST(ConfidenceConnectedTest);
REGISTER_TEST(ConnectedThresholdImageFilterTest);
REGISTER_TEST(FastMarchingImageFilterTest);
REGISTER_TEST(GeodesicActiveContourImageFilterTest);
REGISTER_TEST(GibbsPriorImageFilter1Test);
REGISTER_TEST(HoughTransform2DLinesImageFilter);
REGISTER_TEST(IsolatedConnectedImageFilterTest);
REGISTER_TEST(NeighborhoodConnectedImageFilterTest);
REGISTER_TEST(ShapeDetectionLevelSetFilterTest);
REGISTER_TEST(ThresholdSegmentationLevelSetImageFilterTest);
REGISTER_TEST(WatershedSegmentation1Test);
}
#undef main
#define main CannySegmentationLevelSetImageFilterTest
#include "CannySegmentationLevelSetImageFilter.cxx"
#undef main
#define main ConfidenceConnectedTest
#include "ConfidenceConnected.cxx"
#undef main
#define main ConnectedThresholdImageFilterTest
#include "ConnectedThresholdImageFilter.cxx"
#undef main
#define main FastMarchingImageFilterTest
#include "FastMarchingImageFilter.cxx"
#undef main
#define main GeodesicActiveContourImageFilterTest
#include "GeodesicActiveContourImageFilter.cxx"
#undef main
#define main GibbsPriorImageFilter1Test
#include "GibbsPriorImageFilter1.cxx"
#undef main
#define main HoughTransform2DLinesImageFilter
#include "HoughTransform2DLinesImageFilter.cxx"
#undef main
#define main IsolatedConnectedImageFilterTest
#include "IsolatedConnectedImageFilter.cxx"
#undef main
#define main NeighborhoodConnectedImageFilterTest
#include "NeighborhoodConnectedImageFilter.cxx"
#undef main
#define main ShapeDetectionLevelSetFilterTest
#include "ShapeDetectionLevelSetFilter.cxx"
#undef main
#define main ThresholdSegmentationLevelSetImageFilterTest
#include "ThresholdSegmentationLevelSetImageFilter.cxx"
#undef main
#define main WatershedSegmentation1Test
#include "WatershedSegmentation1.cxx"
<commit_msg>FIX: test name<commit_after>// this file defines the SegmentationExamples for the test driver
// and all it expects is that you have a function called RegisterTests
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(CannySegmentationLevelSetImageFilterTest);
REGISTER_TEST(ConfidenceConnectedTest);
REGISTER_TEST(ConnectedThresholdImageFilterTest);
REGISTER_TEST(FastMarchingImageFilterTest);
REGISTER_TEST(GeodesicActiveContourImageFilterTest);
REGISTER_TEST(GibbsPriorImageFilter1Test);
REGISTER_TEST(HoughTransform2DLinesImageFilterTest);
REGISTER_TEST(IsolatedConnectedImageFilterTest);
REGISTER_TEST(NeighborhoodConnectedImageFilterTest);
REGISTER_TEST(ShapeDetectionLevelSetFilterTest);
REGISTER_TEST(ThresholdSegmentationLevelSetImageFilterTest);
REGISTER_TEST(WatershedSegmentation1Test);
}
#undef main
#define main CannySegmentationLevelSetImageFilterTest
#include "CannySegmentationLevelSetImageFilter.cxx"
#undef main
#define main ConfidenceConnectedTest
#include "ConfidenceConnected.cxx"
#undef main
#define main ConnectedThresholdImageFilterTest
#include "ConnectedThresholdImageFilter.cxx"
#undef main
#define main FastMarchingImageFilterTest
#include "FastMarchingImageFilter.cxx"
#undef main
#define main GeodesicActiveContourImageFilterTest
#include "GeodesicActiveContourImageFilter.cxx"
#undef main
#define main GibbsPriorImageFilter1Test
#include "GibbsPriorImageFilter1.cxx"
#undef main
#define main HoughTransform2DLinesImageFilterTest
#include "HoughTransform2DLinesImageFilter.cxx"
#undef main
#define main IsolatedConnectedImageFilterTest
#include "IsolatedConnectedImageFilter.cxx"
#undef main
#define main NeighborhoodConnectedImageFilterTest
#include "NeighborhoodConnectedImageFilter.cxx"
#undef main
#define main ShapeDetectionLevelSetFilterTest
#include "ShapeDetectionLevelSetFilter.cxx"
#undef main
#define main ThresholdSegmentationLevelSetImageFilterTest
#include "ThresholdSegmentationLevelSetImageFilter.cxx"
#undef main
#define main WatershedSegmentation1Test
#include "WatershedSegmentation1.cxx"
<|endoftext|> |
<commit_before>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <sstream>
#include "common/logging.h"
#include <boost/algorithm/string/join.hpp>
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
#include "common/status.h"
#include "exprs/expr.h"
#include "runtime/descriptors.h"
#include "runtime/runtime-state.h"
#include "runtime/timestamp-value.h"
#include "runtime/data-stream-recvr.h"
#include "util/cpu-info.h"
#include "util/debug-util.h"
#include "util/disk-info.h"
#include "util/error-util.h"
#include "util/jni-util.h"
#include "util/mem-info.h"
#include <jni.h>
#include <iostream>
DECLARE_int32(max_errors);
using namespace boost;
using namespace llvm;
using namespace std;
using namespace boost::algorithm;
namespace impala {
RuntimeState::RuntimeState(const TUniqueId& query_id,
const TUniqueId& fragment_instance_id, const TQueryContext& query_ctxt,
const string& cgroup, ExecEnv* exec_env)
: obj_pool_(new ObjectPool()),
data_stream_recvrs_pool_(new ObjectPool()),
unreported_error_idx_(0),
query_ctxt_(query_ctxt),
now_(new TimestampValue(query_ctxt.now_string.c_str(),
query_ctxt.now_string.size())),
query_id_(query_id),
cgroup_(cgroup),
profile_(obj_pool_.get(), "Fragment " + PrintId(fragment_instance_id)),
is_cancelled_(false) {
Status status = Init(fragment_instance_id, exec_env);
DCHECK(status.ok()) << status.GetErrorMsg();
}
RuntimeState::RuntimeState(const TQueryContext& query_ctxt)
: obj_pool_(new ObjectPool()),
data_stream_recvrs_pool_(new ObjectPool()),
unreported_error_idx_(0),
query_ctxt_(query_ctxt),
now_(new TimestampValue(query_ctxt.now_string.c_str(),
query_ctxt.now_string.size())),
exec_env_(ExecEnv::GetInstance()),
profile_(obj_pool_.get(), "<unnamed>"),
is_cancelled_(false) {
query_ctxt_.request.query_options.__set_batch_size(DEFAULT_BATCH_SIZE);
}
RuntimeState::~RuntimeState() {
if (udf_pool_.get() != NULL) udf_pool_->FreeAll();
// query_mem_tracker_ must be valid as long as instance_mem_tracker_ is so
// delete instance_mem_tracker_ first.
instance_mem_tracker_.reset();
query_mem_tracker_.reset();
}
Status RuntimeState::Init(const TUniqueId& fragment_instance_id, ExecEnv* exec_env) {
fragment_instance_id_ = fragment_instance_id;
exec_env_ = exec_env;
TQueryOptions& query_options = query_ctxt_.request.query_options;
if (!query_options.disable_codegen) {
RETURN_IF_ERROR(CreateCodegen());
} else {
codegen_.reset(NULL);
}
if (query_options.max_errors <= 0) {
// TODO: fix linker error and uncomment this
//query_options_.max_errors = FLAGS_max_errors;
query_options.max_errors = 100;
}
if (query_options.batch_size <= 0) {
query_options.__set_batch_size(DEFAULT_BATCH_SIZE);
}
// Register with the thread mgr
if (exec_env != NULL) {
resource_pool_ = exec_env->thread_mgr()->RegisterPool();
DCHECK(resource_pool_ != NULL);
}
total_cpu_timer_ = ADD_TIMER(runtime_profile(), "TotalCpuTime");
total_storage_wait_timer_ = ADD_TIMER(runtime_profile(), "TotalStorageWaitTime");
total_network_send_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkSendTime");
total_network_receive_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkReceiveTime");
return Status::OK;
}
Status RuntimeState::InitMemTrackers(const TUniqueId& query_id,
const string* pool_name, int64_t query_bytes_limit) {
MemTracker* query_parent_tracker = exec_env_->process_mem_tracker();
if (pool_name != NULL) {
query_parent_tracker = MemTracker::GetRequestPoolMemTracker(*pool_name,
query_parent_tracker);
}
query_mem_tracker_ =
MemTracker::GetQueryMemTracker(query_id, query_bytes_limit, query_parent_tracker,
query_resource_mgr());
instance_mem_tracker_.reset(new MemTracker(runtime_profile(), -1,
runtime_profile()->name(), query_mem_tracker_.get()));
if (query_bytes_limit != -1) {
if (query_bytes_limit > MemInfo::physical_mem()) {
LOG(WARNING) << "Memory limit "
<< PrettyPrinter::Print(query_bytes_limit, TCounterType::BYTES)
<< " exceeds physical memory of "
<< PrettyPrinter::Print(MemInfo::physical_mem(), TCounterType::BYTES);
}
VLOG_QUERY << "Using query memory limit: "
<< PrettyPrinter::Print(query_bytes_limit, TCounterType::BYTES);
}
// TODO: this is a stopgap until we implement ExprContext
udf_mem_tracker_.reset(
new MemTracker(-1, "UDFs", instance_mem_tracker_.get()));
udf_pool_.reset(new MemPool(udf_mem_tracker_.get()));
return Status::OK;
}
DataStreamRecvr* RuntimeState::CreateRecvr(
const RowDescriptor& row_desc, PlanNodeId dest_node_id, int num_senders,
int buffer_size, RuntimeProfile* profile) {
DataStreamRecvr* recvr = exec_env_->stream_mgr()->CreateRecvr(this, row_desc,
fragment_instance_id_, dest_node_id, num_senders, buffer_size, profile);
data_stream_recvrs_pool_->Add(recvr);
return recvr;
}
void RuntimeState::set_now(const TimestampValue* now) {
now_.reset(new TimestampValue(*now));
}
Status RuntimeState::CreateCodegen() {
if (codegen_.get() != NULL) return Status::OK;
RETURN_IF_ERROR(LlvmCodeGen::LoadImpalaIR(obj_pool_.get(), &codegen_));
codegen_->EnableOptimizations(true);
profile_.AddChild(codegen_->runtime_profile());
return Status::OK;
}
bool RuntimeState::ErrorLogIsEmpty() {
lock_guard<mutex> l(error_log_lock_);
return (error_log_.size() > 0);
}
string RuntimeState::ErrorLog() {
lock_guard<mutex> l(error_log_lock_);
return join(error_log_, "\n");
}
string RuntimeState::FileErrors() const {
lock_guard<mutex> l(file_errors_lock_);
stringstream out;
for (int i = 0; i < file_errors_.size(); ++i) {
out << file_errors_[i].second << " errors in " << file_errors_[i].first << endl;
}
return out.str();
}
void RuntimeState::ReportFileErrors(const std::string& file_name, int num_errors) {
lock_guard<mutex> l(file_errors_lock_);
file_errors_.push_back(make_pair(file_name, num_errors));
}
bool RuntimeState::LogError(const string& error) {
lock_guard<mutex> l(error_log_lock_);
if (error_log_.size() < query_ctxt_.request.query_options.max_errors) {
error_log_.push_back(error);
return true;
}
return false;
}
void RuntimeState::LogError(const Status& status) {
if (status.ok()) return;
LogError(status.GetErrorMsg());
}
void RuntimeState::GetUnreportedErrors(vector<string>* new_errors) {
lock_guard<mutex> l(error_log_lock_);
if (unreported_error_idx_ < error_log_.size()) {
new_errors->assign(error_log_.begin() + unreported_error_idx_, error_log_.end());
unreported_error_idx_ = error_log_.size();
}
}
Status RuntimeState::SetMemLimitExceeded(MemTracker* tracker,
int64_t failed_allocation_size) {
DCHECK_GE(failed_allocation_size, 0);
{
boost::lock_guard<boost::mutex> l(query_status_lock_);
if (query_status_.ok()) {
query_status_ = Status::MEM_LIMIT_EXCEEDED;
} else {
return query_status_;
}
}
DCHECK(query_mem_tracker_.get() != NULL);
stringstream ss;
ss << "Memory Limit Exceeded\n";
if (failed_allocation_size != 0) {
DCHECK(tracker != NULL);
ss << " " << tracker->label() << " could not allocate "
<< PrettyPrinter::Print(failed_allocation_size, TCounterType::BYTES)
<< " without exceeding limit."
<< endl;
}
if (exec_env_->process_mem_tracker()->LimitExceeded()) {
ss << exec_env_->process_mem_tracker()->LogUsage();
} else {
ss << query_mem_tracker_->LogUsage();
}
LogError(ss.str());
// Add warning about missing stats.
if (query_ctxt_.__isset.tables_missing_stats
&& !query_ctxt_.tables_missing_stats.empty()) {
LogError(GetTablesMissingStatsWarning(query_ctxt_.tables_missing_stats));
}
DCHECK(query_status_.IsMemLimitExceeded());
return query_status_;
}
Status RuntimeState::CheckQueryState() {
// TODO: it would be nice if this also checked for cancellation, but doing so breaks
// cases where we use Status::CANCELLED to indicate that the limit was reached.
if (instance_mem_tracker_->AnyLimitExceeded()) return SetMemLimitExceeded();
boost::lock_guard<boost::mutex> l(query_status_lock_);
return query_status_;
}
}
<commit_msg>Properly initialise query_resource_mgr_ in RuntimeState<commit_after>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <sstream>
#include "common/logging.h"
#include <boost/algorithm/string/join.hpp>
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
#include "common/status.h"
#include "exprs/expr.h"
#include "runtime/descriptors.h"
#include "runtime/runtime-state.h"
#include "runtime/timestamp-value.h"
#include "runtime/data-stream-recvr.h"
#include "util/cpu-info.h"
#include "util/debug-util.h"
#include "util/disk-info.h"
#include "util/error-util.h"
#include "util/jni-util.h"
#include "util/mem-info.h"
#include <jni.h>
#include <iostream>
DECLARE_int32(max_errors);
using namespace boost;
using namespace llvm;
using namespace std;
using namespace boost::algorithm;
namespace impala {
RuntimeState::RuntimeState(const TUniqueId& query_id,
const TUniqueId& fragment_instance_id, const TQueryContext& query_ctxt,
const string& cgroup, ExecEnv* exec_env)
: obj_pool_(new ObjectPool()),
data_stream_recvrs_pool_(new ObjectPool()),
unreported_error_idx_(0),
query_ctxt_(query_ctxt),
now_(new TimestampValue(query_ctxt.now_string.c_str(),
query_ctxt.now_string.size())),
query_id_(query_id),
cgroup_(cgroup),
profile_(obj_pool_.get(), "Fragment " + PrintId(fragment_instance_id)),
is_cancelled_(false),
query_resource_mgr_(NULL) {
Status status = Init(fragment_instance_id, exec_env);
DCHECK(status.ok()) << status.GetErrorMsg();
}
RuntimeState::RuntimeState(const TQueryContext& query_ctxt)
: obj_pool_(new ObjectPool()),
data_stream_recvrs_pool_(new ObjectPool()),
unreported_error_idx_(0),
query_ctxt_(query_ctxt),
now_(new TimestampValue(query_ctxt.now_string.c_str(),
query_ctxt.now_string.size())),
exec_env_(ExecEnv::GetInstance()),
profile_(obj_pool_.get(), "<unnamed>"),
is_cancelled_(false),
query_resource_mgr_(NULL) {
query_ctxt_.request.query_options.__set_batch_size(DEFAULT_BATCH_SIZE);
}
RuntimeState::~RuntimeState() {
if (udf_pool_.get() != NULL) udf_pool_->FreeAll();
// query_mem_tracker_ must be valid as long as instance_mem_tracker_ is so
// delete instance_mem_tracker_ first.
instance_mem_tracker_.reset();
query_mem_tracker_.reset();
}
Status RuntimeState::Init(const TUniqueId& fragment_instance_id, ExecEnv* exec_env) {
fragment_instance_id_ = fragment_instance_id;
exec_env_ = exec_env;
TQueryOptions& query_options = query_ctxt_.request.query_options;
if (!query_options.disable_codegen) {
RETURN_IF_ERROR(CreateCodegen());
} else {
codegen_.reset(NULL);
}
if (query_options.max_errors <= 0) {
// TODO: fix linker error and uncomment this
//query_options_.max_errors = FLAGS_max_errors;
query_options.max_errors = 100;
}
if (query_options.batch_size <= 0) {
query_options.__set_batch_size(DEFAULT_BATCH_SIZE);
}
// Register with the thread mgr
if (exec_env != NULL) {
resource_pool_ = exec_env->thread_mgr()->RegisterPool();
DCHECK(resource_pool_ != NULL);
}
total_cpu_timer_ = ADD_TIMER(runtime_profile(), "TotalCpuTime");
total_storage_wait_timer_ = ADD_TIMER(runtime_profile(), "TotalStorageWaitTime");
total_network_send_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkSendTime");
total_network_receive_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkReceiveTime");
return Status::OK;
}
Status RuntimeState::InitMemTrackers(const TUniqueId& query_id,
const string* pool_name, int64_t query_bytes_limit) {
MemTracker* query_parent_tracker = exec_env_->process_mem_tracker();
if (pool_name != NULL) {
query_parent_tracker = MemTracker::GetRequestPoolMemTracker(*pool_name,
query_parent_tracker);
}
query_mem_tracker_ =
MemTracker::GetQueryMemTracker(query_id, query_bytes_limit, query_parent_tracker,
query_resource_mgr());
instance_mem_tracker_.reset(new MemTracker(runtime_profile(), -1,
runtime_profile()->name(), query_mem_tracker_.get()));
if (query_bytes_limit != -1) {
if (query_bytes_limit > MemInfo::physical_mem()) {
LOG(WARNING) << "Memory limit "
<< PrettyPrinter::Print(query_bytes_limit, TCounterType::BYTES)
<< " exceeds physical memory of "
<< PrettyPrinter::Print(MemInfo::physical_mem(), TCounterType::BYTES);
}
VLOG_QUERY << "Using query memory limit: "
<< PrettyPrinter::Print(query_bytes_limit, TCounterType::BYTES);
}
// TODO: this is a stopgap until we implement ExprContext
udf_mem_tracker_.reset(
new MemTracker(-1, "UDFs", instance_mem_tracker_.get()));
udf_pool_.reset(new MemPool(udf_mem_tracker_.get()));
return Status::OK;
}
DataStreamRecvr* RuntimeState::CreateRecvr(
const RowDescriptor& row_desc, PlanNodeId dest_node_id, int num_senders,
int buffer_size, RuntimeProfile* profile) {
DataStreamRecvr* recvr = exec_env_->stream_mgr()->CreateRecvr(this, row_desc,
fragment_instance_id_, dest_node_id, num_senders, buffer_size, profile);
data_stream_recvrs_pool_->Add(recvr);
return recvr;
}
void RuntimeState::set_now(const TimestampValue* now) {
now_.reset(new TimestampValue(*now));
}
Status RuntimeState::CreateCodegen() {
if (codegen_.get() != NULL) return Status::OK;
RETURN_IF_ERROR(LlvmCodeGen::LoadImpalaIR(obj_pool_.get(), &codegen_));
codegen_->EnableOptimizations(true);
profile_.AddChild(codegen_->runtime_profile());
return Status::OK;
}
bool RuntimeState::ErrorLogIsEmpty() {
lock_guard<mutex> l(error_log_lock_);
return (error_log_.size() > 0);
}
string RuntimeState::ErrorLog() {
lock_guard<mutex> l(error_log_lock_);
return join(error_log_, "\n");
}
string RuntimeState::FileErrors() const {
lock_guard<mutex> l(file_errors_lock_);
stringstream out;
for (int i = 0; i < file_errors_.size(); ++i) {
out << file_errors_[i].second << " errors in " << file_errors_[i].first << endl;
}
return out.str();
}
void RuntimeState::ReportFileErrors(const std::string& file_name, int num_errors) {
lock_guard<mutex> l(file_errors_lock_);
file_errors_.push_back(make_pair(file_name, num_errors));
}
bool RuntimeState::LogError(const string& error) {
lock_guard<mutex> l(error_log_lock_);
if (error_log_.size() < query_ctxt_.request.query_options.max_errors) {
error_log_.push_back(error);
return true;
}
return false;
}
void RuntimeState::LogError(const Status& status) {
if (status.ok()) return;
LogError(status.GetErrorMsg());
}
void RuntimeState::GetUnreportedErrors(vector<string>* new_errors) {
lock_guard<mutex> l(error_log_lock_);
if (unreported_error_idx_ < error_log_.size()) {
new_errors->assign(error_log_.begin() + unreported_error_idx_, error_log_.end());
unreported_error_idx_ = error_log_.size();
}
}
Status RuntimeState::SetMemLimitExceeded(MemTracker* tracker,
int64_t failed_allocation_size) {
DCHECK_GE(failed_allocation_size, 0);
{
boost::lock_guard<boost::mutex> l(query_status_lock_);
if (query_status_.ok()) {
query_status_ = Status::MEM_LIMIT_EXCEEDED;
} else {
return query_status_;
}
}
DCHECK(query_mem_tracker_.get() != NULL);
stringstream ss;
ss << "Memory Limit Exceeded\n";
if (failed_allocation_size != 0) {
DCHECK(tracker != NULL);
ss << " " << tracker->label() << " could not allocate "
<< PrettyPrinter::Print(failed_allocation_size, TCounterType::BYTES)
<< " without exceeding limit."
<< endl;
}
if (exec_env_->process_mem_tracker()->LimitExceeded()) {
ss << exec_env_->process_mem_tracker()->LogUsage();
} else {
ss << query_mem_tracker_->LogUsage();
}
LogError(ss.str());
// Add warning about missing stats.
if (query_ctxt_.__isset.tables_missing_stats
&& !query_ctxt_.tables_missing_stats.empty()) {
LogError(GetTablesMissingStatsWarning(query_ctxt_.tables_missing_stats));
}
DCHECK(query_status_.IsMemLimitExceeded());
return query_status_;
}
Status RuntimeState::CheckQueryState() {
// TODO: it would be nice if this also checked for cancellation, but doing so breaks
// cases where we use Status::CANCELLED to indicate that the limit was reached.
if (instance_mem_tracker_->AnyLimitExceeded()) return SetMemLimitExceeded();
boost::lock_guard<boost::mutex> l(query_status_lock_);
return query_status_;
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include "DataStruct.h"
ClassImp(Event)
ClassImp(Dimuon)
ClassImp(Spill)
ClassImp(Track)
#define SPILLID_MIN_57 303215
#define SPILLID_MAX_57 370100
#define SPILLID_MIN_59 370110
#define SPILLID_MAX_59 388580
#define SPILLID_MIN_61 388611
#define SPILLID_MAX_61 391100
#define SPILLID_MIN_62 394308
#define SPILLID_MAX_62 482573
#define SPILLID_MIN_67 484946
#define SPILLID_MAX_67 676224
#define SPILLID_MIN_70 676498
#define SPILLID_MAX_70 696455
Event::Event() : runID(-1), spillID(-1), eventID(-1), status(-1), MATRIX1(-1), weight(0.)
{
for(int i = 0; i < 33; ++i) intensity[i] = 0.;
}
bool Event::goodEvent()
{
return MATRIX1 > 0;
}
float Event::weightedIntensity()
{
double weight[] = {0.000814246430361413, 0.0028662467149288, 0.00597015326639906, 0.0121262946061061,
0.0300863195179747, 0.0777262437180552, 0.159446650644417, 0.259932709364831,
0.36718876894966, 0.488159093692654, 0.678969311099113, 0.847788074599439, 0.956475273764143,
1.,
0.989173954042814, 0.897678016090413, 0.767828869998712, 0.647167321489559, 0.533894756174369,
0.448848741080746, 0.356435437171761, 0.263693103645649, 0.177964720504253,
0.108504562083177, 0.0540099990325891, 0.019218568399343, 0.00308302089003216};
double sum = 0.;
for(int i = -13; i <= 13; ++i)
{
sum += (weight[i+13]*intensity[i+16]);
}
return sum/13.;
}
bool Dimuon::goodDimuon()
{
if(fabs(dx) > 2. || fabs(dy) > 2.) return false;
if(dz < -300. || dz > 200.) return false;
if(fabs(dpx) > 3. || fabs(dpy) > 3.) return false;
if(dpz < 30. || dpz > 120.) return false;
if(x1 < 0. || x1 > 1.) return false;
if(x2 < 0. || x2 > 1.) return false;
if(xF < -1. || xF > 1.) return false;
if(fabs(trackSeparation) > 250.) return false;
if(chisq_dimuon > 15.) return false;
if(px1 < 0. || px2 > 0.) return false;
return true;
}
bool Dimuon::targetDimuon()
{
if(dz > -60. || dz < -300.) return false;
return true;
}
bool Dimuon::dumpDimuon()
{
if(dz < 0. || dz > 150.) return false;
return true;
}
Spill::Spill() : spillID(-1), quality(-1), targetPos(-1), TARGPOS_CONTROL(-1), skipflag(false)
{}
bool Spill::goodSpill()
{
return skipflag || (goodTargetPos() && goodTSGo() && goodScaler() && goodBeam() && goodBeamDAQ());
}
bool Spill::goodTargetPos()
{
if(targetPos != TARGPOS_CONTROL) return false;
if(targetPos < 1 || targetPos > 7) return false;
return true;
}
bool Spill::goodTSGo()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
if(TSGo < 1E3 || TSGo > 8E3) return false;
}
else if(trigSet <= 70)
{
if(TSGo < 1E2 || TSGo > 6E3) return false;
}
else
{
return false;
}
return true;
}
bool Spill::goodScaler()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
if(acceptedMatrix1 < 1E3 || acceptedMatrix1 > 8E3) return false;
if(afterInhMatrix1 < 1E3 || afterInhMatrix1 > 3E4) return false;
if(acceptedMatrix1/afterInhMatrix1 < 0.2 || acceptedMatrix1/afterInhMatrix1 > 0.9) return false;
}
else if(trigSet <= 70)
{
if(acceptedMatrix1 < 1E2 || acceptedMatrix1 > 6E3) return false;
if(afterInhMatrix1 < 1E2 || afterInhMatrix1 > 1E4) return false;
if(acceptedMatrix1/afterInhMatrix1 < 0.2 || acceptedMatrix1/afterInhMatrix1 > 1.05) return false;
}
else
{
return false;
}
return true;
}
bool Spill::goodBeam()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
//if(NM3ION < 2E12 || NM3ION > 1E13) return false;
if(G2SEM < 2E12 || G2SEM > 1E13) return false;
if(dutyFactor < 15. || dutyFactor > 60.) return false;
}
else if(trigSet <= 70)
{
//if(NM3ION < 2E12 || NM3ION > 1E13) return false;
if(G2SEM < 2E12 || G2SEM > 1E13) return false;
if(dutyFactor < 10. || dutyFactor > 60.) return false;
}
else
{
return false;
}
return true;
}
bool Spill::goodBeamDAQ()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
if(QIESum < 4E10 || QIESum > 1E12) return false;
if(inhibitSum < 4E9 || inhibitSum > 1E11) return false;
if(busySum < 4E9 || busySum > 1E11) return false;
}
else if(trigSet <= 70)
{
if(QIESum < 4E10 || QIESum > 1E12) return false;
if(inhibitSum < 4E9 || inhibitSum > 2E11) return false;
if(busySum < 4E9 || busySum > 1E11) return false;
}
else
{
return false;
}
return true;
}
int Spill::triggerSet()
{
if(spillID >= 371870 && spillID <= 376533) return -1; //timing shift in #59
if(spillID >= 378366 && spillID <= 379333) return -1; //timing shift in #59
if(spillID >= 416207 && spillID <= 424180) return -1; //manual target movement in #62
if(spillID >= SPILLID_MIN_62 && spillID <= 409540) return -1; //unstable trigger timing in #62
if(spillID >= SPILLID_MIN_57 && spillID <= SPILLID_MAX_57) return 57;
if(spillID >= SPILLID_MIN_59 && spillID <= SPILLID_MAX_59) return 59;
if(spillID >= SPILLID_MIN_61 && spillID <= SPILLID_MAX_61) return 61;
if(spillID >= SPILLID_MIN_62 && spillID <= SPILLID_MAX_62) return 62;
if(spillID >= SPILLID_MIN_67 && spillID <= SPILLID_MAX_67) return 67;
if(spillID >= SPILLID_MIN_70 && spillID <= SPILLID_MAX_70) return 70;
return -1;
}
void Spill::print()
{
using namespace std;
cout << " trigge set: " << triggerSet() << endl;
cout << " targetPos: " << targetPos << " " << TARGPOS_CONTROL << endl;
cout << " TSGo: " << TSGo << endl;
cout << " acceptedMatrix1: " << acceptedMatrix1 << endl;
cout << " afterInhMatrix1: " << afterInhMatrix1 << endl;
cout << " NM3ION: " << NM3ION << endl;
cout << " G2SEM: " << G2SEM << endl;
cout << " QIESum: " << QIESum << endl;
cout << " inhibitSum: " << inhibitSum << endl;
cout << " busySum: " << busySum << endl;
cout << " dutyFactor: " << dutyFactor << endl;
cout << " liveG2SEM: " << liveG2SEM << endl;
}
bool Track::goodTrack()
{
if(nHits <= 14) return false;
if(chisq/(nHits - 5) > 5.) return false;
if(z0 < -400. || z0 > 200.) return false;
if(roadID == 0) return false;
if(nHits < 18 && pz1 < 18.) return false;
return true;
}
bool Track::targetTrack()
{
if(z0 <= -300. || z0 >= 0.) return false;
if(chisq_dump - chisq_target < 10.) return false;
return true;
}
bool Track::dumpTrack()
{
if(z0 <= 0. && z0 >= 150.) return false;
if(chisq_target - chisq_dump < 10.) return false;
return true;
}
<commit_msg>added one more cut to reject the potential double-counted dimuon<commit_after>#include <cmath>
#include "DataStruct.h"
ClassImp(Event)
ClassImp(Dimuon)
ClassImp(Spill)
ClassImp(Track)
#define SPILLID_MIN_57 303215
#define SPILLID_MAX_57 370100
#define SPILLID_MIN_59 370110
#define SPILLID_MAX_59 388580
#define SPILLID_MIN_61 388611
#define SPILLID_MAX_61 391100
#define SPILLID_MIN_62 394308
#define SPILLID_MAX_62 482573
#define SPILLID_MIN_67 484946
#define SPILLID_MAX_67 676224
#define SPILLID_MIN_70 676498
#define SPILLID_MAX_70 696455
#define PEDESTAL 42.
Event::Event() : runID(-1), spillID(-1), eventID(-1), status(-1), MATRIX1(-1), weight(0.)
{
for(int i = 0; i < 33; ++i) intensity[i] = 0.;
}
bool Event::goodEvent()
{
return MATRIX1 > 0 && status == 0;
}
float Event::weightedIntensity()
{
double weight[] = {0.000814246430361413, 0.0028662467149288, 0.00597015326639906, 0.0121262946061061,
0.0300863195179747, 0.0777262437180552, 0.159446650644417, 0.259932709364831,
0.36718876894966, 0.488159093692654, 0.678969311099113, 0.847788074599439, 0.956475273764143,
1.,
0.989173954042814, 0.897678016090413, 0.767828869998712, 0.647167321489559, 0.533894756174369,
0.448848741080746, 0.356435437171761, 0.263693103645649, 0.177964720504253,
0.108504562083177, 0.0540099990325891, 0.019218568399343, 0.00308302089003216};
double sum = 0.;
for(int i = -13; i <= 13; ++i)
{
sum += (weight[i+13]*intensity[i+16]);
}
return sum/13.;
}
bool Dimuon::goodDimuon()
{
if(fabs(dx) > 2. || fabs(dy) > 2.) return false;
if(dz < -300. || dz > 200.) return false;
if(fabs(dpx) > 3. || fabs(dpy) > 3.) return false;
if(dpz < 30. || dpz > 120.) return false;
if(x1 < 0. || x1 > 1.) return false;
if(x2 < 0. || x2 > 1.) return false;
if(xF < -1. || xF > 1.) return false;
if(fabs(trackSeparation) > 250.) return false;
if(chisq_dimuon > 15.) return false;
if(px1 < 0. || px2 > 0.) return false;
return true;
}
bool Dimuon::targetDimuon()
{
if(dz > -60. || dz < -300.) return false;
return true;
}
bool Dimuon::dumpDimuon()
{
if(dz < 0. || dz > 150.) return false;
return true;
}
Spill::Spill() : spillID(-1), quality(-1), targetPos(-1), TARGPOS_CONTROL(-1), skipflag(false)
{}
bool Spill::goodSpill()
{
return skipflag || (goodTargetPos() && goodTSGo() && goodScaler() && goodBeam() && goodBeamDAQ());
}
bool Spill::goodTargetPos()
{
if(targetPos != TARGPOS_CONTROL) return false;
if(targetPos < 1 || targetPos > 7) return false;
return true;
}
bool Spill::goodTSGo()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
if(TSGo < 1E3 || TSGo > 8E3) return false;
}
else if(trigSet <= 70)
{
if(TSGo < 1E2 || TSGo > 6E3) return false;
}
else
{
return false;
}
return true;
}
bool Spill::goodScaler()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
if(acceptedMatrix1 < 1E3 || acceptedMatrix1 > 8E3) return false;
if(afterInhMatrix1 < 1E3 || afterInhMatrix1 > 3E4) return false;
if(acceptedMatrix1/afterInhMatrix1 < 0.2 || acceptedMatrix1/afterInhMatrix1 > 0.9) return false;
}
else if(trigSet <= 70)
{
if(acceptedMatrix1 < 1E2 || acceptedMatrix1 > 6E3) return false;
if(afterInhMatrix1 < 1E2 || afterInhMatrix1 > 1E4) return false;
if(acceptedMatrix1/afterInhMatrix1 < 0.2 || acceptedMatrix1/afterInhMatrix1 > 1.05) return false;
}
else
{
return false;
}
return true;
}
bool Spill::goodBeam()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
//if(NM3ION < 2E12 || NM3ION > 1E13) return false;
if(G2SEM < 2E12 || G2SEM > 1E13) return false;
if(dutyFactor < 15. || dutyFactor > 60.) return false;
}
else if(trigSet <= 70)
{
//if(NM3ION < 2E12 || NM3ION > 1E13) return false;
if(G2SEM < 2E12 || G2SEM > 1E13) return false;
if(dutyFactor < 10. || dutyFactor > 60.) return false;
}
else
{
return false;
}
return true;
}
bool Spill::goodBeamDAQ()
{
int trigSet = triggerSet();
if(trigSet < 0)
{
return false;
}
else if(trigSet <= 61)
{
if(QIESum < 4E10 || QIESum > 1E12) return false;
if(inhibitSum < 4E9 || inhibitSum > 1E11) return false;
if(busySum < 4E9 || busySum > 1E11) return false;
}
else if(trigSet <= 70)
{
if(QIESum < 4E10 || QIESum > 1E12) return false;
if(inhibitSum < 4E9 || inhibitSum > 2E11) return false;
if(busySum < 4E9 || busySum > 1E11) return false;
}
else
{
return false;
}
return true;
}
int Spill::triggerSet()
{
if(spillID >= 371870 && spillID <= 376533) return -1; //timing shift in #59
if(spillID >= 378366 && spillID <= 379333) return -1; //timing shift in #59
if(spillID >= 416207 && spillID <= 424180) return -1; //manual target movement in #62
if(spillID >= SPILLID_MIN_62 && spillID <= 409540) return -1; //unstable trigger timing in #62
if(spillID >= SPILLID_MIN_57 && spillID <= SPILLID_MAX_57) return 57;
if(spillID >= SPILLID_MIN_59 && spillID <= SPILLID_MAX_59) return 59;
if(spillID >= SPILLID_MIN_61 && spillID <= SPILLID_MAX_61) return 61;
if(spillID >= SPILLID_MIN_62 && spillID <= SPILLID_MAX_62) return 62;
if(spillID >= SPILLID_MIN_67 && spillID <= SPILLID_MAX_67) return 67;
if(spillID >= SPILLID_MIN_70 && spillID <= SPILLID_MAX_70) return 70;
return -1;
}
void Spill::print()
{
using namespace std;
cout << " trigge set: " << triggerSet() << endl;
cout << " targetPos: " << targetPos << " " << TARGPOS_CONTROL << endl;
cout << " TSGo: " << TSGo << endl;
cout << " acceptedMatrix1: " << acceptedMatrix1 << endl;
cout << " afterInhMatrix1: " << afterInhMatrix1 << endl;
cout << " NM3ION: " << NM3ION << endl;
cout << " G2SEM: " << G2SEM << endl;
cout << " QIESum: " << QIESum << endl;
cout << " inhibitSum: " << inhibitSum << endl;
cout << " busySum: " << busySum << endl;
cout << " dutyFactor: " << dutyFactor << endl;
cout << " liveG2SEM: " << liveG2SEM << endl;
}
bool Track::goodTrack()
{
if(nHits <= 14) return false;
if(chisq/(nHits - 5) > 5.) return false;
if(z0 < -400. || z0 > 200.) return false;
if(roadID == 0) return false;
if(nHits < 18 && pz1 < 18.) return false;
return true;
}
bool Track::targetTrack()
{
if(z0 <= -300. || z0 >= 0.) return false;
if(chisq_dump - chisq_target < 10.) return false;
return true;
}
bool Track::dumpTrack()
{
if(z0 <= 0. && z0 >= 150.) return false;
if(chisq_target - chisq_dump < 10.) return false;
return true;
}
<|endoftext|> |
<commit_before>// File: btBoostWrapper.cpp
#ifndef _btBoostWrapper_cpp
#define _btBoostWrapper_cpp
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wreorder"
#include <boost/python.hpp>
#include <btBoost/btBoostLinearMath.hpp>
#include <btBoost/btBoostDynamics.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(bullet)
{
defineLinearMath();
defineDynamics();
}
#endif // _btBoostWrapper_cpp
<commit_msg>Define a simple hello method for scratch testing<commit_after>// File: btBoostWrapper.cpp
#ifndef _btBoostWrapper_cpp
#define _btBoostWrapper_cpp
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wreorder"
#include <boost/python.hpp>
#include <btBoost/btBoostLinearMath.hpp>
#include <btBoost/btBoostDynamics.hpp>
#include <btBoost/btBoostHello.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(bullet)
{
defineHello();
defineLinearMath();
defineDynamics();
}
#endif // _btBoostWrapper_cpp
<|endoftext|> |
<commit_before>/*
* SourceCode.cpp
*
* This file is part of the XShaderCompiler project (Copyright (c) 2014-2016 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "SourceCode.h"
#include <algorithm>
namespace Xsc
{
SourceCode::SourceCode(const std::shared_ptr<std::istream>& stream) :
stream_{ stream }
{
}
bool SourceCode::IsValid() const
{
return (stream_ != nullptr && stream_->good());
}
char SourceCode::Next()
{
if (!IsValid())
return 0;
/* Check if reader is at end-of-line */
while (pos_.Column() >= currentLine_.size())
{
/* Read new line in source file */
std::getline(*stream_, currentLine_);
currentLine_ += '\n';
pos_.IncRow();
/* Store current line for later reports */
lines_.push_back(currentLine_);
/* Check if end-of-file is reached */
if (stream_->eof())
return 0;
}
/* Increment column and return current character */
auto chr = currentLine_[pos_.Column()];
pos_.IncColumn();
return chr;
}
static bool FinalizeMarker(
const SourceArea& area, const std::string& lineIn, std::string& lineOut, std::string& markerOut)
{
if (area.pos.Column() >= lineIn.size() || area.pos.Column() == 0 || area.length == 0)
return false;
lineOut = lineIn;
markerOut = std::string(area.pos.Column() - 1, ' ');
for (size_t i = 0, n = markerOut.size(); i < n; ++i)
{
if (lineIn[i] == '\t')
markerOut[i] = '\t';
}
auto len = std::min(area.length, lineIn.size() - area.pos.Column());
markerOut += '^';
markerOut += std::string(len - 1, '~');
return true;
}
bool SourceCode::FetchLineMarker(const SourceArea& area, std::string& line, std::string& marker)
{
if (area.length > 0)
{
auto row = area.pos.Row();
if (row == pos_.Row())
return FinalizeMarker(area, Line(), line, marker);
else if (row > 0)
return FinalizeMarker(area, GetLine(static_cast<std::size_t>(row - 1)), line, marker);
}
return false;
}
/*
* ======= Private: =======
*/
std::string SourceCode::GetLine(std::size_t lineIndex) const
{
return (lineIndex < lines_.size() ? lines_[lineIndex] : "");
}
} // /namespace Xsc
// ================================================================================<commit_msg>Fixed cast problem on MacOS port.<commit_after>/*
* SourceCode.cpp
*
* This file is part of the XShaderCompiler project (Copyright (c) 2014-2016 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "SourceCode.h"
#include <algorithm>
namespace Xsc
{
SourceCode::SourceCode(const std::shared_ptr<std::istream>& stream) :
stream_{ stream }
{
}
bool SourceCode::IsValid() const
{
return (stream_ != nullptr && stream_->good());
}
char SourceCode::Next()
{
if (!IsValid())
return 0;
/* Check if reader is at end-of-line */
while (pos_.Column() >= currentLine_.size())
{
/* Read new line in source file */
std::getline(*stream_, currentLine_);
currentLine_ += '\n';
pos_.IncRow();
/* Store current line for later reports */
lines_.push_back(currentLine_);
/* Check if end-of-file is reached */
if (stream_->eof())
return 0;
}
/* Increment column and return current character */
auto chr = currentLine_[pos_.Column()];
pos_.IncColumn();
return chr;
}
static bool FinalizeMarker(
const SourceArea& area, const std::string& lineIn, std::string& lineOut, std::string& markerOut)
{
if (area.pos.Column() >= lineIn.size() || area.pos.Column() == 0 || area.length == 0)
return false;
lineOut = lineIn;
markerOut = std::string(area.pos.Column() - 1, ' ');
for (size_t i = 0, n = markerOut.size(); i < n; ++i)
{
if (lineIn[i] == '\t')
markerOut[i] = '\t';
}
auto len = std::min(area.length, static_cast<unsigned int>(lineIn.size()) - area.pos.Column());
markerOut += '^';
markerOut += std::string(len - 1, '~');
return true;
}
bool SourceCode::FetchLineMarker(const SourceArea& area, std::string& line, std::string& marker)
{
if (area.length > 0)
{
auto row = area.pos.Row();
if (row == pos_.Row())
return FinalizeMarker(area, Line(), line, marker);
else if (row > 0)
return FinalizeMarker(area, GetLine(static_cast<std::size_t>(row - 1)), line, marker);
}
return false;
}
/*
* ======= Private: =======
*/
std::string SourceCode::GetLine(std::size_t lineIndex) const
{
return (lineIndex < lines_.size() ? lines_[lineIndex] : "");
}
} // /namespace Xsc
// ================================================================================
<|endoftext|> |
<commit_before>//
// TiledVectorLayerTileImageProvider.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 4/30/14.
//
//
#include "TiledVectorLayerTileImageProvider.hpp"
#include "TiledVectorLayer.hpp"
#include "Tile.hpp"
#include "IDownloader.hpp"
#include "TileImageListener.hpp"
#include "TileImageContribution.hpp"
#include "GEOJSONParser.hpp"
#include "GEOObject.hpp"
#include "GEORasterSymbolizer.hpp"
#include "IFactory.hpp"
#include "ICanvas.hpp"
#include "GEORasterProjection.hpp"
TiledVectorLayerTileImageProvider::GEOJSONBufferParser::~GEOJSONBufferParser() {
_imageAssembler->deletedParser();
if (_buffer) printf(" ****** (2) Deleting buffer=%p\n", _buffer);
delete _buffer;
if (_geoObject) printf(" ****** (2) Deleting geoObject=%p\n", _geoObject);
delete _geoObject;
#ifdef JAVA_CODE
super.dispose();
#endif
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferParser::cancel() {
_imageAssembler = NULL;
// printf(" ****** (1) Deleting buffer=%p\n", _buffer);
// delete _buffer;
// _buffer = NULL;
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferParser::runInBackground(const G3MContext* context) {
if ((_imageAssembler != NULL) && (_buffer != NULL)) {
printf(" ****** Parsing buffer=%p\n", _buffer);
_geoObject = GEOJSONParser::parseJSON(_buffer);
printf(" ****** Parsed geoObject=%p\n", _geoObject);
}
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferParser::onPostExecute(const G3MContext* context) {
if (_imageAssembler != NULL) {
GEOObject* geoObject = _geoObject;
_geoObject = NULL; // moves ownership of _geoObject to _imageAssembler
_imageAssembler->parsedGEOObject(geoObject);
}
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferDownloadListener::onDownload(const URL& url,
IByteBuffer* buffer,
bool expired) {
_imageAssembler->bufferDownloaded(buffer);
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferDownloadListener::onError(const URL& url) {
_imageAssembler->bufferDownloadError(url);
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferDownloadListener::onCancel(const URL& url) {
_imageAssembler->bufferDownloadCanceled();
}
TiledVectorLayerTileImageProvider::ImageAssembler::ImageAssembler(TiledVectorLayerTileImageProvider* tileImageProvider,
const Tile* tile,
const TileImageContribution* contribution,
TileImageListener* listener,
bool deleteListener,
const Vector2I& imageResolution,
IDownloader* downloader,
const IThreadUtils* threadUtils) :
_tileImageProvider(tileImageProvider),
_tileId(tile->_id),
_tileSector(tile->_sector),
_tileIsMercator(tile->_mercator),
_tileLevel(tile->_level),
_contribution(contribution),
_listener(listener),
_deleteListener(deleteListener),
_imageWidth(imageResolution._x),
_imageHeight(imageResolution._y),
_downloader(downloader),
_threadUtils(threadUtils),
_canceled(false),
_downloadListener(NULL),
_downloadRequestId(-1),
_parser(NULL),
_symbolizer(NULL)
{
}
void TiledVectorLayerTileImageProvider::ImageAssembler::start(const TiledVectorLayer* layer,
const Tile* tile,
long long tileDownloadPriority,
bool logDownloadActivity) {
_downloadListener = new GEOJSONBufferDownloadListener(this);
_symbolizer = layer->symbolizerCopy();
_downloadRequestId = layer->requestGEOJSONBuffer(tile,
_downloader,
tileDownloadPriority,
logDownloadActivity,
_downloadListener,
true /* deleteListener */);
}
TiledVectorLayerTileImageProvider::ImageAssembler::~ImageAssembler() {
if (_deleteListener) {
delete _listener;
}
TileImageContribution::deleteContribution(_contribution);
delete _symbolizer;
}
void TiledVectorLayerTileImageProvider::ImageAssembler::cancel() {
_canceled = true;
if (_downloadRequestId >= 0) {
_downloader->cancelRequest(_downloadRequestId);
_downloadRequestId = -1;
}
if (_parser != NULL) {
_parser->cancel();
}
#warning TODO call listener cancel
_listener->imageCreationCanceled(_tileId);
_tileImageProvider->requestFinish(_tileId);
}
void TiledVectorLayerTileImageProvider::ImageAssembler::bufferDownloaded(IByteBuffer* buffer) {
_downloadListener = NULL;
_downloadRequestId = -1;
if (!_canceled) {
_parser = new GEOJSONBufferParser(this, buffer);
_threadUtils->invokeAsyncTask(_parser,
true);
}
#warning Diego at work!
}
void TiledVectorLayerTileImageProvider::ImageAssembler::bufferDownloadError(const URL& url) {
_downloadListener = NULL;
_downloadRequestId = -1;
_listener->imageCreationError(_tileId,
"Download error - " + url.getPath());
_tileImageProvider->requestFinish(_tileId);
}
void TiledVectorLayerTileImageProvider::ImageAssembler::bufferDownloadCanceled() {
_downloadListener = NULL;
_downloadRequestId = -1;
// do nothing here, the cancel() method already notified the listener
// _listener->imageCreationCanceled(_tileId);
// _tileImageProvider->requestFinish(_tileId);
}
void TiledVectorLayerTileImageProvider::ImageAssembler::parsedGEOObject(GEOObject* geoObject) {
if (geoObject == NULL) {
_listener->imageCreationError(_tileId, "GEOJSON parser error");
if (_deleteListener) {
delete _listener;
}
}
else {
#warning Diego at work!
//ILogger::instance()->logInfo("Parsed geojson");
if (_canceled) {
printf(" ****** <<CANCELED>> Rasterizing geoObject=%p\n", geoObject);
}
else {
printf(" ****** Rasterizing geoObject=%p\n", geoObject);
}
ICanvas* canvas = IFactory::instance()->createCanvas();
canvas->initialize(_imageWidth, _imageHeight);
const GEORasterProjection* projection = new GEORasterProjection(_tileSector,
_tileIsMercator,
_imageWidth,
_imageHeight);;
geoObject->rasterize(_symbolizer,
canvas,
projection,
_tileLevel);
delete projection;
delete canvas;
printf(" ****** (1) Deleting geoObject=%p\n", geoObject);
delete geoObject;
#warning remove this
_listener->imageCreationError(_tileId,
"NOT YET IMPLEMENTED");
TileImageContribution::deleteContribution(_contribution);
_contribution = NULL;
_tileImageProvider->requestFinish(_tileId);
}
}
void TiledVectorLayerTileImageProvider::ImageAssembler::deletedParser() {
_parser = NULL;
}
const TileImageContribution* TiledVectorLayerTileImageProvider::contribution(const Tile* tile) {
return _layer->contribution(tile);
}
void TiledVectorLayerTileImageProvider::create(const Tile* tile,
const TileImageContribution* contribution,
const Vector2I& resolution,
long long tileDownloadPriority,
bool logDownloadActivity,
TileImageListener* listener,
bool deleteListener,
FrameTasksExecutor* frameTasksExecutor) {
ImageAssembler* assembler = new ImageAssembler(this,
tile,
contribution,
listener,
deleteListener,
resolution,
_downloader,
_threadUtils);
_assemblers[tile->_id] = assembler;
assembler->start(_layer,
tile,
tileDownloadPriority,
logDownloadActivity);
}
void TiledVectorLayerTileImageProvider::cancel(const std::string& tileId) {
#ifdef C_CODE
if (_assemblers.find(tileId) != _assemblers.end()) {
ImageAssembler* assembler = _assemblers[tileId];
assembler->cancel();
}
#endif
#ifdef JAVA_CODE
final ImageAssembler assembler = _assemblers.get(tileId);
if (assembler != null) {
assembler.cancel();
}
#endif
}
void TiledVectorLayerTileImageProvider::requestFinish(const std::string& tileId) {
#ifdef C_CODE
if (_assemblers.find(tileId) != _assemblers.end()) {
ImageAssembler* assembler = _assemblers[tileId];
delete assembler;
_assemblers.erase(tileId);
}
#endif
#ifdef JAVA_CODE
final ImageAssembler assembler = _assemblers.remove(tileId);
if (assembler != null) {
assembler.dispose();
}
#endif
}
<commit_msg>Tile's image creation refactoring - NOT YET USABLE<commit_after>//
// TiledVectorLayerTileImageProvider.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 4/30/14.
//
//
#include "TiledVectorLayerTileImageProvider.hpp"
#include "TiledVectorLayer.hpp"
#include "Tile.hpp"
#include "IDownloader.hpp"
#include "TileImageListener.hpp"
#include "TileImageContribution.hpp"
#include "GEOJSONParser.hpp"
#include "GEOObject.hpp"
#include "GEORasterSymbolizer.hpp"
#include "IFactory.hpp"
#include "ICanvas.hpp"
#include "GEORasterProjection.hpp"
TiledVectorLayerTileImageProvider::GEOJSONBufferParser::~GEOJSONBufferParser() {
_imageAssembler->deletedParser();
delete _buffer;
delete _geoObject;
#ifdef JAVA_CODE
super.dispose();
#endif
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferParser::cancel() {
_imageAssembler = NULL;
// delete _buffer;
// _buffer = NULL;
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferParser::runInBackground(const G3MContext* context) {
if ((_imageAssembler != NULL) && (_buffer != NULL)) {
_geoObject = GEOJSONParser::parseJSON(_buffer);
}
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferParser::onPostExecute(const G3MContext* context) {
if (_imageAssembler != NULL) {
GEOObject* geoObject = _geoObject;
_geoObject = NULL; // moves ownership of _geoObject to _imageAssembler
_imageAssembler->parsedGEOObject(geoObject);
}
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferDownloadListener::onDownload(const URL& url,
IByteBuffer* buffer,
bool expired) {
_imageAssembler->bufferDownloaded(buffer);
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferDownloadListener::onError(const URL& url) {
_imageAssembler->bufferDownloadError(url);
}
void TiledVectorLayerTileImageProvider::GEOJSONBufferDownloadListener::onCancel(const URL& url) {
_imageAssembler->bufferDownloadCanceled();
}
TiledVectorLayerTileImageProvider::ImageAssembler::ImageAssembler(TiledVectorLayerTileImageProvider* tileImageProvider,
const Tile* tile,
const TileImageContribution* contribution,
TileImageListener* listener,
bool deleteListener,
const Vector2I& imageResolution,
IDownloader* downloader,
const IThreadUtils* threadUtils) :
_tileImageProvider(tileImageProvider),
_tileId(tile->_id),
_tileSector(tile->_sector),
_tileIsMercator(tile->_mercator),
_tileLevel(tile->_level),
_contribution(contribution),
_listener(listener),
_deleteListener(deleteListener),
_imageWidth(imageResolution._x),
_imageHeight(imageResolution._y),
_downloader(downloader),
_threadUtils(threadUtils),
_canceled(false),
_downloadListener(NULL),
_downloadRequestId(-1),
_parser(NULL),
_symbolizer(NULL)
{
}
void TiledVectorLayerTileImageProvider::ImageAssembler::start(const TiledVectorLayer* layer,
const Tile* tile,
long long tileDownloadPriority,
bool logDownloadActivity) {
_downloadListener = new GEOJSONBufferDownloadListener(this);
_symbolizer = layer->symbolizerCopy();
_downloadRequestId = layer->requestGEOJSONBuffer(tile,
_downloader,
tileDownloadPriority,
logDownloadActivity,
_downloadListener,
true /* deleteListener */);
}
TiledVectorLayerTileImageProvider::ImageAssembler::~ImageAssembler() {
if (_deleteListener) {
delete _listener;
}
TileImageContribution::deleteContribution(_contribution);
delete _symbolizer;
}
void TiledVectorLayerTileImageProvider::ImageAssembler::cancel() {
_canceled = true;
if (_downloadRequestId >= 0) {
_downloader->cancelRequest(_downloadRequestId);
_downloadRequestId = -1;
}
if (_parser != NULL) {
_parser->cancel();
}
#warning TODO call listener cancel
_listener->imageCreationCanceled(_tileId);
_tileImageProvider->requestFinish(_tileId);
}
void TiledVectorLayerTileImageProvider::ImageAssembler::bufferDownloaded(IByteBuffer* buffer) {
_downloadListener = NULL;
_downloadRequestId = -1;
if (!_canceled) {
_parser = new GEOJSONBufferParser(this, buffer);
_threadUtils->invokeAsyncTask(_parser,
true);
}
#warning Diego at work!
}
void TiledVectorLayerTileImageProvider::ImageAssembler::bufferDownloadError(const URL& url) {
_downloadListener = NULL;
_downloadRequestId = -1;
_listener->imageCreationError(_tileId,
"Download error - " + url.getPath());
_tileImageProvider->requestFinish(_tileId);
}
void TiledVectorLayerTileImageProvider::ImageAssembler::bufferDownloadCanceled() {
_downloadListener = NULL;
_downloadRequestId = -1;
// do nothing here, the cancel() method already notified the listener
// _listener->imageCreationCanceled(_tileId);
// _tileImageProvider->requestFinish(_tileId);
}
void TiledVectorLayerTileImageProvider::ImageAssembler::parsedGEOObject(GEOObject* geoObject) {
if (geoObject == NULL) {
_listener->imageCreationError(_tileId, "GEOJSON parser error");
if (_deleteListener) {
delete _listener;
}
}
else {
#warning Diego at work!
//ILogger::instance()->logInfo("Parsed geojson");
ICanvas* canvas = IFactory::instance()->createCanvas();
canvas->initialize(_imageWidth, _imageHeight);
const GEORasterProjection* projection = new GEORasterProjection(_tileSector,
_tileIsMercator,
_imageWidth,
_imageHeight);;
geoObject->rasterize(_symbolizer,
canvas,
projection,
_tileLevel);
delete projection;
delete canvas;
delete geoObject;
#warning remove this
_listener->imageCreationError(_tileId,
"NOT YET IMPLEMENTED");
TileImageContribution::deleteContribution(_contribution);
_contribution = NULL;
_tileImageProvider->requestFinish(_tileId);
}
}
void TiledVectorLayerTileImageProvider::ImageAssembler::deletedParser() {
_parser = NULL;
}
const TileImageContribution* TiledVectorLayerTileImageProvider::contribution(const Tile* tile) {
return _layer->contribution(tile);
}
void TiledVectorLayerTileImageProvider::create(const Tile* tile,
const TileImageContribution* contribution,
const Vector2I& resolution,
long long tileDownloadPriority,
bool logDownloadActivity,
TileImageListener* listener,
bool deleteListener,
FrameTasksExecutor* frameTasksExecutor) {
ImageAssembler* assembler = new ImageAssembler(this,
tile,
contribution,
listener,
deleteListener,
resolution,
_downloader,
_threadUtils);
_assemblers[tile->_id] = assembler;
assembler->start(_layer,
tile,
tileDownloadPriority,
logDownloadActivity);
}
void TiledVectorLayerTileImageProvider::cancel(const std::string& tileId) {
#ifdef C_CODE
if (_assemblers.find(tileId) != _assemblers.end()) {
ImageAssembler* assembler = _assemblers[tileId];
assembler->cancel();
}
#endif
#ifdef JAVA_CODE
final ImageAssembler assembler = _assemblers.get(tileId);
if (assembler != null) {
assembler.cancel();
}
#endif
}
void TiledVectorLayerTileImageProvider::requestFinish(const std::string& tileId) {
#ifdef C_CODE
if (_assemblers.find(tileId) != _assemblers.end()) {
ImageAssembler* assembler = _assemblers[tileId];
delete assembler;
_assemblers.erase(tileId);
}
#endif
#ifdef JAVA_CODE
final ImageAssembler assembler = _assemblers.remove(tileId);
if (assembler != null) {
assembler.dispose();
}
#endif
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <stdexcept>
const uint32_t MOD = 1000000007;
const size_t MAX_LENGTH = 200;
typedef std::vector<std::vector<uint32_t>> matrix;
/**
* The class substring presents an efficient substring view of a string by
* using an offset and source string reference to avoid copy substrings.
*/
class substring {
private:
const std::string& source;
size_t start;
size_t end;
public:
substring(const std::string& source, size_t start, size_t end) :
source(source), start(start), end(end) {
}
const char& operator[](size_t i) const {
if (i >= this->length()) {
throw std::invalid_argument("Out of bounds!");
}
return this->source[this->start + i];
}
size_t length() const {
return this->end - this->start + 1;
}
};
uint32_t add(const uint32_t& a, const uint32_t& b) {
return ((uint64_t) a + b) % MOD;
}
uint32_t sub(const uint32_t& a, const uint32_t& b) {
return ((uint64_t) a - b + MOD) % MOD;
}
template<class S, class C>
uint32_t common(const S& a, const S& b, C& cache) { // NOLINT
cache[0][0] = 1;
for (size_t j = 0; j <= a.length(); j++) {
for (size_t k = 0; k <= b.length(); k++) {
if (j > 0 || k > 0) {
cache[j][k] = 0;
}
if (j > 0) {
cache[j][k] = add(cache[j][k], cache[j - 1][k]);
}
if (k > 0) {
cache[j][k] = add(cache[j][k], cache[j][k - 1]);
}
if (j > 0 && k > 0 && a[j - 1] != b[k - 1]) {
cache[j][k] = sub(cache[j][k], cache[j - 1][k - 1]);
}
}
}
uint32_t count = 0;
for (size_t k = 0; k < b.length(); k++) {
if (a[a.length() - 1] == b[k]) {
count = add(count, cache[a.length() - 1][k]);
}
}
return count;
}
uint32_t countss(const std::string& str, matrix& cache) { // NOLINT
uint32_t count = 0;
for (size_t i = 0; i < str.length() - 1; i++) {
substring a(str, 0, i);
substring b(str, i + 1, str.length() - 1);
count = add(count, common<substring, matrix>(a, b, cache));
}
return count;
}
uint32_t countss(const std::string& str) {
matrix cache(MAX_LENGTH + 1, std::vector<uint32_t>(MAX_LENGTH + 1, 0));
return countss(str, cache);
}
int main() {
uint16_t T;
std::string S;
std::cin >> T;
while (T--) {
std::cin >> S;
std::cout << countss(S) << std::endl;
}
return 0;
}
<commit_msg>Cleanup Square Subsequences problem<commit_after>#include <iostream>
#include <array>
const uint32_t MOD = 1000000007;
const size_t MAX_LENGTH = 200;
//
// Safely calculates (a + b) % MOD
//
int add(int a, int b) {
return ((int64_t) a + b) % MOD;
}
//
// Safely calculates (a - b) % MOD
//
int sub(int a, int b) {
return ((int64_t) a - b + MOD) % MOD;
}
//
// Calculates the number of subsequences in common between L = s[0...p] and
// R = s[p + 1...n] where each subsequence ends with s[p]. Takes
// O(length(L) * length(R)) time.
//
int common(const std::string& s, int p) {
// Each dp[i][j] is the number of common subsequences in the first i
// characters of L and the first j characters of R.
int dp[MAX_LENGTH][MAX_LENGTH] = {{0}};
// Length of L = s[0...p].
int n = p + 1;
// Length of R = s[p + 1...n].
int m = s.size() - n;
// Base case - Length of longest common subsequences between "" and x where
// |x| > 0 is 1. (The empty subsequence)
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (int j = 0; j <= m; j++) {
dp[0][j] = 1;
}
//
// Consider function f(i, j) = The number of common subsequences between
// L[0...i - 1] and R[0...j - 1]. We have already described the base case
// H(*, 0) = H(0, *) = 1 above. The two recursive cases are as follows.
//
// 1. H(i, j) = H(i, j - 1) + H(i - 1, j) - H(i - 1, j - 1) if
// L[i - 1] != R[j - 1]. We must subtract H(i - 1, j - 1) to avoid double
// counting subsequences. (Inclusion Exclusion Principle)
//
// 2. H(i, j) = H(i, j - 1) + H(i - 1, j) - H(i - 1, j - 1) + H(i - 1, j - 1)
// = H(i - 1, j) + H(i, j - 1) if L[i - 1] == R[j - 1]. We must consider
// common subsequences counted by H(i - 1, j - 1) as a prefix to the
// common subsequences ending with L[i - 1] == R[j - 1].
//
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = add(dp[i][j], dp[i - 1][j]);
dp[i][j] = add(dp[i][j], dp[i][j - 1]);
if (s[i - 1] != s[p + j]) {
dp[i][j] = sub(dp[i][j], dp[i - 1][j - 1]);
}
}
}
//
// Count only the common subsequences ending with s[p] - the last character
// of L.
//
int count = 0;
for (int j = 0; j < m; j++) {
if (s[p] == s[p + j + 1]) {
count = add(count, dp[p][j]);
}
}
return count;
}
//
// Counts the square subsequences in s. The idea behind the algorithm is to...
//
// 1. Consider all partitions s = LR of s where |L| > 0 and |R| > 0
//
// 2. Count the number of subsequences shared between each L and R ending with
// the last character of L. This is important because it forms a partition
// boundary so that we do not double count any subsequences across different
// partitions.
//
int countss(const std::string& s) {
int count = 0;
for (size_t p = 0; p < s.length() - 1; p++) {
count = add(count, common(s, p));
}
return count;
}
int main() {
int T;
std::string S;
std::cin >> T;
while (T--) {
std::cin >> S;
std::cout << countss(S) << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
RCSwitch - Arduino libary for remote control outlet switches
Copyright (c) 2011 Suat Özgür. All right reserved.
Contributors:
- Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com
Project home: http://code.google.com/p/rc-switch/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "RCSwitch.h"
RCSwitchCallback RCSwitch::mCallback;
RCSwitch::RCSwitch() {
this->nReceiverInterrupt = -1;
this->nTransmitterPin = -1;
this->setPulseLength(350);
this->setRepeatTransmit(10);
}
/**
* deprecated
*/
RCSwitch::RCSwitch(int nTransmitterPin) {
this->enableTransmit(nTransmitterPin);
this->setPulseLength(350);
this->setRepeatTransmit(10);
}
/**
* deprecated
*/
RCSwitch::RCSwitch(int nTransmitterPin, int nDelay) {
this->enableTransmit(nTransmitterPin);
this->setPulseLength(nDelay);
this->setRepeatTransmit(10);
}
/**
* Sets pulse length in microseconds
*/
void RCSwitch::setPulseLength(int nPulseLength) {
this->nPulseLength = nPulseLength;
}
/**
* Sets Repeat Transmits
*/
void RCSwitch::setRepeatTransmit(int RepeatTransmit) {
this->RepeatTransmit = RepeatTransmit;
}
/**
* Enable transmissions
*
* @param nTransmitterPin Arduino Pin to which the sender is connected to
*/
void RCSwitch::enableTransmit(int nTransmitterPin) {
this->nTransmitterPin = nTransmitterPin;
pinMode(this->nTransmitterPin, OUTPUT);
}
/**
* Disable transmissions
*/
void RCSwitch::disableTransmit() {
this->nTransmitterPin = -1;
}
/**
* Switch a remote switch on (Type C Intertechno)
*
* @param sFamily Familycode (a..f)
* @param nGroup Number of group (1..4)
* @param nDevice Number of device (1..4)
*/
void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) {
this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, true) );
}
/**
* Switch a remote switch off (Type C Intertechno)
*
* @param sFamily Familycode (a..f)
* @param nGroup Number of group (1..4)
* @param nDevice Number of device (1..4)
*/
void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) {
this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, false) );
}
/**
* Switch a remote switch on (Type B with two rotary/sliding switches)
*
* @param nAddressCode Number of the switch group (1..4)
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOn(int nAddressCode, int nChannelCode) {
this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, true) );
}
/**
* Switch a remote switch off (Type B with two rotary/sliding switches)
*
* @param nAddressCode Number of the switch group (1..4)
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOff(int nAddressCode, int nChannelCode) {
this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, false) );
}
/**
* Switch a remote switch on (Type A with 10 pole DIP switches)
*
* @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111")
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOn(String sGroup, int nChannel) {
this->sendTriState( this->getCodeWordA(sGroup, nChannel, true) );
}
/**
* Switch a remote switch off (Type A with 10 pole DIP switches)
*
* @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111")
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOff(String sGroup, int nChannel) {
this->sendTriState( this->getCodeWordA(sGroup, nChannel, false) );
}
/**
* Returns a String[13], representing the Code Word to be send.
* A Code Word consists of 9 address bits, 3 data bits and one sync bit but in our case only the first 8 address bits and the last 2 data bits were used.
* A Code Bit can have 4 different states: "F" (floating), "0" (low), "1" (high), "S" (synchronous bit)
*
* +-------------------------------+--------------------------------+-----------------------------------------+-----------------------------------------+----------------------+------------+
* | 4 bits address (switch group) | 4 bits address (switch number) | 1 bit address (not used, so never mind) | 1 bit address (not used, so never mind) | 2 data bits (on|off) | 1 sync bit |
* | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | F | F | on=FF off=F0 | S |
* +-------------------------------+--------------------------------+-----------------------------------------+-----------------------------------------+----------------------+------------+
*
* @param nAddressCode Number of the switch group (1..4)
* @param nChannelCode Number of the switch itself (1..4)
* @param bStatus Wether to switch on (true) or off (false)
*
* @return String[13]
*/
String RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, boolean bStatus) {
String code[5] = { "FFFF", "0FFF", "F0FF", "FF0F", "FFF0" };
if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) {
return "";
}
return code[nAddressCode] + code[nChannelCode] + "FF" + (bStatus==true?"FF":"F0");
}
/**
* Like getCodeWord (Type A)
*/
String RCSwitch::getCodeWordA(String sGroup, int nChannelCode, boolean bStatus) {
String code[6] = { "FFFFF", "0FFFF", "F0FFF", "FF0FF", "FFF0F", "FFFF0" };
if (sGroup.length() != 5 || nChannelCode < 1 || nChannelCode > 5) {
return "";
}
String sAddressCode = "";
for (int i = 0; i<5; i++) {
if (sGroup[i] == '0') {
sAddressCode += "F";
} else {
sAddressCode += "0";
}
}
return sAddressCode + code[nChannelCode] + (bStatus==true?"0F":"F0");
}
/**
* Like getCodeWord (Type C = Intertechno)
*/
String RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, boolean bStatus) {
if ( (byte)sFamily < 97 || (byte)sFamily > 112) {
return "";
}
if (nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) {
return "";
}
char* sDeviceGroupCode = dec2binWzerofill( (nDevice-1) + (nGroup-1)*4, 4 );
String familycode[16] = { "0000", "1000", "0100", "1100", "0010", "1010", "0110", "1110", "0001", "1001", "0101", "1101", "0011", "1011", "0111", "1111" };
String sReturn = familycode[ (int)sFamily - 97 ];
for (int i = 0; i<4; i++) {
sReturn = sReturn + sDeviceGroupCode[3-i];
}
sReturn = sReturn + "01";
sReturn = sReturn + (bStatus==true?"11":"10");
return sReturn;
}
/**
* Sends a Code Word
* @param sCodeWord /^[10FS]*$/ -> see getCodeWord
*/
void RCSwitch::sendTriState(String sCodeWord) {
for (int nRepeat=0; nRepeat<RepeatTransmit; nRepeat++) {
for(int i=0; i<sCodeWord.length(); i++) {
switch(sCodeWord[i]) {
case '0':
this->sendT0();
break;
case 'F':
this->sendTF();
break;
case '1':
this->sendT1();
break;
}
}
this->sendSync();
}
}
void RCSwitch::send(unsigned long Code, unsigned int length) {
this->send( this->dec2binWzerofill(Code, length) );
}
void RCSwitch::send(char* sCodeWord) {
for (int nRepeat=0; nRepeat<RepeatTransmit; nRepeat++) {
int i = 0;
while (sCodeWord[i] != '\0') {
switch(sCodeWord[i]) {
case '0':
this->send0();
break;
case '1':
this->send1();
break;
}
i++;
}
this->sendSync();
}
}
void RCSwitch::transmit(int nHighPulses, int nLowPulses) {
if (this->nTransmitterPin != -1) {
int nRec = this->nReceiverInterrupt;
if (this->nReceiverInterrupt != -1) {
this->disableReceive();
}
digitalWrite(this->nTransmitterPin, HIGH);
delayMicroseconds( this->nPulseLength * nHighPulses);
digitalWrite(this->nTransmitterPin, LOW);
delayMicroseconds( this->nPulseLength * nLowPulses);
if (nRec != -1) {
this->enableReceive(nRec, this->mCallback);
}
}
}
/**
* Sends a "0" Bit
* _
* Waveform: | |___
*/
void RCSwitch::send0() {
this->transmit(1,3);
}
/**
* Sends a "1" Bit
* ___
* Waveform: | |_
*/
void RCSwitch::send1() {
this->transmit(3,1);
}
/**
* Sends a Tri-State "0" Bit
* _ _
* Waveform: | |___| |___
*/
void RCSwitch::sendT0() {
this->transmit(1,3);
this->transmit(1,3);
}
/**
* Sends a Tri-State "1" Bit
* ___ ___
* Waveform: | |_| |_
*/
void RCSwitch::sendT1() {
this->transmit(3,1);
this->transmit(3,1);
}
/**
* Sends a Tri-State "F" Bit
* _ ___
* Waveform: | |___| |_
*/
void RCSwitch::sendTF() {
this->transmit(1,3);
this->transmit(3,1);
}
/**
* Sends a "Sync" Bit
* _
* Waveform: | |_______________________________
*/
void RCSwitch::sendSync() {
this->transmit(1,31);
}
/**
* Enable receiving data
*/
void RCSwitch::enableReceive(int interrupt, RCSwitchCallback callback) {
this->nReceiverInterrupt = interrupt;
attachInterrupt(this->nReceiverInterrupt, receiveInterrupt, CHANGE);
this->mCallback = callback;
}
/**
* Disable receiving data
*/
void RCSwitch::disableReceive() {
detachInterrupt(this->nReceiverInterrupt);
this->nReceiverInterrupt = -1;
}
/**
*
*/
void RCSwitch::receiveInterrupt() {
static unsigned int duration;
static unsigned int changeCount;
static unsigned int timings[RCSWITCH_MAX_CHANGES];
static unsigned long lastTime;
static unsigned int repeatCount;
long time = micros();
duration = time - lastTime;
if (duration > 5000 && duration > timings[0] - 200 && duration < timings[0] + 200) {
repeatCount++;
changeCount--;
if (repeatCount == 2) {
unsigned long code = 0;
unsigned long delay = timings[0] / 31;
unsigned long delayTolerance = delay*0.3;
for (int i = 1; i<changeCount ; i=i+2) {
if (timings[i] > delay-delayTolerance && timings[i] < delay+delayTolerance && timings[i+1] > delay*3-delayTolerance && timings[i+1] < delay*3+delayTolerance) {
code = code << 1;
} else if (timings[i] > delay*3-delayTolerance && timings[i] < delay*+delayTolerance && timings[i+1] > delay-delayTolerance && timings[i+1] < delay+delayTolerance) {
code+=1;
code = code << 1;
} else {
// Failed
i = changeCount;
code = 0;
repeatCount = 0;
}
}
code = code >> 1;
(mCallback)(code, changeCount/2, delay, timings);
repeatCount = 0;
}
changeCount = 0;
} else if (duration > 5000) {
changeCount = 0;
}
if (changeCount >= RCSWITCH_MAX_CHANGES) {
changeCount = 0;
repeatCount = 0;
}
timings[changeCount++] = duration;
lastTime = time;
}
/**
* Turns a decimal value to its binary representation
*/
char* RCSwitch::dec2binWzerofill(unsigned long Dec, unsigned int bitLength){
static char bin[64];
unsigned int i=0;
while (Dec > 0) {
bin[32+i++] = (Dec & 1 > 0) ? '1' : '0';
Dec = Dec >> 1;
}
for (unsigned int j = 0; j< bitLength; j++) {
if (j >= bitLength - i) {
bin[j] = bin[ 31 + i - (j - (bitLength - i)) ];
}else {
bin[j] = '0';
}
}
bin[bitLength] = '\0';
return bin;
}
<commit_msg>bugfix Intertechno encoding<commit_after>/*
RCSwitch - Arduino libary for remote control outlet switches
Copyright (c) 2011 Suat Özgür. All right reserved.
Contributors:
- Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com
Project home: http://code.google.com/p/rc-switch/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "RCSwitch.h"
RCSwitchCallback RCSwitch::mCallback;
RCSwitch::RCSwitch() {
this->nReceiverInterrupt = -1;
this->nTransmitterPin = -1;
this->setPulseLength(350);
this->setRepeatTransmit(10);
}
/**
* deprecated
*/
RCSwitch::RCSwitch(int nTransmitterPin) {
this->enableTransmit(nTransmitterPin);
this->setPulseLength(350);
this->setRepeatTransmit(10);
}
/**
* deprecated
*/
RCSwitch::RCSwitch(int nTransmitterPin, int nDelay) {
this->enableTransmit(nTransmitterPin);
this->setPulseLength(nDelay);
this->setRepeatTransmit(10);
}
/**
* Sets pulse length in microseconds
*/
void RCSwitch::setPulseLength(int nPulseLength) {
this->nPulseLength = nPulseLength;
}
/**
* Sets Repeat Transmits
*/
void RCSwitch::setRepeatTransmit(int RepeatTransmit) {
this->RepeatTransmit = RepeatTransmit;
}
/**
* Enable transmissions
*
* @param nTransmitterPin Arduino Pin to which the sender is connected to
*/
void RCSwitch::enableTransmit(int nTransmitterPin) {
this->nTransmitterPin = nTransmitterPin;
pinMode(this->nTransmitterPin, OUTPUT);
}
/**
* Disable transmissions
*/
void RCSwitch::disableTransmit() {
this->nTransmitterPin = -1;
}
/**
* Switch a remote switch on (Type C Intertechno)
*
* @param sFamily Familycode (a..f)
* @param nGroup Number of group (1..4)
* @param nDevice Number of device (1..4)
*/
void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) {
this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, true) );
}
/**
* Switch a remote switch off (Type C Intertechno)
*
* @param sFamily Familycode (a..f)
* @param nGroup Number of group (1..4)
* @param nDevice Number of device (1..4)
*/
void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) {
this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, false) );
}
/**
* Switch a remote switch on (Type B with two rotary/sliding switches)
*
* @param nAddressCode Number of the switch group (1..4)
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOn(int nAddressCode, int nChannelCode) {
this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, true) );
}
/**
* Switch a remote switch off (Type B with two rotary/sliding switches)
*
* @param nAddressCode Number of the switch group (1..4)
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOff(int nAddressCode, int nChannelCode) {
this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, false) );
}
/**
* Switch a remote switch on (Type A with 10 pole DIP switches)
*
* @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111")
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOn(String sGroup, int nChannel) {
this->sendTriState( this->getCodeWordA(sGroup, nChannel, true) );
}
/**
* Switch a remote switch off (Type A with 10 pole DIP switches)
*
* @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111")
* @param nChannelCode Number of the switch itself (1..4)
*/
void RCSwitch::switchOff(String sGroup, int nChannel) {
this->sendTriState( this->getCodeWordA(sGroup, nChannel, false) );
}
/**
* Returns a String[13], representing the Code Word to be send.
* A Code Word consists of 9 address bits, 3 data bits and one sync bit but in our case only the first 8 address bits and the last 2 data bits were used.
* A Code Bit can have 4 different states: "F" (floating), "0" (low), "1" (high), "S" (synchronous bit)
*
* +-------------------------------+--------------------------------+-----------------------------------------+-----------------------------------------+----------------------+------------+
* | 4 bits address (switch group) | 4 bits address (switch number) | 1 bit address (not used, so never mind) | 1 bit address (not used, so never mind) | 2 data bits (on|off) | 1 sync bit |
* | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | F | F | on=FF off=F0 | S |
* +-------------------------------+--------------------------------+-----------------------------------------+-----------------------------------------+----------------------+------------+
*
* @param nAddressCode Number of the switch group (1..4)
* @param nChannelCode Number of the switch itself (1..4)
* @param bStatus Wether to switch on (true) or off (false)
*
* @return String[13]
*/
String RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, boolean bStatus) {
String code[5] = { "FFFF", "0FFF", "F0FF", "FF0F", "FFF0" };
if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) {
return "";
}
return code[nAddressCode] + code[nChannelCode] + "FF" + (bStatus==true?"FF":"F0");
}
/**
* Like getCodeWord (Type A)
*/
String RCSwitch::getCodeWordA(String sGroup, int nChannelCode, boolean bStatus) {
String code[6] = { "FFFFF", "0FFFF", "F0FFF", "FF0FF", "FFF0F", "FFFF0" };
if (sGroup.length() != 5 || nChannelCode < 1 || nChannelCode > 5) {
return "";
}
String sAddressCode = "";
for (int i = 0; i<5; i++) {
if (sGroup[i] == '0') {
sAddressCode += "F";
} else {
sAddressCode += "0";
}
}
return sAddressCode + code[nChannelCode] + (bStatus==true?"0F":"F0");
}
/**
* Like getCodeWord (Type C = Intertechno)
*/
String RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, boolean bStatus) {
if ( (byte)sFamily < 97 || (byte)sFamily > 112) {
return "";
}
if (nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) {
return "";
}
char* sDeviceGroupCode = dec2binWzerofill( (nDevice-1) + (nGroup-1)*4, 4 );
String familycode[16] = { "0000", "F000", "0F00", "FF00", "00F0", "F0F0", "0FF0", "FFF0", "000F", "F00F", "0F0F", "FF0F", "00FF", "F0FF", "0FFF", "FFFF" };
String sReturn = familycode[ (int)sFamily - 97 ];
for (int i = 0; i<4; i++) {
sReturn = sReturn + (sDeviceGroupCode[3-i] == '1' ? "F" : "0");
}
sReturn = sReturn + "0F";
sReturn = sReturn + (bStatus==true?"FF":"F0");
return sReturn;
}
/**
* Sends a Code Word
* @param sCodeWord /^[10FS]*$/ -> see getCodeWord
*/
void RCSwitch::sendTriState(String sCodeWord) {
for (int nRepeat=0; nRepeat<RepeatTransmit; nRepeat++) {
for(int i=0; i<sCodeWord.length(); i++) {
switch(sCodeWord[i]) {
case '0':
this->sendT0();
break;
case 'F':
this->sendTF();
break;
case '1':
this->sendT1();
break;
}
}
this->sendSync();
}
}
void RCSwitch::send(unsigned long Code, unsigned int length) {
this->send( this->dec2binWzerofill(Code, length) );
}
void RCSwitch::send(char* sCodeWord) {
for (int nRepeat=0; nRepeat<RepeatTransmit; nRepeat++) {
int i = 0;
while (sCodeWord[i] != '\0') {
switch(sCodeWord[i]) {
case '0':
this->send0();
break;
case '1':
this->send1();
break;
}
i++;
}
this->sendSync();
}
}
void RCSwitch::transmit(int nHighPulses, int nLowPulses) {
if (this->nTransmitterPin != -1) {
int nRec = this->nReceiverInterrupt;
if (this->nReceiverInterrupt != -1) {
this->disableReceive();
}
digitalWrite(this->nTransmitterPin, HIGH);
delayMicroseconds( this->nPulseLength * nHighPulses);
digitalWrite(this->nTransmitterPin, LOW);
delayMicroseconds( this->nPulseLength * nLowPulses);
if (nRec != -1) {
this->enableReceive(nRec, this->mCallback);
}
}
}
/**
* Sends a "0" Bit
* _
* Waveform: | |___
*/
void RCSwitch::send0() {
this->transmit(1,3);
}
/**
* Sends a "1" Bit
* ___
* Waveform: | |_
*/
void RCSwitch::send1() {
this->transmit(3,1);
}
/**
* Sends a Tri-State "0" Bit
* _ _
* Waveform: | |___| |___
*/
void RCSwitch::sendT0() {
this->transmit(1,3);
this->transmit(1,3);
}
/**
* Sends a Tri-State "1" Bit
* ___ ___
* Waveform: | |_| |_
*/
void RCSwitch::sendT1() {
this->transmit(3,1);
this->transmit(3,1);
}
/**
* Sends a Tri-State "F" Bit
* _ ___
* Waveform: | |___| |_
*/
void RCSwitch::sendTF() {
this->transmit(1,3);
this->transmit(3,1);
}
/**
* Sends a "Sync" Bit
* _
* Waveform: | |_______________________________
*/
void RCSwitch::sendSync() {
this->transmit(1,31);
}
/**
* Enable receiving data
*/
void RCSwitch::enableReceive(int interrupt, RCSwitchCallback callback) {
this->nReceiverInterrupt = interrupt;
attachInterrupt(this->nReceiverInterrupt, receiveInterrupt, CHANGE);
this->mCallback = callback;
}
/**
* Disable receiving data
*/
void RCSwitch::disableReceive() {
detachInterrupt(this->nReceiverInterrupt);
this->nReceiverInterrupt = -1;
}
/**
*
*/
void RCSwitch::receiveInterrupt() {
static unsigned int duration;
static unsigned int changeCount;
static unsigned int timings[RCSWITCH_MAX_CHANGES];
static unsigned long lastTime;
static unsigned int repeatCount;
long time = micros();
duration = time - lastTime;
if (duration > 5000 && duration > timings[0] - 200 && duration < timings[0] + 200) {
repeatCount++;
changeCount--;
if (repeatCount == 2) {
unsigned long code = 0;
unsigned long delay = timings[0] / 31;
unsigned long delayTolerance = delay*0.3;
for (int i = 1; i<changeCount ; i=i+2) {
if (timings[i] > delay-delayTolerance && timings[i] < delay+delayTolerance && timings[i+1] > delay*3-delayTolerance && timings[i+1] < delay*3+delayTolerance) {
code = code << 1;
} else if (timings[i] > delay*3-delayTolerance && timings[i] < delay*+delayTolerance && timings[i+1] > delay-delayTolerance && timings[i+1] < delay+delayTolerance) {
code+=1;
code = code << 1;
} else {
// Failed
i = changeCount;
code = 0;
repeatCount = 0;
}
}
code = code >> 1;
(mCallback)(code, changeCount/2, delay, timings);
repeatCount = 0;
}
changeCount = 0;
} else if (duration > 5000) {
changeCount = 0;
}
if (changeCount >= RCSWITCH_MAX_CHANGES) {
changeCount = 0;
repeatCount = 0;
}
timings[changeCount++] = duration;
lastTime = time;
}
/**
* Turns a decimal value to its binary representation
*/
char* RCSwitch::dec2binWzerofill(unsigned long Dec, unsigned int bitLength){
static char bin[64];
unsigned int i=0;
while (Dec > 0) {
bin[32+i++] = (Dec & 1 > 0) ? '1' : '0';
Dec = Dec >> 1;
}
for (unsigned int j = 0; j< bitLength; j++) {
if (j >= bitLength - i) {
bin[j] = bin[ 31 + i - (j - (bitLength - i)) ];
}else {
bin[j] = '0';
}
}
bin[bitLength] = '\0';
return bin;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "distances/detail/Matrix.hh"
#include "distances/detail/Munkres.hh"
using namespace aleph::distances::detail;
int main()
{
Matrix<unsigned short> m( 3 );
m(0,0) = 1; m(0,1) = 2; m(0,2) = 3;
m(1,0) = 2; m(1,1) = 4; m(1,2) = 6;
m(2,0) = 3; m(2,1) = 6; m(2,2) = 9;
auto separator = std::string( 80, '-' );
std::cerr << separator << "\n"
<< "Original costs\n"
<< separator << "\n"
<< m
<< separator << "\n";
Munkres<unsigned short> solver( m );
solver();
}
<commit_msg>Extended test for Hungarian method<commit_after>#include <iostream>
#include <string>
#include "distances/detail/Matrix.hh"
#include "distances/detail/Munkres.hh"
using namespace aleph::distances::detail;
int main()
{
{
Matrix<unsigned short> m( 3 );
m(0,0) = 1; m(0,1) = 2; m(0,2) = 3;
m(1,0) = 2; m(1,1) = 4; m(1,2) = 6;
m(2,0) = 3; m(2,1) = 6; m(2,2) = 9;
auto separator = std::string( 80, '-' );
std::cerr << separator << "\n"
<< "Original costs\n"
<< separator << "\n"
<< m
<< separator << "\n";
Munkres<unsigned short> solver( m );
solver();
std::cerr << separator << "\n"
<< "Modified costs\n"
<< separator << "\n"
<< m
<< separator << "\n";
}
{
Matrix<unsigned short> m( 4 );
m(0,0) = 82; m(0,1) = 83; m(0,2) = 69; m(0,3) = 92;
m(1,0) = 77; m(1,1) = 37; m(1,2) = 49; m(1,3) = 92;
m(2,0) = 11; m(2,1) = 69; m(2,2) = 5; m(2,3) = 86;
m(3,0) = 8; m(3,1) = 9; m(3,2) = 98; m(3,3) = 23;
Munkres<unsigned short> solver( m );
std::cerr << solver();
// TODO: Check...
// 2,0
// 1,1
// 0,2
// 3,3
// Costs should be 140
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/validators/schema/identity/FieldActivator.hpp>
#include <xercesc/validators/schema/identity/ValueStore.hpp>
#include <xercesc/validators/schema/identity/IC_Field.hpp>
#include <xercesc/validators/schema/identity/IC_KeyRef.hpp>
#include <xercesc/validators/schema/identity/ValueStoreCache.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ValueStore: Constructors and Destructor
// ---------------------------------------------------------------------------
ValueStore::ValueStore(IdentityConstraint* const ic,
XMLScanner* const scanner,
MemoryManager* const manager)
: fDoReportError(false)
, fValuesCount(0)
, fIdentityConstraint(ic)
, fValues(manager)
, fValueTuples(0)
, fKeyValueStore(0)
, fScanner(scanner)
, fMemoryManager(manager)
{
fDoReportError = (scanner && (scanner->getValidationScheme() == XMLScanner::Val_Always));
}
ValueStore::~ValueStore()
{
delete fValueTuples;
}
// ---------------------------------------------------------------------------
// ValueStore: Helper methods
// ---------------------------------------------------------------------------
void ValueStore::addValue(FieldActivator* const fieldActivator,
IC_Field* const field,
DatatypeValidator* const dv,
const XMLCh* const value) {
if (!fieldActivator->getMayMatch(field) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_FieldMultipleMatch);
}
// do we even know this field?
int index = fValues.indexOf(field);
if (index == -1) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_UnknownField);
}
return;
}
// store value
if (!fValues.getDatatypeValidatorAt(index) &&
!fValues.getValueAt(index)) {
fValuesCount++;
}
fValues.put(field, dv, value);
if (fValuesCount == (int) fValues.size()) {
// is this value as a group duplicated?
if (contains(&fValues)) {
duplicateValue();
}
// store values
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(fValues));
}
}
void ValueStore::append(const ValueStore* const other) {
if (!other->fValueTuples) {
return;
}
unsigned int tupleSize = other->fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = other->fValueTuples->elementAt(i);
if (!contains(valueMap)) {
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(*valueMap));
}
}
}
void ValueStore::startValueScope() {
fValuesCount = 0;
int count = fIdentityConstraint->getFieldCount();
for (int i = 0; i < count; i++) {
fValues.put(fIdentityConstraint->getFieldAt(i), 0, 0);
}
}
void ValueStore::endValueScope() {
if (fValuesCount == 0) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEY && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_AbsentKeyValue,
fIdentityConstraint->getElementName());
}
return;
}
// do we have enough values?
if ((fValuesCount != fIdentityConstraint->getFieldCount()) && fDoReportError) {
if(fIdentityConstraint->getType()==IdentityConstraint::ICType_KEY)
{
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotEnoughValues,
fIdentityConstraint->getElementName(), fIdentityConstraint->getIdentityConstraintName());
}
}
}
bool ValueStore::contains(const FieldValueMap* const other) {
if (fValueTuples) {
unsigned int otherSize = other->size();
unsigned int tupleSize = fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (otherSize == valueMap->size()) {
bool matchFound = true;
for (unsigned int j=0; j<otherSize; j++) {
if (!isDuplicateOf(valueMap->getDatatypeValidatorAt(j), valueMap->getValueAt(j),
other->getDatatypeValidatorAt(j), other->getValueAt(j))) {
matchFound = false;
break;
}
}
if (matchFound) { // found it
return true;
}
}
}
}
return false;
}
bool ValueStore::isDuplicateOf(DatatypeValidator* const dv1, const XMLCh* const val1,
DatatypeValidator* const dv2, const XMLCh* const val2) {
// if either validator's null, fall back on string comparison
if(!dv1 || !dv2) {
return (XMLString::equals(val1, val2));
}
bool val1IsEmpty = (val1==0 || *val1==0);
bool val2IsEmpty = (val2==0 || *val2==0);
if (val1IsEmpty && val2IsEmpty) {
if (dv1 == dv2) {
return true;
}
return false;
}
if (val1IsEmpty || val2IsEmpty) {
return false;
}
// are the validators equal?
// As always we are obliged to compare by reference...
if (dv1 == dv2) {
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// see if this.fValidator is derived from value.fValidator:
DatatypeValidator* tempVal = dv1;
for(; !tempVal || tempVal == dv2; tempVal = tempVal->getBaseValidator()) ;
if (tempVal) { // was derived!
return ((dv2->compare(val1, val2, fMemoryManager)) == 0);
}
// see if value.fValidator is derived from this.fValidator:
for(tempVal = dv2; !tempVal || tempVal == dv1; tempVal = tempVal->getBaseValidator()) ;
if(tempVal) { // was derived!
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// if we're here it means the types weren't related. Must fall back to strings:
return (XMLString::equals(val1, val2));
}
// ---------------------------------------------------------------------------
// ValueStore: Document handling methods
// ---------------------------------------------------------------------------
void ValueStore::endDocumentFragment(ValueStoreCache* const valueStoreCache) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEYREF) {
// verify references
// get the key store corresponding (if it exists):
fKeyValueStore = valueStoreCache->getGlobalValueStoreFor(((IC_KeyRef*) fIdentityConstraint)->getKey());
if (!fKeyValueStore) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyRefOutOfScope,
fIdentityConstraint->getIdentityConstraintName());
}
return;
}
unsigned int count = (fValueTuples) ? fValueTuples->size() : 0;
for (unsigned int i = 0; i < count; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (!fKeyValueStore->contains(valueMap) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotFound,
fIdentityConstraint->getElementName());
}
}
}
}
// ---------------------------------------------------------------------------
// ValueStore: Error reporting methods
// ---------------------------------------------------------------------------
void ValueStore::reportNilError(IdentityConstraint* const ic) {
if (fDoReportError && ic->getType() == IdentityConstraint::ICType_KEY) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyMatchesNillable,
ic->getElementName());
}
}
void ValueStore::duplicateValue() {
if (fDoReportError) {
switch (fIdentityConstraint->getType()) {
case IdentityConstraint::ICType_UNIQUE:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateUnique,
fIdentityConstraint->getElementName());
break;
}
case IdentityConstraint::ICType_KEY:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateKey,
fIdentityConstraint->getElementName());
break;
}
}
}
}
XERCES_CPP_NAMESPACE_END
/**
* End of file ValueStore.cpp
*/
<commit_msg>Equal lexical values of unrelated types must be treated as different<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/validators/schema/identity/FieldActivator.hpp>
#include <xercesc/validators/schema/identity/ValueStore.hpp>
#include <xercesc/validators/schema/identity/IC_Field.hpp>
#include <xercesc/validators/schema/identity/IC_KeyRef.hpp>
#include <xercesc/validators/schema/identity/ValueStoreCache.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ValueStore: Constructors and Destructor
// ---------------------------------------------------------------------------
ValueStore::ValueStore(IdentityConstraint* const ic,
XMLScanner* const scanner,
MemoryManager* const manager)
: fDoReportError(false)
, fValuesCount(0)
, fIdentityConstraint(ic)
, fValues(manager)
, fValueTuples(0)
, fKeyValueStore(0)
, fScanner(scanner)
, fMemoryManager(manager)
{
fDoReportError = (scanner && (scanner->getValidationScheme() == XMLScanner::Val_Always));
}
ValueStore::~ValueStore()
{
delete fValueTuples;
}
// ---------------------------------------------------------------------------
// ValueStore: Helper methods
// ---------------------------------------------------------------------------
void ValueStore::addValue(FieldActivator* const fieldActivator,
IC_Field* const field,
DatatypeValidator* const dv,
const XMLCh* const value) {
if (!fieldActivator->getMayMatch(field) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_FieldMultipleMatch);
}
// do we even know this field?
int index = fValues.indexOf(field);
if (index == -1) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_UnknownField);
}
return;
}
// store value
if (!fValues.getDatatypeValidatorAt(index) &&
!fValues.getValueAt(index)) {
fValuesCount++;
}
fValues.put(field, dv, value);
if (fValuesCount == (int) fValues.size()) {
// is this value as a group duplicated?
if (contains(&fValues)) {
duplicateValue();
}
// store values
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(fValues));
}
}
void ValueStore::append(const ValueStore* const other) {
if (!other->fValueTuples) {
return;
}
unsigned int tupleSize = other->fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = other->fValueTuples->elementAt(i);
if (!contains(valueMap)) {
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(*valueMap));
}
}
}
void ValueStore::startValueScope() {
fValuesCount = 0;
int count = fIdentityConstraint->getFieldCount();
for (int i = 0; i < count; i++) {
fValues.put(fIdentityConstraint->getFieldAt(i), 0, 0);
}
}
void ValueStore::endValueScope() {
if (fValuesCount == 0) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEY && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_AbsentKeyValue,
fIdentityConstraint->getElementName());
}
return;
}
// do we have enough values?
if ((fValuesCount != fIdentityConstraint->getFieldCount()) && fDoReportError) {
if(fIdentityConstraint->getType()==IdentityConstraint::ICType_KEY)
{
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotEnoughValues,
fIdentityConstraint->getElementName(), fIdentityConstraint->getIdentityConstraintName());
}
}
}
bool ValueStore::contains(const FieldValueMap* const other) {
if (fValueTuples) {
unsigned int otherSize = other->size();
unsigned int tupleSize = fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (otherSize == valueMap->size()) {
bool matchFound = true;
for (unsigned int j=0; j<otherSize; j++) {
if (!isDuplicateOf(valueMap->getDatatypeValidatorAt(j), valueMap->getValueAt(j),
other->getDatatypeValidatorAt(j), other->getValueAt(j))) {
matchFound = false;
break;
}
}
if (matchFound) { // found it
return true;
}
}
}
}
return false;
}
bool ValueStore::isDuplicateOf(DatatypeValidator* const dv1, const XMLCh* const val1,
DatatypeValidator* const dv2, const XMLCh* const val2) {
// if either validator's null, fall back on string comparison
if(!dv1 || !dv2) {
return (XMLString::equals(val1, val2));
}
bool val1IsEmpty = (val1==0 || *val1==0);
bool val2IsEmpty = (val2==0 || *val2==0);
if (val1IsEmpty && val2IsEmpty) {
if (dv1 == dv2) {
return true;
}
return false;
}
if (val1IsEmpty || val2IsEmpty) {
return false;
}
// are the validators equal?
// As always we are obliged to compare by reference...
if (dv1 == dv2) {
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// see if this.fValidator is derived from value.fValidator:
DatatypeValidator* tempVal = dv1;
for(; tempVal != NULL && tempVal != dv2; tempVal = tempVal->getBaseValidator()) ;
if (tempVal) { // was derived!
return ((dv2->compare(val1, val2, fMemoryManager)) == 0);
}
// see if value.fValidator is derived from this.fValidator:
for(tempVal = dv2; tempVal != NULL && tempVal != dv1; tempVal = tempVal->getBaseValidator()) ;
if(tempVal) { // was derived!
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// if we're here it means the types weren't related. They are different:
return false;
}
// ---------------------------------------------------------------------------
// ValueStore: Document handling methods
// ---------------------------------------------------------------------------
void ValueStore::endDocumentFragment(ValueStoreCache* const valueStoreCache) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEYREF) {
// verify references
// get the key store corresponding (if it exists):
fKeyValueStore = valueStoreCache->getGlobalValueStoreFor(((IC_KeyRef*) fIdentityConstraint)->getKey());
if (!fKeyValueStore) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyRefOutOfScope,
fIdentityConstraint->getIdentityConstraintName());
}
return;
}
unsigned int count = (fValueTuples) ? fValueTuples->size() : 0;
for (unsigned int i = 0; i < count; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (!fKeyValueStore->contains(valueMap) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotFound,
fIdentityConstraint->getElementName());
}
}
}
}
// ---------------------------------------------------------------------------
// ValueStore: Error reporting methods
// ---------------------------------------------------------------------------
void ValueStore::reportNilError(IdentityConstraint* const ic) {
if (fDoReportError && ic->getType() == IdentityConstraint::ICType_KEY) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyMatchesNillable,
ic->getElementName());
}
}
void ValueStore::duplicateValue() {
if (fDoReportError) {
switch (fIdentityConstraint->getType()) {
case IdentityConstraint::ICType_UNIQUE:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateUnique,
fIdentityConstraint->getElementName());
break;
}
case IdentityConstraint::ICType_KEY:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateKey,
fIdentityConstraint->getElementName());
break;
}
}
}
}
XERCES_CPP_NAMESPACE_END
/**
* End of file ValueStore.cpp
*/
<|endoftext|> |
<commit_before>#ifndef __SHADER_PRIORITY_QUEUE_HPP_INCLUDED
#define __SHADER_PRIORITY_QUEUE_HPP_INCLUDED
#include "code/ylikuutio/ontology/shader.hpp"
#include "code/ylikuutio/ontology/shader_compare.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <queue> // std::priority_queue, std::queue
#include <vector> // std::vector
namespace yli
{
namespace ontology
{
// Inspired by https://stackoverflow.com/questions/19467485/how-to-remove-element-not-at-top-from-priority-queue/36711682#36711682
//
// Heap-based priority queue.
// Random access read: O(1)
// Insert: O(log(n))
// Delete: O(log(n))
class ShaderPriorityQueue: public std::priority_queue<yli::ontology::Shader*, std::vector<yli::ontology::Shader*>>
{
public:
bool remove(const std::size_t childID);
};
}
}
#endif
<commit_msg>Removed unncessary `#include` line.<commit_after>#ifndef __SHADER_PRIORITY_QUEUE_HPP_INCLUDED
#define __SHADER_PRIORITY_QUEUE_HPP_INCLUDED
#include "code/ylikuutio/ontology/shader.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <queue> // std::priority_queue, std::queue
#include <vector> // std::vector
namespace yli
{
namespace ontology
{
// Inspired by https://stackoverflow.com/questions/19467485/how-to-remove-element-not-at-top-from-priority-queue/36711682#36711682
//
// Heap-based priority queue.
// Random access read: O(1)
// Insert: O(log(n))
// Delete: O(log(n))
class ShaderPriorityQueue: public std::priority_queue<yli::ontology::Shader*, std::vector<yli::ontology::Shader*>>
{
public:
bool remove(const std::size_t childID);
};
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: bootstrap.hxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:18: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): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_BOOTSTRAP_HXX_
#define CONFIGMGR_BOOTSTRAP_HXX_
#ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_
#include "bootstrapcontext.hxx"
#endif
// ---------------------------------------------------------------------------------------
#define CONFIGMGR_INIFILE SAL_CONFIGFILE("configmgr")
#define BOOTSTRAP_ITEM_INIFILE "CFG_INIFILE"
// ---------------------------------------------------------------------------------------
// standard settings
#define SETTING_UNOSERVICE "BackendService"
#define SETTING_UNOWRAPPER "BackendWrapper"
#define SETTING_OFFLINE "Offline"
#define SETTING_LOCALE_NEW "Locale"
#define SETTING_ASYNC_NEW "EnableAsync"
#define SETTING_INIFILE "Inifile"
// Prefixes
#define CONTEXT_MODULE_PREFIX_ "/modules/com.sun.star.configuration/"
#define CONTEXT_SECTION_BOOTSTRAP_ "bootstrap/"
#define CONTEXT_ITEM_PREFIX_ CONTEXT_MODULE_PREFIX_ CONTEXT_SECTION_BOOTSTRAP_
#define BOOTSTRAP_ITEM_PREFIX_ "CFG_"
// special internal context values
#define CONTEXT_SECTION_INTERNAL_ "factory/"
#define CONTEXT_INTERNAL_PREFIX_ CONTEXT_MODULE_PREFIX_ CONTEXT_SECTION_INTERNAL_
#define CONTEXT_ITEM_ADMINFLAG CONTEXT_INTERNAL_PREFIX_"isAdminConfiguration"
#define CONTEXT_ITEM_BOOTSTRAP_ERROR CONTEXT_INTERNAL_PREFIX_"theBootstrapError"
#define CONTEXT_ITEM_IS_WRAPPER_CONTEXT CONTEXT_INTERNAL_PREFIX_"isWrapperContext"
#define CONTEXT_ITEM_IS_BOOTSTRAP_CONTEXT CONTEXT_INTERNAL_PREFIX_"isBootstrapContext"
// ---------------------------------------------------------------------------------------
#define A_DefaultProviderSingletonName "com.sun.star.configuration.theDefaultProvider"
#define K_DefaultBackendSingletonName "com.sun.star.configuration.backend.theDefaultBackend"
#define K_DefaultSingleBackendSingletonName "com.sun.star.configuration.backend.theDefaultSingleBackend"
#define A_BootstrapContextSingletonName "com.sun.star.configuration.bootstrap.theBootstrapContext"
// -------------------------------------------------------------------------
#define A_DefaultProviderServiceAndImplName "com.sun.star.configuration.DefaultProvider"
#define K_DefaultBackendServiceAndImplName "com.sun.star.configuration.backend.DefaultBackend"
#define K_DefaultSingleBackendServiceAndImplName "com.sun.star.configuration.backend.DefaultSingleBackend"
// ---------------------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace beans = ::com::sun::star::beans;
using ::rtl::OUString;
// -----------------------------------------------------------------------------------
/** Customized ComponentContext for configuration bootstrap data and runtime arguments
*/
class BootstrapContext : public ComponentContext
{
// creation and destruction
private:
friend uno::Reference<uno::XInterface> SAL_CALL
instantiateBootstrapContext( Context const& xContext );
// constructor
BootstrapContext(Context const & _xContext);
// two-phase construct
void initialize();
public:
typedef uno::Sequence < beans::NamedValue > Overrides;
/** Constructs a Context based on the given arguments and context.
@param _xContext
The base context of this component context.
@param _aArguments
The arguments used to create this component context.
*/
static Context createWrapper(Context const & _xContext, Overrides const & _aOverrides);
/** Checks, if the given context is a wrapper.
@param _xContext
The context that is checked.
*/
static sal_Bool isWrapper(Context const & _xContext);
/** Retrieves the BootstrapContext for the given non-bootstrap context.
@param _xContext
The context from which the bootstrap context should be retrieved.
*/
static Context get(Context const & _xContext);
/// Destroys this BootstrapContext
~BootstrapContext();
// gets the INI that should be used for bootstrap data by default
static OUString getDefaultConfigurationBootstrapURL();
// interface implementations
public:
// XComponentContext
/** Retrieves a value from this context.
@param Name
The name of the value to retrieve.
A prefix of "com.sun.star.configuration.bootstrap." is stripped/ignored
@returns
The requested value, or <VOID/> if the value is not found.
*/
virtual uno::Any SAL_CALL
getValueByName( const OUString& Name )
throw (uno::RuntimeException);
public: // used by ArgumentHelper
static OUString makeContextName (OUString const & _aShortName);
private:
static OUString makeBootstrapName(OUString const & _aLongName);
uno::Any makeBootstrapException();
};
// -----------------------------------------------------------------------------
class ContextReader
{
public:
typedef uno::Reference< uno::XComponentContext > Context;
explicit
ContextReader(Context const & context);
// the underlying contexts
sal_Bool hasBootstrapContext() const { return m_fullcontext.is(); }
Context const & getBootstrapContext() const { return m_fullcontext; }
Context const & getBaseContext() const { return m_basecontext; }
Context const & getBestContext() const { return m_fullcontext.is() ? m_fullcontext : m_basecontext; }
uno::Reference< lang::XMultiComponentFactory > getServiceManager() const;
/** Checks, if the given context is a BootstrapContext.
@param _xContext
The context that is checked.
*/
static bool isBootstrapContext(Context const & context);
/** Checks, if the given context has the given 'admin' flag setting..
@param _xContext
The context that is checked.
*/
static bool testAdminService(Context const & context, bool bAdmin);
// general settings
sal_Bool isUnoBackend() const;
sal_Bool hasUnoBackendService() const;
sal_Bool hasUnoBackendWrapper() const;
sal_Bool hasLocale() const;
sal_Bool hasAsyncSetting() const;
sal_Bool hasOfflineSetting() const;
OUString getUnoBackendService() const;
OUString getUnoBackendWrapper() const;
OUString getLocale() const;
sal_Bool getAsyncSetting() const;
sal_Bool getOfflineSetting() const;
// internal settings - should only ever be in configmgr::BootstrapContext instances
// get a special setting
sal_Bool isAdminService() const;
// access to error diagnostics
sal_Bool isBootstrapValid() const;
uno::Any getBootstrapError() const;
private:
sal_Bool hasSetting(OUString const & _aSetting) const;
sal_Bool getBoolSetting(OUString const & _aSetting, sal_Bool bValue) const;
OUString getStringSetting(OUString const & _aSetting, OUString aValue) const;
uno::Any getSetting(OUString const & _aSetting) const;
private:
Context m_basecontext;
Context m_fullcontext;
};
//------------------------------------------------------------------------
class ArgumentHelper
{
bool m_bHasBackendArguments;
public:
typedef uno::Reference< uno::XComponentContext > Context;
explicit
ArgumentHelper(Context const & context)
: m_context(context)
, m_bHasBackendArguments(false)
{}
bool hasBackendArguments() const { return m_bHasBackendArguments; }
bool checkBackendArgument(beans::NamedValue const & aAdjustedValue);
bool filterAndAdjustArgument(beans::NamedValue & rValue);
static
bool extractArgument(beans::NamedValue & rValue, uno::Any const & aArgument);
static beans::NamedValue makeAdminServiceOverride(sal_Bool bAdmin);
private:
Context m_context; // context used to strip identical arguments
};
// -----------------------------------------------------------------------------------
}
#endif // CONFIGMGR_BOOTSTRAP_HXX_
<commit_msg>INTEGRATION: CWS configapi01 (1.22.8); FILE MERGED 2003/04/10 15:47:20 jb 1.22.8.1: #1077715# Move configuration backend API out of drafts; adjust to API changes<commit_after>/*************************************************************************
*
* $RCSfile: bootstrap.hxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: rt $ $Date: 2003-04-17 13:28:01 $
*
* 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 CONFIGMGR_BOOTSTRAP_HXX_
#define CONFIGMGR_BOOTSTRAP_HXX_
#ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_
#include "bootstrapcontext.hxx"
#endif
// ---------------------------------------------------------------------------------------
#define CONFIGMGR_INIFILE SAL_CONFIGFILE("configmgr")
#define BOOTSTRAP_ITEM_INIFILE "CFG_INIFILE"
// ---------------------------------------------------------------------------------------
// standard settings
#define SETTING_UNOSERVICE "BackendService"
#define SETTING_UNOWRAPPER "BackendWrapper"
#define SETTING_OFFLINE "Offline"
#define SETTING_LOCALE_NEW "Locale"
#define SETTING_ASYNC_NEW "EnableAsync"
#define SETTING_INIFILE "Inifile"
// Prefixes
#define CONTEXT_MODULE_PREFIX_ "/modules/com.sun.star.configuration/"
#define CONTEXT_SECTION_BOOTSTRAP_ "bootstrap/"
#define CONTEXT_ITEM_PREFIX_ CONTEXT_MODULE_PREFIX_ CONTEXT_SECTION_BOOTSTRAP_
#define BOOTSTRAP_ITEM_PREFIX_ "CFG_"
// special internal context values
#define CONTEXT_SECTION_INTERNAL_ "factory/"
#define CONTEXT_INTERNAL_PREFIX_ CONTEXT_MODULE_PREFIX_ CONTEXT_SECTION_INTERNAL_
#define CONTEXT_ITEM_ADMINFLAG CONTEXT_INTERNAL_PREFIX_"isAdminConfiguration"
#define CONTEXT_ITEM_BOOTSTRAP_ERROR CONTEXT_INTERNAL_PREFIX_"theBootstrapError"
#define CONTEXT_ITEM_IS_WRAPPER_CONTEXT CONTEXT_INTERNAL_PREFIX_"isWrapperContext"
#define CONTEXT_ITEM_IS_BOOTSTRAP_CONTEXT CONTEXT_INTERNAL_PREFIX_"isBootstrapContext"
// ---------------------------------------------------------------------------------------
#define A_DefaultProviderSingletonName "com.sun.star.configuration.theDefaultProvider"
#define K_DefaultBackendSingletonName "com.sun.star.configuration.backend.theDefaultBackend"
#define A_BootstrapContextSingletonName "com.sun.star.configuration.bootstrap.theBootstrapContext"
// -------------------------------------------------------------------------
#define A_DefaultProviderServiceAndImplName "com.sun.star.configuration.DefaultProvider"
#define K_DefaultBackendServiceAndImplName "com.sun.star.configuration.backend.DefaultBackend"
// ---------------------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace beans = ::com::sun::star::beans;
using ::rtl::OUString;
// -----------------------------------------------------------------------------------
/** Customized ComponentContext for configuration bootstrap data and runtime arguments
*/
class BootstrapContext : public ComponentContext
{
// creation and destruction
private:
friend uno::Reference<uno::XInterface> SAL_CALL
instantiateBootstrapContext( Context const& xContext );
// constructor
BootstrapContext(Context const & _xContext);
// two-phase construct
void initialize();
public:
typedef uno::Sequence < beans::NamedValue > Overrides;
/** Constructs a Context based on the given arguments and context.
@param _xContext
The base context of this component context.
@param _aArguments
The arguments used to create this component context.
*/
static Context createWrapper(Context const & _xContext, Overrides const & _aOverrides);
/** Checks, if the given context is a wrapper.
@param _xContext
The context that is checked.
*/
static sal_Bool isWrapper(Context const & _xContext);
/** Retrieves the BootstrapContext for the given non-bootstrap context.
@param _xContext
The context from which the bootstrap context should be retrieved.
*/
static Context get(Context const & _xContext);
/// Destroys this BootstrapContext
~BootstrapContext();
// gets the INI that should be used for bootstrap data by default
static OUString getDefaultConfigurationBootstrapURL();
// interface implementations
public:
// XComponentContext
/** Retrieves a value from this context.
@param Name
The name of the value to retrieve.
A prefix of "com.sun.star.configuration.bootstrap." is stripped/ignored
@returns
The requested value, or <VOID/> if the value is not found.
*/
virtual uno::Any SAL_CALL
getValueByName( const OUString& Name )
throw (uno::RuntimeException);
public: // used by ArgumentHelper
static OUString makeContextName (OUString const & _aShortName);
private:
static OUString makeBootstrapName(OUString const & _aLongName);
uno::Any makeBootstrapException();
};
// -----------------------------------------------------------------------------
class ContextReader
{
public:
typedef uno::Reference< uno::XComponentContext > Context;
explicit
ContextReader(Context const & context);
// the underlying contexts
sal_Bool hasBootstrapContext() const { return m_fullcontext.is(); }
Context const & getBootstrapContext() const { return m_fullcontext; }
Context const & getBaseContext() const { return m_basecontext; }
Context const & getBestContext() const { return m_fullcontext.is() ? m_fullcontext : m_basecontext; }
uno::Reference< lang::XMultiComponentFactory > getServiceManager() const;
/** Checks, if the given context is a BootstrapContext.
@param _xContext
The context that is checked.
*/
static bool isBootstrapContext(Context const & context);
/** Checks, if the given context has the given 'admin' flag setting..
@param _xContext
The context that is checked.
*/
static bool testAdminService(Context const & context, bool bAdmin);
// general settings
sal_Bool isUnoBackend() const;
sal_Bool hasUnoBackendService() const;
sal_Bool hasUnoBackendWrapper() const;
sal_Bool hasLocale() const;
sal_Bool hasAsyncSetting() const;
sal_Bool hasOfflineSetting() const;
OUString getUnoBackendService() const;
OUString getUnoBackendWrapper() const;
OUString getLocale() const;
sal_Bool getAsyncSetting() const;
sal_Bool getOfflineSetting() const;
// internal settings - should only ever be in configmgr::BootstrapContext instances
// get a special setting
sal_Bool isAdminService() const;
// access to error diagnostics
sal_Bool isBootstrapValid() const;
uno::Any getBootstrapError() const;
private:
sal_Bool hasSetting(OUString const & _aSetting) const;
sal_Bool getBoolSetting(OUString const & _aSetting, sal_Bool bValue) const;
OUString getStringSetting(OUString const & _aSetting, OUString aValue) const;
uno::Any getSetting(OUString const & _aSetting) const;
private:
Context m_basecontext;
Context m_fullcontext;
};
//------------------------------------------------------------------------
class ArgumentHelper
{
bool m_bHasBackendArguments;
public:
typedef uno::Reference< uno::XComponentContext > Context;
explicit
ArgumentHelper(Context const & context)
: m_context(context)
, m_bHasBackendArguments(false)
{}
bool hasBackendArguments() const { return m_bHasBackendArguments; }
bool checkBackendArgument(beans::NamedValue const & aAdjustedValue);
bool filterAndAdjustArgument(beans::NamedValue & rValue);
static
bool extractArgument(beans::NamedValue & rValue, uno::Any const & aArgument);
static beans::NamedValue makeAdminServiceOverride(sal_Bool bAdmin);
private:
Context m_context; // context used to strip identical arguments
};
// -----------------------------------------------------------------------------------
}
#endif // CONFIGMGR_BOOTSTRAP_HXX_
<|endoftext|> |
<commit_before>/***************************************************************************//**
* FILE : block_array.hpp
*
* Implements an array container allocated in blocks.
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#if !defined (BLOCK_ARRAY_HPP)
#define BLOCK_ARRAY_HPP
#include "general/debug.h"
template <typename IndexType, typename EntryType, int blockLength = 256 >
class block_array
{
private:
// Note: any new attributes must be handled by swap()
EntryType **blocks;
IndexType blockCount;
EntryType* getOrCreateBlock(IndexType blockIndex)
{
if (blockIndex >= blockCount)
{
IndexType newBlockCount = blockIndex + 1;
if (newBlockCount < blockCount*2)
{
newBlockCount = blockCount*2;
}
EntryType **newBlocks;
if (!REALLOCATE(newBlocks, blocks, EntryType *, newBlockCount))
return NULL;
for (IndexType i = blockCount; i < newBlockCount; i++)
{
newBlocks[i] = NULL;
}
blocks = newBlocks;
blockCount = newBlockCount;
}
EntryType *block = blocks[blockIndex];
if (!block)
{
if (ALLOCATE(block, EntryType, blockLength))
{
for (IndexType i = 0; i < blockLength; i++)
{
block[i] = 0; // only works for numeric or pointer types
}
blocks[blockIndex] = block;
}
}
return block;
}
public:
block_array() :
blocks(NULL),
blockCount(0)
{
}
~block_array()
{
clear();
}
void clear()
{
for (IndexType i = 0; i < blockCount; i++)
{
if (blocks[i])
{
DEALLOCATE(blocks[i]);
}
}
if (blocks)
{
DEALLOCATE(blocks);
}
blockCount = 0;
}
/** Swaps all data with other block_array. Cannot fail. */
void swap(block_array& other)
{
EntryType **temp_blocks = blocks;
IndexType temp_blockCount = blockCount;
blocks = other.blocks;
blockCount = other.blockCount;
other.blocks = temp_blocks;
other.blockCount = temp_blockCount;
}
/**
* Get a value from the block_array.
* @param index The index of the value to retrieve, starting at 0.
* @param value On success, filled with value held at index.
* @return 1 if value returned, 0 if no value at index.
*/
int getValue(IndexType index, EntryType& value) const
{
IndexType blockIndex = index / blockLength;
if (blockIndex < blockCount)
{
EntryType *block = blocks[blockIndex];
if (block)
{
IndexType entryIndex = index % blockLength;
value = block[entryIndex];
return 1;
}
}
return 0;
}
/**
* Set a value in the block_array.
* @param index The index of the value to set, starting at 0.
* @param value Value to set at index.
* @return 1 if value set, 0 if failed.
*/
int setValue(IndexType index, EntryType value)
{
IndexType blockIndex = index / blockLength;
EntryType* block = getOrCreateBlock(blockIndex);
if (!block)
return 0;
IndexType entryIndex = index % blockLength;
block[entryIndex] = value;
return 1;
}
bool setValues(IndexType minIndex, IndexType maxIndex, EntryType value)
{
// GRC: can be made faster
for (IndexType index = minIndex; index <= maxIndex; index++)
{
if (!setValue(index, value))
return false;
}
return true;
}
};
/** stores boolean values as individual bits, with no value equivalent to false */
template <typename IndexType, int intBlockLength = 32>
class bool_array : private block_array<IndexType, unsigned int, intBlockLength>
{
public:
void clear()
{
block_array<IndexType, unsigned int, intBlockLength>::clear();
}
void swap(bool_array& other)
{
block_array<IndexType, unsigned int, intBlockLength>::swap(other);
}
/** @param oldValue Returns old value so client can determine if status changed */
int setBool(IndexType index, bool value, bool& oldValue)
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
int hasValue = getValue(intIndex, intValue);
if (hasValue || value)
{
unsigned int mask = (1 << (index & 0x1F));
oldValue = (0 != (intValue & mask));
if (oldValue != value)
{
return setValue(intIndex, intValue ^ mask);
}
}
else
{
oldValue = false;
}
return 1;
}
bool getBool(IndexType index) const
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
if (getValue(intIndex, intValue))
{
unsigned int mask = (1 << (index & 0x1F));
return (0 != (intValue & mask));
}
return false;
}
/**
* @param lastTrueIndex Updated to equal or next lower index with true value.
* @return true if found, false if none.
*/
bool updateLastTrueIndex(IndexType& lastTrueIndex)
{
// GRC this can be made much more efficient
while (!getBool(lastTrueIndex))
{
--lastTrueIndex;
if (lastTrueIndex < 0)
return false;
}
return true;
}
/** @return true if values for all indexes in range are true; false otherwise */
bool isRangeTrue(IndexType minIndex, IndexType maxIndex)
{
if (minIndex > maxIndex)
return false;
// GRC this can be made much more efficient
IndexType index = minIndex;
while (getBool(index))
{
if (index == maxIndex)
return true;
index++;
}
return false;
}
/** Sets all entries from index 0..indexCount-1 to true.
* @return true if completely successful, false otherwise */
bool setAllTrue(IndexType indexCount)
{
IndexType intIndexCount = indexCount >> 5;
// bulk set the flags in lots of 32 bits
if (!setValues(0, intIndexCount-1, 0xFFFFFFFF))
return false;
// individually set remaining bits
for (IndexType index = intIndexCount*32; index < indexCount; index++)
{
bool oldValue;
if (!setBool(index, true, oldValue))
return false;
}
return true;
}
};
#endif /* !defined (BLOCK_ARRAY_HPP) */
<commit_msg>Compilation fixes for gcc 4.7.1.<commit_after>/***************************************************************************//**
* FILE : block_array.hpp
*
* Implements an array container allocated in blocks.
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#if !defined (BLOCK_ARRAY_HPP)
#define BLOCK_ARRAY_HPP
#include "general/debug.h"
template <typename IndexType, typename EntryType, int blockLength = 256 >
class block_array
{
private:
// Note: any new attributes must be handled by swap()
EntryType **blocks;
IndexType blockCount;
EntryType* getOrCreateBlock(IndexType blockIndex)
{
if (blockIndex >= blockCount)
{
IndexType newBlockCount = blockIndex + 1;
if (newBlockCount < blockCount*2)
{
newBlockCount = blockCount*2;
}
EntryType **newBlocks;
if (!REALLOCATE(newBlocks, blocks, EntryType *, newBlockCount))
return NULL;
for (IndexType i = blockCount; i < newBlockCount; i++)
{
newBlocks[i] = NULL;
}
blocks = newBlocks;
blockCount = newBlockCount;
}
EntryType *block = blocks[blockIndex];
if (!block)
{
if (ALLOCATE(block, EntryType, blockLength))
{
for (IndexType i = 0; i < blockLength; i++)
{
block[i] = 0; // only works for numeric or pointer types
}
blocks[blockIndex] = block;
}
}
return block;
}
public:
block_array() :
blocks(NULL),
blockCount(0)
{
}
~block_array()
{
clear();
}
void clear()
{
for (IndexType i = 0; i < blockCount; i++)
{
if (blocks[i])
{
DEALLOCATE(blocks[i]);
}
}
if (blocks)
{
DEALLOCATE(blocks);
}
blockCount = 0;
}
/** Swaps all data with other block_array. Cannot fail. */
void swap(block_array& other)
{
EntryType **temp_blocks = blocks;
IndexType temp_blockCount = blockCount;
blocks = other.blocks;
blockCount = other.blockCount;
other.blocks = temp_blocks;
other.blockCount = temp_blockCount;
}
/**
* Get a value from the block_array.
* @param index The index of the value to retrieve, starting at 0.
* @param value On success, filled with value held at index.
* @return 1 if value returned, 0 if no value at index.
*/
int getValue(IndexType index, EntryType& value) const
{
IndexType blockIndex = index / blockLength;
if (blockIndex < blockCount)
{
EntryType *block = blocks[blockIndex];
if (block)
{
IndexType entryIndex = index % blockLength;
value = block[entryIndex];
return 1;
}
}
return 0;
}
/**
* Set a value in the block_array.
* @param index The index of the value to set, starting at 0.
* @param value Value to set at index.
* @return 1 if value set, 0 if failed.
*/
int setValue(IndexType index, EntryType value)
{
IndexType blockIndex = index / blockLength;
EntryType* block = getOrCreateBlock(blockIndex);
if (!block)
return 0;
IndexType entryIndex = index % blockLength;
block[entryIndex] = value;
return 1;
}
bool setValues(IndexType minIndex, IndexType maxIndex, EntryType value)
{
// GRC: can be made faster
for (IndexType index = minIndex; index <= maxIndex; index++)
{
if (!setValue(index, value))
return false;
}
return true;
}
};
/** stores boolean values as individual bits, with no value equivalent to false */
template <typename IndexType, int intBlockLength = 32>
class bool_array : private block_array<IndexType, unsigned int, intBlockLength>
{
public:
void clear()
{
block_array<IndexType, unsigned int, intBlockLength>::clear();
}
void swap(bool_array& other)
{
block_array<IndexType, unsigned int, intBlockLength>::swap(other);
}
using block_array<IndexType, unsigned int, intBlockLength>::getValue;
using block_array<IndexType, unsigned int, intBlockLength>::setValue;
using block_array<IndexType, unsigned int, intBlockLength>::setValues;
/** @param oldValue Returns old value so client can determine if status changed */
int setBool(IndexType index, bool value, bool& oldValue)
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
int hasValue = getValue(intIndex, intValue);
if (hasValue || value)
{
unsigned int mask = (1 << (index & 0x1F));
oldValue = (0 != (intValue & mask));
if (oldValue != value)
{
return setValue(intIndex, intValue ^ mask);
}
}
else
{
oldValue = false;
}
return 1;
}
bool getBool(IndexType index) const
{
IndexType intIndex = index >> 5;
unsigned int intValue = 0;
if (getValue(intIndex, intValue))
{
unsigned int mask = (1 << (index & 0x1F));
return (0 != (intValue & mask));
}
return false;
}
/**
* @param lastTrueIndex Updated to equal or next lower index with true value.
* @return true if found, false if none.
*/
bool updateLastTrueIndex(IndexType& lastTrueIndex)
{
// GRC this can be made much more efficient
while (!getBool(lastTrueIndex))
{
--lastTrueIndex;
if (lastTrueIndex < 0)
return false;
}
return true;
}
/** @return true if values for all indexes in range are true; false otherwise */
bool isRangeTrue(IndexType minIndex, IndexType maxIndex)
{
if (minIndex > maxIndex)
return false;
// GRC this can be made much more efficient
IndexType index = minIndex;
while (getBool(index))
{
if (index == maxIndex)
return true;
index++;
}
return false;
}
/** Sets all entries from index 0..indexCount-1 to true.
* @return true if completely successful, false otherwise */
bool setAllTrue(IndexType indexCount)
{
IndexType intIndexCount = indexCount >> 5;
// bulk set the flags in lots of 32 bits
if (!setValues(0, intIndexCount-1, 0xFFFFFFFF))
return false;
// individually set remaining bits
for (IndexType index = intIndexCount*32; index < indexCount; index++)
{
bool oldValue;
if (!setBool(index, true, oldValue))
return false;
}
return true;
}
};
#endif /* !defined (BLOCK_ARRAY_HPP) */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: valuenode.hxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 13:23:29 $
*
* 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 _CONFIGMGR_TREE_VALUENODE_HXX
#define _CONFIGMGR_TREE_VALUENODE_HXX
#ifndef CONFIGMGR_CONFIGURATION_ATTRIBUTES_HXX_
#include "attributes.hxx"
#endif
#ifndef CFGMGR_ANYPAIR_HXX
#include "anypair.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef CONFIGMGR_RTTIMACROS_HXX
#include "rttimacros.hxx"
#endif
#include <string.h>
#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif
namespace configmgr
{
namespace css = com::sun::star;
namespace uno = css::uno;
class INode;
class ISubtree;
class ValueNode;
using rtl::OUString;
// helper (tag) class
namespace treeop { struct NoChildCopy {}; struct DeepChildCopy {}; enum { ALL_LEVELS = -1 }; }
//==========================================================================
//= Visitors
//==========================================================================
struct NodeAction
{
virtual void handle(ValueNode const&) = 0;
virtual void handle(ISubtree const&) = 0;
void applyToNode(INode const&);
void applyToChildren(ISubtree const&);
protected:
virtual ~NodeAction() {}
};
struct NodeModification
{
virtual void handle(ValueNode&) = 0;
virtual void handle(ISubtree&) = 0;
void applyToNode(INode&);
void applyToChildren(ISubtree&);
protected:
virtual ~NodeModification() {}
};
class INode
{
OUString m_aName;
node::Attributes m_aAttributes;
protected:
INode(){}
void markAsDefault(bool _bDefault = true)
{
m_aAttributes.markAsDefault(_bDefault);
}
public:
explicit
INode(node::Attributes);
INode(OUString const& aName, node::Attributes);
virtual ~INode();
virtual std::auto_ptr<INode> clone() const = 0;
public:
const OUString& getName() const { return m_aName; }
node::Attributes getAttributes() const { return m_aAttributes; }
bool isDefault() const { return m_aAttributes.isDefault(); }
bool isLocalized() const { return m_aAttributes.isLocalized(); }
void modifyState(node::State _eNewState);
void modifyAccess(node::Access _aAccessLevel);
void markMandatory();
void markRemovable();
void promoteAccessToDefault();
void forceReadonlyToFinalized();
// to be used with caution. If the node is referenced from somewhere else under it's old name,
// you may have problems with this inconsistence
void setName(const OUString& _rNewName) { m_aName = _rNewName; }
virtual ValueNode* asValueNode();
virtual ValueNode const* asValueNode() const;
virtual ISubtree* asISubtree();
virtual ISubtree const* asISubtree() const;
// double dispatch support
virtual void dispatch(NodeAction&) const = 0;
virtual void dispatch(NodeModification&) = 0;
// "rtti"
RTTI_BASE(INode);
};
// -----------------------------------------------------------------------------
//==========================================================================
//= ISubtree
//==========================================================================
class ISubtree : public INode
{
sal_Int16 m_nLevel; /// determines if everything is read
sal_Int16 m_nDefaultLevels; /// determines if defaults are read
OUString m_sId;
OUString m_sTemplateName; /// path of the template for child instantiation
OUString m_sTemplateModule; /// module of the template for child instantiation
virtual INode* doGetChild(OUString const& name) const = 0;
protected:
ISubtree():m_nLevel(0){}
ISubtree(ISubtree const& other)
:INode(other)
,m_nLevel(other.m_nLevel)
,m_sId() // do not copy ID while cloning !
,m_nDefaultLevels(other.m_nDefaultLevels)
,m_sTemplateName(other.m_sTemplateName)
,m_sTemplateModule(other.m_sTemplateModule)
{}
public:
// Ctor for group trees
ISubtree(const rtl::OUString& aName, const node::Attributes& _rAttrs)
:INode(aName, _rAttrs)
,m_nLevel(0)
,m_nDefaultLevels(0)
{}
// Ctor for set trees
ISubtree(const rtl::OUString& aName,
const rtl::OUString& _rTemplateName,
const rtl::OUString& _rTemplateModule,
const node::Attributes& _rAttrs)
:INode(aName, _rAttrs)
,m_nLevel(0)
,m_nDefaultLevels(0)
,m_sTemplateName(_rTemplateName)
,m_sTemplateModule(_rTemplateModule){}
INode* getChild(OUString const& name) { return doGetChild(name); }
INode const* getChild(OUString const& name) const { return doGetChild(name); }
ISubtree* asISubtree();
ISubtree const* asISubtree() const;
using INode::markAsDefault;
sal_Int16 getLevel() const { return m_nLevel; }
sal_Int16 getDefaultsLevel() const { return m_nDefaultLevels; }
void setLevels(sal_Int16 _nLevel,sal_Int16 _nDefaultsLevel);
bool isSetNode() const { return m_sTemplateName.getLength() != 0; }
void makeSetNode(OUString const& _sTemplateName, OUString const& _sTemplateModule)
{ m_sTemplateName = _sTemplateName; m_sTemplateModule = _sTemplateModule; }
OUString const& getElementTemplateName() const { return m_sTemplateName; }
OUString const& getElementTemplateModule() const { return m_sTemplateModule; }
virtual INode* addChild(std::auto_ptr<INode> node) =0; // takes ownership
virtual ::std::auto_ptr<INode> removeChild(rtl::OUString const& name) =0; // releases ownership
// Iteration support, stop if (action returns true)
virtual void forEachChild(NodeAction& anAction) const = 0;
virtual void forEachChild(NodeModification& anAction) = 0;
// double dispatch support
virtual void dispatch(NodeAction& anAction) const { anAction.handle(*this); }
virtual void dispatch(NodeModification& anAction) { anAction.handle(*this); }
// "rtti"
RTTI(ISubtree, INode);
};
//==========================================================================
//= ValueNode
//==========================================================================
class ValueNode : public INode
{
AnyPair m_aValuePair;
// uno::Type m_aType;
// uno::Any m_aValue;
// uno::Any m_aDefaultValue;
public:
//ValueNode(){}
//explicit ValueNode(node::Attributes _aAttrs):INode(_aAttrs){}
/*
ValueNode(OUString const& aName, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair()
{}
*/
ValueNode(OUString const& aName,uno::Type const& aType, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair(aType)
{
}
ValueNode(OUString const& aName,uno::Any const& anAny, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair(anAny, selectMember(_aAttrs.isDefault()))
{
}
ValueNode(OUString const& aName,uno::Any const& anAny,uno::Any const& aDefault, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair(anAny, aDefault)
{
}
bool isEmpty() const {return m_aValuePair.isEmpty();}
bool isValid() const {return !m_aValuePair.isEmpty();}
bool isNull() const {return m_aValuePair.isNull();}
bool hasUsableDefault() const {return getAttributes().isNullable() || m_aValuePair.hasSecond();}
uno::Type getValueType() const {return m_aValuePair.getValueType();}
uno::Any getValue() const {return m_aValuePair.getValue( selectMember(this->isDefault()) );}
uno::Any getUserValue() const {return m_aValuePair.getFirst();}
uno::Any getDefault() const {return m_aValuePair.getSecond();}
bool setValueType(uno::Type const& _aType);
bool setValue(uno::Any const& _aValue);
void setDefault();
bool changeDefault(uno::Any const& _aValue);
void promoteToDefault();
virtual std::auto_ptr<INode> clone() const;
ValueNode* asValueNode();
ValueNode const* asValueNode() const;
// double dispatch support
virtual void dispatch(NodeAction& anAction) const { anAction.handle(*this); }
virtual void dispatch(NodeModification& anAction) { anAction.handle(*this); }
// "rtti"
RTTI(ValueNode, INode);
private:
static AnyPair::SelectMember selectValue() { return AnyPair::SELECT_FIRST; }
static AnyPair::SelectMember selectDeflt() { return AnyPair::SELECT_SECOND; }
static AnyPair::SelectMember selectMember(bool bDeflt)
{ return bDeflt ? AnyPair::SELECT_SECOND : AnyPair::SELECT_FIRST; }
};
//==========================================================================
extern bool isLocalizedValueSet(ISubtree const& _aSubtree);
//==========================================================================
//= inlines
//==========================================================================
inline void NodeAction::applyToNode(INode const& aNode)
{ aNode.dispatch(*this); }
inline void NodeAction::applyToChildren(ISubtree const& aSubtree)
{ aSubtree.forEachChild(*this); }
inline void NodeModification::applyToNode(INode& aNode)
{ aNode.dispatch(*this); }
inline void NodeModification::applyToChildren(ISubtree& aSubtree)
{ aSubtree.forEachChild(*this); }
} // namespace configmgr
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.27.86); FILE MERGED 2005/09/05 17:04:43 rt 1.27.86.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: valuenode.hxx,v $
*
* $Revision: 1.28 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:02:07 $
*
* 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 _CONFIGMGR_TREE_VALUENODE_HXX
#define _CONFIGMGR_TREE_VALUENODE_HXX
#ifndef CONFIGMGR_CONFIGURATION_ATTRIBUTES_HXX_
#include "attributes.hxx"
#endif
#ifndef CFGMGR_ANYPAIR_HXX
#include "anypair.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef CONFIGMGR_RTTIMACROS_HXX
#include "rttimacros.hxx"
#endif
#include <string.h>
#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif
namespace configmgr
{
namespace css = com::sun::star;
namespace uno = css::uno;
class INode;
class ISubtree;
class ValueNode;
using rtl::OUString;
// helper (tag) class
namespace treeop { struct NoChildCopy {}; struct DeepChildCopy {}; enum { ALL_LEVELS = -1 }; }
//==========================================================================
//= Visitors
//==========================================================================
struct NodeAction
{
virtual void handle(ValueNode const&) = 0;
virtual void handle(ISubtree const&) = 0;
void applyToNode(INode const&);
void applyToChildren(ISubtree const&);
protected:
virtual ~NodeAction() {}
};
struct NodeModification
{
virtual void handle(ValueNode&) = 0;
virtual void handle(ISubtree&) = 0;
void applyToNode(INode&);
void applyToChildren(ISubtree&);
protected:
virtual ~NodeModification() {}
};
class INode
{
OUString m_aName;
node::Attributes m_aAttributes;
protected:
INode(){}
void markAsDefault(bool _bDefault = true)
{
m_aAttributes.markAsDefault(_bDefault);
}
public:
explicit
INode(node::Attributes);
INode(OUString const& aName, node::Attributes);
virtual ~INode();
virtual std::auto_ptr<INode> clone() const = 0;
public:
const OUString& getName() const { return m_aName; }
node::Attributes getAttributes() const { return m_aAttributes; }
bool isDefault() const { return m_aAttributes.isDefault(); }
bool isLocalized() const { return m_aAttributes.isLocalized(); }
void modifyState(node::State _eNewState);
void modifyAccess(node::Access _aAccessLevel);
void markMandatory();
void markRemovable();
void promoteAccessToDefault();
void forceReadonlyToFinalized();
// to be used with caution. If the node is referenced from somewhere else under it's old name,
// you may have problems with this inconsistence
void setName(const OUString& _rNewName) { m_aName = _rNewName; }
virtual ValueNode* asValueNode();
virtual ValueNode const* asValueNode() const;
virtual ISubtree* asISubtree();
virtual ISubtree const* asISubtree() const;
// double dispatch support
virtual void dispatch(NodeAction&) const = 0;
virtual void dispatch(NodeModification&) = 0;
// "rtti"
RTTI_BASE(INode);
};
// -----------------------------------------------------------------------------
//==========================================================================
//= ISubtree
//==========================================================================
class ISubtree : public INode
{
sal_Int16 m_nLevel; /// determines if everything is read
sal_Int16 m_nDefaultLevels; /// determines if defaults are read
OUString m_sId;
OUString m_sTemplateName; /// path of the template for child instantiation
OUString m_sTemplateModule; /// module of the template for child instantiation
virtual INode* doGetChild(OUString const& name) const = 0;
protected:
ISubtree():m_nLevel(0){}
ISubtree(ISubtree const& other)
:INode(other)
,m_nLevel(other.m_nLevel)
,m_sId() // do not copy ID while cloning !
,m_nDefaultLevels(other.m_nDefaultLevels)
,m_sTemplateName(other.m_sTemplateName)
,m_sTemplateModule(other.m_sTemplateModule)
{}
public:
// Ctor for group trees
ISubtree(const rtl::OUString& aName, const node::Attributes& _rAttrs)
:INode(aName, _rAttrs)
,m_nLevel(0)
,m_nDefaultLevels(0)
{}
// Ctor for set trees
ISubtree(const rtl::OUString& aName,
const rtl::OUString& _rTemplateName,
const rtl::OUString& _rTemplateModule,
const node::Attributes& _rAttrs)
:INode(aName, _rAttrs)
,m_nLevel(0)
,m_nDefaultLevels(0)
,m_sTemplateName(_rTemplateName)
,m_sTemplateModule(_rTemplateModule){}
INode* getChild(OUString const& name) { return doGetChild(name); }
INode const* getChild(OUString const& name) const { return doGetChild(name); }
ISubtree* asISubtree();
ISubtree const* asISubtree() const;
using INode::markAsDefault;
sal_Int16 getLevel() const { return m_nLevel; }
sal_Int16 getDefaultsLevel() const { return m_nDefaultLevels; }
void setLevels(sal_Int16 _nLevel,sal_Int16 _nDefaultsLevel);
bool isSetNode() const { return m_sTemplateName.getLength() != 0; }
void makeSetNode(OUString const& _sTemplateName, OUString const& _sTemplateModule)
{ m_sTemplateName = _sTemplateName; m_sTemplateModule = _sTemplateModule; }
OUString const& getElementTemplateName() const { return m_sTemplateName; }
OUString const& getElementTemplateModule() const { return m_sTemplateModule; }
virtual INode* addChild(std::auto_ptr<INode> node) =0; // takes ownership
virtual ::std::auto_ptr<INode> removeChild(rtl::OUString const& name) =0; // releases ownership
// Iteration support, stop if (action returns true)
virtual void forEachChild(NodeAction& anAction) const = 0;
virtual void forEachChild(NodeModification& anAction) = 0;
// double dispatch support
virtual void dispatch(NodeAction& anAction) const { anAction.handle(*this); }
virtual void dispatch(NodeModification& anAction) { anAction.handle(*this); }
// "rtti"
RTTI(ISubtree, INode);
};
//==========================================================================
//= ValueNode
//==========================================================================
class ValueNode : public INode
{
AnyPair m_aValuePair;
// uno::Type m_aType;
// uno::Any m_aValue;
// uno::Any m_aDefaultValue;
public:
//ValueNode(){}
//explicit ValueNode(node::Attributes _aAttrs):INode(_aAttrs){}
/*
ValueNode(OUString const& aName, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair()
{}
*/
ValueNode(OUString const& aName,uno::Type const& aType, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair(aType)
{
}
ValueNode(OUString const& aName,uno::Any const& anAny, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair(anAny, selectMember(_aAttrs.isDefault()))
{
}
ValueNode(OUString const& aName,uno::Any const& anAny,uno::Any const& aDefault, node::Attributes _aAttrs)
: INode(aName, _aAttrs)
, m_aValuePair(anAny, aDefault)
{
}
bool isEmpty() const {return m_aValuePair.isEmpty();}
bool isValid() const {return !m_aValuePair.isEmpty();}
bool isNull() const {return m_aValuePair.isNull();}
bool hasUsableDefault() const {return getAttributes().isNullable() || m_aValuePair.hasSecond();}
uno::Type getValueType() const {return m_aValuePair.getValueType();}
uno::Any getValue() const {return m_aValuePair.getValue( selectMember(this->isDefault()) );}
uno::Any getUserValue() const {return m_aValuePair.getFirst();}
uno::Any getDefault() const {return m_aValuePair.getSecond();}
bool setValueType(uno::Type const& _aType);
bool setValue(uno::Any const& _aValue);
void setDefault();
bool changeDefault(uno::Any const& _aValue);
void promoteToDefault();
virtual std::auto_ptr<INode> clone() const;
ValueNode* asValueNode();
ValueNode const* asValueNode() const;
// double dispatch support
virtual void dispatch(NodeAction& anAction) const { anAction.handle(*this); }
virtual void dispatch(NodeModification& anAction) { anAction.handle(*this); }
// "rtti"
RTTI(ValueNode, INode);
private:
static AnyPair::SelectMember selectValue() { return AnyPair::SELECT_FIRST; }
static AnyPair::SelectMember selectDeflt() { return AnyPair::SELECT_SECOND; }
static AnyPair::SelectMember selectMember(bool bDeflt)
{ return bDeflt ? AnyPair::SELECT_SECOND : AnyPair::SELECT_FIRST; }
};
//==========================================================================
extern bool isLocalizedValueSet(ISubtree const& _aSubtree);
//==========================================================================
//= inlines
//==========================================================================
inline void NodeAction::applyToNode(INode const& aNode)
{ aNode.dispatch(*this); }
inline void NodeAction::applyToChildren(ISubtree const& aSubtree)
{ aSubtree.forEachChild(*this); }
inline void NodeModification::applyToNode(INode& aNode)
{ aNode.dispatch(*this); }
inline void NodeModification::applyToChildren(ISubtree& aSubtree)
{ aSubtree.forEachChild(*this); }
} // namespace configmgr
#endif
<|endoftext|> |
<commit_before>#include "buffer_cache/mock.hpp"
#include "arch/arch.hpp"
#include "arch/random_delay.hpp"
/* Internal buf object */
struct internal_buf_t {
mock_cache_t *cache;
block_id_t block_id;
repli_timestamp subtree_recency;
void *data;
rwi_lock_t lock;
internal_buf_t(mock_cache_t *_cache, block_id_t _block_id, repli_timestamp _subtree_recency)
: cache(_cache), block_id(_block_id), subtree_recency(_subtree_recency),
data(cache->serializer->malloc()) {
rassert(data);
bzero(data, cache->block_size.value());
}
~internal_buf_t() {
cache->serializer->free(data);
}
void destroy() {
rassert(!lock.locked());
rassert(cache->bufs[block_id] == this);
cache->bufs[block_id] = NULL;
delete this;
}
};
/* Buf */
void mock_buf_t::on_lock_available() {
coro_fifo_acq_t acq;
if (is_write_mode(access)) {
acq.enter(&internal_buf->cache->write_operation_random_delay_fifo);
}
random_delay(cb, &mock_block_available_callback_t::on_block_available, this);
}
block_id_t mock_buf_t::get_block_id() {
return internal_buf->block_id;
}
const void *mock_buf_t::get_data_read() {
return internal_buf->data;
}
void *mock_buf_t::get_data_major_write() {
rassert(access == rwi_write);
dirty = true;
return internal_buf->data;
}
void mock_buf_t::apply_patch(buf_patch_t *patch) {
rassert(access == rwi_write);
patch->apply_to_buf((char*)internal_buf->data);
dirty = true;
delete patch;
}
patch_counter_t mock_buf_t::get_next_patch_counter() {
return 0;
}
void mock_buf_t::set_data(void *dest, const void *src, const size_t n) {
size_t offset = reinterpret_cast<const char *>(dest) - reinterpret_cast<const char *>(internal_buf->data);
apply_patch(new memcpy_patch_t(internal_buf->block_id, get_next_patch_counter(), offset, reinterpret_cast<const char *>(src), n));
}
void mock_buf_t::move_data(void *dest, const void *src, const size_t n) {
size_t dest_offset = reinterpret_cast<const char *>(dest) - reinterpret_cast<const char *>(internal_buf->data);
size_t src_offset = reinterpret_cast<const char *>(src) - reinterpret_cast<const char *>(internal_buf->data);
apply_patch(new memmove_patch_t(internal_buf->block_id, get_next_patch_counter(), dest_offset, src_offset, n));
}
void mock_buf_t::mark_deleted(UNUSED bool write_null) {
// write_null is ignored for the mock cache.
rassert(access == rwi_write);
deleted = true;
}
void mock_buf_t::touch_recency(repli_timestamp timestamp) {
rassert(access == rwi_write);
internal_buf->subtree_recency = timestamp;
}
void mock_buf_t::release() {
internal_buf->lock.unlock();
if (deleted) internal_buf->destroy();
delete this;
}
// TODO: Add notiont of recency_dirty
bool mock_buf_t::is_dirty() {
return dirty;
}
bool mock_buf_t::is_deleted() {
return deleted;
}
mock_buf_t::mock_buf_t(internal_buf_t *internal_buf, access_t access)
: internal_buf(internal_buf), access(access), dirty(false), deleted(false) {
}
/* Transaction */
bool mock_transaction_t::commit(mock_transaction_commit_callback_t *callback) {
switch (access) {
case rwi_read_sync:
case rwi_read:
delete this;
return true;
case rwi_write: {
coro_fifo_acq_t acq;
acq.enter(&cache->write_operation_random_delay_fifo);
if (maybe_random_delay(this, &mock_transaction_t::finish_committing, callback)) {
acq.leave();
finish_committing(NULL);
return true;
} else {
return false;
}
} break;
case rwi_read_outdated_ok:
case rwi_intent:
case rwi_upgrade:
default:
unreachable("Bad access");
}
}
void mock_transaction_t::finish_committing(mock_transaction_commit_callback_t *cb) {
if (cb) cb->on_txn_commit(this);
delete this;
}
mock_buf_t *mock_transaction_t::acquire(block_id_t block_id, access_t mode, mock_block_available_callback_t *callback, UNUSED bool should_load) {
// should_load is ignored for the mock cache.
if (mode == rwi_write) rassert(this->access == rwi_write);
rassert(block_id < cache->bufs.get_size());
internal_buf_t *internal_buf = cache->bufs[block_id];
rassert(internal_buf);
if (!(mode == rwi_read || mode == rwi_read_sync || mode == rwi_read_outdated_ok)) {
internal_buf->subtree_recency = recency_timestamp;
}
mock_buf_t *buf = new mock_buf_t(internal_buf, mode);
if (internal_buf->lock.lock(mode == rwi_read_outdated_ok ? rwi_read : mode, buf)) {
coro_fifo_acq_t acq;
if (is_write_mode(mode)) {
acq.enter(&cache->write_operation_random_delay_fifo);
}
if (maybe_random_delay(callback, &mock_block_available_callback_t::on_block_available, buf)) {
return buf;
} else {
return NULL;
}
} else {
buf->cb = callback;
return NULL;
}
}
mock_buf_t *mock_transaction_t::allocate() {
rassert(this->access == rwi_write);
block_id_t block_id = cache->bufs.get_size();
cache->bufs.set_size(block_id + 1);
internal_buf_t *internal_buf = new internal_buf_t(cache, block_id, recency_timestamp);
cache->bufs[block_id] = internal_buf;
bool locked __attribute__((unused)) = internal_buf->lock.lock(rwi_write, NULL);
rassert(locked);
mock_buf_t *buf = new mock_buf_t(internal_buf, rwi_write);
return buf;
}
void mock_transaction_t::get_subtree_recencies(block_id_t *block_ids, size_t num_block_ids, repli_timestamp *recencies_out, get_subtree_recencies_callback_t *cb) {
for (size_t i = 0; i < num_block_ids; ++i) {
rassert(block_ids[i] < cache->bufs.get_size());
internal_buf_t *internal_buf = cache->bufs[block_ids[i]];
rassert(internal_buf);
recencies_out[i] = internal_buf->subtree_recency;
}
cb->got_subtree_recencies();
}
mock_transaction_t::mock_transaction_t(mock_cache_t *_cache, access_t _access, repli_timestamp _recency_timestamp)
: cache(_cache), order_token(order_token_t::ignore), access(_access), recency_timestamp(_recency_timestamp) {
cache->transaction_counter.acquire();
}
mock_transaction_t::~mock_transaction_t() {
cache->transaction_counter.release();
}
/* Cache */
// TODO: Why do we take a static_config if we don't use it?
// (I.i.r.c. we have a similar situation in the mirrored cache.)
void mock_cache_t::create( translator_serializer_t *serializer, UNUSED mirrored_cache_static_config_t *static_config) {
on_thread_t switcher(serializer->home_thread());
void *superblock = serializer->malloc();
bzero(superblock, serializer->get_block_size().value());
translator_serializer_t::write_t write = translator_serializer_t::write_t::make(
SUPERBLOCK_ID, repli_timestamp::invalid, superblock, false, NULL);
struct : public serializer_t::write_txn_callback_t, public cond_t {
void on_serializer_write_txn() { pulse(); }
} cb;
if (!serializer->do_write(&write, 1, DEFAULT_DISK_ACCOUNT, &cb)) cb.wait();
serializer->free(superblock);
}
// dynamic_config is unused because this is a mock cache and the
// configuration parameters don't apply.
mock_cache_t::mock_cache_t( translator_serializer_t *serializer, UNUSED mirrored_cache_config_t *dynamic_config)
: serializer(serializer), block_size(serializer->get_block_size())
{
on_thread_t switcher(serializer->home_thread());
struct : public serializer_t::read_callback_t, public drain_semaphore_t {
void on_serializer_read() { release(); }
} read_cb;
block_id_t end_block_id = serializer->max_block_id();
bufs.set_size(end_block_id, NULL);
for (block_id_t i = 0; i < end_block_id; i++) {
if (serializer->block_in_use(i)) {
internal_buf_t *internal_buf = new internal_buf_t(this, i, serializer->get_recency(i));
bufs[i] = internal_buf;
if (!serializer->do_read(i, internal_buf->data, DEFAULT_DISK_ACCOUNT, &read_cb)) read_cb.acquire();
}
}
/* Block until all readers are done */
read_cb.drain();
}
mock_cache_t::~mock_cache_t() {
/* Wait for all transactions to complete */
transaction_counter.drain();
{
on_thread_t thread_switcher(serializer->home_thread());
std::vector<translator_serializer_t::write_t> writes;
for (block_id_t i = 0; i < bufs.get_size(); i++) {
writes.push_back(translator_serializer_t::write_t::make(
i, bufs[i] ? bufs[i]->subtree_recency : repli_timestamp::invalid,
bufs[i] ? bufs[i]->data : NULL,
true, NULL));
}
struct : public serializer_t::write_txn_callback_t, public cond_t {
void on_serializer_write_txn() { pulse(); }
} cb;
if (!serializer->do_write(writes.data(), writes.size(), DEFAULT_DISK_ACCOUNT, &cb)) cb.wait();
}
for (block_id_t i = 0; i < bufs.get_size(); i++) {
if (bufs[i]) delete bufs[i];
}
}
block_size_t mock_cache_t::get_block_size() {
return block_size;
}
mock_transaction_t *mock_cache_t::begin_transaction(access_t access, UNUSED int expected_change_count, repli_timestamp recency_timestamp, mock_transaction_begin_callback_t *callback) {
mock_transaction_t *txn = new mock_transaction_t(this, access, recency_timestamp);
switch (access) {
case rwi_read_sync:
case rwi_read:
return txn;
case rwi_write: {
coro_fifo_acq_t acq;
acq.enter(&write_operation_random_delay_fifo);
if (maybe_random_delay(callback, &mock_transaction_begin_callback_t::on_txn_begin, txn)) {
return txn;
} else {
return NULL;
}
} break;
case rwi_read_outdated_ok:
case rwi_intent:
case rwi_upgrade:
default:
unreachable("Bad access.");
}
}
void mock_cache_t::offer_read_ahead_buf(UNUSED block_id_t block_id, void *buf, UNUSED repli_timestamp recency_timestamp) {
serializer->free(buf);
}
bool mock_cache_t::contains_block(UNUSED block_id_t id) {
return true; // TODO (maybe) write a more sensible implementation
}
<commit_msg>Fix ordering guarantee in mock cache's begin_transaction<commit_after>#include "buffer_cache/mock.hpp"
#include "arch/arch.hpp"
#include "arch/random_delay.hpp"
/* Internal buf object */
struct internal_buf_t {
mock_cache_t *cache;
block_id_t block_id;
repli_timestamp subtree_recency;
void *data;
rwi_lock_t lock;
internal_buf_t(mock_cache_t *_cache, block_id_t _block_id, repli_timestamp _subtree_recency)
: cache(_cache), block_id(_block_id), subtree_recency(_subtree_recency),
data(cache->serializer->malloc()) {
rassert(data);
bzero(data, cache->block_size.value());
}
~internal_buf_t() {
cache->serializer->free(data);
}
void destroy() {
rassert(!lock.locked());
rassert(cache->bufs[block_id] == this);
cache->bufs[block_id] = NULL;
delete this;
}
};
/* Buf */
void mock_buf_t::on_lock_available() {
random_delay(cb, &mock_block_available_callback_t::on_block_available, this);
}
block_id_t mock_buf_t::get_block_id() {
return internal_buf->block_id;
}
const void *mock_buf_t::get_data_read() {
return internal_buf->data;
}
void *mock_buf_t::get_data_major_write() {
rassert(access == rwi_write);
dirty = true;
return internal_buf->data;
}
void mock_buf_t::apply_patch(buf_patch_t *patch) {
rassert(access == rwi_write);
patch->apply_to_buf((char*)internal_buf->data);
dirty = true;
delete patch;
}
patch_counter_t mock_buf_t::get_next_patch_counter() {
return 0;
}
void mock_buf_t::set_data(void *dest, const void *src, const size_t n) {
size_t offset = reinterpret_cast<const char *>(dest) - reinterpret_cast<const char *>(internal_buf->data);
apply_patch(new memcpy_patch_t(internal_buf->block_id, get_next_patch_counter(), offset, reinterpret_cast<const char *>(src), n));
}
void mock_buf_t::move_data(void *dest, const void *src, const size_t n) {
size_t dest_offset = reinterpret_cast<const char *>(dest) - reinterpret_cast<const char *>(internal_buf->data);
size_t src_offset = reinterpret_cast<const char *>(src) - reinterpret_cast<const char *>(internal_buf->data);
apply_patch(new memmove_patch_t(internal_buf->block_id, get_next_patch_counter(), dest_offset, src_offset, n));
}
void mock_buf_t::mark_deleted(UNUSED bool write_null) {
// write_null is ignored for the mock cache.
rassert(access == rwi_write);
deleted = true;
}
void mock_buf_t::touch_recency(repli_timestamp timestamp) {
rassert(access == rwi_write);
internal_buf->subtree_recency = timestamp;
}
void mock_buf_t::release() {
internal_buf->lock.unlock();
if (deleted) internal_buf->destroy();
delete this;
}
// TODO: Add notiont of recency_dirty
bool mock_buf_t::is_dirty() {
return dirty;
}
bool mock_buf_t::is_deleted() {
return deleted;
}
mock_buf_t::mock_buf_t(internal_buf_t *internal_buf, access_t access)
: internal_buf(internal_buf), access(access), dirty(false), deleted(false) {
}
/* Transaction */
bool mock_transaction_t::commit(mock_transaction_commit_callback_t *callback) {
switch (access) {
case rwi_read_sync:
case rwi_read:
delete this;
return true;
case rwi_write: {
coro_fifo_acq_t acq;
acq.enter(&cache->write_operation_random_delay_fifo);
if (maybe_random_delay(this, &mock_transaction_t::finish_committing, callback)) {
acq.leave();
finish_committing(NULL);
return true;
} else {
return false;
}
} break;
case rwi_read_outdated_ok:
case rwi_intent:
case rwi_upgrade:
default:
unreachable("Bad access");
}
}
void mock_transaction_t::finish_committing(mock_transaction_commit_callback_t *cb) {
if (cb) cb->on_txn_commit(this);
delete this;
}
mock_buf_t *mock_transaction_t::acquire(block_id_t block_id, access_t mode, mock_block_available_callback_t *callback, UNUSED bool should_load) {
// should_load is ignored for the mock cache.
if (mode == rwi_write) rassert(this->access == rwi_write);
rassert(block_id < cache->bufs.get_size());
internal_buf_t *internal_buf = cache->bufs[block_id];
rassert(internal_buf);
if (!(mode == rwi_read || mode == rwi_read_sync || mode == rwi_read_outdated_ok)) {
internal_buf->subtree_recency = recency_timestamp;
}
mock_buf_t *buf = new mock_buf_t(internal_buf, mode);
if (internal_buf->lock.lock(mode == rwi_read_outdated_ok ? rwi_read : mode, buf)) {
coro_fifo_acq_t acq;
if (is_write_mode(mode)) {
acq.enter(&cache->write_operation_random_delay_fifo);
}
if (maybe_random_delay(callback, &mock_block_available_callback_t::on_block_available, buf)) {
return buf;
} else {
return NULL;
}
} else {
buf->cb = callback;
return NULL;
}
}
mock_buf_t *mock_transaction_t::allocate() {
rassert(this->access == rwi_write);
block_id_t block_id = cache->bufs.get_size();
cache->bufs.set_size(block_id + 1);
internal_buf_t *internal_buf = new internal_buf_t(cache, block_id, recency_timestamp);
cache->bufs[block_id] = internal_buf;
bool locked __attribute__((unused)) = internal_buf->lock.lock(rwi_write, NULL);
rassert(locked);
mock_buf_t *buf = new mock_buf_t(internal_buf, rwi_write);
return buf;
}
void mock_transaction_t::get_subtree_recencies(block_id_t *block_ids, size_t num_block_ids, repli_timestamp *recencies_out, get_subtree_recencies_callback_t *cb) {
for (size_t i = 0; i < num_block_ids; ++i) {
rassert(block_ids[i] < cache->bufs.get_size());
internal_buf_t *internal_buf = cache->bufs[block_ids[i]];
rassert(internal_buf);
recencies_out[i] = internal_buf->subtree_recency;
}
cb->got_subtree_recencies();
}
mock_transaction_t::mock_transaction_t(mock_cache_t *_cache, access_t _access, repli_timestamp _recency_timestamp)
: cache(_cache), order_token(order_token_t::ignore), access(_access), recency_timestamp(_recency_timestamp) {
cache->transaction_counter.acquire();
}
mock_transaction_t::~mock_transaction_t() {
cache->transaction_counter.release();
}
/* Cache */
// TODO: Why do we take a static_config if we don't use it?
// (I.i.r.c. we have a similar situation in the mirrored cache.)
void mock_cache_t::create( translator_serializer_t *serializer, UNUSED mirrored_cache_static_config_t *static_config) {
on_thread_t switcher(serializer->home_thread());
void *superblock = serializer->malloc();
bzero(superblock, serializer->get_block_size().value());
translator_serializer_t::write_t write = translator_serializer_t::write_t::make(
SUPERBLOCK_ID, repli_timestamp::invalid, superblock, false, NULL);
struct : public serializer_t::write_txn_callback_t, public cond_t {
void on_serializer_write_txn() { pulse(); }
} cb;
if (!serializer->do_write(&write, 1, DEFAULT_DISK_ACCOUNT, &cb)) cb.wait();
serializer->free(superblock);
}
// dynamic_config is unused because this is a mock cache and the
// configuration parameters don't apply.
mock_cache_t::mock_cache_t( translator_serializer_t *serializer, UNUSED mirrored_cache_config_t *dynamic_config)
: serializer(serializer), block_size(serializer->get_block_size())
{
on_thread_t switcher(serializer->home_thread());
struct : public serializer_t::read_callback_t, public drain_semaphore_t {
void on_serializer_read() { release(); }
} read_cb;
block_id_t end_block_id = serializer->max_block_id();
bufs.set_size(end_block_id, NULL);
for (block_id_t i = 0; i < end_block_id; i++) {
if (serializer->block_in_use(i)) {
internal_buf_t *internal_buf = new internal_buf_t(this, i, serializer->get_recency(i));
bufs[i] = internal_buf;
if (!serializer->do_read(i, internal_buf->data, DEFAULT_DISK_ACCOUNT, &read_cb)) read_cb.acquire();
}
}
/* Block until all readers are done */
read_cb.drain();
}
mock_cache_t::~mock_cache_t() {
/* Wait for all transactions to complete */
transaction_counter.drain();
{
on_thread_t thread_switcher(serializer->home_thread());
std::vector<translator_serializer_t::write_t> writes;
for (block_id_t i = 0; i < bufs.get_size(); i++) {
writes.push_back(translator_serializer_t::write_t::make(
i, bufs[i] ? bufs[i]->subtree_recency : repli_timestamp::invalid,
bufs[i] ? bufs[i]->data : NULL,
true, NULL));
}
struct : public serializer_t::write_txn_callback_t, public cond_t {
void on_serializer_write_txn() { pulse(); }
} cb;
if (!serializer->do_write(writes.data(), writes.size(), DEFAULT_DISK_ACCOUNT, &cb)) cb.wait();
}
for (block_id_t i = 0; i < bufs.get_size(); i++) {
if (bufs[i]) delete bufs[i];
}
}
block_size_t mock_cache_t::get_block_size() {
return block_size;
}
struct delay_on_txn_begin_wrapper_t {
mock_transaction_begin_callback_t *callback;
coro_fifo_acq_t acq;
void on_txn_begin_wrapper(mock_transaction_t *txn) {
if (!coro_t::self()) {
coro_t::spawn(boost::bind(&delay_on_txn_begin_wrapper_t::on_txn_begin_wrapper, this, txn));
return;
}
acq.leave();
callback->on_txn_begin(txn);
delete this;
}
};
mock_transaction_t *mock_cache_t::begin_transaction(access_t access, UNUSED int expected_change_count, repli_timestamp recency_timestamp, mock_transaction_begin_callback_t *callback) {
mock_transaction_t *txn = new mock_transaction_t(this, access, recency_timestamp);
switch (access) {
case rwi_read_sync:
case rwi_read:
return txn;
case rwi_write: {
delay_on_txn_begin_wrapper_t *delay_on_txn_begin_wrapper = new delay_on_txn_begin_wrapper_t();
delay_on_txn_begin_wrapper->acq.enter(&write_operation_random_delay_fifo);
if (maybe_random_delay(delay_on_txn_begin_wrapper, &delay_on_txn_begin_wrapper_t::on_txn_begin_wrapper, txn)) {
delete delay_on_txn_begin_wrapper;
return txn;
} else {
delay_on_txn_begin_wrapper->callback = callback;
return NULL;
}
} break;
case rwi_read_outdated_ok:
case rwi_intent:
case rwi_upgrade:
default:
unreachable("Bad access.");
}
}
void mock_cache_t::offer_read_ahead_buf(UNUSED block_id_t block_id, void *buf, UNUSED repli_timestamp recency_timestamp) {
serializer->free(buf);
}
bool mock_cache_t::contains_block(UNUSED block_id_t id) {
return true; // TODO (maybe) write a more sensible implementation
}
<|endoftext|> |
<commit_before>
#include <gloperate/gloperate-version.h>
#include <gloperate/plugin/plugin_api.h>
#include "multiframepainter/MultiFramePainter.h"
#include "singleframepainter/SingleFramePainter.h"
GLOPERATE_PLUGIN_LIBRARY
GLOPERATE_PAINTER_PLUGIN(MultiFramePainter
, "MultiFramePainter"
, "Moep"
, GLOPERATE_AUTHOR_ORGANIZATION
, "v0.0.0" )
GLOPERATE_PAINTER_PLUGIN(SingleFramePainter
, "SingleFramePainter"
, "Moep"
, GLOPERATE_AUTHOR_ORGANIZATION
, "v0.0.0" )
GLOPERATE_PLUGIN_LIBRARY_END
<commit_msg>fix version<commit_after>
#include <multiframesampling/multiframesampling-version.h>
#include <gloperate/plugin/plugin_api.h>
#include "multiframepainter/MultiFramePainter.h"
#include "singleframepainter/SingleFramePainter.h"
GLOPERATE_PLUGIN_LIBRARY
GLOPERATE_PAINTER_PLUGIN(MultiFramePainter
, "MultiFramePainter"
, "Moep"
, MULTIFRAMESAMPLING_AUTHOR_ORGANIZATION
, "v0.0.0" )
GLOPERATE_PAINTER_PLUGIN(SingleFramePainter
, "SingleFramePainter"
, "Moep"
, MULTIFRAMESAMPLING_AUTHOR_ORGANIZATION
, "v0.0.0" )
GLOPERATE_PLUGIN_LIBRARY_END
<|endoftext|> |
<commit_before>/**
* \file
* \brief Scheduler class implementation
*
* \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-11-19
*/
#include "distortos/scheduler/Scheduler.hpp"
#include "distortos/SoftwareTimer.hpp"
#include "distortos/scheduler/MainThreadControlBlock.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/architecture/InterruptUnmaskingLock.hpp"
#include <cerrno>
namespace distortos
{
namespace scheduler
{
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Scheduler::Scheduler() :
currentThreadControlBlock_{},
mutexControlBlockListAllocatorPool_{},
threadControlBlockListAllocatorPool_{},
threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_},
runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable},
suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended},
softwareTimerControlBlockSupervisor_{},
contextSwitchCount_{},
tickCount_{}
{
}
void Scheduler::add(ThreadControlBlock& threadControlBlock)
{
architecture::InterruptMaskingLock interruptMaskingLock;
threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink());
runnableList_.sortedEmplace(threadControlBlock);
maybeRequestContextSwitch();
}
void Scheduler::block(ThreadControlBlockList& container)
{
block(container, currentThreadControlBlock_);
}
int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto ret = blockInternal(container, iterator);
if (ret != 0)
return ret;
if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required
return 0;
}
forceContextSwitch();
return 0;
}
int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint)
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto iterator = currentThreadControlBlock_;
bool timedOut {};
// This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock
// should be avoided (it could mess the order of threads of the same priority). In that case it also marks the
// "timed out" reason of unblocking.
auto softwareTimer = makeSoftwareTimer(
[this, iterator, &timedOut]()
{
if (iterator->get().getList() != &runnableList_)
{
unblockInternal(iterator);
timedOut = true;
}
});
softwareTimer.start(timePoint);
block(container);
return timedOut == false ? 0 : ETIMEDOUT;
}
uint64_t Scheduler::getContextSwitchCount() const
{
architecture::InterruptMaskingLock interruptMaskingLock;
return contextSwitchCount_;
}
uint64_t Scheduler::getTickCount() const
{
architecture::InterruptMaskingLock interruptMaskingLock;
return tickCount_;
}
void Scheduler::initialize(MainThreadControlBlock& mainThreadControlBlock)
{
add(mainThreadControlBlock);
currentThreadControlBlock_ = runnableList_.begin();
}
void Scheduler::maybeRequestContextSwitch() const
{
if (isContextSwitchRequired() == true)
architecture::requestContextSwitch();
}
int Scheduler::remove()
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated};
const auto ret = blockInternal(terminatedList, currentThreadControlBlock_);
if (ret != 0)
return ret;
terminatedList.begin()->get().terminationHook();
}
forceContextSwitch();
return 0;
}
int Scheduler::resume(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
if (iterator->get().getList() != &suspendedList_)
return EINVAL;
unblock(iterator);
return 0;
}
void Scheduler::suspend()
{
suspend(currentThreadControlBlock_);
}
int Scheduler::suspend(const ThreadControlBlockListIterator iterator)
{
return block(suspendedList_, iterator);
}
void* Scheduler::switchContext(void* const stackPointer)
{
architecture::InterruptMaskingLock interruptMaskingLock;
++contextSwitchCount_;
getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer);
currentThreadControlBlock_ = runnableList_.begin();
return getCurrentThreadControlBlock().getStack().getStackPointer();
}
bool Scheduler::tickInterruptHandler()
{
architecture::InterruptMaskingLock interruptMaskingLock;
++tickCount_;
getCurrentThreadControlBlock().getRoundRobinQuantum().decrement();
// if the object is on the "runnable" list, it uses SchedulingPolicy::RoundRobin and it used its round-robin
// quantum, then do the "rotation": move current thread to the end of same-priority group to implement round-robin
// scheduling
if (getCurrentThreadControlBlock().getList() == &runnableList_ &&
getCurrentThreadControlBlock().getSchedulingPolicy() == SchedulingPolicy::RoundRobin &&
getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true)
{
getCurrentThreadControlBlock().getRoundRobinQuantum().reset();
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
}
softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}});
return isContextSwitchRequired();
}
void Scheduler::unblock(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
unblockInternal(iterator);
maybeRequestContextSwitch();
}
void Scheduler::yield()
{
architecture::InterruptMaskingLock interruptMaskingLock;
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
maybeRequestContextSwitch();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
void Scheduler::addInternal(ThreadControlBlock& threadControlBlock)
{
threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink());
runnableList_.sortedEmplace(threadControlBlock);
}
int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
if (iterator->get().getList() != &runnableList_)
return EINVAL;
container.sortedSplice(runnableList_, iterator);
return 0;
}
void Scheduler::forceContextSwitch() const
{
architecture::InterruptUnmaskingLock interruptUnmaskingLock;
architecture::requestContextSwitch();
}
bool Scheduler::isContextSwitchRequired() const
{
// this check must be first, because during early startup currentThreadControlBlock_ is not yet initialized (so
// futher conditions would dereference nullptr) and no threads are available
if (runnableList_.size() <= 1) // no threads or single thread available?
return false; // no context switch possible
if (getCurrentThreadControlBlock().getList() != &runnableList_)
return true;
if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available?
return true;
return false;
}
void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator)
{
runnableList_.sortedSplice(*iterator->get().getList(), iterator);
iterator->get().getRoundRobinQuantum().reset();
}
} // namespace scheduler
} // namespace distortos
<commit_msg>Scheduler: implement Scheduler::add() with Scheduler::addInternal()<commit_after>/**
* \file
* \brief Scheduler class implementation
*
* \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-11-19
*/
#include "distortos/scheduler/Scheduler.hpp"
#include "distortos/SoftwareTimer.hpp"
#include "distortos/scheduler/MainThreadControlBlock.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/architecture/InterruptUnmaskingLock.hpp"
#include <cerrno>
namespace distortos
{
namespace scheduler
{
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Scheduler::Scheduler() :
currentThreadControlBlock_{},
mutexControlBlockListAllocatorPool_{},
threadControlBlockListAllocatorPool_{},
threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_},
runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable},
suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended},
softwareTimerControlBlockSupervisor_{},
contextSwitchCount_{},
tickCount_{}
{
}
void Scheduler::add(ThreadControlBlock& threadControlBlock)
{
architecture::InterruptMaskingLock interruptMaskingLock;
addInternal(threadControlBlock);
maybeRequestContextSwitch();
}
void Scheduler::block(ThreadControlBlockList& container)
{
block(container, currentThreadControlBlock_);
}
int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto ret = blockInternal(container, iterator);
if (ret != 0)
return ret;
if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required
return 0;
}
forceContextSwitch();
return 0;
}
int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint)
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto iterator = currentThreadControlBlock_;
bool timedOut {};
// This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock
// should be avoided (it could mess the order of threads of the same priority). In that case it also marks the
// "timed out" reason of unblocking.
auto softwareTimer = makeSoftwareTimer(
[this, iterator, &timedOut]()
{
if (iterator->get().getList() != &runnableList_)
{
unblockInternal(iterator);
timedOut = true;
}
});
softwareTimer.start(timePoint);
block(container);
return timedOut == false ? 0 : ETIMEDOUT;
}
uint64_t Scheduler::getContextSwitchCount() const
{
architecture::InterruptMaskingLock interruptMaskingLock;
return contextSwitchCount_;
}
uint64_t Scheduler::getTickCount() const
{
architecture::InterruptMaskingLock interruptMaskingLock;
return tickCount_;
}
void Scheduler::initialize(MainThreadControlBlock& mainThreadControlBlock)
{
add(mainThreadControlBlock);
currentThreadControlBlock_ = runnableList_.begin();
}
void Scheduler::maybeRequestContextSwitch() const
{
if (isContextSwitchRequired() == true)
architecture::requestContextSwitch();
}
int Scheduler::remove()
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated};
const auto ret = blockInternal(terminatedList, currentThreadControlBlock_);
if (ret != 0)
return ret;
terminatedList.begin()->get().terminationHook();
}
forceContextSwitch();
return 0;
}
int Scheduler::resume(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
if (iterator->get().getList() != &suspendedList_)
return EINVAL;
unblock(iterator);
return 0;
}
void Scheduler::suspend()
{
suspend(currentThreadControlBlock_);
}
int Scheduler::suspend(const ThreadControlBlockListIterator iterator)
{
return block(suspendedList_, iterator);
}
void* Scheduler::switchContext(void* const stackPointer)
{
architecture::InterruptMaskingLock interruptMaskingLock;
++contextSwitchCount_;
getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer);
currentThreadControlBlock_ = runnableList_.begin();
return getCurrentThreadControlBlock().getStack().getStackPointer();
}
bool Scheduler::tickInterruptHandler()
{
architecture::InterruptMaskingLock interruptMaskingLock;
++tickCount_;
getCurrentThreadControlBlock().getRoundRobinQuantum().decrement();
// if the object is on the "runnable" list, it uses SchedulingPolicy::RoundRobin and it used its round-robin
// quantum, then do the "rotation": move current thread to the end of same-priority group to implement round-robin
// scheduling
if (getCurrentThreadControlBlock().getList() == &runnableList_ &&
getCurrentThreadControlBlock().getSchedulingPolicy() == SchedulingPolicy::RoundRobin &&
getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true)
{
getCurrentThreadControlBlock().getRoundRobinQuantum().reset();
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
}
softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}});
return isContextSwitchRequired();
}
void Scheduler::unblock(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
unblockInternal(iterator);
maybeRequestContextSwitch();
}
void Scheduler::yield()
{
architecture::InterruptMaskingLock interruptMaskingLock;
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
maybeRequestContextSwitch();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
void Scheduler::addInternal(ThreadControlBlock& threadControlBlock)
{
threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink());
runnableList_.sortedEmplace(threadControlBlock);
}
int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
if (iterator->get().getList() != &runnableList_)
return EINVAL;
container.sortedSplice(runnableList_, iterator);
return 0;
}
void Scheduler::forceContextSwitch() const
{
architecture::InterruptUnmaskingLock interruptUnmaskingLock;
architecture::requestContextSwitch();
}
bool Scheduler::isContextSwitchRequired() const
{
// this check must be first, because during early startup currentThreadControlBlock_ is not yet initialized (so
// futher conditions would dereference nullptr) and no threads are available
if (runnableList_.size() <= 1) // no threads or single thread available?
return false; // no context switch possible
if (getCurrentThreadControlBlock().getList() != &runnableList_)
return true;
if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available?
return true;
return false;
}
void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator)
{
runnableList_.sortedSplice(*iterator->get().getList(), iterator);
iterator->get().getRoundRobinQuantum().reset();
}
} // namespace scheduler
} // namespace distortos
<|endoftext|> |
<commit_before>/**
* \file
* \brief Scheduler class implementation
*
* \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-11-04
*/
#include "distortos/scheduler/Scheduler.hpp"
#include "distortos/SoftwareTimer.hpp"
#include "distortos/scheduler/MainThreadControlBlock.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/architecture/InterruptUnmaskingLock.hpp"
#include <cerrno>
namespace distortos
{
namespace scheduler
{
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Scheduler::Scheduler() :
currentThreadControlBlock_{},
mutexControlBlockListAllocatorPool_{},
threadControlBlockListAllocatorPool_{},
threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_},
runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable},
suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended},
softwareTimerControlBlockSupervisor_{},
contextSwitchCount_{},
tickCount_{}
{
}
void Scheduler::add(ThreadControlBlock& threadControlBlock)
{
architecture::InterruptMaskingLock interruptMaskingLock;
threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink());
runnableList_.sortedEmplace(threadControlBlock);
maybeRequestContextSwitch();
}
void Scheduler::block(ThreadControlBlockList& container)
{
block(container, currentThreadControlBlock_);
}
int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto ret = blockInternal(container, iterator);
if (ret != 0)
return ret;
if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required
return 0;
}
forceContextSwitch();
return 0;
}
int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint)
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto iterator = currentThreadControlBlock_;
bool timedOut {};
// This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock
// should be avoided (it could mess the order of threads of the same priority). In that case it also marks the
// "timed out" reason of unblocking.
auto softwareTimer = makeSoftwareTimer(
[this, iterator, &timedOut]()
{
if (iterator->get().getList() != &runnableList_)
{
unblockInternal(iterator);
timedOut = true;
}
});
softwareTimer.start(timePoint);
block(container);
return timedOut == false ? 0 : ETIMEDOUT;
}
uint64_t Scheduler::getTickCount() const
{
architecture::InterruptMaskingLock interruptMaskingLock;
return tickCount_;
}
void Scheduler::initialize(MainThreadControlBlock& mainThreadControlBlock)
{
add(mainThreadControlBlock);
currentThreadControlBlock_ = runnableList_.begin();
}
void Scheduler::maybeRequestContextSwitch() const
{
if (isContextSwitchRequired() == true)
architecture::requestContextSwitch();
}
int Scheduler::remove()
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated};
const auto ret = blockInternal(terminatedList, currentThreadControlBlock_);
if (ret != 0)
return ret;
terminatedList.begin()->get().terminationHook();
}
forceContextSwitch();
return 0;
}
int Scheduler::resume(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
if (iterator->get().getList() != &suspendedList_)
return EINVAL;
unblock(iterator);
return 0;
}
void Scheduler::suspend()
{
suspend(currentThreadControlBlock_);
}
int Scheduler::suspend(const ThreadControlBlockListIterator iterator)
{
return block(suspendedList_, iterator);
}
void* Scheduler::switchContext(void* const stackPointer)
{
architecture::InterruptMaskingLock interruptMaskingLock;
getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer);
currentThreadControlBlock_ = runnableList_.begin();
return getCurrentThreadControlBlock().getStack().getStackPointer();
}
bool Scheduler::tickInterruptHandler()
{
architecture::InterruptMaskingLock interruptMaskingLock;
++tickCount_;
getCurrentThreadControlBlock().getRoundRobinQuantum().decrement();
// if the object is on the "runnable" list and it used its round-robin quantum, then do the "rotation": move current
// thread to the end of same-priority group to implement round-robin scheduling
if (getCurrentThreadControlBlock().getList() == &runnableList_ &&
getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true)
{
getCurrentThreadControlBlock().getRoundRobinQuantum().reset();
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
}
softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}});
return isContextSwitchRequired();
}
void Scheduler::unblock(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
unblockInternal(iterator);
maybeRequestContextSwitch();
}
void Scheduler::yield()
{
architecture::InterruptMaskingLock interruptMaskingLock;
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
maybeRequestContextSwitch();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
if (iterator->get().getList() != &runnableList_)
return EINVAL;
container.sortedSplice(runnableList_, iterator);
return 0;
}
void Scheduler::forceContextSwitch() const
{
architecture::InterruptUnmaskingLock interruptUnmaskingLock;
architecture::requestContextSwitch();
}
bool Scheduler::isContextSwitchRequired() const
{
// this check must be first, because during early startup currentThreadControlBlock_ is not yet initialized (so
// futher conditions would dereference nullptr) and no threads are available
if (runnableList_.size() <= 1) // no threads or single thread available?
return false; // no context switch possible
if (getCurrentThreadControlBlock().getList() != &runnableList_)
return true;
if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available?
return true;
if (getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true)
{
const auto nextThread = ++runnableList_.begin();
const auto nextThreadPriority = nextThread->get().getPriority();
// thread with same priority available?
if (getCurrentThreadControlBlock().getPriority() == nextThreadPriority)
return true; // switch context to do round-robin scheduling
}
return false;
}
void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator)
{
runnableList_.sortedSplice(*iterator->get().getList(), iterator);
iterator->get().getRoundRobinQuantum().reset();
}
} // namespace scheduler
} // namespace distortos
<commit_msg>Scheduler: count context switches in Scheduler::switchContext()<commit_after>/**
* \file
* \brief Scheduler class implementation
*
* \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-11-04
*/
#include "distortos/scheduler/Scheduler.hpp"
#include "distortos/SoftwareTimer.hpp"
#include "distortos/scheduler/MainThreadControlBlock.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/architecture/InterruptUnmaskingLock.hpp"
#include <cerrno>
namespace distortos
{
namespace scheduler
{
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Scheduler::Scheduler() :
currentThreadControlBlock_{},
mutexControlBlockListAllocatorPool_{},
threadControlBlockListAllocatorPool_{},
threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_},
runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable},
suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended},
softwareTimerControlBlockSupervisor_{},
contextSwitchCount_{},
tickCount_{}
{
}
void Scheduler::add(ThreadControlBlock& threadControlBlock)
{
architecture::InterruptMaskingLock interruptMaskingLock;
threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink());
runnableList_.sortedEmplace(threadControlBlock);
maybeRequestContextSwitch();
}
void Scheduler::block(ThreadControlBlockList& container)
{
block(container, currentThreadControlBlock_);
}
int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto ret = blockInternal(container, iterator);
if (ret != 0)
return ret;
if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required
return 0;
}
forceContextSwitch();
return 0;
}
int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint)
{
architecture::InterruptMaskingLock interruptMaskingLock;
const auto iterator = currentThreadControlBlock_;
bool timedOut {};
// This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock
// should be avoided (it could mess the order of threads of the same priority). In that case it also marks the
// "timed out" reason of unblocking.
auto softwareTimer = makeSoftwareTimer(
[this, iterator, &timedOut]()
{
if (iterator->get().getList() != &runnableList_)
{
unblockInternal(iterator);
timedOut = true;
}
});
softwareTimer.start(timePoint);
block(container);
return timedOut == false ? 0 : ETIMEDOUT;
}
uint64_t Scheduler::getTickCount() const
{
architecture::InterruptMaskingLock interruptMaskingLock;
return tickCount_;
}
void Scheduler::initialize(MainThreadControlBlock& mainThreadControlBlock)
{
add(mainThreadControlBlock);
currentThreadControlBlock_ = runnableList_.begin();
}
void Scheduler::maybeRequestContextSwitch() const
{
if (isContextSwitchRequired() == true)
architecture::requestContextSwitch();
}
int Scheduler::remove()
{
{
architecture::InterruptMaskingLock interruptMaskingLock;
ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated};
const auto ret = blockInternal(terminatedList, currentThreadControlBlock_);
if (ret != 0)
return ret;
terminatedList.begin()->get().terminationHook();
}
forceContextSwitch();
return 0;
}
int Scheduler::resume(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
if (iterator->get().getList() != &suspendedList_)
return EINVAL;
unblock(iterator);
return 0;
}
void Scheduler::suspend()
{
suspend(currentThreadControlBlock_);
}
int Scheduler::suspend(const ThreadControlBlockListIterator iterator)
{
return block(suspendedList_, iterator);
}
void* Scheduler::switchContext(void* const stackPointer)
{
architecture::InterruptMaskingLock interruptMaskingLock;
++contextSwitchCount_;
getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer);
currentThreadControlBlock_ = runnableList_.begin();
return getCurrentThreadControlBlock().getStack().getStackPointer();
}
bool Scheduler::tickInterruptHandler()
{
architecture::InterruptMaskingLock interruptMaskingLock;
++tickCount_;
getCurrentThreadControlBlock().getRoundRobinQuantum().decrement();
// if the object is on the "runnable" list and it used its round-robin quantum, then do the "rotation": move current
// thread to the end of same-priority group to implement round-robin scheduling
if (getCurrentThreadControlBlock().getList() == &runnableList_ &&
getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true)
{
getCurrentThreadControlBlock().getRoundRobinQuantum().reset();
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
}
softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}});
return isContextSwitchRequired();
}
void Scheduler::unblock(const ThreadControlBlockListIterator iterator)
{
architecture::InterruptMaskingLock interruptMaskingLock;
unblockInternal(iterator);
maybeRequestContextSwitch();
}
void Scheduler::yield()
{
architecture::InterruptMaskingLock interruptMaskingLock;
runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_);
maybeRequestContextSwitch();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator)
{
if (iterator->get().getList() != &runnableList_)
return EINVAL;
container.sortedSplice(runnableList_, iterator);
return 0;
}
void Scheduler::forceContextSwitch() const
{
architecture::InterruptUnmaskingLock interruptUnmaskingLock;
architecture::requestContextSwitch();
}
bool Scheduler::isContextSwitchRequired() const
{
// this check must be first, because during early startup currentThreadControlBlock_ is not yet initialized (so
// futher conditions would dereference nullptr) and no threads are available
if (runnableList_.size() <= 1) // no threads or single thread available?
return false; // no context switch possible
if (getCurrentThreadControlBlock().getList() != &runnableList_)
return true;
if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available?
return true;
if (getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true)
{
const auto nextThread = ++runnableList_.begin();
const auto nextThreadPriority = nextThread->get().getPriority();
// thread with same priority available?
if (getCurrentThreadControlBlock().getPriority() == nextThreadPriority)
return true; // switch context to do round-robin scheduling
}
return false;
}
void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator)
{
runnableList_.sortedSplice(*iterator->get().getList(), iterator);
iterator->get().getRoundRobinQuantum().reset();
}
} // namespace scheduler
} // namespace distortos
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: appmain.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: hr $ $Date: 2004-02-03 19:53:21 $
*
* 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): _______________________________________
*
*
************************************************************************/
//#define TF_NEWDESKTOP
#define _SDINTERN_HXX
#pragma hdrstop
#ifndef _PVER_HXX //autogen
#include <svtools/pver.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#if SUPD<613//MUSTINI
#ifndef _SFXINIMGR_HXX //autogen
#include <svtools/iniman.hxx>
#endif
#endif
#ifndef _CSTITEM_HXX //autogen
#include <svtools/cstitem.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX
#include <svtools/startoptions.hxx>
#endif
#include <svtools/itempool.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/helpopt.hxx>
#include <vos/process.hxx>
#include "appimp.hxx"
#include "sfxtypes.hxx"
#include "appdata.hxx"
#include "docfac.hxx"
#include "app.hxx"
#include "arrdecl.hxx"
#include "dispatch.hxx"
#include "sfxresid.hxx"
#include "interno.hxx"
#include "fcontnr.hxx"
#include "viewsh.hxx"
#include "intro.hxx"
#include "msgpool.hxx"
#include "cfgmgr.hxx"
#include "accmgr.hxx"
#include "mnumgr.hxx"
#include "stbmgr.hxx"
#include "imgmgr.hxx"
#include "appuno.hxx"
#include "objuno.hxx"
#include "app.hrc"
#include "docfile.hxx"
#if SUPD<613//MUSTINI
#include "inimgr.hxx"
#endif
#ifdef WNT
#include <tools/svwin.h>
#endif
#ifdef UNX
#define stricmp(a,b) strcmp(a,b)
#endif
//===================================================================
/*DBG_NAME(SfxAppMainIntro);
DBG_NAME(SfxAppMainSO_Init);
DBG_NAME(SfxAppMainAppRes);
DBG_NAME(SfxAppMainInit0);
DBG_NAME(SfxAppMainCreateAppWin);
DBG_NAME(SfxAppMainInit1);
DBG_NAME(SfxAppMainCfgMgr);
DBG_NAME(SfxAppMainInitController);
DBG_NAME(SfxAppMainInitException);
DBG_NAME(SfxAppMainRegisterIF);
DBG_NAME(SfxAppMainInit);
DBG_NAME(SfxAppMainLoadBasMgr);
DBG_NAME(SfxAppMainSbxInit);*/
DBG_NAME(SfxAppMainNewMenu);
DBG_NAME(SfxAppMainBmkMenu);
DBG_NAME(SfxAppMainWizMenu);
DBG_NAME(SfxAppMainOLEReg);
DBG_NAME(SfxAppMainCHAOSReg);
/*DBG_NAME(SfxAppMainInitDispatcher);
DBG_NAME(SfxAppMainLoadConfig);
DBG_NAME(SfxAppMainInitAppWin);
DBG_NAME(SfxAppMainAppEvents);*/
//===================================================================
#define SFX_TEMPNAMEBASE_DIR "soffice.tmp"
#define SFX_KEY_TEMPNAMEBASE "Temp-Dir"
//===================================================================
#pragma code_seg("STATICS")
static SfxVoidItem aStaticDefault(1);
#pragma code_seg()
static SfxPoolItem* aStaticDefaults[1] =
{
&aStaticDefault
};
#ifdef TF_POOLABLE
static SfxItemInfo __READONLY_DATA aItemInfos[] =
{
{ 0, 0 }
};
#endif
//===================================================================
typedef Link* LinkPtr;
SV_DECL_PTRARR(SfxInitLinkList, LinkPtr, 4, 4);
TYPEINIT1(SfxSysChangeHint, SfxHint);
TYPEINIT2(SfxApplication,SfxShell,SfxBroadcaster);
//--------------------------------------------------------------------
void SfxApplication::Init
(
)
/* [Beschreibung]
Diese virtuelle Methode wird vom SFx aus Application:a:Main() gerufen,
bevor Execute() ausgef"uhrt wird und
- das Intro bereits angezeigt ist,
- das Applikationsfenster exisitiert, aber noch hidden ist,
- die Bindings bereits existieren (Controller sind anmeldbar),
- der Ini- und Config-Manager bereits existiert,
- die Standard-Controller bereits exisitieren,
- die SFx-Shells ihre Interfaces bereits registriert haben.
[Querverweise]
<SfxApplication::Exit()>
<SfxApplication::OpenClients()>
*/
{
#ifdef DDE_AVAILABLE
#ifdef PRODUCT
InitializeDde();
#else
if( !InitializeDde() )
{
ByteString aStr( "Kein DDE-Service moeglich. Fehler: " );
if( GetDdeService() )
aStr += GetDdeService()->GetError();
else
aStr += '?';
DBG_ASSERT( sal_False, aStr.GetBuffer() )
}
#endif
#endif
}
//--------------------------------------------------------------------
void SfxApplication::Exit()
/* [Beschreibung]
Diese virtuelle Methode wird vom SFx aus Application::Main() gerufen,
nachdem Execute() beendet ist und
- die Konfiguration (SfxConfigManager) bereits gespeichert wurde,
- die Fensterpostionen etc. in den SfxIniManager geschrieben wurden,
- das Applikationsfenster noch existiert, aber hidden ist
- s"amtliche Dokumente und deren Views bereits geschlossen sind.
- Dispatcher, Bindings etc. bereits zerst"ort sind
[Querverweise]
<SfxApplication::Init(int,char*[])>
*/
{
}
//---------------------------------------------------------------------------
void SfxApplication::PreInit( )
{
}
USHORT SfxApplication::ParseCommandLine_Impl()
{
USHORT nEvents = 0; // return value ( event mask )
BOOL bPrintEvent = FALSE;
BOOL bOpenEvent = TRUE;
::vos::OExtCommandLine aCmdLine;
USHORT nCount = aCmdLine.getCommandArgCount();
for( USHORT i=0; i < nCount; i++ )
{
String aArg;
::rtl::OUString aDummy;
aCmdLine.getCommandArg( i, aDummy );
aArg = aDummy;
if ( aArg.EqualsIgnoreCaseAscii("-minimized") == sal_True )
pAppData_Impl->bMinimized = TRUE;
else if ( aArg.EqualsIgnoreCaseAscii("-invisible") == sal_True )
pAppData_Impl->bInvisible = TRUE;
else if ( aArg.EqualsIgnoreCaseAscii("-embedding") == sal_True )
pAppData_Impl->nAppEvent |= DISPATCH_SERVER;
else if ( aArg.EqualsIgnoreCaseAscii("-bean") == sal_True )
{
pAppData_Impl->bBean = TRUE;
pAppData_Impl->bInvisible = TRUE;
}
else if ( aArg.EqualsIgnoreCaseAscii("-plugin") == sal_True )
{
pAppData_Impl->bBean = TRUE;
pAppData_Impl->bInvisible = TRUE;
pAppData_Impl->bPlugged = TRUE;
}
else if ( aArg.EqualsIgnoreCaseAscii("-server") )
pAppData_Impl->bServer = true;
else if ( aArg.CompareIgnoreCaseToAscii("-portal,",
RTL_CONSTASCII_LENGTH(
"-portal,"))
== COMPARE_EQUAL )
pAppData_Impl->aPortalConnect
= aArg.Copy(RTL_CONSTASCII_LENGTH("-portal,"));
const xub_Unicode* pArg = aArg.GetBuffer();
// Erstmal nur mit -, da unter Unix Dateinmane auch mit Slasch anfangen koennen
if ( (*pArg == '-') /* || (*pArg == '/') */ )
{
pArg++;
// Ein Schalter
if ( (*pArg == 'p') || (*pArg == 'P') )
{
bPrintEvent = TRUE;
bOpenEvent = FALSE; // Ab hier keine OpenEvents mehr
}
}
else
{
// Dies wird als Dateiname interpretiert
if ( bOpenEvent )
{
// Open Event anhaengen
if ( pAppData_Impl->aOpenList.Len() )
pAppData_Impl->aOpenList += APPEVENT_PARAM_DELIMITER;
pAppData_Impl->aOpenList += aArg;
}
else if ( bPrintEvent )
{
// Print Event anhaengen
if( pAppData_Impl->aPrintList.Len() )
pAppData_Impl->aPrintList += APPEVENT_PARAM_DELIMITER;
pAppData_Impl->aPrintList += aArg;
}
}
}
if ( pAppData_Impl->aOpenList.Len() )
nEvents |= DISPATCH_OPEN;
if ( pAppData_Impl->aPrintList.Len() )
nEvents |= DISPATCH_PRINT;
return nEvents;
}
//---------------------------------------------------------------------------
void SfxApplication::InitLabelResMgr( const char* pLabelPrefix )
{
// Label-DLL mit diversen Resourcen fuer OEM-Ver. etc. (Intro, Titel, About)
pAppData_Impl->bBean = FALSE;
pAppData_Impl->nAppEvent = ParseCommandLine_Impl();
if ( pLabelPrefix )
{
// versuchen, die Label-DLL zu erzeugen
pAppData_Impl->pLabelResMgr = CreateResManager( pLabelPrefix );
// keine separate Label-DLL vorhanden?
if ( !pAppData_Impl->pLabelResMgr )
// dann den ResMgr vom Executable verwenden
pAppData_Impl->pLabelResMgr = new ResMgr;
}
else
{
pAppData_Impl->bBean = TRUE;
pAppData_Impl->bInvisible = TRUE;
}
// merken, falls Applikation normal gestartet wurde
if ( 0 == pAppData_Impl->nAppEvent || DISPATCH_OPEN == pAppData_Impl->nAppEvent )
pAppData_Impl->bDirectAliveCount = TRUE;
}
void SfxApplication::Main( )
{
}
//--------------------------------------------------------------------
#if defined( MAC )
void InstallAppleScriptHdl();
#endif
//-------------------------------------------------------------------------
void SfxApplication::InsertLateInitHdl(const Link& rLink)
{
if ( Application::IsInExecute() )
Application::PostUserEvent( rLink );
else
{
if ( !pAppData_Impl->pInitLinkList )
pAppData_Impl->pInitLinkList = new SfxInitLinkList;
Link *pLink = new Link;
*pLink = rLink;
USHORT nCount = ( USHORT ) pAppData_Impl->pInitLinkList->Count();
pAppData_Impl->pInitLinkList->Insert(pLink, nCount);
}
}
void SfxApplication::ForcePendingInitFactories()
{
List& rList = Get_Impl()->aPendingInitFactories;
USHORT nPos = (USHORT) rList.Count();
#if LATEINIT
DBG_ASSERT( !nPos, "Filter nicht im LateInit" );
#endif
while( nPos = rList.Count() )
{
SfxObjectFactory* pFac = (SfxObjectFactory*)rList.Remove( --nPos );
pFac->DoInitFactory();
}
}
//-------------------------------------------------------------------------
IMPL_LINK( SfxApplication, LateInitTimerHdl_Impl, void*, pvoid)
{
if ( !SfxViewFrame::GetFirst( 0,0,FALSE ) )
{
pAppData_Impl->aLateInitTimer.Start();
return 0;
}
// Ersten Link aus der Liste holen und ausf"uhren
Link *pLink = (*pAppData_Impl->pInitLinkList)[0];
pLink->Call(0);
// Link entfernen
pAppData_Impl->pInitLinkList->Remove(0);
delete pLink;
// Timer wieder starten, wenn noch weitere Links da sind
if ( pAppData_Impl->pInitLinkList->Count() )
pAppData_Impl->aLateInitTimer.Start();
else
{
// LateInit ist fertig
DELETEZ (pAppData_Impl->pInitLinkList);
#if SUPD<613//MUSTINI
pAppIniMgr->ResetLock();
#endif
}
return 0;
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
SfxFilterMatcher& SfxApplication::GetFilterMatcher()
{
if( !pAppData_Impl->pMatcher )
{
pAppData_Impl->pMatcher = new SfxFilterMatcher();
URIHelper::SetMaybeFileHdl( STATIC_LINK(
pAppData_Impl->pMatcher, SfxFilterMatcher, MaybeFileHdl_Impl ) );
}
return *pAppData_Impl->pMatcher;
}<commit_msg>INTEGRATION: CWS layoutmanager (1.14.124); FILE MERGED 2004/02/19 17:08:03 cd 1.14.124.4: RESYNC: (1.16-1.17); FILE MERGED 2004/01/29 19:47:46 cd 1.14.124.3: RESYNC: (1.15-1.16); FILE MERGED 2003/10/06 11:49:24 cd 1.14.124.2: RESYNC: (1.14-1.15); FILE MERGED 2003/08/20 16:05:05 cd 1.14.124.1: 111899# Framework based user interface preparation<commit_after>/*************************************************************************
*
* $RCSfile: appmain.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: kz $ $Date: 2004-02-25 15:41:14 $
*
* 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): _______________________________________
*
*
************************************************************************/
//#define TF_NEWDESKTOP
#define _SDINTERN_HXX
#pragma hdrstop
#ifndef _PVER_HXX //autogen
#include <svtools/pver.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#if SUPD<613//MUSTINI
#ifndef _SFXINIMGR_HXX //autogen
#include <svtools/iniman.hxx>
#endif
#endif
#ifndef _CSTITEM_HXX //autogen
#include <svtools/cstitem.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX
#include <svtools/startoptions.hxx>
#endif
#include <svtools/itempool.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/helpopt.hxx>
#include <vos/process.hxx>
#include <framework/sfxhelperfunctions.hxx>
#include "appimp.hxx"
#include "sfxtypes.hxx"
#include "appdata.hxx"
#include "docfac.hxx"
#include "app.hxx"
#include "arrdecl.hxx"
#include "dispatch.hxx"
#include "sfxresid.hxx"
#include "interno.hxx"
#include "fcontnr.hxx"
#include "viewsh.hxx"
#include "intro.hxx"
#include "msgpool.hxx"
#include "cfgmgr.hxx"
#include "accmgr.hxx"
#include "mnumgr.hxx"
#include "stbmgr.hxx"
#include "imgmgr.hxx"
#include "appuno.hxx"
#include "objuno.hxx"
#include "app.hrc"
#include "docfile.hxx"
#include "workwin.hxx"
#if SUPD<613//MUSTINI
#include "inimgr.hxx"
#endif
#ifdef WNT
#include <tools/svwin.h>
#endif
#ifdef UNX
#define stricmp(a,b) strcmp(a,b)
#endif
//===================================================================
/*DBG_NAME(SfxAppMainIntro);
DBG_NAME(SfxAppMainSO_Init);
DBG_NAME(SfxAppMainAppRes);
DBG_NAME(SfxAppMainInit0);
DBG_NAME(SfxAppMainCreateAppWin);
DBG_NAME(SfxAppMainInit1);
DBG_NAME(SfxAppMainCfgMgr);
DBG_NAME(SfxAppMainInitController);
DBG_NAME(SfxAppMainInitException);
DBG_NAME(SfxAppMainRegisterIF);
DBG_NAME(SfxAppMainInit);
DBG_NAME(SfxAppMainLoadBasMgr);
DBG_NAME(SfxAppMainSbxInit);*/
DBG_NAME(SfxAppMainNewMenu);
DBG_NAME(SfxAppMainBmkMenu);
DBG_NAME(SfxAppMainWizMenu);
DBG_NAME(SfxAppMainOLEReg);
DBG_NAME(SfxAppMainCHAOSReg);
/*DBG_NAME(SfxAppMainInitDispatcher);
DBG_NAME(SfxAppMainLoadConfig);
DBG_NAME(SfxAppMainInitAppWin);
DBG_NAME(SfxAppMainAppEvents);*/
//===================================================================
#define SFX_TEMPNAMEBASE_DIR "soffice.tmp"
#define SFX_KEY_TEMPNAMEBASE "Temp-Dir"
//===================================================================
#pragma code_seg("STATICS")
static SfxVoidItem aStaticDefault(1);
#pragma code_seg()
static SfxPoolItem* aStaticDefaults[1] =
{
&aStaticDefault
};
#ifdef TF_POOLABLE
static SfxItemInfo __READONLY_DATA aItemInfos[] =
{
{ 0, 0 }
};
#endif
//===================================================================
typedef Link* LinkPtr;
SV_DECL_PTRARR(SfxInitLinkList, LinkPtr, 4, 4);
TYPEINIT1(SfxSysChangeHint, SfxHint);
TYPEINIT2(SfxApplication,SfxShell,SfxBroadcaster);
//--------------------------------------------------------------------
void SfxApplication::Init
(
)
/* [Beschreibung]
Diese virtuelle Methode wird vom SFx aus Application:a:Main() gerufen,
bevor Execute() ausgef"uhrt wird und
- das Intro bereits angezeigt ist,
- das Applikationsfenster exisitiert, aber noch hidden ist,
- die Bindings bereits existieren (Controller sind anmeldbar),
- der Ini- und Config-Manager bereits existiert,
- die Standard-Controller bereits exisitieren,
- die SFx-Shells ihre Interfaces bereits registriert haben.
[Querverweise]
<SfxApplication::Exit()>
<SfxApplication::OpenClients()>
*/
{
#ifdef DDE_AVAILABLE
#ifdef PRODUCT
InitializeDde();
#else
if( !InitializeDde() )
{
ByteString aStr( "Kein DDE-Service moeglich. Fehler: " );
if( GetDdeService() )
aStr += GetDdeService()->GetError();
else
aStr += '?';
DBG_ASSERT( sal_False, aStr.GetBuffer() )
}
#endif
#endif
SetToolBoxCreator( CreateToolBox );
}
//--------------------------------------------------------------------
void SfxApplication::Exit()
/* [Beschreibung]
Diese virtuelle Methode wird vom SFx aus Application::Main() gerufen,
nachdem Execute() beendet ist und
- die Konfiguration (SfxConfigManager) bereits gespeichert wurde,
- die Fensterpostionen etc. in den SfxIniManager geschrieben wurden,
- das Applikationsfenster noch existiert, aber hidden ist
- s"amtliche Dokumente und deren Views bereits geschlossen sind.
- Dispatcher, Bindings etc. bereits zerst"ort sind
[Querverweise]
<SfxApplication::Init(int,char*[])>
*/
{
}
//---------------------------------------------------------------------------
void SfxApplication::PreInit( )
{
}
USHORT SfxApplication::ParseCommandLine_Impl()
{
USHORT nEvents = 0; // return value ( event mask )
BOOL bPrintEvent = FALSE;
BOOL bOpenEvent = TRUE;
::vos::OExtCommandLine aCmdLine;
USHORT nCount = aCmdLine.getCommandArgCount();
for( USHORT i=0; i < nCount; i++ )
{
String aArg;
::rtl::OUString aDummy;
aCmdLine.getCommandArg( i, aDummy );
aArg = aDummy;
if ( aArg.EqualsIgnoreCaseAscii("-minimized") == sal_True )
pAppData_Impl->bMinimized = TRUE;
else if ( aArg.EqualsIgnoreCaseAscii("-invisible") == sal_True )
pAppData_Impl->bInvisible = TRUE;
else if ( aArg.EqualsIgnoreCaseAscii("-embedding") == sal_True )
pAppData_Impl->nAppEvent |= DISPATCH_SERVER;
else if ( aArg.EqualsIgnoreCaseAscii("-bean") == sal_True )
{
pAppData_Impl->bBean = TRUE;
pAppData_Impl->bInvisible = TRUE;
}
else if ( aArg.EqualsIgnoreCaseAscii("-plugin") == sal_True )
{
pAppData_Impl->bBean = TRUE;
pAppData_Impl->bInvisible = TRUE;
pAppData_Impl->bPlugged = TRUE;
}
else if ( aArg.EqualsIgnoreCaseAscii("-server") )
pAppData_Impl->bServer = true;
else if ( aArg.CompareIgnoreCaseToAscii("-portal,",
RTL_CONSTASCII_LENGTH(
"-portal,"))
== COMPARE_EQUAL )
pAppData_Impl->aPortalConnect
= aArg.Copy(RTL_CONSTASCII_LENGTH("-portal,"));
const xub_Unicode* pArg = aArg.GetBuffer();
// Erstmal nur mit -, da unter Unix Dateinmane auch mit Slasch anfangen koennen
if ( (*pArg == '-') /* || (*pArg == '/') */ )
{
pArg++;
// Ein Schalter
if ( (*pArg == 'p') || (*pArg == 'P') )
{
bPrintEvent = TRUE;
bOpenEvent = FALSE; // Ab hier keine OpenEvents mehr
}
}
else
{
// Dies wird als Dateiname interpretiert
if ( bOpenEvent )
{
// Open Event anhaengen
if ( pAppData_Impl->aOpenList.Len() )
pAppData_Impl->aOpenList += APPEVENT_PARAM_DELIMITER;
pAppData_Impl->aOpenList += aArg;
}
else if ( bPrintEvent )
{
// Print Event anhaengen
if( pAppData_Impl->aPrintList.Len() )
pAppData_Impl->aPrintList += APPEVENT_PARAM_DELIMITER;
pAppData_Impl->aPrintList += aArg;
}
}
}
if ( pAppData_Impl->aOpenList.Len() )
nEvents |= DISPATCH_OPEN;
if ( pAppData_Impl->aPrintList.Len() )
nEvents |= DISPATCH_PRINT;
return nEvents;
}
//---------------------------------------------------------------------------
void SfxApplication::InitLabelResMgr( const char* pLabelPrefix )
{
// Label-DLL mit diversen Resourcen fuer OEM-Ver. etc. (Intro, Titel, About)
pAppData_Impl->bBean = FALSE;
pAppData_Impl->nAppEvent = ParseCommandLine_Impl();
if ( pLabelPrefix )
{
// versuchen, die Label-DLL zu erzeugen
pAppData_Impl->pLabelResMgr = CreateResManager( pLabelPrefix );
// keine separate Label-DLL vorhanden?
if ( !pAppData_Impl->pLabelResMgr )
// dann den ResMgr vom Executable verwenden
pAppData_Impl->pLabelResMgr = new ResMgr;
}
else
{
pAppData_Impl->bBean = TRUE;
pAppData_Impl->bInvisible = TRUE;
}
// merken, falls Applikation normal gestartet wurde
if ( 0 == pAppData_Impl->nAppEvent || DISPATCH_OPEN == pAppData_Impl->nAppEvent )
pAppData_Impl->bDirectAliveCount = TRUE;
}
void SfxApplication::Main( )
{
}
//--------------------------------------------------------------------
#if defined( MAC )
void InstallAppleScriptHdl();
#endif
//-------------------------------------------------------------------------
void SfxApplication::InsertLateInitHdl(const Link& rLink)
{
if ( Application::IsInExecute() )
Application::PostUserEvent( rLink );
else
{
if ( !pAppData_Impl->pInitLinkList )
pAppData_Impl->pInitLinkList = new SfxInitLinkList;
Link *pLink = new Link;
*pLink = rLink;
USHORT nCount = ( USHORT ) pAppData_Impl->pInitLinkList->Count();
pAppData_Impl->pInitLinkList->Insert(pLink, nCount);
}
}
void SfxApplication::ForcePendingInitFactories()
{
List& rList = Get_Impl()->aPendingInitFactories;
USHORT nPos = (USHORT) rList.Count();
#if LATEINIT
DBG_ASSERT( !nPos, "Filter nicht im LateInit" );
#endif
while( nPos = rList.Count() )
{
SfxObjectFactory* pFac = (SfxObjectFactory*)rList.Remove( --nPos );
pFac->DoInitFactory();
}
}
//-------------------------------------------------------------------------
IMPL_LINK( SfxApplication, LateInitTimerHdl_Impl, void*, pvoid)
{
if ( !SfxViewFrame::GetFirst( 0,0,FALSE ) )
{
pAppData_Impl->aLateInitTimer.Start();
return 0;
}
// Ersten Link aus der Liste holen und ausf"uhren
Link *pLink = (*pAppData_Impl->pInitLinkList)[0];
pLink->Call(0);
// Link entfernen
pAppData_Impl->pInitLinkList->Remove(0);
delete pLink;
// Timer wieder starten, wenn noch weitere Links da sind
if ( pAppData_Impl->pInitLinkList->Count() )
pAppData_Impl->aLateInitTimer.Start();
else
{
// LateInit ist fertig
DELETEZ (pAppData_Impl->pInitLinkList);
#if SUPD<613//MUSTINI
pAppIniMgr->ResetLock();
#endif
}
return 0;
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
SfxFilterMatcher& SfxApplication::GetFilterMatcher()
{
if( !pAppData_Impl->pMatcher )
{
pAppData_Impl->pMatcher = new SfxFilterMatcher();
URIHelper::SetMaybeFileHdl( STATIC_LINK(
pAppData_Impl->pMatcher, SfxFilterMatcher, MaybeFileHdl_Impl ) );
}
return *pAppData_Impl->pMatcher;
}<|endoftext|> |
<commit_before>#pragma once
#include <ContinuousArtScroller.h>
#include <MeshFactory.h>
#include <MeshInterface.h>
#include <Texture.h>
#include <sstream>
#include <MY_ResourceManager.h>
ContinuousArtScroller::ContinuousArtScroller(std::string _fileDir, ComponentShaderBase * _shader) :
ArtLayer(dynamic_cast<ShaderComponentReplace *>(_shader->getComponentAt(2))),
fileDir(_fileDir),
imageId(1),
imageCount(0),
progress(0),
numPlanes(4)
{
while (true){
++imageCount;
std::stringstream src;
src << "assets/textures/" << fileDir << "/";
if(imageCount < 10){
src << "0";
}
src << imageCount << ".png";
if (!FileUtils::fileExists(src.str())){
break;
}
Texture * texture = new Texture(src.str(), true, false);
texture->loadImageData();
images.push_back(texture);
}
MeshInterface * m = MeshFactory::getPlaneMesh();
m->configureDefaultVertexAttributes(_shader);
m->pushTexture2D(MY_ResourceManager::scenario->defaultTexture->texture);
m->scaleModeMag = m->scaleModeMin = GL_NEAREST;
for(unsigned long int i = 0; i < numPlanes; ++i){
MeshEntity * plane = new MeshEntity(MeshFactory::getPlaneMesh(), _shader);
loadTexOntoPlane(i+1, plane);
plane->mesh->scaleModeMag = plane->mesh->scaleModeMin = GL_NEAREST;
plane->meshTransform->addChild(m)->translate(0, -1, 0);
childTransform->addChild(plane)->translate(i,0,0);
planes.push_back(plane);
}
m->referenceCount += numPlanes;
backPlane = 0;
frontPlane = numPlanes-1;
}
ContinuousArtScroller::~ContinuousArtScroller(){
// remove any active textures so they aren't delete twice
for(MeshEntity * e : planes){
while(e->mesh->textures.size() > 0){
e->mesh->textures.at(0)->unload();
e->mesh->removeTextureAt(0);
}
}
// delete textures
while (images.size() > 0){
delete images.back();
images.pop_back();
}
}
void ContinuousArtScroller::cycle(signed long int _delta){
imageId += _delta;
if (_delta > 0){
loadTexOntoPlane(imageId+(numPlanes/2+1), planes.at(backPlane));
planes.at(backPlane)->firstParent()->translate(numPlanes, 0, 0);
frontPlane = backPlane;
++backPlane;
if(backPlane >= numPlanes){
backPlane = 0;
}
}else{
loadTexOntoPlane(imageId, planes.at(frontPlane));
planes.at(frontPlane)->firstParent()->translate(-(signed long int)numPlanes, 0, 0);
backPlane = frontPlane;
--frontPlane;
if(frontPlane >= numPlanes){
frontPlane = numPlanes-1;
}
}
}
void ContinuousArtScroller::loadTexOntoPlane(unsigned long int _texId, MeshEntity * _plane){
while(_plane->mesh->textures.size() > 0){
_plane->mesh->textures.at(0)->unload();
_plane->mesh->removeTextureAt(0);
}
if (_texId < images.size()){
_plane->mesh->pushTexture2D(images.at(_texId));
}else{
_plane->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("DEFAULT")->texture);
}
_plane->mesh->textures.at(0)->load();
}
void ContinuousArtScroller::update(Step * _step){
while (imageId - progress < -(signed long int)numPlanes/2){
cycle(1);
}while (imageId - progress > -(signed long int)numPlanes/2+1){
cycle(-1);
}
Entity::update(_step);
}<commit_msg>no mipmaps on art layers<commit_after>#pragma once
#include <ContinuousArtScroller.h>
#include <MeshFactory.h>
#include <MeshInterface.h>
#include <Texture.h>
#include <sstream>
#include <MY_ResourceManager.h>
ContinuousArtScroller::ContinuousArtScroller(std::string _fileDir, ComponentShaderBase * _shader) :
ArtLayer(dynamic_cast<ShaderComponentReplace *>(_shader->getComponentAt(2))),
fileDir(_fileDir),
imageId(1),
imageCount(0),
progress(0),
numPlanes(4)
{
while (true){
++imageCount;
std::stringstream src;
src << "assets/textures/" << fileDir << "/";
if(imageCount < 10){
src << "0";
}
src << imageCount << ".png";
if (!FileUtils::fileExists(src.str())){
break;
}
Texture * texture = new Texture(src.str(), true, false, false);
texture->loadImageData();
images.push_back(texture);
}
MeshInterface * m = MeshFactory::getPlaneMesh();
m->configureDefaultVertexAttributes(_shader);
m->pushTexture2D(MY_ResourceManager::scenario->defaultTexture->texture);
m->scaleModeMag = m->scaleModeMin = GL_NEAREST;
for(unsigned long int i = 0; i < numPlanes; ++i){
MeshEntity * plane = new MeshEntity(MeshFactory::getPlaneMesh(), _shader);
loadTexOntoPlane(i+1, plane);
plane->mesh->scaleModeMag = plane->mesh->scaleModeMin = GL_NEAREST;
plane->meshTransform->addChild(m)->translate(0, -1, 0);
childTransform->addChild(plane)->translate(i,0,0);
planes.push_back(plane);
}
m->referenceCount += numPlanes;
backPlane = 0;
frontPlane = numPlanes-1;
}
ContinuousArtScroller::~ContinuousArtScroller(){
// remove any active textures so they aren't delete twice
for(MeshEntity * e : planes){
while(e->mesh->textures.size() > 0){
e->mesh->textures.at(0)->unload();
e->mesh->removeTextureAt(0);
}
}
// delete textures
while (images.size() > 0){
delete images.back();
images.pop_back();
}
}
void ContinuousArtScroller::cycle(signed long int _delta){
imageId += _delta;
if (_delta > 0){
loadTexOntoPlane(imageId+(numPlanes/2+1), planes.at(backPlane));
planes.at(backPlane)->firstParent()->translate(numPlanes, 0, 0);
frontPlane = backPlane;
++backPlane;
if(backPlane >= numPlanes){
backPlane = 0;
}
}else{
loadTexOntoPlane(imageId, planes.at(frontPlane));
planes.at(frontPlane)->firstParent()->translate(-(signed long int)numPlanes, 0, 0);
backPlane = frontPlane;
--frontPlane;
if(frontPlane >= numPlanes){
frontPlane = numPlanes-1;
}
}
}
void ContinuousArtScroller::loadTexOntoPlane(unsigned long int _texId, MeshEntity * _plane){
while(_plane->mesh->textures.size() > 0){
_plane->mesh->textures.at(0)->unload();
_plane->mesh->removeTextureAt(0);
}
if (_texId < images.size()){
_plane->mesh->pushTexture2D(images.at(_texId));
}else{
_plane->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("DEFAULT")->texture);
}
_plane->mesh->textures.at(0)->load();
}
void ContinuousArtScroller::update(Step * _step){
while (imageId - progress < -(signed long int)numPlanes/2){
cycle(1);
}while (imageId - progress > -(signed long int)numPlanes/2+1){
cycle(-1);
}
Entity::update(_step);
}<|endoftext|> |
<commit_before>/*
* This file is part of Maliit Plugins
*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <[email protected]>
*
* 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 Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "wordengine.h"
#include "spellchecker.h"
#ifdef HAVE_PRESAGE
#include <presage.h>
#endif
namespace MaliitKeyboard {
namespace Logic {
#ifdef HAVE_PRESAGE
class CandidatesCallback
: public PresageCallback
{
private:
const std::string& m_past_context;
const std::string m_empty;
public:
explicit CandidatesCallback(const std::string& past_context);
std::string get_past_stream() const;
std::string get_future_stream() const;
};
CandidatesCallback::CandidatesCallback(const std::string &past_context)
: m_past_context(past_context)
, m_empty()
{}
std::string CandidatesCallback::get_past_stream() const
{
return m_past_context;
}
std::string CandidatesCallback::get_future_stream() const
{
return m_empty;
}
#endif
class WordEnginePrivate
{
public:
QStringList candidates;
SpellChecker spell_checker;
#ifdef HAVE_PRESAGE
std::string candidates_context;
CandidatesCallback presage_candidates;
Presage presage;
#endif
explicit WordEnginePrivate();
};
WordEnginePrivate::WordEnginePrivate()
: candidates()
, spell_checker()
#ifdef HAVE_PRESAGE
, candidates_context()
, presage_candidates(CandidatesCallback(candidates_context))
, presage(&presage_candidates)
#endif
{}
WordEngine::WordEngine(QObject *parent)
: QObject(parent)
, d_ptr(new WordEnginePrivate)
{}
WordEngine::~WordEngine()
{}
void WordEngine::onTextChanged(const Model::SharedText &text)
{
if (text.isNull()) {
qWarning() << __PRETTY_FUNCTION__
<< "No text model specified.";
}
Q_D(WordEngine);
const QString &preedit(text->preedit());
if (preedit.isEmpty()) {
if (not d->candidates.isEmpty()) {
d->candidates.clear();
Q_EMIT candidatesUpdated(d->candidates);
}
return;
}
d->candidates.clear();
#ifdef HAVE_PRESAGE
// FIXME: Using surroundingLeft + preedit throws an exception in presage.
// Using only preedit for now.
const QString &context = preedit;
d->candidates_context = context.toStdString();
const std::vector<std::string> predictions = d->presage.predict();
// TODO: Fine-tune presage behaviour to also perform error correction, not just word prediction.
if (not context.isEmpty()) {
// FIXME: max_candidates should come from style, too:
const static unsigned int max_candidates = 7;
const int count(qMin<int>(predictions.size(), max_candidates));
for (int index = 0; index < count; ++index) {
const QString &prediction(QString::fromStdString(predictions.at(index)));
if (d->candidates.contains(prediction)) {
continue;
}
d->candidates.append(prediction);
}
}
#endif
if (d->candidates.isEmpty()) {
d->candidates.append(d->spell_checker.suggest(preedit, 5));
}
Q_EMIT candidatesUpdated(d->candidates);
}
}} // namespace Logic, MaliitKeyboard
<commit_msg>Set Presage config and use surrounding text<commit_after>/*
* This file is part of Maliit Plugins
*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <[email protected]>
*
* 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 Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "wordengine.h"
#include "spellchecker.h"
#include <iostream>
#ifdef HAVE_PRESAGE
#include <presage.h>
#endif
namespace MaliitKeyboard {
namespace Logic {
#ifdef HAVE_PRESAGE
class CandidatesCallback
: public PresageCallback
{
private:
const std::string& m_past_context;
const std::string m_empty;
public:
explicit CandidatesCallback(const std::string& past_context);
std::string get_past_stream() const;
std::string get_future_stream() const;
};
CandidatesCallback::CandidatesCallback(const std::string &past_context)
: m_past_context(past_context)
, m_empty()
{}
std::string CandidatesCallback::get_past_stream() const
{
return m_past_context;
}
std::string CandidatesCallback::get_future_stream() const
{
return m_empty;
}
#endif
class WordEnginePrivate
{
public:
QStringList candidates;
SpellChecker spell_checker;
#ifdef HAVE_PRESAGE
std::string candidates_context;
CandidatesCallback presage_candidates;
Presage presage;
#endif
explicit WordEnginePrivate();
};
WordEnginePrivate::WordEnginePrivate()
: candidates()
, spell_checker()
#ifdef HAVE_PRESAGE
, candidates_context()
, presage_candidates(CandidatesCallback(candidates_context))
, presage(&presage_candidates)
#endif
{
#ifdef HAVE_PRESAGE
presage.config("Presage.Selector.SUGGESTIONS", "6");
presage.config("Presage.Selector.REPEAT_SUGGESTIONS", "yes");
#endif
}
WordEngine::WordEngine(QObject *parent)
: QObject(parent)
, d_ptr(new WordEnginePrivate)
{}
WordEngine::~WordEngine()
{}
void WordEngine::onTextChanged(const Model::SharedText &text)
{
if (text.isNull()) {
qWarning() << __PRETTY_FUNCTION__
<< "No text model specified.";
}
Q_D(WordEngine);
const QString &preedit(text->preedit());
if (preedit.isEmpty()) {
if (not d->candidates.isEmpty()) {
d->candidates.clear();
Q_EMIT candidatesUpdated(d->candidates);
}
return;
}
d->candidates.clear();
#ifdef HAVE_PRESAGE
// FIXME: Using surroundingLeft + preedit throws an exception in presage.
// Using only preedit for now.
const QString &context = (text->surroundingLeft() + preedit);
d->candidates_context = context.toStdString();
const std::vector<std::string> predictions = d->presage.predict();
// TODO: Fine-tune presage behaviour to also perform error correction, not just word prediction.
if (not context.isEmpty()) {
// FIXME: max_candidates should come from style, too:
const static unsigned int max_candidates = 7;
const int count(qMin<int>(predictions.size(), max_candidates));
for (int index = 0; index < count; ++index) {
const QString &prediction(QString::fromStdString(predictions.at(index)));
if (d->candidates.contains(prediction)) {
continue;
}
d->candidates.append(prediction);
}
}
#endif
if (d->candidates.isEmpty()) {
d->candidates.append(d->spell_checker.suggest(preedit, 5));
}
Q_EMIT candidatesUpdated(d->candidates);
}
}} // namespace Logic, MaliitKeyboard
<|endoftext|> |
<commit_before>//===------------------------- incomplete_type.cpp --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// http://mentorembedded.github.io/cxx-abi/abi.html#rtti-layout
// Two abi::__pbase_type_info objects can always be compared for equality
// (i.e. of the types represented) or ordering by comparison of their name
// NTBS addresses. In addition, unless either or both have either of the
// incomplete flags set, equality can be tested by comparing the type_info
// addresses.
// RUN: %cxx %flags %compile_flags -c %s -o %t.one.o
// RUN: %cxx %flags %compile_flags -c %s -o %t.two.o -DTU_ONE
// RUN: %cxx %flags %link_flags -o %t.exe %t.one.o %t.two.o
// RUN: %exec %t.exe
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <typeinfo>
// Check that the addresses of the typeinfo differ but still compare equal
// via their NTBS.
inline void
AssertIncompleteTypeInfoEquals(std::type_info const& LHS, std::type_info const& RHS)
{
assert(&LHS != &RHS);
assert(strcmp(LHS.name(), RHS.name()) == 0);
}
struct NeverDefined;
void ThrowNeverDefinedMP();
std::type_info const& ReturnTypeInfoNeverDefinedMP();
struct IncompleteAtThrow;
void ThrowIncompleteMP();
void ThrowIncompletePP();
void ThrowIncompletePMP();
std::type_info const& ReturnTypeInfoIncompleteMP();
std::type_info const& ReturnTypeInfoIncompletePP();
struct CompleteAtThrow;
void ThrowCompleteMP();
void ThrowCompletePP();
void ThrowCompletePMP();
std::type_info const& ReturnTypeInfoCompleteMP();
std::type_info const& ReturnTypeInfoCompletePP();
void ThrowNullptr();
#ifndef TU_ONE
void ThrowNeverDefinedMP() { throw (int NeverDefined::*)nullptr; }
std::type_info const& ReturnTypeInfoNeverDefinedMP() { return typeid(int NeverDefined::*); }
void ThrowIncompleteMP() { throw (int IncompleteAtThrow::*)nullptr; }
void ThrowIncompletePP() { throw (IncompleteAtThrow**)nullptr; }
void ThrowIncompletePMP() { throw (int IncompleteAtThrow::**)nullptr; }
std::type_info const& ReturnTypeInfoIncompleteMP() { return typeid(int IncompleteAtThrow::*); }
std::type_info const& ReturnTypeInfoIncompletePP() { return typeid(IncompleteAtThrow**); }
struct CompleteAtThrow {};
void ThrowCompleteMP() { throw (int CompleteAtThrow::*)nullptr; }
void ThrowCompletePP() { throw (CompleteAtThrow**)nullptr; }
void ThrowCompletePMP() { throw (int CompleteAtThrow::**)nullptr; }
std::type_info const& ReturnTypeInfoCompleteMP() { return typeid(int CompleteAtThrow::*); }
std::type_info const& ReturnTypeInfoCompletePP() { return typeid(CompleteAtThrow**); }
void ThrowNullptr() { throw nullptr; }
#else
struct IncompleteAtThrow {};
int main() {
AssertIncompleteTypeInfoEquals(ReturnTypeInfoNeverDefinedMP(), typeid(int NeverDefined::*));
try {
ThrowNeverDefinedMP();
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (int NeverDefined::*) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoIncompleteMP(), typeid(int IncompleteAtThrow::*));
try {
ThrowIncompleteMP();
assert(false);
} catch (CompleteAtThrow**) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoIncompletePP(), typeid(IncompleteAtThrow**));
try {
ThrowIncompletePP();
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (IncompleteAtThrow**) {}
try {
ThrowIncompletePMP();
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::**) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoCompleteMP(), typeid(int CompleteAtThrow::*));
try {
ThrowCompleteMP();
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (CompleteAtThrow**) {
assert(false);
} catch (int CompleteAtThrow::*) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoCompletePP(), typeid(CompleteAtThrow**));
try {
ThrowCompletePP();
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (CompleteAtThrow**) {}
try {
ThrowCompletePMP();
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (CompleteAtThrow**) {
assert(false);
} catch (int CompleteAtThrow::**) {}
#if __cplusplus >= 201103L
// Catch nullptr as complete type
try {
ThrowNullptr();
} catch (int IncompleteAtThrow::*) {}
// Catch nullptr as an incomplete type
try {
ThrowNullptr();
} catch (int CompleteAtThrow::*) {}
// Catch nullptr as a type that is never complete.
try {
ThrowNullptr();
} catch (int NeverDefined::*) {}
#endif
}
#endif
<commit_msg>Fix link flags order in RUN command.<commit_after>//===------------------------- incomplete_type.cpp --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// http://mentorembedded.github.io/cxx-abi/abi.html#rtti-layout
// Two abi::__pbase_type_info objects can always be compared for equality
// (i.e. of the types represented) or ordering by comparison of their name
// NTBS addresses. In addition, unless either or both have either of the
// incomplete flags set, equality can be tested by comparing the type_info
// addresses.
// RUN: %cxx %flags %compile_flags -c %s -o %t.one.o
// RUN: %cxx %flags %compile_flags -c %s -o %t.two.o -DTU_ONE
// RUN: %cxx %flags %t.one.o %t.two.o %link_flags -o %t.exe
// RUN: %exec %t.exe
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <typeinfo>
// Check that the addresses of the typeinfo differ but still compare equal
// via their NTBS.
inline void
AssertIncompleteTypeInfoEquals(std::type_info const& LHS, std::type_info const& RHS)
{
assert(&LHS != &RHS);
assert(strcmp(LHS.name(), RHS.name()) == 0);
}
struct NeverDefined;
void ThrowNeverDefinedMP();
std::type_info const& ReturnTypeInfoNeverDefinedMP();
struct IncompleteAtThrow;
void ThrowIncompleteMP();
void ThrowIncompletePP();
void ThrowIncompletePMP();
std::type_info const& ReturnTypeInfoIncompleteMP();
std::type_info const& ReturnTypeInfoIncompletePP();
struct CompleteAtThrow;
void ThrowCompleteMP();
void ThrowCompletePP();
void ThrowCompletePMP();
std::type_info const& ReturnTypeInfoCompleteMP();
std::type_info const& ReturnTypeInfoCompletePP();
void ThrowNullptr();
#ifndef TU_ONE
void ThrowNeverDefinedMP() { throw (int NeverDefined::*)nullptr; }
std::type_info const& ReturnTypeInfoNeverDefinedMP() { return typeid(int NeverDefined::*); }
void ThrowIncompleteMP() { throw (int IncompleteAtThrow::*)nullptr; }
void ThrowIncompletePP() { throw (IncompleteAtThrow**)nullptr; }
void ThrowIncompletePMP() { throw (int IncompleteAtThrow::**)nullptr; }
std::type_info const& ReturnTypeInfoIncompleteMP() { return typeid(int IncompleteAtThrow::*); }
std::type_info const& ReturnTypeInfoIncompletePP() { return typeid(IncompleteAtThrow**); }
struct CompleteAtThrow {};
void ThrowCompleteMP() { throw (int CompleteAtThrow::*)nullptr; }
void ThrowCompletePP() { throw (CompleteAtThrow**)nullptr; }
void ThrowCompletePMP() { throw (int CompleteAtThrow::**)nullptr; }
std::type_info const& ReturnTypeInfoCompleteMP() { return typeid(int CompleteAtThrow::*); }
std::type_info const& ReturnTypeInfoCompletePP() { return typeid(CompleteAtThrow**); }
void ThrowNullptr() { throw nullptr; }
#else
struct IncompleteAtThrow {};
int main() {
AssertIncompleteTypeInfoEquals(ReturnTypeInfoNeverDefinedMP(), typeid(int NeverDefined::*));
try {
ThrowNeverDefinedMP();
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (int NeverDefined::*) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoIncompleteMP(), typeid(int IncompleteAtThrow::*));
try {
ThrowIncompleteMP();
assert(false);
} catch (CompleteAtThrow**) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoIncompletePP(), typeid(IncompleteAtThrow**));
try {
ThrowIncompletePP();
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (IncompleteAtThrow**) {}
try {
ThrowIncompletePMP();
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::**) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoCompleteMP(), typeid(int CompleteAtThrow::*));
try {
ThrowCompleteMP();
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (CompleteAtThrow**) {
assert(false);
} catch (int CompleteAtThrow::*) {}
AssertIncompleteTypeInfoEquals(ReturnTypeInfoCompletePP(), typeid(CompleteAtThrow**));
try {
ThrowCompletePP();
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (CompleteAtThrow**) {}
try {
ThrowCompletePMP();
assert(false);
} catch (IncompleteAtThrow**) {
assert(false);
} catch (int IncompleteAtThrow::*) {
assert(false);
} catch (int CompleteAtThrow::*) {
assert(false);
} catch (CompleteAtThrow**) {
assert(false);
} catch (int CompleteAtThrow::**) {}
#if __cplusplus >= 201103L
// Catch nullptr as complete type
try {
ThrowNullptr();
} catch (int IncompleteAtThrow::*) {}
// Catch nullptr as an incomplete type
try {
ThrowNullptr();
} catch (int CompleteAtThrow::*) {}
// Catch nullptr as a type that is never complete.
try {
ThrowNullptr();
} catch (int NeverDefined::*) {}
#endif
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Erik Rigtorp <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <cstring>
#include <iostream>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <pcap/pcap.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int ifindex = 0;
int loopback = 0;
double speed = 1;
int ttl = -1;
int opt;
while ((opt = getopt(argc, argv, "i:ls:t:")) != -1) {
switch (opt) {
case 'i':
ifindex = if_nametoindex(optarg);
if (ifindex == 0) {
std::cerr << "if_nametoindex: " << strerror(errno) << std::endl;
return 1;
}
break;
case 'l':
loopback = 1;
break;
case 's':
speed = std::stod(optarg);
break;
case 't':
ttl = std::stoi(optarg);
break;
default:
std::cerr << "usage: " << argv[0]
<< " [-i iface] [-l] [-s speed] [-t ttl] pcap" << std::endl;
return 1;
}
}
if (optind >= argc) {
std::cerr << "usage: " << argv[0]
<< " [-i iface] [-l] [-s speed] [-t ttl] pcap" << std::endl;
return 1;
}
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
std::cerr << "socket: " << strerror(errno) << std::endl;
return 1;
}
if (ifindex != 0) {
ip_mreqn mreqn;
memset(&mreqn, 0, sizeof(mreqn));
mreqn.imr_ifindex = ifindex;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn)) ==
-1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (loopback != 0) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loopback,
sizeof(loopback)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (ttl != -1) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle = pcap_open_offline(argv[optind], errbuf);
if (handle == nullptr) {
std::cerr << "pcap_open: " << errbuf << std::endl;
return 1;
}
pcap_pkthdr header;
const u_char *p;
timeval tv = {0, 0};
while ((p = pcap_next(handle, &header))) {
if (header.len != header.caplen) {
continue;
}
auto eth = reinterpret_cast<const ether_header *>(p);
if (ntohs(eth->ether_type) != ETHERTYPE_IP) {
continue;
}
auto ip = reinterpret_cast<const iphdr *>(p + sizeof(ether_header));
if (ip->version != 4) {
continue;
}
if (ip->protocol != IPPROTO_UDP) {
continue;
}
auto udp = reinterpret_cast<const udphdr *>(p + sizeof(ether_header) +
ip->ihl * 4);
if (tv.tv_sec == 0) {
tv = header.ts;
}
timeval diff;
timersub(&header.ts, &tv, &diff);
usleep((diff.tv_sec * 1000000 + diff.tv_usec) * speed);
ssize_t len = ntohs(udp->len) - 8;
const u_char *d = &p[sizeof(ether_header) + ip->ihl * 4 + sizeof(udphdr)];
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = udp->dest;
addr.sin_addr = {ip->daddr};
auto n = sendto(fd, d, len, 0, reinterpret_cast<sockaddr *>(&addr),
sizeof(addr));
if (n != len) {
std::cerr << "sendto: " << strerror(errno) << std::endl;
return 1;
}
}
return 0;
}
<commit_msg>Add usage to executable<commit_after>/*
Copyright (c) 2016 Erik Rigtorp <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <cstring>
#include <iostream>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <pcap/pcap.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
static const char usage[] =
" [-i iface] [-l] [-s speed] [-t ttl] pcap\n"
"\n"
" -i iface interface to send packets through\n"
" -l enable loopback\n"
" -s speed replay speed relative to pcap timestamps\n"
" -t ttl packet ttl";
int ifindex = 0;
int loopback = 0;
double speed = 1;
int ttl = -1;
int opt;
while ((opt = getopt(argc, argv, "i:ls:t:")) != -1) {
switch (opt) {
case 'i':
ifindex = if_nametoindex(optarg);
if (ifindex == 0) {
std::cerr << "if_nametoindex: " << strerror(errno) << std::endl;
return 1;
}
break;
case 'l':
loopback = 1;
break;
case 's':
speed = std::stod(optarg);
break;
case 't':
ttl = std::stoi(optarg);
break;
default:
std::cerr << "usage: " << argv[0] << usage << std::endl;
return 1;
}
}
if (optind >= argc) {
std::cerr << "usage: " << argv[0] << usage << std::endl;
return 1;
}
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
std::cerr << "socket: " << strerror(errno) << std::endl;
return 1;
}
if (ifindex != 0) {
ip_mreqn mreqn;
memset(&mreqn, 0, sizeof(mreqn));
mreqn.imr_ifindex = ifindex;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn)) ==
-1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (loopback != 0) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loopback,
sizeof(loopback)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (ttl != -1) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle = pcap_open_offline(argv[optind], errbuf);
if (handle == nullptr) {
std::cerr << "pcap_open: " << errbuf << std::endl;
return 1;
}
pcap_pkthdr header;
const u_char *p;
timeval tv = {0, 0};
while ((p = pcap_next(handle, &header))) {
if (header.len != header.caplen) {
continue;
}
auto eth = reinterpret_cast<const ether_header *>(p);
if (ntohs(eth->ether_type) != ETHERTYPE_IP) {
continue;
}
auto ip = reinterpret_cast<const iphdr *>(p + sizeof(ether_header));
if (ip->version != 4) {
continue;
}
if (ip->protocol != IPPROTO_UDP) {
continue;
}
auto udp = reinterpret_cast<const udphdr *>(p + sizeof(ether_header) +
ip->ihl * 4);
if (tv.tv_sec == 0) {
tv = header.ts;
}
timeval diff;
timersub(&header.ts, &tv, &diff);
usleep((diff.tv_sec * 1000000 + diff.tv_usec) * speed);
ssize_t len = ntohs(udp->len) - 8;
const u_char *d = &p[sizeof(ether_header) + ip->ihl * 4 + sizeof(udphdr)];
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = udp->dest;
addr.sin_addr = {ip->daddr};
auto n = sendto(fd, d, len, 0, reinterpret_cast<sockaddr *>(&addr),
sizeof(addr));
if (n != len) {
std::cerr << "sendto: " << strerror(errno) << std::endl;
return 1;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_TRIANGULATION_TRIANGULATION_TEMPLATES_HPP_INCLUDED
#define __YLIKUUTIO_TRIANGULATION_TRIANGULATION_TEMPLATES_HPP_INCLUDED
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector> // std::vector
namespace yli::triangulation
{
template<class T1>
T1 get_y(
const T1* const vertex_data,
const std::size_t x,
const std::size_t z,
const std::size_t image_width)
{
// This function returns the altitude value based on x & z coordinates.
// This works only for a raw heightmap data (for a 2D array of altitudes).
const T1* const vertex_pointer = vertex_data + z * image_width + x;
return static_cast<T1>(*vertex_pointer);
}
// for bilinear interpolation.
template<class T1>
float southwest_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x - x_step, z - z_step, image_width));
}
template<class T1>
float southeast_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x, z - z_step, image_width));
}
template<class T1>
float northwest_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x - x_step, z, image_width));
}
template<class T1>
float northeast_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x, z, image_width));
}
template<class T1>
float center_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(southwest_y(x, z, input_vertex_pointer, image_width, x_step, z_step) +
southeast_y(x, z, input_vertex_pointer, image_width, x_step, z_step) +
northwest_y(x, z, input_vertex_pointer, image_width, x_step, z_step) +
northeast_y(x, z, input_vertex_pointer, image_width, x_step, z_step)) / 4.0f;
}
template<class T1>
bool compute_range(
const T1* const input_vertex_pointer,
const std::size_t image_width,
const std::size_t image_height,
const std::size_t x_step,
const std::size_t z_step,
float& min_y_value,
float& max_y_value,
float& divisor)
{
for (std::size_t z = 0; z < image_height; z += z_step)
{
for (std::size_t x = 0; x < image_width; x += x_step)
{
const T1& vertex_height = input_vertex_pointer[image_width * z + x];
if (std::isnan(min_y_value) || vertex_height < min_y_value)
{
min_y_value = vertex_height;
}
if (std::isnan(max_y_value) || vertex_height > max_y_value)
{
max_y_value = vertex_height;
}
}
}
divisor = max_y_value - min_y_value;
if (std::isnan(divisor))
{
std::cerr << "ERROR: the value of `divisor` is `NAN`.\n";
return false;
}
if (divisor == 0)
{
std::cerr << "ERROR: the value of `divisor` is 0.\n";
return false;
}
return true;
}
template<class T1>
bool define_vertices(
const T1* const input_vertex_pointer,
const std::size_t image_width,
const std::size_t image_height,
const std::size_t x_step,
const std::size_t z_step,
const bool use_real_texture_coordinates,
std::vector<glm::vec3>& temp_vertices,
std::vector<glm::vec2>& temp_uvs)
{
if (image_width < 2 || image_height < 2)
{
// Can not define vertices if image width < 2 or image height < 2.
return false;
}
if (x_step == 0 || z_step == 0)
{
// Can not define vertices if x_step == 0 or z_step == 0.
return false;
}
// Elevation maps are created using a mapping from [min_y_value, max_y_value] to [0, 1].
// `min_y_value` & `max_y_value` are needed only for elevation maps.
float min_y_value = NAN;
float max_y_value = NAN;
float divisor = NAN;
if (!use_real_texture_coordinates)
{
bool result = yli::triangulation::compute_range(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
min_y_value,
max_y_value,
divisor);
if (!result)
{
return false;
}
}
const std::size_t actual_image_width = image_width / x_step;
const std::size_t actual_image_height = image_height / z_step;
std::size_t number_of_vertices = actual_image_width * actual_image_height;
temp_vertices.reserve(number_of_vertices);
temp_uvs.reserve(number_of_vertices);
// Define the temporary vertices in a double loop.
std::size_t texture_y = 0;
for (std::size_t z = 0; z < image_height; z += z_step)
{
std::size_t texture_x = 0;
for (std::size_t x = 0; x < image_width; x += x_step)
{
// current x,z coordinates).
float y = static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x, z, image_width));
// This corresponds to "v": specify one vertex.
glm::vec3 vertex;
vertex.x = static_cast<float>(x);
vertex.y = static_cast<float>(y);
vertex.z = static_cast<float>(z);
temp_vertices.emplace_back(vertex);
// This corresponds to "vt": specify texture coordinates of one vertex.
glm::vec2 uv;
if (use_real_texture_coordinates)
{
uv.x = round(static_cast<float>(texture_x));
uv.y = round(static_cast<float>(texture_y));
}
else
{
uv.x = static_cast<float>(y - min_y_value) / divisor;
uv.y = 0.0f;
}
temp_uvs.emplace_back(uv);
// `uv.x` is repeated 0, 1, 0, 1 ... when moving eastward.
// this causes the texture be mirrored horizontally for every other quad.
texture_x ^= 1;
}
// `uv.y` is repeated 0, 1, 0, 1 ... when moving southward.
// this causes the texture be mirrored vertically for every other quad.
texture_y ^= 1;
}
return true;
}
template<class T1>
bool interpolate_and_define_vertices_using_bilinear_interpolation(
const T1* const input_vertex_pointer,
const std::size_t image_width,
const std::size_t image_height,
const std::size_t x_step,
const std::size_t z_step,
const bool use_real_texture_coordinates,
std::vector<glm::vec3>& temp_vertices,
std::vector<glm::vec2>& temp_uvs)
{
std::cout << "Interpolating center vertices.\n";
if (image_width < 2 || image_height < 2)
{
// Can not interpolate center vertices if image width < 2 or image height < 2.
return false;
}
if (x_step <= 0 || z_step <= 0)
{
// Can not interpolate center vertices if x_step <= 0 or z_step <= 0.
return false;
}
// Elevation maps are created using a mapping from [min_y_value, max_y_value] to [0, 1].
// `min_y_value` & `max_y_value` are needed only for elevation maps.
float min_y_value = NAN;
float max_y_value = NAN;
float divisor = NAN;
if (!use_real_texture_coordinates)
{
bool result = yli::triangulation::compute_range(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
min_y_value,
max_y_value,
divisor);
if (!result)
{
return false;
}
}
// Then, define the faces in a double loop.
// Begin from index `z_step`.
for (std::size_t z = z_step; z < image_height; z += z_step)
{
// Begin from index `x_step`.
for (std::size_t x = x_step; x < image_width; x += x_step)
{
// This corresponds to "f": specify a face (but here we specify 2 faces instead!).
// Interpolate y coordinate (altitude).
const float y = center_y(x, z, input_vertex_pointer, image_width, x_step, z_step);
// Create a new vertex using bilinear interpolation.
// This corresponds to "v": specify one vertex.
glm::vec3 vertex;
vertex.x = static_cast<float>(x) - 0.5f * x_step;
vertex.y = static_cast<float>(y);
vertex.z = static_cast<float>(z) - 0.5f * z_step;
temp_vertices.emplace_back(vertex);
// This corresponds to "vt": specify texture coordinates of one vertex.
glm::vec2 uv;
if (use_real_texture_coordinates)
{
uv.x = 0.5f;
uv.y = 0.5f;
}
else
{
uv.x = static_cast<float>(y - min_y_value) / divisor;
uv.y = 0.0f;
}
temp_uvs.emplace_back(uv);
}
}
return true;
}
}
#endif
<commit_msg>Bugfix: do not use `<= 0` for unsigned variables.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_TRIANGULATION_TRIANGULATION_TEMPLATES_HPP_INCLUDED
#define __YLIKUUTIO_TRIANGULATION_TRIANGULATION_TEMPLATES_HPP_INCLUDED
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector> // std::vector
namespace yli::triangulation
{
template<class T1>
T1 get_y(
const T1* const vertex_data,
const std::size_t x,
const std::size_t z,
const std::size_t image_width)
{
// This function returns the altitude value based on x & z coordinates.
// This works only for a raw heightmap data (for a 2D array of altitudes).
const T1* const vertex_pointer = vertex_data + z * image_width + x;
return static_cast<T1>(*vertex_pointer);
}
// for bilinear interpolation.
template<class T1>
float southwest_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x - x_step, z - z_step, image_width));
}
template<class T1>
float southeast_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x, z - z_step, image_width));
}
template<class T1>
float northwest_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x - x_step, z, image_width));
}
template<class T1>
float northeast_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x, z, image_width));
}
template<class T1>
float center_y(const std::size_t x, const std::size_t z, const T1* const input_vertex_pointer, const std::size_t image_width, const std::size_t x_step, const std::size_t z_step)
{
return static_cast<float>(southwest_y(x, z, input_vertex_pointer, image_width, x_step, z_step) +
southeast_y(x, z, input_vertex_pointer, image_width, x_step, z_step) +
northwest_y(x, z, input_vertex_pointer, image_width, x_step, z_step) +
northeast_y(x, z, input_vertex_pointer, image_width, x_step, z_step)) / 4.0f;
}
template<class T1>
bool compute_range(
const T1* const input_vertex_pointer,
const std::size_t image_width,
const std::size_t image_height,
const std::size_t x_step,
const std::size_t z_step,
float& min_y_value,
float& max_y_value,
float& divisor)
{
for (std::size_t z = 0; z < image_height; z += z_step)
{
for (std::size_t x = 0; x < image_width; x += x_step)
{
const T1& vertex_height = input_vertex_pointer[image_width * z + x];
if (std::isnan(min_y_value) || vertex_height < min_y_value)
{
min_y_value = vertex_height;
}
if (std::isnan(max_y_value) || vertex_height > max_y_value)
{
max_y_value = vertex_height;
}
}
}
divisor = max_y_value - min_y_value;
if (std::isnan(divisor))
{
std::cerr << "ERROR: the value of `divisor` is `NAN`.\n";
return false;
}
if (divisor == 0)
{
std::cerr << "ERROR: the value of `divisor` is 0.\n";
return false;
}
return true;
}
template<class T1>
bool define_vertices(
const T1* const input_vertex_pointer,
const std::size_t image_width,
const std::size_t image_height,
const std::size_t x_step,
const std::size_t z_step,
const bool use_real_texture_coordinates,
std::vector<glm::vec3>& temp_vertices,
std::vector<glm::vec2>& temp_uvs)
{
if (image_width < 2 || image_height < 2)
{
// Can not define vertices if image width < 2 or image height < 2.
return false;
}
if (x_step == 0 || z_step == 0)
{
// Can not define vertices if x_step == 0 or z_step == 0.
return false;
}
// Elevation maps are created using a mapping from [min_y_value, max_y_value] to [0, 1].
// `min_y_value` & `max_y_value` are needed only for elevation maps.
float min_y_value = NAN;
float max_y_value = NAN;
float divisor = NAN;
if (!use_real_texture_coordinates)
{
bool result = yli::triangulation::compute_range(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
min_y_value,
max_y_value,
divisor);
if (!result)
{
return false;
}
}
const std::size_t actual_image_width = image_width / x_step;
const std::size_t actual_image_height = image_height / z_step;
std::size_t number_of_vertices = actual_image_width * actual_image_height;
temp_vertices.reserve(number_of_vertices);
temp_uvs.reserve(number_of_vertices);
// Define the temporary vertices in a double loop.
std::size_t texture_y = 0;
for (std::size_t z = 0; z < image_height; z += z_step)
{
std::size_t texture_x = 0;
for (std::size_t x = 0; x < image_width; x += x_step)
{
// current x,z coordinates).
float y = static_cast<float>(yli::triangulation::get_y(input_vertex_pointer, x, z, image_width));
// This corresponds to "v": specify one vertex.
glm::vec3 vertex;
vertex.x = static_cast<float>(x);
vertex.y = static_cast<float>(y);
vertex.z = static_cast<float>(z);
temp_vertices.emplace_back(vertex);
// This corresponds to "vt": specify texture coordinates of one vertex.
glm::vec2 uv;
if (use_real_texture_coordinates)
{
uv.x = round(static_cast<float>(texture_x));
uv.y = round(static_cast<float>(texture_y));
}
else
{
uv.x = static_cast<float>(y - min_y_value) / divisor;
uv.y = 0.0f;
}
temp_uvs.emplace_back(uv);
// `uv.x` is repeated 0, 1, 0, 1 ... when moving eastward.
// this causes the texture be mirrored horizontally for every other quad.
texture_x ^= 1;
}
// `uv.y` is repeated 0, 1, 0, 1 ... when moving southward.
// this causes the texture be mirrored vertically for every other quad.
texture_y ^= 1;
}
return true;
}
template<class T1>
bool interpolate_and_define_vertices_using_bilinear_interpolation(
const T1* const input_vertex_pointer,
const std::size_t image_width,
const std::size_t image_height,
const std::size_t x_step,
const std::size_t z_step,
const bool use_real_texture_coordinates,
std::vector<glm::vec3>& temp_vertices,
std::vector<glm::vec2>& temp_uvs)
{
std::cout << "Interpolating center vertices.\n";
if (image_width < 2 || image_height < 2)
{
// Can not interpolate center vertices if image width < 2 or image height < 2.
return false;
}
if (x_step == 0 || z_step == 0)
{
// Can not interpolate center vertices if x_step == 0 or z_step == 0.
return false;
}
// Elevation maps are created using a mapping from [min_y_value, max_y_value] to [0, 1].
// `min_y_value` & `max_y_value` are needed only for elevation maps.
float min_y_value = NAN;
float max_y_value = NAN;
float divisor = NAN;
if (!use_real_texture_coordinates)
{
bool result = yli::triangulation::compute_range(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
min_y_value,
max_y_value,
divisor);
if (!result)
{
return false;
}
}
// Then, define the faces in a double loop.
// Begin from index `z_step`.
for (std::size_t z = z_step; z < image_height; z += z_step)
{
// Begin from index `x_step`.
for (std::size_t x = x_step; x < image_width; x += x_step)
{
// This corresponds to "f": specify a face (but here we specify 2 faces instead!).
// Interpolate y coordinate (altitude).
const float y = center_y(x, z, input_vertex_pointer, image_width, x_step, z_step);
// Create a new vertex using bilinear interpolation.
// This corresponds to "v": specify one vertex.
glm::vec3 vertex;
vertex.x = static_cast<float>(x) - 0.5f * x_step;
vertex.y = static_cast<float>(y);
vertex.z = static_cast<float>(z) - 0.5f * z_step;
temp_vertices.emplace_back(vertex);
// This corresponds to "vt": specify texture coordinates of one vertex.
glm::vec2 uv;
if (use_real_texture_coordinates)
{
uv.x = 0.5f;
uv.y = 0.5f;
}
else
{
uv.x = static_cast<float>(y - min_y_value) / divisor;
uv.y = 0.0f;
}
temp_uvs.emplace_back(uv);
}
}
return true;
}
}
#endif
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include "EditorWindow.hpp"
#include "Util/EditorSettings.hpp"
#include <Engine/Util/Log.hpp>
#include "GUI/ImageButton.hpp"
#include "GUI/ImageTextButton.hpp"
#include <Engine/Resources.hpp>
#include <File.png.hpp>
#include <Options.png.hpp>
#include <Play.png.hpp>
#include <NewHymn.png.hpp>
#include <OpenHymn.png.hpp>
#include <ABeeZee.ttf.hpp>
#include <Engine/Hymn.hpp>
EditorWindow::EditorWindow() : Container(nullptr) {
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// Enable debug context and set message callback.
if (EditorSettings::GetInstance().GetBool("Debug Context"))
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
window = glfwCreateWindow(640, 480, "Hymn to Beauty", nullptr, nullptr);
if (!window) {
glfwTerminate();
/// @todo Print error to log.
}
glfwMakeContextCurrent(window);
gameWindow = nullptr;
childWindow = nullptr;
input = new InputHandler(window);
}
EditorWindow::~EditorWindow() {
delete fileButton;
delete optionsButton;
delete playButton;
delete menuBar;
delete newHymnButton;
delete openHymnButton;
delete fileMenu;
Resources().FreeTexture2D(fileTexture);
Resources().FreeTexture2D(optionsTexture);
Resources().FreeTexture2D(playTexture);
Resources().FreeTexture2D(newHymnTexture);
Resources().FreeTexture2D(openHymnTexture);
delete input;
Resources().FreeFont(font);
glfwDestroyWindow(window);
}
void EditorWindow::Init() {
int width, height;
glfwGetWindowSize(window, &width, &height);
font = Resources().CreateFontEmbedded(ABEEZEE_TTF, ABEEZEE_TTF_LENGTH, 24.f);
// Menu bar.
menuBar = new GUI::HorizontalLayout(this);
menuBar->SetSize(glm::vec2(static_cast<float>(width), 64.f));
AddWidget(menuBar);
fileTexture = Resources().CreateTexture2D(FILE_PNG, FILE_PNG_LENGTH);
fileButton = new GUI::ImageButton(menuBar, fileTexture);
fileButton->SetClickedCallback(std::bind(&OpenFileMenu, this));
menuBar->AddWidget(fileButton);
optionsTexture = Resources().CreateTexture2D(OPTIONS_PNG, OPTIONS_PNG_LENGTH);
optionsButton = new GUI::ImageButton(menuBar, optionsTexture);
optionsButton->SetClickedCallback(std::bind(&OpenProjectOptions, this));
menuBar->AddWidget(optionsButton);
playTexture = Resources().CreateTexture2D(PLAY_PNG, PLAY_PNG_LENGTH);
playButton = new GUI::ImageButton(menuBar, playTexture);
playButton->SetClickedCallback(std::bind(&Play, this));
menuBar->AddWidget(playButton);
// File menu.
fileMenu = new GUI::VerticalLayout(this);
fileMenu->SetSize(glm::vec2(256.f, 2.f * 64.f));
fileMenu->SetPosition(glm::vec2(0.f, 64.f));
fileMenu->SetVisible(false);
AddWidget(fileMenu);
newHymnTexture = Resources().CreateTexture2D(NEWHYMN_PNG, NEWHYMN_PNG_LENGTH);
newHymnButton = new GUI::ImageTextButton(fileMenu, newHymnTexture, font, "New Hymn");
newHymnButton->SetSize(glm::vec2(256.f, 64.f));
newHymnButton->SetClickedCallback(std::bind(&NewHymn, this));
fileMenu->AddWidget(newHymnButton);
openHymnTexture = Resources().CreateTexture2D(OPENHYMN_PNG, OPENHYMN_PNG_LENGTH);
openHymnButton = new GUI::ImageTextButton(fileMenu, openHymnTexture, font, "Open Hymn");
openHymnButton->SetSize(glm::vec2(256.f, 64.f));
openHymnButton->SetClickedCallback(std::bind(&OpenHymn, this));
fileMenu->AddWidget(openHymnButton);
glEnable(GL_DEPTH_TEST);
}
bool EditorWindow::ShouldClose() const {
return (glfwWindowShouldClose(window) != 0);
}
void EditorWindow::Update() {
// Handle running game.
if (gameWindow != nullptr) {
gameWindow->Update();
if (gameWindow->ShouldClose()) {
delete gameWindow;
gameWindow = nullptr;
}
} else if (childWindow != nullptr) {
input->Update();
input->SetActive();
childWindow->Update();
} else if (glfwGetKey(window, GLFW_KEY_F5) == GLFW_PRESS) {
Play();
} else {
input->Update();
input->SetActive();
UpdateWidgets();
}
}
void EditorWindow::Render() {
int width, height;
glfwGetWindowSize(window, &width, &height);
Render(glm::vec2(static_cast<float>(width), static_cast<float>(height)));
}
void EditorWindow::Render(const glm::vec2& screenSize) {
if (gameWindow != nullptr) {
gameWindow->Render();
} else {
glfwMakeContextCurrent(window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
RenderWidgets(screenSize);
if (childWindow != nullptr)
childWindow->Render(screenSize);
glfwSwapBuffers(window);
}
}
glm::vec2 EditorWindow::Size() const {
int width, height;
glfwGetWindowSize(window, &width, &height);
return glm::vec2(static_cast<float>(width), static_cast<float>(height));
}
void EditorWindow::OpenFileMenu() {
fileMenu->SetVisible(!fileMenu->Visible());
}
void EditorWindow::OpenProjectOptions() {
///@todo Project options
Log() << "Click test!\n";
}
void EditorWindow::Play() {
gameWindow = new GameWindow();
}
void EditorWindow::NewHymn() {
childWindow = new GUI::SelectHymnWindow(this);
childWindow->SetPosition(glm::vec2(0.f, 0.f));
childWindow->SetSize(Size());
childWindow->SetClosedCallback(std::bind(&NewHymnClosed, this));
}
void EditorWindow::NewHymnClosed() {
// Create new hymn
Hymn().Clear();
/// @todo Set path.
delete childWindow;
childWindow = nullptr;
}
void EditorWindow::OpenHymn() {
childWindow = new GUI::SelectHymnWindow(this);
childWindow->SetPosition(glm::vec2(0.f, 0.f));
childWindow->SetSize(Size());
childWindow->SetClosedCallback(std::bind(&OpenHymnClosed, this));
}
void EditorWindow::OpenHymnClosed() {
/// @todo Open hymn.
delete childWindow;
childWindow = nullptr;
}
<commit_msg>Set the path when creating a new hymn.<commit_after>#include <GL/glew.h>
#include "EditorWindow.hpp"
#include "Util/EditorSettings.hpp"
#include <Engine/Util/Log.hpp>
#include "GUI/ImageButton.hpp"
#include "GUI/ImageTextButton.hpp"
#include <Engine/Resources.hpp>
#include <File.png.hpp>
#include <Options.png.hpp>
#include <Play.png.hpp>
#include <NewHymn.png.hpp>
#include <OpenHymn.png.hpp>
#include <ABeeZee.ttf.hpp>
#include <Engine/Hymn.hpp>
EditorWindow::EditorWindow() : Container(nullptr) {
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// Enable debug context and set message callback.
if (EditorSettings::GetInstance().GetBool("Debug Context"))
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
window = glfwCreateWindow(640, 480, "Hymn to Beauty", nullptr, nullptr);
if (!window) {
glfwTerminate();
/// @todo Print error to log.
}
glfwMakeContextCurrent(window);
gameWindow = nullptr;
childWindow = nullptr;
input = new InputHandler(window);
}
EditorWindow::~EditorWindow() {
delete fileButton;
delete optionsButton;
delete playButton;
delete menuBar;
delete newHymnButton;
delete openHymnButton;
delete fileMenu;
Resources().FreeTexture2D(fileTexture);
Resources().FreeTexture2D(optionsTexture);
Resources().FreeTexture2D(playTexture);
Resources().FreeTexture2D(newHymnTexture);
Resources().FreeTexture2D(openHymnTexture);
delete input;
Resources().FreeFont(font);
glfwDestroyWindow(window);
}
void EditorWindow::Init() {
int width, height;
glfwGetWindowSize(window, &width, &height);
font = Resources().CreateFontEmbedded(ABEEZEE_TTF, ABEEZEE_TTF_LENGTH, 24.f);
// Menu bar.
menuBar = new GUI::HorizontalLayout(this);
menuBar->SetSize(glm::vec2(static_cast<float>(width), 64.f));
AddWidget(menuBar);
fileTexture = Resources().CreateTexture2D(FILE_PNG, FILE_PNG_LENGTH);
fileButton = new GUI::ImageButton(menuBar, fileTexture);
fileButton->SetClickedCallback(std::bind(&OpenFileMenu, this));
menuBar->AddWidget(fileButton);
optionsTexture = Resources().CreateTexture2D(OPTIONS_PNG, OPTIONS_PNG_LENGTH);
optionsButton = new GUI::ImageButton(menuBar, optionsTexture);
optionsButton->SetClickedCallback(std::bind(&OpenProjectOptions, this));
menuBar->AddWidget(optionsButton);
playTexture = Resources().CreateTexture2D(PLAY_PNG, PLAY_PNG_LENGTH);
playButton = new GUI::ImageButton(menuBar, playTexture);
playButton->SetClickedCallback(std::bind(&Play, this));
menuBar->AddWidget(playButton);
// File menu.
fileMenu = new GUI::VerticalLayout(this);
fileMenu->SetSize(glm::vec2(256.f, 2.f * 64.f));
fileMenu->SetPosition(glm::vec2(0.f, 64.f));
fileMenu->SetVisible(false);
AddWidget(fileMenu);
newHymnTexture = Resources().CreateTexture2D(NEWHYMN_PNG, NEWHYMN_PNG_LENGTH);
newHymnButton = new GUI::ImageTextButton(fileMenu, newHymnTexture, font, "New Hymn");
newHymnButton->SetSize(glm::vec2(256.f, 64.f));
newHymnButton->SetClickedCallback(std::bind(&NewHymn, this));
fileMenu->AddWidget(newHymnButton);
openHymnTexture = Resources().CreateTexture2D(OPENHYMN_PNG, OPENHYMN_PNG_LENGTH);
openHymnButton = new GUI::ImageTextButton(fileMenu, openHymnTexture, font, "Open Hymn");
openHymnButton->SetSize(glm::vec2(256.f, 64.f));
openHymnButton->SetClickedCallback(std::bind(&OpenHymn, this));
fileMenu->AddWidget(openHymnButton);
glEnable(GL_DEPTH_TEST);
}
bool EditorWindow::ShouldClose() const {
return (glfwWindowShouldClose(window) != 0);
}
void EditorWindow::Update() {
// Handle running game.
if (gameWindow != nullptr) {
gameWindow->Update();
if (gameWindow->ShouldClose()) {
delete gameWindow;
gameWindow = nullptr;
}
} else if (childWindow != nullptr) {
input->Update();
input->SetActive();
childWindow->Update();
} else if (glfwGetKey(window, GLFW_KEY_F5) == GLFW_PRESS) {
Play();
} else {
input->Update();
input->SetActive();
UpdateWidgets();
}
}
void EditorWindow::Render() {
int width, height;
glfwGetWindowSize(window, &width, &height);
Render(glm::vec2(static_cast<float>(width), static_cast<float>(height)));
}
void EditorWindow::Render(const glm::vec2& screenSize) {
if (gameWindow != nullptr) {
gameWindow->Render();
} else {
glfwMakeContextCurrent(window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
RenderWidgets(screenSize);
if (childWindow != nullptr)
childWindow->Render(screenSize);
glfwSwapBuffers(window);
}
}
glm::vec2 EditorWindow::Size() const {
int width, height;
glfwGetWindowSize(window, &width, &height);
return glm::vec2(static_cast<float>(width), static_cast<float>(height));
}
void EditorWindow::OpenFileMenu() {
fileMenu->SetVisible(!fileMenu->Visible());
}
void EditorWindow::OpenProjectOptions() {
///@todo Project options
Log() << "Click test!\n";
}
void EditorWindow::Play() {
gameWindow = new GameWindow();
}
void EditorWindow::NewHymn() {
childWindow = new GUI::SelectHymnWindow(this);
childWindow->SetPosition(glm::vec2(0.f, 0.f));
childWindow->SetSize(Size());
childWindow->SetClosedCallback(std::bind(&NewHymnClosed, this));
}
void EditorWindow::NewHymnClosed() {
// Create new hymn
Hymn().Clear();
Hymn().SetPath(childWindow->GetHymn());
delete childWindow;
childWindow = nullptr;
}
void EditorWindow::OpenHymn() {
childWindow = new GUI::SelectHymnWindow(this);
childWindow->SetPosition(glm::vec2(0.f, 0.f));
childWindow->SetSize(Size());
childWindow->SetClosedCallback(std::bind(&OpenHymnClosed, this));
}
void EditorWindow::OpenHymnClosed() {
/// @todo Open hymn.
delete childWindow;
childWindow = nullptr;
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:2; c-basic-offset:2; indent-tabs-mode:t -*-
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include <string>
#include "LogType.h"
#include "Logger.h"
#include <iostream>
#include "Clock.h"
#include "config.h"
#include <sys/stat.h>
#include <sys/types.h>
// per-process lock. lame, but this way I protect LogType too!
Mutex logger_lock;
Logger::Logger(string fn, LogType *type)
{
logger_lock.Lock();
{
filename = "log/";
if (g_conf.log_name) {
filename += g_conf.log_name;
::mkdir( filename.c_str(), 0755 ); // make sure dir exists
filename += "/";
}
filename += fn;
//cout << "log " << filename << endl;
interval = g_conf.log_interval;
start = g_clock.now(); // time 0!
last_logged = 0;
wrote_header = -1;
open = false;
this->type = type;
wrote_header_last = 0;
version = 0;
}
logger_lock.Unlock();
flush(false);
}
Logger::~Logger()
{
flush(true);
out.close();
}
long Logger::inc(const char *key, long v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_inc(key);
flush();
vals[i] += v;
long r = vals[i];
logger_lock.Unlock();
return r;
}
double Logger::finc(const char *key, double v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_inc(key);
flush();
fvals[i] += v;
double r = fvals[i];
logger_lock.Unlock();
return r;
}
long Logger::set(const char *key, long v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_set(key);
flush();
long r = vals[i] = v;
logger_lock.Unlock();
return r;
}
double Logger::fset(const char *key, double v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_set(key);
flush();
double r = fvals[i] = v;
logger_lock.Unlock();
return r;
}
long Logger::get(const char* key)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
long r = 0;
if (i >= 0 && (int)vals.size() > i)
r = vals[i];
logger_lock.Unlock();
return r;
}
void Logger::flush(bool force)
{
if (!g_conf.log) return;
logger_lock.Lock();
if (version != type->version) {
while (type->keys.size() > vals.size())
vals.push_back(0);
while (type->keys.size() > fvals.size())
fvals.push_back(0);
version = type->version;
}
if (!open) {
out.open(filename.c_str(), ofstream::out);
open = true;
//cout << "opening log file " << filename << endl;
}
utime_t fromstart = g_clock.now();
if (fromstart < start) {
cerr << "logger time jumped backwards from " << start << " to " << fromstart << endl;
assert(0);
start = fromstart;
}
fromstart -= start;
while (force ||
((fromstart.sec() > last_logged) &&
(fromstart.sec() - last_logged >= interval))) {
last_logged += interval;
force = false;
//cout << "logger " << this << " advancing from " << last_logged << " now " << now << endl;
if (!open) {
out.open(filename.c_str(), ofstream::out);
open = true;
//cout << "opening log file " << filename << endl;
}
// header?
wrote_header_last++;
if (wrote_header != type->version ||
wrote_header_last > 10) {
out << "#" << type->keymap.size();
for (unsigned i=0; i<type->keys.size(); i++)
out << "\t" << type->keys[i];
out << endl; //out << "\t (" << type->keymap.size() << ")" << endl;
wrote_header = type->version;
wrote_header_last = 0;
}
// write line to log
out << last_logged;
for (unsigned i=0; i<type->keys.size(); i++) {
if (fvals[i] > 0 && vals[i] == 0)
out << "\t" << fvals[i];
else
out << "\t" << vals[i];
}
out << endl;
// reset the counters
for (unsigned i=0; i<type->keys.size(); i++) {
if (type->inc_keys.count(i)) {
this->vals[i] = 0;
this->fvals[i] = 0;
}
}
}
logger_lock.Unlock();
}
<commit_msg>tabbing<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This 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. See file COPYING.
*
*/
#include <string>
#include "LogType.h"
#include "Logger.h"
#include <iostream>
#include "Clock.h"
#include "config.h"
#include <sys/stat.h>
#include <sys/types.h>
// per-process lock. lame, but this way I protect LogType too!
Mutex logger_lock;
Logger::Logger(string fn, LogType *type)
{
logger_lock.Lock();
{
filename = "log/";
if (g_conf.log_name) {
filename += g_conf.log_name;
::mkdir( filename.c_str(), 0755 ); // make sure dir exists
filename += "/";
}
filename += fn;
//cout << "log " << filename << endl;
interval = g_conf.log_interval;
start = g_clock.now(); // time 0!
last_logged = 0;
wrote_header = -1;
open = false;
this->type = type;
wrote_header_last = 0;
version = 0;
}
logger_lock.Unlock();
flush(false);
}
Logger::~Logger()
{
flush(true);
out.close();
}
long Logger::inc(const char *key, long v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_inc(key);
flush();
vals[i] += v;
long r = vals[i];
logger_lock.Unlock();
return r;
}
double Logger::finc(const char *key, double v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_inc(key);
flush();
fvals[i] += v;
double r = fvals[i];
logger_lock.Unlock();
return r;
}
long Logger::set(const char *key, long v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_set(key);
flush();
long r = vals[i] = v;
logger_lock.Unlock();
return r;
}
double Logger::fset(const char *key, double v)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
if (i < 0) i = type->add_set(key);
flush();
double r = fvals[i] = v;
logger_lock.Unlock();
return r;
}
long Logger::get(const char* key)
{
if (!g_conf.log) return 0;
logger_lock.Lock();
int i = type->lookup_key(key);
long r = 0;
if (i >= 0 && (int)vals.size() > i)
r = vals[i];
logger_lock.Unlock();
return r;
}
void Logger::flush(bool force)
{
if (!g_conf.log) return;
logger_lock.Lock();
if (version != type->version) {
while (type->keys.size() > vals.size())
vals.push_back(0);
while (type->keys.size() > fvals.size())
fvals.push_back(0);
version = type->version;
}
if (!open) {
out.open(filename.c_str(), ofstream::out);
open = true;
//cout << "opening log file " << filename << endl;
}
utime_t fromstart = g_clock.now();
if (fromstart < start) {
cerr << "logger time jumped backwards from " << start << " to " << fromstart << endl;
assert(0);
start = fromstart;
}
fromstart -= start;
while (force ||
((fromstart.sec() > last_logged) &&
(fromstart.sec() - last_logged >= interval))) {
last_logged += interval;
force = false;
//cout << "logger " << this << " advancing from " << last_logged << " now " << now << endl;
if (!open) {
out.open(filename.c_str(), ofstream::out);
open = true;
//cout << "opening log file " << filename << endl;
}
// header?
wrote_header_last++;
if (wrote_header != type->version ||
wrote_header_last > 10) {
out << "#" << type->keymap.size();
for (unsigned i=0; i<type->keys.size(); i++)
out << "\t" << type->keys[i];
out << endl; //out << "\t (" << type->keymap.size() << ")" << endl;
wrote_header = type->version;
wrote_header_last = 0;
}
// write line to log
out << last_logged;
for (unsigned i=0; i<type->keys.size(); i++) {
if (fvals[i] > 0 && vals[i] == 0)
out << "\t" << fvals[i];
else
out << "\t" << vals[i];
}
out << endl;
// reset the counters
for (unsigned i=0; i<type->keys.size(); i++) {
if (type->inc_keys.count(i)) {
this->vals[i] = 0;
this->fvals[i] = 0;
}
}
}
logger_lock.Unlock();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#include "mcrouter/lib/network/ThriftTransport.h"
#include <folly/fibers/FiberManager.h>
#include <folly/io/async/AsyncSSLSocket.h>
#include <folly/io/async/AsyncSocket.h>
#include <folly/io/async/EventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>
#include <thrift/lib/cpp2/async/RequestChannel.h>
#include "mcrouter/lib/fbi/cpp/LogFailure.h"
#include "mcrouter/lib/network/AsyncTlsToPlaintextSocket.h"
#include "mcrouter/lib/network/ConnectionOptions.h"
#include "mcrouter/lib/network/McFizzClient.h"
#include "mcrouter/lib/network/SecurityOptions.h"
#include "mcrouter/lib/network/SocketUtil.h"
using apache::thrift::async::TAsyncSocket;
namespace facebook {
namespace memcache {
ThriftTransportBase::ThriftTransportBase(
folly::EventBase& eventBase,
ConnectionOptions options)
: eventBase_(eventBase), connectionOptions_(std::move(options)) {}
void ThriftTransportBase::closeNow() {
resetClient();
}
void ThriftTransportBase::setConnectionStatusCallbacks(
ConnectionStatusCallbacks callbacks) {
connectionCallbacks_ = std::move(callbacks);
}
void ThriftTransportBase::setRequestStatusCallbacks(
RequestStatusCallbacks callbacks) {
requestCallbacks_ = std::move(callbacks);
}
void ThriftTransportBase::setThrottle(size_t maxInflight, size_t maxPending) {
maxInflight_ = maxInflight;
maxPending_ = maxPending;
}
Transport::RequestQueueStats ThriftTransportBase::getRequestQueueStats() const {
return RequestQueueStats{0, 0};
}
void ThriftTransportBase::updateTimeoutsIfShorter(
std::chrono::milliseconds /* connectTimeout */,
std::chrono::milliseconds /* writeTimeout */) {}
const folly::AsyncTransportWrapper* ThriftTransportBase::getTransport() const {
return nullptr;
}
double ThriftTransportBase::getRetransmitsPerKb() {
return 0.0;
}
apache::thrift::async::TAsyncTransport::UniquePtr
ThriftTransportBase::getConnectingSocket() {
return folly::fibers::runInMainContext(
[this]() -> apache::thrift::async::TAsyncTransport::UniquePtr {
auto expectedSocket =
createTAsyncSocket(eventBase_, connectionOptions_);
if (expectedSocket.hasError()) {
LOG_FAILURE(
"ThriftTransport",
failure::Category::kBadEnvironment,
"{}",
expectedSocket.error().what());
return {};
}
auto socket = std::move(expectedSocket).value();
auto sockAddressExpected = getSocketAddress(connectionOptions_);
if (sockAddressExpected.hasError()) {
const auto& ex = sockAddressExpected.error();
LOG_FAILURE(
"ThriftTransport",
failure::Category::kBadEnvironment,
"{}",
ex.what());
return {};
}
folly::SocketAddress address = std::move(sockAddressExpected).value();
auto socketOptions = createSocketOptions(address, connectionOptions_);
connectionState_ = ConnectionState::Connecting;
const auto securityMech =
connectionOptions_.accessPoint->getSecurityMech();
if (securityMech == SecurityMech::TLS_TO_PLAINTEXT) {
socket->setSendTimeout(connectionOptions_.writeTimeout.count());
socket->getUnderlyingTransport<AsyncTlsToPlaintextSocket>()->connect(
this,
address,
connectionOptions_.connectTimeout,
std::move(socketOptions));
} else {
DCHECK(securityMech == SecurityMech::NONE);
socket->setSendTimeout(connectionOptions_.writeTimeout.count());
socket->getUnderlyingTransport<folly::AsyncSocket>()->connect(
this,
address,
connectionOptions_.connectTimeout.count(),
socketOptions);
}
return socket;
});
}
apache::thrift::RocketClientChannel::Ptr ThriftTransportBase::createChannel() {
auto socket = getConnectingSocket();
if (!socket) {
return nullptr;
}
auto channel =
apache::thrift::RocketClientChannel::newChannel(std::move(socket));
channel->setProtocolId(apache::thrift::protocol::T_COMPACT_PROTOCOL);
channel->setCloseCallback(this);
return channel;
}
apache::thrift::RpcOptions ThriftTransportBase::getRpcOptions(
std::chrono::milliseconds timeout) const {
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setTimeout(timeout);
rpcOptions.setClientOnlyTimeouts(true);
return rpcOptions;
}
void ThriftTransportBase::connectSuccess() noexcept {
assert(connectionState_ == ConnectionState::Connecting);
connectionState_ = ConnectionState::Up;
VLOG(5) << "[ThriftTransport] Connection successfully established!";
}
void ThriftTransportBase::connectErr(
const folly::AsyncSocketException& ex) noexcept {
assert(connectionState_ == ConnectionState::Connecting);
connectionState_ = ConnectionState::Error;
connectionTimedOut_ =
(ex.getType() == folly::AsyncSocketException::TIMED_OUT);
VLOG(2) << "[ThriftTransport] Error connecting: " << ex.what();
}
void ThriftTransportBase::channelClosed() {
VLOG(3) << "[ThriftTransport] Channel closed.";
resetClient();
}
} // namespace memcache
} // namespace facebook
<commit_msg>Support building mcrouter without thrift client support<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#include "mcrouter/lib/network/ThriftTransport.h"
#include <folly/fibers/FiberManager.h>
#include <folly/io/async/AsyncSSLSocket.h>
#include <folly/io/async/AsyncSocket.h>
#include <folly/io/async/EventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>
#include <thrift/lib/cpp2/async/RequestChannel.h>
#include "mcrouter/lib/fbi/cpp/LogFailure.h"
#include "mcrouter/lib/network/AsyncTlsToPlaintextSocket.h"
#include "mcrouter/lib/network/ConnectionOptions.h"
#include "mcrouter/lib/network/McFizzClient.h"
#include "mcrouter/lib/network/SecurityOptions.h"
#include "mcrouter/lib/network/SocketUtil.h"
using apache::thrift::async::TAsyncSocket;
namespace facebook {
namespace memcache {
ThriftTransportBase::ThriftTransportBase(
folly::EventBase& eventBase,
ConnectionOptions options)
: eventBase_(eventBase), connectionOptions_(std::move(options)) {}
void ThriftTransportBase::closeNow() {
resetClient();
}
void ThriftTransportBase::setConnectionStatusCallbacks(
ConnectionStatusCallbacks callbacks) {
connectionCallbacks_ = std::move(callbacks);
}
void ThriftTransportBase::setRequestStatusCallbacks(
RequestStatusCallbacks callbacks) {
requestCallbacks_ = std::move(callbacks);
}
void ThriftTransportBase::setThrottle(size_t maxInflight, size_t maxPending) {
maxInflight_ = maxInflight;
maxPending_ = maxPending;
}
Transport::RequestQueueStats ThriftTransportBase::getRequestQueueStats() const {
return RequestQueueStats{0, 0};
}
void ThriftTransportBase::updateTimeoutsIfShorter(
std::chrono::milliseconds /* connectTimeout */,
std::chrono::milliseconds /* writeTimeout */) {}
const folly::AsyncTransportWrapper* ThriftTransportBase::getTransport() const {
return nullptr;
}
double ThriftTransportBase::getRetransmitsPerKb() {
return 0.0;
}
apache::thrift::async::TAsyncTransport::UniquePtr
ThriftTransportBase::getConnectingSocket() {
return folly::fibers::runInMainContext(
[this]() -> apache::thrift::async::TAsyncTransport::UniquePtr {
auto expectedSocket =
createTAsyncSocket(eventBase_, connectionOptions_);
if (expectedSocket.hasError()) {
LOG_FAILURE(
"ThriftTransport",
failure::Category::kBadEnvironment,
"{}",
expectedSocket.error().what());
return {};
}
auto socket = std::move(expectedSocket).value();
auto sockAddressExpected = getSocketAddress(connectionOptions_);
if (sockAddressExpected.hasError()) {
const auto& ex = sockAddressExpected.error();
LOG_FAILURE(
"ThriftTransport",
failure::Category::kBadEnvironment,
"{}",
ex.what());
return {};
}
folly::SocketAddress address = std::move(sockAddressExpected).value();
auto socketOptions = createSocketOptions(address, connectionOptions_);
connectionState_ = ConnectionState::Connecting;
const auto securityMech =
connectionOptions_.accessPoint->getSecurityMech();
if (securityMech == SecurityMech::TLS_TO_PLAINTEXT) {
socket->setSendTimeout(connectionOptions_.writeTimeout.count());
socket->getUnderlyingTransport<AsyncTlsToPlaintextSocket>()->connect(
this,
address,
connectionOptions_.connectTimeout,
std::move(socketOptions));
} else {
DCHECK(securityMech == SecurityMech::NONE);
socket->setSendTimeout(connectionOptions_.writeTimeout.count());
socket->getUnderlyingTransport<folly::AsyncSocket>()->connect(
this,
address,
connectionOptions_.connectTimeout.count(),
socketOptions);
}
return socket;
});
}
apache::thrift::RocketClientChannel::Ptr ThriftTransportBase::createChannel() {
// HHVM supports Debian 8 (EOL 2020-06-30), which includes OpenSSL 1.0.1;
// Rocket/RSocket require ALPN, which requiers 1.0.2.
//
// For these platforms, build MCRouter client without a functional
// Thrift transport, but continue to permit use as an async Memcache client
// library for Hack
#ifndef MCROUTER_NOOP_THRIFT_CLIENT
auto socket = getConnectingSocket();
if (!socket) {
return nullptr;
}
auto channel =
apache::thrift::RocketClientChannel::newChannel(std::move(socket));
channel->setProtocolId(apache::thrift::protocol::T_COMPACT_PROTOCOL);
channel->setCloseCallback(this);
return channel;
#else
return nullptr;
#endif
}
apache::thrift::RpcOptions ThriftTransportBase::getRpcOptions(
std::chrono::milliseconds timeout) const {
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setTimeout(timeout);
rpcOptions.setClientOnlyTimeouts(true);
return rpcOptions;
}
void ThriftTransportBase::connectSuccess() noexcept {
assert(connectionState_ == ConnectionState::Connecting);
connectionState_ = ConnectionState::Up;
VLOG(5) << "[ThriftTransport] Connection successfully established!";
}
void ThriftTransportBase::connectErr(
const folly::AsyncSocketException& ex) noexcept {
assert(connectionState_ == ConnectionState::Connecting);
connectionState_ = ConnectionState::Error;
connectionTimedOut_ =
(ex.getType() == folly::AsyncSocketException::TIMED_OUT);
VLOG(2) << "[ThriftTransport] Error connecting: " << ex.what();
}
void ThriftTransportBase::channelClosed() {
VLOG(3) << "[ThriftTransport] Channel closed.";
resetClient();
}
} // namespace memcache
} // namespace facebook
<|endoftext|> |
<commit_before>
<commit_msg>Delete mistake<commit_after><|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/node.h"
#include "libmesh/elem.h"
#include "libmesh/reference_elem.h"
#include "libmesh/libmesh_singleton.h"
#include "libmesh/threads.h"
// C++ includes
#include <map>
#include <sstream>
//-----------------------------------------------
// anonymous namespace for implementation details
namespace
{
using namespace libMesh;
namespace ElemDataStrings
{
#include "reference_elem.data"
}
typedef Threads::spin_mutex InitMutex;
// Mutex for thread safety.
InitMutex init_mtx;
// map from ElemType to reference element file system object name
typedef std::map<ElemType, const char *> FileMapType;
FileMapType ref_elem_file;
Elem * ref_elem_map[INVALID_ELEM];
class SingletonCache : public libMesh::Singleton
{
public:
~SingletonCache()
{
for (unsigned int e=0; e<elem_list.size(); e++)
{
delete elem_list[e];
elem_list[e] = NULL;
}
elem_list.clear();
for (unsigned int n=0; n<node_list.size(); n++)
{
delete node_list[n];
node_list[n] = NULL;
}
node_list.clear();
}
std::vector<Node *> node_list;
std::vector<Elem *> elem_list;
};
// singleton object, dynamically created and then
// removed at program exit
SingletonCache * singleton_cache = NULL;
Elem * read_ref_elem (const ElemType Type,
std::istream & in)
{
libmesh_assert (singleton_cache != NULL);
static const unsigned int comm_len = 1024;
char comm[comm_len];
std::string foo;
unsigned int n_elem, n_nodes, elem_type, nn;
double x, y, z;
in >> foo;
in >> n_elem; /**/ in.getline (comm, comm_len); libmesh_assert_equal_to (n_elem, 1);
in >> n_nodes; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> n_elem; /**/ in.getline (comm, comm_len); libmesh_assert_equal_to (n_elem, 1);
in >> elem_type;
libmesh_assert_less (elem_type, INVALID_ELEM);
libmesh_assert_equal_to (elem_type, static_cast<unsigned int>(Type));
libmesh_assert_equal_to (n_nodes, Elem::type_to_n_nodes_map[elem_type]);
// Construct the elem
Elem * elem = Elem::build(static_cast<ElemType>(elem_type)).release();
// We are expecing an identity map, so assert it!
for (unsigned int n=0; n<n_nodes; n++)
{
in >> nn;
libmesh_assert_equal_to (n,nn);
}
for (unsigned int n=0; n<n_nodes; n++)
{
in >> x >> y >> z;
Node * node = new Node(x,y,z,n);
singleton_cache->node_list.push_back(node);
elem->set_node(n) = node;
}
// it is entirely possible we ran out of file or encountered
// another error. If so, cleanly abort.
if (!in)
{
delete elem;
elem = NULL;
libmesh_error_msg("ERROR while creating element singleton!");
}
else
singleton_cache->elem_list.push_back (elem);
ref_elem_map[Type] = elem;
return elem;
}
void init_ref_elem_table()
{
// ouside mutex - if this pointer is set, we can trust it.
if (singleton_cache != NULL) return;
// playing with fire here - lock before touching shared
// data structures
InitMutex::scoped_lock lock(init_mtx);
// inside mutex - pointer may have changed while waiting
// for the lock to acquire, check it again.
if (singleton_cache != NULL) return;
// OK, if we get here we have the lock and we are not
// initialized. populate singleton.
singleton_cache = new SingletonCache;
// initialize the reference file table
{
ref_elem_file.clear();
// // 1D elements
ref_elem_file[EDGE2] = ElemDataStrings::one_edge;
ref_elem_file[EDGE3] = ElemDataStrings::one_edge3;
ref_elem_file[EDGE4] = ElemDataStrings::one_edge4;
// 2D elements
ref_elem_file[TRI3] = ElemDataStrings::one_tri;
ref_elem_file[TRI6] = ElemDataStrings::one_tri6;
ref_elem_file[QUAD4] = ElemDataStrings::one_quad;
ref_elem_file[QUAD8] = ElemDataStrings::one_quad8;
ref_elem_file[QUAD9] = ElemDataStrings::one_quad9;
// 3D elements
ref_elem_file[HEX8] = ElemDataStrings::one_hex;
ref_elem_file[HEX20] = ElemDataStrings::one_hex20;
ref_elem_file[HEX27] = ElemDataStrings::one_hex27;
ref_elem_file[TET4] = ElemDataStrings::one_tet;
ref_elem_file[TET10] = ElemDataStrings::one_tet10;
ref_elem_file[PRISM6] = ElemDataStrings::one_prism;
ref_elem_file[PRISM15] = ElemDataStrings::one_prism15;
ref_elem_file[PRISM18] = ElemDataStrings::one_prism18;
ref_elem_file[PYRAMID5] = ElemDataStrings::one_pyramid;
ref_elem_file[PYRAMID13] = ElemDataStrings::one_pyramid13;
ref_elem_file[PYRAMID14] = ElemDataStrings::one_pyramid14;
}
// Read'em
for (FileMapType::const_iterator it=ref_elem_file.begin();
it != ref_elem_file.end(); ++it)
{
std::istringstream stream(it->second);
read_ref_elem(it->first,
stream);
}
}
// no reason to do this at startup -
// data structures will get initialized *if*
// ReferenceElem::get() is ever called.
// // Class to setup singleton data
// class ReferenceElemSetup : public Singleton::Setup
// {
// void setup ()
// {
// init_ref_elem_table();
// }
// } reference_elem_setup;
} // anonymous namespace
//----------------------------------------------------------------------------
// external API Implementation
namespace libMesh
{
namespace ReferenceElem
{
const Elem & get (const ElemType Type)
{
libmesh_assert_less (Type, INVALID_ELEM);
init_ref_elem_table();
libmesh_assert (ref_elem_map[Type] != NULL);
return *ref_elem_map[Type];
}
} // namespace ReferenceElem
} // namespace libMesh
<commit_msg>Ignore overlength string warnings from reference_elem.data<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/node.h"
#include "libmesh/elem.h"
#include "libmesh/reference_elem.h"
#include "libmesh/libmesh_singleton.h"
#include "libmesh/threads.h"
// C++ includes
#include <map>
#include <sstream>
//-----------------------------------------------
// anonymous namespace for implementation details
namespace
{
using namespace libMesh;
namespace ElemDataStrings
{
// GCC 5.2.0 warns about overlength strings in the auto-generated
// reference_elem.data file.
#pragma GCC diagnostic ignored "-Woverlength-strings"
#include "reference_elem.data"
#pragma GCC diagnostic warning "-Woverlength-strings"
}
typedef Threads::spin_mutex InitMutex;
// Mutex for thread safety.
InitMutex init_mtx;
// map from ElemType to reference element file system object name
typedef std::map<ElemType, const char *> FileMapType;
FileMapType ref_elem_file;
Elem * ref_elem_map[INVALID_ELEM];
class SingletonCache : public libMesh::Singleton
{
public:
~SingletonCache()
{
for (unsigned int e=0; e<elem_list.size(); e++)
{
delete elem_list[e];
elem_list[e] = NULL;
}
elem_list.clear();
for (unsigned int n=0; n<node_list.size(); n++)
{
delete node_list[n];
node_list[n] = NULL;
}
node_list.clear();
}
std::vector<Node *> node_list;
std::vector<Elem *> elem_list;
};
// singleton object, dynamically created and then
// removed at program exit
SingletonCache * singleton_cache = NULL;
Elem * read_ref_elem (const ElemType Type,
std::istream & in)
{
libmesh_assert (singleton_cache != NULL);
static const unsigned int comm_len = 1024;
char comm[comm_len];
std::string foo;
unsigned int n_elem, n_nodes, elem_type, nn;
double x, y, z;
in >> foo;
in >> n_elem; /**/ in.getline (comm, comm_len); libmesh_assert_equal_to (n_elem, 1);
in >> n_nodes; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> foo; /**/ in.getline (comm, comm_len);
in >> n_elem; /**/ in.getline (comm, comm_len); libmesh_assert_equal_to (n_elem, 1);
in >> elem_type;
libmesh_assert_less (elem_type, INVALID_ELEM);
libmesh_assert_equal_to (elem_type, static_cast<unsigned int>(Type));
libmesh_assert_equal_to (n_nodes, Elem::type_to_n_nodes_map[elem_type]);
// Construct the elem
Elem * elem = Elem::build(static_cast<ElemType>(elem_type)).release();
// We are expecing an identity map, so assert it!
for (unsigned int n=0; n<n_nodes; n++)
{
in >> nn;
libmesh_assert_equal_to (n,nn);
}
for (unsigned int n=0; n<n_nodes; n++)
{
in >> x >> y >> z;
Node * node = new Node(x,y,z,n);
singleton_cache->node_list.push_back(node);
elem->set_node(n) = node;
}
// it is entirely possible we ran out of file or encountered
// another error. If so, cleanly abort.
if (!in)
{
delete elem;
elem = NULL;
libmesh_error_msg("ERROR while creating element singleton!");
}
else
singleton_cache->elem_list.push_back (elem);
ref_elem_map[Type] = elem;
return elem;
}
void init_ref_elem_table()
{
// ouside mutex - if this pointer is set, we can trust it.
if (singleton_cache != NULL) return;
// playing with fire here - lock before touching shared
// data structures
InitMutex::scoped_lock lock(init_mtx);
// inside mutex - pointer may have changed while waiting
// for the lock to acquire, check it again.
if (singleton_cache != NULL) return;
// OK, if we get here we have the lock and we are not
// initialized. populate singleton.
singleton_cache = new SingletonCache;
// initialize the reference file table
{
ref_elem_file.clear();
// // 1D elements
ref_elem_file[EDGE2] = ElemDataStrings::one_edge;
ref_elem_file[EDGE3] = ElemDataStrings::one_edge3;
ref_elem_file[EDGE4] = ElemDataStrings::one_edge4;
// 2D elements
ref_elem_file[TRI3] = ElemDataStrings::one_tri;
ref_elem_file[TRI6] = ElemDataStrings::one_tri6;
ref_elem_file[QUAD4] = ElemDataStrings::one_quad;
ref_elem_file[QUAD8] = ElemDataStrings::one_quad8;
ref_elem_file[QUAD9] = ElemDataStrings::one_quad9;
// 3D elements
ref_elem_file[HEX8] = ElemDataStrings::one_hex;
ref_elem_file[HEX20] = ElemDataStrings::one_hex20;
ref_elem_file[HEX27] = ElemDataStrings::one_hex27;
ref_elem_file[TET4] = ElemDataStrings::one_tet;
ref_elem_file[TET10] = ElemDataStrings::one_tet10;
ref_elem_file[PRISM6] = ElemDataStrings::one_prism;
ref_elem_file[PRISM15] = ElemDataStrings::one_prism15;
ref_elem_file[PRISM18] = ElemDataStrings::one_prism18;
ref_elem_file[PYRAMID5] = ElemDataStrings::one_pyramid;
ref_elem_file[PYRAMID13] = ElemDataStrings::one_pyramid13;
ref_elem_file[PYRAMID14] = ElemDataStrings::one_pyramid14;
}
// Read'em
for (FileMapType::const_iterator it=ref_elem_file.begin();
it != ref_elem_file.end(); ++it)
{
std::istringstream stream(it->second);
read_ref_elem(it->first,
stream);
}
}
// no reason to do this at startup -
// data structures will get initialized *if*
// ReferenceElem::get() is ever called.
// // Class to setup singleton data
// class ReferenceElemSetup : public Singleton::Setup
// {
// void setup ()
// {
// init_ref_elem_table();
// }
// } reference_elem_setup;
} // anonymous namespace
//----------------------------------------------------------------------------
// external API Implementation
namespace libMesh
{
namespace ReferenceElem
{
const Elem & get (const ElemType Type)
{
libmesh_assert_less (Type, INVALID_ELEM);
init_ref_elem_table();
libmesh_assert (ref_elem_map[Type] != NULL);
return *ref_elem_map[Type];
}
} // namespace ReferenceElem
} // namespace libMesh
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rsckey.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:46:38 $
*
* 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
*
************************************************************************/
/****************** I N C L U D E S **************************************/
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCKEY_HXX
#include <rsckey.hxx>
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
#define _cdecl __cdecl
#endif
/****************** C o d e **********************************************/
/****************** keyword sort function ********************************/
extern "C" {
#if defined( ZTC ) && defined( PM2 )
int __CLIB KeyCompare( const void * pFirst, const void * pSecond );
#else
#if defined( WNT ) && !defined( WTC ) && !defined (ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond );
#else
int KeyCompare( const void * pFirst, const void * pSecond );
#endif
#endif
}
#if defined( WNT ) && !defined( WTC ) && !defined(ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond ){
#else
int KeyCompare( const void * pFirst, const void * pSecond ){
#endif
if( ((KEY_STRUCT *)pFirst)->nName > ((KEY_STRUCT *)pSecond)->nName )
return( 1 );
else if( ((KEY_STRUCT *)pFirst)->nName < ((KEY_STRUCT *)pSecond)->nName )
return( -1 );
else
return( 0 );
}
/*************************************************************************
|*
|* RscNameTable::RscNameTable()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
RscNameTable::RscNameTable() {
bSort = TRUE;
nEntries = 0;
pTable = NULL;
};
/*************************************************************************
|*
|* RscNameTable::~RscNameTable()
|*
|* Beschreibung
|* Ersterstellung MM 15.05.91
|* Letzte Aenderung MM 15.05.91
|*
*************************************************************************/
RscNameTable::~RscNameTable() {
if( pTable )
rtl_freeMemory( pTable );
};
/*************************************************************************
|*
|* RscNameTable::SetSort()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
void RscNameTable::SetSort( BOOL bSorted ){
bSort = bSorted;
if( bSort && pTable){
// Schluesselwort Feld sortieren
qsort( (void *)pTable, nEntries,
sizeof( KEY_STRUCT ), KeyCompare );
};
};
/*************************************************************************
|*
|* RscNameTable::Put()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, long nValue ){
if( pTable )
pTable = (KEY_STRUCT *)
rtl_reallocateMemory( (void *)pTable,
((nEntries +1) * sizeof( KEY_STRUCT )) );
else
pTable = (KEY_STRUCT *)
rtl_allocateMemory( ((nEntries +1)
* sizeof( KEY_STRUCT )) );
pTable[ nEntries ].nName = nName;
pTable[ nEntries ].nTyp = nTyp;
pTable[ nEntries ].yylval = nValue;
nEntries++;
if( bSort )
SetSort();
return( nName );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, long nValue )
{
return( Put( pHS->getID( pName ), nTyp, nValue ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp )
{
return( Put( nName, nTyp, (long)nName ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp )
{
Atom nId;
nId = pHS->getID( pName );
return( Put( nId, nTyp, (long)nId ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( nName, nTyp, (long)pClass ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( pHS->getID( pName ), nTyp, (long)pClass ) );
};
/*************************************************************************
|*
|* RscNameTable::Get()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
BOOL RscNameTable::Get( Atom nName, KEY_STRUCT * pEle ){
KEY_STRUCT * pKey = NULL;
KEY_STRUCT aSearchName;
sal_uInt32 i;
if( bSort ){
// Suche nach dem Schluesselwort
aSearchName.nName = nName;
pKey = (KEY_STRUCT *)bsearch(
#ifdef UNX
(const char *) &aSearchName, (char *)pTable,
#else
(const void *) &aSearchName, (const void *)pTable,
#endif
nEntries, sizeof( KEY_STRUCT ), KeyCompare );
}
else{
i = 0;
while( i < nEntries && !pKey ){
if( pTable[ i ].nName == nName )
pKey = &pTable[ i ];
i++;
};
};
if( pKey ){ // Schluesselwort gefunden
*pEle = *pKey;
return( TRUE );
};
return( FALSE );
};
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.20); FILE MERGED 2006/09/01 17:33:21 kaib 1.5.20.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rsckey.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 15:59:43 $
*
* 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_rsc.hxx"
/****************** I N C L U D E S **************************************/
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCKEY_HXX
#include <rsckey.hxx>
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
#define _cdecl __cdecl
#endif
/****************** C o d e **********************************************/
/****************** keyword sort function ********************************/
extern "C" {
#if defined( ZTC ) && defined( PM2 )
int __CLIB KeyCompare( const void * pFirst, const void * pSecond );
#else
#if defined( WNT ) && !defined( WTC ) && !defined (ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond );
#else
int KeyCompare( const void * pFirst, const void * pSecond );
#endif
#endif
}
#if defined( WNT ) && !defined( WTC ) && !defined(ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond ){
#else
int KeyCompare( const void * pFirst, const void * pSecond ){
#endif
if( ((KEY_STRUCT *)pFirst)->nName > ((KEY_STRUCT *)pSecond)->nName )
return( 1 );
else if( ((KEY_STRUCT *)pFirst)->nName < ((KEY_STRUCT *)pSecond)->nName )
return( -1 );
else
return( 0 );
}
/*************************************************************************
|*
|* RscNameTable::RscNameTable()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
RscNameTable::RscNameTable() {
bSort = TRUE;
nEntries = 0;
pTable = NULL;
};
/*************************************************************************
|*
|* RscNameTable::~RscNameTable()
|*
|* Beschreibung
|* Ersterstellung MM 15.05.91
|* Letzte Aenderung MM 15.05.91
|*
*************************************************************************/
RscNameTable::~RscNameTable() {
if( pTable )
rtl_freeMemory( pTable );
};
/*************************************************************************
|*
|* RscNameTable::SetSort()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
void RscNameTable::SetSort( BOOL bSorted ){
bSort = bSorted;
if( bSort && pTable){
// Schluesselwort Feld sortieren
qsort( (void *)pTable, nEntries,
sizeof( KEY_STRUCT ), KeyCompare );
};
};
/*************************************************************************
|*
|* RscNameTable::Put()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, long nValue ){
if( pTable )
pTable = (KEY_STRUCT *)
rtl_reallocateMemory( (void *)pTable,
((nEntries +1) * sizeof( KEY_STRUCT )) );
else
pTable = (KEY_STRUCT *)
rtl_allocateMemory( ((nEntries +1)
* sizeof( KEY_STRUCT )) );
pTable[ nEntries ].nName = nName;
pTable[ nEntries ].nTyp = nTyp;
pTable[ nEntries ].yylval = nValue;
nEntries++;
if( bSort )
SetSort();
return( nName );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, long nValue )
{
return( Put( pHS->getID( pName ), nTyp, nValue ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp )
{
return( Put( nName, nTyp, (long)nName ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp )
{
Atom nId;
nId = pHS->getID( pName );
return( Put( nId, nTyp, (long)nId ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( nName, nTyp, (long)pClass ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( pHS->getID( pName ), nTyp, (long)pClass ) );
};
/*************************************************************************
|*
|* RscNameTable::Get()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
BOOL RscNameTable::Get( Atom nName, KEY_STRUCT * pEle ){
KEY_STRUCT * pKey = NULL;
KEY_STRUCT aSearchName;
sal_uInt32 i;
if( bSort ){
// Suche nach dem Schluesselwort
aSearchName.nName = nName;
pKey = (KEY_STRUCT *)bsearch(
#ifdef UNX
(const char *) &aSearchName, (char *)pTable,
#else
(const void *) &aSearchName, (const void *)pTable,
#endif
nEntries, sizeof( KEY_STRUCT ), KeyCompare );
}
else{
i = 0;
while( i < nEntries && !pKey ){
if( pTable[ i ].nName == nName )
pKey = &pTable[ i ];
i++;
};
};
if( pKey ){ // Schluesselwort gefunden
*pEle = *pKey;
return( TRUE );
};
return( FALSE );
};
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIWindowManager.cpp
created: 21/2/2004
author: Paul D Turner
purpose: Implements the WindowManager class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUIWindowManager.h"
#include "CEGUIWindowFactoryManager.h"
#include "CEGUIWindowFactory.h"
#include "CEGUIWindow.h"
#include "CEGUIExceptions.h"
#include "CEGUIGUILayout_xmlHandler.h"
#include "CEGUIXMLParser.h"
#include <iostream>
#include <sstream>
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> WindowManager* Singleton<WindowManager>::ms_Singleton = 0;
// default resource group
String WindowManager::d_defaultResourceGroup;
/*************************************************************************
Definition of constant data for WindowManager
*************************************************************************/
// Declared in WindowManager
const char WindowManager::GUILayoutSchemaName[] = "GUILayout.xsd";
const String WindowManager::GeneratedWindowNameBase("__cewin_uid_");
const String WindowManager::EventNamespace("WindowManager");
const String WindowManager::EventWindowCreated("WindowCreated");
const String WindowManager::EventWindowDestroyed("WindowDestroyed");
/*************************************************************************
Constructor
*************************************************************************/
WindowManager::WindowManager(void) :
d_uid_counter(0),
d_lockCount(0)
{
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(this));
Logger::getSingleton().logEvent(
"CEGUI::WindowManager singleton created " + String(addr_buff));
}
/*************************************************************************
Destructor
*************************************************************************/
WindowManager::~WindowManager(void)
{
destroyAllWindows();
cleanDeadPool();
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(this));
Logger::getSingleton().logEvent(
"CEGUI::WindowManager singleton destroyed " + String(addr_buff));
}
/*************************************************************************
Create a new window of the specified type
*************************************************************************/
Window* WindowManager::createWindow( const String& type, const String& name /*= ""*/, const String& prefix /*= ""*/ )
{
// only allow creation of Window objects if we are in unlocked state
if (isLocked())
throw InvalidRequestException("WindowManager::createWindow - "
"WindowManager is in the locked state.");
// Make sure that a non-empty name gets passed to the factory
String finalName(prefix + name);
// Still empty?
if (finalName.empty())
{
finalName = generateUniqueWindowName();
}
if (isWindowPresent(finalName))
{
throw AlreadyExistsException("WindowManager::createWindow - A Window object with the name '" + finalName +"' already exists within the system.");
}
WindowFactoryManager& wfMgr = WindowFactoryManager::getSingleton();
WindowFactory* factory = wfMgr.getFactory(type);
Window* newWindow = factory->createWindow(finalName);
newWindow->setPrefix(prefix);
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(newWindow));
Logger::getSingleton().logEvent("Window '" + finalName +"' of type '" +
type + "' has been created. " + addr_buff, Informative);
// see if we need to assign a look to this window
if (wfMgr.isFalagardMappedType(type))
{
const WindowFactoryManager::FalagardWindowMapping& fwm = wfMgr.getFalagardMappingForType(type);
// this was a mapped type, so assign a look to the window so it can finalise
// its initialisation
newWindow->d_falagardType = type;
newWindow->setWindowRenderer(fwm.d_rendererType);
newWindow->setLookNFeel(fwm.d_lookName);
}
d_windowRegistry[finalName] = newWindow;
// fire event to notify interested parites about the new window.
WindowEventArgs args(newWindow);
fireEvent(EventWindowCreated, args);
return newWindow;
}
/*************************************************************************
Destroy the given window by pointer
*************************************************************************/
void WindowManager::destroyWindow(Window* window)
{
if (window)
{
// this is done because the name is used for the log after the window is destroyed,
// if we just did getName() we would get a const ref to the Window's internal name
// string which is destroyed along with the window so wouldn't exist when the log tried
// to use it (as I soon discovered).
String name = window->getName();
destroyWindow(name);
}
}
/*************************************************************************
Destroy the given window by name
*************************************************************************/
void WindowManager::destroyWindow(const String& window)
{
WindowRegistry::iterator wndpos = d_windowRegistry.find(window);
if (wndpos != d_windowRegistry.end())
{
Window* wnd = wndpos->second;
// remove entry from the WindowRegistry.
d_windowRegistry.erase(wndpos);
// do 'safe' part of cleanup
wnd->destroy();
// add window to dead pool
d_deathrow.push_back(wnd);
// notify system object of the window destruction
System::getSingleton().notifyWindowDestroyed(wnd);
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(wnd));
Logger::getSingleton().logEvent("Window '" + window + "' has been "
"added to dead pool. " + addr_buff, Informative);
// fire event to notify interested parites about window destruction.
// TODO: Perhaps this should fire first, so window is still usable?
WindowEventArgs args(wnd);
fireEvent(EventWindowDestroyed, args);
}
}
/*************************************************************************
Return a pointer to the named window
*************************************************************************/
Window* WindowManager::getWindow(const String& name) const
{
WindowRegistry::const_iterator pos = d_windowRegistry.find(name);
if (pos == d_windowRegistry.end())
{
throw UnknownObjectException("WindowManager::getWindow - A Window object with the name '" + name +"' does not exist within the system");
}
return pos->second;
}
/*************************************************************************
Return true if a window with the given name is present
*************************************************************************/
bool WindowManager::isWindowPresent(const String& name) const
{
return (d_windowRegistry.find(name) != d_windowRegistry.end());
}
/*************************************************************************
Destroy all Window objects
*************************************************************************/
void WindowManager::destroyAllWindows(void)
{
String window_name;
while (!d_windowRegistry.empty())
{
window_name = d_windowRegistry.begin()->first;
destroyWindow(window_name);
}
}
/*************************************************************************
Creates a set of windows (a Gui layout) from the information in the
specified XML file.
*************************************************************************/
Window* WindowManager::loadWindowLayout(const String& filename, const String& name_prefix, const String& resourceGroup, PropertyCallback* callback, void* userdata)
{
if (filename.empty())
{
throw InvalidRequestException("WindowManager::loadWindowLayout - Filename supplied for gui-layout loading must be valid.");
}
// log the fact we are about to load a layout
Logger::getSingleton().logEvent("---- Beginning loading of GUI layout from '" + filename + "' ----", Informative);
// create handler object
GUILayout_xmlHandler handler(name_prefix, callback, userdata);
// do parse (which uses handler to create actual data)
try
{
System::getSingleton().getXMLParser()->parseXMLFile(handler,
filename, GUILayoutSchemaName, resourceGroup.empty() ? d_defaultResourceGroup : resourceGroup);
}
catch(...)
{
Logger::getSingleton().logEvent("WindowManager::loadWindowLayout - loading of layout from file '" + filename +"' failed.", Errors);
throw;
}
// log the completion of loading
Logger::getSingleton().logEvent("---- Successfully completed loading of GUI layout from '" + filename + "' ----", Standard);
return handler.getLayoutRootWindow();
}
Window* WindowManager::loadWindowLayout( const String& filename, bool generateRandomPrefix )
{
//We really just use the bool to get rid of ambiguity with the other loadWindowLayout. There is no difference between
//calling this loadWindowLayout and setting GRP to false, and calling the other one with no argument
if(generateRandomPrefix)
return loadWindowLayout(filename,generateUniqueWindowPrefix());
return loadWindowLayout(filename);
}
bool WindowManager::isDeadPoolEmpty(void) const
{
return d_deathrow.empty();
}
void WindowManager::cleanDeadPool(void)
{
WindowVector::reverse_iterator curr = d_deathrow.rbegin();
for (; curr != d_deathrow.rend(); ++curr)
{
// in debug mode, log what gets cleaned from the dead pool (insane level)
#if defined(DEBUG) || defined (_DEBUG)
CEGUI_LOGINSANE("Window '" + (*curr)->getName() + "' about to be finally destroyed from dead pool.");
#endif
WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory((*curr)->getType());
factory->destroyWindow(*curr);
}
// all done here, so clear all pointers from dead pool
d_deathrow.clear();
}
void WindowManager::writeWindowLayoutToStream(const Window& window, OutStream& out_stream, bool writeParent) const
{
XMLSerializer xml(out_stream);
// output GUILayout start element
xml.openTag("GUILayout");
// see if we need the parent attribute to be written
if ((window.getParent() != 0) && writeParent)
{
xml.attribute("Parent", window.getParent()->getName());
}
// write windows
window.writeXMLToStream(xml);
// write closing GUILayout element
xml.closeTag();
}
void WindowManager::writeWindowLayoutToStream(const String& window, OutStream& out_stream, bool writeParent) const
{
writeWindowLayoutToStream(*getWindow(window), out_stream, writeParent);
}
String WindowManager::generateUniqueWindowName()
{
// build name
std::ostringstream uidname;
uidname << GeneratedWindowNameBase.c_str() << d_uid_counter;
// update counter for next time
unsigned long old_uid = d_uid_counter;
++d_uid_counter;
// log if we ever wrap-around (which should be pretty unlikely)
if (d_uid_counter < old_uid)
Logger::getSingleton().logEvent("UID counter for generated window names has wrapped around - the fun shall now commence!");
// return generated name as a CEGUI::String.
return String(uidname.str());
}
CEGUI::String WindowManager::generateUniqueWindowPrefix()
{
std::ostringstream prefix;
prefix << d_uid_counter << "_";
// update counter for next time
unsigned long old_uid = d_uid_counter;
++d_uid_counter;
// log if we ever wrap-around (which should be pretty unlikely)
if (d_uid_counter < old_uid)
Logger::getSingleton().logEvent("UID counter for generated window names has wrapped around - the fun shall now commence!");
//return generated prefix
return String(prefix.str());
}
void WindowManager::renameWindow(const String& window, const String& new_name)
{
renameWindow(getWindow(window), new_name);
}
void WindowManager::renameWindow(Window* window, const String& new_name)
{
if (window)
{
WindowRegistry::iterator pos = d_windowRegistry.find(window->getName());
if (pos != d_windowRegistry.end())
{
// erase old window name from registry
d_windowRegistry.erase(pos);
try
{
// attempt to rename the window
window->rename(new_name);
}
// rename fails if target name already exists
catch (AlreadyExistsException&)
{
// re-add window to registry under it's old name
d_windowRegistry[window->getName()] = window;
// rethrow exception.
throw;
}
// add window to registry under new name
d_windowRegistry[new_name] = window;
}
}
}
/*************************************************************************
Return a WindowManager::WindowIterator object to iterate over the
currently defined Windows.
*************************************************************************/
WindowManager::WindowIterator WindowManager::getIterator(void) const
{
return WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end());
}
/*************************************************************************
Outputs the names of ALL existing windows to log (DEBUG function).
*************************************************************************/
void WindowManager::DEBUG_dumpWindowNames(String zone)
{
Logger::getSingleton().logEvent("WINDOW NAMES DUMP (" + zone + ")");
Logger::getSingleton().logEvent("-----------------");
CEGUI::WindowManager::WindowIterator windowIt = getIterator();
while (!windowIt.isAtEnd())
{
Logger::getSingleton().logEvent("Window : " + windowIt.getCurrentValue()->getName());
++windowIt;
}
Logger::getSingleton().logEvent("-----------------");
}
//----------------------------------------------------------------------------//
void WindowManager::lock()
{
++d_lockCount;
}
//----------------------------------------------------------------------------//
void WindowManager::unlock()
{
if (d_lockCount > 0)
--d_lockCount;
}
//----------------------------------------------------------------------------//
bool WindowManager::isLocked() const
{
return d_lockCount != 0;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>Forgot to include the EventNamespace for global event set support of WindowManager events (not that it's important in this case).<commit_after>/***********************************************************************
filename: CEGUIWindowManager.cpp
created: 21/2/2004
author: Paul D Turner
purpose: Implements the WindowManager class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUIWindowManager.h"
#include "CEGUIWindowFactoryManager.h"
#include "CEGUIWindowFactory.h"
#include "CEGUIWindow.h"
#include "CEGUIExceptions.h"
#include "CEGUIGUILayout_xmlHandler.h"
#include "CEGUIXMLParser.h"
#include <iostream>
#include <sstream>
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> WindowManager* Singleton<WindowManager>::ms_Singleton = 0;
// default resource group
String WindowManager::d_defaultResourceGroup;
/*************************************************************************
Definition of constant data for WindowManager
*************************************************************************/
// Declared in WindowManager
const char WindowManager::GUILayoutSchemaName[] = "GUILayout.xsd";
const String WindowManager::GeneratedWindowNameBase("__cewin_uid_");
const String WindowManager::EventNamespace("WindowManager");
const String WindowManager::EventWindowCreated("WindowCreated");
const String WindowManager::EventWindowDestroyed("WindowDestroyed");
/*************************************************************************
Constructor
*************************************************************************/
WindowManager::WindowManager(void) :
d_uid_counter(0),
d_lockCount(0)
{
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(this));
Logger::getSingleton().logEvent(
"CEGUI::WindowManager singleton created " + String(addr_buff));
}
/*************************************************************************
Destructor
*************************************************************************/
WindowManager::~WindowManager(void)
{
destroyAllWindows();
cleanDeadPool();
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(this));
Logger::getSingleton().logEvent(
"CEGUI::WindowManager singleton destroyed " + String(addr_buff));
}
/*************************************************************************
Create a new window of the specified type
*************************************************************************/
Window* WindowManager::createWindow( const String& type, const String& name /*= ""*/, const String& prefix /*= ""*/ )
{
// only allow creation of Window objects if we are in unlocked state
if (isLocked())
throw InvalidRequestException("WindowManager::createWindow - "
"WindowManager is in the locked state.");
// Make sure that a non-empty name gets passed to the factory
String finalName(prefix + name);
// Still empty?
if (finalName.empty())
{
finalName = generateUniqueWindowName();
}
if (isWindowPresent(finalName))
{
throw AlreadyExistsException("WindowManager::createWindow - A Window object with the name '" + finalName +"' already exists within the system.");
}
WindowFactoryManager& wfMgr = WindowFactoryManager::getSingleton();
WindowFactory* factory = wfMgr.getFactory(type);
Window* newWindow = factory->createWindow(finalName);
newWindow->setPrefix(prefix);
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(newWindow));
Logger::getSingleton().logEvent("Window '" + finalName +"' of type '" +
type + "' has been created. " + addr_buff, Informative);
// see if we need to assign a look to this window
if (wfMgr.isFalagardMappedType(type))
{
const WindowFactoryManager::FalagardWindowMapping& fwm = wfMgr.getFalagardMappingForType(type);
// this was a mapped type, so assign a look to the window so it can finalise
// its initialisation
newWindow->d_falagardType = type;
newWindow->setWindowRenderer(fwm.d_rendererType);
newWindow->setLookNFeel(fwm.d_lookName);
}
d_windowRegistry[finalName] = newWindow;
// fire event to notify interested parites about the new window.
WindowEventArgs args(newWindow);
fireEvent(EventWindowCreated, args, EventNamespace);
return newWindow;
}
/*************************************************************************
Destroy the given window by pointer
*************************************************************************/
void WindowManager::destroyWindow(Window* window)
{
if (window)
{
// this is done because the name is used for the log after the window is destroyed,
// if we just did getName() we would get a const ref to the Window's internal name
// string which is destroyed along with the window so wouldn't exist when the log tried
// to use it (as I soon discovered).
String name = window->getName();
destroyWindow(name);
}
}
/*************************************************************************
Destroy the given window by name
*************************************************************************/
void WindowManager::destroyWindow(const String& window)
{
WindowRegistry::iterator wndpos = d_windowRegistry.find(window);
if (wndpos != d_windowRegistry.end())
{
Window* wnd = wndpos->second;
// remove entry from the WindowRegistry.
d_windowRegistry.erase(wndpos);
// do 'safe' part of cleanup
wnd->destroy();
// add window to dead pool
d_deathrow.push_back(wnd);
// notify system object of the window destruction
System::getSingleton().notifyWindowDestroyed(wnd);
char addr_buff[32];
sprintf(addr_buff, "(%p)", static_cast<void*>(wnd));
Logger::getSingleton().logEvent("Window '" + window + "' has been "
"added to dead pool. " + addr_buff, Informative);
// fire event to notify interested parites about window destruction.
// TODO: Perhaps this should fire first, so window is still usable?
WindowEventArgs args(wnd);
fireEvent(EventWindowDestroyed, args, EventNamespace);
}
}
/*************************************************************************
Return a pointer to the named window
*************************************************************************/
Window* WindowManager::getWindow(const String& name) const
{
WindowRegistry::const_iterator pos = d_windowRegistry.find(name);
if (pos == d_windowRegistry.end())
{
throw UnknownObjectException("WindowManager::getWindow - A Window object with the name '" + name +"' does not exist within the system");
}
return pos->second;
}
/*************************************************************************
Return true if a window with the given name is present
*************************************************************************/
bool WindowManager::isWindowPresent(const String& name) const
{
return (d_windowRegistry.find(name) != d_windowRegistry.end());
}
/*************************************************************************
Destroy all Window objects
*************************************************************************/
void WindowManager::destroyAllWindows(void)
{
String window_name;
while (!d_windowRegistry.empty())
{
window_name = d_windowRegistry.begin()->first;
destroyWindow(window_name);
}
}
/*************************************************************************
Creates a set of windows (a Gui layout) from the information in the
specified XML file.
*************************************************************************/
Window* WindowManager::loadWindowLayout(const String& filename, const String& name_prefix, const String& resourceGroup, PropertyCallback* callback, void* userdata)
{
if (filename.empty())
{
throw InvalidRequestException("WindowManager::loadWindowLayout - Filename supplied for gui-layout loading must be valid.");
}
// log the fact we are about to load a layout
Logger::getSingleton().logEvent("---- Beginning loading of GUI layout from '" + filename + "' ----", Informative);
// create handler object
GUILayout_xmlHandler handler(name_prefix, callback, userdata);
// do parse (which uses handler to create actual data)
try
{
System::getSingleton().getXMLParser()->parseXMLFile(handler,
filename, GUILayoutSchemaName, resourceGroup.empty() ? d_defaultResourceGroup : resourceGroup);
}
catch(...)
{
Logger::getSingleton().logEvent("WindowManager::loadWindowLayout - loading of layout from file '" + filename +"' failed.", Errors);
throw;
}
// log the completion of loading
Logger::getSingleton().logEvent("---- Successfully completed loading of GUI layout from '" + filename + "' ----", Standard);
return handler.getLayoutRootWindow();
}
Window* WindowManager::loadWindowLayout( const String& filename, bool generateRandomPrefix )
{
//We really just use the bool to get rid of ambiguity with the other loadWindowLayout. There is no difference between
//calling this loadWindowLayout and setting GRP to false, and calling the other one with no argument
if(generateRandomPrefix)
return loadWindowLayout(filename,generateUniqueWindowPrefix());
return loadWindowLayout(filename);
}
bool WindowManager::isDeadPoolEmpty(void) const
{
return d_deathrow.empty();
}
void WindowManager::cleanDeadPool(void)
{
WindowVector::reverse_iterator curr = d_deathrow.rbegin();
for (; curr != d_deathrow.rend(); ++curr)
{
// in debug mode, log what gets cleaned from the dead pool (insane level)
#if defined(DEBUG) || defined (_DEBUG)
CEGUI_LOGINSANE("Window '" + (*curr)->getName() + "' about to be finally destroyed from dead pool.");
#endif
WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory((*curr)->getType());
factory->destroyWindow(*curr);
}
// all done here, so clear all pointers from dead pool
d_deathrow.clear();
}
void WindowManager::writeWindowLayoutToStream(const Window& window, OutStream& out_stream, bool writeParent) const
{
XMLSerializer xml(out_stream);
// output GUILayout start element
xml.openTag("GUILayout");
// see if we need the parent attribute to be written
if ((window.getParent() != 0) && writeParent)
{
xml.attribute("Parent", window.getParent()->getName());
}
// write windows
window.writeXMLToStream(xml);
// write closing GUILayout element
xml.closeTag();
}
void WindowManager::writeWindowLayoutToStream(const String& window, OutStream& out_stream, bool writeParent) const
{
writeWindowLayoutToStream(*getWindow(window), out_stream, writeParent);
}
String WindowManager::generateUniqueWindowName()
{
// build name
std::ostringstream uidname;
uidname << GeneratedWindowNameBase.c_str() << d_uid_counter;
// update counter for next time
unsigned long old_uid = d_uid_counter;
++d_uid_counter;
// log if we ever wrap-around (which should be pretty unlikely)
if (d_uid_counter < old_uid)
Logger::getSingleton().logEvent("UID counter for generated window names has wrapped around - the fun shall now commence!");
// return generated name as a CEGUI::String.
return String(uidname.str());
}
CEGUI::String WindowManager::generateUniqueWindowPrefix()
{
std::ostringstream prefix;
prefix << d_uid_counter << "_";
// update counter for next time
unsigned long old_uid = d_uid_counter;
++d_uid_counter;
// log if we ever wrap-around (which should be pretty unlikely)
if (d_uid_counter < old_uid)
Logger::getSingleton().logEvent("UID counter for generated window names has wrapped around - the fun shall now commence!");
//return generated prefix
return String(prefix.str());
}
void WindowManager::renameWindow(const String& window, const String& new_name)
{
renameWindow(getWindow(window), new_name);
}
void WindowManager::renameWindow(Window* window, const String& new_name)
{
if (window)
{
WindowRegistry::iterator pos = d_windowRegistry.find(window->getName());
if (pos != d_windowRegistry.end())
{
// erase old window name from registry
d_windowRegistry.erase(pos);
try
{
// attempt to rename the window
window->rename(new_name);
}
// rename fails if target name already exists
catch (AlreadyExistsException&)
{
// re-add window to registry under it's old name
d_windowRegistry[window->getName()] = window;
// rethrow exception.
throw;
}
// add window to registry under new name
d_windowRegistry[new_name] = window;
}
}
}
/*************************************************************************
Return a WindowManager::WindowIterator object to iterate over the
currently defined Windows.
*************************************************************************/
WindowManager::WindowIterator WindowManager::getIterator(void) const
{
return WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end());
}
/*************************************************************************
Outputs the names of ALL existing windows to log (DEBUG function).
*************************************************************************/
void WindowManager::DEBUG_dumpWindowNames(String zone)
{
Logger::getSingleton().logEvent("WINDOW NAMES DUMP (" + zone + ")");
Logger::getSingleton().logEvent("-----------------");
CEGUI::WindowManager::WindowIterator windowIt = getIterator();
while (!windowIt.isAtEnd())
{
Logger::getSingleton().logEvent("Window : " + windowIt.getCurrentValue()->getName());
++windowIt;
}
Logger::getSingleton().logEvent("-----------------");
}
//----------------------------------------------------------------------------//
void WindowManager::lock()
{
++d_lockCount;
}
//----------------------------------------------------------------------------//
void WindowManager::unlock()
{
if (d_lockCount > 0)
--d_lockCount;
}
//----------------------------------------------------------------------------//
bool WindowManager::isLocked() const
{
return d_lockCount != 0;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>
#include "../Flare.h"
#include "FlareTurret.h"
#include "FlareSpacecraft.h"
#include "FlareShell.h"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareTurret::UFlareTurret(const class FObjectInitializer& PCIP)
: Super(PCIP)
, TurretComponent(NULL)
, BarrelComponent(NULL)
{
HasFlickeringLights = false;
}
/*----------------------------------------------------
Gameplay
----------------------------------------------------*/
void UFlareTurret::Initialize(const FFlareSpacecraftComponentSave* Data, UFlareCompany* Company, AFlareSpacecraftPawn* OwnerShip, bool IsInMenu)
{
Super::Initialize(Data, Company, OwnerShip, IsInMenu);
AimDirection = FVector::ZeroVector;
// Initialize pilot
Pilot = NewObject<UFlareTurretPilot>(this, UFlareTurretPilot::StaticClass());
Pilot->Initialize(&(Data->Pilot), Company, this);
}
void UFlareTurret::SetupFiringEffects()
{
if (FiringEffect == NULL && FiringEffectTemplate)
{
FiringEffects.Empty();
for (int32 i = 0; i < ComponentDescription->WeaponCharacteristics.GunCharacteristics.GunCount; i++)
{
// Create the effect
UParticleSystemComponent* TempFiringEffect = UGameplayStatics::SpawnEmitterAttached(
FiringEffectTemplate,
this,
NAME_None,
GetMuzzleLocation(i),
GetComponentRotation(),
EAttachLocation::KeepWorldPosition,
false);
// Additional setup
TempFiringEffect->DeactivateSystem();
TempFiringEffect->SetTickGroup(ETickingGroup::TG_PostPhysics);
FiringEffects.Add(TempFiringEffect);
}
}
}
void UFlareTurret::SetupComponentMesh()
{
Super::SetupComponentMesh();
// Turret Mesh
if (Spacecraft && ComponentDescription && ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMesh)
{
TurretComponent = NewObject<UFlareSpacecraftSubComponent>(this, UFlareSpacecraftSubComponent::StaticClass(), TEXT("TurretMesh"));
if (TurretComponent)
{
TurretComponent->SetParentSpacecraftComponent(this);
TurretComponent->RegisterComponent();
TurretComponent->AttachTo(this);
TurretComponent->SetStaticMesh(ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMesh);
TurretComponent->SetMaterial(0, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMesh->GetMaterial(0));
TurretComponent->Initialize(NULL, PlayerCompany, Spacecraft, false);
Spacecraft->AddOwnedComponent(TurretComponent);
}
}
// Barrel Mesh
if (Spacecraft && ComponentDescription && ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMesh)
{
BarrelComponent = NewObject<UFlareSpacecraftSubComponent>(this, UFlareSpacecraftSubComponent::StaticClass() , TEXT("BarrelMesh"));
if (BarrelComponent)
{
BarrelComponent->SetParentSpacecraftComponent(this);
BarrelComponent->RegisterComponent();
if (TurretComponent)
{
BarrelComponent->AttachTo(TurretComponent, FName("Axis"));
}
else
{
BarrelComponent->AttachTo(this);
}
BarrelComponent->SetStaticMesh(ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMesh);
BarrelComponent->SetMaterial(0, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMesh->GetMaterial(0));
Spacecraft->AddOwnedComponent(BarrelComponent);
}
}
}
void UFlareTurret::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
if (Spacecraft->GetDamageSystem()->IsAlive() && Pilot)
{
Pilot->TickPilot(DeltaTime);
//FLOGV("Pilot exist WantFire %d", Pilot->IsWantFire());
if (Pilot->IsWantFire())
{
StartFire();
}
else
{
StopFire();
}
AimDirection = Pilot->GetTargetAimAxis();
//FLOGV("Pilot AimDirection %s", *AimDirection.ToString());
}
if (Spacecraft->GetDamageSystem()->IsAlive() && GetUsableRatio() > 0)
{
if (TurretComponent && ComponentDescription)
{
float TargetTurretAngle = 0;
if (AimDirection != FVector::ZeroVector)
{
FVector LocalTurretAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(AimDirection);
TargetTurretAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalTurretAimDirection.Y, LocalTurretAimDirection.X)));
}
// Clamp movements
TargetTurretAngle = FMath::Clamp(TargetTurretAngle, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMinAngle, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMaxAngle);
float UsableTurretVelocity = GetUsableRatio() * ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretAngularVelocity;
float TurretAngleDiff = FMath::UnwindDegrees(TargetTurretAngle - ShipComponentData.Turret.TurretAngle);
if (FMath::Abs(TurretAngleDiff) <= UsableTurretVelocity * DeltaTime)
{
ShipComponentData.Turret.TurretAngle = TargetTurretAngle;
}
else if (TurretAngleDiff < 0)
{
ShipComponentData.Turret.TurretAngle -= UsableTurretVelocity * DeltaTime;
}
else
{
ShipComponentData.Turret.TurretAngle += UsableTurretVelocity * DeltaTime;
}
TurretComponent->SetRelativeRotation(FRotator(0, ShipComponentData.Turret.TurretAngle, 0));
}
if (BarrelComponent)
{
float TargetBarrelAngle = 15;
if (AimDirection != FVector::ZeroVector)
{
FVector LocalBarrelAimDirection;
if (TurretComponent)
{
LocalBarrelAimDirection = TurretComponent->GetComponentToWorld().GetRotation().Inverse().RotateVector(AimDirection);
}
else
{
LocalBarrelAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(AimDirection);
}
TargetBarrelAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalBarrelAimDirection.Z, LocalBarrelAimDirection.X)));
}
// Clamp movements
TargetBarrelAngle = FMath::Clamp(TargetBarrelAngle, GetMinLimitAtAngle(ShipComponentData.Turret.TurretAngle), ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMaxAngle);
// TODO Add ship specific bound
float UsableBarrelsVelocity = GetUsableRatio() * ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretAngularVelocity;
float BarrelAngleDiff = FMath::UnwindDegrees(TargetBarrelAngle - ShipComponentData.Turret.BarrelsAngle);
if (FMath::Abs(BarrelAngleDiff) <= UsableBarrelsVelocity * DeltaTime) {
ShipComponentData.Turret.BarrelsAngle = TargetBarrelAngle;
} else if (BarrelAngleDiff < 0) {
ShipComponentData.Turret.BarrelsAngle -= UsableBarrelsVelocity * DeltaTime;
} else {
ShipComponentData.Turret.BarrelsAngle += UsableBarrelsVelocity * DeltaTime;
}
BarrelComponent->SetRelativeRotation(FRotator(ShipComponentData.Turret.BarrelsAngle, 0, 0));
}
}
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
FVector UFlareTurret::GetFireAxis() const
{
if (BarrelComponent)
{
return BarrelComponent->GetComponentRotation().RotateVector(FVector(1, 0, 0));
}
else if (TurretComponent)
{
return TurretComponent->GetComponentRotation().RotateVector(FVector(1, 0, 0));
}
else
{
return Super::GetFireAxis();
}
}
FVector UFlareTurret::GetIdleAxis() const
{
// Ship front
return Spacecraft->Airframe->GetComponentRotation().RotateVector(FVector(1, 0, 0));
}
FVector UFlareTurret::GetMuzzleLocation(int GunIndex) const
{
const UStaticMeshComponent* GunComponent = this;
if (BarrelComponent)
{
GunComponent = BarrelComponent;
}
else if (TurretComponent)
{
GunComponent = TurretComponent;
}
if (ComponentDescription->WeaponCharacteristics.GunCharacteristics.GunCount <= 1)
{
return GunComponent->GetSocketLocation(FName("Muzzle"));
}
else
{
return GunComponent->GetSocketLocation(FName(*(FString("Muzzle") + FString::FromInt(GunIndex))));
}
}
FVector UFlareTurret::GetTurretBaseLocation() const
{
if (BarrelComponent)
{
return BarrelComponent->GetComponentLocation();
}
else if (TurretComponent)
{
return TurretComponent->GetComponentLocation();
}
return GetComponentLocation();
}
bool UFlareTurret::IsSafeToFire(int GunIndex) const
{
FVector FiringLocation = GetMuzzleLocation(GunIndex);
FVector FiringDirection = GetFireAxis();
FVector TargetLocation = FiringLocation + FiringDirection * 100000;
FHitResult HitResult(ForceInit);
if (Trace(FiringLocation, TargetLocation, HitResult))
{
if (HitResult.Actor.IsValid() && HitResult.Actor == Spacecraft)
{
FLOG("!!!!!!!!!Not safe to fire !");
return false;
}
}
return true;
}
bool UFlareTurret::Trace(const FVector& Start, const FVector& End, FHitResult& HitOut) const
{
FCollisionQueryParams TraceParams(FName(TEXT("Shell Trace")), true, NULL);
TraceParams.bTraceComplex = true;
//TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = false;
//Re-initialize hit info
HitOut = FHitResult(ForceInit);
ECollisionChannel CollisionChannel = (ECollisionChannel) (ECC_WorldStatic | ECC_WorldDynamic | ECC_Pawn);
//Trace!
GetWorld()->LineTraceSingleByChannel(
HitOut, //result
Start, //start
End , //end
CollisionChannel, //collision channel
TraceParams
);
//Hit any Actor?
return (HitOut.GetActor() != NULL) ;
}
bool UFlareTurret::IsReacheableAxis(FVector TargetAxis) const
{
float TargetTurretAngle = 0;
if (TurretComponent && ComponentDescription)
{
FVector LocalTurretAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(TargetAxis);
TargetTurretAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalTurretAimDirection.Y, LocalTurretAimDirection.X)));
if (TargetTurretAngle > ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMaxAngle
|| TargetTurretAngle < ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMinAngle)
{
return false;
}
}
if (BarrelComponent && ComponentDescription)
{
FVector LocalBarrelAimDirection;
if (TurretComponent)
{
LocalBarrelAimDirection = TurretComponent->GetComponentToWorld().GetRotation().Inverse().RotateVector(TargetAxis);
}
else
{
LocalBarrelAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(TargetAxis);
}
float TargetBarrelAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalBarrelAimDirection.Z, LocalBarrelAimDirection.X)));
if (TargetBarrelAngle > ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMaxAngle
|| TargetBarrelAngle < GetMinLimitAtAngle(TargetTurretAngle))
{
return false;
}
}
return true;
}
static inline int PositiveModulo(int i, int n)
{
return (i % n + n) % n;
}
float UFlareTurret::GetMinLimitAtAngle(float Angle) const
{
float BarrelsMinAngle = ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMinAngle;
//Fine Local slot check
for (int32 i = 0; i < Spacecraft->GetDescription()->TurretSlots.Num(); i++)
{
// TODO optimize and store that in cache
if (Spacecraft->GetDescription()->TurretSlots[i].SlotIdentifier == ShipComponentData.ShipSlotIdentifier)
{
int LimitStepCount = Spacecraft->GetDescription()->TurretSlots[i].TurretBarrelsAngleLimit.Num();
if (LimitStepCount > 0)
{
float StepAngle = 360.f / (float) LimitStepCount;
float AngleInStep = Angle / StepAngle;
int NearestStep = FMath::FloorToInt(AngleInStep + 0.5f);
int SecondNearestStep;
if (AngleInStep > NearestStep)
{
SecondNearestStep = NearestStep+1;
}
else
{
SecondNearestStep = NearestStep-1;
}
float Ratio = FMath::Abs(Angle - NearestStep * StepAngle) / StepAngle;
float LocalMin = Spacecraft->GetDescription()->TurretSlots[i].TurretBarrelsAngleLimit[PositiveModulo(NearestStep, LimitStepCount)] * (1.f - Ratio)
+ Spacecraft->GetDescription()->TurretSlots[i].TurretBarrelsAngleLimit[PositiveModulo(SecondNearestStep,LimitStepCount)] * Ratio;
BarrelsMinAngle = FMath::Max(BarrelsMinAngle, LocalMin);
}
}
}
return BarrelsMinAngle;
}
void UFlareTurret::GetBoundingSphere(FVector& Location, float& SphereRadius)
{
Super::GetBoundingSphere(Location, SphereRadius);
if (TurretComponent || BarrelComponent)
{
SphereRadius = 0;
}
}
void UFlareTurret::ShowFiringEffects(int GunIndex)
{
if (FiringEffects[GunIndex])
{
FiringEffects[GunIndex]->ActivateSystem();
}
}
<commit_msg>Don't rotate turret in presentation mode<commit_after>
#include "../Flare.h"
#include "FlareTurret.h"
#include "FlareSpacecraft.h"
#include "FlareShell.h"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareTurret::UFlareTurret(const class FObjectInitializer& PCIP)
: Super(PCIP)
, TurretComponent(NULL)
, BarrelComponent(NULL)
{
HasFlickeringLights = false;
}
/*----------------------------------------------------
Gameplay
----------------------------------------------------*/
void UFlareTurret::Initialize(const FFlareSpacecraftComponentSave* Data, UFlareCompany* Company, AFlareSpacecraftPawn* OwnerShip, bool IsInMenu)
{
Super::Initialize(Data, Company, OwnerShip, IsInMenu);
AimDirection = FVector::ZeroVector;
// Initialize pilot
Pilot = NewObject<UFlareTurretPilot>(this, UFlareTurretPilot::StaticClass());
Pilot->Initialize(&(Data->Pilot), Company, this);
}
void UFlareTurret::SetupFiringEffects()
{
if (FiringEffect == NULL && FiringEffectTemplate)
{
FiringEffects.Empty();
for (int32 i = 0; i < ComponentDescription->WeaponCharacteristics.GunCharacteristics.GunCount; i++)
{
// Create the effect
UParticleSystemComponent* TempFiringEffect = UGameplayStatics::SpawnEmitterAttached(
FiringEffectTemplate,
this,
NAME_None,
GetMuzzleLocation(i),
GetComponentRotation(),
EAttachLocation::KeepWorldPosition,
false);
// Additional setup
TempFiringEffect->DeactivateSystem();
TempFiringEffect->SetTickGroup(ETickingGroup::TG_PostPhysics);
FiringEffects.Add(TempFiringEffect);
}
}
}
void UFlareTurret::SetupComponentMesh()
{
Super::SetupComponentMesh();
// Turret Mesh
if (Spacecraft && ComponentDescription && ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMesh)
{
TurretComponent = NewObject<UFlareSpacecraftSubComponent>(this, UFlareSpacecraftSubComponent::StaticClass(), TEXT("TurretMesh"));
if (TurretComponent)
{
TurretComponent->SetParentSpacecraftComponent(this);
TurretComponent->RegisterComponent();
TurretComponent->AttachTo(this);
TurretComponent->SetStaticMesh(ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMesh);
TurretComponent->SetMaterial(0, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMesh->GetMaterial(0));
TurretComponent->Initialize(NULL, PlayerCompany, Spacecraft, false);
Spacecraft->AddOwnedComponent(TurretComponent);
}
}
// Barrel Mesh
if (Spacecraft && ComponentDescription && ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMesh)
{
BarrelComponent = NewObject<UFlareSpacecraftSubComponent>(this, UFlareSpacecraftSubComponent::StaticClass() , TEXT("BarrelMesh"));
if (BarrelComponent)
{
BarrelComponent->SetParentSpacecraftComponent(this);
BarrelComponent->RegisterComponent();
if (TurretComponent)
{
BarrelComponent->AttachTo(TurretComponent, FName("Axis"));
}
else
{
BarrelComponent->AttachTo(this);
}
BarrelComponent->SetStaticMesh(ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMesh);
BarrelComponent->SetMaterial(0, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMesh->GetMaterial(0));
Spacecraft->AddOwnedComponent(BarrelComponent);
}
}
}
void UFlareTurret::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
if (Spacecraft->GetDamageSystem()->IsAlive() && Pilot)
{
Pilot->TickPilot(DeltaTime);
//FLOGV("Pilot exist WantFire %d", Pilot->IsWantFire());
if (Pilot->IsWantFire())
{
StartFire();
}
else
{
StopFire();
}
AimDirection = Pilot->GetTargetAimAxis();
//FLOGV("Pilot AimDirection %s", *AimDirection.ToString());
}
if (Spacecraft->GetDamageSystem()->IsAlive() && GetUsableRatio() > 0)
{
if (TurretComponent && ComponentDescription)
{
float TargetTurretAngle = 0;
if (AimDirection != FVector::ZeroVector)
{
FVector LocalTurretAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(AimDirection);
TargetTurretAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalTurretAimDirection.Y, LocalTurretAimDirection.X)));
}
// Clamp movements
TargetTurretAngle = FMath::Clamp(TargetTurretAngle, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMinAngle, ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMaxAngle);
float UsableTurretVelocity = GetUsableRatio() * ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretAngularVelocity;
float TurretAngleDiff = FMath::UnwindDegrees(TargetTurretAngle - ShipComponentData.Turret.TurretAngle);
if (FMath::Abs(TurretAngleDiff) <= UsableTurretVelocity * DeltaTime)
{
ShipComponentData.Turret.TurretAngle = TargetTurretAngle;
}
else if (TurretAngleDiff < 0)
{
ShipComponentData.Turret.TurretAngle -= UsableTurretVelocity * DeltaTime;
}
else
{
ShipComponentData.Turret.TurretAngle += UsableTurretVelocity * DeltaTime;
}
TurretComponent->SetRelativeRotation(FRotator(0, ShipComponentData.Turret.TurretAngle, 0));
}
if (BarrelComponent)
{
float TargetBarrelAngle = 15;
if (AimDirection != FVector::ZeroVector)
{
FVector LocalBarrelAimDirection;
if (TurretComponent)
{
LocalBarrelAimDirection = TurretComponent->GetComponentToWorld().GetRotation().Inverse().RotateVector(AimDirection);
}
else
{
LocalBarrelAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(AimDirection);
}
TargetBarrelAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalBarrelAimDirection.Z, LocalBarrelAimDirection.X)));
}
// Clamp movements
TargetBarrelAngle = FMath::Clamp(TargetBarrelAngle, GetMinLimitAtAngle(ShipComponentData.Turret.TurretAngle), ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMaxAngle);
// TODO Add ship specific bound
float UsableBarrelsVelocity = GetUsableRatio() * ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretAngularVelocity;
float BarrelAngleDiff = FMath::UnwindDegrees(TargetBarrelAngle - ShipComponentData.Turret.BarrelsAngle);
if (FMath::Abs(BarrelAngleDiff) <= UsableBarrelsVelocity * DeltaTime) {
ShipComponentData.Turret.BarrelsAngle = TargetBarrelAngle;
} else if (BarrelAngleDiff < 0) {
ShipComponentData.Turret.BarrelsAngle -= UsableBarrelsVelocity * DeltaTime;
} else {
ShipComponentData.Turret.BarrelsAngle += UsableBarrelsVelocity * DeltaTime;
}
BarrelComponent->SetRelativeRotation(FRotator(ShipComponentData.Turret.BarrelsAngle, 0, 0));
}
}
if(Spacecraft->IsPresentationMode())
{
TurretComponent->SetRelativeRotation(FRotator(0, 0, 0));
BarrelComponent->SetRelativeRotation(FRotator(15, 0, 0));
}
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
FVector UFlareTurret::GetFireAxis() const
{
if (BarrelComponent)
{
return BarrelComponent->GetComponentRotation().RotateVector(FVector(1, 0, 0));
}
else if (TurretComponent)
{
return TurretComponent->GetComponentRotation().RotateVector(FVector(1, 0, 0));
}
else
{
return Super::GetFireAxis();
}
}
FVector UFlareTurret::GetIdleAxis() const
{
// Ship front
return Spacecraft->Airframe->GetComponentRotation().RotateVector(FVector(1, 0, 0));
}
FVector UFlareTurret::GetMuzzleLocation(int GunIndex) const
{
const UStaticMeshComponent* GunComponent = this;
if (BarrelComponent)
{
GunComponent = BarrelComponent;
}
else if (TurretComponent)
{
GunComponent = TurretComponent;
}
if (ComponentDescription->WeaponCharacteristics.GunCharacteristics.GunCount <= 1)
{
return GunComponent->GetSocketLocation(FName("Muzzle"));
}
else
{
return GunComponent->GetSocketLocation(FName(*(FString("Muzzle") + FString::FromInt(GunIndex))));
}
}
FVector UFlareTurret::GetTurretBaseLocation() const
{
if (BarrelComponent)
{
return BarrelComponent->GetComponentLocation();
}
else if (TurretComponent)
{
return TurretComponent->GetComponentLocation();
}
return GetComponentLocation();
}
bool UFlareTurret::IsSafeToFire(int GunIndex) const
{
FVector FiringLocation = GetMuzzleLocation(GunIndex);
FVector FiringDirection = GetFireAxis();
FVector TargetLocation = FiringLocation + FiringDirection * 100000;
FHitResult HitResult(ForceInit);
if (Trace(FiringLocation, TargetLocation, HitResult))
{
if (HitResult.Actor.IsValid() && HitResult.Actor == Spacecraft)
{
FLOG("!!!!!!!!!Not safe to fire !");
return false;
}
}
return true;
}
bool UFlareTurret::Trace(const FVector& Start, const FVector& End, FHitResult& HitOut) const
{
FCollisionQueryParams TraceParams(FName(TEXT("Shell Trace")), true, NULL);
TraceParams.bTraceComplex = true;
//TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = false;
//Re-initialize hit info
HitOut = FHitResult(ForceInit);
ECollisionChannel CollisionChannel = (ECollisionChannel) (ECC_WorldStatic | ECC_WorldDynamic | ECC_Pawn);
//Trace!
GetWorld()->LineTraceSingleByChannel(
HitOut, //result
Start, //start
End , //end
CollisionChannel, //collision channel
TraceParams
);
//Hit any Actor?
return (HitOut.GetActor() != NULL) ;
}
bool UFlareTurret::IsReacheableAxis(FVector TargetAxis) const
{
float TargetTurretAngle = 0;
if (TurretComponent && ComponentDescription)
{
FVector LocalTurretAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(TargetAxis);
TargetTurretAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalTurretAimDirection.Y, LocalTurretAimDirection.X)));
if (TargetTurretAngle > ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMaxAngle
|| TargetTurretAngle < ComponentDescription->WeaponCharacteristics.TurretCharacteristics.TurretMinAngle)
{
return false;
}
}
if (BarrelComponent && ComponentDescription)
{
FVector LocalBarrelAimDirection;
if (TurretComponent)
{
LocalBarrelAimDirection = TurretComponent->GetComponentToWorld().GetRotation().Inverse().RotateVector(TargetAxis);
}
else
{
LocalBarrelAimDirection = GetComponentToWorld().GetRotation().Inverse().RotateVector(TargetAxis);
}
float TargetBarrelAngle = FMath::UnwindDegrees(FMath::RadiansToDegrees(FMath::Atan2(LocalBarrelAimDirection.Z, LocalBarrelAimDirection.X)));
if (TargetBarrelAngle > ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMaxAngle
|| TargetBarrelAngle < GetMinLimitAtAngle(TargetTurretAngle))
{
return false;
}
}
return true;
}
static inline int PositiveModulo(int i, int n)
{
return (i % n + n) % n;
}
float UFlareTurret::GetMinLimitAtAngle(float Angle) const
{
float BarrelsMinAngle = ComponentDescription->WeaponCharacteristics.TurretCharacteristics.BarrelsMinAngle;
//Fine Local slot check
for (int32 i = 0; i < Spacecraft->GetDescription()->TurretSlots.Num(); i++)
{
// TODO optimize and store that in cache
if (Spacecraft->GetDescription()->TurretSlots[i].SlotIdentifier == ShipComponentData.ShipSlotIdentifier)
{
int LimitStepCount = Spacecraft->GetDescription()->TurretSlots[i].TurretBarrelsAngleLimit.Num();
if (LimitStepCount > 0)
{
float StepAngle = 360.f / (float) LimitStepCount;
float AngleInStep = Angle / StepAngle;
int NearestStep = FMath::FloorToInt(AngleInStep + 0.5f);
int SecondNearestStep;
if (AngleInStep > NearestStep)
{
SecondNearestStep = NearestStep+1;
}
else
{
SecondNearestStep = NearestStep-1;
}
float Ratio = FMath::Abs(Angle - NearestStep * StepAngle) / StepAngle;
float LocalMin = Spacecraft->GetDescription()->TurretSlots[i].TurretBarrelsAngleLimit[PositiveModulo(NearestStep, LimitStepCount)] * (1.f - Ratio)
+ Spacecraft->GetDescription()->TurretSlots[i].TurretBarrelsAngleLimit[PositiveModulo(SecondNearestStep,LimitStepCount)] * Ratio;
BarrelsMinAngle = FMath::Max(BarrelsMinAngle, LocalMin);
}
}
}
return BarrelsMinAngle;
}
void UFlareTurret::GetBoundingSphere(FVector& Location, float& SphereRadius)
{
Super::GetBoundingSphere(Location, SphereRadius);
if (TurretComponent || BarrelComponent)
{
SphereRadius = 0;
}
}
void UFlareTurret::ShowFiringEffects(int GunIndex)
{
if (FiringEffects[GunIndex])
{
FiringEffects[GunIndex]->ActivateSystem();
}
}
<|endoftext|> |
<commit_before>#ifdef __EMSCRIPTEN__
#include <babylon/asio/asio.h>
#include <babylon/core/logging.h>
#include <babylon/misc/string_tools.h>
#include <iostream>
#include <emscripten.h>
#include <unordered_map>
#include <thread>
#include <chrono>
#include <sstream>
namespace BABYLON {
namespace asio {
namespace
{
static std::string ArrayBufferToString(const ArrayBuffer & dataUint8)
{
std::string dataString;
dataString.resize(dataUint8.size());
for (size_t i = 0; i < dataUint8.size(); ++i)
dataString[i] = static_cast<char>(dataUint8[i]);
dataString = BABYLON::StringTools::replace(dataString, "\r\n", "\n");
return dataString;
}
struct DownloadInfo
{
std::string url;
std::function<void(const ArrayBuffer& data)> onSuccessFunction;
std::function<void(const std::string& message)> onErrorFunction;
};
using DownloadId = int;
std::unordered_map<DownloadId, DownloadInfo> gDownloadInfos;
DownloadId storeDownloadInfo(
const std::string &url,
std::function<void(const ArrayBuffer& data)> onSuccessFunction,
std::function<void(const std::string& message)> onErrorFunction)
{
static int id = 0;
++id;
DownloadInfo info {url, onSuccessFunction, onErrorFunction};
gDownloadInfos[id] = info;
return id;
}
DownloadInfo consumeDownloadInfo(DownloadId id)
{
if (gDownloadInfos.find(id) == gDownloadInfos.end()) {
std::stringstream msg;
msg << "consumeDownloadInfo bad id:" << id << " gDownloadInfos size=" << gDownloadInfos.size();
BABYLON_LOG_ERROR("asio_emscripten", msg.str().c_str(), "");
throw std::runtime_error(msg.str().c_str());
}
DownloadInfo r = gDownloadInfos.at(id);
gDownloadInfos.erase(id);
return r;
}
// See https://emscripten.org/docs/api_reference/emscripten.h.html#c.emscripten_async_wget_data
void babylon_emscripten_onLoad(void *arg_downloadId, void *bufferData, int bufferSize)
{
uint8_t* bufferDataAsUint8 = static_cast<uint8_t *>(bufferData);
ArrayBuffer arrayBuffer(bufferDataAsUint8, bufferDataAsUint8 + bufferSize); // this makes a copy
DownloadInfo info = consumeDownloadInfo((DownloadId)arg_downloadId);
BABYLON_LOG_DEBUG("babylon_emscripten_onLoad", info.url.c_str(), " Success!");
info.onSuccessFunction(arrayBuffer);
}
void babylon_emscripten_onError(void *arg_downloadId)
{
DownloadInfo info = consumeDownloadInfo((DownloadId)arg_downloadId);
std::string errorMessage = std::string("Error while downloading ") + info.url;
BABYLON_LOG_DEBUG("babylon_emscripten_onError", info.url.c_str(), " Failure!");
info.onErrorFunction(errorMessage);
}
static std::string BaseUrl() {
return "./emscripten_http_assets/assets/";
}
} // anonymous namespace
void set_HACK_DISABLE_ASYNC(bool v)
{
BABYLON_LOG_WARN("asio", "set_HACK_DISABLE_ASYNC does not work under emscripten", "");
}
void LoadUrlAsync_Text(
const std::string& url,
const std::function<void(const std::string& data)>& onSuccessFunction,
const OnErrorFunction& onErrorFunction,
const OnProgressFunction& onProgressFunction
)
{
std::string fullUrl = BaseUrl() + url;
auto onSuccessFunctionArrayBuffer = [onSuccessFunction](const ArrayBuffer& dataUint8) {
onSuccessFunction(ArrayBufferToString(dataUint8));
};
auto downloadId = storeDownloadInfo(fullUrl.c_str(), onSuccessFunctionArrayBuffer, onErrorFunction);
emscripten_async_wget_data(fullUrl.c_str(), (void*)downloadId, babylon_emscripten_onLoad, babylon_emscripten_onError);
}
void LoadUrlAsync_Binary(
const std::string& url,
const std::function<void(const ArrayBuffer& data)>& onSuccessFunction,
const OnErrorFunction& onErrorFunction,
const OnProgressFunction& onProgressFunction
)
{
std::string fullUrl = BaseUrl() + url;
auto downloadId = storeDownloadInfo(fullUrl.c_str(), onSuccessFunction, onErrorFunction);
emscripten_async_wget_data(fullUrl.c_str(), (void*)downloadId, babylon_emscripten_onLoad, babylon_emscripten_onError);
}
// Call this in the app's main loop: it will run the callbacks synchronously
// after the io completion
void HeartBeat_Sync()
{
}
void Service_WaitAll_Sync()
{
using namespace std::literals;
while(!gDownloadInfos.empty())
std::this_thread::sleep_for(30ms);
}
BABYLON_SHARED_EXPORT void Service_Stop()
{
}
bool HasRemainingTasks()
{
return !gDownloadInfos.empty();
}
} // namespace asio
} // namespace BABYLON
#endif //#ifdef __EMSCRIPTEN__
<commit_msg>asio_emscripten: correct / wait<commit_after>#ifdef __EMSCRIPTEN__
#include <babylon/asio/asio.h>
#include <babylon/core/logging.h>
#include <babylon/misc/string_tools.h>
#include <iostream>
#include <emscripten.h>
#include <unordered_map>
#include <thread>
#include <chrono>
#include <sstream>
namespace BABYLON {
namespace asio {
namespace
{
static std::string ArrayBufferToString(const ArrayBuffer & dataUint8)
{
std::string dataString;
dataString.resize(dataUint8.size());
for (size_t i = 0; i < dataUint8.size(); ++i)
dataString[i] = static_cast<char>(dataUint8[i]);
dataString = BABYLON::StringTools::replace(dataString, "\r\n", "\n");
return dataString;
}
struct DownloadInfo
{
std::string url;
std::function<void(const ArrayBuffer& data)> onSuccessFunction;
std::function<void(const std::string& message)> onErrorFunction;
};
using DownloadId = int;
std::unordered_map<DownloadId, DownloadInfo> gDownloadInfos;
DownloadId storeDownloadInfo(
const std::string &url,
std::function<void(const ArrayBuffer& data)> onSuccessFunction,
std::function<void(const std::string& message)> onErrorFunction)
{
static int id = 0;
++id;
DownloadInfo info {url, onSuccessFunction, onErrorFunction};
gDownloadInfos[id] = info;
return id;
}
DownloadInfo consumeDownloadInfo(DownloadId id)
{
if (gDownloadInfos.find(id) == gDownloadInfos.end()) {
std::stringstream msg;
msg << "consumeDownloadInfo bad id:" << id << " gDownloadInfos size=" << gDownloadInfos.size();
BABYLON_LOG_ERROR("asio_emscripten", msg.str().c_str(), "");
throw std::runtime_error(msg.str().c_str());
}
DownloadInfo r = gDownloadInfos.at(id);
gDownloadInfos.erase(id);
return r;
}
// See https://emscripten.org/docs/api_reference/emscripten.h.html#c.emscripten_async_wget_data
void babylon_emscripten_onLoad(void *arg_downloadId, void *bufferData, int bufferSize)
{
uint8_t* bufferDataAsUint8 = static_cast<uint8_t *>(bufferData);
ArrayBuffer arrayBuffer(bufferDataAsUint8, bufferDataAsUint8 + bufferSize); // this makes a copy
DownloadInfo info = consumeDownloadInfo((DownloadId)arg_downloadId);
BABYLON_LOG_DEBUG("babylon_emscripten_onLoad", info.url.c_str(), " Success!");
info.onSuccessFunction(arrayBuffer);
}
void babylon_emscripten_onError(void *arg_downloadId)
{
DownloadInfo info = consumeDownloadInfo((DownloadId)arg_downloadId);
std::string errorMessage = std::string("Error while downloading ") + info.url;
BABYLON_LOG_DEBUG("babylon_emscripten_onError", info.url.c_str(), " Failure!");
info.onErrorFunction(errorMessage);
}
static std::string BaseUrl() {
return "./emscripten_http_assets/assets/";
}
} // anonymous namespace
void push_HACK_DISABLE_ASYNC()
{
BABYLON_LOG_WARN("asio", "push_HACK_DISABLE_ASYNC does not work under emscripten", "");
}
void pop_HACK_DISABLE_ASYNC()
{
BABYLON_LOG_WARN("asio", "pop_HACK_DISABLE_ASYNC does not work under emscripten", "");
}
void LoadUrlAsync_Text(
const std::string& url,
const std::function<void(const std::string& data)>& onSuccessFunction,
const OnErrorFunction& onErrorFunction,
const OnProgressFunction& onProgressFunction
)
{
std::string fullUrl = BaseUrl() + url;
auto onSuccessFunctionArrayBuffer = [onSuccessFunction](const ArrayBuffer& dataUint8) {
onSuccessFunction(ArrayBufferToString(dataUint8));
};
auto downloadId = storeDownloadInfo(fullUrl.c_str(), onSuccessFunctionArrayBuffer, onErrorFunction);
emscripten_async_wget_data(fullUrl.c_str(), (void*)downloadId, babylon_emscripten_onLoad, babylon_emscripten_onError);
}
void LoadUrlAsync_Binary(
const std::string& url,
const std::function<void(const ArrayBuffer& data)>& onSuccessFunction,
const OnErrorFunction& onErrorFunction,
const OnProgressFunction& onProgressFunction
)
{
std::string fullUrl = BaseUrl() + url;
auto downloadId = storeDownloadInfo(fullUrl.c_str(), onSuccessFunction, onErrorFunction);
emscripten_async_wget_data(fullUrl.c_str(), (void*)downloadId, babylon_emscripten_onLoad, babylon_emscripten_onError);
}
// Call this in the app's main loop: it will run the callbacks synchronously
// after the io completion
void HeartBeat_Sync()
{
}
void Service_WaitAll_Sync()
{
using namespace std::literals;
while(!gDownloadInfos.empty())
std::this_thread::sleep_for(30ms);
}
BABYLON_SHARED_EXPORT void Service_Stop()
{
}
bool HasRemainingTasks()
{
return !gDownloadInfos.empty();
}
} // namespace asio
} // namespace BABYLON
#endif //#ifdef __EMSCRIPTEN__
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/flex/whitelisted_flex_ops.h"
#include <set>
namespace tflite {
namespace flex {
bool IsWhitelistedFlexOp(const std::string& tensorflow_op_name) {
static const std::set<std::string>* whitelisted_flex_ops =
new std::set<std::string>({
"Abort",
"Abs",
"Add",
"AddN",
"AddV2",
"All",
"Any",
"ApplyAdadelta",
"ApplyAdagrad",
"ApplyAdagradDA",
"ApplyAdam",
"ApplyAdaMax",
"ApplyAddSign",
"ApplyCenteredRMSProp",
"ApplyFtrl",
"ApplyFtrlV2",
"ApplyGradientDescent",
"ApplyMomentum",
"ApplyPowerSign",
"ApplyProximalAdagrad",
"ApplyProximalGradientDescent",
"ApplyRMSProp",
"ApproximateEqual",
"_Arg",
"ArgMax",
"ArgMin",
"_ArrayToList",
"Assert",
"Assign",
"AssignAdd",
"AssignSub",
"AudioSpectrogram",
"AvgPool",
"AvgPool3D",
"AvgPoolGrad",
"BatchMatMul",
"BatchMatMulV2",
"BatchNormWithGlobalNormalization",
"BatchNormWithGlobalNormalizationGrad",
"BatchToSpace",
"BatchToSpaceND",
"BiasAdd",
"BiasAddGrad",
"BiasAddV1",
"BroadcastArgs",
"BroadcastGradientArgs",
"BroadcastTo",
"Cast",
"Ceil",
"CheckNumerics",
"ComplexAbs",
"Concat",
"ConcatOffset",
"ConcatV2",
"ConjugateTranspose",
"Const",
"ControlTrigger",
"Conv2D",
"Conv2DBackpropFilter",
"Conv2DBackpropInput",
"Conv3D",
"Cos",
"Cosh",
"CropAndResize",
"CropAndResizeGradBoxes",
"CropAndResizeGradImage",
"CTCBeamSearchDecoder",
"CTCGreedyDecoder",
"DataFormatDimMap",
"DataFormatVecPermute",
"DebugGradientIdentity",
"DebugGradientRefIdentity",
"DecodeBmp",
"DecodeWav",
"DeleteSessionTensor",
"DepthToSpace",
"DepthwiseConv2dNative",
"Dequantize",
"DestroyTemporaryVariable",
"Div",
"DivNoNan",
"DynamicPartition",
"DynamicStitch",
"Einsum",
"Elu",
"EluGrad",
"EncodeWav",
"EnsureShape",
"Enter",
"Equal",
"Erf",
"Exit",
"Exp",
"ExpandDims",
"FakeQuantWithMinMaxArgs",
"FakeQuantWithMinMaxArgsGradient",
"FakeQuantWithMinMaxVars",
"FakeQuantWithMinMaxVarsGradient",
"FakeQuantWithMinMaxVarsPerChannel",
"FakeQuantWithMinMaxVarsPerChannelGradient",
"FakeQueue",
"FFT",
"FFT2D",
"FFT3D",
"FIFOQueue",
"FIFOQueueV2",
"Fill",
"Floor",
"FloorDiv",
"FloorMod",
"FusedBatchNorm",
"FusedBatchNormGrad",
"FusedBatchNormGradV2",
"FusedBatchNormV2",
"FusedBatchNormV3",
"FusedPadConv2D",
"FusedResizeAndPadConv2D",
"Gather",
"GatherNd",
"GatherV2",
"GetSessionHandle",
"GetSessionHandleV2",
"GetSessionTensor",
"Greater",
"GreaterEqual",
"_HostCast",
"_HostRecv",
"_HostSend",
"Identity",
"IdentityN",
"IFFT",
"IFFT2D",
"IFFT3D",
"IRFFT",
"IRFFT2D",
"IRFFT3D",
"ImmutableConst",
"InTopK",
"InTopKV2",
"Inv",
"InvertPermutation",
"InvGrad",
"IsFinite",
"IsNan",
"IsVariableInitialized",
"LeakyRelu",
"LeakyReluGrad",
"Less",
"LessEqual",
"LinSpace",
"ListDiff",
"_ListToArray",
"Log",
"LogicalAnd",
"LogicalNot",
"LogicalOr",
"LogSoftmax",
"LoopCond",
"LRN",
"MatMul",
"MatrixDiag",
"MatrixDiagV2",
"MatrixDiagV3",
"MatrixSetDiag",
"MatrixSetDiagV2",
"MatrixSetDiagV3",
"Max",
"Maximum",
"MaxPool",
"MaxPool3D",
"MaxPoolGrad",
"MaxPoolGradGrad",
"MaxPoolGradGradV2",
"MaxPoolGradV2",
"MaxPoolGradWithArgmax",
"MaxPoolV2",
"MaxPoolWithArgmax",
"Mean",
"Merge",
"MergeV2Checkpoints",
"Mfcc",
"Min",
"Minimum",
"MirrorPad",
"MirrorPadGrad",
"Mul",
"MulNoNan",
"Multinomial",
"Neg",
"NextIteration",
"NonMaxSuppression",
"NonMaxSuppressionV2",
"NonMaxSuppressionV3",
"NonMaxSuppressionV4",
"NonMaxSuppressionWithOverlaps",
"NoOp",
"NotEqual",
"OneHot",
"OnesLike",
"Pack",
"Pad",
"PaddingFIFOQueue",
"PaddingFIFOQueueV2",
"PadV2",
"ParallelDynamicStitch",
"ParseExample",
"ParseSequenceExample",
"ParseSingleExample",
"ParseSingleSequenceExample",
"Placeholder",
"PlaceholderV2",
"PlaceholderWithDefault",
"Pow",
"PreventGradient",
"Print",
"PrintV2",
"Prod",
"QuantizedAdd",
"QuantizedAvgPool",
"QuantizedBatchNormWithGlobalNormalization",
"QuantizedBiasAdd",
"QuantizedConcat",
"QuantizedConv2D",
"QuantizedInstanceNorm",
"QuantizedMatMul",
"QuantizedMaxPool",
"QuantizedMul",
"QuantizeDownAndShrinkRange",
"QuantizedRelu",
"QuantizedRelu6",
"QuantizedReshape",
"QuantizedResizeBilinear",
"QuantizeV2",
"QueueClose",
"QueueCloseV2",
"QueueDequeue",
"QueueDequeueMany",
"QueueDequeueManyV2",
"QueueDequeueUpTo",
"QueueDequeueUpToV2",
"QueueDequeueV2",
"QueueEnqueue",
"QueueEnqueueMany",
"QueueEnqueueManyV2",
"QueueEnqueueV2",
"QueueIsClosed",
"QueueIsClosedV2",
"QueueSize",
"QueueSizeV2",
"RandomGamma",
"RandomStandardNormal",
"RandomUniform",
"RandomUniformInt",
"Range",
"Rank",
"RealDiv",
"Reciprocal",
"ReciprocalGrad",
"_Recv",
"RefEnter",
"RefExit",
"RefIdentity",
"RefMerge",
"RefNextIteration",
"RefSelect",
"RefSwitch",
"Relu",
"Relu6",
"Relu6Grad",
"ReluGrad",
"RemoteCall",
"RequantizationRange",
"Requantize",
"Reshape",
"ResizeBilinear",
"ResizeBilinearGrad",
"ResizeNearestNeighbor",
"ResizeNearestNeighborGrad",
"ResourceApplyAdadelta",
"ResourceApplyAdagrad",
"ResourceApplyAdagradDA",
"ResourceApplyAdam",
"ResourceApplyAdaMax",
"ResourceApplyAddSign",
"ResourceApplyCenteredRMSProp",
"ResourceApplyFtrl",
"ResourceApplyFtrlV2",
"ResourceApplyGradientDescent",
"ResourceApplyMomentum",
"ResourceApplyPowerSign",
"ResourceApplyProximalAdagrad",
"ResourceApplyProximalGradientDescent",
"ResourceApplyRMSProp",
"ResourceSparseApplyAdadelta",
"ResourceSparseApplyAdagrad",
"ResourceSparseApplyAdagradDA",
"ResourceSparseApplyCenteredRMSProp",
"ResourceSparseApplyFtrl",
"ResourceSparseApplyFtrlV2",
"ResourceSparseApplyMomentum",
"ResourceSparseApplyProximalAdagrad",
"ResourceSparseApplyProximalGradientDescent",
"ResourceSparseApplyRMSProp",
"ResourceStridedSliceAssign",
"Restore",
"RestoreSlice",
"RestoreV2",
"_Retval",
"Reverse",
"ReverseSequence",
"ReverseV2",
"RFFT",
"RFFT2D",
"RFFT3D",
"Round",
"Rsqrt",
"RsqrtGrad",
"Save",
"SaveSlices",
"SaveV2",
"ScatterNd",
"SegmentMax",
"SegmentMean",
"SegmentMin",
"SegmentProd",
"SegmentSum",
"Select",
"Selu",
"SeluGrad",
"_Send",
"Shape",
"ShapeN",
"ShardedFilename",
"ShardedFilespec",
"Sigmoid",
"SigmoidGrad",
"Sign",
"Sin",
"Sinh",
"Size",
"Slice",
"Softmax",
"SoftmaxCrossEntropyWithLogits",
"Softplus",
"SoftplusGrad",
"Softsign",
"SoftsignGrad",
"SpaceToBatch",
"SpaceToBatchND",
"SpaceToDepth",
"SparseApplyAdadelta",
"SparseApplyAdagrad",
"SparseApplyAdagradDA",
"SparseApplyCenteredRMSProp",
"SparseApplyFtrl",
"SparseApplyFtrlV2",
"SparseApplyMomentum",
"SparseApplyProximalAdagrad",
"SparseApplyProximalGradientDescent",
"SparseApplyRMSProp",
"SparseFillEmptyRows",
"SparseFillEmptyRowsGrad",
"SparseReshape",
"SparseSegmentMean",
"SparseSegmentMeanGrad",
"SparseSegmentMeanWithNumSegments",
"SparseSegmentSqrtN",
"SparseSegmentSqrtNGrad",
"SparseSegmentSqrtNWithNumSegments",
"SparseSegmentSum",
"SparseSegmentSumWithNumSegments",
"SparseToDense",
"Split",
"SplitV",
"Sqrt",
"SqrtGrad",
"Square",
"SquaredDifference",
"Squeeze",
"Stack",
"StackClose",
"StackCloseV2",
"StackPop",
"StackPopV2",
"StackPush",
"StackPushV2",
"StackV2",
"StopGradient",
"StridedSlice",
"StridedSliceAssign",
"StridedSliceGrad",
"StringJoin",
"Sub",
"Sum",
"Switch",
"SymbolicGradient",
"Tan",
"Tanh",
"TanhGrad",
"TemporaryVariable",
"TensorArray",
"TensorArrayClose",
"TensorArrayCloseV2",
"TensorArrayCloseV3",
"TensorArrayConcat",
"TensorArrayConcatV2",
"TensorArrayConcatV3",
"TensorArrayGather",
"TensorArrayGatherV2",
"TensorArrayGatherV3",
"TensorArrayGrad",
"TensorArrayGradV2",
"TensorArrayGradV3",
"TensorArrayGradWithShape",
"TensorArrayPack",
"TensorArrayRead",
"TensorArrayReadV2",
"TensorArrayReadV3",
"TensorArrayScatter",
"TensorArrayScatterV2",
"TensorArrayScatterV3",
"TensorArraySize",
"TensorArraySizeV2",
"TensorArraySizeV3",
"TensorArraySplit",
"TensorArraySplitV2",
"TensorArraySplitV3",
"TensorArrayUnpack",
"TensorArrayV2",
"TensorArrayV3",
"TensorArrayWrite",
"TensorArrayWriteV2",
"TensorArrayWriteV3",
"Tile",
"TileGrad",
"Timestamp",
"TopK",
"TopKV2",
"Transpose",
"TruncateDiv",
"TruncatedNormal",
"Unique",
"UniqueV2",
"UniqueWithCounts",
"UniqueWithCountsV2",
"Unpack",
"UnsortedSegmentMax",
"UnsortedSegmentMin",
"UnsortedSegmentProd",
"UnsortedSegmentSum",
"Variable",
"VariableV2",
"Where",
"Xdivy",
"Xlogy",
"ZerosLike",
});
return whitelisted_flex_ops->find(tensorflow_op_name) !=
whitelisted_flex_ops->end();
}
} // namespace flex
} // namespace tflite
<commit_msg>Add `tf.empty` into whitelisted flex op.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/flex/whitelisted_flex_ops.h"
#include <set>
namespace tflite {
namespace flex {
bool IsWhitelistedFlexOp(const std::string& tensorflow_op_name) {
static const std::set<std::string>* whitelisted_flex_ops =
new std::set<std::string>({
"Abort",
"Abs",
"Add",
"AddN",
"AddV2",
"All",
"Any",
"ApplyAdadelta",
"ApplyAdagrad",
"ApplyAdagradDA",
"ApplyAdam",
"ApplyAdaMax",
"ApplyAddSign",
"ApplyCenteredRMSProp",
"ApplyFtrl",
"ApplyFtrlV2",
"ApplyGradientDescent",
"ApplyMomentum",
"ApplyPowerSign",
"ApplyProximalAdagrad",
"ApplyProximalGradientDescent",
"ApplyRMSProp",
"ApproximateEqual",
"_Arg",
"ArgMax",
"ArgMin",
"_ArrayToList",
"Assert",
"Assign",
"AssignAdd",
"AssignSub",
"AudioSpectrogram",
"AvgPool",
"AvgPool3D",
"AvgPoolGrad",
"BatchMatMul",
"BatchMatMulV2",
"BatchNormWithGlobalNormalization",
"BatchNormWithGlobalNormalizationGrad",
"BatchToSpace",
"BatchToSpaceND",
"BiasAdd",
"BiasAddGrad",
"BiasAddV1",
"BroadcastArgs",
"BroadcastGradientArgs",
"BroadcastTo",
"Cast",
"Ceil",
"CheckNumerics",
"ComplexAbs",
"Concat",
"ConcatOffset",
"ConcatV2",
"ConjugateTranspose",
"Const",
"ControlTrigger",
"Conv2D",
"Conv2DBackpropFilter",
"Conv2DBackpropInput",
"Conv3D",
"Cos",
"Cosh",
"CropAndResize",
"CropAndResizeGradBoxes",
"CropAndResizeGradImage",
"CTCBeamSearchDecoder",
"CTCGreedyDecoder",
"DataFormatDimMap",
"DataFormatVecPermute",
"DebugGradientIdentity",
"DebugGradientRefIdentity",
"DecodeBmp",
"DecodeWav",
"DeleteSessionTensor",
"DepthToSpace",
"DepthwiseConv2dNative",
"Dequantize",
"DestroyTemporaryVariable",
"Div",
"DivNoNan",
"DynamicPartition",
"DynamicStitch",
"Einsum",
"Elu",
"EluGrad",
"Empty",
"EncodeWav",
"EnsureShape",
"Enter",
"Equal",
"Erf",
"Exit",
"Exp",
"ExpandDims",
"FakeQuantWithMinMaxArgs",
"FakeQuantWithMinMaxArgsGradient",
"FakeQuantWithMinMaxVars",
"FakeQuantWithMinMaxVarsGradient",
"FakeQuantWithMinMaxVarsPerChannel",
"FakeQuantWithMinMaxVarsPerChannelGradient",
"FakeQueue",
"FFT",
"FFT2D",
"FFT3D",
"FIFOQueue",
"FIFOQueueV2",
"Fill",
"Floor",
"FloorDiv",
"FloorMod",
"FusedBatchNorm",
"FusedBatchNormGrad",
"FusedBatchNormGradV2",
"FusedBatchNormV2",
"FusedBatchNormV3",
"FusedPadConv2D",
"FusedResizeAndPadConv2D",
"Gather",
"GatherNd",
"GatherV2",
"GetSessionHandle",
"GetSessionHandleV2",
"GetSessionTensor",
"Greater",
"GreaterEqual",
"_HostCast",
"_HostRecv",
"_HostSend",
"Identity",
"IdentityN",
"IFFT",
"IFFT2D",
"IFFT3D",
"IRFFT",
"IRFFT2D",
"IRFFT3D",
"ImmutableConst",
"InTopK",
"InTopKV2",
"Inv",
"InvertPermutation",
"InvGrad",
"IsFinite",
"IsNan",
"IsVariableInitialized",
"LeakyRelu",
"LeakyReluGrad",
"Less",
"LessEqual",
"LinSpace",
"ListDiff",
"_ListToArray",
"Log",
"LogicalAnd",
"LogicalNot",
"LogicalOr",
"LogSoftmax",
"LoopCond",
"LRN",
"MatMul",
"MatrixDiag",
"MatrixDiagV2",
"MatrixDiagV3",
"MatrixSetDiag",
"MatrixSetDiagV2",
"MatrixSetDiagV3",
"Max",
"Maximum",
"MaxPool",
"MaxPool3D",
"MaxPoolGrad",
"MaxPoolGradGrad",
"MaxPoolGradGradV2",
"MaxPoolGradV2",
"MaxPoolGradWithArgmax",
"MaxPoolV2",
"MaxPoolWithArgmax",
"Mean",
"Merge",
"MergeV2Checkpoints",
"Mfcc",
"Min",
"Minimum",
"MirrorPad",
"MirrorPadGrad",
"Mul",
"MulNoNan",
"Multinomial",
"Neg",
"NextIteration",
"NonMaxSuppression",
"NonMaxSuppressionV2",
"NonMaxSuppressionV3",
"NonMaxSuppressionV4",
"NonMaxSuppressionWithOverlaps",
"NoOp",
"NotEqual",
"OneHot",
"OnesLike",
"Pack",
"Pad",
"PaddingFIFOQueue",
"PaddingFIFOQueueV2",
"PadV2",
"ParallelDynamicStitch",
"ParseExample",
"ParseSequenceExample",
"ParseSingleExample",
"ParseSingleSequenceExample",
"Placeholder",
"PlaceholderV2",
"PlaceholderWithDefault",
"Pow",
"PreventGradient",
"Print",
"PrintV2",
"Prod",
"QuantizedAdd",
"QuantizedAvgPool",
"QuantizedBatchNormWithGlobalNormalization",
"QuantizedBiasAdd",
"QuantizedConcat",
"QuantizedConv2D",
"QuantizedInstanceNorm",
"QuantizedMatMul",
"QuantizedMaxPool",
"QuantizedMul",
"QuantizeDownAndShrinkRange",
"QuantizedRelu",
"QuantizedRelu6",
"QuantizedReshape",
"QuantizedResizeBilinear",
"QuantizeV2",
"QueueClose",
"QueueCloseV2",
"QueueDequeue",
"QueueDequeueMany",
"QueueDequeueManyV2",
"QueueDequeueUpTo",
"QueueDequeueUpToV2",
"QueueDequeueV2",
"QueueEnqueue",
"QueueEnqueueMany",
"QueueEnqueueManyV2",
"QueueEnqueueV2",
"QueueIsClosed",
"QueueIsClosedV2",
"QueueSize",
"QueueSizeV2",
"RandomGamma",
"RandomStandardNormal",
"RandomUniform",
"RandomUniformInt",
"Range",
"Rank",
"RealDiv",
"Reciprocal",
"ReciprocalGrad",
"_Recv",
"RefEnter",
"RefExit",
"RefIdentity",
"RefMerge",
"RefNextIteration",
"RefSelect",
"RefSwitch",
"Relu",
"Relu6",
"Relu6Grad",
"ReluGrad",
"RemoteCall",
"RequantizationRange",
"Requantize",
"Reshape",
"ResizeBilinear",
"ResizeBilinearGrad",
"ResizeNearestNeighbor",
"ResizeNearestNeighborGrad",
"ResourceApplyAdadelta",
"ResourceApplyAdagrad",
"ResourceApplyAdagradDA",
"ResourceApplyAdam",
"ResourceApplyAdaMax",
"ResourceApplyAddSign",
"ResourceApplyCenteredRMSProp",
"ResourceApplyFtrl",
"ResourceApplyFtrlV2",
"ResourceApplyGradientDescent",
"ResourceApplyMomentum",
"ResourceApplyPowerSign",
"ResourceApplyProximalAdagrad",
"ResourceApplyProximalGradientDescent",
"ResourceApplyRMSProp",
"ResourceSparseApplyAdadelta",
"ResourceSparseApplyAdagrad",
"ResourceSparseApplyAdagradDA",
"ResourceSparseApplyCenteredRMSProp",
"ResourceSparseApplyFtrl",
"ResourceSparseApplyFtrlV2",
"ResourceSparseApplyMomentum",
"ResourceSparseApplyProximalAdagrad",
"ResourceSparseApplyProximalGradientDescent",
"ResourceSparseApplyRMSProp",
"ResourceStridedSliceAssign",
"Restore",
"RestoreSlice",
"RestoreV2",
"_Retval",
"Reverse",
"ReverseSequence",
"ReverseV2",
"RFFT",
"RFFT2D",
"RFFT3D",
"Round",
"Rsqrt",
"RsqrtGrad",
"Save",
"SaveSlices",
"SaveV2",
"ScatterNd",
"SegmentMax",
"SegmentMean",
"SegmentMin",
"SegmentProd",
"SegmentSum",
"Select",
"Selu",
"SeluGrad",
"_Send",
"Shape",
"ShapeN",
"ShardedFilename",
"ShardedFilespec",
"Sigmoid",
"SigmoidGrad",
"Sign",
"Sin",
"Sinh",
"Size",
"Slice",
"Softmax",
"SoftmaxCrossEntropyWithLogits",
"Softplus",
"SoftplusGrad",
"Softsign",
"SoftsignGrad",
"SpaceToBatch",
"SpaceToBatchND",
"SpaceToDepth",
"SparseApplyAdadelta",
"SparseApplyAdagrad",
"SparseApplyAdagradDA",
"SparseApplyCenteredRMSProp",
"SparseApplyFtrl",
"SparseApplyFtrlV2",
"SparseApplyMomentum",
"SparseApplyProximalAdagrad",
"SparseApplyProximalGradientDescent",
"SparseApplyRMSProp",
"SparseFillEmptyRows",
"SparseFillEmptyRowsGrad",
"SparseReshape",
"SparseSegmentMean",
"SparseSegmentMeanGrad",
"SparseSegmentMeanWithNumSegments",
"SparseSegmentSqrtN",
"SparseSegmentSqrtNGrad",
"SparseSegmentSqrtNWithNumSegments",
"SparseSegmentSum",
"SparseSegmentSumWithNumSegments",
"SparseToDense",
"Split",
"SplitV",
"Sqrt",
"SqrtGrad",
"Square",
"SquaredDifference",
"Squeeze",
"Stack",
"StackClose",
"StackCloseV2",
"StackPop",
"StackPopV2",
"StackPush",
"StackPushV2",
"StackV2",
"StopGradient",
"StridedSlice",
"StridedSliceAssign",
"StridedSliceGrad",
"StringJoin",
"Sub",
"Sum",
"Switch",
"SymbolicGradient",
"Tan",
"Tanh",
"TanhGrad",
"TemporaryVariable",
"TensorArray",
"TensorArrayClose",
"TensorArrayCloseV2",
"TensorArrayCloseV3",
"TensorArrayConcat",
"TensorArrayConcatV2",
"TensorArrayConcatV3",
"TensorArrayGather",
"TensorArrayGatherV2",
"TensorArrayGatherV3",
"TensorArrayGrad",
"TensorArrayGradV2",
"TensorArrayGradV3",
"TensorArrayGradWithShape",
"TensorArrayPack",
"TensorArrayRead",
"TensorArrayReadV2",
"TensorArrayReadV3",
"TensorArrayScatter",
"TensorArrayScatterV2",
"TensorArrayScatterV3",
"TensorArraySize",
"TensorArraySizeV2",
"TensorArraySizeV3",
"TensorArraySplit",
"TensorArraySplitV2",
"TensorArraySplitV3",
"TensorArrayUnpack",
"TensorArrayV2",
"TensorArrayV3",
"TensorArrayWrite",
"TensorArrayWriteV2",
"TensorArrayWriteV3",
"Tile",
"TileGrad",
"Timestamp",
"TopK",
"TopKV2",
"Transpose",
"TruncateDiv",
"TruncatedNormal",
"Unique",
"UniqueV2",
"UniqueWithCounts",
"UniqueWithCountsV2",
"Unpack",
"UnsortedSegmentMax",
"UnsortedSegmentMin",
"UnsortedSegmentProd",
"UnsortedSegmentSum",
"Variable",
"VariableV2",
"Where",
"Xdivy",
"Xlogy",
"ZerosLike",
});
return whitelisted_flex_ops->find(tensorflow_op_name) !=
whitelisted_flex_ops->end();
}
} // namespace flex
} // namespace tflite
<|endoftext|> |
<commit_before>#ifndef _CCTAG_MODECONFIG_HPP
#define _CCTAG_MODECONFIG_HPP
#ifdef DEBUG
#define CCTAG_SERIALIZE
#endif
#endif /* MODECONFIG_HPP */
<commit_msg>Remove modeConfig.hpp<commit_after><|endoftext|> |
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/algorithms/get_all_states.h"
namespace open_spiel {
namespace algorithms {
namespace {
// Walk a subgame and return all states contained in the subgames. This does
// a recursive tree walk, therefore all valid sequences must have finite number
// of actions. The state collection is key-indexed by the state's string
// representation so that duplicates are not added.
// Requires State::Clone() to be implemented.
// Use with extreme caution!
// Currently not implemented for simultaneous games.
void GetSubgameStates(State* state,
std::map<std::string, std::unique_ptr<State>>* all_states,
int depth_limit, int depth, bool include_terminals,
bool include_chance_states) {
if (state->IsTerminal()) {
if (include_terminals) {
// Include if not already present and then terminate recursion.
std::string key = state->ToString();
if (all_states->find(key) == all_states->end()) {
(*all_states)[key] = state->Clone();
}
}
return;
}
if (depth_limit >= 0 && depth > depth_limit) {
return;
}
if (!state->IsChanceNode() || include_chance_states) {
// Decision node; add only if not already present
std::string key = state->ToString();
if (all_states->find(key) == all_states->end()) {
(*all_states)[key] = state->Clone();
}
}
for (auto action : state->LegalActions()) {
auto next_state = state->Clone();
next_state->ApplyAction(action);
GetSubgameStates(next_state.get(), all_states, depth_limit, depth + 1,
include_terminals, include_chance_states);
}
}
} // namespace
std::map<std::string, std::unique_ptr<State>> GetAllStates(
const Game& game, int depth_limit, bool include_terminals,
bool include_chance_states) {
// Get the root state.
std::unique_ptr<State> state = game.NewInitialState();
std::map<std::string, std::unique_ptr<State>> all_states;
// Then, do a recursive tree walk to fill up the map.
GetSubgameStates(state.get(), &all_states, depth_limit, 0, include_terminals,
include_chance_states);
if (all_states.empty()) {
SpielFatalError("GetSubgameStates returned 0 states!");
}
return all_states;
}
} // namespace algorithms
} // namespace open_spiel
<commit_msg>get_all_states now also works if state transitions contain loops<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/algorithms/get_all_states.h"
namespace open_spiel {
namespace algorithms {
namespace {
// Walk a subgame and return all states contained in the subgames. This does
// a recursive tree walk, therefore all valid sequences must have finite number
// of actions. The state collection is key-indexed by the state's string
// representation so that duplicates are not added.
// Requires State::Clone() to be implemented.
// Use with extreme caution!
// Currently not implemented for simultaneous games.
void GetSubgameStates(State* state,
std::map<std::string, std::unique_ptr<State>>* all_states,
int depth_limit, int depth, bool include_terminals,
bool include_chance_states) {
if (state->IsTerminal()) {
if (include_terminals) {
// Include if not already present and then terminate recursion.
std::string key = state->ToString();
if (all_states->find(key) == all_states->end()) {
(*all_states)[key] = state->Clone();
}
}
return;
}
if (depth_limit >= 0 && depth > depth_limit) {
return;
}
bool explore = true;
if (!state->IsChanceNode() || include_chance_states) {
// Decision node; add only if not already present
std::string key = state->ToString();
if (all_states->find(key) == all_states->end()) {
(*all_states)[key] = state->Clone();
} else {
explore = false;
}
}
if (explore) {
for (auto action : state->LegalActions()) {
auto next_state = state->Clone();
next_state->ApplyAction(action);
GetSubgameStates(next_state.get(), all_states, depth_limit, depth + 1,
include_terminals, include_chance_states);
}
}
}
} // namespace
std::map<std::string, std::unique_ptr<State>> GetAllStates(
const Game& game, int depth_limit, bool include_terminals,
bool include_chance_states) {
// Get the root state.
std::unique_ptr<State> state = game.NewInitialState();
std::map<std::string, std::unique_ptr<State>> all_states;
// Then, do a recursive tree walk to fill up the map.
GetSubgameStates(state.get(), &all_states, depth_limit, 0, include_terminals,
include_chance_states);
if (all_states.empty()) {
SpielFatalError("GetSubgameStates returned 0 states!");
}
return all_states;
}
} // namespace algorithms
} // namespace open_spiel
<|endoftext|> |
<commit_before>#ifndef database_connection_hpp
#define database_connection_hpp
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <set>
#include <string>
#include "shared_sql_statement.hpp"
#include "detail/sqlite_dbconn.hpp"
/**
* Namespace for housing all Sqloxx code. Sqloxx is intended as a
* thin wrapper around SQLite, to facilitate using SQLite from C++,
* to facilitate managing the resources required by SQLite using RAII,
* and to reduce the verbosity required in client code wishing to
* using the SQLite library. Sqloxx will not necessarily provide
* much in the way of objected-relational mapping. The intention is
* that the C++ API of Sqloxx will largely mirror the C API of
* SQLite, so that Sqloxx could be used easily by anyone who is
* familiar with SQLite (and with C++).
*
* @todo HIGH PRIORITY The API docs sometimes assume throw_on_failure will
* only ever throw a derivative of SQLiteException; however InvalidConnection
* is not a derivative of SQLiteException. Fix this.
*/
namespace sqloxx
{
// Forward declaration
namespace detail
{
class SQLStatement;
} // namespace detail
/**
* @class DatabaseConnection
*
* Represents a SQLite3 database connection. Class can be extended to provide
* representations of connections to application-specific databases.
*/
class DatabaseConnection:
private boost::noncopyable
{
public:
typedef
boost::unordered_map
< std::string, boost::shared_ptr<detail::SQLStatement>
>
StatementCache;
/**
* Initializes SQLite3 and creates a database connection initially
* set to null, i.e. not connected to any file.
*
* @param p_cache_capacity indicates the number of SQLStatements to
* be stored in a cache for reuse (via the class SharedSQLStatement)
* by the DatabaseConnection instance.
*
* Initializes SQLite3 and creates a database connection initially
* set to null, i.e. not connected to any file.
*
* @throws SQLiteInitializationError if initialization fails
* for any reason.
*
* Exception safety: <em>strong guarantee</em>.
*/
explicit
DatabaseConnection(StatementCache::size_type p_cache_capacity = 300);
/**
* Exception safety: <em>nothrow guarantee<em>. (Of course, the exception
* safety of derived classes will depend on their own destructors.)
*/
virtual ~DatabaseConnection();
/**
* @returns true if and only if there is a connection to a valid
* database AND detail_id_valid() also returns true. By
* default, detail_is_valid() always returns true; however it may
* be redefined in derived classes to provide additional checks.
*
* Exception safety: the base class function
* DatabaseConnection::is_valid offers the <em>nothrow guarantee</em>,
* however if detail_is_valid is redefined in derived classes, exception
* safety will depend on how it is redefined.
*/
virtual bool is_valid() const;
/**
* Points the database connection to a specific file
* given by \c filename. If the file
* does not already exist it is created. Note the SQLite pragma
* foreign_keys is always executed immediately the file is opened, to
* enable foreign key constraints.
*
* @todo This should be made to support Unicode filepaths, which
* apparently are used on Windows.
*
* @todo It appears that boost::filesystem::path::string() produces
* a GENERIC string (safely passable to SQLite database connection
* opening function) in Boost Version 1.42; but that in Version 1.46
* this produces a NATIVE string! Currently this function relies on the
* behaviour in version 1.42. I should use a macro or something to
* make it portable between versions of Boost.
*
* @param filepath File to connect to. The is in the form of a
* \c boost::filesystem::path to facilitate portability.
*
* @todo Do a full portability test to Windows, especially for cases
* involving escape characters and such.
*
* @throws sqloxx::InvalidFilename if filename is an empty string.
*
* @throws sqloxx::MultipleConnectionException if already connected to a
* database (be it this or another database).
*
* @throws SQLiteException or an exception derived therefrom (likely, but
* not guaranteed, to be SQLiteCantOpen) if for some other reason the
* connection cannot be opened.
*
* Exception safety: appears to offer the <em>basic guarantee</em>,
* <em>however</em> this has not been properly tested.
*/
void open(boost::filesystem::path const& filepath);
/**
* Executes a string as an SQL command on the database connection.
* This should be used only where the developer has complete
* control of the string being passed, to prevent SQL injection
* attacks. Generally, the functions provided by SQLStatement should
* be the preferred means for building and executing SQL statements.
*
* @throws DatabaseException or some exception inheriting thereof,
* whenever
* there is any kind of error executing the statement.
*
* Exception safety: <em>basic guarantee</em>. (Possibly also offers
* strong guarantee, but not certain.)
*/
void execute_sql(std::string const& str);
/**
* Given the name of a table in the connected database, assuming that
* table has a single-column primary key, and assuming that column is
* an autoincrementing primary key, this function will return the next
* highest key value (the value 1 greater than the highest primary key
* so far in the table). This will be the next key assigned by SQLite
* for an ordinary insertion into the table (assuming the default
* behaviour of SQLite in this regard has not been altered in some way).
* This function does NOT check whether the primary
* key is in fact autoincrementing, or even whether there is a primary
* key, or even whether the table with this name exists. In the event
* the next primary key can't be found, a
* value of \c KeyType(1) is simply returned. In other words, it is
* the caller's responsibility to make sure that table_name does in
* fact correspond to a table with an autoincrementing integer
* primary key.
*
* Assumes keys start from 1.
*
* KeyType should be an integral type, and should also be a type
* supported by SQLStatement::extract. If not, behaviour is \e undefined,
* although it is expected that compilation will fail where a KeyType
* that is not accepted by SQLStatement::extract is provided.
*
* It is the caller's responsibility to ensure that KeyType is large
* enough to accommodate the values that are \e already in the
* primary key of the table - otherwise behaviour is undefined.
*
* This function should not be used if \c table_name is an untrusted
* string.
*
* @param table_name The name of the table
*
* @returns the next highest primary key for the table, assuming it has
* a single-column primary key. Note if there are gaps in the numbering
* these are ignored. The returned value is always one greater than the
* currently greatest value for the key (but see exceptions).
*
* @throws sqloxx::TableSizeException if the greatest primary key value
* already in the table is the maximum value for \c KeyType, so that
* another row could not be inserted without overflow.
*
* @throws sqloxx::DatabaseException, or a derivative therefrom, may
* be thrown if there is some other
* error finding the next primary key value. This should not occur except
* in the case of a corrupt database, or a memory allocation error
* (extremely unlikely), or the database connection being invalid
* (including because not yet connected to a database file).
*/
template <typename KeyType>
KeyType next_auto_key(std::string const& table_name);
/**
* Creates table containing integers representing boolean values.
* This might be used to provide foreign key constraints for other
* tables where we wish a particular column to have boolean values
* only.
*
* The table is called "booleans" and has one column, an integer
* primary key field with the heading "representation". There are
* two rows, one with 0 in the "representation" column, representing
* \e false, and the other with 1, representing \e true.
*
* Exception safety: <em>strong guarantee</em>.
*/
void setup_boolean_table();
/**
* Returns the maximum level of transaction nesting that can be handled
* by the DatabaseConnection class.
*
* Exception safety: <em>nothrow guarantee</em>.
*/
static int max_nesting();
/**
* Begins a transaction. Transactions may be nested. Only the
* outermost call to begin_transaction causes the "begin transaction"
* SQL command to be executed.
*
* SQL transactions should be controlled either solely through the
* methods begin_transaction and end_transaction, \e or solely through
* the direct execution of SQL statement strings "begin transaction" and
* "end transaction". Mixing the two will result in undefined behaviour.
*
* @throws TransactionNestingException in the event that the maximum
* level of nesting has been reached. The maximum level of nesting is
* equal to the value returned by max_nesting().
*/
void begin_transaction();
/**
* Ends a transaction. Transactions may be nested. Only the outermost
* call to end_transaction causes the "end transaction" SQL command
* to be executed.
*
* See documentation of begin_transaction also.
*
* @throws TransactionNestingException in the event that there are
* more calls to end_transaction than there have been to
* begin_transaction.
*/
void end_transaction();
/**
* @returns a shared pointer to a SQLStatement. This will
* either point to an existing SQLStatement that is cached within
* the DatabaseConnection (if a SQLStatement with \c
* statement_text has already been created on this DatabaseConnection and
* is not being used elsewhere), or
* will be a pointer to a newly created and new cached SQLStatement (if a
* SQLStatement with \c statement_text has not yet been created on this
* DatabaseConnection, or it has been created but is being used
* elsewhere).
*
* This function is only intended to be called by the
* constructor of SharedSQLStatement. It should not be called elsewhere.
*/
boost::shared_ptr<detail::SQLStatement> provide_sql_statement
( std::string const& statement_text
);
private:
void unchecked_end_transaction();
/**
* By default this always returns true. However it may be overriden
* in derived classes as required.
*/
virtual bool detail_is_valid() const;
boost::shared_ptr<detail::SQLiteDBConn> m_sqlite_dbconn;
int m_transaction_nesting_level;
StatementCache m_statement_cache;
StatementCache::size_type m_cache_capacity;
static int const s_max_nesting;
};
// FUNCTION TEMPLATE DEFINITIONS AND INLINE FUNCTIONS
inline
bool
DatabaseConnection::is_valid() const
{
return m_sqlite_dbconn->is_valid() && detail_is_valid();
}
inline
void
DatabaseConnection::open(boost::filesystem::path const& filepath)
{
m_sqlite_dbconn->open(filepath);
return;
}
inline
void
DatabaseConnection::execute_sql(std::string const& str)
{
m_sqlite_dbconn->execute_sql(str);
return;
}
inline
bool
DatabaseConnection::detail_is_valid() const
{
return true;
}
template <typename KeyType>
inline
KeyType
DatabaseConnection::next_auto_key(std::string const& table_name)
{
try
{
SharedSQLStatement statement
( *this,
"select seq from sqlite_sequence where name = :p"
);
statement.bind(":p", table_name);
if (!statement.step())
{
return 1;
}
KeyType const max_key = statement.extract<KeyType>(0);
if (max_key == std::numeric_limits<KeyType>::max())
{
throw TableSizeException
( "Key cannot be safely incremented with given type."
);
}
return max_key + 1;
}
catch (SQLiteError&)
{
// Catches case where there is no sqlite_sequence table
SharedSQLStatement sequence_finder
( *this,
"select name from sqlite_master where type = 'table' and "
"name = 'sqlite_sequence';"
);
if (!sequence_finder.step())
{
return 1;
}
throw;
}
}
inline
int
DatabaseConnection::max_nesting()
{
return s_max_nesting;
}
inline
void
DatabaseConnection::unchecked_end_transaction()
{
SharedSQLStatement statement
( *this,
"end"
);
statement.step();
return;
}
} // namespace sqloxx
#endif // database_connection_hpp
<commit_msg>Got rid of unused function DatabaseConnection::detail_is_valid. Was adding complexity to API for no obvious benefit.<commit_after>#ifndef database_connection_hpp
#define database_connection_hpp
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <set>
#include <string>
#include "shared_sql_statement.hpp"
#include "detail/sqlite_dbconn.hpp"
/**
* Namespace for housing all Sqloxx code. Sqloxx is intended as a
* thin wrapper around SQLite, to facilitate using SQLite from C++,
* to facilitate managing the resources required by SQLite using RAII,
* and to reduce the verbosity required in client code wishing to
* using the SQLite library. Sqloxx will not necessarily provide
* much in the way of objected-relational mapping. The intention is
* that the C++ API of Sqloxx will largely mirror the C API of
* SQLite, so that Sqloxx could be used easily by anyone who is
* familiar with SQLite (and with C++).
*
* @todo HIGH PRIORITY The API docs sometimes assume throw_on_failure will
* only ever throw a derivative of SQLiteException; however InvalidConnection
* is not a derivative of SQLiteException. Fix this.
*/
namespace sqloxx
{
// Forward declaration
namespace detail
{
class SQLStatement;
} // namespace detail
/**
* @class DatabaseConnection
*
* Represents a SQLite3 database connection. Class can be extended to provide
* representations of connections to application-specific databases.
*/
class DatabaseConnection:
private boost::noncopyable
{
public:
typedef
boost::unordered_map
< std::string, boost::shared_ptr<detail::SQLStatement>
>
StatementCache;
/**
* Initializes SQLite3 and creates a database connection initially
* set to null, i.e. not connected to any file.
*
* @param p_cache_capacity indicates the number of SQLStatements to
* be stored in a cache for reuse (via the class SharedSQLStatement)
* by the DatabaseConnection instance.
*
* Initializes SQLite3 and creates a database connection initially
* set to null, i.e. not connected to any file.
*
* @throws SQLiteInitializationError if initialization fails
* for any reason.
*
* Exception safety: <em>strong guarantee</em>.
*/
explicit
DatabaseConnection(StatementCache::size_type p_cache_capacity = 300);
/**
* Exception safety: <em>nothrow guarantee<em>. (Of course, the exception
* safety of derived classes will depend on their own destructors.)
*/
virtual ~DatabaseConnection();
/**
* @returns true if and only if there is a connection to a valid
* database.
*
* Exception safety: <em>nothrow guarantee</em>.
*/
virtual bool is_valid() const;
/**
* Points the database connection to a specific file
* given by \c filename. If the file
* does not already exist it is created. Note the SQLite pragma
* foreign_keys is always executed immediately the file is opened, to
* enable foreign key constraints.
*
* @todo This should be made to support Unicode filepaths, which
* apparently are used on Windows.
*
* @todo It appears that boost::filesystem::path::string() produces
* a GENERIC string (safely passable to SQLite database connection
* opening function) in Boost Version 1.42; but that in Version 1.46
* this produces a NATIVE string! Currently this function relies on the
* behaviour in version 1.42. I should use a macro or something to
* make it portable between versions of Boost.
*
* @param filepath File to connect to. The is in the form of a
* \c boost::filesystem::path to facilitate portability.
*
* @todo Do a full portability test to Windows, especially for cases
* involving escape characters and such.
*
* @throws sqloxx::InvalidFilename if filename is an empty string.
*
* @throws sqloxx::MultipleConnectionException if already connected to a
* database (be it this or another database).
*
* @throws SQLiteException or an exception derived therefrom (likely, but
* not guaranteed, to be SQLiteCantOpen) if for some other reason the
* connection cannot be opened.
*
* Exception safety: appears to offer the <em>basic guarantee</em>,
* <em>however</em> this has not been properly tested.
*/
void open(boost::filesystem::path const& filepath);
/**
* Executes a string as an SQL command on the database connection.
* This should be used only where the developer has complete
* control of the string being passed, to prevent SQL injection
* attacks. Generally, the functions provided by SQLStatement should
* be the preferred means for building and executing SQL statements.
*
* @throws DatabaseException or some exception inheriting thereof,
* whenever
* there is any kind of error executing the statement.
*
* @throws InvalidConnection if the database connection is invalid.
*
* Exception safety: <em>basic guarantee</em>. (Possibly also offers
* strong guarantee, but not certain.)
*/
void execute_sql(std::string const& str);
/**
* Given the name of a table in the connected database, assuming that
* table has a single-column primary key, and assuming that column is
* an autoincrementing primary key, this function will return the next
* highest key value (the value 1 greater than the highest primary key
* so far in the table). This will be the next key assigned by SQLite
* for an ordinary insertion into the table (assuming the default
* behaviour of SQLite in this regard has not been altered in some way).
* This function does NOT check whether the primary
* key is in fact autoincrementing, or even whether there is a primary
* key, or even whether the table with this name exists. In the event
* the next primary key can't be found, a
* value of \c KeyType(1) is simply returned. In other words, it is
* the caller's responsibility to make sure that table_name does in
* fact correspond to a table with an autoincrementing integer
* primary key.
*
* Assumes keys start from 1.
*
* KeyType should be an integral type, and should also be a type
* supported by SQLStatement::extract. If not, behaviour is \e undefined,
* although it is expected that compilation will fail where a KeyType
* that is not accepted by SQLStatement::extract is provided.
*
* It is the caller's responsibility to ensure that KeyType is large
* enough to accommodate the values that are \e already in the
* primary key of the table - otherwise behaviour is undefined.
*
* This function should not be used if \c table_name is an untrusted
* string.
*
* @param table_name The name of the table
*
* @returns the next highest primary key for the table, assuming it has
* a single-column primary key. Note if there are gaps in the numbering
* these are ignored. The returned value is always one greater than the
* currently greatest value for the key (but see exceptions).
*
* @throws sqloxx::TableSizeException if the greatest primary key value
* already in the table is the maximum value for \c KeyType, so that
* another row could not be inserted without overflow.
*
* @throws sqloxx::DatabaseException, or a derivative therefrom, may
* be thrown if there is some other
* error finding the next primary key value. This should not occur except
* in the case of a corrupt database, or a memory allocation error
* (extremely unlikely), or the database connection being invalid
* (including because not yet connected to a database file).
*/
template <typename KeyType>
KeyType next_auto_key(std::string const& table_name);
/**
* Creates table containing integers representing boolean values.
* This might be used to provide foreign key constraints for other
* tables where we wish a particular column to have boolean values
* only.
*
* The table is called "booleans" and has one column, an integer
* primary key field with the heading "representation". There are
* two rows, one with 0 in the "representation" column, representing
* \e false, and the other with 1, representing \e true.
*
* Exception safety: <em>strong guarantee</em>.
*/
void setup_boolean_table();
/**
* Returns the maximum level of transaction nesting that can be handled
* by the DatabaseConnection class.
*
* Exception safety: <em>nothrow guarantee</em>.
*/
static int max_nesting();
/**
* Begins a transaction. Transactions may be nested. Only the
* outermost call to begin_transaction causes the "begin transaction"
* SQL command to be executed.
*
* SQL transactions should be controlled either solely through the
* methods begin_transaction and end_transaction, \e or solely through
* the direct execution of SQL statement strings "begin transaction" and
* "end transaction". Mixing the two will result in undefined behaviour.
*
* @throws TransactionNestingException in the event that the maximum
* level of nesting has been reached. The maximum level of nesting is
* equal to the value returned by max_nesting().
*/
void begin_transaction();
/**
* Ends a transaction. Transactions may be nested. Only the outermost
* call to end_transaction causes the "end transaction" SQL command
* to be executed.
*
* See documentation of begin_transaction also.
*
* @throws TransactionNestingException in the event that there are
* more calls to end_transaction than there have been to
* begin_transaction.
*/
void end_transaction();
/**
* @returns a shared pointer to a SQLStatement. This will
* either point to an existing SQLStatement that is cached within
* the DatabaseConnection (if a SQLStatement with \c
* statement_text has already been created on this DatabaseConnection and
* is not being used elsewhere), or
* will be a pointer to a newly created and new cached SQLStatement (if a
* SQLStatement with \c statement_text has not yet been created on this
* DatabaseConnection, or it has been created but is being used
* elsewhere).
*
* This function is only intended to be called by the
* constructor of SharedSQLStatement. It should not be called elsewhere.
*/
boost::shared_ptr<detail::SQLStatement> provide_sql_statement
( std::string const& statement_text
);
private:
void unchecked_end_transaction();
boost::shared_ptr<detail::SQLiteDBConn> m_sqlite_dbconn;
int m_transaction_nesting_level;
StatementCache m_statement_cache;
StatementCache::size_type m_cache_capacity;
static int const s_max_nesting;
};
// FUNCTION TEMPLATE DEFINITIONS AND INLINE FUNCTIONS
inline
bool
DatabaseConnection::is_valid() const
{
return m_sqlite_dbconn->is_valid();
}
inline
void
DatabaseConnection::open(boost::filesystem::path const& filepath)
{
m_sqlite_dbconn->open(filepath);
return;
}
inline
void
DatabaseConnection::execute_sql(std::string const& str)
{
m_sqlite_dbconn->execute_sql(str);
return;
}
template <typename KeyType>
inline
KeyType
DatabaseConnection::next_auto_key(std::string const& table_name)
{
try
{
SharedSQLStatement statement
( *this,
"select seq from sqlite_sequence where name = :p"
);
statement.bind(":p", table_name);
if (!statement.step())
{
return 1;
}
KeyType const max_key = statement.extract<KeyType>(0);
if (max_key == std::numeric_limits<KeyType>::max())
{
throw TableSizeException
( "Key cannot be safely incremented with given type."
);
}
return max_key + 1;
}
catch (SQLiteError&)
{
// Catches case where there is no sqlite_sequence table
SharedSQLStatement sequence_finder
( *this,
"select name from sqlite_master where type = 'table' and "
"name = 'sqlite_sequence';"
);
if (!sequence_finder.step())
{
return 1;
}
throw;
}
}
inline
int
DatabaseConnection::max_nesting()
{
return s_max_nesting;
}
inline
void
DatabaseConnection::unchecked_end_transaction()
{
SharedSQLStatement statement
( *this,
"end"
);
statement.step();
return;
}
} // namespace sqloxx
#endif // database_connection_hpp
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright The University of Auckland
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.
*******************************************************************************/
//==============================================================================
// Editor find/replace widget
//==============================================================================
#include "coreguiutils.h"
#include "editorwidgetfindreplacewidget.h"
#include "i18ninterface.h"
//==============================================================================
#include "ui_editorwidgetfindreplacewidget.h"
//==============================================================================
#include <Qt>
//==============================================================================
#include <QAction>
#include <QKeyEvent>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QPainter>
#include <QPixmap>
#include <QSize>
#include <QToolButton>
//==============================================================================
namespace OpenCOR {
namespace EditorWidget {
//==============================================================================
EditorWidgetFindReplaceWidget::EditorWidgetFindReplaceWidget(QWidget *pParent) :
Core::Widget(pParent),
mGui(new Ui::EditorWidgetFindReplaceWidget),
mActive(false)
{
// Set up the GUI
mGui->setupUi(this);
#ifdef Q_OS_MAC
mGui->findEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
mGui->replaceEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
// Note: the above remove the focus border since it messes up the look of
// our edit widgets...
#endif
// Create and handle our drop-down menu action
mDropDownAction = Core::newAction(this);
mCaseSensitiveAction = Core::newAction(true, this);
mWholeWordsOnlyAction = Core::newAction(true, this);
mRegularExpressionAction = Core::newAction(true, this);
QMenu *dropDownMenu = new QMenu(this);
dropDownMenu->addAction(mCaseSensitiveAction);
dropDownMenu->addAction(mWholeWordsOnlyAction);
dropDownMenu->addAction(mRegularExpressionAction);
mDropDownAction->setMenu(dropDownMenu);
mGui->findEdit->addAction(mDropDownAction, QLineEdit::LeadingPosition);
connect(mCaseSensitiveAction, SIGNAL(toggled(bool)),
this, SLOT(searchOptionChanged()));
connect(mWholeWordsOnlyAction, SIGNAL(toggled(bool)),
this, SLOT(searchOptionChanged()));
connect(mRegularExpressionAction, SIGNAL(toggled(bool)),
this, SLOT(searchOptionChanged()));
// Create and handle our clear find and replace text actions
mClearFindTextAction = Core::newAction(QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/images/editclear.png"), this);
mClearReplaceTextAction = Core::newAction(QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/images/editclear.png"), this);
connect(mClearFindTextAction, SIGNAL(triggered(bool)),
mGui->findEdit, SLOT(clear()));
connect(mClearReplaceTextAction, SIGNAL(triggered(bool)),
mGui->replaceEdit, SLOT(clear()));
// Make our find edit widget our focus proxy
setFocusProxy(mGui->findEdit);
// Some connections for our find-related widgets
connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(updateClearFindTextAction(const QString &)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->findPreviousButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->findNextButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->replaceButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->replaceAndFindButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->replaceAllButton, SLOT(setEnabled(bool)));
// A connection for our replace widget
connect(mGui->replaceEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(updateClearReplaceTextAction(const QString &)));
// A few more things , so that we are properly initialised
retranslateUi();
searchOptionChanged();
setActive(true);
updateStyleSheet();
updateHeight();
// Note: just to be safe, we update our height after updating our style
// sheet since we change the size of our tool buttons...
mGui->findPreviousButton->setEnabled(false);
mGui->findNextButton->setEnabled(false);
mGui->replaceButton->setEnabled(false);
mGui->replaceAndFindButton->setEnabled(false);
mGui->replaceAllButton->setEnabled(false);
}
//==============================================================================
EditorWidgetFindReplaceWidget::~EditorWidgetFindReplaceWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void EditorWidgetFindReplaceWidget::retranslateUi()
{
// Retranslate our GUI
mGui->retranslateUi(this);
// Retranslate our actions
I18nInterface::retranslateAction(mCaseSensitiveAction, tr("Case Sensitive"),
tr("The search is case sensitive"));
I18nInterface::retranslateAction(mWholeWordsOnlyAction, tr("Whole Words Only"),
tr("The search is done on whole words only"));
I18nInterface::retranslateAction(mRegularExpressionAction, tr("Regular Expression"),
tr("The search uses a regular expression"));
I18nInterface::retranslateAction(mClearFindTextAction, tr("Clear Text"),
tr("Clear the text"));
I18nInterface::retranslateAction(mClearReplaceTextAction, tr("Clear Text"),
tr("Clear the text"));
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::isCaseSensitive() const
{
// Return whether the search is to be case sensitive
return mCaseSensitiveAction->isChecked();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::searchWholeWordsOnly() const
{
// Return whether we search whole words only
return mWholeWordsOnlyAction->isChecked();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::useRegularExpression() const
{
// Return whether we use a regular expression
return mRegularExpressionAction->isChecked();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::setReadOnly(const bool &pReadOnly)
{
// Show/hide our replace-related widgets based on whether we are in
// read-only mode
Core::showEnableWidget(mGui->replaceLabel, !pReadOnly);
Core::showEnableWidget(mGui->replaceEdit, !pReadOnly);
Core::showEnableWidget(mGui->replaceButton, !pReadOnly);
Core::showEnableWidget(mGui->replaceAndFindButton, !pReadOnly);
Core::showEnableWidget(mGui->replaceAllButton, !pReadOnly);
// Enable/disable our find spacer
mGui->findLayout->setStretch(2, !pReadOnly);
// Disable our replace-related buttons, if needed
if (findText().isEmpty()) {
mGui->replaceButton->setEnabled(false);
mGui->replaceAndFindButton->setEnabled(false);
mGui->replaceAllButton->setEnabled(false);
}
// Update our height
updateHeight();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::isFindPreviousNextAvailable() const
{
// Return whether the find previous/next actions are available
return !findText().isEmpty();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::selectFindText() const
{
// Select our find text
mGui->findEdit->selectAll();
}
//==============================================================================
QString EditorWidgetFindReplaceWidget::findText() const
{
// Return our find text
return mGui->findEdit->text();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::setFindText(const QString &pFindText)
{
// Set our find text and select it
mGui->findEdit->setText(pFindText);
selectFindText();
}
//==============================================================================
QString EditorWidgetFindReplaceWidget::replaceText() const
{
// Return our replace text
return mGui->replaceEdit->text();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::findEditHasFocus() const
{
// Return whether our find edit has the focus
return mGui->findEdit->hasFocus();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::replaceEditHasFocus() const
{
// Return whether our replace edit has the focus
return mGui->replaceEdit->hasFocus();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::isActive() const
{
// Return whether we are active
return mActive;
}
//==============================================================================
void EditorWidgetFindReplaceWidget::setActive(const bool &pActive)
{
if (pActive == mActive)
return;
// Set our active state
mActive = pActive;
if (pActive)
connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),
this, SIGNAL(findTextChanged(const QString &)));
else
disconnect(mGui->findEdit, SIGNAL(textChanged(const QString &)),
this, SIGNAL(findTextChanged(const QString &)));
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateFrom(EditorWidgetFindReplaceWidget *pFindReplace)
{
// Update our find and replace texts from the given find/replace widget
mGui->findEdit->setText(pFindReplace->findText());
mGui->replaceEdit->setText(pFindReplace->replaceText());
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateHeight()
{
// Update our layout
// Note: we shouldn't have to do this, but if the user opens a read-only and
// shows ourselves, then the find-related widgets will be too 'low'.
// This is because the replace-related widgets get hidden/disabled as
// expected, but the layout doesn't get updated before we fix our
// height, so we update our layout here and in all cases...
mGui->layout->update();
// Update our height
setFixedHeight(mGui->layout->sizeHint().height());
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateStyleSheet()
{
// Change the style of our tool buttons
QColor shadowColor = Core::shadowColor();
setStyleSheet(QString("QToolButton {"
" border: 0px;"
" border-radius: 3px;"
" padding: 1px;"
"}"
""
"QToolButton:focus {"
" background: rgba(%1, %2, %3, 0.13);"
" border: 1px solid rgba(%1, %2, %3, 0.39);"
"}"
""
"QToolButton:hover {"
" background: rgba(%1, %2, %3, 0.39);"
"}"
""
"QToolButton:pressed {"
" background: rgba(%1, %2, %3, 0.79);"
"}").arg(QString::number(shadowColor.red()),
QString::number(shadowColor.green()),
QString::number(shadowColor.blue())));
}
//==============================================================================
void EditorWidgetFindReplaceWidget::changeEvent(QEvent *pEvent)
{
// Check whether the palette has changed and if so then update our style
// sheet
if (pEvent->type() == QEvent::PaletteChange)
updateStyleSheet();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::keyPressEvent(QKeyEvent *pEvent)
{
// Let people know that a key has been pressed
bool handled = false;
emit keyPressed(pEvent, handled);
// Carry on as normal, if the event wasn't handled
if (handled)
// Accept the event
pEvent->accept();
else
// Default handling of the event
Core::Widget::keyPressEvent(pEvent);
}
//==============================================================================
void EditorWidgetFindReplaceWidget::resizeEvent(QResizeEvent *pEvent)
{
// Default handling of the event
Core::Widget::resizeEvent(pEvent);
// Update our height
updateHeight();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_findPreviousButton_clicked()
{
// Let people know that we want to find the previous occurrence of the text
emit findPreviousRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_findNextButton_clicked()
{
// Let people know that we want to find the next occurrence of the text
emit findNextRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_replaceButton_clicked()
{
// Let people know that we want to replace the current text
emit replaceRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_replaceAndFindButton_clicked()
{
// Let people know that we want to replace the current text and the find the
// next occurence of the text
emit replaceAndFindRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_replaceAllButton_clicked()
{
// Let people know that we want to replace all the occurences of the text
emit replaceAllRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::searchOptionChanged()
{
// Update the icon used for the leading position of our find widget
static const QIcon DefaultIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/images/magnifier.png");
static const QIcon CaseSensitiveIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/find/images/casesensitively.png");
static const QIcon WholeWordsOnlyIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/find/images/wholewords.png");
static const QIcon RegularExpressionIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/find/images/regexp.png");
int nbOfOptions = mCaseSensitiveAction->isChecked()
+mWholeWordsOnlyAction->isChecked()
+mRegularExpressionAction->isChecked();
if (nbOfOptions) {
static const int IconSize = 16;
static const int IconWidth = 6;
QPixmap dropDownPixmap = QPixmap(nbOfOptions*IconWidth-mRegularExpressionAction->isChecked(),
IconSize);
// Note: -mRegularExpressionAction->isChecked(), because
// regularExpressionIcon is effectively one pixel narrower than
// caseSensitiveIcon and wholeWordsOnlyIcon...
dropDownPixmap.fill(Qt::transparent);
QPainter dropDownPixmapPainter(&dropDownPixmap);
int left = -IconWidth;
if (mCaseSensitiveAction->isChecked()) {
CaseSensitiveIcon.paint(&dropDownPixmapPainter, left, 0, IconSize, IconSize);
left += IconWidth;
}
if (mWholeWordsOnlyAction->isChecked()) {
WholeWordsOnlyIcon.paint(&dropDownPixmapPainter, left, 0, IconSize, IconSize);
left += IconWidth;
}
if (mRegularExpressionAction->isChecked())
RegularExpressionIcon.paint(&dropDownPixmapPainter, left-1, 0, IconSize, IconSize);
mDropDownAction->setIcon(dropDownPixmap);
} else {
// No options are set, so use our default icon
mDropDownAction->setIcon(DefaultIcon);
}
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateClearFindTextAction(const QString &pText)
{
// Show/hide our clear text action, based on whether our find widget
// contains some text
if (pText.isEmpty())
mGui->findEdit->removeAction(mClearFindTextAction);
else
mGui->findEdit->addAction(mClearFindTextAction, QLineEdit::TrailingPosition);
// Let people know whether we can find/replace
emit canFindReplace(!findText().isEmpty());
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateClearReplaceTextAction(const QString &pText)
{
// Show/hide our clear text action, based on whether our replace widget
// contains some text
if (pText.isEmpty())
mGui->replaceEdit->removeAction(mClearReplaceTextAction);
else
mGui->replaceEdit->addAction(mClearReplaceTextAction, QLineEdit::TrailingPosition);
}
//==============================================================================
} // namespace EditorWidget
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Editor (find/replace widget): fixed a problem with the icon for the search options / magnifier looking wrong (closes #1026).<commit_after>/*******************************************************************************
Copyright The University of Auckland
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.
*******************************************************************************/
//==============================================================================
// Editor find/replace widget
//==============================================================================
#include "coreguiutils.h"
#include "editorwidgetfindreplacewidget.h"
#include "i18ninterface.h"
//==============================================================================
#include "ui_editorwidgetfindreplacewidget.h"
//==============================================================================
#include <Qt>
//==============================================================================
#include <QAction>
#include <QKeyEvent>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QPainter>
#include <QPixmap>
#include <QSize>
#include <QToolButton>
//==============================================================================
namespace OpenCOR {
namespace EditorWidget {
//==============================================================================
EditorWidgetFindReplaceWidget::EditorWidgetFindReplaceWidget(QWidget *pParent) :
Core::Widget(pParent),
mGui(new Ui::EditorWidgetFindReplaceWidget),
mActive(false)
{
// Set up the GUI
mGui->setupUi(this);
#ifdef Q_OS_MAC
mGui->findEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
mGui->replaceEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
// Note: the above remove the focus border since it messes up the look of
// our edit widgets...
#endif
// Create and handle our drop-down menu action
mDropDownAction = Core::newAction(this);
mCaseSensitiveAction = Core::newAction(true, this);
mWholeWordsOnlyAction = Core::newAction(true, this);
mRegularExpressionAction = Core::newAction(true, this);
QMenu *dropDownMenu = new QMenu(this);
dropDownMenu->addAction(mCaseSensitiveAction);
dropDownMenu->addAction(mWholeWordsOnlyAction);
dropDownMenu->addAction(mRegularExpressionAction);
mDropDownAction->setMenu(dropDownMenu);
mGui->findEdit->addAction(mDropDownAction, QLineEdit::LeadingPosition);
connect(mCaseSensitiveAction, SIGNAL(toggled(bool)),
this, SLOT(searchOptionChanged()));
connect(mWholeWordsOnlyAction, SIGNAL(toggled(bool)),
this, SLOT(searchOptionChanged()));
connect(mRegularExpressionAction, SIGNAL(toggled(bool)),
this, SLOT(searchOptionChanged()));
// Create and handle our clear find and replace text actions
mClearFindTextAction = Core::newAction(QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/images/editclear.png"), this);
mClearReplaceTextAction = Core::newAction(QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/images/editclear.png"), this);
connect(mClearFindTextAction, SIGNAL(triggered(bool)),
mGui->findEdit, SLOT(clear()));
connect(mClearReplaceTextAction, SIGNAL(triggered(bool)),
mGui->replaceEdit, SLOT(clear()));
// Make our find edit widget our focus proxy
setFocusProxy(mGui->findEdit);
// Some connections for our find-related widgets
connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(updateClearFindTextAction(const QString &)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->findPreviousButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->findNextButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->replaceButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->replaceAndFindButton, SLOT(setEnabled(bool)));
connect(this, SIGNAL(canFindReplace(const bool &)),
mGui->replaceAllButton, SLOT(setEnabled(bool)));
// A connection for our replace widget
connect(mGui->replaceEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(updateClearReplaceTextAction(const QString &)));
// A few more things , so that we are properly initialised
retranslateUi();
searchOptionChanged();
setActive(true);
updateStyleSheet();
updateHeight();
// Note: just to be safe, we update our height after updating our style
// sheet since we change the size of our tool buttons...
mGui->findPreviousButton->setEnabled(false);
mGui->findNextButton->setEnabled(false);
mGui->replaceButton->setEnabled(false);
mGui->replaceAndFindButton->setEnabled(false);
mGui->replaceAllButton->setEnabled(false);
}
//==============================================================================
EditorWidgetFindReplaceWidget::~EditorWidgetFindReplaceWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void EditorWidgetFindReplaceWidget::retranslateUi()
{
// Retranslate our GUI
mGui->retranslateUi(this);
// Retranslate our actions
I18nInterface::retranslateAction(mCaseSensitiveAction, tr("Case Sensitive"),
tr("The search is case sensitive"));
I18nInterface::retranslateAction(mWholeWordsOnlyAction, tr("Whole Words Only"),
tr("The search is done on whole words only"));
I18nInterface::retranslateAction(mRegularExpressionAction, tr("Regular Expression"),
tr("The search uses a regular expression"));
I18nInterface::retranslateAction(mClearFindTextAction, tr("Clear Text"),
tr("Clear the text"));
I18nInterface::retranslateAction(mClearReplaceTextAction, tr("Clear Text"),
tr("Clear the text"));
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::isCaseSensitive() const
{
// Return whether the search is to be case sensitive
return mCaseSensitiveAction->isChecked();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::searchWholeWordsOnly() const
{
// Return whether we search whole words only
return mWholeWordsOnlyAction->isChecked();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::useRegularExpression() const
{
// Return whether we use a regular expression
return mRegularExpressionAction->isChecked();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::setReadOnly(const bool &pReadOnly)
{
// Show/hide our replace-related widgets based on whether we are in
// read-only mode
Core::showEnableWidget(mGui->replaceLabel, !pReadOnly);
Core::showEnableWidget(mGui->replaceEdit, !pReadOnly);
Core::showEnableWidget(mGui->replaceButton, !pReadOnly);
Core::showEnableWidget(mGui->replaceAndFindButton, !pReadOnly);
Core::showEnableWidget(mGui->replaceAllButton, !pReadOnly);
// Enable/disable our find spacer
mGui->findLayout->setStretch(2, !pReadOnly);
// Disable our replace-related buttons, if needed
if (findText().isEmpty()) {
mGui->replaceButton->setEnabled(false);
mGui->replaceAndFindButton->setEnabled(false);
mGui->replaceAllButton->setEnabled(false);
}
// Update our height
updateHeight();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::isFindPreviousNextAvailable() const
{
// Return whether the find previous/next actions are available
return !findText().isEmpty();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::selectFindText() const
{
// Select our find text
mGui->findEdit->selectAll();
}
//==============================================================================
QString EditorWidgetFindReplaceWidget::findText() const
{
// Return our find text
return mGui->findEdit->text();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::setFindText(const QString &pFindText)
{
// Set our find text and select it
mGui->findEdit->setText(pFindText);
selectFindText();
}
//==============================================================================
QString EditorWidgetFindReplaceWidget::replaceText() const
{
// Return our replace text
return mGui->replaceEdit->text();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::findEditHasFocus() const
{
// Return whether our find edit has the focus
return mGui->findEdit->hasFocus();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::replaceEditHasFocus() const
{
// Return whether our replace edit has the focus
return mGui->replaceEdit->hasFocus();
}
//==============================================================================
bool EditorWidgetFindReplaceWidget::isActive() const
{
// Return whether we are active
return mActive;
}
//==============================================================================
void EditorWidgetFindReplaceWidget::setActive(const bool &pActive)
{
if (pActive == mActive)
return;
// Set our active state
mActive = pActive;
if (pActive)
connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),
this, SIGNAL(findTextChanged(const QString &)));
else
disconnect(mGui->findEdit, SIGNAL(textChanged(const QString &)),
this, SIGNAL(findTextChanged(const QString &)));
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateFrom(EditorWidgetFindReplaceWidget *pFindReplace)
{
// Update our find and replace texts from the given find/replace widget
mGui->findEdit->setText(pFindReplace->findText());
mGui->replaceEdit->setText(pFindReplace->replaceText());
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateHeight()
{
// Update our layout
// Note: we shouldn't have to do this, but if the user opens a read-only and
// shows ourselves, then the find-related widgets will be too 'low'.
// This is because the replace-related widgets get hidden/disabled as
// expected, but the layout doesn't get updated before we fix our
// height, so we update our layout here and in all cases...
mGui->layout->update();
// Update our height
setFixedHeight(mGui->layout->sizeHint().height());
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateStyleSheet()
{
// Change the style of our tool buttons
QColor shadowColor = Core::shadowColor();
setStyleSheet(QString("QToolButton {"
" border: 0px;"
" border-radius: 3px;"
" padding: 1px;"
"}"
""
"QToolButton:focus {"
" background: rgba(%1, %2, %3, 0.13);"
" border: 1px solid rgba(%1, %2, %3, 0.39);"
"}"
""
"QToolButton:hover {"
" background: rgba(%1, %2, %3, 0.39);"
"}"
""
"QToolButton:pressed {"
" background: rgba(%1, %2, %3, 0.79);"
"}").arg(QString::number(shadowColor.red()),
QString::number(shadowColor.green()),
QString::number(shadowColor.blue())));
}
//==============================================================================
void EditorWidgetFindReplaceWidget::changeEvent(QEvent *pEvent)
{
// Check whether the palette has changed and if so then update our style
// sheet
if (pEvent->type() == QEvent::PaletteChange)
updateStyleSheet();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::keyPressEvent(QKeyEvent *pEvent)
{
// Let people know that a key has been pressed
bool handled = false;
emit keyPressed(pEvent, handled);
// Carry on as normal, if the event wasn't handled
if (handled)
// Accept the event
pEvent->accept();
else
// Default handling of the event
Core::Widget::keyPressEvent(pEvent);
}
//==============================================================================
void EditorWidgetFindReplaceWidget::resizeEvent(QResizeEvent *pEvent)
{
// Default handling of the event
Core::Widget::resizeEvent(pEvent);
// Update our height
updateHeight();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_findPreviousButton_clicked()
{
// Let people know that we want to find the previous occurrence of the text
emit findPreviousRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_findNextButton_clicked()
{
// Let people know that we want to find the next occurrence of the text
emit findNextRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_replaceButton_clicked()
{
// Let people know that we want to replace the current text
emit replaceRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_replaceAndFindButton_clicked()
{
// Let people know that we want to replace the current text and the find the
// next occurence of the text
emit replaceAndFindRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::on_replaceAllButton_clicked()
{
// Let people know that we want to replace all the occurences of the text
emit replaceAllRequested();
}
//==============================================================================
void EditorWidgetFindReplaceWidget::searchOptionChanged()
{
// Update the icon used for the leading position of our find widget
static const QIcon MagnifierIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/images/magnifier.png");
static const QIcon CaseSensitiveIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/find/images/casesensitively.png");
static const QIcon WholeWordsOnlyIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/find/images/wholewords.png");
static const QIcon RegularExpressionIcon = QIcon(":/EditorWidget/qtCreator/src/plugins/coreplugin/find/images/regexp.png");
static const int IconSize = 16;
static const int MagnifierIconWidth = 17;
static const int MagnifierIconHeight = 11;
static const int CaseSensitiveIconShift = 6;
static const int WholeWordsOnlyIconShift = 6;
static const int RegularExpressionShift = 7;
static const int CaseSensitiveIconWidth = 5;
static const int WholeWordsOnlyIconWidth = 5;
static const int RegularExpressionWidth = 4;
int nbOfOptions = mCaseSensitiveAction->isChecked()
+mWholeWordsOnlyAction->isChecked()
+mRegularExpressionAction->isChecked();
QPixmap dropDownPixmap = QPixmap(IconSize, IconSize);
dropDownPixmap.fill(Qt::transparent);
QPainter dropDownPixmapPainter(&dropDownPixmap);
if (nbOfOptions) {
int left = ( IconSize-nbOfOptions+1
-mCaseSensitiveAction->isChecked()*CaseSensitiveIconWidth
-mWholeWordsOnlyAction->isChecked()*WholeWordsOnlyIconWidth
-mRegularExpressionAction->isChecked()*RegularExpressionWidth) >> 1;
if (mCaseSensitiveAction->isChecked()) {
CaseSensitiveIcon.paint(&dropDownPixmapPainter,
left-CaseSensitiveIconShift, 0,
IconSize, IconSize);
left += CaseSensitiveIconWidth+1;
}
if (mWholeWordsOnlyAction->isChecked()) {
WholeWordsOnlyIcon.paint(&dropDownPixmapPainter,
left-WholeWordsOnlyIconShift, 0,
IconSize, IconSize);
left += WholeWordsOnlyIconWidth+1;
}
if (mRegularExpressionAction->isChecked()) {
RegularExpressionIcon.paint(&dropDownPixmapPainter,
left-RegularExpressionShift, 0,
IconSize, IconSize);
}
} else {
// We hack of magnifier icon away so that it ends up looking the way we
// want it (since it's wider than 16 pixels)
MagnifierIcon.paint(&dropDownPixmapPainter,
-1, ((IconSize-MagnifierIconHeight) >> 1)+1,
MagnifierIconWidth, MagnifierIconHeight);
QPen pen = dropDownPixmapPainter.pen();
pen.setColor(Qt::white);
dropDownPixmapPainter.setPen(pen);
dropDownPixmapPainter.drawPoint(0, 13);
}
mDropDownAction->setIcon(dropDownPixmap);
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateClearFindTextAction(const QString &pText)
{
// Show/hide our clear text action, based on whether our find widget
// contains some text
if (pText.isEmpty())
mGui->findEdit->removeAction(mClearFindTextAction);
else
mGui->findEdit->addAction(mClearFindTextAction, QLineEdit::TrailingPosition);
// Let people know whether we can find/replace
emit canFindReplace(!findText().isEmpty());
}
//==============================================================================
void EditorWidgetFindReplaceWidget::updateClearReplaceTextAction(const QString &pText)
{
// Show/hide our clear text action, based on whether our replace widget
// contains some text
if (pText.isEmpty())
mGui->replaceEdit->removeAction(mClearReplaceTextAction);
else
mGui->replaceEdit->addAction(mClearReplaceTextAction, QLineEdit::TrailingPosition);
}
//==============================================================================
} // namespace EditorWidget
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|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/gtk/about_chrome_dialog.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_version_info.h"
#include "base/gfx/gtk_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/gtk_util.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "webkit/glue/webkit_glue.h"
namespace {
// The URLs that you navigate to when clicking the links in the About dialog.
const char* const kAcknowledgements = "about:credits";
const char* const kTOS = "about:terms";
// Left or right margin.
const int kPanelHorizMargin = 13;
// Top or bottom margin.
const int kPanelVertMargin = 20;
// Extra spacing between product name and version number.
const int kExtraLineSpacing = 5;
// These are used as placeholder text around the links in the text in the about
// dialog.
const char* kBeginLinkChr = "BEGIN_LINK_CHR";
const char* kBeginLinkOss = "BEGIN_LINK_OSS";
// We don't actually use this one.
// const char* kEndLinkChr = "END_LINK_CHR";
const char* kEndLinkOss = "END_LINK_OSS";
const char* kBeginLink = "BEGIN_LINK";
const char* kEndLink = "END_LINK";
void OnDialogResponse(GtkDialog* dialog, int response_id) {
// We're done.
gtk_widget_destroy(GTK_WIDGET(dialog));
}
void FixLabelWrappingCallback(GtkWidget *label,
GtkAllocation *allocation,
gpointer data) {
gtk_widget_set_size_request(label, allocation->width, -1);
}
GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {
GtkWidget* label = gtk_label_new(NULL);
char* markup = g_markup_printf_escaped(format, str.c_str());
gtk_label_set_markup(GTK_LABEL(label), markup);
g_free(markup);
// Left align it.
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
return label;
}
void OnLinkButtonClick(GtkWidget* button, const char* url) {
BrowserList::GetLastActive()->
OpenURL(GURL(url), GURL(), NEW_WINDOW, PageTransition::LINK);
}
const char* GetChromiumUrl() {
static std::string url(l10n_util::GetStringUTF8(IDS_CHROMIUM_PROJECT_URL));
return url.c_str();
}
} // namespace
void ShowAboutDialogForProfile(GtkWindow* parent, Profile* profile) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
static GdkPixbuf* background = rb.GetPixbufNamed(IDR_ABOUT_BACKGROUND);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
std::wstring current_version = version_info->file_version();
#if !defined(GOOGLE_CHROME_BUILD)
current_version += L" (";
current_version += version_info->last_change();
current_version += L")";
#endif
// Build the dialog.
GtkWidget* dialog = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_ABOUT_CHROME_TITLE).c_str(),
parent,
GTK_DIALOG_MODAL,
GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
NULL);
// Pick up the style set in gtk_util.cc:InitRCStyles().
// The layout of this dialog is special because the logo should be flush
// with the edges of the window.
gtk_widget_set_name(dialog, "about-dialog");
gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);
GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
// Use an event box to get the background painting correctly
GtkWidget* ebox = gtk_event_box_new();
gtk_widget_modify_bg(ebox, GTK_STATE_NORMAL, &gfx::kGdkWhite);
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
GtkWidget* text_alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(text_alignment),
kPanelVertMargin, kPanelVertMargin,
kPanelHorizMargin, kPanelHorizMargin);
GtkWidget* text_vbox = gtk_vbox_new(FALSE, kExtraLineSpacing);
GtkWidget* product_label = MakeMarkupLabel(
"<span font_desc=\"18\" weight=\"bold\" style=\"normal\">%s</span>",
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME));
gtk_box_pack_start(GTK_BOX(text_vbox), product_label, FALSE, FALSE, 0);
GtkWidget* version_label = gtk_label_new(WideToUTF8(current_version).c_str());
gtk_misc_set_alignment(GTK_MISC(version_label), 0.0, 0.5);
gtk_label_set_selectable(GTK_LABEL(version_label), TRUE);
gtk_box_pack_start(GTK_BOX(text_vbox), version_label, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(text_alignment), text_vbox);
gtk_box_pack_start(GTK_BOX(hbox), text_alignment, TRUE, TRUE, 0);
GtkWidget* image_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(image_vbox),
gtk_image_new_from_pixbuf(background),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), image_vbox, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(ebox), hbox);
gtk_box_pack_start(GTK_BOX(content_area), ebox, TRUE, TRUE, 0);
// We use a separate box for the licensing etc. text. See the comment near
// the top of this function about using a special layout for this dialog.
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(vbox),
gtk_util::kContentAreaBorder);
GtkWidget* copyright_label = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_COPYRIGHT));
gtk_box_pack_start(GTK_BOX(vbox), copyright_label, TRUE, TRUE, 5);
std::string license = l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_LICENSE);
bool chromium_url_appears_first =
license.find(kBeginLinkChr) < license.find(kBeginLinkOss);
size_t link1 = license.find(kBeginLink);
DCHECK(link1 != std::string::npos);
size_t link1_end = license.find(kEndLink, link1);
DCHECK(link1_end != std::string::npos);
size_t link2 = license.find(kBeginLink, link1_end);
DCHECK(link2 != std::string::npos);
size_t link2_end = license.find(kEndLink, link2);
DCHECK(link1_end != std::string::npos);
GtkWidget* license_chunk1 = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
license.substr(0, link1));
GtkWidget* license_chunk2 = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
license.substr(link1_end + strlen(kEndLinkOss),
link2 - link1_end - strlen(kEndLinkOss)));
GtkWidget* license_chunk3 = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
license.substr(link2_end + strlen(kEndLinkOss)));
std::string first_link_text =
std::string("<span size=\"smaller\">") +
license.substr(link1 + strlen(kBeginLinkOss),
link1_end - link1 - strlen(kBeginLinkOss)) +
std::string("</span>");
std::string second_link_text =
std::string("<span size=\"smaller\">") +
license.substr(link2 + strlen(kBeginLinkOss),
link2_end - link2 - strlen(kBeginLinkOss)) +
std::string("</span>");
GtkWidget* first_link =
gtk_chrome_link_button_new_with_markup(first_link_text.c_str());
GtkWidget* second_link =
gtk_chrome_link_button_new_with_markup(second_link_text.c_str());
if (!chromium_url_appears_first) {
GtkWidget* swap = second_link;
second_link = first_link;
first_link = swap;
}
g_signal_connect(chromium_url_appears_first ? first_link : second_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(GetChromiumUrl()));
g_signal_connect(chromium_url_appears_first ? second_link : first_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(kAcknowledgements));
GtkWidget* license_hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk1,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), first_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk2,
FALSE, FALSE, 0);
// Since there's no good way to dynamically wrap the license block, force
// a line break right before the second link (which matches en-US Windows
// chromium).
GtkWidget* license_hbox2 = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), second_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), license_chunk3,
FALSE, FALSE, 0);
GtkWidget* license_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox2, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), license_vbox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(content_area), vbox, TRUE, TRUE, 0);
g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), NULL);
gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
gtk_widget_show_all(dialog);
}
<commit_msg>Make chrome version legible in about:chrome dialog for dark themes.<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/gtk/about_chrome_dialog.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_version_info.h"
#include "base/gfx/gtk_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/gtk_util.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "webkit/glue/webkit_glue.h"
namespace {
// The URLs that you navigate to when clicking the links in the About dialog.
const char* const kAcknowledgements = "about:credits";
const char* const kTOS = "about:terms";
// Left or right margin.
const int kPanelHorizMargin = 13;
// Top or bottom margin.
const int kPanelVertMargin = 20;
// Extra spacing between product name and version number.
const int kExtraLineSpacing = 5;
// These are used as placeholder text around the links in the text in the about
// dialog.
const char* kBeginLinkChr = "BEGIN_LINK_CHR";
const char* kBeginLinkOss = "BEGIN_LINK_OSS";
// We don't actually use this one.
// const char* kEndLinkChr = "END_LINK_CHR";
const char* kEndLinkOss = "END_LINK_OSS";
const char* kBeginLink = "BEGIN_LINK";
const char* kEndLink = "END_LINK";
const char* kSmaller = "<span size=\"smaller\">%s</span>";
void OnDialogResponse(GtkDialog* dialog, int response_id) {
// We're done.
gtk_widget_destroy(GTK_WIDGET(dialog));
}
void FixLabelWrappingCallback(GtkWidget *label,
GtkAllocation *allocation,
gpointer data) {
gtk_widget_set_size_request(label, allocation->width, -1);
}
GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {
GtkWidget* label = gtk_label_new(NULL);
char* markup = g_markup_printf_escaped(format, str.c_str());
gtk_label_set_markup(GTK_LABEL(label), markup);
g_free(markup);
// Left align it.
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
return label;
}
void OnLinkButtonClick(GtkWidget* button, const char* url) {
BrowserList::GetLastActive()->
OpenURL(GURL(url), GURL(), NEW_WINDOW, PageTransition::LINK);
}
const char* GetChromiumUrl() {
static std::string url(l10n_util::GetStringUTF8(IDS_CHROMIUM_PROJECT_URL));
return url.c_str();
}
std::string Smaller(const std::string& text) {
return std::string("<span size=\"smaller\">") + text + std::string("</span>");
}
} // namespace
void ShowAboutDialogForProfile(GtkWindow* parent, Profile* profile) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
static GdkPixbuf* background = rb.GetPixbufNamed(IDR_ABOUT_BACKGROUND);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
std::wstring current_version = version_info->file_version();
#if !defined(GOOGLE_CHROME_BUILD)
current_version += L" (";
current_version += version_info->last_change();
current_version += L")";
#endif
// Build the dialog.
GtkWidget* dialog = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_ABOUT_CHROME_TITLE).c_str(),
parent,
GTK_DIALOG_MODAL,
GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
NULL);
// Pick up the style set in gtk_util.cc:InitRCStyles().
// The layout of this dialog is special because the logo should be flush
// with the edges of the window.
gtk_widget_set_name(dialog, "about-dialog");
gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);
GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
// Use an event box to get the background painting correctly
GtkWidget* ebox = gtk_event_box_new();
gtk_widget_modify_bg(ebox, GTK_STATE_NORMAL, &gfx::kGdkWhite);
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
GtkWidget* text_alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(text_alignment),
kPanelVertMargin, kPanelVertMargin,
kPanelHorizMargin, kPanelHorizMargin);
GtkWidget* text_vbox = gtk_vbox_new(FALSE, kExtraLineSpacing);
GdkColor black = gfx::kGdkBlack;
GtkWidget* product_label = MakeMarkupLabel(
"<span font_desc=\"18\" weight=\"bold\" style=\"normal\">%s</span>",
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME));
gtk_widget_modify_fg(product_label, GTK_STATE_NORMAL, &black);
gtk_box_pack_start(GTK_BOX(text_vbox), product_label, FALSE, FALSE, 0);
GtkWidget* version_label = gtk_label_new(WideToUTF8(current_version).c_str());
gtk_misc_set_alignment(GTK_MISC(version_label), 0.0, 0.5);
gtk_label_set_selectable(GTK_LABEL(version_label), TRUE);
gtk_widget_modify_fg(version_label, GTK_STATE_NORMAL, &black);
gtk_box_pack_start(GTK_BOX(text_vbox), version_label, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(text_alignment), text_vbox);
gtk_box_pack_start(GTK_BOX(hbox), text_alignment, TRUE, TRUE, 0);
GtkWidget* image_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(image_vbox),
gtk_image_new_from_pixbuf(background),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), image_vbox, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(ebox), hbox);
gtk_box_pack_start(GTK_BOX(content_area), ebox, TRUE, TRUE, 0);
// We use a separate box for the licensing etc. text. See the comment near
// the top of this function about using a special layout for this dialog.
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(vbox),
gtk_util::kContentAreaBorder);
GtkWidget* copyright_label = MakeMarkupLabel(
kSmaller, l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_COPYRIGHT));
gtk_box_pack_start(GTK_BOX(vbox), copyright_label, TRUE, TRUE, 5);
std::string license = l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_LICENSE);
bool chromium_url_appears_first =
license.find(kBeginLinkChr) < license.find(kBeginLinkOss);
size_t link1 = license.find(kBeginLink);
DCHECK(link1 != std::string::npos);
size_t link1_end = license.find(kEndLink, link1);
DCHECK(link1_end != std::string::npos);
size_t link2 = license.find(kBeginLink, link1_end);
DCHECK(link2 != std::string::npos);
size_t link2_end = license.find(kEndLink, link2);
DCHECK(link1_end != std::string::npos);
GtkWidget* license_chunk1 = MakeMarkupLabel(
kSmaller, license.substr(0, link1));
GtkWidget* license_chunk2 = MakeMarkupLabel(
kSmaller,
license.substr(link1_end + strlen(kEndLinkOss),
link2 - link1_end - strlen(kEndLinkOss)));
GtkWidget* license_chunk3 = MakeMarkupLabel(
kSmaller, license.substr(link2_end + strlen(kEndLinkOss)));
std::string first_link_text = Smaller(
license.substr(link1 + strlen(kBeginLinkOss),
link1_end - link1 - strlen(kBeginLinkOss)));
std::string second_link_text = Smaller(
license.substr(link2 + strlen(kBeginLinkOss),
link2_end - link2 - strlen(kBeginLinkOss)));
GtkWidget* first_link =
gtk_chrome_link_button_new_with_markup(first_link_text.c_str());
GtkWidget* second_link =
gtk_chrome_link_button_new_with_markup(second_link_text.c_str());
if (!chromium_url_appears_first) {
GtkWidget* swap = second_link;
second_link = first_link;
first_link = swap;
}
g_signal_connect(chromium_url_appears_first ? first_link : second_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(GetChromiumUrl()));
g_signal_connect(chromium_url_appears_first ? second_link : first_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(kAcknowledgements));
GtkWidget* license_hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk1,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), first_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk2,
FALSE, FALSE, 0);
// Since there's no good way to dynamically wrap the license block, force
// a line break right before the second link (which matches en-US Windows
// chromium).
GtkWidget* license_hbox2 = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), second_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), license_chunk3,
FALSE, FALSE, 0);
GtkWidget* license_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox2, FALSE, FALSE, 0);
#if defined(GOOGLE_CHROME_BUILD)
std::vector<size_t> url_offsets;
std::wstring text = l10n_util::GetStringF(IDS_ABOUT_TERMS_OF_SERVICE,
std::wstring(),
std::wstring(),
&url_offsets);
std::string tos_link_text = Smaller(
l10n_util::GetStringUTF8(IDS_TERMS_OF_SERVICE));
GtkWidget* tos_chunk1 = MakeMarkupLabel(
kSmaller, WideToUTF8(text.substr(0, url_offsets[0])).c_str());
GtkWidget* tos_link =
gtk_chrome_link_button_new_with_markup(tos_link_text.c_str());
GtkWidget* tos_chunk2 = MakeMarkupLabel(
kSmaller, WideToUTF8(text.substr(url_offsets[0])).c_str());
GtkWidget* tos_hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(tos_hbox), tos_chunk1, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tos_hbox), tos_link, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tos_hbox), tos_chunk2, FALSE, FALSE, 0);
g_signal_connect(tos_link, "clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(kTOS));
#endif
gtk_box_pack_start(GTK_BOX(vbox), license_vbox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), tos_hbox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(content_area), vbox, TRUE, TRUE, 0);
g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), NULL);
gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
gtk_widget_show_all(dialog);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_LINUX) || defined(HOST_OS_MACOS) || \
defined(HOST_OS_ANDROID) || defined(HOST_OS_FUCHSIA)
#include "bin/console.h"
#include <errno.h>
#include <sys/ioctl.h>
#include <termios.h>
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
namespace dart {
namespace bin {
class PosixConsole {
public:
static const tcflag_t kInvalidFlag = -1;
static void Initialize() {
SaveMode(STDOUT_FILENO, &stdout_initial_c_lflag_);
SaveMode(STDERR_FILENO, &stderr_initial_c_lflag_);
SaveMode(STDIN_FILENO, &stdin_initial_c_lflag_);
}
static void Cleanup() {
RestoreMode(STDOUT_FILENO, stdout_initial_c_lflag_);
RestoreMode(STDERR_FILENO, stderr_initial_c_lflag_);
RestoreMode(STDIN_FILENO, stdin_initial_c_lflag_);
ClearLFlags();
}
private:
static tcflag_t stdout_initial_c_lflag_;
static tcflag_t stderr_initial_c_lflag_;
static tcflag_t stdin_initial_c_lflag_;
static void ClearLFlags() {
stdout_initial_c_lflag_ = kInvalidFlag;
stderr_initial_c_lflag_ = kInvalidFlag;
stdin_initial_c_lflag_ = kInvalidFlag;
}
static void SaveMode(intptr_t fd, tcflag_t* flag) {
ASSERT(flag != NULL);
struct termios term;
int status = NO_RETRY_EXPECTED(tcgetattr(fd, &term));
if (status != 0) {
return;
}
*flag = term.c_lflag;
}
static void RestoreMode(intptr_t fd, tcflag_t flag) {
if (flag == kInvalidFlag) {
return;
}
struct termios term;
int status = NO_RETRY_EXPECTED(tcgetattr(fd, &term));
if (status != 0) {
return;
}
term.c_lflag = flag;
NO_RETRY_EXPECTED(tcsetattr(fd, TCSANOW, &term));
}
DISALLOW_ALLOCATION();
DISALLOW_IMPLICIT_CONSTRUCTORS(PosixConsole);
};
tcflag_t PosixConsole::stdout_initial_c_lflag_ = PosixConsole::kInvalidFlag;
tcflag_t PosixConsole::stderr_initial_c_lflag_ = PosixConsole::kInvalidFlag;
tcflag_t PosixConsole::stdin_initial_c_lflag_ = PosixConsole::kInvalidFlag;
void Console::SaveConfig() {
PosixConsole::Initialize();
}
void Console::RestoreConfig() {
PosixConsole::Cleanup();
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_LINUX) || defined(HOST_OS_MACOS) || \
// defined(HOST_OS_ANDROID) || defined(HOST_OS_FUCHSIA)
<commit_msg>[ VM / Flutter ] Replaced NO_RETRY_EXPECTED with VOID_TEMP_FAILURE_RETRY in console_posix.cc:69.<commit_after>// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_LINUX) || defined(HOST_OS_MACOS) || \
defined(HOST_OS_ANDROID) || defined(HOST_OS_FUCHSIA)
#include "bin/console.h"
#include <errno.h>
#include <sys/ioctl.h>
#include <termios.h>
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
namespace dart {
namespace bin {
class PosixConsole {
public:
static const tcflag_t kInvalidFlag = -1;
static void Initialize() {
SaveMode(STDOUT_FILENO, &stdout_initial_c_lflag_);
SaveMode(STDERR_FILENO, &stderr_initial_c_lflag_);
SaveMode(STDIN_FILENO, &stdin_initial_c_lflag_);
}
static void Cleanup() {
RestoreMode(STDOUT_FILENO, stdout_initial_c_lflag_);
RestoreMode(STDERR_FILENO, stderr_initial_c_lflag_);
RestoreMode(STDIN_FILENO, stdin_initial_c_lflag_);
ClearLFlags();
}
private:
static tcflag_t stdout_initial_c_lflag_;
static tcflag_t stderr_initial_c_lflag_;
static tcflag_t stdin_initial_c_lflag_;
static void ClearLFlags() {
stdout_initial_c_lflag_ = kInvalidFlag;
stderr_initial_c_lflag_ = kInvalidFlag;
stdin_initial_c_lflag_ = kInvalidFlag;
}
static void SaveMode(intptr_t fd, tcflag_t* flag) {
ASSERT(flag != NULL);
struct termios term;
int status = TEMP_FAILURE_RETRY(tcgetattr(fd, &term));
if (status != 0) {
return;
}
*flag = term.c_lflag;
}
static void RestoreMode(intptr_t fd, tcflag_t flag) {
if (flag == kInvalidFlag) {
return;
}
struct termios term;
int status = TEMP_FAILURE_RETRY(tcgetattr(fd, &term));
if (status != 0) {
return;
}
term.c_lflag = flag;
VOID_TEMP_FAILURE_RETRY(tcsetattr(fd, TCSANOW, &term));
}
DISALLOW_ALLOCATION();
DISALLOW_IMPLICIT_CONSTRUCTORS(PosixConsole);
};
tcflag_t PosixConsole::stdout_initial_c_lflag_ = PosixConsole::kInvalidFlag;
tcflag_t PosixConsole::stderr_initial_c_lflag_ = PosixConsole::kInvalidFlag;
tcflag_t PosixConsole::stdin_initial_c_lflag_ = PosixConsole::kInvalidFlag;
void Console::SaveConfig() {
PosixConsole::Initialize();
}
void Console::RestoreConfig() {
PosixConsole::Cleanup();
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_LINUX) || defined(HOST_OS_MACOS) || \
// defined(HOST_OS_ANDROID) || defined(HOST_OS_FUCHSIA)
<|endoftext|> |
<commit_before>#include <sirius.h>
using namespace sirius;
void test_unit_cell()
{
Simulation_context ctx("sirius.json", mpi_comm_world());
ctx.unit_cell().initialize();
vector3d<int> k_grid(2, 2, 1);
vector3d<int> k_shift(1, 1, 0);
mdarray<double, 2> kp;
std::vector<double> wk;
int nk = ctx.unit_cell().symmetry()->get_irreducible_reciprocal_mesh(k_grid, k_shift, kp, wk);
printf("number of k-points: %i\n", nk);
for (int ik = 0; ik < nk; ik++)
{
printf("kp: %f %f %f\n", kp(0, ik), kp(1, ik), kp(2, ik));
}
}
int main(int argn, char** argv)
{
cmd_args args;
args.parse_args(argn, argv);
if (args.exist("help"))
{
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
sirius::initialize(1);
test_unit_cell();
sirius::finalize();
}
<commit_msg>update test<commit_after>#include <sirius.h>
using namespace sirius;
void test1()
{
Simulation_context ctx(mpi_comm_world(), "pseudopotential");
ctx.set_processing_unit("cpu");
int N = 7;
double a{4};
ctx.unit_cell().set_lattice_vectors({{N*a,0,0}, {0,N*a,0}, {0,0,N*a}});
ctx.unit_cell().add_atom_type("A");
auto& atype = ctx.unit_cell().atom_type(0);
ctx.unit_cell().atom_type(0).zn(1);
ctx.unit_cell().atom_type(0).set_radial_grid(radial_grid_t::lin_exp_grid, 1000, 0, 2);
std::vector<double> beta(ctx.unit_cell().atom_type(0).num_mt_points());
for (int i = 0; i < atype.num_mt_points(); i++) {
double x = atype.radial_grid(i);
beta[i] = std::exp(-x) * (4 - x * x);
}
ctx.unit_cell().atom_type(0).add_beta_radial_function(0, beta);
ctx.unit_cell().atom_type(0).add_beta_radial_function(1, beta);
ctx.unit_cell().atom_type(0).add_beta_radial_function(2, beta);
for (int i1 = 0; i1 < N; i1++) {
for (int i2 = 0; i2 < N; i2++) {
for (int i3 = 0; i3 < N; i3++) {
ctx.unit_cell().add_atom("A", {1.0 * i1 / N, 1.0 * i2 / N, 1.0 * i3 / N});
}
}
}
ctx.initialize();
ctx.print_info();
double vk[] = {0, 0, 0};
K_point kp(ctx, vk, 1.0);
kp.initialize();
printf("num_gkvec: %i\n", kp.num_gkvec());
auto& bp_chunks = ctx.beta_projector_chunks();
for (int k = 0; k < 10; k++) {
kp.beta_projectors().prepare();
for (int ichunk = 0; ichunk < bp_chunks.num_chunks(); ichunk++) {
kp.beta_projectors().generate(ichunk);
}
kp.beta_projectors().dismiss();
}
}
int main(int argn, char** argv)
{
cmd_args args;
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
sirius::initialize();
test1();
if (mpi_comm_world().rank() == 0) {
sddk::timer::print();
}
sirius::finalize();
}
<|endoftext|> |
<commit_before>/*****************************************************************************/
/**
* @file ScreenBase.cpp
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#include "ScreenBase.h"
#include "Application.h"
#include "KVSMouseButton.h"
#include "KVSKey.h"
#include <kvs/Message>
#include <kvs/TimerEventListener>
namespace
{
/*===========================================================================*/
/**
* @brief Returns pointer to the screen.
* @param handler [in] the window handler
* @return pointer to the screen
*/
/*===========================================================================*/
kvs::glfw::ScreenBase* ThisScreen( GLFWwindow* handler )
{
return static_cast<kvs::glfw::ScreenBase*>( glfwGetWindowUserPointer( handler ) );
}
}
namespace kvs
{
namespace glfw
{
/*===========================================================================*/
/**
* @brief Returns the pointer to the glfw screen base downcasted from the screen base.
* @param screen [in] the screen base.
* @return pointer to the glfw screen base
*/
/*===========================================================================*/
ScreenBase* ScreenBase::DownCast( kvs::ScreenBase* screen )
{
return dynamic_cast<ScreenBase*>( screen );
}
/*===========================================================================*/
/**
* @brief Returns the const pointer to the glfw screen base downcasted from the screen base.
* @param screen [in] the screen base.
* @return const pointer to the glfw screen base
*/
/*===========================================================================*/
const ScreenBase* ScreenBase::DownCast( const kvs::ScreenBase* screen )
{
return dynamic_cast<ScreenBase*>( const_cast<kvs::ScreenBase*>( screen ) );
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when the window is resized.
* @param handler [in] the window handler
* @param width [in] the window width
* @param height [in] the window height
*/
/*===========================================================================*/
void WindowSizeCallback( GLFWwindow* handler, int width, int height )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
const auto vp = kvs::OpenGL::Viewport();
this_screen->resizeEvent( width, height );
if ( this_screen->width() != ( vp[2] - vp[0] ) ) // device_pixel_ratio != 1.0
{
kvs::OpenGL::SetViewport( vp );
}
this_screen->releaseContext();
this_screen->redraw();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when a mouse button is pressed or released.
* @param handler [in] the window handler
* @param button [in] the mouse button
* @param action [in] the action (GLFW_PRESS or GLFW_RELEASE)
* @param mods [in] the modifier keys
*/
/*===========================================================================*/
void MouseButtonCallback( GLFWwindow* handler, int button, int action, int mods )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
double x = 0.0;
double y = 0.0;
glfwGetCursorPos( handler, &x, &y );
this_screen->m_mouse_event->setPosition( int( x ), int( y ) );
this_screen->m_mouse_event->setButton( kvs::glfw::KVSMouseButton::Button( button ) );
this_screen->m_mouse_event->setState( kvs::glfw::KVSMouseButton::State( action ) );
this_screen->m_mouse_event->setModifiers( kvs::glfw::KVSKey::Modifier( mods ) );
switch ( action )
{
case GLFW_PRESS:
{
this_screen->m_elapse_time_counter.stop();
if ( this_screen->m_elapse_time_counter.sec() < 0.2f )
{
this_screen->m_mouse_event->setAction( kvs::MouseButton::DoubleClicked );
this_screen->mouseDoubleClickEvent( this_screen->m_mouse_event );
}
else
{
this_screen->m_mouse_event->setAction( kvs::MouseButton::Pressed );
this_screen->mousePressEvent( this_screen->m_mouse_event );
}
this_screen->m_elapse_time_counter.start();
break;
}
case GLFW_RELEASE:
{
this_screen->m_mouse_event->setAction( kvs::MouseButton::Released );
this_screen->mouseReleaseEvent( this_screen->m_mouse_event );
break;
}
default: break;
}
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when the cursor is moved.
* @param handler [in] the window handler
* @param x [in] the x-coordinate of the cursor
* @param y [in] the y-coordinate of the cursor
*/
/*===========================================================================*/
void CursorPosCallback( GLFWwindow* handler, double x, double y )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
if ( this_screen->m_mouse_event->state() == kvs::MouseButton::Down )
{
this_screen->m_mouse_event->setPosition( x, y );
this_screen->m_mouse_event->setAction( kvs::MouseButton::Moved );
this_screen->mouseMoveEvent( this_screen->m_mouse_event );
}
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when the scrolling device is used.
* @param handler [in] the window handler
* @param x [in] the scroll offset along the x-axis
* @param y [in] the scroll offset along the y-axis
*/
/*===========================================================================*/
void ScrollCallback( GLFWwindow* handler, double x, double y )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
this_screen->m_wheel_event->setPosition( x, y );
this_screen->m_wheel_event->setDirection( y > 0.0 ? 1 : -1 );
this_screen->wheelEvent( this_screen->m_wheel_event );
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when a key is pressed, repeated or released.
* @param handler [in] the window handler
* @param key [in] the key that was pressed or released
* @param scancode [in] the system-specific scancode of the key
* @param action [in] the action (GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT)
* @param mods [in] the modifier keys
*/
/*===========================================================================*/
void KeyCallback( GLFWwindow* handler, int key, int scancode, int action, int mods )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
double x = 0.0;
double y = 0.0;
glfwGetCursorPos( handler, &x, &y );
this_screen->m_key_event->setPosition( int( x ), int( y ) );
this_screen->m_key_event->setModifiers( kvs::glfw::KVSKey::Modifier( mods ) );
this_screen->m_key_event->setKey( kvs::glfw::KVSKey::Code( key, mods ) );
switch ( action )
{
case GLFW_PRESS:
this_screen->keyPressEvent( this_screen->m_key_event );
break;
default:
break;
}
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Constructs a ScreenBase class.
* @param application [in] the application
*/
/*===========================================================================*/
ScreenBase::ScreenBase( kvs::glfw::Application* application ):
m_handler( 0 ),
m_id( -1 ),
m_mouse_event( 0 ),
m_key_event( 0 ),
m_wheel_event( 0 ),
m_is_fullscreen( false )
{
if ( application ) application->attach( this );
m_mouse_event = new kvs::MouseEvent();
m_key_event = new kvs::KeyEvent();
m_wheel_event = new kvs::WheelEvent();
m_elapse_time_counter.start();
}
/*===========================================================================*/
/**
* @brief Destroys the ScreenBase class.
*/
/*===========================================================================*/
ScreenBase::~ScreenBase()
{
if ( m_mouse_event ) { delete m_mouse_event; }
if ( m_key_event ) { delete m_key_event; }
if ( m_wheel_event ) { delete m_wheel_event; }
if ( m_handler ) { glfwDestroyWindow( m_handler ); }
}
/*===========================================================================*/
/**
* @brief Creates a screen.
*/
/*===========================================================================*/
void ScreenBase::create()
{
KVS_ASSERT( m_id == -1 );
// Create window.
m_handler = glfwCreateWindow(
BaseClass::width(),
BaseClass::height(),
BaseClass::title().c_str(),
NULL, NULL );
if ( !m_handler )
{
kvsMessageError() << "Cannot create GLFW screen." << std::endl;
return;
}
glfwMakeContextCurrent( m_handler );
glfwSwapInterval(1);
// Set callback functions.
glfwSetWindowUserPointer( m_handler, this );
glfwSetWindowSizeCallback( m_handler, WindowSizeCallback );
glfwSetMouseButtonCallback( m_handler, MouseButtonCallback );
glfwSetCursorPosCallback( m_handler, CursorPosCallback );
glfwSetScrollCallback( m_handler, ScrollCallback );
glfwSetKeyCallback( m_handler, KeyCallback );
// Initialize GLEW. (Before glfwMakeContextCurrent)
#if defined( KVS_ENABLE_GLEW )
GLenum result = glewInit();
if ( result != GLEW_OK )
{
const std::string error( glewGetErrorString( result ) );
kvsMessageError() << "GLEW initialization failed: " << error << "." << std::endl;
}
#endif
// Create paint device.
BaseClass::paintDevice()->create();
// Generate window ID.
static int counter = 0;
m_id = counter++;
glfwMakeContextCurrent( NULL );
}
/*===========================================================================*/
/**
* @brief Shows the screen.
*/
/*===========================================================================*/
void ScreenBase::show()
{
#if 1 // KVS_ENABLE_DEPRECATED
if ( m_id == -1 ) { this->create(); }
#endif
glfwShowWindow( m_handler );
}
/*===========================================================================*/
/**
* @brief Hides the screen.
*/
/*===========================================================================*/
void ScreenBase::hide()
{
glfwHideWindow( m_handler );
}
/*===========================================================================*/
/**
* @brief Shows the screen as fullscreen size.
*/
/*===========================================================================*/
void ScreenBase::showFullScreen()
{
if ( m_is_fullscreen ) return;
m_is_fullscreen = true;
int x = 0, y = 0;
glfwGetWindowPos( m_handler, &x, &y );
BaseClass::setPosition( x, y );
auto* monitor = glfwGetPrimaryMonitor();
const auto* mode = glfwGetVideoMode( monitor );
glfwSetWindowMonitor( m_handler, monitor, 0, 0, mode->width, mode->height, 0 );
}
/*===========================================================================*/
/**
* @brief Shows the screen as normal size.
*/
/*===========================================================================*/
void ScreenBase::showNormal()
{
if ( !m_is_fullscreen ) return;
m_is_fullscreen = false;
const int x = BaseClass::x();
const int y = BaseClass::y();
const int w = BaseClass::width();
const int h = BaseClass::height();
glfwSetWindowMonitor( m_handler, nullptr, x, y, w, h, 0 );
}
/*===========================================================================*/
/**
* @brief Pop up the screen.
*/
/*===========================================================================*/
void ScreenBase::popUp()
{
glfwFocusWindow( m_handler );
}
/*===========================================================================*/
/**
* @brief Push down the screen. (not yet implemented)
*/
/*===========================================================================*/
void ScreenBase::pushDown()
{
// To-Do
}
/*===========================================================================*/
/**
* @brief Redraw the screen.
*/
/*===========================================================================*/
void ScreenBase::redraw()
{
this->aquireContext();
this->paintEvent();
this->releaseContext();
}
/*===========================================================================*/
/**
* @brief Resize the screen.
* @param width [in] the window width
* @param height [in] the window height
*/
/*===========================================================================*/
void ScreenBase::resize( int width, int height )
{
glfwSetWindowSize( m_handler, width, height );
}
/*===========================================================================*/
/**
* @brief Returns true if the screen is shown as fullscreen size.
* @return true if the screen is fullscreen.
*/
/*===========================================================================*/
bool ScreenBase::isFullScreen() const
{
return m_is_fullscreen;
}
void ScreenBase::enable() {}
void ScreenBase::disable() {}
void ScreenBase::reset() {}
void ScreenBase::initializeEvent(){}
void ScreenBase::paintEvent(){}
void ScreenBase::resizeEvent( int, int ){}
void ScreenBase::mousePressEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseMoveEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseReleaseEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseDoubleClickEvent( kvs::MouseEvent* ){}
void ScreenBase::wheelEvent( kvs::WheelEvent* ){}
void ScreenBase::keyPressEvent( kvs::KeyEvent* ){}
std::list<kvs::glfw::Timer*>& ScreenBase::timerEventHandler()
{
return m_timer_event_handler;
}
void ScreenBase::addTimerEvent( kvs::TimerEventListener* event, kvs::glfw::Timer* timer )
{
event->setScreen( this );
timer->setEventListener( event );
m_timer_event_handler.push_back( timer );
}
} // end of namespace glfw
} // end of namespace kvs
<commit_msg>Update ScreenBase.cpp<commit_after>/*****************************************************************************/
/**
* @file ScreenBase.cpp
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#include "ScreenBase.h"
#include "Application.h"
#include "KVSMouseButton.h"
#include "KVSKey.h"
#include <kvs/Message>
#include <kvs/TimerEventListener>
namespace
{
/*===========================================================================*/
/**
* @brief Returns pointer to the screen.
* @param handler [in] the window handler
* @return pointer to the screen
*/
/*===========================================================================*/
kvs::glfw::ScreenBase* ThisScreen( GLFWwindow* handler )
{
return static_cast<kvs::glfw::ScreenBase*>( glfwGetWindowUserPointer( handler ) );
}
}
namespace kvs
{
namespace glfw
{
/*===========================================================================*/
/**
* @brief Returns the pointer to the glfw screen base downcasted from the screen base.
* @param screen [in] the screen base.
* @return pointer to the glfw screen base
*/
/*===========================================================================*/
ScreenBase* ScreenBase::DownCast( kvs::ScreenBase* screen )
{
return dynamic_cast<ScreenBase*>( screen );
}
/*===========================================================================*/
/**
* @brief Returns the const pointer to the glfw screen base downcasted from the screen base.
* @param screen [in] the screen base.
* @return const pointer to the glfw screen base
*/
/*===========================================================================*/
const ScreenBase* ScreenBase::DownCast( const kvs::ScreenBase* screen )
{
return dynamic_cast<ScreenBase*>( const_cast<kvs::ScreenBase*>( screen ) );
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when the window is resized.
* @param handler [in] the window handler
* @param width [in] the window width
* @param height [in] the window height
*/
/*===========================================================================*/
void WindowSizeCallback( GLFWwindow* handler, int width, int height )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
this_screen->resizeEvent( width, height );
this_screen->releaseContext();
this_screen->redraw();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when a mouse button is pressed or released.
* @param handler [in] the window handler
* @param button [in] the mouse button
* @param action [in] the action (GLFW_PRESS or GLFW_RELEASE)
* @param mods [in] the modifier keys
*/
/*===========================================================================*/
void MouseButtonCallback( GLFWwindow* handler, int button, int action, int mods )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
double x = 0.0;
double y = 0.0;
glfwGetCursorPos( handler, &x, &y );
this_screen->m_mouse_event->setPosition( int( x ), int( y ) );
this_screen->m_mouse_event->setButton( kvs::glfw::KVSMouseButton::Button( button ) );
this_screen->m_mouse_event->setState( kvs::glfw::KVSMouseButton::State( action ) );
this_screen->m_mouse_event->setModifiers( kvs::glfw::KVSKey::Modifier( mods ) );
switch ( action )
{
case GLFW_PRESS:
{
this_screen->m_elapse_time_counter.stop();
if ( this_screen->m_elapse_time_counter.sec() < 0.2f )
{
this_screen->m_mouse_event->setAction( kvs::MouseButton::DoubleClicked );
this_screen->mouseDoubleClickEvent( this_screen->m_mouse_event );
}
else
{
this_screen->m_mouse_event->setAction( kvs::MouseButton::Pressed );
this_screen->mousePressEvent( this_screen->m_mouse_event );
}
this_screen->m_elapse_time_counter.start();
break;
}
case GLFW_RELEASE:
{
this_screen->m_mouse_event->setAction( kvs::MouseButton::Released );
this_screen->mouseReleaseEvent( this_screen->m_mouse_event );
break;
}
default: break;
}
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when the cursor is moved.
* @param handler [in] the window handler
* @param x [in] the x-coordinate of the cursor
* @param y [in] the y-coordinate of the cursor
*/
/*===========================================================================*/
void CursorPosCallback( GLFWwindow* handler, double x, double y )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
if ( this_screen->m_mouse_event->state() == kvs::MouseButton::Down )
{
this_screen->m_mouse_event->setPosition( x, y );
this_screen->m_mouse_event->setAction( kvs::MouseButton::Moved );
this_screen->mouseMoveEvent( this_screen->m_mouse_event );
}
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when the scrolling device is used.
* @param handler [in] the window handler
* @param x [in] the scroll offset along the x-axis
* @param y [in] the scroll offset along the y-axis
*/
/*===========================================================================*/
void ScrollCallback( GLFWwindow* handler, double x, double y )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
this_screen->m_wheel_event->setPosition( x, y );
this_screen->m_wheel_event->setDirection( y > 0.0 ? 1 : -1 );
this_screen->wheelEvent( this_screen->m_wheel_event );
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Callback function, which is called when a key is pressed, repeated or released.
* @param handler [in] the window handler
* @param key [in] the key that was pressed or released
* @param scancode [in] the system-specific scancode of the key
* @param action [in] the action (GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT)
* @param mods [in] the modifier keys
*/
/*===========================================================================*/
void KeyCallback( GLFWwindow* handler, int key, int scancode, int action, int mods )
{
auto* this_screen = ::ThisScreen( handler );
this_screen->aquireContext();
double x = 0.0;
double y = 0.0;
glfwGetCursorPos( handler, &x, &y );
this_screen->m_key_event->setPosition( int( x ), int( y ) );
this_screen->m_key_event->setModifiers( kvs::glfw::KVSKey::Modifier( mods ) );
this_screen->m_key_event->setKey( kvs::glfw::KVSKey::Code( key, mods ) );
switch ( action )
{
case GLFW_PRESS:
this_screen->keyPressEvent( this_screen->m_key_event );
break;
default:
break;
}
this_screen->releaseContext();
}
/*===========================================================================*/
/**
* @brief Constructs a ScreenBase class.
* @param application [in] the application
*/
/*===========================================================================*/
ScreenBase::ScreenBase( kvs::glfw::Application* application ):
m_handler( 0 ),
m_id( -1 ),
m_mouse_event( 0 ),
m_key_event( 0 ),
m_wheel_event( 0 ),
m_is_fullscreen( false )
{
if ( application ) application->attach( this );
m_mouse_event = new kvs::MouseEvent();
m_key_event = new kvs::KeyEvent();
m_wheel_event = new kvs::WheelEvent();
m_elapse_time_counter.start();
}
/*===========================================================================*/
/**
* @brief Destroys the ScreenBase class.
*/
/*===========================================================================*/
ScreenBase::~ScreenBase()
{
if ( m_mouse_event ) { delete m_mouse_event; }
if ( m_key_event ) { delete m_key_event; }
if ( m_wheel_event ) { delete m_wheel_event; }
if ( m_handler ) { glfwDestroyWindow( m_handler ); }
}
/*===========================================================================*/
/**
* @brief Creates a screen.
*/
/*===========================================================================*/
void ScreenBase::create()
{
KVS_ASSERT( m_id == -1 );
// Create window.
m_handler = glfwCreateWindow(
BaseClass::width(),
BaseClass::height(),
BaseClass::title().c_str(),
NULL, NULL );
if ( !m_handler )
{
kvsMessageError() << "Cannot create GLFW screen." << std::endl;
return;
}
glfwMakeContextCurrent( m_handler );
glfwSwapInterval(1);
// Set callback functions.
glfwSetWindowUserPointer( m_handler, this );
glfwSetWindowSizeCallback( m_handler, WindowSizeCallback );
glfwSetMouseButtonCallback( m_handler, MouseButtonCallback );
glfwSetCursorPosCallback( m_handler, CursorPosCallback );
glfwSetScrollCallback( m_handler, ScrollCallback );
glfwSetKeyCallback( m_handler, KeyCallback );
// Initialize GLEW. (Before glfwMakeContextCurrent)
#if defined( KVS_ENABLE_GLEW )
GLenum result = glewInit();
if ( result != GLEW_OK )
{
const std::string error( glewGetErrorString( result ) );
kvsMessageError() << "GLEW initialization failed: " << error << "." << std::endl;
}
#endif
// Create paint device.
BaseClass::paintDevice()->create();
// Set device pixel ratio.
const kvs::Vec4 vp = kvs::OpenGL::Viewport();
BaseClass::setDevicePixelRatio( vp[2] / BaseClass::width() );
// Generate window ID.
static int counter = 0;
m_id = counter++;
glfwMakeContextCurrent( NULL );
}
/*===========================================================================*/
/**
* @brief Shows the screen.
*/
/*===========================================================================*/
void ScreenBase::show()
{
#if 1 // KVS_ENABLE_DEPRECATED
if ( m_id == -1 ) { this->create(); }
#endif
glfwShowWindow( m_handler );
}
/*===========================================================================*/
/**
* @brief Hides the screen.
*/
/*===========================================================================*/
void ScreenBase::hide()
{
glfwHideWindow( m_handler );
}
/*===========================================================================*/
/**
* @brief Shows the screen as fullscreen size.
*/
/*===========================================================================*/
void ScreenBase::showFullScreen()
{
if ( m_is_fullscreen ) return;
m_is_fullscreen = true;
int x = 0, y = 0;
glfwGetWindowPos( m_handler, &x, &y );
BaseClass::setPosition( x, y );
auto* monitor = glfwGetPrimaryMonitor();
const auto* mode = glfwGetVideoMode( monitor );
glfwSetWindowMonitor( m_handler, monitor, 0, 0, mode->width, mode->height, 0 );
}
/*===========================================================================*/
/**
* @brief Shows the screen as normal size.
*/
/*===========================================================================*/
void ScreenBase::showNormal()
{
if ( !m_is_fullscreen ) return;
m_is_fullscreen = false;
const int x = BaseClass::x();
const int y = BaseClass::y();
const int w = BaseClass::width();
const int h = BaseClass::height();
glfwSetWindowMonitor( m_handler, nullptr, x, y, w, h, 0 );
}
/*===========================================================================*/
/**
* @brief Pop up the screen.
*/
/*===========================================================================*/
void ScreenBase::popUp()
{
glfwFocusWindow( m_handler );
}
/*===========================================================================*/
/**
* @brief Push down the screen. (not yet implemented)
*/
/*===========================================================================*/
void ScreenBase::pushDown()
{
// To-Do
}
/*===========================================================================*/
/**
* @brief Redraw the screen.
*/
/*===========================================================================*/
void ScreenBase::redraw()
{
this->aquireContext();
this->paintEvent();
this->releaseContext();
}
/*===========================================================================*/
/**
* @brief Resize the screen.
* @param width [in] the window width
* @param height [in] the window height
*/
/*===========================================================================*/
void ScreenBase::resize( int width, int height )
{
glfwSetWindowSize( m_handler, width, height );
}
/*===========================================================================*/
/**
* @brief Returns true if the screen is shown as fullscreen size.
* @return true if the screen is fullscreen.
*/
/*===========================================================================*/
bool ScreenBase::isFullScreen() const
{
return m_is_fullscreen;
}
void ScreenBase::enable() {}
void ScreenBase::disable() {}
void ScreenBase::reset() {}
void ScreenBase::initializeEvent(){}
void ScreenBase::paintEvent(){}
void ScreenBase::resizeEvent( int, int ){}
void ScreenBase::mousePressEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseMoveEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseReleaseEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseDoubleClickEvent( kvs::MouseEvent* ){}
void ScreenBase::wheelEvent( kvs::WheelEvent* ){}
void ScreenBase::keyPressEvent( kvs::KeyEvent* ){}
std::list<kvs::glfw::Timer*>& ScreenBase::timerEventHandler()
{
return m_timer_event_handler;
}
void ScreenBase::addTimerEvent( kvs::TimerEventListener* event, kvs::glfw::Timer* timer )
{
event->setScreen( this );
timer->setEventListener( event );
m_timer_event_handler.push_back( timer );
}
} // end of namespace glfw
} // end of namespace kvs
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
//
// This problem is driving me NUTS!
// I'm trying to solve this in O(n), and currently passing 9/17, the rest are WA.
//
// Here is the main issue with the problem:
//
// Initially the problem seems to be analogous to the merge step of merge sort,
// sadly that is not the case. This is because the case where the two strings have
// equal chars, we need to look ahead (possibly quite a bit) before picking the right one
//
// e.g. (AAABBBBBC) and (AAABBBBBD) in this case, we need to look ahead until we notice a difference (c vs d)
// Unfortunately this makes the algorithm O(n^2)
//
// My Solution in O(n):
// Assume s1p points to current location in str1, and s2p for str2.
//
// This solution exploits what I call *speculative execution in software*.
// e.g. in the above case, we will speculatively pick str1, and go ahead with the merging.
// (we will also note down some bookkeeping information, e.g. the positions where we first started
// our speculation as s1eqint and s2eqind. these are the indices of the first A in both strings)
//
// When we finally reach C vs D, we can check whether our speculation was correct. If so, we keep going
// as if nothing happened. If it was wrong, we can *switch* pointers to make s1p = s1eqind, and s2p = s2eqind + deltaTraveled
// This allows the whole algorithm to now finish in O(n)
//
// Of course, this was easier said than done. In particular, I found the details of the speculation very tricky to implement.
// I have provided comments in the code below, to show the various cases, e.g.
// |
// ->CABCCCC
// ->CABAAAA
// | *
// Here The starting Cs of both are s1eqind and s2eqind (pointed by ->)
// s2p remained at starting C, while s1p went ahead executing speculatively (denoted by |)
// In the above example, we noticed later on, that our speculation was wrong, so we will
// switch s1p to point to starting C, and s2p to point to the A (marked by *)
// Hope that makes sense.
//
// Unfortunately there is some bug somewhere, which causes 1 test pair from each of the tests from 10 onwards to fail.
// If you can get through the convoluted code below, and spot and fix the bug, PLEASE shoot me an email! :-)
//
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
using std::string;
using std::vector;
//s1p is the same as s2p
// how does s1p compare against s2future?
void processStateEqual(string& ret, const string& str1, const string& str2, int& s1p, int& s2p, int& s1eqind, int& s2eqind, bool& stateequal) {
int delta = s1p - s1eqind;
int s2future = s2p + delta;
if (s2future < str2.length()) {
if (str1[s1p] > str2[s2future]) { //made a bad decision earlier
// |
// CABCCCC
// CABAAAA
// |
s2p = s2future;
s1p = s1eqind;
stateequal = false;
} else if (str1[s1p] < str2[s2future]) { //previous call was correct
// |
// CABCCCC
// CABDDDD
// |
stateequal = false;
} else { //same
// |
// CABCCCC
// CABCCCC
// |
ret.push_back(str1[s1p++]); //choose str1 speculatively
}
} else {
// |
// CABCCCC
// CAB
// |
stateequal = false;
}
}
// s1p is lesser than s2p
// how does s1p compare to s2future?
void processStateLesser(string& ret, const string& str1, const string& str2, int& s1p, int& s2p, int& s1eqind, int& s2eqind, bool& stateequal) {
int delta = s1p - s1eqind;
int s2future = s2p + delta;
if (s2future < str2.length()) {
if (str1[s1p] > str2[s2future]) { //made a bad decision earlier
// |
// CABBBBB
// CABABBB
// |
s2p = s2future;
s1p = s1eqind;
stateequal = false;
} else if (str1[s1p] < str2[s2future]) { //previous call was correct
// |
// CABACCC
// CABDDDD
// |
stateequal = false;
} else { //same
// |
// CABACCC
// CABADDD
// |
ret.push_back(str1[s1p++]);
}
} else {
// |
// CABACCC
// CAB
// |
stateequal = false;
}
}
// s1p is greater than s2p
// how does s2p compare to s2future?
void processStateGreater(string& ret, const string& str1, const string& str2, int& s1p, int& s2p, int& s1eqind, int& s2eqind, bool& stateequal) {
int delta = s1p - s1eqind;
int s2future = s2p + delta;
if (s2future < str2.length()) {
if (str1[s1p] < str2[s2future]) { //previous call was correct
// |
// CABFCCC
// CABGDDD
// |
stateequal = false;
} else if (str1[s1p] > str2[s2future]) {
// |
// CABFCCC
// CABEDDD
// |
s2p = s2future;
s1p = s1eqind;
stateequal = false;
} else {
// |
// CABFCCC
// CABFDDD
// |
stateequal = false; //PROGRAMMER BEWARE! Deceptive.
}
} else {
// |
// CABFCCC
// CAB
// |
//s2p = s2future;
//s1p = s1eqind;
stateequal = false;
}
}
void processStrings(const string& str1, const string& str2) {
string ret;
int s1p=0, s2p=0;
int s1eqind = -1, s2eqind = -1;
//stateequal denotes the following invariant
// Everything from [s1eqind, s1p] is the same as everything from [s2eqind, s2eqind + (s1eqind - s1p)]
bool stateequal = false;
while (s1p < str1.length() && s2p < str2.length()) {
if (stateequal) {
int len = s1p - s1eqind;
if (s1p < str1.length() && (s2p + len) < str2.length()) {
assert(str1.substr(s1eqind, len) == str2.substr(s2eqind, len));
}
}
if (str1[s1p] < str2[s2p]){
if (stateequal) {
processStateLesser(ret, str1, str2, s1p, s2p, s1eqind, s2eqind, stateequal);
} else {
ret.push_back(str1[s1p++]);
}
}else if (str1[s1p] > str2[s2p]){
if (stateequal) {
processStateGreater(ret, str1, str2, s1p, s2p, s1eqind, s2eqind, stateequal);
} else {
ret.push_back(str2[s2p++]);
}
} else {
if (stateequal == false) {
stateequal = true;
s1eqind = s1p;
s2eqind = s2p;
ret.push_back(str1[s1p++]); //choose str1 speculatively
} else {
processStateEqual(ret, str1, str2, s1p, s2p, s1eqind, s2eqind, stateequal);
}
}
if (stateequal && s1p == str1.length()) { //and we are in equal state, swap
int delta = s1p - s1eqind;
int s2pfuture = s2p + delta;
s2p = s2pfuture;
s1p = s1eqind;
stateequal = false;
}
}
if (s1p < str1.length()) {
ret += str1.substr(s1p);
} else if (s2p < str2.length()) {
ret += str2.substr(s2p);
}
std::cout << ret << std::endl;;
}
int main() {
int tc; std::cin >> tc;
for (int i=0; i<tc; i++) {
string str1, str2;
std::cin >> str1;
std::cin >> str2;
processStrings(str1, str2);
}
}
<commit_msg>Fixed the cryptic bug in this!<commit_after>// -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
//
// This problem is driving me NUTS!
// I'm trying to solve this in O(n), and currently passing 9/17, the rest are WA.
// EDIT: Bug fixed. All tests pass within the 2 sec time limit now.
//
// Here is the main issue with the problem:
//
// Initially the problem seems to be analogous to the merge step of merge sort,
// sadly that is not the case. This is because the case where the two strings have
// equal chars, we need to look ahead (possibly quite a bit) before picking the right one
//
// e.g. (AAABBBBBC) and (AAABBBBBD) in this case, we need to look ahead until we notice a difference (c vs d)
// Unfortunately this makes the algorithm O(n^2)
//
// My Solution in O(n):
// Assume s1p points to current location in str1, and s2p for str2.
//
// This solution exploits what I call *speculative execution in software*.
// e.g. in the above case, we will speculatively pick str1, and go ahead with the merging.
// (we will also note down some bookkeeping information, e.g. the positions where we first started
// our speculation as s1eqint and s2eqind. these are the indices of the first A in both strings)
//
// When we finally reach C vs D, we can check whether our speculation was correct. If so, we keep going
// as if nothing happened. If it was wrong, we can *switch* pointers to make s1p = s1eqind, and s2p = s2eqind + deltaTraveled
// This allows the whole algorithm to now finish in O(n)
//
// Of course, this was easier said than done. In particular, I found the details of the speculation very tricky to implement.
// I have provided comments in the code below, to show the various cases, e.g.
// |
// ->CABCCCC
// ->CABAAAA
// | *
// Here The starting Cs of both are s1eqind and s2eqind (pointed by ->)
// s2p remained at starting C, while s1p went ahead executing speculatively (denoted by |)
// In the above example, we noticed later on, that our speculation was wrong, so we will
// switch s1p to point to starting C, and s2p to point to the A (marked by *)
// Hope that makes sense.
//
// Unfortunately there is some bug somewhere, which causes 1 test pair from each of the tests from 10 onwards to fail.
// If you can get through the convoluted code below, and spot and fix the bug, PLEASE shoot me an email! :-)
//
// EDIT: Fixed the bug. It had to do with the case shown below in processStateEqual
// Basically, I needed an additional rollback point. Compare the corresponding cases
// in processStateGreater and processStateLesser, to see why.
//
// I apologize, the code is really convoluted. I would like to come back and clean it up sometime! ;)
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
using std::string;
using std::vector;
//s1p is the same as s2p
// how does s1p compare against s2future?
void processStateEqual(string& ret, const string& str1, const string& str2, int& s1p, int& s2p, int& s1eqind, int& s2eqind, int& rollbackpoint, bool& stateequal) {
int delta = s1p - s1eqind;
int s2future = s2p + delta;
if (s2future < str2.length()) {
if (str1[s1p] > str2[s2future]) { //made a bad decision earlier
// |
// CABCCCC
// CABAAAA
// |
s2p = rollbackpoint == -1 ? s2future : s2p + (rollbackpoint- s1eqind);
if (rollbackpoint != -1) { for (int c=0; c<(s1p-rollbackpoint); c++) ret.pop_back(); }
s1p = s1eqind;
stateequal = false; rollbackpoint = -1;
} else if (str1[s1p] < str2[s2future]) { //previous call was correct
// |
// CABCCCC
// CABDDDD
// |
stateequal = false; rollbackpoint = -1;
} else { //same
// |
// CABCCCC
// CABCCCC
// |
//PROGRAMMER BEWARE: This is where the nasty bug was found. Basically compare these else cases in the
// processStateLesser and processStateGreater functions. This case is on the fence, and we really need
// to go futher down the road to figure out how it proceeds. If speculation fails, I need
// to rollback to this point
if (rollbackpoint == -1) {rollbackpoint = s1p;}
ret.push_back(str1[s1p++]); //choose str1 speculatively
}
} else {
// |
// CABCCCC
// CAB
// |
stateequal = false; rollbackpoint = -1;
}
}
// s1p is lesser than s2p
// how does s1p compare to s2future?
void processStateLesser(string& ret, const string& str1, const string& str2, int& s1p, int& s2p, int& s1eqind, int& s2eqind, int& rollbackpoint, bool& stateequal) {
int delta = s1p - s1eqind;
int s2future = s2p + delta;
if (s2future < str2.length()) {
if (str1[s1p] > str2[s2future]) { //made a bad decision earlier
// |
// CABBBBB
// CABABBB
// |
s2p = rollbackpoint == -1 ? s2future : s2p + (rollbackpoint- s1eqind);
if (rollbackpoint != -1) { for (int c=0; c<(s1p-rollbackpoint); c++) ret.pop_back(); }
s1p = s1eqind;
stateequal = false; rollbackpoint = -1;
} else if (str1[s1p] < str2[s2future]) { //previous call was correct
// |
// CABACCC
// CABDDDD
// |
stateequal = false; rollbackpoint = -1;
} else { //same
// |
// CABACCC
// CABADDD
// |
ret.push_back(str1[s1p++]);
}
} else {
// |
// CABACCC
// CAB
// |
stateequal = false; rollbackpoint = -1;
}
}
// s1p is greater than s2p
// how does s2p compare to s2future?
void processStateGreater(string& ret, const string& str1, const string& str2, int& s1p, int& s2p, int& s1eqind, int& s2eqind, int& rollbackpoint, bool& stateequal) {
int delta = s1p - s1eqind;
int s2future = s2p + delta;
if (s2future < str2.length()) {
if (str1[s1p] < str2[s2future]) { //previous call was correct
// |
// CABFCCC
// CABGDDD
// |
stateequal = false; rollbackpoint = -1;
} else if (str1[s1p] > str2[s2future]) {
// |
// CABFCCC
// CABEDDD
// |
s2p = rollbackpoint == -1 ? s2future : s2p + (rollbackpoint- s1eqind);
if (rollbackpoint != -1) { for (int c=0; c<(s1p-rollbackpoint); c++) ret.pop_back(); }
s1p = s1eqind;
stateequal = false; rollbackpoint = -1;
} else {
// |
// CABFCCC
// CABFDDD
// |
stateequal = false; rollbackpoint = -1;
}
} else {
// |
// CABFCCC
// CAB
// |
//s2p = s2future;
//s1p = s1eqind;
stateequal = false; rollbackpoint = -1;
}
}
void processStrings(const string& str1, const string& str2) {
string ret;
int s1p=0, s2p=0;
int s1eqind = -1, s2eqind = -1;
int rollbackpoint=-1;
//stateequal denotes the following invariant
// Everything from [s1eqind, s1p] is the same as everything from [s2eqind, s2eqind + (s1eqind - s1p)]
bool stateequal = false;
while (s1p < str1.length() && s2p < str2.length()) {
if (stateequal) {
int len = s1p - s1eqind;
if (s1p < str1.length() && (s2p + len) < str2.length()) {
assert(str1.substr(s1eqind, len) == str2.substr(s2eqind, len));
}
}
if (str1[s1p] < str2[s2p]){
if (stateequal) {
processStateLesser(ret, str1, str2, s1p, s2p, s1eqind, s2eqind, rollbackpoint, stateequal);
} else {
ret.push_back(str1[s1p++]);
}
}else if (str1[s1p] > str2[s2p]){
if (stateequal) {
processStateGreater(ret, str1, str2, s1p, s2p, s1eqind, s2eqind, rollbackpoint, stateequal);
} else {
ret.push_back(str2[s2p++]);
}
} else {
if (stateequal == false) {
stateequal = true;
s1eqind = s1p;
s2eqind = s2p;
ret.push_back(str1[s1p++]); //choose str1 speculatively
} else {
processStateEqual(ret, str1, str2, s1p, s2p, s1eqind, s2eqind, rollbackpoint, stateequal);
}
}
if (stateequal && s1p == str1.length()) { //and we are in equal state, swap
int delta = s1p - s1eqind;
int s2pfuture = s2p + delta;
s2p = rollbackpoint == -1 ? s2pfuture : s2p + (rollbackpoint- s1eqind);
if (rollbackpoint != -1) { for (int c=0; c<(s1p-rollbackpoint); c++) ret.pop_back(); }
s1p = s1eqind;
stateequal = false; rollbackpoint = -1;
}
}
if (s1p < str1.length()) {
ret += str1.substr(s1p);
} else if (s2p < str2.length()) {
ret += str2.substr(s2p);
}
std::cout << ret << std::endl;;
}
int main() {
int tc; std::cin >> tc;
for (int i=0; i<tc; i++) {
string str1, str2;
std::cin >> str1;
std::cin >> str2;
processStrings(str1, str2);
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/algorithm/string/predicate.hpp"
#include "Gaffer/Context.h"
#include "Gaffer/StringPlug.h"
#include "GafferScene/Isolate.h"
#include "GafferScene/PathMatcherData.h"
using namespace std;
using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;
IE_CORE_DEFINERUNTIMETYPED( Isolate );
size_t Isolate::g_firstPlugIndex = 0;
Isolate::Isolate( const std::string &name )
: FilteredSceneProcessor( name, Filter::EveryMatch )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new StringPlug( "from", Plug::In, "/" ) );
addChild( new BoolPlug( "adjustBounds", Plug::In, false ) );
// Direct pass-throughs
outPlug()->transformPlug()->setInput( inPlug()->transformPlug() );
outPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );
outPlug()->objectPlug()->setInput( inPlug()->objectPlug() );
outPlug()->globalsPlug()->setInput( inPlug()->globalsPlug() );
outPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );
}
Isolate::~Isolate()
{
}
Gaffer::StringPlug *Isolate::fromPlug()
{
return getChild<StringPlug>( g_firstPlugIndex );
}
const Gaffer::StringPlug *Isolate::fromPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex );
}
Gaffer::BoolPlug *Isolate::adjustBoundsPlug()
{
return getChild<BoolPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::BoolPlug *Isolate::adjustBoundsPlug() const
{
return getChild<BoolPlug>( g_firstPlugIndex + 1 );
}
void Isolate::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
FilteredSceneProcessor::affects( input, outputs );
const ScenePlug *in = inPlug();
if( input->parent<ScenePlug>() == in )
{
outputs.push_back( outPlug()->getChild<ValuePlug>( input->getName() ) );
}
else if( input == filterPlug() || input == fromPlug() )
{
outputs.push_back( outPlug()->childNamesPlug() );
outputs.push_back( outPlug()->setPlug() );
}
else if( input == adjustBoundsPlug() )
{
outputs.push_back( outPlug()->boundPlug() );
}
}
bool Isolate::acceptsInput( const Gaffer::Plug *plug, const Gaffer::Plug *inputPlug ) const
{
if( !FilteredSceneProcessor::acceptsInput( plug, inputPlug ) )
{
return false;
}
if( plug == filterPlug() )
{
if( const Filter *filter = runTimeCast<const Filter>( inputPlug->source<Plug>()->node() ) )
{
if(
filter->sceneAffectsMatch( inPlug(), inPlug()->boundPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->transformPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->attributesPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->objectPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->childNamesPlug() )
)
{
// We make a single call to filterHash() in hashSet(), to account for
// the fact that the filter is used in remapping sets. This wouldn't
// work for filter types which actually vary based on data within the
// scene hierarchy, because then multiple calls would be necessary.
// We could make more calls here, but that would be expensive.
/// \todo In an ideal world we'd be able to compute a hash for the
/// filter across a whole hierarchy.
return false;
}
}
}
return true;
}
void Isolate::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
if( adjustBoundsPlug()->getValue() && mayPruneChildren( path, filterValue( context ) ) )
{
h = hashOfTransformedChildBounds( path, outPlug() );
return;
}
// pass through
h = inPlug()->boundPlug()->hash();
}
Imath::Box3f Isolate::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const
{
if( adjustBoundsPlug()->getValue() && mayPruneChildren( path, filterValue( context ) ) )
{
return unionOfTransformedChildBounds( path, outPlug() );
}
return inPlug()->boundPlug()->getValue();
}
void Isolate::hashChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
ContextPtr tmpContext = filterContext( context );
Context::Scope scopedContext( tmpContext.get() );
if( mayPruneChildren( path, filterPlug()->getValue() ) )
{
// we might be computing new childnames for this level.
FilteredSceneProcessor::hashChildNames( path, context, parent, h );
inPlug()->childNamesPlug()->hash( h );
filterPlug()->hash( h );
}
else
{
// pass through
h = inPlug()->childNamesPlug()->hash();
}
}
IECore::ConstInternedStringVectorDataPtr Isolate::computeChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const
{
ContextPtr tmpContext = filterContext( context );
Context::Scope scopedContext( tmpContext.get() );
if( mayPruneChildren( path, filterPlug()->getValue() ) )
{
// we may need to delete one or more of our children
ConstInternedStringVectorDataPtr inputChildNamesData = inPlug()->childNamesPlug()->getValue();
const vector<InternedString> &inputChildNames = inputChildNamesData->readable();
InternedStringVectorDataPtr outputChildNamesData = new InternedStringVectorData;
vector<InternedString> &outputChildNames = outputChildNamesData->writable();
ScenePath childPath = path;
childPath.push_back( InternedString() ); // for the child name
for( vector<InternedString>::const_iterator it = inputChildNames.begin(), eIt = inputChildNames.end(); it != eIt; it++ )
{
childPath[path.size()] = *it;
tmpContext->set( ScenePlug::scenePathContextName, childPath );
if( filterPlug()->getValue() != Filter::NoMatch )
{
outputChildNames.push_back( *it );
}
}
return outputChildNamesData;
}
else
{
// pass through
return inPlug()->childNamesPlug()->getValue();
}
}
void Isolate::hashSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
FilteredSceneProcessor::hashSet( setName, context, parent, h );
inPlug()->setPlug()->hash( h );
fromPlug()->hash( h );
// The sets themselves do not depend on the "scene:path"
// context entry - the whole point is that they're global.
// However, the PathFilter is dependent on scene:path, so
// we must remove the path before hashing in the filter in
// case we're computed from multiple contexts with different
// paths (from a SetFilter for instance). If we didn't do this,
// our different hashes would lead to huge numbers of redundant
// calls to computeSet() and a huge overhead in recomputing
// the same sets repeatedly.
//
// See further comments in FilteredSceneProcessor::affects().
ContextPtr c = filterContext( context );
c->remove( ScenePlug::scenePathContextName );
Context::Scope s( c.get() );
filterPlug()->hash( h );
}
GafferScene::ConstPathMatcherDataPtr Isolate::computeSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent ) const
{
ConstPathMatcherDataPtr inputSetData = inPlug()->setPlug()->getValue();
const PathMatcher &inputSet = inputSetData->readable();
if( inputSet.isEmpty() )
{
return inputSetData;
}
PathMatcherDataPtr outputSetData = new PathMatcherData;
PathMatcher &outputSet = outputSetData->writable();
ContextPtr tmpContext = filterContext( context );
Context::Scope scopedContext( tmpContext.get() );
const std::string fromString = fromPlug()->getValue();
ScenePlug::ScenePath fromPath; ScenePlug::stringToPath( fromString, fromPath );
for( PathMatcher::RawIterator pIt = inputSet.begin(), peIt = inputSet.end(); pIt != peIt; )
{
tmpContext->set( ScenePlug::scenePathContextName, *pIt );
const int m = filterPlug()->getValue();
if( m & ( Filter::ExactMatch | Filter::AncestorMatch ) )
{
// We want to keep everything below this point, and
// we can speed things up by not checking the filter
// for our descendants.
PathMatcher::RawIterator next = pIt; next.prune(); ++next;
while( pIt != next )
{
if( pIt.exactMatch() )
{
outputSet.addPath( *pIt );
}
++pIt;
}
}
else if( m & Filter::DescendantMatch )
{
// We might be removing things below here,
// so just continue our iteration normally
// so we can find out.
if( pIt.exactMatch() )
{
outputSet.addPath( *pIt );
}
++pIt;
}
else
{
assert( m == Filter::NoMatch );
if( boost::starts_with( *pIt, fromPath ) )
{
// Not going to keep anything below
// here, so we can prune traversal
// entirely.
pIt.prune();
}
else if( pIt.exactMatch() )
{
outputSet.addPath( *pIt );
}
++pIt;
}
}
return outputSetData;
}
bool Isolate::mayPruneChildren( const ScenePath &path, unsigned filterValue ) const
{
const std::string fromString = fromPlug()->getValue();
ScenePlug::ScenePath fromPath; ScenePlug::stringToPath( fromString, fromPath );
if( !boost::starts_with( path, fromPath ) )
{
return false;
}
return filterValue == Filter::DescendantMatch || filterValue == Filter::NoMatch;
}
<commit_msg>Isolate : Take advantage of PathMatcher node sharing.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/algorithm/string/predicate.hpp"
#include "Gaffer/Context.h"
#include "Gaffer/StringPlug.h"
#include "GafferScene/Isolate.h"
#include "GafferScene/PathMatcherData.h"
using namespace std;
using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;
IE_CORE_DEFINERUNTIMETYPED( Isolate );
size_t Isolate::g_firstPlugIndex = 0;
Isolate::Isolate( const std::string &name )
: FilteredSceneProcessor( name, Filter::EveryMatch )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new StringPlug( "from", Plug::In, "/" ) );
addChild( new BoolPlug( "adjustBounds", Plug::In, false ) );
// Direct pass-throughs
outPlug()->transformPlug()->setInput( inPlug()->transformPlug() );
outPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );
outPlug()->objectPlug()->setInput( inPlug()->objectPlug() );
outPlug()->globalsPlug()->setInput( inPlug()->globalsPlug() );
outPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );
}
Isolate::~Isolate()
{
}
Gaffer::StringPlug *Isolate::fromPlug()
{
return getChild<StringPlug>( g_firstPlugIndex );
}
const Gaffer::StringPlug *Isolate::fromPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex );
}
Gaffer::BoolPlug *Isolate::adjustBoundsPlug()
{
return getChild<BoolPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::BoolPlug *Isolate::adjustBoundsPlug() const
{
return getChild<BoolPlug>( g_firstPlugIndex + 1 );
}
void Isolate::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
FilteredSceneProcessor::affects( input, outputs );
const ScenePlug *in = inPlug();
if( input->parent<ScenePlug>() == in )
{
outputs.push_back( outPlug()->getChild<ValuePlug>( input->getName() ) );
}
else if( input == filterPlug() || input == fromPlug() )
{
outputs.push_back( outPlug()->childNamesPlug() );
outputs.push_back( outPlug()->setPlug() );
}
else if( input == adjustBoundsPlug() )
{
outputs.push_back( outPlug()->boundPlug() );
}
}
bool Isolate::acceptsInput( const Gaffer::Plug *plug, const Gaffer::Plug *inputPlug ) const
{
if( !FilteredSceneProcessor::acceptsInput( plug, inputPlug ) )
{
return false;
}
if( plug == filterPlug() )
{
if( const Filter *filter = runTimeCast<const Filter>( inputPlug->source<Plug>()->node() ) )
{
if(
filter->sceneAffectsMatch( inPlug(), inPlug()->boundPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->transformPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->attributesPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->objectPlug() ) ||
filter->sceneAffectsMatch( inPlug(), inPlug()->childNamesPlug() )
)
{
// We make a single call to filterHash() in hashSet(), to account for
// the fact that the filter is used in remapping sets. This wouldn't
// work for filter types which actually vary based on data within the
// scene hierarchy, because then multiple calls would be necessary.
// We could make more calls here, but that would be expensive.
/// \todo In an ideal world we'd be able to compute a hash for the
/// filter across a whole hierarchy.
return false;
}
}
}
return true;
}
void Isolate::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
if( adjustBoundsPlug()->getValue() && mayPruneChildren( path, filterValue( context ) ) )
{
h = hashOfTransformedChildBounds( path, outPlug() );
return;
}
// pass through
h = inPlug()->boundPlug()->hash();
}
Imath::Box3f Isolate::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const
{
if( adjustBoundsPlug()->getValue() && mayPruneChildren( path, filterValue( context ) ) )
{
return unionOfTransformedChildBounds( path, outPlug() );
}
return inPlug()->boundPlug()->getValue();
}
void Isolate::hashChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
ContextPtr tmpContext = filterContext( context );
Context::Scope scopedContext( tmpContext.get() );
if( mayPruneChildren( path, filterPlug()->getValue() ) )
{
// we might be computing new childnames for this level.
FilteredSceneProcessor::hashChildNames( path, context, parent, h );
inPlug()->childNamesPlug()->hash( h );
filterPlug()->hash( h );
}
else
{
// pass through
h = inPlug()->childNamesPlug()->hash();
}
}
IECore::ConstInternedStringVectorDataPtr Isolate::computeChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const
{
ContextPtr tmpContext = filterContext( context );
Context::Scope scopedContext( tmpContext.get() );
if( mayPruneChildren( path, filterPlug()->getValue() ) )
{
// we may need to delete one or more of our children
ConstInternedStringVectorDataPtr inputChildNamesData = inPlug()->childNamesPlug()->getValue();
const vector<InternedString> &inputChildNames = inputChildNamesData->readable();
InternedStringVectorDataPtr outputChildNamesData = new InternedStringVectorData;
vector<InternedString> &outputChildNames = outputChildNamesData->writable();
ScenePath childPath = path;
childPath.push_back( InternedString() ); // for the child name
for( vector<InternedString>::const_iterator it = inputChildNames.begin(), eIt = inputChildNames.end(); it != eIt; it++ )
{
childPath[path.size()] = *it;
tmpContext->set( ScenePlug::scenePathContextName, childPath );
if( filterPlug()->getValue() != Filter::NoMatch )
{
outputChildNames.push_back( *it );
}
}
return outputChildNamesData;
}
else
{
// pass through
return inPlug()->childNamesPlug()->getValue();
}
}
void Isolate::hashSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
FilteredSceneProcessor::hashSet( setName, context, parent, h );
inPlug()->setPlug()->hash( h );
fromPlug()->hash( h );
// The sets themselves do not depend on the "scene:path"
// context entry - the whole point is that they're global.
// However, the PathFilter is dependent on scene:path, so
// we must remove the path before hashing in the filter in
// case we're computed from multiple contexts with different
// paths (from a SetFilter for instance). If we didn't do this,
// our different hashes would lead to huge numbers of redundant
// calls to computeSet() and a huge overhead in recomputing
// the same sets repeatedly.
//
// See further comments in FilteredSceneProcessor::affects().
ContextPtr c = filterContext( context );
c->remove( ScenePlug::scenePathContextName );
Context::Scope s( c.get() );
filterPlug()->hash( h );
}
GafferScene::ConstPathMatcherDataPtr Isolate::computeSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent ) const
{
ConstPathMatcherDataPtr inputSetData = inPlug()->setPlug()->getValue();
const PathMatcher &inputSet = inputSetData->readable();
if( inputSet.isEmpty() )
{
return inputSetData;
}
PathMatcherDataPtr outputSetData = inputSetData->copy();
PathMatcher &outputSet = outputSetData->writable();
ContextPtr tmpContext = filterContext( context );
Context::Scope scopedContext( tmpContext.get() );
const std::string fromString = fromPlug()->getValue();
ScenePlug::ScenePath fromPath; ScenePlug::stringToPath( fromString, fromPath );
for( PathMatcher::RawIterator pIt = inputSet.begin(), peIt = inputSet.end(); pIt != peIt; )
{
tmpContext->set( ScenePlug::scenePathContextName, *pIt );
const int m = filterPlug()->getValue();
if( m & ( Filter::ExactMatch | Filter::AncestorMatch ) )
{
// We want to keep everything below this point, so
// can just prune our iteration.
pIt.prune();
++pIt;
}
else if( m & Filter::DescendantMatch )
{
// We might be removing things below here,
// so just continue our iteration normally
// so we can find out.
++pIt;
}
else
{
assert( m == Filter::NoMatch );
if( boost::starts_with( *pIt, fromPath ) )
{
// Not going to keep anything below
// here, so we can prune traversal
// entirely.
outputSet.prune( *pIt );
pIt.prune();
}
++pIt;
}
}
return outputSetData;
}
bool Isolate::mayPruneChildren( const ScenePath &path, unsigned filterValue ) const
{
const std::string fromString = fromPlug()->getValue();
ScenePlug::ScenePath fromPath; ScenePlug::stringToPath( fromString, fromPath );
if( !boost::starts_with( path, fromPath ) )
{
return false;
}
return filterValue == Filter::DescendantMatch || filterValue == Filter::NoMatch;
}
<|endoftext|> |
<commit_before>#include <SDL2/SDL.h>
#include "PrjHndl.h"
#include "TxtRead.h"
#include "Resource.h"
#include "compression/KidDec.h"
#include "compression/ReadPlain.h"
#include "FW_KENSC/comper.h"
#include "FW_KENSC/enigma.h"
#include "FW_KENSC/kosinski.h"
#include "FW_KENSC/nemesis.h"
#include "FW_KENSC/saxman.h"
const char* const FILE_MAP_DEFAULT = "MapDefault.bin";
Resource::Resource(void)
{
strcpy(this->name, "");
this->offset = 0;
this->length = 0;
this->compression = comprType::INVALID;
this->kosinski_module_size = 0x1000;
}
void Resource::Save(const char* const filename, const char* const dstfilename)
{
CompressFile(filename, dstfilename);
remove(filename);
}
long Resource::DecompressToFile(const char* const dstfile)
{
int decompressed_length;
switch (this->compression)
{
case comprType::NONE:
decompressed_length = ReadPlain(this->name, dstfile, this->offset, this->length);
break;
case comprType::ENIGMA:
decompressed_length = enigma::decode(this->name, dstfile, this->offset, false);
break;
case comprType::KOSINSKI:
decompressed_length = kosinski::decode(this->name, dstfile, this->offset, false, 16u);
break;
case comprType::MODULED_KOSINSKI:
decompressed_length = kosinski::decode(this->name, dstfile, this->offset, true, 16u);
break;
case comprType::NEMESIS:
decompressed_length = nemesis::decode(this->name, dstfile, this->offset, 0);
break;
case comprType::KID_CHAMELEON:
decompressed_length = KidDec(this->name, dstfile, this->offset);
break;
case comprType::COMPER:
decompressed_length = comper::decode(this->name, dstfile, this->offset);
break;
case comprType::SAXMAN:
decompressed_length = saxman::decode(this->name, dstfile, this->offset, 0);
break;
}
return decompressed_length;
}
void Resource::CompressFile(const char* const srcfile, const char* const dstfile)
{
switch (this->compression)
{
case comprType::NONE:
remove(dstfile);
rename(srcfile, dstfile);
break;
case comprType::ENIGMA:
enigma::encode(srcfile, dstfile, false);
break;
case comprType::KOSINSKI:
kosinski::encode(srcfile, dstfile, false, this->kosinski_module_size, 16u);
break;
case comprType::MODULED_KOSINSKI:
kosinski::encode(srcfile, dstfile, true, this->kosinski_module_size, 16u);
break;
case comprType::NEMESIS:
nemesis::encode(srcfile, dstfile);
break;
case comprType::COMPER:
comper::encode(srcfile, dstfile);
break;
case comprType::SAXMAN:
saxman::encode(srcfile, dstfile, false);
break;
}
}
ResourceArt::ResourceArt(void)
{
this->tileAmount = 0;
}
void ResourceArt::Load(const char* const filename)
{
if (this->compression == comprType::INVALID)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid art compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL);
exit(1);
}
int decompressed_length = DecompressToFile(filename);
if (decompressed_length < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress art file. Are you sure the compression is correct?", NULL);
exit(1);
}
this->tileAmount = decompressed_length/0x20;
}
ResourceMap::ResourceMap(void)
{
this->xSize = 0;
this->ySize = 0;
strcpy(this->saveName, "");
}
void ResourceMap::Load(const char* const filename)
{
if (this->compression == comprType::INVALID || this->compression == comprType::KID_CHAMELEON)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Comper'\n'Saxman'", NULL);
exit(1);
}
int decompressed_length = DecompressToFile(filename);
if (decompressed_length < 0) {
//file could not be decompressed or found
decompressed_length = 2*this->xSize*this->ySize;
if (!CheckCreateBlankFile(this->name, filename, this->offset, decompressed_length))
{
//file is existant but could not be decompressed
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress map file. Are you sure the compression is correct?", NULL);
exit(1);
}
else
{
//file non-existant, blank template created
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", "No map file found, created blank template.", NULL);
}
}
if (decompressed_length < 2*this->xSize*this->ySize)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", "Specified size exceeds map size.\nField has been trimmed vertically.", NULL);
this->ySize = (decompressed_length/this->xSize) / 2;
if (this->ySize == 0)
exit(1);
}
if (strlen(this->saveName) == 0)
{
if (this->offset == 0)
{
strcpy(this->saveName, this->name); //overwrite existing map
}
else
{
const char* const part_message = "This tool cannot overwrite a ROM. Plane map will be saved to ";
char* whole_message = new char[strlen(part_message)+strlen(FILE_MAP_DEFAULT)+1];
sprintf(whole_message, "%s%s", part_message, FILE_MAP_DEFAULT);
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", whole_message, NULL);
delete[] whole_message;
strcpy(this->saveName, FILE_MAP_DEFAULT); //write to default file
}
}
}
ResourcePal::ResourcePal(void)
{
// For backwards compatibility, palette is assumed to be uncompressed by default
this->compression = comprType::NONE;
}
void ResourcePal::Load(const char* const filename)
{
if (this->compression == comprType::INVALID)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid palette compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL);
exit(1);
}
int decompressed_length = DecompressToFile(filename);
if (decompressed_length < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress palette file. Are you sure the compression is correct?", NULL);
exit(1);
}
}
<commit_msg>Changed how saveName is deemed unset<commit_after>#include <SDL2/SDL.h>
#include "PrjHndl.h"
#include "TxtRead.h"
#include "Resource.h"
#include "compression/KidDec.h"
#include "compression/ReadPlain.h"
#include "FW_KENSC/comper.h"
#include "FW_KENSC/enigma.h"
#include "FW_KENSC/kosinski.h"
#include "FW_KENSC/nemesis.h"
#include "FW_KENSC/saxman.h"
const char* const FILE_MAP_DEFAULT = "MapDefault.bin";
Resource::Resource(void)
{
strcpy(this->name, "");
this->offset = 0;
this->length = 0;
this->compression = comprType::INVALID;
this->kosinski_module_size = 0x1000;
}
void Resource::Save(const char* const filename, const char* const dstfilename)
{
CompressFile(filename, dstfilename);
remove(filename);
}
long Resource::DecompressToFile(const char* const dstfile)
{
int decompressed_length;
switch (this->compression)
{
case comprType::NONE:
decompressed_length = ReadPlain(this->name, dstfile, this->offset, this->length);
break;
case comprType::ENIGMA:
decompressed_length = enigma::decode(this->name, dstfile, this->offset, false);
break;
case comprType::KOSINSKI:
decompressed_length = kosinski::decode(this->name, dstfile, this->offset, false, 16u);
break;
case comprType::MODULED_KOSINSKI:
decompressed_length = kosinski::decode(this->name, dstfile, this->offset, true, 16u);
break;
case comprType::NEMESIS:
decompressed_length = nemesis::decode(this->name, dstfile, this->offset, 0);
break;
case comprType::KID_CHAMELEON:
decompressed_length = KidDec(this->name, dstfile, this->offset);
break;
case comprType::COMPER:
decompressed_length = comper::decode(this->name, dstfile, this->offset);
break;
case comprType::SAXMAN:
decompressed_length = saxman::decode(this->name, dstfile, this->offset, 0);
break;
}
return decompressed_length;
}
void Resource::CompressFile(const char* const srcfile, const char* const dstfile)
{
switch (this->compression)
{
case comprType::NONE:
remove(dstfile);
rename(srcfile, dstfile);
break;
case comprType::ENIGMA:
enigma::encode(srcfile, dstfile, false);
break;
case comprType::KOSINSKI:
kosinski::encode(srcfile, dstfile, false, this->kosinski_module_size, 16u);
break;
case comprType::MODULED_KOSINSKI:
kosinski::encode(srcfile, dstfile, true, this->kosinski_module_size, 16u);
break;
case comprType::NEMESIS:
nemesis::encode(srcfile, dstfile);
break;
case comprType::COMPER:
comper::encode(srcfile, dstfile);
break;
case comprType::SAXMAN:
saxman::encode(srcfile, dstfile, false);
break;
}
}
ResourceArt::ResourceArt(void)
{
this->tileAmount = 0;
}
void ResourceArt::Load(const char* const filename)
{
if (this->compression == comprType::INVALID)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid art compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL);
exit(1);
}
int decompressed_length = DecompressToFile(filename);
if (decompressed_length < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress art file. Are you sure the compression is correct?", NULL);
exit(1);
}
this->tileAmount = decompressed_length/0x20;
}
ResourceMap::ResourceMap(void)
{
this->xSize = 0;
this->ySize = 0;
strcpy(this->saveName, "");
}
void ResourceMap::Load(const char* const filename)
{
if (this->compression == comprType::INVALID || this->compression == comprType::KID_CHAMELEON)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Comper'\n'Saxman'", NULL);
exit(1);
}
int decompressed_length = DecompressToFile(filename);
if (decompressed_length < 0) {
//file could not be decompressed or found
decompressed_length = 2*this->xSize*this->ySize;
if (!CheckCreateBlankFile(this->name, filename, this->offset, decompressed_length))
{
//file is existant but could not be decompressed
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress map file. Are you sure the compression is correct?", NULL);
exit(1);
}
else
{
//file non-existant, blank template created
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", "No map file found, created blank template.", NULL);
}
}
if (decompressed_length < 2*this->xSize*this->ySize)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", "Specified size exceeds map size.\nField has been trimmed vertically.", NULL);
this->ySize = (decompressed_length/this->xSize) / 2;
if (this->ySize == 0)
exit(1);
}
if (strcmp(this->saveName, "") == 0)
{
if (this->offset == 0)
{
strcpy(this->saveName, this->name); //overwrite existing map
}
else
{
const char* const part_message = "This tool cannot overwrite a ROM. Plane map will be saved to ";
char* whole_message = new char[strlen(part_message)+strlen(FILE_MAP_DEFAULT)+1];
sprintf(whole_message, "%s%s", part_message, FILE_MAP_DEFAULT);
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", whole_message, NULL);
delete[] whole_message;
strcpy(this->saveName, FILE_MAP_DEFAULT); //write to default file
}
}
}
ResourcePal::ResourcePal(void)
{
// For backwards compatibility, palette is assumed to be uncompressed by default
this->compression = comprType::NONE;
}
void ResourcePal::Load(const char* const filename)
{
if (this->compression == comprType::INVALID)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid palette compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL);
exit(1);
}
int decompressed_length = DecompressToFile(filename);
if (decompressed_length < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress palette file. Are you sure the compression is correct?", NULL);
exit(1);
}
}
<|endoftext|> |
<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.
// Navigates the browser to server and client redirect pages and makes sure
// that the correct redirects are reflected in the history database. Errors
// here might indicate that WebKit changed the calls our glue layer gets in
// the case of redirects. It may also mean problems with the history system.
#include "base/file_util.h"
#include "base/platform_thread.h"
#include "base/scoped_ptr.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "views/event.h"
namespace {
class RedirectTest : public UITest {
public:
RedirectTest()
: test_server_(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data"))) {
}
protected:
net::TestServer test_server_;
};
// Tests a single server redirect
TEST_F(RedirectTest, Server) {
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL(std::string());
GURL first_url = test_server_.GetURL(
"server-redirect?" + final_url.spec());
NavigateToURL(first_url);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
std::vector<GURL> redirects;
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
ASSERT_EQ(1U, redirects.size());
EXPECT_EQ(final_url.spec(), redirects[0].spec());
}
// Tests a single client redirect.
TEST_F(RedirectTest, Client) {
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL(std::string());
GURL first_url = test_server_.GetURL(
"client-redirect?" + final_url.spec());
// The client redirect appears as two page visits in the browser.
NavigateToURLBlockUntilNavigationsComplete(first_url, 2);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
std::vector<GURL> redirects;
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
ASSERT_EQ(1U, redirects.size());
EXPECT_EQ(final_url.spec(), redirects[0].spec());
// The address bar should display the final URL.
GURL tab_url;
EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
EXPECT_TRUE(final_url == tab_url);
// Navigate one more time.
NavigateToURLBlockUntilNavigationsComplete(first_url, 2);
// The address bar should still display the final URL.
EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
EXPECT_TRUE(final_url == tab_url);
}
TEST_F(RedirectTest, ClientEmptyReferer) {
ASSERT_TRUE(test_server_.Start());
// Create the file contents, which will do a redirect to the
// test server.
GURL final_url = test_server_.GetURL(std::string());
ASSERT_TRUE(final_url.is_valid());
std::string file_redirect_contents = StringPrintf(
"<html>"
"<head></head>"
"<body onload=\"document.location='%s'\"></body>"
"</html>",
final_url.spec().c_str());
// Write the contents to a temporary file.
ScopedTempDir temp_directory;
ASSERT_TRUE(temp_directory.CreateUniqueTempDir());
FilePath temp_file;
ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_directory.path(),
&temp_file));
ASSERT_EQ(static_cast<int>(file_redirect_contents.size()),
file_util::WriteFile(temp_file,
file_redirect_contents.data(),
file_redirect_contents.size()));
// Navigate to the file through the browser. The client redirect will appear
// as two page visits in the browser.
GURL first_url = net::FilePathToFileURL(temp_file);
NavigateToURLBlockUntilNavigationsComplete(first_url, 2);
std::vector<GURL> redirects;
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
ASSERT_EQ(1U, redirects.size());
EXPECT_EQ(final_url.spec(), redirects[0].spec());
}
// Tests to make sure a location change when a pending redirect exists isn't
// flagged as a redirect.
#if defined(OS_MACOSX)
// SimulateOSClick is broken on the Mac: http://crbug.com/45162
#define MAYBE_ClientCancelled DISABLED_ClientCancelled
#elif defined(OS_WIN)
// http://crbug.com/53091
#define MAYBE_ClientCancelled FAILS_ClientCancelled
#else
#define MAYBE_ClientCancelled ClientCancelled
#endif
TEST_F(RedirectTest, MAYBE_ClientCancelled) {
FilePath first_path(test_data_directory_);
first_path = first_path.AppendASCII("cancelled_redirect_test.html");
ASSERT_TRUE(file_util::AbsolutePath(&first_path));
GURL first_url = net::FilePathToFileURL(first_path);
NavigateToURLBlockUntilNavigationsComplete(first_url, 1);
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
int64 last_nav_time = 0;
EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
// Simulate a click to force to make a user-initiated location change;
// otherwise, a non user-initiated in-page location change will be treated
// as client redirect and the redirect will be recoreded, which can cause
// this test failed.
gfx::Rect tab_view_bounds;
ASSERT_TRUE(browser->BringToFront());
ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
true));
ASSERT_TRUE(
window->SimulateOSClick(tab_view_bounds.CenterPoint(),
views::Event::EF_LEFT_BUTTON_DOWN));
EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));
std::vector<GURL> redirects;
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
// There should be no redirects from first_url, because the anchor location
// change that occurs should not be flagged as a redirect and the meta-refresh
// won't have fired yet.
ASSERT_EQ(0U, redirects.size());
GURL current_url;
ASSERT_TRUE(tab_proxy->GetCurrentURL(¤t_url));
// Need to test final path and ref separately since constructing a file url
// containing an anchor using FilePathToFileURL will escape the anchor as
// %23, but in current_url the anchor will be '#'.
std::string final_ref = "myanchor";
FilePath current_path;
ASSERT_TRUE(net::FileURLToFilePath(current_url, ¤t_path));
ASSERT_TRUE(file_util::AbsolutePath(¤t_path));
// Path should remain unchanged.
EXPECT_EQ(StringToLowerASCII(first_path.value()),
StringToLowerASCII(current_path.value()));
EXPECT_EQ(final_ref, current_url.ref());
}
// Tests a client->server->server redirect
TEST_F(RedirectTest, ClientServerServer) {
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL(std::string());
GURL next_to_last = test_server_.GetURL(
"server-redirect?" + final_url.spec());
GURL second_url = test_server_.GetURL(
"server-redirect?" + next_to_last.spec());
GURL first_url = test_server_.GetURL(
"client-redirect?" + second_url.spec());
std::vector<GURL> redirects;
// We need the sleep for the client redirects, because it appears as two
// page visits in the browser.
NavigateToURL(first_url);
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
if (!redirects.empty())
break;
}
ASSERT_EQ(3U, redirects.size());
EXPECT_EQ(second_url.spec(), redirects[0].spec());
EXPECT_EQ(next_to_last.spec(), redirects[1].spec());
EXPECT_EQ(final_url.spec(), redirects[2].spec());
}
// Tests that the "#reference" gets preserved across server redirects.
TEST_F(RedirectTest, ServerReference) {
ASSERT_TRUE(test_server_.Start());
const std::string ref("reference");
GURL final_url = test_server_.GetURL(std::string());
GURL initial_url = test_server_.GetURL(
"server-redirect?" + final_url.spec() + "#" + ref);
NavigateToURL(initial_url);
GURL url = GetActiveTabURL();
EXPECT_EQ(ref, url.ref());
}
// Test that redirect from http:// to file:// :
// A) does not crash the browser or confuse the redirect chain, see bug 1080873
// B) does not take place.
TEST_F(RedirectTest, NoHttpToFile) {
ASSERT_TRUE(test_server_.Start());
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("http_to_file.html");
GURL file_url = net::FilePathToFileURL(test_file);
GURL initial_url = test_server_.GetURL(
"client-redirect?" + file_url.spec());
NavigateToURL(initial_url);
// UITest will check for crashes. We make sure the title doesn't match the
// title from the file, because the nav should not have taken place.
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
std::wstring actual_title;
ASSERT_TRUE(tab_proxy->GetTabTitle(&actual_title));
EXPECT_NE("File!", WideToUTF8(actual_title));
}
// Ensures that non-user initiated location changes (within page) are
// flagged as client redirects. See bug 1139823.
TEST_F(RedirectTest, ClientFragments) {
ASSERT_TRUE(test_server_.Start());
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("ref_redirect.html");
GURL first_url = net::FilePathToFileURL(test_file);
std::vector<GURL> redirects;
NavigateToURL(first_url);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
EXPECT_EQ(1U, redirects.size());
EXPECT_EQ(first_url.spec() + "#myanchor", redirects[0].spec());
}
// TODO(timsteele): This is disabled because our current testserver can't
// handle multiple requests in parallel, making it hang on the first request
// to /slow?60. It's unable to serve our second request for files/title2.html
// until /slow? completes, which doesn't give the desired behavior. We could
// alternatively load the second page from disk, but we would need to start
// the browser for this testcase with --process-per-tab, and I don't think
// we can do this at test-case-level granularity at the moment.
// http://crbug.com/45056
TEST_F(RedirectTest,
DISABLED_ClientCancelledByNewNavigationAfterProvisionalLoad) {
// We want to initiate a second navigation after the provisional load for
// the client redirect destination has started, but before this load is
// committed. To achieve this, we tell the browser to load a slow page,
// which causes it to start a provisional load, and while it is waiting
// for the response (which means it hasn't committed the load for the client
// redirect destination page yet), we issue a new navigation request.
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL("files/title2.html");
GURL slow = test_server_.GetURL("slow?60");
GURL first_url = test_server_.GetURL(
"client-redirect?" + slow.spec());
std::vector<GURL> redirects;
NavigateToURL(first_url);
// We don't sleep here - the first navigation won't have been committed yet
// because we told the server to wait a minute. This means the browser has
// started it's provisional load for the client redirect destination page but
// hasn't completed. Our time is now!
NavigateToURL(final_url);
std::wstring tab_title;
std::wstring final_url_title = UTF8ToWide("Title Of Awesomeness");
// Wait till the final page has been loaded.
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetTabTitle(&tab_title));
if (tab_title == final_url_title) {
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
break;
}
}
// Check to make sure the navigation did in fact take place and we are
// at the expected page.
EXPECT_EQ(final_url_title, tab_title);
bool final_navigation_not_redirect = true;
// Check to make sure our request for files/title2.html doesn't get flagged
// as a client redirect from the first (/client-redirect?) page.
for (std::vector<GURL>::iterator it = redirects.begin();
it != redirects.end(); ++it) {
if (final_url.spec() == it->spec()) {
final_navigation_not_redirect = false;
break;
}
}
EXPECT_TRUE(final_navigation_not_redirect);
}
} // namespace
<commit_msg>Marking the RedirectTest.ClientEmptyReferer as flaky.<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.
// Navigates the browser to server and client redirect pages and makes sure
// that the correct redirects are reflected in the history database. Errors
// here might indicate that WebKit changed the calls our glue layer gets in
// the case of redirects. It may also mean problems with the history system.
#include "base/file_util.h"
#include "base/platform_thread.h"
#include "base/scoped_ptr.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "views/event.h"
namespace {
class RedirectTest : public UITest {
public:
RedirectTest()
: test_server_(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data"))) {
}
protected:
net::TestServer test_server_;
};
// Tests a single server redirect
TEST_F(RedirectTest, Server) {
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL(std::string());
GURL first_url = test_server_.GetURL(
"server-redirect?" + final_url.spec());
NavigateToURL(first_url);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
std::vector<GURL> redirects;
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
ASSERT_EQ(1U, redirects.size());
EXPECT_EQ(final_url.spec(), redirects[0].spec());
}
// Tests a single client redirect.
TEST_F(RedirectTest, Client) {
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL(std::string());
GURL first_url = test_server_.GetURL(
"client-redirect?" + final_url.spec());
// The client redirect appears as two page visits in the browser.
NavigateToURLBlockUntilNavigationsComplete(first_url, 2);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
std::vector<GURL> redirects;
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
ASSERT_EQ(1U, redirects.size());
EXPECT_EQ(final_url.spec(), redirects[0].spec());
// The address bar should display the final URL.
GURL tab_url;
EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
EXPECT_TRUE(final_url == tab_url);
// Navigate one more time.
NavigateToURLBlockUntilNavigationsComplete(first_url, 2);
// The address bar should still display the final URL.
EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));
EXPECT_TRUE(final_url == tab_url);
}
// http://code.google.com/p/chromium/issues/detail?id=62772
TEST_F(RedirectTest, FLAKY_ClientEmptyReferer) {
ASSERT_TRUE(test_server_.Start());
// Create the file contents, which will do a redirect to the
// test server.
GURL final_url = test_server_.GetURL(std::string());
ASSERT_TRUE(final_url.is_valid());
std::string file_redirect_contents = StringPrintf(
"<html>"
"<head></head>"
"<body onload=\"document.location='%s'\"></body>"
"</html>",
final_url.spec().c_str());
// Write the contents to a temporary file.
ScopedTempDir temp_directory;
ASSERT_TRUE(temp_directory.CreateUniqueTempDir());
FilePath temp_file;
ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_directory.path(),
&temp_file));
ASSERT_EQ(static_cast<int>(file_redirect_contents.size()),
file_util::WriteFile(temp_file,
file_redirect_contents.data(),
file_redirect_contents.size()));
// Navigate to the file through the browser. The client redirect will appear
// as two page visits in the browser.
GURL first_url = net::FilePathToFileURL(temp_file);
NavigateToURLBlockUntilNavigationsComplete(first_url, 2);
std::vector<GURL> redirects;
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
ASSERT_EQ(1U, redirects.size());
EXPECT_EQ(final_url.spec(), redirects[0].spec());
}
// Tests to make sure a location change when a pending redirect exists isn't
// flagged as a redirect.
#if defined(OS_MACOSX)
// SimulateOSClick is broken on the Mac: http://crbug.com/45162
#define MAYBE_ClientCancelled DISABLED_ClientCancelled
#elif defined(OS_WIN)
// http://crbug.com/53091
#define MAYBE_ClientCancelled FAILS_ClientCancelled
#else
#define MAYBE_ClientCancelled ClientCancelled
#endif
TEST_F(RedirectTest, MAYBE_ClientCancelled) {
FilePath first_path(test_data_directory_);
first_path = first_path.AppendASCII("cancelled_redirect_test.html");
ASSERT_TRUE(file_util::AbsolutePath(&first_path));
GURL first_url = net::FilePathToFileURL(first_path);
NavigateToURLBlockUntilNavigationsComplete(first_url, 1);
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
int64 last_nav_time = 0;
EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
// Simulate a click to force to make a user-initiated location change;
// otherwise, a non user-initiated in-page location change will be treated
// as client redirect and the redirect will be recoreded, which can cause
// this test failed.
gfx::Rect tab_view_bounds;
ASSERT_TRUE(browser->BringToFront());
ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
true));
ASSERT_TRUE(
window->SimulateOSClick(tab_view_bounds.CenterPoint(),
views::Event::EF_LEFT_BUTTON_DOWN));
EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));
std::vector<GURL> redirects;
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
// There should be no redirects from first_url, because the anchor location
// change that occurs should not be flagged as a redirect and the meta-refresh
// won't have fired yet.
ASSERT_EQ(0U, redirects.size());
GURL current_url;
ASSERT_TRUE(tab_proxy->GetCurrentURL(¤t_url));
// Need to test final path and ref separately since constructing a file url
// containing an anchor using FilePathToFileURL will escape the anchor as
// %23, but in current_url the anchor will be '#'.
std::string final_ref = "myanchor";
FilePath current_path;
ASSERT_TRUE(net::FileURLToFilePath(current_url, ¤t_path));
ASSERT_TRUE(file_util::AbsolutePath(¤t_path));
// Path should remain unchanged.
EXPECT_EQ(StringToLowerASCII(first_path.value()),
StringToLowerASCII(current_path.value()));
EXPECT_EQ(final_ref, current_url.ref());
}
// Tests a client->server->server redirect
TEST_F(RedirectTest, ClientServerServer) {
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL(std::string());
GURL next_to_last = test_server_.GetURL(
"server-redirect?" + final_url.spec());
GURL second_url = test_server_.GetURL(
"server-redirect?" + next_to_last.spec());
GURL first_url = test_server_.GetURL(
"client-redirect?" + second_url.spec());
std::vector<GURL> redirects;
// We need the sleep for the client redirects, because it appears as two
// page visits in the browser.
NavigateToURL(first_url);
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
if (!redirects.empty())
break;
}
ASSERT_EQ(3U, redirects.size());
EXPECT_EQ(second_url.spec(), redirects[0].spec());
EXPECT_EQ(next_to_last.spec(), redirects[1].spec());
EXPECT_EQ(final_url.spec(), redirects[2].spec());
}
// Tests that the "#reference" gets preserved across server redirects.
TEST_F(RedirectTest, ServerReference) {
ASSERT_TRUE(test_server_.Start());
const std::string ref("reference");
GURL final_url = test_server_.GetURL(std::string());
GURL initial_url = test_server_.GetURL(
"server-redirect?" + final_url.spec() + "#" + ref);
NavigateToURL(initial_url);
GURL url = GetActiveTabURL();
EXPECT_EQ(ref, url.ref());
}
// Test that redirect from http:// to file:// :
// A) does not crash the browser or confuse the redirect chain, see bug 1080873
// B) does not take place.
TEST_F(RedirectTest, NoHttpToFile) {
ASSERT_TRUE(test_server_.Start());
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("http_to_file.html");
GURL file_url = net::FilePathToFileURL(test_file);
GURL initial_url = test_server_.GetURL(
"client-redirect?" + file_url.spec());
NavigateToURL(initial_url);
// UITest will check for crashes. We make sure the title doesn't match the
// title from the file, because the nav should not have taken place.
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
std::wstring actual_title;
ASSERT_TRUE(tab_proxy->GetTabTitle(&actual_title));
EXPECT_NE("File!", WideToUTF8(actual_title));
}
// Ensures that non-user initiated location changes (within page) are
// flagged as client redirects. See bug 1139823.
TEST_F(RedirectTest, ClientFragments) {
ASSERT_TRUE(test_server_.Start());
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("ref_redirect.html");
GURL first_url = net::FilePathToFileURL(test_file);
std::vector<GURL> redirects;
NavigateToURL(first_url);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
EXPECT_EQ(1U, redirects.size());
EXPECT_EQ(first_url.spec() + "#myanchor", redirects[0].spec());
}
// TODO(timsteele): This is disabled because our current testserver can't
// handle multiple requests in parallel, making it hang on the first request
// to /slow?60. It's unable to serve our second request for files/title2.html
// until /slow? completes, which doesn't give the desired behavior. We could
// alternatively load the second page from disk, but we would need to start
// the browser for this testcase with --process-per-tab, and I don't think
// we can do this at test-case-level granularity at the moment.
// http://crbug.com/45056
TEST_F(RedirectTest,
DISABLED_ClientCancelledByNewNavigationAfterProvisionalLoad) {
// We want to initiate a second navigation after the provisional load for
// the client redirect destination has started, but before this load is
// committed. To achieve this, we tell the browser to load a slow page,
// which causes it to start a provisional load, and while it is waiting
// for the response (which means it hasn't committed the load for the client
// redirect destination page yet), we issue a new navigation request.
ASSERT_TRUE(test_server_.Start());
GURL final_url = test_server_.GetURL("files/title2.html");
GURL slow = test_server_.GetURL("slow?60");
GURL first_url = test_server_.GetURL(
"client-redirect?" + slow.spec());
std::vector<GURL> redirects;
NavigateToURL(first_url);
// We don't sleep here - the first navigation won't have been committed yet
// because we told the server to wait a minute. This means the browser has
// started it's provisional load for the client redirect destination page but
// hasn't completed. Our time is now!
NavigateToURL(final_url);
std::wstring tab_title;
std::wstring final_url_title = UTF8ToWide("Title Of Awesomeness");
// Wait till the final page has been loaded.
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->GetTabTitle(&tab_title));
if (tab_title == final_url_title) {
ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));
break;
}
}
// Check to make sure the navigation did in fact take place and we are
// at the expected page.
EXPECT_EQ(final_url_title, tab_title);
bool final_navigation_not_redirect = true;
// Check to make sure our request for files/title2.html doesn't get flagged
// as a client redirect from the first (/client-redirect?) page.
for (std::vector<GURL>::iterator it = redirects.begin();
it != redirects.end(); ++it) {
if (final_url.spec() == it->spec()) {
final_navigation_not_redirect = false;
break;
}
}
EXPECT_TRUE(final_navigation_not_redirect);
}
} // namespace
<|endoftext|> |
<commit_before>#include "PublishSpriteSheet.h"
#include "SpritePackerProjectFile.h"
#include "SpriteAtlas.h"
#include "PListSerializer.h"
#include <QMessageBox>
#include "PngOptimizer.h"
#include "PVRTexture.h"
#include "PVRTextureUtilities.h"
using namespace pvrtexture;
QMap<QString, QString> PublishSpriteSheet::_formats;
QString imagePrefix(ImageFormat imageFormat) {
switch (imageFormat) {
case kPNG: return ".png";
case kJPG: return ".jpg";
case kPKM: return ".pvr";
case kPVR: return ".pvr";
case kPVR_CCZ: return ".pvr.ccz";
default: return ".png";
}
}
QJSValue jsValue(QJSEngine& engine, const QRect& rect) {
QJSValue value = engine.newObject();
value.setProperty("x", rect.left());
value.setProperty("y", rect.top());
value.setProperty("width", rect.width());
value.setProperty("height", rect.height());
return value;
}
QJSValue jsValue(QJSEngine& engine, const QSize& size) {
QJSValue value = engine.newObject();
value.setProperty("width", size.width());
value.setProperty("height", size.height());
return value;
}
QJSValue jsValue(QJSEngine& engine, const QPoint& point) {
QJSValue value = engine.newObject();
value.setProperty("x", point.x());
value.setProperty("y", point.y());
return value;
}
QJSValue jsValue(QJSEngine& engine, const Triangles& triangles) {
QJSValue value = engine.newObject();
int index = 0;
QJSValue verts = engine.newArray(triangles.verts.size());
for (auto vert: triangles.verts) {
verts.setProperty(index, jsValue(engine, vert));
++index;
}
value.setProperty("verts", verts);
index = 0;
QJSValue indices = engine.newArray(triangles.indices.size());
for (auto idx: triangles.indices) {
indices.setProperty(index, idx);
++index;
}
value.setProperty("indices", indices);
return value;
}
void JSConsole::log(QString msg) {
qDebug() << "js:"<< msg;
}
PublishSpriteSheet::PublishSpriteSheet() {
_imageFormat = kPNG;
_pixelFormat = kARGB8888;
_premultiplied = true;
_jpgQuality = 80;
_trimSpriteNames = true;
_prependSmartFolderName = true;
}
void PublishSpriteSheet::addSpriteSheet(const SpriteAtlas &atlas, const QString &fileName) {
_spriteAtlases.append(atlas);
_fileNames.append(fileName);
}
bool PublishSpriteSheet::publish(const QString& format, bool errorMessage) {
if (_spriteAtlases.size() != _fileNames.size()) {
return false;
}
QStringList outputFilePaths;
for (int i = 0; i < _spriteAtlases.size(); i++) {
const SpriteAtlas& atlas = _spriteAtlases.at(i);
const QString& filePath = _fileNames.at(i);
for (int n=0; n<atlas.outputData().size(); ++n) {
const auto& outputData = atlas.outputData().at(n);
QString outputFilePath = filePath;
if (outputFilePath.contains("{n}")) {
outputFilePath.replace("{n}", QString::number(n));
} else if (outputFilePath.contains("{n1}")) {
outputFilePath.replace("{n1}", QString::number(n + 1));
} else if (atlas.outputData().size() > 1) {
outputFilePath = outputFilePath + "_" + QString::number(n);
}
// save this name for optimize png
outputFilePaths.push_back(outputFilePath);
// generate the data file and the image
if (!generateDataFile(outputFilePath, format, outputData._spriteFrames, outputData._atlasImage, errorMessage)) {
return false;
}
// save image
qDebug() << "Save image:" << outputFilePath + imagePrefix(_imageFormat);
if ((_imageFormat == kPNG) || (_imageFormat == kJPG) || (_imageFormat == kJPG_PNG)) {
QImage image = convertImage(outputData._atlasImage, _pixelFormat, _premultiplied);
if (_imageFormat == kPNG) {
QImageWriter writer(outputFilePath + imagePrefix(kPNG), "png");
writer.setOptimizedWrite(true);
writer.setCompression(100);
writer.setQuality(0);
writer.write(image);
} else if ((_imageFormat == kJPG) || (_imageFormat == kJPG_PNG)) {
QImageWriter writer(outputFilePath + imagePrefix(kJPG), "jpg");
writer.setOptimizedWrite(true);
writer.setCompression(100);
writer.setQuality(_jpgQuality);
writer.write(image);
if (_imageFormat == kJPG_PNG) {
QImage maskImage = convertImage(outputData._atlasImage, kALPHA, _premultiplied);
QImageWriter writer(outputFilePath + imagePrefix(kPNG), "png");
writer.setOptimizedWrite(true);
writer.setCompression(100);
writer.setQuality(0);
writer.write(maskImage);
}
}
} else if ((_imageFormat == kPKM) || (_imageFormat == kPVR) || (_imageFormat == kPVR_CCZ)) {
CPVRTextureHeader pvrHeader(PVRStandard8PixelType.PixelTypeID, outputData._atlasImage.width(), outputData._atlasImage.height());
// create the texture
CPVRTexture pvrTexture(pvrHeader, outputData._atlasImage.bits());
switch (_pixelFormat) {
case kETC1: Transcode(pvrTexture, ePVRTPF_ETC1, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC2: Transcode(pvrTexture, ePVRTPF_PVRTCI_2bpp_RGB, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC2A: Transcode(pvrTexture, ePVRTPF_PVRTCI_2bpp_RGBA, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC4: Transcode(pvrTexture, ePVRTPF_PVRTCI_4bpp_RGB, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC4A: Transcode(pvrTexture, ePVRTPF_PVRTCI_4bpp_RGBA, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
default: Transcode(pvrTexture, ePVRTPF_ETC1, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
}
// save the file
if (_imageFormat == kPVR_CCZ) {
//TODO: use qCompress
} else {
pvrTexture.saveFile((outputFilePath + imagePrefix(_imageFormat)).toStdString().c_str());
}
}
}
}
if ((_imageFormat == kPNG) && (_pngQuality.optMode != "None")) {
qDebug() << "Begin optimize image...";
// we use values 1-7 so that it is more user friendly, because 0 also means optimization.
optimizePNGInThread(outputFilePaths, _pngQuality.optMode, _pngQuality.optLevel - 1);
}
_spriteAtlases.clear();
_fileNames.clear();
return true;
}
bool PublishSpriteSheet::generateDataFile(const QString& filePath, const QString& format, const QMap<QString, SpriteFrameInfo>& spriteFrames, const QImage& atlasImage, bool errorMessage) {
QJSEngine engine;
auto it_format = _formats.find(format);
if (it_format == _formats.end()) {
QString errorString = QString("Not found script file for [%1] format").arg(format);
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
}
QString scriptFileName = it_format.value();
QFile scriptFile(scriptFileName);
if (!scriptFile.open(QIODevice::ReadOnly)) {
qDebug() << "File [" << scriptFileName << "] not found!";
return false;
}
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
// add console object
JSConsole console;
QJSValue consoleObj = engine.newQObject(&console);
engine.globalObject().setProperty("console", consoleObj);
// evaluate export plugin script
qDebug() << "Run script...";
QJSValue result = engine.evaluate(contents);
if (result.isError()) {
QString errorString = "Uncaught exception at line " + result.property("lineNumber").toString() + " : " + result.toString();
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
}
if (engine.globalObject().hasOwnProperty("exportSpriteSheet")) {
QJSValueList args;
args << QJSValue(filePath);
if (_imageFormat == kJPG_PNG) {
QJSValue imageFilePathsValue = engine.newObject();
imageFilePathsValue.setProperty("rgb", QJSValue(filePath + imagePrefix(kJPG)));
imageFilePathsValue.setProperty("mask", QJSValue(filePath + imagePrefix(kPNG)));
args << imageFilePathsValue;
} else {
args << QJSValue(filePath + imagePrefix(_imageFormat));
}
// collect sprite frames
QJSValue spriteFramesValue = engine.newObject();
auto it_f = spriteFrames.cbegin();
for (; it_f != spriteFrames.cend(); ++it_f) {
QJSValue spriteFrameValue = engine.newObject();
spriteFrameValue.setProperty("frame", jsValue(engine, it_f.value().frame));
spriteFrameValue.setProperty("offset", jsValue(engine, it_f.value().offset));
spriteFrameValue.setProperty("rotated", it_f.value().rotated);
spriteFrameValue.setProperty("sourceColorRect", jsValue(engine, it_f.value().sourceColorRect));
spriteFrameValue.setProperty("sourceSize", jsValue(engine, it_f.value().sourceSize));
spriteFrameValue.setProperty("triangles", jsValue(engine, it_f.value().triangles));
QString name = it_f.key();
// remove root folder if needed
if (!_prependSmartFolderName) {
auto idx = name.indexOf('/');
if (idx != -1) {
name = name.right(name.length() - idx - 1);
}
}
if (_trimSpriteNames) {
name = QFileInfo(name).path() + QDir::separator() + QFileInfo(name).baseName();
}
spriteFramesValue.setProperty(name, spriteFrameValue);
}
args << QJSValue(spriteFramesValue);
args << jsValue(engine, atlasImage.size());
// run export
QJSValue exportSpriteSheet = engine.globalObject().property("exportSpriteSheet");
result = exportSpriteSheet.call(args);
if (result.isError()) {
QString errorString = "Uncaught exception at line " + result.property("lineNumber").toString() + " : " + result.toString();
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
} else {
// write data
if (!result.hasProperty("data") || !result.hasProperty("format")) {
QString errorString = "Script function must be return object: {data:data, format:'plist|json|other'}";
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
} else {
QJSValue data = result.property("data");
QString format = result.property("format").toString();
QFile file(filePath + "." + format);
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
if (format == "plist") {
out << PListSerializer::toPList(data.toVariant());
} else {
out << data.toString();
}
}
}
} else {
qDebug() << "Not found global exportSpriteSheet function!";
if (errorMessage) QMessageBox::critical(NULL, "Export script error", "Not found global exportSpriteSheet function!");
return false;
}
return true;
}
bool PublishSpriteSheet::optimizePNG(const QString& fileName, const QString& optMode, int optLevel) {
bool result = false;
if (optMode == "Lossless") {
OptiPngOptimizer optimizer(optLevel);
_mutex.lock();
result = optimizer.optimizeFile(fileName + ".png");
_mutex.unlock();
} else if (optMode == "Lossy") {
PngQuantOptimizer optimizer(optLevel);
_mutex.lock();
result = optimizer.optimizeFile(fileName + ".png");
_mutex.unlock();
}
return result;
}
void PublishSpriteSheet::optimizePNGInThread(QStringList fileNames, const QString& optMode, int optLevel) {
QObject::connect(&_watcher, SIGNAL(finished()), this, SIGNAL(onCompletedOptimizePNG()));
QFuture<bool> resultFuture;
for (const QString& fileName : fileNames) {
resultFuture = QtConcurrent::run(this, &PublishSpriteSheet::optimizePNG, fileName, optMode, optLevel);
}
_watcher.setFuture(resultFuture);
}
<commit_msg>fix windows separator in spriteframe names<commit_after>#include "PublishSpriteSheet.h"
#include "SpritePackerProjectFile.h"
#include "SpriteAtlas.h"
#include "PListSerializer.h"
#include <QMessageBox>
#include "PngOptimizer.h"
#include "PVRTexture.h"
#include "PVRTextureUtilities.h"
using namespace pvrtexture;
QMap<QString, QString> PublishSpriteSheet::_formats;
QString imagePrefix(ImageFormat imageFormat) {
switch (imageFormat) {
case kPNG: return ".png";
case kJPG: return ".jpg";
case kPKM: return ".pvr";
case kPVR: return ".pvr";
case kPVR_CCZ: return ".pvr.ccz";
default: return ".png";
}
}
QJSValue jsValue(QJSEngine& engine, const QRect& rect) {
QJSValue value = engine.newObject();
value.setProperty("x", rect.left());
value.setProperty("y", rect.top());
value.setProperty("width", rect.width());
value.setProperty("height", rect.height());
return value;
}
QJSValue jsValue(QJSEngine& engine, const QSize& size) {
QJSValue value = engine.newObject();
value.setProperty("width", size.width());
value.setProperty("height", size.height());
return value;
}
QJSValue jsValue(QJSEngine& engine, const QPoint& point) {
QJSValue value = engine.newObject();
value.setProperty("x", point.x());
value.setProperty("y", point.y());
return value;
}
QJSValue jsValue(QJSEngine& engine, const Triangles& triangles) {
QJSValue value = engine.newObject();
int index = 0;
QJSValue verts = engine.newArray(triangles.verts.size());
for (auto vert: triangles.verts) {
verts.setProperty(index, jsValue(engine, vert));
++index;
}
value.setProperty("verts", verts);
index = 0;
QJSValue indices = engine.newArray(triangles.indices.size());
for (auto idx: triangles.indices) {
indices.setProperty(index, idx);
++index;
}
value.setProperty("indices", indices);
return value;
}
void JSConsole::log(QString msg) {
qDebug() << "js:"<< msg;
}
PublishSpriteSheet::PublishSpriteSheet() {
_imageFormat = kPNG;
_pixelFormat = kARGB8888;
_premultiplied = true;
_jpgQuality = 80;
_trimSpriteNames = true;
_prependSmartFolderName = true;
}
void PublishSpriteSheet::addSpriteSheet(const SpriteAtlas &atlas, const QString &fileName) {
_spriteAtlases.append(atlas);
_fileNames.append(fileName);
}
bool PublishSpriteSheet::publish(const QString& format, bool errorMessage) {
if (_spriteAtlases.size() != _fileNames.size()) {
return false;
}
QStringList outputFilePaths;
for (int i = 0; i < _spriteAtlases.size(); i++) {
const SpriteAtlas& atlas = _spriteAtlases.at(i);
const QString& filePath = _fileNames.at(i);
for (int n=0; n<atlas.outputData().size(); ++n) {
const auto& outputData = atlas.outputData().at(n);
QString outputFilePath = filePath;
if (outputFilePath.contains("{n}")) {
outputFilePath.replace("{n}", QString::number(n));
} else if (outputFilePath.contains("{n1}")) {
outputFilePath.replace("{n1}", QString::number(n + 1));
} else if (atlas.outputData().size() > 1) {
outputFilePath = outputFilePath + "_" + QString::number(n);
}
// save this name for optimize png
outputFilePaths.push_back(outputFilePath);
// generate the data file and the image
if (!generateDataFile(outputFilePath, format, outputData._spriteFrames, outputData._atlasImage, errorMessage)) {
return false;
}
// save image
qDebug() << "Save image:" << outputFilePath + imagePrefix(_imageFormat);
if ((_imageFormat == kPNG) || (_imageFormat == kJPG) || (_imageFormat == kJPG_PNG)) {
QImage image = convertImage(outputData._atlasImage, _pixelFormat, _premultiplied);
if (_imageFormat == kPNG) {
QImageWriter writer(outputFilePath + imagePrefix(kPNG), "png");
writer.setOptimizedWrite(true);
writer.setCompression(100);
writer.setQuality(0);
writer.write(image);
} else if ((_imageFormat == kJPG) || (_imageFormat == kJPG_PNG)) {
QImageWriter writer(outputFilePath + imagePrefix(kJPG), "jpg");
writer.setOptimizedWrite(true);
writer.setCompression(100);
writer.setQuality(_jpgQuality);
writer.write(image);
if (_imageFormat == kJPG_PNG) {
QImage maskImage = convertImage(outputData._atlasImage, kALPHA, _premultiplied);
QImageWriter writer(outputFilePath + imagePrefix(kPNG), "png");
writer.setOptimizedWrite(true);
writer.setCompression(100);
writer.setQuality(0);
writer.write(maskImage);
}
}
} else if ((_imageFormat == kPKM) || (_imageFormat == kPVR) || (_imageFormat == kPVR_CCZ)) {
CPVRTextureHeader pvrHeader(PVRStandard8PixelType.PixelTypeID, outputData._atlasImage.width(), outputData._atlasImage.height());
// create the texture
CPVRTexture pvrTexture(pvrHeader, outputData._atlasImage.bits());
switch (_pixelFormat) {
case kETC1: Transcode(pvrTexture, ePVRTPF_ETC1, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC2: Transcode(pvrTexture, ePVRTPF_PVRTCI_2bpp_RGB, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC2A: Transcode(pvrTexture, ePVRTPF_PVRTCI_2bpp_RGBA, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC4: Transcode(pvrTexture, ePVRTPF_PVRTCI_4bpp_RGB, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
case kPVRTC4A: Transcode(pvrTexture, ePVRTPF_PVRTCI_4bpp_RGBA, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
default: Transcode(pvrTexture, ePVRTPF_ETC1, ePVRTVarTypeUnsignedByteNorm, ePVRTCSpacelRGB); break;
}
// save the file
if (_imageFormat == kPVR_CCZ) {
//TODO: use qCompress
} else {
pvrTexture.saveFile((outputFilePath + imagePrefix(_imageFormat)).toStdString().c_str());
}
}
}
}
if ((_imageFormat == kPNG) && (_pngQuality.optMode != "None")) {
qDebug() << "Begin optimize image...";
// we use values 1-7 so that it is more user friendly, because 0 also means optimization.
optimizePNGInThread(outputFilePaths, _pngQuality.optMode, _pngQuality.optLevel - 1);
}
_spriteAtlases.clear();
_fileNames.clear();
return true;
}
bool PublishSpriteSheet::generateDataFile(const QString& filePath, const QString& format, const QMap<QString, SpriteFrameInfo>& spriteFrames, const QImage& atlasImage, bool errorMessage) {
QJSEngine engine;
auto it_format = _formats.find(format);
if (it_format == _formats.end()) {
QString errorString = QString("Not found script file for [%1] format").arg(format);
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
}
QString scriptFileName = it_format.value();
QFile scriptFile(scriptFileName);
if (!scriptFile.open(QIODevice::ReadOnly)) {
qDebug() << "File [" << scriptFileName << "] not found!";
return false;
}
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
// add console object
JSConsole console;
QJSValue consoleObj = engine.newQObject(&console);
engine.globalObject().setProperty("console", consoleObj);
// evaluate export plugin script
qDebug() << "Run script...";
QJSValue result = engine.evaluate(contents);
if (result.isError()) {
QString errorString = "Uncaught exception at line " + result.property("lineNumber").toString() + " : " + result.toString();
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
}
if (engine.globalObject().hasOwnProperty("exportSpriteSheet")) {
QJSValueList args;
args << QJSValue(filePath);
if (_imageFormat == kJPG_PNG) {
QJSValue imageFilePathsValue = engine.newObject();
imageFilePathsValue.setProperty("rgb", QJSValue(filePath + imagePrefix(kJPG)));
imageFilePathsValue.setProperty("mask", QJSValue(filePath + imagePrefix(kPNG)));
args << imageFilePathsValue;
} else {
args << QJSValue(filePath + imagePrefix(_imageFormat));
}
// collect sprite frames
QJSValue spriteFramesValue = engine.newObject();
auto it_f = spriteFrames.cbegin();
for (; it_f != spriteFrames.cend(); ++it_f) {
QJSValue spriteFrameValue = engine.newObject();
spriteFrameValue.setProperty("frame", jsValue(engine, it_f.value().frame));
spriteFrameValue.setProperty("offset", jsValue(engine, it_f.value().offset));
spriteFrameValue.setProperty("rotated", it_f.value().rotated);
spriteFrameValue.setProperty("sourceColorRect", jsValue(engine, it_f.value().sourceColorRect));
spriteFrameValue.setProperty("sourceSize", jsValue(engine, it_f.value().sourceSize));
spriteFrameValue.setProperty("triangles", jsValue(engine, it_f.value().triangles));
QString name = it_f.key();
// remove root folder if needed
if (!_prependSmartFolderName) {
auto idx = name.indexOf('/');
if (idx != -1) {
name = name.right(name.length() - idx - 1);
}
}
if (_trimSpriteNames) {
name = QDir::fromNativeSeparators(QFileInfo(name).path() + QDir::separator() + QFileInfo(name).baseName());
}
spriteFramesValue.setProperty(name, spriteFrameValue);
}
args << QJSValue(spriteFramesValue);
args << jsValue(engine, atlasImage.size());
// run export
QJSValue exportSpriteSheet = engine.globalObject().property("exportSpriteSheet");
result = exportSpriteSheet.call(args);
if (result.isError()) {
QString errorString = "Uncaught exception at line " + result.property("lineNumber").toString() + " : " + result.toString();
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
} else {
// write data
if (!result.hasProperty("data") || !result.hasProperty("format")) {
QString errorString = "Script function must be return object: {data:data, format:'plist|json|other'}";
qDebug() << errorString;
if (errorMessage) QMessageBox::critical(NULL, "Export script error", errorString);
return false;
} else {
QJSValue data = result.property("data");
QString format = result.property("format").toString();
QFile file(filePath + "." + format);
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
if (format == "plist") {
out << PListSerializer::toPList(data.toVariant());
} else {
out << data.toString();
}
}
}
} else {
qDebug() << "Not found global exportSpriteSheet function!";
if (errorMessage) QMessageBox::critical(NULL, "Export script error", "Not found global exportSpriteSheet function!");
return false;
}
return true;
}
bool PublishSpriteSheet::optimizePNG(const QString& fileName, const QString& optMode, int optLevel) {
bool result = false;
if (optMode == "Lossless") {
OptiPngOptimizer optimizer(optLevel);
_mutex.lock();
result = optimizer.optimizeFile(fileName + ".png");
_mutex.unlock();
} else if (optMode == "Lossy") {
PngQuantOptimizer optimizer(optLevel);
_mutex.lock();
result = optimizer.optimizeFile(fileName + ".png");
_mutex.unlock();
}
return result;
}
void PublishSpriteSheet::optimizePNGInThread(QStringList fileNames, const QString& optMode, int optLevel) {
QObject::connect(&_watcher, SIGNAL(finished()), this, SIGNAL(onCompletedOptimizePNG()));
QFuture<bool> resultFuture;
for (const QString& fileName : fileNames) {
resultFuture = QtConcurrent::run(this, &PublishSpriteSheet::optimizePNG, fileName, optMode, optLevel);
}
_watcher.setFuture(resultFuture);
}
<|endoftext|> |
<commit_before>// Copyright 2022 The gRPC 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 <grpc/support/port_platform.h>
#include <deque>
#include "absl/container/flat_hash_map.h"
#include "src/core/lib/event_engine/common_closures.h"
#include "src/core/lib/event_engine/work_queue.h"
#include "src/libfuzzer/libfuzzer_macro.h"
#include "test/core/event_engine/work_queue/work_queue_fuzzer.pb.h"
bool squelch = true;
bool leak_check = true;
namespace grpc_event_engine {
namespace experimental {
class WorkQueueFuzzer {
public:
WorkQueueFuzzer() { CheckEqual(); };
~WorkQueueFuzzer() { CheckEqual(); };
void Run(const work_queue_fuzzer::Action& action) {
switch (action.action_type_case()) {
case work_queue_fuzzer::Action::kAdd: {
if (action.add().type() == work_queue_fuzzer::CALLBACK_TYPE_CLOSURE) {
work_queue_.Add(CreateClosure(action.add().key()));
deque_.push_back(CreateClosure(action.add().key()));
} else {
work_queue_.Add(CreateInvocable(action.add().key()));
deque_.push_back(CreateClosureWrappedInvocable(action.add().key()));
}
} break;
case work_queue_fuzzer::Action::kPopFront: {
// pop front closures, executing both to check they are a pair
auto* wq_c = work_queue_.PopFront();
if (wq_c == nullptr) {
if (!work_queue_.Empty() || !deque_.empty()) abort();
} else {
auto* dq_c = deque_.front();
deque_.pop_front();
wq_c->Run();
dq_c->Run();
}
} break;
case work_queue_fuzzer::Action::kPopBack: {
// pop back closures, executing both to check they are a pair
auto* wq_c = work_queue_.PopBack();
if (wq_c == nullptr) {
if (!work_queue_.Empty() || !deque_.empty()) abort();
} else {
auto* dq_c = deque_.back();
deque_.pop_back();
wq_c->Run();
dq_c->Run();
}
} break;
case work_queue_fuzzer::Action::kEmpty: {
if (work_queue_.Empty() != deque_.empty()) abort();
} break;
case work_queue_fuzzer::Action::ACTION_TYPE_NOT_SET:
break;
};
}
private:
EventEngine::Closure* CreateClosure(int key) {
return SelfDeletingClosure::Create([key, this] {
if (last_executed_key_.has_value()) {
if (*last_executed_key_ != key) abort();
last_executed_key_.reset();
} else {
last_executed_key_ = key;
}
});
}
absl::AnyInvocable<void()> CreateInvocable(int key) {
return absl::AnyInvocable<void()>([key, this] {
if (last_executed_key_.has_value()) {
if (*last_executed_key_ != key) abort();
last_executed_key_.reset();
} else {
last_executed_key_ = key;
}
});
}
EventEngine::Closure* CreateClosureWrappedInvocable(int key) {
auto invocable = CreateInvocable(key);
return SelfDeletingClosure::Create(
[invocable = std::move(invocable)]() mutable { invocable(); });
}
void CheckEqual() {
while (auto* wq_c = work_queue_.PopBack()) {
if (deque_.empty()) abort();
auto* dq_c = deque_.back();
deque_.pop_back();
wq_c->Run();
dq_c->Run();
}
}
WorkQueue work_queue_;
std::deque<EventEngine::Closure*> deque_;
// Closures are always added in pairs and checked in paris.
// When checking, each popped closure encounters one of these situations:
// A) it is the first of a pair, denoted by an empty last_executed_key_, so
// it sets last_executed_key_ to its own key.
// B) last_executed_key_ is set, so its value must match this closure's own
// key to assert that it is the other part of the pair. last_executed_key_
// is then reset.
absl::optional<int> last_executed_key_;
};
} // namespace experimental
} // namespace grpc_event_engine
DEFINE_PROTO_FUZZER(const work_queue_fuzzer::Msg& msg) {
for (const auto& action : msg.actions()) {
grpc_event_engine::experimental::WorkQueueFuzzer().Run(action);
}
}
<commit_msg>small test cleanup (#31137)<commit_after>// Copyright 2022 The gRPC 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 <grpc/support/port_platform.h>
#include <deque>
#include "absl/container/flat_hash_map.h"
#include "src/core/lib/event_engine/common_closures.h"
#include "src/core/lib/event_engine/work_queue.h"
#include "src/libfuzzer/libfuzzer_macro.h"
#include "test/core/event_engine/work_queue/work_queue_fuzzer.pb.h"
bool squelch = true;
bool leak_check = true;
namespace grpc_event_engine {
namespace experimental {
class WorkQueueFuzzer {
public:
WorkQueueFuzzer() { CheckEqual(); }
~WorkQueueFuzzer() { CheckEqual(); }
void Run(const work_queue_fuzzer::Action& action) {
switch (action.action_type_case()) {
case work_queue_fuzzer::Action::kAdd: {
if (action.add().type() == work_queue_fuzzer::CALLBACK_TYPE_CLOSURE) {
work_queue_.Add(CreateClosure(action.add().key()));
deque_.push_back(CreateClosure(action.add().key()));
} else {
work_queue_.Add(CreateInvocable(action.add().key()));
deque_.push_back(CreateClosureWrappedInvocable(action.add().key()));
}
} break;
case work_queue_fuzzer::Action::kPopFront: {
// pop front closures, executing both to check they are a pair
auto* wq_c = work_queue_.PopFront();
if (wq_c == nullptr) {
if (!work_queue_.Empty() || !deque_.empty()) abort();
} else {
auto* dq_c = deque_.front();
deque_.pop_front();
wq_c->Run();
dq_c->Run();
}
} break;
case work_queue_fuzzer::Action::kPopBack: {
// pop back closures, executing both to check they are a pair
auto* wq_c = work_queue_.PopBack();
if (wq_c == nullptr) {
if (!work_queue_.Empty() || !deque_.empty()) abort();
} else {
auto* dq_c = deque_.back();
deque_.pop_back();
wq_c->Run();
dq_c->Run();
}
} break;
case work_queue_fuzzer::Action::kEmpty: {
if (work_queue_.Empty() != deque_.empty()) abort();
} break;
case work_queue_fuzzer::Action::ACTION_TYPE_NOT_SET:
break;
}
}
private:
EventEngine::Closure* CreateClosure(int key) {
return SelfDeletingClosure::Create([key, this] {
if (last_executed_key_.has_value()) {
if (*last_executed_key_ != key) abort();
last_executed_key_.reset();
} else {
last_executed_key_ = key;
}
});
}
absl::AnyInvocable<void()> CreateInvocable(int key) {
return absl::AnyInvocable<void()>([key, this] {
if (last_executed_key_.has_value()) {
if (*last_executed_key_ != key) abort();
last_executed_key_.reset();
} else {
last_executed_key_ = key;
}
});
}
EventEngine::Closure* CreateClosureWrappedInvocable(int key) {
auto invocable = CreateInvocable(key);
return SelfDeletingClosure::Create(
[invocable = std::move(invocable)]() mutable { invocable(); });
}
void CheckEqual() {
while (auto* wq_c = work_queue_.PopBack()) {
if (deque_.empty()) abort();
auto* dq_c = deque_.back();
deque_.pop_back();
wq_c->Run();
dq_c->Run();
}
}
WorkQueue work_queue_;
std::deque<EventEngine::Closure*> deque_;
// Closures are always added in pairs and checked in paris.
// When checking, each popped closure encounters one of these situations:
// A) it is the first of a pair, denoted by an empty last_executed_key_, so
// it sets last_executed_key_ to its own key.
// B) last_executed_key_ is set, so its value must match this closure's own
// key to assert that it is the other part of the pair. last_executed_key_
// is then reset.
absl::optional<int> last_executed_key_;
};
} // namespace experimental
} // namespace grpc_event_engine
DEFINE_PROTO_FUZZER(const work_queue_fuzzer::Msg& msg) {
for (const auto& action : msg.actions()) {
grpc_event_engine::experimental::WorkQueueFuzzer().Run(action);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basedlgs.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 21:16:29 $
*
* 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 _BASEDLGS_HXX
#define _BASEDLGS_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _FLOATWIN_HXX //autogen
#include <vcl/floatwin.hxx>
#endif
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
class SfxTabPage;
class SfxBindings;
class SfxChildWindow;
struct SfxChildWinInfo;
class SfxItemSet;
class SfxItemPool;
class OKButton;
class CancelButton;
class HelpButton;
class Button;
// class SfxModalDefParentHelper -----------------------------------------
class SfxModalDefParentHelper
{
private:
Window *pOld;
public:
SfxModalDefParentHelper(Window* pWindow);
~SfxModalDefParentHelper();
};
// class SfxModalDialog --------------------------------------------------
class SFX2_DLLPUBLIC SfxModalDialog: public ModalDialog
{
sal_uInt32 nUniqId;
String aExtraData;
Timer aTimer;
SAL_DLLPRIVATE SfxModalDialog(SfxModalDialog &); // not defined
SAL_DLLPRIVATE void operator =(SfxModalDialog &); // not defined
//#if 0 // _SOLAR__PRIVATE
DECL_DLLPRIVATE_LINK( TimerHdl_Impl, Timer* );
//#endif
SAL_DLLPRIVATE void SetDialogData_Impl();
SAL_DLLPRIVATE void GetDialogData_Impl();
SAL_DLLPRIVATE void init();
protected:
SfxModalDialog(Window *pParent, const ResId &);
SfxModalDialog(Window* pParent, sal_uInt32 nUniqueId,
WinBits nWinStyle = WB_STDMODAL);
~SfxModalDialog();
String& GetExtraData() { return aExtraData; }
sal_uInt32 GetUniqId() const { return nUniqId; }
};
// class SfxModelessDialog --------------------------------------------------
class SfxModelessDialog_Impl;
class SFX2_DLLPUBLIC SfxModelessDialog: public ModelessDialog
{
SfxBindings* pBindings;
Size aSize;
SfxModelessDialog_Impl* pImp;
SAL_DLLPRIVATE SfxModelessDialog(SfxModelessDialog &); // not defined
SAL_DLLPRIVATE void operator =(SfxModelessDialog &); // not defined
protected:
SfxModelessDialog( SfxBindings*, SfxChildWindow*,
Window*, const ResId& );
SfxModelessDialog( SfxBindings*, SfxChildWindow*,
Window*, WinBits nWinStyle = WB_STDMODELESS );
~SfxModelessDialog();
virtual BOOL Close();
virtual void Resize();
virtual void Move();
virtual void StateChanged( StateChangedType nStateChange );
public:
virtual void FillInfo(SfxChildWinInfo&) const;
void Initialize (SfxChildWinInfo* pInfo);
virtual long Notify( NotifyEvent& rNEvt );
SfxBindings& GetBindings()
{ return *pBindings; }
};
// class SfxFloatingWindow --------------------------------------------------
class SfxFloatingWindow_Impl;
class SFX2_DLLPUBLIC SfxFloatingWindow: public FloatingWindow
{
SfxBindings* pBindings;
Size aSize;
SfxFloatingWindow_Impl* pImp;
SAL_DLLPRIVATE SfxFloatingWindow(SfxFloatingWindow &); // not defined
SAL_DLLPRIVATE void operator =(SfxFloatingWindow &); // not defined
protected:
SfxFloatingWindow( SfxBindings *pBindings,
SfxChildWindow *pCW,
Window* pParent,
WinBits nWinBits=WB_STDMODELESS);
SfxFloatingWindow( SfxBindings *pBindings,
SfxChildWindow *pCW,
Window* pParent,
const ResId& rResId);
~SfxFloatingWindow();
virtual void StateChanged( StateChangedType nStateChange );
virtual BOOL Close();
virtual void Resize();
virtual void Move();
virtual long Notify( NotifyEvent& rNEvt );
SfxBindings& GetBindings()
{ return *pBindings; }
public:
virtual void FillInfo(SfxChildWinInfo&) const;
void Initialize (SfxChildWinInfo* pInfo);
};
// class SfxSingleTabDialog --------------------------------------------------
typedef USHORT* (*GetTabPageRanges)(); // liefert internationale Which-Werte
class SFX2_DLLPUBLIC SfxSingleTabDialog : public SfxModalDialog
{
public:
SfxSingleTabDialog( Window* pParent, const SfxItemSet& rOptionsSet, USHORT nUniqueId );
SfxSingleTabDialog( Window* pParent, USHORT nUniqueId, const SfxItemSet* pInSet = 0 );
virtual ~SfxSingleTabDialog();
void SetTabPage( SfxTabPage* pTabPage,
GetTabPageRanges pRangesFunc = 0 );
SfxTabPage* GetTabPage() const { return pPage; }
// liefert ggf. per Map konvertierte lokale Slots
const USHORT* GetInputRanges( const SfxItemPool& rPool );
void SetInputSet( const SfxItemSet* pInSet )
{ pOptions = pInSet; }
const SfxItemSet* GetOutputItemSet() const { return pOutSet; }
OKButton* GetOKButton() const { return pOKBtn; }
CancelButton* GetCancelButton() const { return pCancelBtn; }
private:
GetTabPageRanges fnGetRanges; // Pointer auf die Ranges-Funktion
USHORT* pRanges;
OKButton* pOKBtn;
CancelButton* pCancelBtn;
HelpButton* pHelpBtn;
SfxTabPage* pPage;
const SfxItemSet* pOptions;
SfxItemSet* pOutSet;
//#if 0 // _SOLAR__PRIVATE
DECL_DLLPRIVATE_LINK( OKHdl_Impl, Button * );
//#endif
};
#endif
<commit_msg>INTEGRATION: CWS fwk82_SRC680 (1.2.208); FILE MERGED 2008/01/07 14:57:58 cd 1.2.208.1: #i63848# Include modeless dialog class and resize operation into the asynchronous processing of window attribute persistence (Views.xcu)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basedlgs.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2008-01-29 16:27:13 $
*
* 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 _BASEDLGS_HXX
#define _BASEDLGS_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _FLOATWIN_HXX //autogen
#include <vcl/floatwin.hxx>
#endif
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
class SfxTabPage;
class SfxBindings;
class SfxChildWindow;
struct SfxChildWinInfo;
class SfxItemSet;
class SfxItemPool;
class OKButton;
class CancelButton;
class HelpButton;
class Button;
// class SfxModalDefParentHelper -----------------------------------------
class SfxModalDefParentHelper
{
private:
Window *pOld;
public:
SfxModalDefParentHelper(Window* pWindow);
~SfxModalDefParentHelper();
};
// class SfxModalDialog --------------------------------------------------
class SFX2_DLLPUBLIC SfxModalDialog: public ModalDialog
{
sal_uInt32 nUniqId;
String aExtraData;
Timer aTimer;
SAL_DLLPRIVATE SfxModalDialog(SfxModalDialog &); // not defined
SAL_DLLPRIVATE void operator =(SfxModalDialog &); // not defined
//#if 0 // _SOLAR__PRIVATE
DECL_DLLPRIVATE_LINK( TimerHdl_Impl, Timer* );
//#endif
SAL_DLLPRIVATE void SetDialogData_Impl();
SAL_DLLPRIVATE void GetDialogData_Impl();
SAL_DLLPRIVATE void init();
protected:
SfxModalDialog(Window *pParent, const ResId &);
SfxModalDialog(Window* pParent, sal_uInt32 nUniqueId,
WinBits nWinStyle = WB_STDMODAL);
~SfxModalDialog();
String& GetExtraData() { return aExtraData; }
sal_uInt32 GetUniqId() const { return nUniqId; }
};
// class SfxModelessDialog --------------------------------------------------
class SfxModelessDialog_Impl;
class SFX2_DLLPUBLIC SfxModelessDialog: public ModelessDialog
{
SfxBindings* pBindings;
Size aSize;
SfxModelessDialog_Impl* pImp;
SAL_DLLPRIVATE SfxModelessDialog(SfxModelessDialog &); // not defined
SAL_DLLPRIVATE void operator =(SfxModelessDialog &); // not defined
protected:
SfxModelessDialog( SfxBindings*, SfxChildWindow*,
Window*, const ResId& );
SfxModelessDialog( SfxBindings*, SfxChildWindow*,
Window*, WinBits nWinStyle = WB_STDMODELESS );
~SfxModelessDialog();
virtual BOOL Close();
virtual void Resize();
virtual void Move();
virtual void StateChanged( StateChangedType nStateChange );
public:
virtual void FillInfo(SfxChildWinInfo&) const;
void Initialize (SfxChildWinInfo* pInfo);
virtual long Notify( NotifyEvent& rNEvt );
SfxBindings& GetBindings()
{ return *pBindings; }
DECL_LINK( TimerHdl, Timer* );
};
// class SfxFloatingWindow --------------------------------------------------
class SfxFloatingWindow_Impl;
class SFX2_DLLPUBLIC SfxFloatingWindow: public FloatingWindow
{
SfxBindings* pBindings;
Size aSize;
SfxFloatingWindow_Impl* pImp;
SAL_DLLPRIVATE SfxFloatingWindow(SfxFloatingWindow &); // not defined
SAL_DLLPRIVATE void operator =(SfxFloatingWindow &); // not defined
protected:
SfxFloatingWindow( SfxBindings *pBindings,
SfxChildWindow *pCW,
Window* pParent,
WinBits nWinBits=WB_STDMODELESS);
SfxFloatingWindow( SfxBindings *pBindings,
SfxChildWindow *pCW,
Window* pParent,
const ResId& rResId);
~SfxFloatingWindow();
virtual void StateChanged( StateChangedType nStateChange );
virtual BOOL Close();
virtual void Resize();
virtual void Move();
virtual long Notify( NotifyEvent& rNEvt );
SfxBindings& GetBindings()
{ return *pBindings; }
public:
virtual void FillInfo(SfxChildWinInfo&) const;
void Initialize (SfxChildWinInfo* pInfo);
DECL_LINK( TimerHdl, Timer* );
};
// class SfxSingleTabDialog --------------------------------------------------
typedef USHORT* (*GetTabPageRanges)(); // liefert internationale Which-Werte
class SFX2_DLLPUBLIC SfxSingleTabDialog : public SfxModalDialog
{
public:
SfxSingleTabDialog( Window* pParent, const SfxItemSet& rOptionsSet, USHORT nUniqueId );
SfxSingleTabDialog( Window* pParent, USHORT nUniqueId, const SfxItemSet* pInSet = 0 );
virtual ~SfxSingleTabDialog();
void SetTabPage( SfxTabPage* pTabPage,
GetTabPageRanges pRangesFunc = 0 );
SfxTabPage* GetTabPage() const { return pPage; }
// liefert ggf. per Map konvertierte lokale Slots
const USHORT* GetInputRanges( const SfxItemPool& rPool );
void SetInputSet( const SfxItemSet* pInSet )
{ pOptions = pInSet; }
const SfxItemSet* GetOutputItemSet() const { return pOutSet; }
OKButton* GetOKButton() const { return pOKBtn; }
CancelButton* GetCancelButton() const { return pCancelBtn; }
private:
GetTabPageRanges fnGetRanges; // Pointer auf die Ranges-Funktion
USHORT* pRanges;
OKButton* pOKBtn;
CancelButton* pCancelBtn;
HelpButton* pHelpBtn;
SfxTabPage* pPage;
const SfxItemSet* pOptions;
SfxItemSet* pOutSet;
//#if 0 // _SOLAR__PRIVATE
DECL_DLLPRIVATE_LINK( OKHdl_Impl, Button * );
//#endif
};
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <unordered_map>
#include <cstring>
#include <limits>
#include <cmath>
#include <cfloat>
class Tokenizer {
public:
void updateToken(
const char *&text) //Указатель будет сдвигаться. Текст - это ссылка на указатель константной char. Не смогу менять то, что внутри, но указатель смогу.
{
while (const auto c = *text++) {//Когда встретит 0 - остановится. Приоритет выше у инкремента - прибавим сначала, но разыменуем предыдущий указатель
switch (c) {
case ' ':
continue;
case '-':
thisToken = Token::Minus;
return;
case '+':
thisToken = Token::Plus;
return;
case '*':
thisToken = Token::Mul;
return;
case '/':
thisToken = Token::Div;
return;
case '(':
thisToken = Token::LBrace;
return;
case ')':
thisToken = Token::RBrace;
return;
}
if (c >= '0' && c <= '9') {
thisToken = Token::Number;
return;
}
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
thisToken = Token::Const;
return;
}
throw std::runtime_error("Invalid Symbol"); // Вместо return Token::Invalid;
}
thisToken = Token::End;
return;
}
enum class Token {
Minus,
Plus,
Mul,
Div,
Number,
End,
Const,
LBrace,
RBrace
};
Token thisToken;
};
template <class T>
struct Parser
{
};
template <class T>
struct NumericTraits
{
};
template<> struct NumericTraits<double>{
static constexpr double min = std::numeric_limits<double>::min();
static constexpr double max = std::numeric_limits<double>::max();
};
template <>
struct NumericTraits<int>{
static constexpr int min = std::numeric_limits<int>::min();
static constexpr int max = std::numeric_limits<int>::max();
};
template <>
struct NumericTraits<long>{
static constexpr long min = std::numeric_limits<long>::min();
static constexpr long max = std::numeric_limits<long>::max();
};
template<>
struct Parser<int>
{
static bool parse(const char*& text, int& value)
{
long tmp = long(*text - '0');
while (*(++text) >= '0' && *text <= '9') {
tmp = tmp * 10 + long(*text - '0');
}
if(tmp < NumericTraits<int>::min || tmp > NumericTraits<int>::max)
return false;
value = tmp;
return true;
}
static long bigType;
static bool checkType(long &a){
if(a > NumericTraits<int>::max || a < - NumericTraits<int>::max){
return false;
}
return true;
}
};
template<>
struct Parser<long>
{
static bool parse(const char*& text, long& value)
{
long long tmp = (long long)(*text - '0');
while (*(++text) >= '0' && *text <= '9') {
tmp = tmp * 10 + (long long)(*text - '0');
}
if(tmp < NumericTraits<long>::min || tmp > NumericTraits<long>::max)
return false;
value = tmp;
return true;
}
static long long bigType;
static bool checkType(long long &a){
if(a > NumericTraits<long>::max || a < - NumericTraits<long>::max){
return false;
}
return true;
}
};
template<>
struct Parser<double>
{
static bool parse(const char*& text, double& value)
{
long double tmp = (long double)(*text - '0');
while (*(++text) >= '0' && *text <= '9') {
tmp = tmp * 10 + (long double)(*text - '0');
}
if((*text == '.') && (*(++text) >= '0' || *(text) <= '9')){
tmp += (long double)(*text - '0') / 10;
int power = -1;
while (*(++text) >= '0' && *text <= '9') {
--power;
tmp += (long double)(*text - '0') * pow(10.0, power);
}
}
if(!std::isfinite(tmp)){//Требуется, потому что в случае проверки NumericTraits 0.0 не пройдет проверку.
return false;
}
if(tmp > NumericTraits<double>::max){
return false;
}
value = tmp;
return true;
}
static bool checkType(long double &a){
if(!std::isfinite((double)a)){//Требуется, потому что в случае проверки NumericTraits 0.0 не пройдет проверку.
return false;
}
if(a > NumericTraits<double>::max || a < - NumericTraits<double>::max){
return false;
}
return true;
}
static long double bigType;
};
template <class T, class Parser>
class calculator {
public:
calculator(char *&text){
expression = text;
}
calculator(){
}
T calculate(char *&text){
expression = text;
T result = expr(expression);
std::cout << result << std::endl;
return result;
}
/*void setExpr(std::string expr){
//this->expression = expr;
strcpy(this->expression, expr.c_str());
}*/
private:
T prim(const char *&text) {
bool isPositive = true;
thisToken.updateToken(text);
--text;
if (thisToken.thisToken == Tokenizer::Token::Minus) { //Checking if number is positive/negative
isPositive = false;
thisToken.updateToken(++text); //Checking what goes after subtraction symbol
--text;
}
if(thisToken.thisToken == Tokenizer::Token::LBrace){//If there are braces - create loop to calculate expr in braces.
++text;
T c = expr(text, true);
return c * (2 * isPositive - 1);
}
if (thisToken.thisToken == Tokenizer::Token::End) {
return 0;
}
if (thisToken.thisToken == Tokenizer::Token::Const){
int length = 1;
++text ;
while ((*text >= 'A' && *text <= 'Z') || (*text >= 'a' && *text <= 'z')) {
length += 1;
++text;
}
std::string var;
//auto* var = new std::string();
var.assign(text-length, length);
return constants.at(var) * (2 * isPositive - 1);
}
if (thisToken.thisToken != Tokenizer::Token::Number) {
throw std::runtime_error("Syntax error");
}
T c;
if(!Parser::parse(text, c))
throw std::runtime_error ("Syntax error: number can not be read");
return c * (2 * isPositive - 1);
}
T term(const char *&text) {
T c = prim(text);
thisToken.updateToken(text);
while (thisToken.thisToken == Tokenizer::Token::Mul || thisToken.thisToken == Tokenizer::Token::Div) {
decltype(Parser::bigType) test = 0.0;
if (thisToken.thisToken == Tokenizer::Token::Mul) {
test = (decltype(Parser::bigType))c * (decltype(Parser::bigType))prim(text);
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else {
T divider = prim(text);
if (divider) {
test = (decltype(Parser::bigType))c / (decltype(Parser::bigType))divider;
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else throw std::runtime_error("Division by zero");
}
}
--text;
return c;
}
T expr(const char *&text, bool fromPrim = false) {
T c = term(text);
thisToken.updateToken(text);
while (thisToken.thisToken != Tokenizer::Token::End && thisToken.thisToken != Tokenizer::Token::RBrace && thisToken.thisToken != Tokenizer::Token::LBrace) {
decltype(Parser::bigType) test = 0.0;
if (thisToken.thisToken == Tokenizer::Token::Plus) {
test = (decltype(Parser::bigType))c + (decltype(Parser::bigType))term(text);
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else if (thisToken.thisToken == Tokenizer::Token::Minus) {
test = (decltype(Parser::bigType))c - (decltype(Parser::bigType))term(text);
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else
throw std::runtime_error("Syntax error");
}
if (thisToken.thisToken == Tokenizer::Token::LBrace){
throw std::runtime_error("Brace syntax error");
}
if (thisToken.thisToken != Tokenizer::Token::RBrace || fromPrim){
return c;
}
throw std::runtime_error("Brace syntax error");
}
const char* expression;
std::unordered_map<std::string, double> constants =
{
{ "Pi", M_PI },
{ "e", M_E }
};
Tokenizer thisToken;
};
void checkErrors(bool a){
if(!a)
std::cout << "error" << std::endl;
return;
}
bool isEqual(const double &left, const double &right){
return fabs(left - right) < DBL_EPSILON;
}
int main(int argc, char* argv[]) {
/*if(argc<2){
throw std::runtime_error("No input expression");
}
const char* expression = argv[1];
calculator<int,Parser<int>>(expression).calculate();
*/// I do without args/uncomment and use if needed
if(argc>1){
//const char* expression = argv[1];
//calculator<int,Parser<int>>(expression).calculate();
}
char* Expr1 = new char[255];
std::strcpy(Expr1, std::string("3+3").c_str());
char* Expr2 = new char[255];
std::strcpy(Expr2, std::string("9/2*2").c_str());
char* Expr3 = new char[255];
std::strcpy(Expr3, std::string("Pi*-e").c_str());
char* Expr4 = new char[255];
std::strcpy(Expr4, std::string("8*Pi").c_str());
//DOUBLE
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr1),(double)6));
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr2),(double)9));
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr3),(double)-M_PI*M_E));
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr4),(double)M_PI*8));
//INT
checkErrors(calculator<int,Parser<int>>().calculate(Expr1)==6);
checkErrors(calculator<int,Parser<int>>().calculate(Expr2)==8);
checkErrors(calculator<int,Parser<int>>().calculate(Expr3)==-6);
checkErrors(calculator<int,Parser<int>>().calculate(Expr4)==24);
//LONG
checkErrors(calculator<long,Parser<long>>().calculate(Expr1)==6);
checkErrors(calculator<long,Parser<long>>().calculate(Expr2)==8);
checkErrors(calculator<long,Parser<long>>().calculate(Expr3)==-6);
checkErrors(calculator<long,Parser<long>>().calculate(Expr4)==24);
return 0;
}<commit_msg>Fixed memory allocation<commit_after>#include <iostream>
#include <unordered_map>
#include <cstring>
#include <limits>
#include <cmath>
#include <cfloat>
class Tokenizer {
public:
void updateToken(
const char *&text) //Указатель будет сдвигаться. Текст - это ссылка на указатель константной char. Не смогу менять то, что внутри, но указатель смогу.
{
while (const auto c = *text++) {//Когда встретит 0 - остановится. Приоритет выше у инкремента - прибавим сначала, но разыменуем предыдущий указатель
switch (c) {
case ' ':
continue;
case '-':
thisToken = Token::Minus;
return;
case '+':
thisToken = Token::Plus;
return;
case '*':
thisToken = Token::Mul;
return;
case '/':
thisToken = Token::Div;
return;
case '(':
thisToken = Token::LBrace;
return;
case ')':
thisToken = Token::RBrace;
return;
}
if (c >= '0' && c <= '9') {
thisToken = Token::Number;
return;
}
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
thisToken = Token::Const;
return;
}
throw std::runtime_error("Invalid Symbol"); // Вместо return Token::Invalid;
}
thisToken = Token::End;
return;
}
enum class Token {
Minus,
Plus,
Mul,
Div,
Number,
End,
Const,
LBrace,
RBrace
};
Token thisToken;
};
template <class T>
struct Parser
{
};
template <class T>
struct NumericTraits
{
};
template<> struct NumericTraits<double>{
static constexpr double min = std::numeric_limits<double>::min();
static constexpr double max = std::numeric_limits<double>::max();
};
template <>
struct NumericTraits<int>{
static constexpr int min = std::numeric_limits<int>::min();
static constexpr int max = std::numeric_limits<int>::max();
};
template <>
struct NumericTraits<long>{
static constexpr long min = std::numeric_limits<long>::min();
static constexpr long max = std::numeric_limits<long>::max();
};
template<>
struct Parser<int>
{
static bool parse(const char*& text, int& value)
{
long tmp = long(*text - '0');
while (*(++text) >= '0' && *text <= '9') {
tmp = tmp * 10 + long(*text - '0');
}
if(tmp < NumericTraits<int>::min || tmp > NumericTraits<int>::max)
return false;
value = tmp;
return true;
}
static long bigType;
static bool checkType(long &a){
if(a > NumericTraits<int>::max || a < - NumericTraits<int>::max){
return false;
}
return true;
}
};
template<>
struct Parser<long>
{
static bool parse(const char*& text, long& value)
{
long long tmp = (long long)(*text - '0');
while (*(++text) >= '0' && *text <= '9') {
tmp = tmp * 10 + (long long)(*text - '0');
}
if(tmp < NumericTraits<long>::min || tmp > NumericTraits<long>::max)
return false;
value = tmp;
return true;
}
static long long bigType;
static bool checkType(long long &a){
if(a > NumericTraits<long>::max || a < - NumericTraits<long>::max){
return false;
}
return true;
}
};
template<>
struct Parser<double>
{
static bool parse(const char*& text, double& value)
{
long double tmp = (long double)(*text - '0');
while (*(++text) >= '0' && *text <= '9') {
tmp = tmp * 10 + (long double)(*text - '0');
}
if((*text == '.') && (*(++text) >= '0' || *(text) <= '9')){
tmp += (long double)(*text - '0') / 10;
int power = -1;
while (*(++text) >= '0' && *text <= '9') {
--power;
tmp += (long double)(*text - '0') * pow(10.0, power);
}
}
if(!std::isfinite(tmp)){//Требуется, потому что в случае проверки NumericTraits 0.0 не пройдет проверку.
return false;
}
if(tmp > NumericTraits<double>::max){
return false;
}
value = tmp;
return true;
}
static bool checkType(long double &a){
if(!std::isfinite((double)a)){//Требуется, потому что в случае проверки NumericTraits 0.0 не пройдет проверку.
return false;
}
if(a > NumericTraits<double>::max || a < - NumericTraits<double>::max){
return false;
}
return true;
}
static long double bigType;
};
template <class T, class Parser>
class calculator {
public:
calculator(char *&text){
expression = text;
}
calculator(){
}
T calculate(char *&text){
expression = text;
T result = expr(expression);
std::cout << result << std::endl;
return result;
}
/*void setExpr(std::string expr){
//this->expression = expr;
strcpy(this->expression, expr.c_str());
}*/
private:
T prim(const char *&text) {
bool isPositive = true;
thisToken.updateToken(text);
--text;
if (thisToken.thisToken == Tokenizer::Token::Minus) { //Checking if number is positive/negative
isPositive = false;
thisToken.updateToken(++text); //Checking what goes after subtraction symbol
--text;
}
if(thisToken.thisToken == Tokenizer::Token::LBrace){//If there are braces - create loop to calculate expr in braces.
++text;
T c = expr(text, true);
return c * (2 * isPositive - 1);
}
if (thisToken.thisToken == Tokenizer::Token::End) {
return 0;
}
if (thisToken.thisToken == Tokenizer::Token::Const){
int length = 1;
++text ;
while ((*text >= 'A' && *text <= 'Z') || (*text >= 'a' && *text <= 'z')) {
length += 1;
++text;
}
std::string var;
//auto* var = new std::string();
var.assign(text-length, length);
return constants.at(var) * (2 * isPositive - 1);
}
if (thisToken.thisToken != Tokenizer::Token::Number) {
throw std::runtime_error("Syntax error");
}
T c;
if(!Parser::parse(text, c))
throw std::runtime_error ("Syntax error: number can not be read");
return c * (2 * isPositive - 1);
}
T term(const char *&text) {
T c = prim(text);
thisToken.updateToken(text);
while (thisToken.thisToken == Tokenizer::Token::Mul || thisToken.thisToken == Tokenizer::Token::Div) {
decltype(Parser::bigType) test = 0.0;
if (thisToken.thisToken == Tokenizer::Token::Mul) {
test = (decltype(Parser::bigType))c * (decltype(Parser::bigType))prim(text);
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else {
T divider = prim(text);
if (divider) {
test = (decltype(Parser::bigType))c / (decltype(Parser::bigType))divider;
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else throw std::runtime_error("Division by zero");
}
}
--text;
return c;
}
T expr(const char *&text, bool fromPrim = false) {
T c = term(text);
thisToken.updateToken(text);
while (thisToken.thisToken != Tokenizer::Token::End && thisToken.thisToken != Tokenizer::Token::RBrace && thisToken.thisToken != Tokenizer::Token::LBrace) {
decltype(Parser::bigType) test = 0.0;
if (thisToken.thisToken == Tokenizer::Token::Plus) {
test = (decltype(Parser::bigType))c + (decltype(Parser::bigType))term(text);
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else if (thisToken.thisToken == Tokenizer::Token::Minus) {
test = (decltype(Parser::bigType))c - (decltype(Parser::bigType))term(text);
if(Parser::checkType(test)){
c = T(test);
}else throw std::runtime_error("Result left type limits");
thisToken.updateToken(text);
} else
throw std::runtime_error("Syntax error");
}
if (thisToken.thisToken == Tokenizer::Token::LBrace){
throw std::runtime_error("Brace syntax error");
}
if (thisToken.thisToken != Tokenizer::Token::RBrace || fromPrim){
return c;
}
throw std::runtime_error("Brace syntax error");
}
const char* expression;
std::unordered_map<std::string, double> constants =
{
{ "Pi", M_PI },
{ "e", M_E }
};
Tokenizer thisToken;
};
void checkErrors(bool a){
if(!a)
std::cout << "error" << std::endl;
return;
}
bool isEqual(const double &left, const double &right){
return fabs(left - right) < DBL_EPSILON;
}
int main(int argc, char* argv[]) {
/*if(argc<2){
throw std::runtime_error("No input expression");
}
const char* expression = argv[1];
calculator<int,Parser<int>>(expression).calculate();
*/// I do without args/uncomment and use if needed
if(argc>1){
//const char* expression = argv[1];
//calculator<int,Parser<int>>(expression).calculate();
}
char* Expr1 = new char[255];
std::strcpy(Expr1, std::string("3+3").c_str());
char* Expr2 = new char[255];
std::strcpy(Expr2, std::string("9/2*2").c_str());
char* Expr3 = new char[255];
std::strcpy(Expr3, std::string("Pi*-e").c_str());
char* Expr4 = new char[255];
std::strcpy(Expr4, std::string("8*Pi").c_str());
//DOUBLE
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr1),(double)6));
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr2),(double)9));
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr3),(double)-M_PI*M_E));
checkErrors(isEqual(calculator<double,Parser<double>>().calculate(Expr4),(double)M_PI*8));
//INT
checkErrors(calculator<int,Parser<int>>().calculate(Expr1)==6);
checkErrors(calculator<int,Parser<int>>().calculate(Expr2)==8);
checkErrors(calculator<int,Parser<int>>().calculate(Expr3)==-6);
checkErrors(calculator<int,Parser<int>>().calculate(Expr4)==24);
//LONG
checkErrors(calculator<long,Parser<long>>().calculate(Expr1)==6);
checkErrors(calculator<long,Parser<long>>().calculate(Expr2)==8);
checkErrors(calculator<long,Parser<long>>().calculate(Expr3)==-6);
checkErrors(calculator<long,Parser<long>>().calculate(Expr4)==24);
delete [] Expr1;
delete [] Expr2;
delete [] Expr3;
delete [] Expr4;
return 0;
}<|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.
// Portions based heavily on:
// third_party/WebKit/Source/WebKit/chromium/public/gtk/WebInputEventFactory.cpp
//
/*
* Copyright (C) 2006-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "content/browser/renderer_host/web_input_event_aura.h"
#include <cstdlib>
#include <X11/Xlib.h>
#include "base/event_types.h"
#include "base/logging.h"
#include "ui/aura/event.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
namespace content {
// chromium WebKit does not provide a WebInputEventFactory for X11, so we have
// to do the work here ourselves.
namespace {
double XEventTimeToWebEventTime(Time time) {
// Convert from time in ms to time in s.
return time / 1000.0;
}
int EventFlagsToWebEventModifiers(int flags) {
int modifiers = 0;
if (flags & ui::EF_SHIFT_DOWN)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (flags & ui::EF_CONTROL_DOWN)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (flags & ui::EF_ALT_DOWN)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (flags & ui::EF_LEFT_BUTTON_DOWN)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (flags & ui::EF_MIDDLE_BUTTON_DOWN)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (flags & ui::EF_RIGHT_BUTTON_DOWN)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (flags & ui::EF_CAPS_LOCK_DOWN)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
return modifiers;
}
int XStateToWebEventModifiers(unsigned int state) {
int modifiers = 0;
if (state & ShiftMask)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (state & ControlMask)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (state & Mod1Mask)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (state & Button1Mask)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (state & Button2Mask)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (state & Button3Mask)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (state & LockMask)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
if (state & Mod2Mask)
modifiers |= WebKit::WebInputEvent::NumLockOn;
return modifiers;
}
int XKeyEventToWindowsKeyCode(XKeyEvent* event) {
return ui::KeyboardCodeFromXKeyEvent((XEvent*)event);
}
// From
// third_party/WebKit/Source/WebKit/chromium/src/gtk/WebInputEventFactory.cpp:
WebKit::WebUChar GetControlCharacter(int windows_key_code, bool shift) {
if (windows_key_code >= ui::VKEY_A &&
windows_key_code <= ui::VKEY_Z) {
// ctrl-A ~ ctrl-Z map to \x01 ~ \x1A
return windows_key_code - ui::VKEY_A + 1;
}
if (shift) {
// following graphics chars require shift key to input.
switch (windows_key_code) {
// ctrl-@ maps to \x00 (Null byte)
case ui::VKEY_2:
return 0;
// ctrl-^ maps to \x1E (Record separator, Information separator two)
case ui::VKEY_6:
return 0x1E;
// ctrl-_ maps to \x1F (Unit separator, Information separator one)
case ui::VKEY_OEM_MINUS:
return 0x1F;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
} else {
switch (windows_key_code) {
// ctrl-[ maps to \x1B (Escape)
case ui::VKEY_OEM_4:
return 0x1B;
// ctrl-\ maps to \x1C (File separator, Information separator four)
case ui::VKEY_OEM_5:
return 0x1C;
// ctrl-] maps to \x1D (Group separator, Information separator three)
case ui::VKEY_OEM_6:
return 0x1D;
// ctrl-Enter maps to \x0A (Line feed)
case ui::VKEY_RETURN:
return 0x0A;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
}
return 0;
}
WebKit::WebMouseEvent::Button ButtonFromXButton(int button) {
switch (button) {
case 1:
return WebKit::WebMouseEvent::ButtonLeft;
case 2:
return WebKit::WebMouseEvent::ButtonMiddle;
case 3:
return WebKit::WebMouseEvent::ButtonRight;
default:
break;
}
return WebKit::WebMouseEvent::ButtonNone;
}
WebKit::WebMouseEvent::Button ButtonFromXState(int state) {
if (state & Button1MotionMask)
return WebKit::WebMouseEvent::ButtonLeft;
if (state & Button2MotionMask)
return WebKit::WebMouseEvent::ButtonMiddle;
if (state & Button3MotionMask)
return WebKit::WebMouseEvent::ButtonRight;
return WebKit::WebMouseEvent::ButtonNone;
}
// We have to count clicks (for double-clicks) manually.
unsigned int g_num_clicks = 0;
double g_last_click_time = 0.0;
int g_last_click_x = 0;
int g_last_click_y = 0;
WebKit::WebMouseEvent::Button g_last_click_button =
WebKit::WebMouseEvent::ButtonNone;
bool ShouldForgetPreviousClick(double time, int x, int y) {
const double double_click_time = 0.250; // in seconds
const int double_click_distance = 5;
return (time - g_last_click_time) > double_click_time ||
std::abs(x - g_last_click_x) > double_click_distance ||
std::abs(y - g_last_click_y) > double_click_distance;
}
void ResetClickCountState() {
g_num_clicks = 0;
g_last_click_time = 0.0;
g_last_click_x = 0;
g_last_click_y = 0;
g_last_click_button = WebKit::WebMouseEvent::ButtonNone;
}
} // namespace
WebKit::WebMouseEvent MakeWebMouseEventFromAuraEvent(aura::MouseEvent* event) {
WebKit::WebMouseEvent webkit_event;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().ToDoubleT();
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
if (event->flags() & ui::EF_LEFT_BUTTON_DOWN)
webkit_event.button = WebKit::WebMouseEvent::ButtonLeft;
if (event->flags() & ui::EF_MIDDLE_BUTTON_DOWN)
webkit_event.button = WebKit::WebMouseEvent::ButtonMiddle;
if (event->flags() & ui::EF_RIGHT_BUTTON_DOWN)
webkit_event.button = WebKit::WebMouseEvent::ButtonRight;
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
webkit_event.type = WebKit::WebInputEvent::MouseDown;
if (!ShouldForgetPreviousClick(event->time_stamp().ToDoubleT(),
event->location().x(), event->location().y()) &&
webkit_event.button == g_last_click_button) {
++g_num_clicks;
} else {
g_num_clicks = 1;
g_last_click_time = event->time_stamp().ToDoubleT();
g_last_click_x = event->location().x();
g_last_click_y = event->location().y();
g_last_click_button = webkit_event.button;
}
webkit_event.clickCount = g_num_clicks;
break;
case ui::ET_MOUSE_RELEASED:
webkit_event.type = WebKit::WebInputEvent::MouseUp;
break;
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
webkit_event.type = WebKit::WebInputEvent::MouseMove;
if (ShouldForgetPreviousClick(event->time_stamp().ToDoubleT(),
event->location().x(), event->location().y()))
ResetClickCountState();
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->type();
break;
}
return webkit_event;
}
WebKit::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
aura::MouseEvent* event) {
WebKit::WebMouseWheelEvent webkit_event;
// TODO(sadrul): !
return webkit_event;
}
WebKit::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent(
aura::KeyEvent* event) {
base::NativeEvent native_event = event->native_event();
WebKit::WebKeyboardEvent webkit_event;
XKeyEvent* native_key_event = &native_event->xkey;
webkit_event.timeStampSeconds =
XEventTimeToWebEventTime(native_key_event->time);
webkit_event.modifiers = XStateToWebEventModifiers(native_key_event->state);
switch (native_event->type) {
case KeyPress:
webkit_event.type = event->is_char() ? WebKit::WebInputEvent::Char :
WebKit::WebInputEvent::RawKeyDown;
break;
case KeyRelease:
webkit_event.type = WebKit::WebInputEvent::KeyUp;
break;
case GenericEvent:
// TODO(sadrul): touch!
break;
default:
NOTREACHED();
}
if (webkit_event.modifiers & WebKit::WebInputEvent::AltKey)
webkit_event.isSystemKey = true;
webkit_event.windowsKeyCode = XKeyEventToWindowsKeyCode(native_key_event);
webkit_event.nativeKeyCode = native_key_event->keycode;
if (webkit_event.windowsKeyCode == ui::VKEY_RETURN) {
webkit_event.unmodifiedText[0] = '\r';
} else {
webkit_event.unmodifiedText[0] =
ui::DefaultXKeysymFromHardwareKeycode(native_key_event->keycode);
}
if (webkit_event.modifiers & WebKit::WebInputEvent::ControlKey) {
webkit_event.text[0] =
GetControlCharacter(
webkit_event.windowsKeyCode,
webkit_event.modifiers & WebKit::WebInputEvent::ShiftKey);
} else {
webkit_event.text[0] = webkit_event.unmodifiedText[0];
}
webkit_event.setKeyIdentifierFromWindowsKeyCode();
// TODO: IsAutoRepeat/IsKeyPad?
return webkit_event;
}
} // namespace content
<commit_msg>aura: Add mouse wheel event support for x11 in RWHVA.<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.
// Portions based heavily on:
// third_party/WebKit/Source/WebKit/chromium/public/gtk/WebInputEventFactory.cpp
//
/*
* Copyright (C) 2006-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "content/browser/renderer_host/web_input_event_aura.h"
#include <cstdlib>
#include <X11/Xlib.h>
#include "base/event_types.h"
#include "base/logging.h"
#include "ui/aura/event.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
namespace content {
// chromium WebKit does not provide a WebInputEventFactory for X11, so we have
// to do the work here ourselves.
namespace {
double XEventTimeToWebEventTime(Time time) {
// Convert from time in ms to time in s.
return time / 1000.0;
}
int EventFlagsToWebEventModifiers(int flags) {
int modifiers = 0;
if (flags & ui::EF_SHIFT_DOWN)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (flags & ui::EF_CONTROL_DOWN)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (flags & ui::EF_ALT_DOWN)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (flags & ui::EF_LEFT_BUTTON_DOWN)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (flags & ui::EF_MIDDLE_BUTTON_DOWN)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (flags & ui::EF_RIGHT_BUTTON_DOWN)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (flags & ui::EF_CAPS_LOCK_DOWN)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
return modifiers;
}
int XStateToWebEventModifiers(unsigned int state) {
int modifiers = 0;
if (state & ShiftMask)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (state & ControlMask)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (state & Mod1Mask)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (state & Button1Mask)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (state & Button2Mask)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (state & Button3Mask)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (state & LockMask)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
if (state & Mod2Mask)
modifiers |= WebKit::WebInputEvent::NumLockOn;
return modifiers;
}
int XKeyEventToWindowsKeyCode(XKeyEvent* event) {
return ui::KeyboardCodeFromXKeyEvent((XEvent*)event);
}
// From
// third_party/WebKit/Source/WebKit/chromium/src/gtk/WebInputEventFactory.cpp:
WebKit::WebUChar GetControlCharacter(int windows_key_code, bool shift) {
if (windows_key_code >= ui::VKEY_A &&
windows_key_code <= ui::VKEY_Z) {
// ctrl-A ~ ctrl-Z map to \x01 ~ \x1A
return windows_key_code - ui::VKEY_A + 1;
}
if (shift) {
// following graphics chars require shift key to input.
switch (windows_key_code) {
// ctrl-@ maps to \x00 (Null byte)
case ui::VKEY_2:
return 0;
// ctrl-^ maps to \x1E (Record separator, Information separator two)
case ui::VKEY_6:
return 0x1E;
// ctrl-_ maps to \x1F (Unit separator, Information separator one)
case ui::VKEY_OEM_MINUS:
return 0x1F;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
} else {
switch (windows_key_code) {
// ctrl-[ maps to \x1B (Escape)
case ui::VKEY_OEM_4:
return 0x1B;
// ctrl-\ maps to \x1C (File separator, Information separator four)
case ui::VKEY_OEM_5:
return 0x1C;
// ctrl-] maps to \x1D (Group separator, Information separator three)
case ui::VKEY_OEM_6:
return 0x1D;
// ctrl-Enter maps to \x0A (Line feed)
case ui::VKEY_RETURN:
return 0x0A;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
}
return 0;
}
WebKit::WebMouseEvent::Button ButtonFromXButton(int button) {
switch (button) {
case 1:
return WebKit::WebMouseEvent::ButtonLeft;
case 2:
return WebKit::WebMouseEvent::ButtonMiddle;
case 3:
return WebKit::WebMouseEvent::ButtonRight;
default:
break;
}
return WebKit::WebMouseEvent::ButtonNone;
}
WebKit::WebMouseEvent::Button ButtonFromXState(int state) {
if (state & Button1MotionMask)
return WebKit::WebMouseEvent::ButtonLeft;
if (state & Button2MotionMask)
return WebKit::WebMouseEvent::ButtonMiddle;
if (state & Button3MotionMask)
return WebKit::WebMouseEvent::ButtonRight;
return WebKit::WebMouseEvent::ButtonNone;
}
// We have to count clicks (for double-clicks) manually.
unsigned int g_num_clicks = 0;
double g_last_click_time = 0.0;
int g_last_click_x = 0;
int g_last_click_y = 0;
WebKit::WebMouseEvent::Button g_last_click_button =
WebKit::WebMouseEvent::ButtonNone;
bool ShouldForgetPreviousClick(double time, int x, int y) {
const double double_click_time = 0.250; // in seconds
const int double_click_distance = 5;
return (time - g_last_click_time) > double_click_time ||
std::abs(x - g_last_click_x) > double_click_distance ||
std::abs(y - g_last_click_y) > double_click_distance;
}
void ResetClickCountState() {
g_num_clicks = 0;
g_last_click_time = 0.0;
g_last_click_x = 0;
g_last_click_y = 0;
g_last_click_button = WebKit::WebMouseEvent::ButtonNone;
}
} // namespace
WebKit::WebMouseEvent MakeWebMouseEventFromAuraEvent(aura::MouseEvent* event) {
WebKit::WebMouseEvent webkit_event;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().ToDoubleT();
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
if (event->flags() & ui::EF_LEFT_BUTTON_DOWN)
webkit_event.button = WebKit::WebMouseEvent::ButtonLeft;
if (event->flags() & ui::EF_MIDDLE_BUTTON_DOWN)
webkit_event.button = WebKit::WebMouseEvent::ButtonMiddle;
if (event->flags() & ui::EF_RIGHT_BUTTON_DOWN)
webkit_event.button = WebKit::WebMouseEvent::ButtonRight;
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
webkit_event.type = WebKit::WebInputEvent::MouseDown;
if (!ShouldForgetPreviousClick(event->time_stamp().ToDoubleT(),
event->location().x(), event->location().y()) &&
webkit_event.button == g_last_click_button) {
++g_num_clicks;
} else {
g_num_clicks = 1;
g_last_click_time = event->time_stamp().ToDoubleT();
g_last_click_x = event->location().x();
g_last_click_y = event->location().y();
g_last_click_button = webkit_event.button;
}
webkit_event.clickCount = g_num_clicks;
break;
case ui::ET_MOUSE_RELEASED:
webkit_event.type = WebKit::WebInputEvent::MouseUp;
break;
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
webkit_event.type = WebKit::WebInputEvent::MouseMove;
if (ShouldForgetPreviousClick(event->time_stamp().ToDoubleT(),
event->location().x(), event->location().y()))
ResetClickCountState();
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->type();
break;
}
return webkit_event;
}
WebKit::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
aura::MouseEvent* event) {
WebKit::WebMouseWheelEvent webkit_event;
webkit_event.type = WebKit::WebInputEvent::MouseWheel;
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().ToDoubleT();
webkit_event.deltaY = ui::GetMouseWheelOffset(event->native_event());
webkit_event.wheelTicksY = webkit_event.deltaY > 0 ? 1 : -1;
return webkit_event;
}
WebKit::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent(
aura::KeyEvent* event) {
base::NativeEvent native_event = event->native_event();
WebKit::WebKeyboardEvent webkit_event;
XKeyEvent* native_key_event = &native_event->xkey;
webkit_event.timeStampSeconds =
XEventTimeToWebEventTime(native_key_event->time);
webkit_event.modifiers = XStateToWebEventModifiers(native_key_event->state);
switch (native_event->type) {
case KeyPress:
webkit_event.type = event->is_char() ? WebKit::WebInputEvent::Char :
WebKit::WebInputEvent::RawKeyDown;
break;
case KeyRelease:
webkit_event.type = WebKit::WebInputEvent::KeyUp;
break;
case GenericEvent:
// TODO(sadrul): touch!
break;
default:
NOTREACHED();
}
if (webkit_event.modifiers & WebKit::WebInputEvent::AltKey)
webkit_event.isSystemKey = true;
webkit_event.windowsKeyCode = XKeyEventToWindowsKeyCode(native_key_event);
webkit_event.nativeKeyCode = native_key_event->keycode;
if (webkit_event.windowsKeyCode == ui::VKEY_RETURN) {
webkit_event.unmodifiedText[0] = '\r';
} else {
webkit_event.unmodifiedText[0] =
ui::DefaultXKeysymFromHardwareKeycode(native_key_event->keycode);
}
if (webkit_event.modifiers & WebKit::WebInputEvent::ControlKey) {
webkit_event.text[0] =
GetControlCharacter(
webkit_event.windowsKeyCode,
webkit_event.modifiers & WebKit::WebInputEvent::ShiftKey);
} else {
webkit_event.text[0] = webkit_event.unmodifiedText[0];
}
webkit_event.setKeyIdentifierFromWindowsKeyCode();
// TODO: IsAutoRepeat/IsKeyPad?
return webkit_event;
}
} // namespace content
<|endoftext|> |
<commit_before>/**
This file contains a sequence of tests to perform for different instances of a templatized fixture.
It is thus inlined several times in the .cpp test file.
*/
// ==============================
// Set/get value tests
TEST_F(TestMatrix, set_fullMat ) { ASSERT_TRUE( matrixMaxDiff(mat,fullMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs1 ) { ASSERT_TRUE( matrixMaxDiff( fullMat,crs1 ) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,crs2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_mapMat ) { ASSERT_TRUE( matrixMaxDiff(fullMat,mapMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock1 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock1) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBase ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBase) < 100*epsilon() ); }
TEST_F(TestMatrix, eigenMatrix_update ) { ASSERT_TRUE( checkEigenMatrixUpdate() ); }
TEST_F(TestMatrix, eigenMatrix_block_row_filling ) { ASSERT_TRUE( checkEigenMatrixBlockRowFilling() ); }
TEST_F(TestMatrix, eigenMatrixBlockFromCompressedRowSparseMatrix ) { ASSERT_TRUE( checkEigenMatrixBlockFromCompressedRowSparseMatrix() ); }
TEST_F(TestMatrix, eigenMapToDenseMatrix ) { ASSERT_TRUE( checkEigenDenseMatrix() ); }
// ==============================
// Matrix-Vector product tests
TEST_F(TestMatrix, set_fullVec_nrows_reference )
{
ASSERT_TRUE(vectorMaxDiff(vecM,fullVec_nrows_reference) < epsilon() );
}
TEST_F(TestMatrix, fullMat_vector_product )
{
// fullMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = fullMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, mapMat_vector_product )
{
// mapMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = mapMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, eiBlock1_vector_product )
{
// eiBlock1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
// eiBlock1.multVector(fullVec_nrows_result,fullVec_ncols);
fullVec_nrows_result = eiBlock1 * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, crs1_vector_product )
{
// EXPECT_TRUE(NROWS%BROWS==0 && NCOLS%BCOLS==0) << "Error: CompressedRowSparseMatrix * Vector crashes when the size of the matrix is not a multiple of the size of the matrix blocks. Aborting this test, and reporting a failure."; // otherwise the product crashes
// crs1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = crs1 * fullVec_ncols;
ASSERT_FALSE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() ); // create an error to check if I get a message from Jenkins
// ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
// ==============================
// Matrix product tests
TEST_F(TestMatrix, full_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(matMultiplication,fullMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,crsMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenBase_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,eiBaseMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenSparseDense_matrix_product ) { ASSERT_TRUE( EigenDenseMatrix(eiBaseMultiplication.compressedMatrix) == eiDenseMultiplication ); }
TEST_F(TestMatrix, full_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(matTransposeMultiplication,fullTransposeMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(fullTransposeMultiplication,crsTransposeMultiplication) < 100*epsilon() ); }
// Matrix addition
TEST_F(TestMatrix, crs_matrix_addition )
{
crs2 = crs1 + crs1;
ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
crs2 += crs1;
ASSERT_TRUE( matrixMaxDiff(mat*3,crs2) < 100*epsilon() );
crs2 -= crs1;
ASSERT_FALSE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() ); // create an error to check if I get a message from Jenkins
// ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
}
<commit_msg>META-TEST clean up<commit_after>/**
This file contains a sequence of tests to perform for different instances of a templatized fixture.
It is thus inlined several times in the .cpp test file.
*/
// ==============================
// Set/get value tests
TEST_F(TestMatrix, set_fullMat ) { ASSERT_TRUE( matrixMaxDiff(mat,fullMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs1 ) { ASSERT_TRUE( matrixMaxDiff( fullMat,crs1 ) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,crs2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_mapMat ) { ASSERT_TRUE( matrixMaxDiff(fullMat,mapMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock1 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock1) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBase ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBase) < 100*epsilon() ); }
TEST_F(TestMatrix, eigenMatrix_update ) { ASSERT_TRUE( checkEigenMatrixUpdate() ); }
TEST_F(TestMatrix, eigenMatrix_block_row_filling ) { ASSERT_TRUE( checkEigenMatrixBlockRowFilling() ); }
TEST_F(TestMatrix, eigenMatrixBlockFromCompressedRowSparseMatrix ) { ASSERT_TRUE( checkEigenMatrixBlockFromCompressedRowSparseMatrix() ); }
TEST_F(TestMatrix, eigenMapToDenseMatrix ) { ASSERT_TRUE( checkEigenDenseMatrix() ); }
// ==============================
// Matrix-Vector product tests
TEST_F(TestMatrix, set_fullVec_nrows_reference )
{
ASSERT_TRUE(vectorMaxDiff(vecM,fullVec_nrows_reference) < epsilon() );
}
TEST_F(TestMatrix, fullMat_vector_product )
{
// fullMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = fullMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, mapMat_vector_product )
{
// mapMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = mapMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, eiBlock1_vector_product )
{
// eiBlock1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
// eiBlock1.multVector(fullVec_nrows_result,fullVec_ncols);
fullVec_nrows_result = eiBlock1 * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, crs1_vector_product )
{
// EXPECT_TRUE(NROWS%BROWS==0 && NCOLS%BCOLS==0) << "Error: CompressedRowSparseMatrix * Vector crashes when the size of the matrix is not a multiple of the size of the matrix blocks. Aborting this test, and reporting a failure."; // otherwise the product crashes
// crs1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = crs1 * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
// ==============================
// Matrix product tests
TEST_F(TestMatrix, full_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(matMultiplication,fullMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,crsMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenBase_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,eiBaseMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenSparseDense_matrix_product ) { ASSERT_TRUE( EigenDenseMatrix(eiBaseMultiplication.compressedMatrix) == eiDenseMultiplication ); }
TEST_F(TestMatrix, full_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(matTransposeMultiplication,fullTransposeMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(fullTransposeMultiplication,crsTransposeMultiplication) < 100*epsilon() ); }
// Matrix addition
TEST_F(TestMatrix, crs_matrix_addition )
{
crs2 = crs1 + crs1;
ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
crs2 += crs1;
ASSERT_TRUE( matrixMaxDiff(mat*3,crs2) < 100*epsilon() );
crs2 -= crs1;
ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.